High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a blocking JS dialog is diagnosed on one path and misreported on every other, including a wrong remedy and retryable:true that loop forever (PIN-110)
Luigi Agostifa734e555b3a
diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.goindex 999d62f4..a9d669ce 100644--- a/internal/handlers/action_execution.go+++ b/internal/handlers/action_execution.go@@ -288,20 +288,12 @@ func (h *Handlers) refreshRefCache(ctx context.Context, tabID string) {})}-func isClickTimeoutWithPendingDialog(err error, kind, tabID string, b bridge.BridgeAPI) bool {- if err == nil || tabID == "" {+func isTimeoutWithPendingDialog(err error, tabID string, b bridge.BridgeAPI) bool {+ if err == nil {return false}if !errors.Is(err, context.DeadlineExceeded) {return false}- kind = bridge.CanonicalActionKind(kind)- if kind != bridge.ActionClick && kind != bridge.ActionDoubleClick {- return false- }- dm := b.GetDialogManager()- if dm == nil {- return false- }- return dm.GetPending(tabID) != nil+ return pendingTabDialog(b, tabID) != nil}diff --git a/internal/handlers/action_submit_test.go b/internal/handlers/action_submit_test.goindex 7ee48294..a00b859d 100644--- a/internal/handlers/action_submit_test.go+++ b/internal/handlers/action_submit_test.go@@ -273,7 +273,7 @@ func TestHandleClickSubmitNativeDialogKeepsDialogBlockingContract(t *testing.T)h := New(b, &config.RuntimeConfig{ActionTimeout: 10 * time.Millisecond}, nil, nil, nil)w := postSubmitRequest(t, h, `{"kind":"click","tabId":"tab1","nodeId":42,"submit":true}`)- if w.Code != http.StatusInternalServerError || !strings.Contains(w.Body.String(), `"code":"dialog_blocking"`) {+ if w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), `"code":"dialog_blocked"`) {t.Fatalf("native dialog contract changed: status=%d body=%s", w.Code, w.Body.String())}if b.urlCalls != 1 {diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 9a286cf8..7b1019e6 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -82,8 +82,6 @@ func rejectMultiStepSubmitClicks(w http.ResponseWriter, actions []bridge.ActionRreturn true}-const dialogActionHint = "use --dialog-action accept or --dialog-action dismiss"-const navigationChangedHint = "The action navigated the page, which the guard reports unless the request declares it: set waitNav true to wait for the navigation, or submit true when the click submits a form."const navigationChangedRemedy = "pinchtab click <ref> --wait-nav (use --submit instead when the click submits a form)"@@ -111,36 +109,21 @@ func navigatedToURL(err error) string {return strings.TrimSpace(message[idx+len(" -> "):])}-type dialogBlockingError struct {- message string- dialogType string- dialogText string-}--func (h *Handlers) mapDialogBlockingError(err error, kind, tabID string) (dialogBlockingError, bool) {+func (h *Handlers) mapDialogBlockingError(err error, kind, tabID string) (string, *bridge.DialogState, bool) {var dialogErr *bridge.ErrDialogBlockingif errors.As(err, &dialogErr) {- return dialogBlockingError{- message: err.Error(),- dialogType: dialogErr.DialogType,- dialogText: dialogErr.DialogMessage,- }, true- }- if isClickTimeoutWithPendingDialog(err, kind, tabID, h.Bridge) {- if ds := h.Bridge.GetDialogManager().GetPending(tabID); ds != nil {- return dialogBlockingError{- message: fmt.Sprintf("action %s timed out; a JavaScript dialog is blocking (%s: %q) — %s", kind, ds.Type, ds.Message, dialogActionHint),- dialogType: ds.Type,- dialogText: ds.Message,- }, true- }- }- return dialogBlockingError{}, false+ return err.Error(), &bridge.DialogState{Type: dialogErr.DialogType, Message: dialogErr.DialogMessage}, true+ }+ if isTimeoutWithPendingDialog(err, tabID, h.Bridge) {+ dialog := pendingTabDialog(h.Bridge, tabID)+ return fmt.Sprintf("action %s timed out; a JavaScript dialog is blocking (%s: %q)", kind, dialog.Type, dialog.Message), dialog, true+ }+ return "", nil, false}func (h *Handlers) dialogAwareActionError(err error, kind, tabID, fallback string) string {- if db, ok := h.mapDialogBlockingError(err, kind, tabID); ok {- return db.message+ if message, _, ok := h.mapDialogBlockingError(err, kind, tabID); ok {+ return message}return fallback}@@ -311,6 +294,9 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {httpx.ErrorCode(w, 423, "tab_locked", err.Error(), false, nil)return}+ if h.refuseIfDialogBlocked(w, resolvedTabID) {+ return+ }if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {return}@@ -385,7 +371,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {}result, actionBackend, recoveryResult, actionErr := h.executeActionResilient(tCtx, &req, effectiveCfg, resolvedTabID, refMissing)- submitTimeoutWithDialog := submitClick && isClickTimeoutWithPendingDialog(actionErr, req.Kind, resolvedTabID, h.Bridge)+ submitTimeoutWithDialog := submitClick && isTimeoutWithPendingDialog(actionErr, resolvedTabID, h.Bridge)if submitClick && !submitTimeoutWithDialog && (actionErr == nil || errors.Is(actionErr, context.DeadlineExceeded)) {actionTimedOut := errors.Is(actionErr, context.DeadlineExceeded)dispatch := "acknowledged"@@ -429,12 +415,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {httpx.ErrorCode(w, http.StatusForbidden, "idpi_blocked", actionErr.Error(), false, nil)return}- if db, ok := h.mapDialogBlockingError(actionErr, req.Kind, resolvedTabID); ok {- httpx.ErrorCode(w, 500, "dialog_blocking", db.message, false, map[string]any{- "suggestion": dialogActionHint,- "dialog_type": db.dialogType,- "dialog_message": db.dialogText,- })+ if message, dialog, ok := h.mapDialogBlockingError(actionErr, req.Kind, resolvedTabID); ok {+ writeDialogBlocked(w, resolvedTabID, dialog, message)return}retryable := !submitClickdiff --git a/internal/handlers/dialog_blocked.go b/internal/handlers/dialog_blocked.gonew file mode 100644index 00000000..ccec92c5--- /dev/null+++ b/internal/handlers/dialog_blocked.go@@ -0,0 +1,59 @@+package handlers++import (+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/httpx"+)++const dialogBlockedCode = "dialog_blocked"++const dialogBlockedHint = "a JavaScript dialog is open on this tab and blocks every page interaction until it is answered. It belongs to this tab, so retrying, activating the tab or opening a fresh one cannot clear it."++const dialogBlockedRemedy = "pinchtab dialog accept|dismiss (or pass --dialog-action accept|dismiss on the action that opens the dialog)"++func pendingTabDialog(b bridge.BridgeAPI, tabID string) *bridge.DialogState {+ if b == nil || tabID == "" {+ return nil+ }+ dm := b.GetDialogManager()+ if dm == nil {+ return nil+ }+ return dm.GetPending(tabID)+}++func dialogBlockedMessage(tabID string, dialog *bridge.DialogState) string {+ return fmt.Sprintf("tab %s is blocked by a JavaScript dialog (%s: %q)", tabID, dialog.Type, dialog.Message)+}++func dialogBlockedDetails(tabID string, dialog *bridge.DialogState) map[string]any {+ return map[string]any{+ "tabId": tabID,+ "dialogType": dialog.Type,+ "dialogMessage": dialog.Message,+ "hint": dialogBlockedHint,+ "remedy": dialogBlockedRemedy,+ }+}++func writeDialogBlocked(w http.ResponseWriter, tabID string, dialog *bridge.DialogState, message string) {+ if message == "" {+ message = dialogBlockedMessage(tabID, dialog)+ }+ httpx.ErrorCode(w, http.StatusConflict, dialogBlockedCode, message, false, dialogBlockedDetails(tabID, dialog))+}++// refuseIfDialogBlocked answers the request with dialog_blocked when a dialog is+// pending on the tab. The lookup is in-memory, so it never touches the page it is+// reporting on.+func (h *Handlers) refuseIfDialogBlocked(w http.ResponseWriter, tabID string) bool {+ dialog := pendingTabDialog(h.Bridge, tabID)+ if dialog == nil {+ return false+ }+ writeDialogBlocked(w, tabID, dialog, "")+ return true+}diff --git a/internal/handlers/dialog_blocked_test.go b/internal/handlers/dialog_blocked_test.gonew file mode 100644index 00000000..4a923b74--- /dev/null+++ b/internal/handlers/dialog_blocked_test.go@@ -0,0 +1,127 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++type dialogBlockedFailure struct {+ Code string `json:"code"`+ Error string `json:"error"`+ Retryable bool `json:"retryable"`+ Details struct {+ TabID string `json:"tabId"`+ DialogType string `json:"dialogType"`+ DialogMessage string `json:"dialogMessage"`+ Hint string `json:"hint"`+ Remedy string `json:"remedy"`+ } `json:"details"`+}++func decodeDialogBlocked(t *testing.T, w *httptest.ResponseRecorder, dialog *bridge.DialogState) {+ t.Helper()+ if w.Code != http.StatusConflict {+ t.Fatalf("status = %d, want %d; body=%s", w.Code, http.StatusConflict, w.Body.String())+ }+ var failure dialogBlockedFailure+ if err := json.Unmarshal(w.Body.Bytes(), &failure); err != nil {+ t.Fatalf("decode failure: %v body=%s", err, w.Body.String())+ }+ if failure.Code != dialogBlockedCode {+ t.Fatalf("code = %q, want %q; body=%s", failure.Code, dialogBlockedCode, w.Body.String())+ }+ if failure.Retryable {+ t.Fatalf("dialog-blocked response advertises retryable: %s", w.Body.String())+ }+ if failure.Details.DialogType != dialog.Type || failure.Details.DialogMessage != dialog.Message {+ t.Fatalf("dialog not named: %s", w.Body.String())+ }+ if failure.Details.Remedy != dialogBlockedRemedy {+ t.Fatalf("remedy = %q, want %q", failure.Details.Remedy, dialogBlockedRemedy)+ }+ if failure.Details.Hint == "" {+ t.Fatalf("missing hint: %s", w.Body.String())+ }+}++func TestDialogBlockedIsTheSameContractOnReadsAndActions(t *testing.T) {+ dialogs := []*bridge.DialogState{+ {Type: "alert", Message: "hello alert"},+ {Type: "confirm", Message: "are you sure?"},+ {Type: "prompt", Message: "your name?", DefaultPrompt: "anon"},+ }++ paths := []struct {+ name string+ call func(h *Handlers, w *httptest.ResponseRecorder)+ }{+ {"url", func(h *Handlers, w *httptest.ResponseRecorder) {+ h.HandleURL(w, httptest.NewRequest("GET", "/url?tabId=tab1", nil))+ }},+ {"title", func(h *Handlers, w *httptest.ResponseRecorder) {+ h.HandleTitle(w, httptest.NewRequest("GET", "/title?tabId=tab1", nil))+ }},+ {"text", func(h *Handlers, w *httptest.ResponseRecorder) {+ h.HandleText(w, httptest.NewRequest("GET", "/text?tabId=tab1", nil))+ }},+ {"snapshot", func(h *Handlers, w *httptest.ResponseRecorder) {+ h.HandleSnapshot(w, httptest.NewRequest("GET", "/snapshot?tabId=tab1", nil))+ }},+ {"action", func(h *Handlers, w *httptest.ResponseRecorder) {+ body := bytes.NewReader([]byte(`{"kind":"click","tabId":"tab1","nodeId":42}`))+ h.HandleAction(w, httptest.NewRequest("POST", "/action", body))+ }},+ }++ for _, dialog := range dialogs {+ for _, path := range paths {+ t.Run(dialog.Type+"/"+path.name, func(t *testing.T) {+ mb := &mockBridge{}+ mb.GetDialogManager().SetPending("tab1", dialog)+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)++ w := httptest.NewRecorder()+ path.call(h, w)+ decodeDialogBlocked(t, w, dialog)+ })+ }+ }+}++func TestBusyTabWithAPendingDialogIsDialogBlockedNotUnresponsive(t *testing.T) {+ dialog := &bridge.DialogState{Type: "alert", Message: "hello alert"}+ b := &busyPolicyBridge{currentURLErr: context.DeadlineExceeded}+ b.GetDialogManager().SetPending("exact-tab", dialog)+ h := New(b, &config.RuntimeConfig{+ AllowedDomains: []string{"example.com"},+ IDPI: config.IDPIConfig{Enabled: true, StrictMode: true},+ }, nil, nil, nil)++ w := httptest.NewRecorder()+ h.handleWaitCore(w, httptest.NewRequest("POST", "/tabs/exact-tab/wait", nil), waitRequest{TabID: "exact-tab", Text: "ready"})++ decodeDialogBlocked(t, w, dialog)+ if strings.Contains(w.Body.String(), "fresh tab") {+ t.Fatalf("dialog-blocked response suggests a fresh tab: %s", w.Body.String())+ }+}++func TestReadsAreNotDialogBlockedWithoutAPendingDialog(t *testing.T) {+ mb := &mockBridge{}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)++ w := httptest.NewRecorder()+ h.HandleURL(w, httptest.NewRequest("GET", "/url?tabId=tab1", nil))+ if w.Code == http.StatusConflict {+ t.Fatalf("read refused as dialog-blocked with no dialog pending: %s", w.Body.String())+ }+}diff --git a/internal/handlers/dialog_test.go b/internal/handlers/dialog_test.goindex ccc252ae..dd132b13 100644--- a/internal/handlers/dialog_test.go+++ b/internal/handlers/dialog_test.go@@ -145,14 +145,13 @@ func TestDialogManagerFromMockBridge(t *testing.T) {}}-func TestIsClickTimeoutWithPendingDialog(t *testing.T) {+func TestIsTimeoutWithPendingDialog(t *testing.T) {mb := &mockBridge{}dm := mb.GetDialogManager()tests := []struct {name stringerr error- kind stringtabID stringpending *bridge.DialogStateexpected bool@@ -160,52 +159,31 @@ func TestIsClickTimeoutWithPendingDialog(t *testing.T) {{name: "nil error",err: nil,- kind: "click",tabID: "tab1",expected: false,},{name: "non-timeout error",err: fmt.Errorf("some other error"),- kind: "click",tabID: "tab1",expected: false,},{name: "timeout but no pending dialog",err: context.DeadlineExceeded,- kind: "click",tabID: "tab1",expected: false,},{- name: "timeout with pending dialog on click",+ name: "timeout with pending dialog",err: context.DeadlineExceeded,- kind: "click",tabID: "tab1",pending: &bridge.DialogState{Type: "alert", Message: "Hello"},expected: true,},- {- name: "timeout with pending dialog on doubleclick",- err: context.DeadlineExceeded,- kind: "dblclick",- tabID: "tab1",- pending: &bridge.DialogState{Type: "confirm", Message: "Are you sure?"},- expected: true,- },- {- name: "timeout with pending dialog on type action",- err: context.DeadlineExceeded,- kind: "type",- tabID: "tab1",- pending: &bridge.DialogState{Type: "alert", Message: "Hello"},- expected: false,- },{name: "timeout with empty tab ID",err: context.DeadlineExceeded,- kind: "click",tabID: "",pending: &bridge.DialogState{Type: "alert", Message: "Hello"},expected: false,@@ -219,9 +197,9 @@ func TestIsClickTimeoutWithPendingDialog(t *testing.T) {dm.SetPending(tc.tabID, tc.pending)}- got := isClickTimeoutWithPendingDialog(tc.err, tc.kind, tc.tabID, mb)+ got := isTimeoutWithPendingDialog(tc.err, tc.tabID, mb)if got != tc.expected {- t.Errorf("isClickTimeoutWithPendingDialog() = %v, want %v", got, tc.expected)+ t.Errorf("isTimeoutWithPendingDialog() = %v, want %v", got, tc.expected)}})}diff --git a/internal/handlers/read_prelude.go b/internal/handlers/read_prelude.goindex 8bd37567..6d3bc5cf 100644--- a/internal/handlers/read_prelude.go+++ b/internal/handlers/read_prelude.go@@ -49,6 +49,9 @@ func (h *Handlers) resolveReadContext(w http.ResponseWriter, r *http.Request, taWriteTabContextError(w, err, 404)return "", nil, nil, false}+ if h.refuseIfDialogBlocked(w, resolvedTabID) {+ return "", nil, nil, false+ }if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {return "", nil, nil, false}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex c0368f00..ed43617a 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -125,7 +125,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if !ghostRoute {modalNodeID, modalOpen, modalErr = bridge.TopmostModalNodeID(tCtx, frameScope)if modalErr != nil {- httpx.Error(w, selectorResolutionHTTPStatus(modalErr), fmt.Errorf("resolve topmost dialog: %w", modalErr))+ httpx.Error(w, selectorResolutionHTTPStatus(modalErr), modalErr)return}}diff --git a/internal/handlers/tab_policy.go b/internal/handlers/tab_policy.goindex 28f24e87..3e81fa93 100644--- a/internal/handlers/tab_policy.go+++ b/internal/handlers/tab_policy.go@@ -50,6 +50,9 @@ func (h *Handlers) enforceCurrentTabDomainPolicy(w http.ResponseWriter, r *http.currentURL, err := h.Bridge.CurrentURL(lookupCtx)if err != nil {if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {+ if h.refuseIfDialogBlocked(w, tabID) {+ return "", false+ }httpx.ErrorCode(w,http.StatusServiceUnavailable,diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex e1e716b4..e29f922c 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -63,7 +63,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if !ghostRoute {modalNodeID, modalOpen, err = bridge.TopmostModalNodeID(tCtx, targetFrameID)if err != nil {- httpx.Error(w, selectorResolutionHTTPStatus(err), fmt.Errorf("resolve topmost dialog: %w", err))+ httpx.Error(w, selectorResolutionHTTPStatus(err), err)return}}