High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add dialog accept/dismiss commands with auto-handling (#296) (#302)
Alice Losasso33c85125d0d5
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.goindex b4f97d02..c648e6e4 100644--- a/cmd/pinchtab/cmd_cli.go+++ b/cmd/pinchtab/cmd_cli.go@@ -330,6 +330,40 @@ var findCmd = &cobra.Command{},}+var dialogCmd = &cobra.Command{+ Use: "dialog",+ Short: "Handle JavaScript dialogs (alert, confirm, prompt)",+}++var dialogAcceptCmd = &cobra.Command{+ Use: "accept [text]",+ Short: "Accept (OK) the current dialog",+ Args: cobra.MaximumNArgs(1),+ Run: func(cmd *cobra.Command, args []string) {+ text := ""+ if len(args) > 0 {+ text = args[0]+ }+ tabID, _ := cmd.Flags().GetString("tab")+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.Dialog(client, base, token, "accept", text, tabID)+ })+ },+}++var dialogDismissCmd = &cobra.Command{+ Use: "dismiss",+ Short: "Dismiss (Cancel) the current dialog",+ Run: func(cmd *cobra.Command, args []string) {+ tabID, _ := cmd.Flags().GetString("tab")+ cfg := config.Load()+ runCLIWith(cfg, func(client *http.Client, base, token string) {+ browseractions.Dialog(client, base, token, "dismiss", "", tabID)+ })+ },+}+var selectCmd = &cobra.Command{Use: "select <ref> <value>",Short: "Select option in dropdown",@@ -407,6 +441,7 @@ func init() {checkCmd.GroupID = "browser"uncheckCmd.GroupID = "browser"networkCmd.GroupID = "browser"+ dialogCmd.GroupID = "browser"tabsCmd.AddCommand(&cobra.Command{Use: "new [url]",@@ -551,6 +586,12 @@ func init() {networkCmd.Flags().String("buffer-size", "", "Per-tab network buffer size (default 100)")networkCmd.Flags().Bool("stream", false, "Stream network entries in real-time (like tail -f)")+ dialogAcceptCmd.Flags().String("tab", "", "Tab ID")+ dialogDismissCmd.Flags().String("tab", "", "Tab ID")+ dialogCmd.AddCommand(dialogAcceptCmd)+ dialogCmd.AddCommand(dialogDismissCmd)+ rootCmd.AddCommand(dialogCmd)+instanceCmd.GroupID = "management"startInstanceCmd := &cobra.Command{diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex f01ec54e..fcd815fb 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -47,6 +47,9 @@ type BridgeAPI interface {// Network monitoringNetworkMonitor() *NetworkMonitor++ // Dialog management+ GetDialogManager() *DialogManager}type LockInfo struct {diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 45892fe2..42fab890 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -40,6 +40,7 @@ type Bridge struct {StealthScript stringActions map[string]ActionFuncLocks *LockManager+ Dialogs *DialogManager// Network monitoringnetMonitor *NetworkMonitor@@ -69,8 +70,10 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg// Only initialize TabManager if browserCtx is provided (not lazy-init case)if cfg != nil && browserCtx != nil {b.TabManager = NewTabManager(browserCtx, cfg, idMgr, b.tabSetup)+ b.SetDialogManager(b.Dialogs)}b.Locks = NewLockManager()+ b.Dialogs = NewDialogManager()b.InitActionRegistry()return b}@@ -181,6 +184,7 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {b.IdMgr = idutil.NewManager()}b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)+ b.SetDialogManager(b.Dialogs)}// Ensure action registry is populated (idempotent)@@ -251,6 +255,7 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contexb.IdMgr = idutil.NewManager()}b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.tabSetup)+ b.SetDialogManager(b.Dialogs)}}@@ -288,6 +293,11 @@ func (b *Bridge) AvailableActions() []string {return keys}+// GetDialogManager returns the bridge's dialog manager.+func (b *Bridge) GetDialogManager() *DialogManager {+ return b.Dialogs+}+// ActionFunc is the type for action handlers.type ActionFunc func(ctx context.Context, req ActionRequest) (map[string]any, error)diff --git a/internal/bridge/dialog.go b/internal/bridge/dialog.gonew file mode 100644index 00000000..b49bf6e8--- /dev/null+++ b/internal/bridge/dialog.go@@ -0,0 +1,139 @@+package bridge++import (+ "context"+ "fmt"+ "log/slog"+ "sync"++ "github.com/chromedp/cdproto/page"+ "github.com/chromedp/chromedp"+)++// DialogState represents a pending JavaScript dialog.+type DialogState struct {+ Type string `json:"type"` // "alert", "confirm", "prompt", "beforeunload"+ Message string `json:"message"` // dialog message text+ DefaultPrompt string `json:"defaultPrompt,omitempty"`+ HasBrowserHandler bool `json:"-"` // whether auto-accept handled it already+}++// DialogManager tracks pending JavaScript dialogs per tab.+type DialogManager struct {+ mu sync.RWMutex+ pending map[string]*DialogState // tabID → pending dialog+}++// NewDialogManager creates a new DialogManager.+func NewDialogManager() *DialogManager {+ return &DialogManager{+ pending: make(map[string]*DialogState),+ }+}++// SetPending stores a pending dialog for a tab.+func (dm *DialogManager) SetPending(tabID string, state *DialogState) {+ dm.mu.Lock()+ defer dm.mu.Unlock()+ dm.pending[tabID] = state+}++// GetPending returns the pending dialog for a tab, or nil.+func (dm *DialogManager) GetPending(tabID string) *DialogState {+ dm.mu.RLock()+ defer dm.mu.RUnlock()+ return dm.pending[tabID]+}++// ClearPending removes the pending dialog for a tab.+func (dm *DialogManager) ClearPending(tabID string) {+ dm.mu.Lock()+ defer dm.mu.Unlock()+ delete(dm.pending, tabID)+}++// GetAndClear atomically gets and clears the pending dialog.+func (dm *DialogManager) GetAndClear(tabID string) *DialogState {+ dm.mu.Lock()+ defer dm.mu.Unlock()+ state := dm.pending[tabID]+ delete(dm.pending, tabID)+ return state+}++// HandleDialog accepts or dismisses the current dialog on a tab via CDP.+func HandleDialog(ctx context.Context, accept bool, promptText string) error {+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return page.HandleJavaScriptDialog(accept).WithPromptText(promptText).Do(ctx)+ }))+}++// ListenDialogEvents sets up a CDP event listener for JavaScript dialog events+// on the given context. When autoAccept is true, dialogs are automatically accepted.+func ListenDialogEvents(ctx context.Context, tabID string, dm *DialogManager, autoAccept bool) {+ chromedp.ListenTarget(ctx, func(ev interface{}) {+ switch e := ev.(type) {+ case *page.EventJavascriptDialogOpening:+ state := &DialogState{+ Type: string(e.Type),+ Message: e.Message,+ DefaultPrompt: e.DefaultPrompt,+ }+ slog.Debug("dialog opened", "tabId", tabID, "type", e.Type, "message", e.Message)++ if autoAccept {+ state.HasBrowserHandler = true+ // Auto-accept: handle immediately+ if err := HandleDialog(ctx, true, e.DefaultPrompt); err != nil {+ slog.Warn("auto-accept dialog failed", "tabId", tabID, "err", err)+ // Still store it so manual handling can retry+ dm.SetPending(tabID, state)+ } else {+ slog.Debug("dialog auto-accepted", "tabId", tabID, "type", e.Type)+ // Don't store — already handled+ }+ } else {+ dm.SetPending(tabID, state)+ }++ case *page.EventJavascriptDialogClosed:+ slog.Debug("dialog closed", "tabId", tabID, "result", e.Result)+ dm.ClearPending(tabID)+ }+ })+}++// EnableDialogEvents enables Page domain events needed for dialog tracking.+func EnableDialogEvents(ctx context.Context) error {+ return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {+ return page.Enable().Do(ctx)+ }))+}++// DialogResult is the response returned after handling a dialog.+type DialogResult struct {+ Type string `json:"type"`+ Message string `json:"message"`+ Handled bool `json:"handled"`+}++// HandlePendingDialog handles the pending dialog for a tab.+// Returns an error if no dialog is pending.+func HandlePendingDialog(ctx context.Context, tabID string, dm *DialogManager, accept bool, promptText string) (*DialogResult, error) {+ state := dm.GetAndClear(tabID)+ if state == nil {+ return nil, fmt.Errorf("no dialog open on tab %s", tabID)+ }++ if err := HandleDialog(ctx, accept, promptText); err != nil {+ // Put it back if handling failed+ dm.SetPending(tabID, state)+ return nil, fmt.Errorf("handle dialog: %w", err)+ }++ return &DialogResult{+ Type: state.Type,+ Message: state.Message,+ Handled: true,+ }, nil+}diff --git a/internal/bridge/dialog_test.go b/internal/bridge/dialog_test.gonew file mode 100644index 00000000..f24da709--- /dev/null+++ b/internal/bridge/dialog_test.go@@ -0,0 +1,148 @@+package bridge++import (+ "context"+ "testing"+)++func TestDialogManager_SetAndGetPending(t *testing.T) {+ dm := NewDialogManager()++ // No pending dialog initially+ if got := dm.GetPending("tab1"); got != nil {+ t.Fatalf("expected nil, got %+v", got)+ }++ // Set a pending dialog+ state := &DialogState{Type: "alert", Message: "Hello"}+ dm.SetPending("tab1", state)++ got := dm.GetPending("tab1")+ if got == nil {+ t.Fatal("expected pending dialog, got nil")+ }+ if got.Type != "alert" {+ t.Errorf("expected type 'alert', got %q", got.Type)+ }+ if got.Message != "Hello" {+ t.Errorf("expected message 'Hello', got %q", got.Message)+ }+}++func TestDialogManager_ClearPending(t *testing.T) {+ dm := NewDialogManager()+ dm.SetPending("tab1", &DialogState{Type: "confirm", Message: "Are you sure?"})++ dm.ClearPending("tab1")++ if got := dm.GetPending("tab1"); got != nil {+ t.Fatalf("expected nil after clear, got %+v", got)+ }+}++func TestDialogManager_ClearPending_NoOp(t *testing.T) {+ dm := NewDialogManager()+ // Should not panic+ dm.ClearPending("nonexistent")+}++func TestDialogManager_GetAndClear(t *testing.T) {+ dm := NewDialogManager()+ dm.SetPending("tab1", &DialogState{Type: "prompt", Message: "Enter name", DefaultPrompt: "default"})++ got := dm.GetAndClear("tab1")+ if got == nil {+ t.Fatal("expected pending dialog, got nil")+ }+ if got.Type != "prompt" {+ t.Errorf("expected type 'prompt', got %q", got.Type)+ }+ if got.DefaultPrompt != "default" {+ t.Errorf("expected defaultPrompt 'default', got %q", got.DefaultPrompt)+ }++ // Should be cleared now+ if got2 := dm.GetPending("tab1"); got2 != nil {+ t.Fatalf("expected nil after GetAndClear, got %+v", got2)+ }+}++func TestDialogManager_GetAndClear_NoPending(t *testing.T) {+ dm := NewDialogManager()+ got := dm.GetAndClear("tab1")+ if got != nil {+ t.Fatalf("expected nil, got %+v", got)+ }+}++func TestDialogManager_MultipleTabsIndependent(t *testing.T) {+ dm := NewDialogManager()+ dm.SetPending("tab1", &DialogState{Type: "alert", Message: "Tab 1"})+ dm.SetPending("tab2", &DialogState{Type: "confirm", Message: "Tab 2"})++ got1 := dm.GetPending("tab1")+ got2 := dm.GetPending("tab2")++ if got1 == nil || got1.Message != "Tab 1" {+ t.Errorf("tab1: expected 'Tab 1', got %+v", got1)+ }+ if got2 == nil || got2.Message != "Tab 2" {+ t.Errorf("tab2: expected 'Tab 2', got %+v", got2)+ }++ // Clear tab1, tab2 should remain+ dm.ClearPending("tab1")+ if dm.GetPending("tab1") != nil {+ t.Error("tab1 should be cleared")+ }+ if dm.GetPending("tab2") == nil {+ t.Error("tab2 should still be pending")+ }+}++func TestDialogManager_OverwritePending(t *testing.T) {+ dm := NewDialogManager()+ dm.SetPending("tab1", &DialogState{Type: "alert", Message: "First"})+ dm.SetPending("tab1", &DialogState{Type: "confirm", Message: "Second"})++ got := dm.GetPending("tab1")+ if got == nil {+ t.Fatal("expected pending dialog")+ }+ if got.Type != "confirm" || got.Message != "Second" {+ t.Errorf("expected overwritten dialog, got %+v", got)+ }+}++func TestDialogState_Fields(t *testing.T) {+ state := &DialogState{+ Type: "prompt",+ Message: "Enter value",+ DefaultPrompt: "default",+ HasBrowserHandler: true,+ }+ if state.Type != "prompt" {+ t.Errorf("expected type 'prompt', got %q", state.Type)+ }+ if state.Message != "Enter value" {+ t.Errorf("expected message 'Enter value', got %q", state.Message)+ }+ if state.DefaultPrompt != "default" {+ t.Errorf("expected defaultPrompt 'default', got %q", state.DefaultPrompt)+ }+ if !state.HasBrowserHandler {+ t.Error("expected HasBrowserHandler to be true")+ }+}++func TestHandlePendingDialog_NoPending(t *testing.T) {+ dm := NewDialogManager()+ // No real CDP context needed — should fail before reaching CDP+ _, err := HandlePendingDialog(context.TODO(), "tab1", dm, true, "")+ if err == nil {+ t.Fatal("expected error for no pending dialog")+ }+ if got := err.Error(); got != "no dialog open on tab tab1" {+ t.Errorf("unexpected error: %s", got)+ }+}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 754af0f2..be0cfabc 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -25,6 +25,7 @@ type TabManager struct {accessed map[string]boolsnapshots map[string]*RefCacheonTabSetup TabSetupFunc+ dialogMgr *DialogManagercurrentTab string // ID of the most recently used tabexecutor *TabExecutormu sync.RWMutex@@ -50,6 +51,11 @@ func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr}}+// SetDialogManager sets the dialog manager for dialog event tracking on new tabs.+func (tm *TabManager) SetDialogManager(dm *DialogManager) {+ tm.dialogMgr = dm+}+func (tm *TabManager) markAccessed(tabID string) {tm.mu.Lock()tm.accessed[tabID] = true@@ -287,6 +293,12 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CatabID := tm.idMgr.TabIDFromCDPTarget(rawCDPID)now := time.Now()+ // Set up dialog event listening for this tab+ if tm.dialogMgr != nil {+ autoAccept := tm.config != nil && tm.config.DialogAutoAccept+ ListenDialogEvents(ctx, tabID, tm.dialogMgr, autoAccept)+ }+tm.mu.Lock()tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel, CDPID: rawCDPID, CreatedAt: now, LastUsed: now}tm.accessed[tabID] = truediff --git a/internal/cli/actions/actions_dialog.go b/internal/cli/actions/actions_dialog.gonew file mode 100644index 00000000..aaec7364--- /dev/null+++ b/internal/cli/actions/actions_dialog.go@@ -0,0 +1,21 @@+package actions++import (+ "fmt"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+)++// Dialog handles a JavaScript dialog (accept or dismiss).+func Dialog(client *http.Client, base, token string, action string, text string, tabID string) {+ body := map[string]any{"action": action}+ if text != "" {+ body["text"] = text+ }+ path := "/dialog"+ if tabID != "" {+ path = fmt.Sprintf("/tabs/%s/dialog", tabID)+ }+ apiclient.DoPost(client, base, token, path, body)+}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex d71b1bca..3c76d47a 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -270,6 +270,9 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.InstanceDefaults.TabEvictionPolicy != "" {cfg.TabEvictionPolicy = fc.InstanceDefaults.TabEvictionPolicy}+ if fc.InstanceDefaults.DialogAutoAccept != nil {+ cfg.DialogAutoAccept = *fc.InstanceDefaults.DialogAutoAccept+ }// Profilesif fc.Profiles.BaseDir != "" {diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 97deea3f..77d04304 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -64,6 +64,9 @@ type RuntimeConfig struct {// IDPI (Indirect Prompt Injection defense) settingsIDPI IDPIConfig+ // Dialog settings+ DialogAutoAccept bool+// Engine mode: "chrome" (default), "lite", or "auto"Engine string@@ -154,6 +157,7 @@ type InstanceDefaultsConfig struct {NoAnimations *bool `json:"noAnimations,omitempty"`StealthLevel string `json:"stealthLevel,omitempty"`TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`+ DialogAutoAccept *bool `json:"dialogAutoAccept,omitempty"`}type ProfilesConfig struct {diff --git a/internal/handlers/dialog.go b/internal/handlers/dialog.gonew file mode 100644index 00000000..e9ed4cc2--- /dev/null+++ b/internal/handlers/dialog.go@@ -0,0 +1,109 @@+package handlers++import (+ "bytes"+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "net/http"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/web"+)++// HandleDialog handles the current JavaScript dialog (accept/dismiss).+//+// @Endpoint POST /dialog+func (h *Handlers) HandleDialog(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ Action string `json:"action"` // "accept" or "dismiss"+ Text string `json:"text"` // optional prompt text+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }+ if req.Action == "" {+ web.Error(w, 400, fmt.Errorf("action required (accept or dismiss)"))+ return+ }+ if req.Action != "accept" && req.Action != "dismiss" {+ web.Error(w, 400, fmt.Errorf("action must be 'accept' or 'dismiss'"))+ return+ }++ ctx, resolvedID, err := h.Bridge.TabContext(req.TabID)+ if err != nil {+ web.Error(w, 404, err)+ return+ }++ accept := req.Action == "accept"+ h.handleDialogAction(w, r, ctx, resolvedID, accept, req.Text)+}++// HandleTabDialog handles the current JavaScript dialog for a specific tab.+//+// @Endpoint POST /tabs/{id}/dialog+func (h *Handlers) HandleTabDialog(w http.ResponseWriter, r *http.Request) {+ tabID := r.PathValue("id")+ if tabID == "" {+ web.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ body := map[string]any{}+ dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize))+ if err := dec.Decode(&body); err != nil && !errors.Is(err, io.EOF) {+ web.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ if rawTabID, ok := body["tabId"]; ok {+ if provided, ok := rawTabID.(string); !ok || provided == "" {+ web.Error(w, 400, fmt.Errorf("invalid tabId"))+ return+ } else if provided != tabID {+ web.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))+ return+ }+ }++ body["tabId"] = tabID++ payload, err := json.Marshal(body)+ if err != nil {+ web.Error(w, 500, fmt.Errorf("encode: %w", err))+ return+ }++ req := r.Clone(r.Context())+ req.Body = io.NopCloser(bytes.NewReader(payload))+ req.ContentLength = int64(len(payload))+ req.Header = r.Header.Clone()+ req.Header.Set("Content-Type", "application/json")+ h.HandleDialog(w, req)+}++func (h *Handlers) handleDialogAction(w http.ResponseWriter, r *http.Request, ctx context.Context, tabID string, accept bool, promptText string) {+ dm := h.Bridge.GetDialogManager()+ if dm == nil {+ web.Error(w, 500, fmt.Errorf("dialog manager not available"))+ return+ }++ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)+ defer tCancel()+ go web.CancelOnClientDone(r.Context(), tCancel)++ result, err := bridge.HandlePendingDialog(tCtx, tabID, dm, accept, promptText)+ if err != nil {+ web.Error(w, 400, err)+ return+ }++ web.JSON(w, 200, result)+}diff --git a/internal/handlers/dialog_test.go b/internal/handlers/dialog_test.gonew file mode 100644index 00000000..ef4b6fa6--- /dev/null+++ b/internal/handlers/dialog_test.go@@ -0,0 +1,148 @@+package handlers++import (+ "bytes"+ "encoding/json"+ "net/http/httptest"+ "testing"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func TestHandleDialog_InvalidJSON(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`not json`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleDialog_MissingAction(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleDialog_InvalidAction(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"invalid"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleDialog_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}++func TestHandleDialog_NoPendingDialog(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ // Should return 400 because no dialog is pending+ if w.Code != 400 {+ t.Errorf("expected 400 for no pending dialog, got %d: %s", w.Code, w.Body.String())+ }+}++func TestHandleDialog_AcceptAction(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ // With no pending dialog, should get 400+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if _, ok := resp["error"]; !ok {+ t.Error("expected error in response")+ }+}++func TestHandleDialog_DismissAction(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"dismiss"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabDialog_MissingTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs//dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))+ w := httptest.NewRecorder()+ h.HandleTabDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabDialog_TabIDMismatch(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/dialog", bytes.NewReader([]byte(`{"tabId":"tab_other","action":"accept"}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabDialog(w, req)+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestHandleTabDialog_NoTab(t *testing.T) {+ h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/tabs/tab_abc/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))+ req.SetPathValue("id", "tab_abc")+ w := httptest.NewRecorder()+ h.HandleTabDialog(w, req)+ if w.Code != 404 {+ t.Errorf("expected 404, got %d", w.Code)+ }+}++func TestHandleDialog_AcceptWithText(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{ActionTimeout: 5e9}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept","text":"hello"}`)))+ w := httptest.NewRecorder()+ h.HandleDialog(w, req)+ // No pending dialog, so 400+ if w.Code != 400 {+ t.Errorf("expected 400, got %d", w.Code)+ }+}++func TestDialogManagerFromMockBridge(t *testing.T) {+ mb := &mockBridge{}+ dm := mb.GetDialogManager()+ if dm == nil {+ t.Fatal("expected non-nil DialogManager from mockBridge")+ }++ // Verify it works+ dm.SetPending("tab1", &bridge.DialogState{Type: "alert", Message: "test"})+ got := dm.GetPending("tab1")+ if got == nil || got.Type != "alert" {+ t.Errorf("expected alert dialog, got %+v", got)+ }+}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex fffed8e2..025a4b97 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -153,6 +153,8 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("GET /tabs/{id}/network", h.HandleTabNetwork)mux.HandleFunc("GET /tabs/{id}/network/stream", h.HandleTabNetworkStream)mux.HandleFunc("GET /tabs/{id}/network/{requestId}", h.HandleTabNetworkByID)+ mux.HandleFunc("POST /dialog", h.HandleDialog)+ mux.HandleFunc("POST /tabs/{id}/dialog", h.HandleTabDialog)mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/html; charset=utf-8")_, _ = w.Write([]byte(assets.WelcomeHTML))diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 9c626b34..c5fc8858 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -91,6 +91,10 @@ func (m *mockBridge) NetworkMonitor() *bridge.NetworkMonitor {return nil}+func (m *mockBridge) GetDialogManager() *bridge.DialogManager {+ return bridge.NewDialogManager()+}+func (m *mockBridge) Execute(ctx context.Context, tabID string, task func(ctx context.Context) error) error {return task(ctx)}diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 71e0afd1..0970a41b 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -358,6 +358,10 @@ func (m *MockBridge) NetworkMonitor() *bridge.NetworkMonitor {return nil}+func (m *MockBridge) GetDialogManager() *bridge.DialogManager {+ return bridge.NewDialogManager()+}+func (m *MockBridge) Execute(ctx context.Context, tabID string, task func(ctx context.Context) error) error {return task(ctx)}diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.goindex ae0fd34e..e84b6495 100644--- a/internal/mcp/handlers.go+++ b/internal/mcp/handlers.go@@ -54,6 +54,9 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)"pinchtab_network": handleNetwork(c),"pinchtab_network_detail": handleNetworkDetail(c),"pinchtab_network_clear": handleNetworkClear(c),++ // Dialog+ "pinchtab_dialog": handleDialog(c),}}@@ -591,3 +594,29 @@ func handleNetworkClear(c *Client) func(context.Context, mcp.CallToolRequest) (*return resultFromBytes(body, code)}}++// ── Dialog handlers ────────────────────────────────────────────────────++func handleDialog(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ action, err := r.RequireString("action")+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ if action != "accept" && action != "dismiss" {+ return mcp.NewToolResultError("action must be 'accept' or 'dismiss'"), nil+ }+ payload := map[string]any{"action": action}+ if text := optString(r, "text"); text != "" {+ payload["text"] = text+ }+ if tabID := optString(r, "tabId"); tabID != "" {+ payload["tabId"] = tabID+ }+ body, code, err := c.Post(ctx, "/dialog", payload)+ if err != nil {+ return mcp.NewToolResultError(err.Error()), nil+ }+ return resultFromBytes(body, code)+ }+}diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.goindex d3caae81..9dc1db1e 100644--- a/internal/mcp/server_test.go+++ b/internal/mcp/server_test.go@@ -18,8 +18,8 @@ func TestNewServerRegistersAllTools(t *testing.T) {// The server should have registered all tools.// We verify by checking that NewServer doesn't panic — the panic// in NewServer fires if any tool lacks a handler.- if len(tools) != 25 {- t.Errorf("expected 25 tools, got %d", len(tools))+ if len(tools) != 26 {+ t.Errorf("expected 26 tools, got %d", len(tools))}}diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex 2083e832..ce9bbf00 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -156,5 +156,13 @@ func allTools() []mcp.Tool {mcp.WithDescription("Clear captured network data for a tab or all tabs"),mcp.WithString("tabId", mcp.Description("Target tab ID (optional, clears all if empty)")),),++ // ── Dialog ──────────────────────────────────────────────────+ mcp.NewTool("pinchtab_dialog",+ mcp.WithDescription("Handle a JavaScript dialog (alert, confirm, prompt). Accept or dismiss the currently open dialog."),+ mcp.WithString("action", mcp.Required(), mcp.Description("Action to take: 'accept' or 'dismiss'")),+ mcp.WithString("text", mcp.Description("Text to enter for prompt dialogs (only used with accept)")),+ mcp.WithString("tabId", mcp.Description("Target tab ID")),+ ),}}