High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: route.attempts records a phantom accepted entry and misattributes the skipped provider PIN-011
Luigi Agostiab5cdd5ca624
diff --git a/internal/browserops/browserops.go b/internal/browserops/browserops.goindex e35c7cf5..dfb64552 100644--- a/internal/browserops/browserops.go+++ b/internal/browserops/browserops.go@@ -106,16 +106,6 @@ type RouteAttempt struct {Reason string `json:"reason,omitempty"`}-func SingleBrowserRoute(browser string) *RouteMetadata {- return &RouteMetadata{- RequestedBrowser: browser,- UsedBrowser: browser,- Attempts: []RouteAttempt{- {Browser: browser, Accepted: true},- },- }-}-// BrowserRuntime is the minimal interface implemented by browser operation// runtimes such as static fetch or browser-backed CDP adapters.type BrowserRuntime interface {diff --git a/internal/browserops/browserops_test.go b/internal/browserops/browserops_test.goindex 16013056..c648eb39 100644--- a/internal/browserops/browserops_test.go+++ b/internal/browserops/browserops_test.go@@ -5,25 +5,11 @@ import ("testing")-func TestSingleBrowserRoute(t *testing.T) {- route := SingleBrowserRoute("chrome")- if route.RequestedBrowser != "chrome" {- t.Errorf("RequestedBrowser = %q, want %q", route.RequestedBrowser, "chrome")- }- if route.UsedBrowser != "chrome" {- t.Errorf("UsedBrowser = %q, want %q", route.UsedBrowser, "chrome")- }- if route.Escalated {- t.Error("Escalated should be false")- }- if len(route.Attempts) != 1 {- t.Fatalf("len(Attempts) = %d, want 1", len(route.Attempts))- }- if route.Attempts[0].Browser != "chrome" {- t.Errorf("Attempts[0].Browser = %q, want %q", route.Attempts[0].Browser, "chrome")- }- if !route.Attempts[0].Accepted {- t.Error("Attempts[0].Accepted should be true")+func singleBrowserRoute(browser string) *RouteMetadata {+ return &RouteMetadata{+ RequestedBrowser: browser,+ UsedBrowser: browser,+ Attempts: []RouteAttempt{{Browser: browser, Accepted: true}},}}@@ -32,7 +18,7 @@ func TestRouteMetadataJSONKeys(t *testing.T) {TabID: "tab-1",URL: "https://example.com",Title: "Example",- Route: SingleBrowserRoute("chrome"),+ Route: singleBrowserRoute("chrome"),}data, err := json.Marshal(result)@@ -101,7 +87,7 @@ func TestRouteMetadataJSONKeys(t *testing.T) {// TestResultStructsOmitEngine verifies that all result structs serialize// with "route" metadata and never include an "browserops" key.func TestResultStructsOmitEngine(t *testing.T) {- route := SingleBrowserRoute("lite")+ route := singleBrowserRoute("lite")tests := []struct {name stringdiff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 4cf46d69..f868cd12 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -65,22 +65,6 @@ func (h *Handlers) enforceTabNotPausedForHandoff(tabID string) error {return fmt.Errorf("tab %s is paused for human handoff", tabID)}-// buildActionRoute assembles the route metadata recorded by the single, batch,-// and macro action endpoints: a single-browser route plus one attempt reflecting-// the handle decision, with the originally requested browser when provided.-func buildActionRoute(resolvedBrowser, requestBrowser string, decision browsers.HandleDecision) *browserops.RouteMetadata {- route := browserops.SingleBrowserRoute(resolvedBrowser)- route.Attempts = append(route.Attempts, browserops.RouteAttempt{- Browser: resolvedBrowser,- Accepted: decision.Decision == browsers.DecisionHandle,- Reason: decision.Reason,- })- if requestBrowser != "" {- route.RequestedBrowser = requestBrowser- }- return route-}-// rejectMixedBrowsers returns the first action's browser as the request browser,// rejecting (with a 400) any later action that names a different browser, since a// batch/macro executes on a single browser. noun/field tune the error wording@@ -261,9 +245,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if !ok {return}- requestBrowser := routing.RequestBrowserresolvedBrowser := routing.Browser- handleDecision := routing.DecisioneffectiveCfg := routing.EffectiveCfgreq.Browser = resolvedBrowser@@ -465,7 +447,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {markCreatedTab(w, switched)h.recordResolvedTab(r, switched)}- actionRoute := buildActionRoute(resolvedBrowser, requestBrowser, handleDecision)+ actionRoute := routeMetadataFor(routing)h.recordActivity(r, activity.Update{Route: actionRoute})resp := map[string]any{"success": true, "result": result, "route": actionRoute}if recoveryResult != nil {@@ -516,8 +498,6 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, reif !ok {return}- resolvedBrowser := routing.Browser- handleDecision := routing.DecisioneffectiveCfg := routing.EffectiveCfgvar ctx context.Context@@ -608,7 +588,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re}}- batchRoute := buildActionRoute(resolvedBrowser, requestBrowser, handleDecision)+ batchRoute := routeMetadataFor(routing)h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, results, len(req.Actions), batchRoute, nil)}@@ -729,6 +709,7 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {return}}+ macroIntentBrowser := macroResolvedBrowsermacroHandleDecision, err := checkBrowserCanHandle(macroResolvedBrowser, browsers.RequestIntent{Shape: browsers.ShapeInteraction,StateChanging: true,@@ -815,6 +796,12 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {}}- macroRoute := buildActionRoute(macroResolvedBrowser, macroRequestBrowser, macroHandleDecision)+ macroRoute := routeMetadataFor(browserRouting{+ Browser: macroResolvedBrowser,+ IntentBrowser: macroIntentBrowser,+ RequestBrowser: macroRequestBrowser,+ EffectiveCfg: macroEffectiveCfg,+ Decision: macroHandleDecision,+ })h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, results, len(req.Steps), macroRoute, map[string]any{"kind": "macro"})}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 23df9d78..ee421627 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -255,15 +255,7 @@ func (h *Handlers) validateNavigateTargets(w http.ResponseWriter, r *http.Reques// records it as activity, and returns it for the execute phase (the static-first// and escalation paths may replace it).func (h *Handlers) recordNavigateRoute(r *http.Request, routing browserRouting) *browserops.RouteMetadata {- navRoute := browserops.SingleBrowserRoute(routing.Browser)- navRoute.Attempts = append(navRoute.Attempts, browserops.RouteAttempt{- Browser: routing.Browser,- Accepted: routing.Decision.Decision == browsers.DecisionHandle,- Reason: routing.Decision.Reason,- })- if routing.RequestBrowser != "" {- navRoute.RequestedBrowser = routing.RequestBrowser- }+ navRoute := routeMetadataFor(routing)h.recordActivity(r, activity.Update{Route: navRoute})return navRoute}diff --git a/internal/handlers/read_prelude.go b/internal/handlers/read_prelude.goindex 5f214106..8bd37567 100644--- a/internal/handlers/read_prelude.go+++ b/internal/handlers/read_prelude.go@@ -15,9 +15,9 @@ import (// resolveReadRouting performs the shared browser routing for a rendered/static// read: it resolves the browser, records the read request, builds the route-// metadata (with the handle attempt and any requested browser), and records the-// route activity. ok=false means an error response was already written. The-// returned route is threaded back to the caller for the eventual response.+// metadata, and records the route activity. ok=false means an error response was+// already written. The returned route is threaded back to the caller for the+// eventual response.func (h *Handlers) resolveReadRouting(w http.ResponseWriter, r *http.Request, tabID, recordName, shape string) (*config.RuntimeConfig, *browserops.RouteMetadata, bool) {routing, ok := h.resolveBrowserForRequest(w, r, tabID, strings.TrimSpace(r.URL.Query().Get("browser")), browsers.RequestIntent{Shape: shape,@@ -28,15 +28,7 @@ func (h *Handlers) resolveReadRouting(w http.ResponseWriter, r *http.Request, tah.recordReadRequest(r, recordName, tabID)- route := browserops.SingleBrowserRoute(routing.Browser)- route.Attempts = append(route.Attempts, browserops.RouteAttempt{- Browser: routing.Browser,- Accepted: routing.Decision.Decision == browsers.DecisionHandle,- Reason: routing.Decision.Reason,- })- if routing.RequestBrowser != "" {- route.RequestedBrowser = routing.RequestBrowser- }+ route := routeMetadataFor(routing)h.recordActivity(r, activity.Update{Route: route})return routing.EffectiveCfg, route, truediff --git a/internal/handlers/route_metadata.go b/internal/handlers/route_metadata.gonew file mode 100644index 00000000..6419c8fb--- /dev/null+++ b/internal/handlers/route_metadata.go@@ -0,0 +1,40 @@+package handlers++import (+ "github.com/pinchtab/pinchtab/internal/browserops"+ "github.com/pinchtab/pinchtab/internal/browsers"+)++// routeMetadataFor builds the route metadata for a resolved request: one attempt+// per browser actually consulted. A CanHandle downgrade counts as two — the+// intent browser that declined, then chrome — and marks the route escalated.+func routeMetadataFor(routing browserRouting) *browserops.RouteMetadata {+ route := &browserops.RouteMetadata{+ RequestedBrowser: routing.Browser,+ UsedBrowser: routing.Browser,+ }+ if routing.RequestBrowser != "" {+ route.RequestedBrowser = routing.RequestBrowser+ }++ intentBrowser := routing.IntentBrowser+ if intentBrowser == "" {+ intentBrowser = routing.Browser+ }++ if intentBrowser != routing.Browser {+ route.Escalated = true+ route.Attempts = []browserops.RouteAttempt{+ {Browser: intentBrowser, Reason: routing.Decision.Reason},+ {Browser: routing.Browser, Accepted: true},+ }+ return route+ }++ route.Attempts = []browserops.RouteAttempt{{+ Browser: routing.Browser,+ Accepted: routing.Decision.Decision == browsers.DecisionHandle,+ Reason: routing.Decision.Reason,+ }}+ return route+}diff --git a/internal/handlers/route_metadata_test.go b/internal/handlers/route_metadata_test.gonew file mode 100644index 00000000..93d90bb4--- /dev/null+++ b/internal/handlers/route_metadata_test.go@@ -0,0 +1,213 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "net"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/browserops"+ "github.com/pinchtab/pinchtab/internal/browsers"+ _ "github.com/pinchtab/pinchtab/internal/browsers/chrome"+ _ "github.com/pinchtab/pinchtab/internal/browsers/cloak"+ _ "github.com/pinchtab/pinchtab/internal/browsers/ghostchrome"+ "github.com/pinchtab/pinchtab/internal/config"+)++func routeTestConfig() *config.RuntimeConfig {+ return &config.RuntimeConfig{+ ActionTimeout: time.Second,+ BrowsersAvailable: []string{config.BrowserChrome, config.BrowserCloak, "ghost-chrome"},+ }+}++func assertSingleAttempt(t *testing.T, route *browserops.RouteMetadata, browser string) {+ t.Helper()+ if route == nil {+ t.Fatal("expected route metadata, got nil")+ }+ if len(route.Attempts) != 1 {+ t.Fatalf("len(Attempts) = %d, want 1: %+v", len(route.Attempts), route.Attempts)+ }+ if route.Attempts[0].Browser != browser || !route.Attempts[0].Accepted {+ t.Fatalf("Attempts[0] = %+v, want accepted %q", route.Attempts[0], browser)+ }+ if route.Escalated {+ t.Errorf("Escalated = true, want false on the plain handle path")+ }+ if route.UsedBrowser != browser {+ t.Errorf("UsedBrowser = %q, want %q", route.UsedBrowser, browser)+ }+}++func assertGhostChromeDowngrade(t *testing.T, route *browserops.RouteMetadata) {+ t.Helper()+ if route == nil {+ t.Fatal("expected route metadata, got nil")+ }+ if len(route.Attempts) != 2 {+ t.Fatalf("len(Attempts) = %d, want 2 (ghost-chrome then chrome): %+v", len(route.Attempts), route.Attempts)+ }+ skipped, ran := route.Attempts[0], route.Attempts[1]+ if skipped.Browser != "ghost-chrome" || skipped.Accepted {+ t.Errorf("Attempts[0] = %+v, want ghost-chrome rejected", skipped)+ }+ if skipped.Reason == "" {+ t.Error("Attempts[0].Reason is empty, want the skipping browser's own reason")+ }+ if ran.Browser != config.BrowserChrome || !ran.Accepted {+ t.Errorf("Attempts[1] = %+v, want chrome accepted", ran)+ }+ for _, attempt := range route.Attempts {+ if attempt.Browser == config.BrowserChrome && !attempt.Accepted {+ t.Errorf("chrome recorded as rejected (%+v); chrome is the browser that ran", attempt)+ }+ }+ if !route.Escalated {+ t.Error("Escalated = false, want true on a capability downgrade")+ }+ if route.UsedBrowser != config.BrowserChrome {+ t.Errorf("UsedBrowser = %q, want %q", route.UsedBrowser, config.BrowserChrome)+ }+ if route.RequestedBrowser != "ghost-chrome" {+ t.Errorf("RequestedBrowser = %q, want %q", route.RequestedBrowser, "ghost-chrome")+ }+}++func readRoute(t *testing.T, h *Handlers, browser, recordName, shape string) *browserops.RouteMetadata {+ t.Helper()+ w := httptest.NewRecorder()+ r := httptest.NewRequest("GET", "/"+recordName+"?browser="+browser, nil)+ _, route, ok := h.resolveReadRouting(w, r, "", recordName, shape)+ if !ok {+ t.Fatalf("resolveReadRouting(%s) failed: %d %s", recordName, w.Code, w.Body.String())+ }+ return route+}++func TestResolveReadRouting_SingleBrowserRecordsOneAttempt(t *testing.T) {+ reads := []struct {+ name string+ shape string+ }{+ {"text", browsers.ShapeRenderedRead},+ {"snapshot", browsers.ShapeStaticSnapshot},+ {"capture", browsers.ShapeVisual},+ }++ for _, read := range reads {+ t.Run(read.name, func(t *testing.T) {+ h := New(&mockBridge{}, routeTestConfig(), nil, nil, nil)+ assertSingleAttempt(t, readRoute(t, h, config.BrowserCloak, read.name, read.shape), config.BrowserCloak)+ })+ }+}++func TestResolveReadRouting_GhostChromeDowngradeRecordsBothBrowsers(t *testing.T) {+ h := New(&mockBridge{}, routeTestConfig(), nil, nil, nil)+ assertGhostChromeDowngrade(t, readRoute(t, h, "ghost-chrome", "text", browsers.ShapeRenderedRead))+}++func actionRoute(t *testing.T, browser string) *browserops.RouteMetadata {+ t.Helper()+ h := New(&autoSwitchActionBridge{}, routeTestConfig(), nil, nil, nil)+ body := []byte(`{"kind":"click","browser":"` + browser + `"}`)+ req := httptest.NewRequest("POST", "/action", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleAction(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp struct {+ Route *browserops.RouteMetadata `json:"route"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp.Route+}++func TestHandleAction_SingleBrowserRecordsOneAttempt(t *testing.T) {+ assertSingleAttempt(t, actionRoute(t, config.BrowserCloak), config.BrowserCloak)+}++func TestHandleAction_GhostChromeDowngradeRecordsBothBrowsers(t *testing.T) {+ assertGhostChromeDowngrade(t, actionRoute(t, "ghost-chrome"))+}++func multiStepRoute(t *testing.T, path, body string) *browserops.RouteMetadata {+ t.Helper()+ cfg := routeTestConfig()+ cfg.AllowMacro = true+ h := New(&autoSwitchActionBridge{}, cfg, nil, nil, nil)+ req := httptest.NewRequest("POST", path, bytes.NewReader([]byte(body)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ if path == "/macro" {+ h.HandleMacro(w, req)+ } else {+ h.HandleActions(w, req)+ }++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp struct {+ Route *browserops.RouteMetadata `json:"route"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp.Route+}++func TestHandleActions_GhostChromeDowngradeRecordsBothBrowsers(t *testing.T) {+ assertGhostChromeDowngrade(t, multiStepRoute(t, "/actions", `{"actions":[{"kind":"click","browser":"ghost-chrome"}]}`))+}++func TestHandleMacro_SingleBrowserRecordsOneAttempt(t *testing.T) {+ assertSingleAttempt(t, multiStepRoute(t, "/macro", `{"steps":[{"kind":"click","browser":"cloak"}]}`), config.BrowserCloak)+}++func TestHandleMacro_GhostChromeDowngradeRecordsBothBrowsers(t *testing.T) {+ assertGhostChromeDowngrade(t, multiStepRoute(t, "/macro", `{"steps":[{"kind":"click","browser":"ghost-chrome"}]}`))+}++func navigateRoute(t *testing.T, browser string) *browserops.RouteMetadata {+ t.Helper()+ stubNavigateHostResolution(t, func(context.Context, string, string) ([]net.IP, error) {+ return []net.IP{net.ParseIP("93.184.216.34")}, nil+ })++ m := &mockBridge{navigateResult: &bridge.NavigateResult{TabID: "tab_abc12345", URL: "https://example.com/"}}+ h := New(m, routeTestConfig(), nil, nil, nil)+ body := []byte(`{"url":"https://example.com","browser":"` + browser + `"}`)+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader(body))+ w := httptest.NewRecorder()+ h.HandleNavigate(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())+ }+ var resp struct {+ Route *browserops.RouteMetadata `json:"route"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ return resp.Route+}++func TestHandleNavigate_SingleBrowserRecordsOneAttempt(t *testing.T) {+ assertSingleAttempt(t, navigateRoute(t, config.BrowserCloak), config.BrowserCloak)+}++func TestHandleNavigate_GhostChromeDowngradeRecordsBothBrowsers(t *testing.T) {+ assertGhostChromeDowngrade(t, navigateRoute(t, "ghost-chrome"))+}