High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: strategy framework — explicit + simple allocation strategies
Bosch94b159970ca7
diff --git a/internal/allocation/fcfs.go b/internal/allocation/fcfs.gonew file mode 100644index 00000000..e81265a4--- /dev/null+++ b/internal/allocation/fcfs.go@@ -0,0 +1,16 @@+package allocation++import "github.com/pinchtab/pinchtab/internal/bridge"++// FCFS (First Come First Served) returns the first running candidate.+// This is the default policy — simple, predictable, deterministic.+type FCFS struct{}++func (f *FCFS) Name() string { return "fcfs" }++func (f *FCFS) Select(candidates []bridge.Instance) (bridge.Instance, error) {+ if len(candidates) == 0 {+ return bridge.Instance{}, ErrNoCandidates+ }+ return candidates[0], nil+}diff --git a/internal/allocation/policy.go b/internal/allocation/policy.gonew file mode 100644index 00000000..b211b3f8--- /dev/null+++ b/internal/allocation/policy.go@@ -0,0 +1,38 @@+// Package allocation defines the AllocationPolicy interface and built-in implementations.+// An AllocationPolicy decides which running instance should handle the next request.+// It is independent from Strategy (API style) — both are swappable independently.+package allocation++import (+ "fmt"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Policy selects an instance from a list of running candidates.+// Implementations must be safe for concurrent use.+type Policy interface {+ // Name returns the policy identifier (for config/logging).+ Name() string++ // Select picks the best instance from the given candidates.+ // Returns an error if candidates is empty or no suitable instance exists.+ Select(candidates []bridge.Instance) (bridge.Instance, error)+}++// ErrNoCandidates is returned when Select receives an empty slice.+var ErrNoCandidates = fmt.Errorf("no candidate instances available")++// New creates a Policy by name. Returns an error for unknown names.+func New(name string) (Policy, error) {+ switch name {+ case "fcfs", "":+ return &FCFS{}, nil+ case "round_robin":+ return NewRoundRobin(), nil+ case "random":+ return &Random{}, nil+ default:+ return nil, fmt.Errorf("unknown allocation policy: %q (available: fcfs, round_robin, random)", name)+ }+}diff --git a/internal/allocation/policy_test.go b/internal/allocation/policy_test.gonew file mode 100644index 00000000..8b56cad5--- /dev/null+++ b/internal/allocation/policy_test.go@@ -0,0 +1,115 @@+package allocation_test++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/allocation"+ "github.com/pinchtab/pinchtab/internal/bridge"+)++func candidates(ids ...string) []bridge.Instance {+ out := make([]bridge.Instance, len(ids))+ for i, id := range ids {+ out[i] = bridge.Instance{ID: id, Status: "running"}+ }+ return out+}++func TestFCFS_SelectsFirst(t *testing.T) {+ p := &allocation.FCFS{}+ got, err := p.Select(candidates("a", "b", "c"))+ if err != nil {+ t.Fatal(err)+ }+ if got.ID != "a" {+ t.Errorf("expected a, got %s", got.ID)+ }+}++func TestFCFS_EmptyReturnsError(t *testing.T) {+ p := &allocation.FCFS{}+ _, err := p.Select(nil)+ if err != allocation.ErrNoCandidates {+ t.Errorf("expected ErrNoCandidates, got %v", err)+ }+}++func TestRoundRobin_Cycles(t *testing.T) {+ p := allocation.NewRoundRobin()+ c := candidates("a", "b", "c")++ expected := []string{"a", "b", "c", "a", "b", "c"}+ for i, want := range expected {+ got, err := p.Select(c)+ if err != nil {+ t.Fatal(err)+ }+ if got.ID != want {+ t.Errorf("call %d: expected %s, got %s", i, want, got.ID)+ }+ }+}++func TestRoundRobin_EmptyReturnsError(t *testing.T) {+ p := allocation.NewRoundRobin()+ _, err := p.Select(nil)+ if err != allocation.ErrNoCandidates {+ t.Errorf("expected ErrNoCandidates, got %v", err)+ }+}++func TestRandom_SelectsFromCandidates(t *testing.T) {+ p := &allocation.Random{}+ c := candidates("a", "b", "c")++ // Run enough times to verify it doesn't panic and returns valid candidates.+ seen := map[string]bool{}+ for range 100 {+ got, err := p.Select(c)+ if err != nil {+ t.Fatal(err)+ }+ seen[got.ID] = true+ }+ // With 100 tries and 3 candidates, we should see at least 2.+ if len(seen) < 2 {+ t.Errorf("random policy only selected %d unique candidates in 100 tries", len(seen))+ }+}++func TestRandom_EmptyReturnsError(t *testing.T) {+ p := &allocation.Random{}+ _, err := p.Select(nil)+ if err != allocation.ErrNoCandidates {+ t.Errorf("expected ErrNoCandidates, got %v", err)+ }+}++func TestNew_KnownPolicies(t *testing.T) {+ tests := []struct {+ name string+ wantName string+ }{+ {"fcfs", "fcfs"},+ {"", "fcfs"},+ {"round_robin", "round_robin"},+ {"random", "random"},+ }+ for _, tt := range tests {+ p, err := allocation.New(tt.name)+ if err != nil {+ t.Errorf("New(%q): %v", tt.name, err)+ continue+ }+ if p.Name() != tt.wantName {+ t.Errorf("New(%q).Name() = %q, want %q", tt.name, p.Name(), tt.wantName)+ }+ }+}++func TestNew_UnknownPolicy(t *testing.T) {+ _, err := allocation.New("does_not_exist")+ if err == nil {+ t.Error("expected error for unknown policy")+ }+}diff --git a/internal/allocation/random.go b/internal/allocation/random.gonew file mode 100644index 00000000..e6664279--- /dev/null+++ b/internal/allocation/random.go@@ -0,0 +1,19 @@+package allocation++import (+ "math/rand/v2"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Random selects a random candidate.+type Random struct{}++func (r *Random) Name() string { return "random" }++func (r *Random) Select(candidates []bridge.Instance) (bridge.Instance, error) {+ if len(candidates) == 0 {+ return bridge.Instance{}, ErrNoCandidates+ }+ return candidates[rand.IntN(len(candidates))], nil+}diff --git a/internal/allocation/round_robin.go b/internal/allocation/round_robin.gonew file mode 100644index 00000000..e154addb--- /dev/null+++ b/internal/allocation/round_robin.go@@ -0,0 +1,28 @@+package allocation++import (+ "sync/atomic"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// RoundRobin cycles through candidates in order.+// Thread-safe via atomic counter.+type RoundRobin struct {+ counter atomic.Uint64+}++// NewRoundRobin creates a new RoundRobin policy.+func NewRoundRobin() *RoundRobin {+ return &RoundRobin{}+}++func (rr *RoundRobin) Name() string { return "round_robin" }++func (rr *RoundRobin) Select(candidates []bridge.Instance) (bridge.Instance, error) {+ if len(candidates) == 0 {+ return bridge.Instance{}, ErrNoCandidates+ }+ idx := rr.counter.Add(1) - 1+ return candidates[idx%uint64(len(candidates))], nil+}diff --git a/internal/config/config.go b/internal/config/config.goindex 86cabd0d..e035cfa0 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -39,6 +39,10 @@ type RuntimeConfig struct {NavigateTimeout time.DurationShutdownTimeout time.DurationWaitNavDelay time.Duration++ // Orchestrator settings (dashboard mode only).+ Strategy string // "simple" (default) or "explicit"+ AllocationPolicy string // "fcfs" (default), "round_robin", "random"}func envOr(key, fallback string) string {@@ -249,6 +253,8 @@ func Load() *RuntimeConfig {NoAnimations: envBoolOrMigrate("PINCHTAB_NO_ANIMATIONS", "BRIDGE_NO_ANIMATIONS", false),StealthLevel: envOrMigrate("PINCHTAB_STEALTH", "BRIDGE_STEALTH", "light"),TabEvictionPolicy: envOr("PINCHTAB_TAB_EVICTION_POLICY", "reject"),+ Strategy: envOr("PINCHTAB_STRATEGY", "simple"),+ AllocationPolicy: envOr("PINCHTAB_ALLOCATION_POLICY", "fcfs"),ActionTimeout: 30 * time.Second,NavigateTimeout: 60 * time.Second,ShutdownTimeout: 10 * time.Second,diff --git a/internal/instance/allocator.go b/internal/instance/allocator.gonew file mode 100644index 00000000..08e24350--- /dev/null+++ b/internal/instance/allocator.go@@ -0,0 +1,43 @@+package instance++import (+ "fmt"++ "github.com/pinchtab/pinchtab/internal/allocation"+ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Allocator selects an instance using the configured AllocationPolicy.+// It reads candidates from the Repository and delegates selection to the policy.+type Allocator struct {+ repo *Repository+ policy allocation.Policy+}++// NewAllocator creates an Allocator with the given policy.+func NewAllocator(repo *Repository, policy allocation.Policy) *Allocator {+ return &Allocator{repo: repo, policy: policy}+}++// Allocate selects a running instance using the configured policy.+func (a *Allocator) Allocate() (*bridge.Instance, error) {+ candidates := a.repo.Running()+ if len(candidates) == 0 {+ return nil, fmt.Errorf("no running instances available")+ }+ selected, err := a.policy.Select(candidates)+ if err != nil {+ return nil, fmt.Errorf("allocation policy %q failed: %w", a.policy.Name(), err)+ }+ return &selected, nil+}++// Policy returns the current allocation policy.+func (a *Allocator) Policy() allocation.Policy {+ return a.policy+}++// SetPolicy swaps the allocation policy at runtime.+func (a *Allocator) SetPolicy(p allocation.Policy) {+ a.policy = p+}diff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.gonew file mode 100644index 00000000..cc82f428--- /dev/null+++ b/internal/instance/bridge_client.go@@ -0,0 +1,236 @@+package instance++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "strings"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// BridgeClient makes HTTP calls to a bridge instance.+// Each method targets a specific bridge endpoint.+type BridgeClient struct {+ client *http.Client+}++// NewBridgeClient creates a BridgeClient.+func NewBridgeClient() *BridgeClient {+ return &BridgeClient{+ client: &http.Client{Timeout: 60 * time.Second},+ }+}++// FetchTabs implements TabFetcher by querying a bridge's /tabs endpoint.+func (bc *BridgeClient) FetchTabs(instanceURL string) ([]bridge.InstanceTab, error) {+ resp, err := bc.client.Get(instanceURL + "/tabs")+ if err != nil {+ return nil, fmt.Errorf("fetch tabs: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("fetch tabs: status %d", resp.StatusCode)+ }++ // Bridge returns {"tabs": [...]}+ var wrapper struct {+ Tabs []bridge.InstanceTab `json:"tabs"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&wrapper); err != nil {+ return nil, fmt.Errorf("decode tabs: %w", err)+ }+ return wrapper.Tabs, nil+}++// CreateTab creates a new tab on a bridge instance. Returns the tab ID.+func (bc *BridgeClient) CreateTab(ctx context.Context, port, url string) (string, error) {+ // Create blank tab first to avoid waitFor issues+ body := `{"action":"new","url":"about:blank"}`+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, bridgeURL(port, "/tab"), strings.NewReader(body))+ if err != nil {+ return "", fmt.Errorf("create tab request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")++ resp, err := bc.client.Do(req)+ if err != nil {+ return "", fmt.Errorf("create tab: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ respBody, _ := io.ReadAll(resp.Body)+ return "", fmt.Errorf("create tab: status %d: %s", resp.StatusCode, respBody)+ }++ var result struct {+ TabID string `json:"tabId"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return "", fmt.Errorf("decode create tab response: %w", err)+ }++ // If URL provided and not about:blank, navigate to it+ if url != "" && url != "about:blank" {+ if err := bc.NavigateTab(ctx, port, result.TabID, url); err != nil {+ return "", fmt.Errorf("navigate after create: %w", err)+ }+ }++ return result.TabID, nil+}++// NavigateTab navigates an existing tab to a URL+func (bc *BridgeClient) NavigateTab(ctx context.Context, port, tabID, url string) error {+ body := fmt.Sprintf(`{"url":%q,"waitFor":"dom"}`, url)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, bridgeURL(port, "/tabs/"+tabID+"/navigate"), strings.NewReader(body))+ if err != nil {+ return fmt.Errorf("navigate request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")++ resp, err := bc.client.Do(req)+ if err != nil {+ return fmt.Errorf("navigate: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ respBody, _ := io.ReadAll(resp.Body)+ return fmt.Errorf("navigate: status %d: %s", resp.StatusCode, respBody)+ }++ return nil+}++// CloseTab closes a tab on a bridge instance.+func (bc *BridgeClient) CloseTab(ctx context.Context, port, tabID string) error {+ body := fmt.Sprintf(`{"action":"close","tabId":%q}`, tabID)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, bridgeURL(port, "/tab"), strings.NewReader(body))+ if err != nil {+ return fmt.Errorf("close tab request: %w", err)+ }+ req.Header.Set("Content-Type", "application/json")++ resp, err := bc.client.Do(req)+ if err != nil {+ return fmt.Errorf("close tab: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()++ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("close tab: status %d", resp.StatusCode)+ }+ return nil+}++// SnapshotTab calls GET /tabs/{tabID}/snapshot on the bridge to populate+// the snapshot cache. The response body is discarded.+func (bc *BridgeClient) SnapshotTab(ctx context.Context, port, tabID string) {+ url := bridgeURL(port, "/tabs/"+tabID+"/snapshot")+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)+ if err != nil {+ return+ }+ resp, err := bc.client.Do(req)+ if err != nil {+ return+ }+ _ = resp.Body.Close()+}++// ProxyWithTabID proxies a request to a bridge shorthand endpoint (e.g. /find),+// injecting the tabId into the JSON request body so the bridge knows which tab+// to operate on. Used for endpoints that don't support /tabs/{id}/... paths.+func (bc *BridgeClient) ProxyWithTabID(w http.ResponseWriter, r *http.Request, port, tabID, path string) {+ // Read original body and inject tabId.+ var body map[string]any+ if r.Body != nil {+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ body = map[string]any{}+ }+ } else {+ body = map[string]any{}+ }+ body["tabId"] = tabID++ encoded, err := json.Marshal(body)+ if err != nil {+ http.Error(w, fmt.Sprintf("encode body: %s", err), http.StatusInternalServerError)+ return+ }++ targetURL := bridgeURL(port, path)+ proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, strings.NewReader(string(encoded)))+ if err != nil {+ http.Error(w, fmt.Sprintf("proxy request: %s", err), http.StatusInternalServerError)+ return+ }+ proxyReq.Header.Set("Content-Type", "application/json")++ resp, err := bc.client.Do(proxyReq)+ if err != nil {+ http.Error(w, fmt.Sprintf("proxy failed: %s", err), http.StatusBadGateway)+ return+ }+ defer func() { _ = resp.Body.Close() }()++ for key, values := range resp.Header {+ for _, v := range values {+ w.Header().Add(key, v)+ }+ }+ w.WriteHeader(resp.StatusCode)+ _, _ = io.Copy(w, resp.Body)+}++// ProxyToTab forwards an HTTP request to a specific bridge tab endpoint.+// It builds the URL as http://localhost:{port}/tabs/{tabID}/{suffix} and+// copies the request method, body, and headers.+func (bc *BridgeClient) ProxyToTab(w http.ResponseWriter, r *http.Request, port, tabID, suffix string) {+ targetURL := bridgeURL(port, "/tabs/"+tabID+suffix)+ if r.URL.RawQuery != "" {+ targetURL += "?" + r.URL.RawQuery+ }++ proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)+ if err != nil {+ http.Error(w, fmt.Sprintf("proxy request: %s", err), http.StatusInternalServerError)+ return+ }++ for key, values := range r.Header {+ switch key {+ case "Host", "Connection", "Keep-Alive", "Proxy-Authenticate",+ "Proxy-Authorization", "Te", "Trailers", "Transfer-Encoding", "Upgrade":+ default:+ for _, v := range values {+ proxyReq.Header.Add(key, v)+ }+ }+ }++ resp, err := bc.client.Do(proxyReq)+ if err != nil {+ http.Error(w, fmt.Sprintf("proxy failed: %s", err), http.StatusBadGateway)+ return+ }+ defer func() { _ = resp.Body.Close() }()++ for key, values := range resp.Header {+ for _, v := range values {+ w.Header().Add(key, v)+ }+ }+ w.WriteHeader(resp.StatusCode)+ _, _ = io.Copy(w, resp.Body)+}++func bridgeURL(port, path string) string {+ return "http://localhost:" + port + path+}diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.gonew file mode 100644index 00000000..fe99678d--- /dev/null+++ b/internal/instance/instance_test.go@@ -0,0 +1,362 @@+package instance_test++import (+ "fmt"+ "testing"++ "github.com/pinchtab/pinchtab/internal/allocation"+ bridgepkg "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/instance"+)++// --- Test doubles ---++type mockLauncher struct {+ instances map[string]*bridgepkg.Instance+ nextID int+ stopErr error+}++func newMockLauncher() *mockLauncher {+ return &mockLauncher{instances: make(map[string]*bridgepkg.Instance)}+}++func (m *mockLauncher) Launch(name, port string, headless bool) (*bridgepkg.Instance, error) {+ m.nextID+++ inst := &bridgepkg.Instance{+ ID: fmt.Sprintf("inst_%d", m.nextID),+ ProfileName: name,+ Port: port,+ Headless: headless,+ Status: "running",+ }+ m.instances[inst.ID] = inst+ return inst, nil+}++func (m *mockLauncher) Stop(id string) error {+ if m.stopErr != nil {+ return m.stopErr+ }+ delete(m.instances, id)+ return nil+}++type mockFetcher struct {+ // tabsByURL maps instance URL → tabs+ tabsByURL map[string][]bridgepkg.InstanceTab+}++func newMockFetcher() *mockFetcher {+ return &mockFetcher{tabsByURL: make(map[string][]bridgepkg.InstanceTab)}+}++func (f *mockFetcher) FetchTabs(instanceURL string) ([]bridgepkg.InstanceTab, error) {+ tabs, ok := f.tabsByURL[instanceURL]+ if !ok {+ return nil, fmt.Errorf("instance %s not reachable", instanceURL)+ }+ return tabs, nil+}++func (f *mockFetcher) AddTab(instancePort, tabID, url string) {+ key := "http://localhost:" + instancePort+ f.tabsByURL[key] = append(f.tabsByURL[key], bridgepkg.InstanceTab{+ ID: tabID,+ URL: url,+ })+}++// --- Repository tests ---++func TestRepository_LaunchAndGet(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)++ inst, err := repo.Launch("default", "9868", true)+ if err != nil {+ t.Fatal(err)+ }++ got, ok := repo.Get(inst.ID)+ if !ok {+ t.Fatal("instance not found after launch")+ }+ if got.ProfileName != "default" {+ t.Errorf("expected profile default, got %s", got.ProfileName)+ }+ if repo.Count() != 1 {+ t.Errorf("expected count 1, got %d", repo.Count())+ }+}++func TestRepository_StopRemovesInstance(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)++ inst, _ := repo.Launch("default", "9868", true)+ if err := repo.Stop(inst.ID); err != nil {+ t.Fatal(err)+ }+ if _, ok := repo.Get(inst.ID); ok {+ t.Error("instance should be gone after stop")+ }+ if repo.Count() != 0 {+ t.Errorf("expected count 0, got %d", repo.Count())+ }+}++func TestRepository_Running_FiltersNonRunning(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)++ inst1, _ := repo.Launch("prof1", "9868", true)+ _, _ = repo.Launch("prof2", "9869", true)++ // Manually mark inst1 as stopped via Add.+ stopped := *inst1+ stopped.Status = "stopped"+ repo.Add(&stopped)++ running := repo.Running()+ if len(running) != 1 {+ t.Errorf("expected 1 running, got %d", len(running))+ }+}++// --- Locator tests ---++func TestLocator_CacheHit(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ inst, _ := repo.Launch("default", "9868", true)++ // Pre-register in cache.+ locator.Register("tab_abc", inst.ID)++ found, err := locator.FindInstanceByTabID("tab_abc")+ if err != nil {+ t.Fatal(err)+ }+ if found.ID != inst.ID {+ t.Errorf("expected %s, got %s", inst.ID, found.ID)+ }+}++func TestLocator_CacheMiss_QueriesBridges(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ inst, _ := repo.Launch("default", "9868", true)++ // Set up fetcher to return tabs for this instance.+ fetcher.AddTab("9868", "tab_xyz", "https://example.com")++ found, err := locator.FindInstanceByTabID("tab_xyz")+ if err != nil {+ t.Fatal(err)+ }+ if found.ID != inst.ID {+ t.Errorf("expected %s, got %s", inst.ID, found.ID)+ }++ // Should now be cached.+ if locator.CacheSize() != 1 {+ t.Errorf("expected cache size 1, got %d", locator.CacheSize())+ }+}++func TestLocator_TabNotFound(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ _, _ = repo.Launch("default", "9868", true)+ fetcher.AddTab("9868", "tab_abc", "https://example.com")++ _, err := locator.FindInstanceByTabID("nonexistent")+ if err == nil {+ t.Error("expected error for nonexistent tab")+ }+}++func TestLocator_InvalidateRemovesCacheEntry(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ inst, _ := repo.Launch("default", "9868", true)+ locator.Register("tab_abc", inst.ID)++ if locator.CacheSize() != 1 {+ t.Fatal("expected cache size 1")+ }++ locator.Invalidate("tab_abc")+ if locator.CacheSize() != 0 {+ t.Error("expected cache size 0 after invalidate")+ }+}++func TestLocator_InvalidateInstance_RemovesAllTabs(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ inst, _ := repo.Launch("default", "9868", true)+ locator.Register("tab_1", inst.ID)+ locator.Register("tab_2", inst.ID)+ locator.Register("tab_3", inst.ID)++ locator.InvalidateInstance(inst.ID)+ if locator.CacheSize() != 0 {+ t.Errorf("expected cache size 0, got %d", locator.CacheSize())+ }+}++func TestLocator_StaleCache_InstanceGone(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ repo := instance.NewRepository(launcher)+ locator := instance.NewLocator(repo, fetcher)++ inst, _ := repo.Launch("default", "9868", true)+ locator.Register("tab_abc", inst.ID)++ // Remove instance from repo (simulates crash/stop).+ repo.Remove(inst.ID)++ // Cache hit returns stale entry, but instance is gone → should fallback.+ _, err := locator.FindInstanceByTabID("tab_abc")+ if err == nil {+ t.Error("expected error when instance is gone")+ }+}++// --- Allocator tests ---++func TestAllocator_FCFS(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)+ policy := &allocation.FCFS{}+ alloc := instance.NewAllocator(repo, policy)++ _, _ = repo.Launch("prof1", "9868", true)++ got, err := alloc.Allocate()+ if err != nil {+ t.Fatal(err)+ }+ if got.ProfileName != "prof1" {+ t.Errorf("expected prof1, got %s", got.ProfileName)+ }+}++func TestAllocator_RoundRobin(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)+ policy := allocation.NewRoundRobin()+ alloc := instance.NewAllocator(repo, policy)++ _, _ = repo.Launch("prof1", "9868", true)+ _, _ = repo.Launch("prof2", "9869", true)++ // RoundRobin should cycle. Exact order depends on map iteration,+ // but each allocation should succeed.+ for range 4 {+ _, err := alloc.Allocate()+ if err != nil {+ t.Fatal(err)+ }+ }+}++func TestAllocator_NoRunningInstances(t *testing.T) {+ launcher := newMockLauncher()+ repo := instance.NewRepository(launcher)+ alloc := instance.NewAllocator(repo, &allocation.FCFS{})++ _, err := alloc.Allocate()+ if err == nil {+ t.Error("expected error with no running instances")+ }+}++// --- Manager facade tests ---++func TestManager_DelegatesToComponents(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ mgr := instance.NewManager(launcher, fetcher, &allocation.FCFS{})++ // Launch via manager → delegates to repo.+ inst, err := mgr.Launch("default", "9868", true)+ if err != nil {+ t.Fatal(err)+ }++ // Get via manager → delegates to repo.+ got, ok := mgr.Get(inst.ID)+ if !ok || got.ID != inst.ID {+ t.Error("Get should delegate to repo")+ }++ // List via manager → delegates to repo.+ list := mgr.List()+ if len(list) != 1 {+ t.Errorf("expected 1 instance, got %d", len(list))+ }++ // RegisterTab + FindInstanceByTabID → delegates to locator.+ mgr.RegisterTab("tab_abc", inst.ID)+ found, err := mgr.FindInstanceByTabID("tab_abc")+ if err != nil {+ t.Fatal(err)+ }+ if found.ID != inst.ID {+ t.Error("FindInstanceByTabID should delegate to locator")+ }++ // Allocate → delegates to allocator.+ alloc, err := mgr.Allocate()+ if err != nil {+ t.Fatal(err)+ }+ if alloc.ProfileName != "default" {+ t.Error("Allocate should delegate to allocator")+ }++ // Stop → delegates to repo + invalidates cache.+ if err := mgr.Stop(inst.ID); err != nil {+ t.Fatal(err)+ }+ if _, ok := mgr.Get(inst.ID); ok {+ t.Error("instance should be gone after stop")+ }+}++func TestManager_StopInvalidatesTabCache(t *testing.T) {+ launcher := newMockLauncher()+ fetcher := newMockFetcher()+ mgr := instance.NewManager(launcher, fetcher, nil)++ inst, _ := mgr.Launch("default", "9868", true)+ mgr.RegisterTab("tab_1", inst.ID)+ mgr.RegisterTab("tab_2", inst.ID)++ _ = mgr.Stop(inst.ID)++ // Tabs should be invalidated.+ _, err := mgr.FindInstanceByTabID("tab_1")+ if err == nil {+ t.Error("expected error: tab cache should be invalidated after stop")+ }+}diff --git a/internal/instance/locator.go b/internal/instance/locator.gonew file mode 100644index 00000000..5621fc12--- /dev/null+++ b/internal/instance/locator.go@@ -0,0 +1,125 @@+package instance++import (+ "fmt"+ "log/slog"+ "sync"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Locator discovers which instance owns a given tab.+// Uses an in-memory cache for O(1) lookups, falling back to+// querying bridge instances on cache miss.+type Locator struct {+ mu sync.RWMutex+ cache map[string]string // tabID → instanceID++ repo *Repository+ fetcher TabFetcher+}++// NewLocator creates a Locator backed by the given repository and tab fetcher.+func NewLocator(repo *Repository, fetcher TabFetcher) *Locator {+ return &Locator{+ cache: make(map[string]string),+ repo: repo,+ fetcher: fetcher,+ }+}++// FindInstanceByTabID returns the instance that owns the given tab.+// Fast path: cache hit (O(1)). Slow path: queries all bridges.+func (l *Locator) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {+ // Fast path: check cache.+ l.mu.RLock()+ instID, ok := l.cache[tabID]+ l.mu.RUnlock()++ if ok {+ inst, found := l.repo.Get(instID)+ if found && inst.Status == "running" {+ return inst, nil+ }+ // Stale cache entry — instance gone or not running.+ l.Invalidate(tabID)+ }++ // Slow path: query all running bridges.+ running := l.repo.Running()+ for _, inst := range running {+ url := fmt.Sprintf("http://localhost:%s", inst.Port)+ tabs, err := l.fetcher.FetchTabs(url)+ if err != nil {+ slog.Debug("locator: failed to fetch tabs", "instance", inst.ID, "err", err)+ continue+ }+ for _, tab := range tabs {+ // Cache every tab we discover for future lookups.+ l.mu.Lock()+ l.cache[tab.ID] = inst.ID+ l.mu.Unlock()++ if tab.ID == tabID {+ result := inst // copy+ return &result, nil+ }+ }+ }++ return nil, fmt.Errorf("tab %q not found in any running instance", tabID)+}++// Register adds a tab→instance mapping to the cache.+func (l *Locator) Register(tabID, instanceID string) {+ l.mu.Lock()+ l.cache[tabID] = instanceID+ l.mu.Unlock()+}++// Invalidate removes a tab from the cache.+func (l *Locator) Invalidate(tabID string) {+ l.mu.Lock()+ delete(l.cache, tabID)+ l.mu.Unlock()+}++// InvalidateInstance removes all cached tabs for an instance.+func (l *Locator) InvalidateInstance(instanceID string) {+ l.mu.Lock()+ for tabID, instID := range l.cache {+ if instID == instanceID {+ delete(l.cache, tabID)+ }+ }+ l.mu.Unlock()+}++// RefreshAll clears the cache and re-discovers all tabs from running instances.+func (l *Locator) RefreshAll() {+ l.mu.Lock()+ l.cache = make(map[string]string)+ l.mu.Unlock()++ running := l.repo.Running()+ for _, inst := range running {+ url := fmt.Sprintf("http://localhost:%s", inst.Port)+ tabs, err := l.fetcher.FetchTabs(url)+ if err != nil {+ slog.Debug("locator: refresh failed", "instance", inst.ID, "err", err)+ continue+ }+ l.mu.Lock()+ for _, tab := range tabs {+ l.cache[tab.ID] = inst.ID+ }+ l.mu.Unlock()+ }+}++// CacheSize returns the number of cached tab→instance mappings.+func (l *Locator) CacheSize() int {+ l.mu.RLock()+ defer l.mu.RUnlock()+ return len(l.cache)+}diff --git a/internal/instance/manager.go b/internal/instance/manager.gonew file mode 100644index 00000000..b3ea65f3--- /dev/null+++ b/internal/instance/manager.go@@ -0,0 +1,84 @@+package instance++import (+ "github.com/pinchtab/pinchtab/internal/allocation"+ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Manager is the InstanceManager facade.+// It composes Repository, Locator, and Allocator —+// delegating all calls, owning zero business logic.+type Manager struct {+ Repo *Repository+ Locator *Locator+ Allocator *Allocator+}++// NewManager creates a fully wired Manager.+func NewManager(launcher InstanceLauncher, fetcher TabFetcher, policy allocation.Policy) *Manager {+ if policy == nil {+ policy = &allocation.FCFS{}+ }++ repo := NewRepository(launcher)+ locator := NewLocator(repo, fetcher)+ allocator := NewAllocator(repo, policy)++ return &Manager{+ Repo: repo,+ Locator: locator,+ Allocator: allocator,+ }+}++// --- Lifecycle (delegates to Repository) ---++// Launch starts a new instance.+func (m *Manager) Launch(name, port string, headless bool) (*bridge.Instance, error) {+ return m.Repo.Launch(name, port, headless)+}++// Stop terminates an instance and invalidates its tab cache.+func (m *Manager) Stop(id string) error {+ m.Locator.InvalidateInstance(id)+ return m.Repo.Stop(id)+}++// List returns all tracked instances.+func (m *Manager) List() []bridge.Instance {+ return m.Repo.List()+}++// Get returns an instance by ID.+func (m *Manager) Get(id string) (*bridge.Instance, bool) {+ return m.Repo.Get(id)+}++// Running returns only running instances.+func (m *Manager) Running() []bridge.Instance {+ return m.Repo.Running()+}++// --- Discovery (delegates to Locator) ---++// FindInstanceByTabID returns the instance that owns a tab.+func (m *Manager) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {+ return m.Locator.FindInstanceByTabID(tabID)+}++// RegisterTab adds a tab→instance mapping to the cache.+func (m *Manager) RegisterTab(tabID, instanceID string) {+ m.Locator.Register(tabID, instanceID)+}++// InvalidateTab removes a tab from the cache.+func (m *Manager) InvalidateTab(tabID string) {+ m.Locator.Invalidate(tabID)+}++// --- Allocation (delegates to Allocator) ---++// Allocate selects a running instance using the configured policy.+func (m *Manager) Allocate() (*bridge.Instance, error) {+ return m.Allocator.Allocate()+}diff --git a/internal/instance/repository.go b/internal/instance/repository.gonew file mode 100644index 00000000..09bf6c69--- /dev/null+++ b/internal/instance/repository.go@@ -0,0 +1,104 @@+package instance++import (+ "fmt"+ "sync"++ "github.com/pinchtab/pinchtab/internal/bridge"+)++// Repository manages the in-memory store of instances and delegates+// process lifecycle to an InstanceLauncher (typically the Orchestrator).+type Repository struct {+ mu sync.RWMutex+ instances map[string]*bridge.Instance+ launcher InstanceLauncher+}++// NewRepository creates a Repository backed by the given launcher.+func NewRepository(launcher InstanceLauncher) *Repository {+ return &Repository{+ instances: make(map[string]*bridge.Instance),+ launcher: launcher,+ }+}++// Launch starts a new instance and adds it to the store.+func (r *Repository) Launch(name, port string, headless bool) (*bridge.Instance, error) {+ inst, err := r.launcher.Launch(name, port, headless)+ if err != nil {+ return nil, fmt.Errorf("launch instance: %w", err)+ }+ r.mu.Lock()+ r.instances[inst.ID] = inst+ r.mu.Unlock()+ return inst, nil+}++// Stop terminates an instance and removes it from the store.+func (r *Repository) Stop(id string) error {+ if err := r.launcher.Stop(id); err != nil {+ return fmt.Errorf("stop instance %q: %w", id, err)+ }+ r.mu.Lock()+ delete(r.instances, id)+ r.mu.Unlock()+ return nil+}++// List returns all instances. The returned slice is a snapshot.+func (r *Repository) List() []bridge.Instance {+ r.mu.RLock()+ defer r.mu.RUnlock()+ out := make([]bridge.Instance, 0, len(r.instances))+ for _, inst := range r.instances {+ out = append(out, *inst)+ }+ return out+}++// Running returns only instances with status "running".+func (r *Repository) Running() []bridge.Instance {+ r.mu.RLock()+ defer r.mu.RUnlock()+ out := make([]bridge.Instance, 0, len(r.instances))+ for _, inst := range r.instances {+ if inst.Status == "running" {+ out = append(out, *inst)+ }+ }+ return out+}++// Get returns an instance by ID.+func (r *Repository) Get(id string) (*bridge.Instance, bool) {+ r.mu.RLock()+ defer r.mu.RUnlock()+ inst, ok := r.instances[id]+ if !ok {+ return nil, false+ }+ copy := *inst+ return ©, true+}++// Add registers an existing instance (used for sync with external state).+func (r *Repository) Add(inst *bridge.Instance) {+ r.mu.Lock()+ r.instances[inst.ID] = inst+ r.mu.Unlock()+}++// Remove deletes an instance from the store without stopping it.+func (r *Repository) Remove(id string) {+ r.mu.Lock()+ delete(r.instances, id)+ r.mu.Unlock()+}++// Count returns the number of tracked instances.+func (r *Repository) Count() int {+ r.mu.RLock()+ defer r.mu.RUnlock()+ return len(r.instances)+}diff --git a/internal/instance/types.go b/internal/instance/types.gonew file mode 100644index 00000000..93e00630--- /dev/null+++ b/internal/instance/types.go@@ -0,0 +1,31 @@+// Package instance implements the decomposed InstanceManager (Facade Pattern).+//+// Components:+// - Repository: instance lifecycle (Launch, Stop, List, Get)+// - Locator: tab discovery + cache (FindInstanceByTabID)+// - Allocator: policy application (AllocateInstance)+// - TabService: tab operations (CreateTab, CloseTab, ListTabs)+// - Router: HTTP proxying (ProxyTabRequest)+// - Manager: facade composing all 5 components+package instance++import "github.com/pinchtab/pinchtab/internal/bridge"++// TabEntry represents a tab in a bridge's registry.+type TabEntry struct {+ ID string `json:"id"`+ URL string `json:"url"`+}++// InstanceLauncher abstracts the process of launching and stopping browser instances.+// The Orchestrator implements this — the instance package delegates to it+// for process management while owning the higher-level abstractions.+type InstanceLauncher interface {+ Launch(name, port string, headless bool) (*bridge.Instance, error)+ Stop(id string) error+}++// TabFetcher abstracts fetching tabs from a bridge instance via HTTP.+type TabFetcher interface {+ FetchTabs(instanceURL string) ([]bridge.InstanceTab, error)+}diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.goindex 595e8d82..b64c674d 100644--- a/internal/orchestrator/health.go+++ b/internal/orchestrator/health.go@@ -76,6 +76,7 @@ func (o *Orchestrator) monitor(inst *InstanceInternal) {if resolvedURL != "" {inst.URL = resolvedURL}+ o.syncInstanceToManager(&inst.Instance)eventType = "instance.started"slog.Info("instance ready", "id", inst.ID, "port", inst.Port)} else if exitedEarly {diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex cd2a983f..5df73990 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -14,9 +14,11 @@ import ("sync""time"+ "github.com/pinchtab/pinchtab/internal/allocation""github.com/pinchtab/pinchtab/internal/api/types""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/idutil"+ "github.com/pinchtab/pinchtab/internal/instance""github.com/pinchtab/pinchtab/internal/profiles")@@ -48,6 +50,7 @@ type Orchestrator struct {portAllocator *PortAllocatoridMgr *idutil.ManageronEvent EventHandler+ instanceMgr *instance.Manager}// OnEvent sets the event handler for instance lifecycle events.@@ -125,9 +128,53 @@ func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *OrchestratorportAllocator: NewPortAllocator(9868, 9968),idMgr: idutil.NewManager(),}++ bridgeClient := instance.NewBridgeClient()+ defaultPolicy, _ := allocation.New("fcfs")+ orch.instanceMgr = instance.NewManager(+ &orchestratorLauncher{orch: orch},+ bridgeClient,+ defaultPolicy,+ )+return orch}+// InstanceManager returns the decomposed instance manager.+func (o *Orchestrator) InstanceManager() *instance.Manager {+ return o.instanceMgr+}++// SetAllocationPolicy changes the allocation policy at runtime.+func (o *Orchestrator) SetAllocationPolicy(name string) error {+ p, err := allocation.New(name)+ if err != nil {+ return err+ }+ o.instanceMgr.Allocator.SetPolicy(p)+ slog.Info("allocation policy changed", "policy", name)+ return nil+}++type orchestratorLauncher struct {+ orch *Orchestrator+}++func (l *orchestratorLauncher) Launch(name, port string, headless bool) (*bridge.Instance, error) {+ return l.orch.Launch(name, port, headless, nil)+}++func (l *orchestratorLauncher) Stop(id string) error {+ return l.orch.Stop(id)+}++func (o *Orchestrator) syncInstanceToManager(inst *bridge.Instance) {+ if o.instanceMgr == nil {+ return+ }+ o.instanceMgr.Repo.Add(inst)+}+func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {o.profiles = pm}@@ -366,6 +413,11 @@ func (o *Orchestrator) markStopped(id string) {delete(o.instances, id)o.mu.Unlock()+ if o.instanceMgr != nil {+ o.instanceMgr.Locator.InvalidateInstance(id)+ o.instanceMgr.Repo.Remove(id)+ }+slog.Info("instance stopped and removed", "id", id, "profile", profileName)if strings.HasPrefix(profileName, "instance-") {diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex f399cc1f..c0e2d904 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -12,6 +12,9 @@ import (// proxyTabRequest is a generic handler that proxies requests to the instance// that owns the tab specified in the path. Works for any /tabs/{id}/* route.+//+// Uses the instance Manager's Locator for O(1) cached lookups, falling back+// to the legacy O(n×m) bridge query on cache miss.func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {tabID := r.PathValue("id")if tabID == "" {@@ -19,12 +22,32 @@ func (o *Orchestrator) proxyTabRequest(w http.ResponseWriter, r *http.Request) {return}+ // Fast path: Locator cache hit+ if o.instanceMgr != nil {+ if inst, err := o.instanceMgr.FindInstanceByTabID(tabID); err == nil {+ targetURL := &url.URL{+ Scheme: "http",+ Host: net.JoinHostPort("localhost", inst.Port),+ Path: r.URL.Path,+ RawQuery: r.URL.RawQuery,+ }+ o.proxyToURL(w, r, targetURL)+ return+ }+ }++ // Slow path: legacy lookupinst, err := o.findRunningInstanceByTabID(tabID)if err != nil {web.Error(w, 404, err)return}+ // Cache for future O(1) lookups+ if o.instanceMgr != nil {+ o.instanceMgr.Locator.Register(tabID, inst.ID)+ }+targetURL := &url.URL{Scheme: "http",Host: net.JoinHostPort("localhost", inst.Port),diff --git a/internal/strategy/explicit/explicit.go b/internal/strategy/explicit/explicit.gonew file mode 100644index 00000000..66ff0772--- /dev/null+++ b/internal/strategy/explicit/explicit.go@@ -0,0 +1,123 @@+// Package explicit implements the "explicit" strategy.+// All orchestrator endpoints are exposed directly — agents manage+// instances, profiles, and tabs explicitly. This reproduces the+// default dashboard behavior prior to the strategy framework.+package explicit++import (+ "context"+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/orchestrator"+ "github.com/pinchtab/pinchtab/internal/strategy"+ "github.com/pinchtab/pinchtab/internal/web"+)++func init() {+ strategy.MustRegister("explicit", func() strategy.Strategy {+ return &Strategy{}+ })+}++// Strategy exposes all orchestrator endpoints directly.+type Strategy struct {+ orch *orchestrator.Orchestrator+}++func (s *Strategy) Name() string { return "explicit" }++// SetOrchestrator injects the orchestrator after construction.+func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {+ s.orch = o+}++func (s *Strategy) Start(_ context.Context) error { return nil }+func (s *Strategy) Stop() error { return nil }++// RegisterRoutes adds all orchestrator routes plus shorthand proxy endpoints.+func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {+ s.orch.RegisterHandlers(mux)++ // Shorthand endpoints proxy to first running instance.+ shorthandRoutes := []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 _, route := range shorthandRoutes {+ mux.HandleFunc(route, s.proxyToFirst)+ }++ // /tabs returns empty list when no instances running.+ mux.HandleFunc("GET /tabs", s.handleTabs)+}++func (s *Strategy) proxyToFirst(w http.ResponseWriter, r *http.Request) {+ target := s.orch.FirstRunningURL()+ if target == "" {+ web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))+ return+ }+ proxyHTTP(w, r, target+r.URL.Path)+}++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 proxyHTTP(w http.ResponseWriter, r *http.Request, targetURL string) {+ if r.URL.RawQuery != "" {+ targetURL += "?" + r.URL.RawQuery+ }++ client := &http.Client{}+ 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/simple/simple.go b/internal/strategy/simple/simple.gonew file mode 100644index 00000000..346f9e78--- /dev/null+++ b/internal/strategy/simple/simple.go@@ -0,0 +1,172 @@+// Package simple implements the "simple" allocation strategy.+//+// Simple makes orchestrator mode feel like bridge mode.+// All shorthand endpoints proxy to the first running instance.+// If no instances are running, one is auto-launched on first request.+//+// Tab lifecycle is handled by the bridge — the strategy is just+// a thin proxy with auto-launch.+package simple++import (+ "context"+ "fmt"+ "log/slog"+ "net/http"+ "time"++ "github.com/pinchtab/pinchtab/internal/orchestrator"+ "github.com/pinchtab/pinchtab/internal/strategy"+ "github.com/pinchtab/pinchtab/internal/web"+)++func init() {+ strategy.MustRegister("simple", func() strategy.Strategy {+ return &Strategy{}+ })+}++// Strategy proxies all shorthand endpoints to the first running instance,+// auto-launching one if needed.+type Strategy struct {+ orch *orchestrator.Orchestrator+}++func (s *Strategy) Name() string { return "simple" }++// SetOrchestrator injects the orchestrator after construction.+func (s *Strategy) SetOrchestrator(o *orchestrator.Orchestrator) {+ s.orch = o+}++func (s *Strategy) Start(_ context.Context) error { return nil }+func (s *Strategy) Stop() error { return nil }++// RegisterRoutes adds shorthand endpoints that proxy to the first running instance.+func (s *Strategy) RegisterRoutes(mux *http.ServeMux) {+ // Register orchestrator's instance/profile/tab-specific routes.+ s.orch.RegisterHandlers(mux)++ // Shorthand endpoints — all proxy to first running instance.+ 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.proxyToFirst)+ }++ mux.HandleFunc("GET /tabs", s.handleTabs)+}++// proxyToFirst ensures an instance is running, then proxies the request to it.+func (s *Strategy) proxyToFirst(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)+}++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")+}++// ensureRunning returns the URL of a running instance, auto-launching one if needed.+func (s *Strategy) ensureRunning() (string, error) {+ if s.orch == nil {+ return "", fmt.Errorf("no running instances")+ }+ if target := s.orch.FirstRunningURL(); target != "" {+ return target, nil+ }++ slog.Info("simple strategy: no running instances, auto-launching")+ mgr := s.orch.InstanceManager()+ if mgr == nil {+ return "", fmt.Errorf("no running instances")+ }++ launched, err := mgr.Launch("default", "", true)+ if err != nil {+ return "", fmt.Errorf("auto-launch failed: %w", err)+ }++ // Wait for instance to become ready.+ deadline := time.Now().Add(30 * time.Second)+ for time.Now().Before(deadline) {+ time.Sleep(500 * time.Millisecond)+ url := fmt.Sprintf("http://localhost:%s", launched.Port)+ resp, healthErr := http.Get(url + "/health")+ if healthErr == nil {+ _ = resp.Body.Close()+ if resp.StatusCode == 200 {+ return url, nil+ }+ }+ }++ return "", fmt.Errorf("instance launched but did not become ready in time")+}++// 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/simple/simple_test.go b/internal/strategy/simple/simple_test.gonew file mode 100644index 00000000..897604ba--- /dev/null+++ b/internal/strategy/simple/simple_test.go@@ -0,0 +1,92 @@+package simple++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// 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 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_Name(t *testing.T) {+ s := &Strategy{}+ if s.Name() != "simple" {+ t.Errorf("expected 'simple', got %q", s.Name())+ }+}++func TestStrategy_ProxyToFirst_NoOrch_Returns503(t *testing.T) {+ s := &Strategy{} // no orchestrator+ req := httptest.NewRequest("GET", "/snapshot", nil)+ rec := httptest.NewRecorder()+ s.proxyToFirst(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) {+ // handleTabs with nil orch would panic — test the empty-tabs path+ // by checking the JSON response format of proxyHTTP fallback.+ 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)+ }+}diff --git a/internal/strategy/strategy.go b/internal/strategy/strategy.gonew file mode 100644index 00000000..24a4c6e3--- /dev/null+++ b/internal/strategy/strategy.go@@ -0,0 +1,82 @@+// Package strategy defines the interface for pluggable allocation strategies.+// Strategies control how the dashboard routes requests to browser instances.+package strategy++import (+ "context"+ "fmt"+ "net/http"+ "sync"+)++// Orchestrator is the interface strategies need from the orchestrator.+// Avoids import cycles by depending on the interface, not the concrete type.+type Orchestrator interface {+ RegisterHandlers(mux *http.ServeMux)+ FirstRunningURL() string+}++// Strategy defines a browser allocation approach.+type Strategy interface {+ // Name returns the strategy identifier.+ Name() string++ // RegisterRoutes adds strategy-specific HTTP endpoints to the mux.+ RegisterRoutes(mux *http.ServeMux)++ // Start begins any background tasks.+ Start(ctx context.Context) error++ // Stop gracefully shuts down.+ Stop() error+}++// Factory creates a new Strategy instance.+type Factory func() Strategy++var (+ registry = make(map[string]Factory)+ mu sync.RWMutex+)++// Register adds a strategy factory to the registry.+func Register(name string, factory Factory) error {+ mu.Lock()+ defer mu.Unlock()+ if _, exists := registry[name]; exists {+ return fmt.Errorf("strategy %q already registered", name)+ }+ registry[name] = factory+ return nil+}++// MustRegister is like Register but panics on duplicate name.+func MustRegister(name string, factory Factory) {+ if err := Register(name, factory); err != nil {+ panic(err)+ }+}++// New creates a strategy by name from the registry.+func New(name string) (Strategy, error) {+ mu.RLock()+ factory, ok := registry[name]+ mu.RUnlock()++ if !ok {+ return nil, fmt.Errorf("unknown strategy: %s (available: %v)", name, Names())+ }+ return factory(), nil+}++// Names returns all registered strategy names.+func Names() []string {+ mu.RLock()+ defer mu.RUnlock()++ names := make([]string, 0, len(registry))+ for name := range registry {+ names = append(names, name)+ }+ return names+}diff --git a/internal/strategy/strategy_test.go b/internal/strategy/strategy_test.gonew file mode 100644index 00000000..fa506307--- /dev/null+++ b/internal/strategy/strategy_test.go@@ -0,0 +1,52 @@+package strategy_test++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/strategy"++ // Register strategies via init()+ _ "github.com/pinchtab/pinchtab/internal/strategy/explicit"+ _ "github.com/pinchtab/pinchtab/internal/strategy/simple"+)++func TestRegistry_ExplicitRegistered(t *testing.T) {+ s, err := strategy.New("explicit")+ if err != nil {+ t.Fatalf("explicit strategy not registered: %v", err)+ }+ if s.Name() != "explicit" {+ t.Errorf("expected name 'explicit', got %q", s.Name())+ }+}++func TestRegistry_SimpleRegistered(t *testing.T) {+ s, err := strategy.New("simple")+ if err != nil {+ t.Fatalf("simple strategy not registered: %v", err)+ }+ if s.Name() != "simple" {+ t.Errorf("expected name 'simple', got %q", s.Name())+ }+}++func TestRegistry_UnknownStrategy(t *testing.T) {+ _, err := strategy.New("nonexistent")+ if err == nil {+ t.Error("expected error for unknown strategy")+ }+}++func TestRegistry_Names(t *testing.T) {+ names := strategy.Names()+ found := map[string]bool{}+ for _, n := range names {+ found[n] = true+ }+ if !found["explicit"] {+ t.Error("explicit not in names")+ }+ if !found["simple"] {+ t.Error("simple not in names")+ }+}