High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: harden bridge lifecycle edge cases
Luigi Agosti7a311f8ea1a1
diff --git a/docs/commands.md b/docs/commands.mdindex 4cc9f36d..2b7b79a5 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -78,6 +78,7 @@ pinchtab frame # Show current frame scopepinchtab frame "#payment-frame" # Scope selectors to an iframepinchtab frame main # Return selector scope to the top documentpinchtab click [selector] # Click an element or coordinates with --x/--y+pinchtab click <selector> --submit # One terminal submit click; reports bounded post-submit statepinchtab click --css <selector> # Force CSS selector modepinchtab click --wait-nav <selector> # Click and wait for navigationpinchtab click --snap <selector> # Click and output interactive snapshot@@ -142,6 +143,28 @@ Selector-based actions now fail fast when a selector does not match. If the UIis still loading, use `pinchtab wait` first instead of relying on actiontimeouts.+For a form button whose action must never be retried, use `pinchtab click+<selector> --submit`. This performs exactly one DOM click and reports a short+post-submit observation instead of retrying delivery. It cannot be combined+with `--wait-nav`, `--mode`, or `--humanize`; use a normal click for those+workflows. `pinchtab fill <selector> <text> --submit` remains the separate+Enter-after-fill shortcut.++## Standalone Bridges++Standalone `pinchtab bridge` processes register themselves in the local state+directory while running. Inspect them without sending signals:++```bash+pinchtab bridges list+pinchtab bridges list --json+pinchtab bridges list --prune # Remove only records whose original PID is dead or reused+```++`--prune` never kills a process. It removes only conclusively stale registry+records; an unreachable listener with a live or unknown PID remains visible for+operator investigation.+## Keyboard, Wait, And Diagnostics```bashdiff --git a/docs/reference/click.md b/docs/reference/click.mdindex 99210951..f29d9e24 100644--- a/docs/reference/click.md+++ b/docs/reference/click.md@@ -25,6 +25,7 @@ OK| `--dialog-text` | Prompt response text (with `--dialog-action accept`) || `--x`, `--y` | Click at specific coordinates || `--humanize` | Use humanized bezier+jitter input path (overrides instance config) |+| `--submit` | Use the once-only submit-click path and include bounded post-submit state in the response || `--mode dom\|dispatch` | Broad low-level escape hatch for click delivery. Omit `--mode` for the normal click path, use `dom` for `element.click()`, or `dispatch` for synthetic click events on the target || `--json` | Full JSON response || `--tab` | Target specific tab |@@ -38,6 +39,7 @@ pinchtab click "text:Submit" # Click by textpinchtab click e5 --snap # Click and show new snapshotpinchtab click e5 --wait-nav # Click and wait for navigationpinchtab click e5 --dialog-action accept # Auto-accept alert/confirm+pinchtab click "#sign-in" --submit # Submit once and report the observed outcomepinchtab click e5 --mode dom # Activate target directly despite occlusionpinchtab click e5 --mode dispatch # Dispatch click events on target despite occlusionpinchtab click --x 100 --y 200 # Click at coordinates@@ -55,6 +57,7 @@ pinchtab click --x 100 --y 200 # Click at coordinates- Treat `mode` as a broad, low-level escape hatch for click delivery. Occlusion bypass is the common case, but it can also help with pages that need a non-default click path.- `mode` and `humanize:true` are mutually exclusive.- To opt a click into the slower humanized path for a page that needs it, pass `humanize:true` in the action JSON or set `instanceDefaults.humanize:true`.+- `submit:true` is for terminal form actions where retrying could submit twice. For clicks it sends exactly one DOM click, disables recovery/retry delivery, and reports a bounded `postState` result (`succeeded` when the URL changes or an open modal closes; otherwise `pending`). It requires an element target and cannot be combined with coordinates, `waitNav`, `mode`, or `humanize:true`. It is accepted only on a single `/action` request, not a batch or macro.## Related Pagesdiff --git a/internal/bridge/attach_indicator_test.go b/internal/bridge/attach_indicator_test.goindex 6d35add3..66e3766f 100644--- a/internal/bridge/attach_indicator_test.go+++ b/internal/bridge/attach_indicator_test.go@@ -51,7 +51,7 @@ func TestAttachIndicatorNamesPortPersistsAndClears(t *testing.T) {b := New(context.Background(), ctx, cfg)b.stealthLaunchMode = stealth.LaunchModeAttachedexecCtx := cdp.WithExecutor(ctx, chromedp.FromContext(ctx).Target)- b.TabManager.RegisterTab("tab-indicator", execCtx)+ b.RegisterTab("tab-indicator", execCtx)if err := b.tabSetup(execCtx, "tab-indicator"); err != nil {t.Fatal(err)}@@ -82,7 +82,7 @@ func TestAttachIndicatorNamesPortPersistsAndClears(t *testing.T) {b2 := New(context.Background(), ctx, &config.RuntimeConfig{Port: "9877"})b2.stealthLaunchMode = stealth.LaunchModeAttached- b2.TabManager.RegisterTab("tab-indicator", execCtx)+ b2.RegisterTab("tab-indicator", execCtx)if err := b2.tabSetup(execCtx, "tab-indicator"); err != nil {t.Fatal(err)}diff --git a/internal/bridge/debugger_guard_test.go b/internal/bridge/debugger_guard_test.goindex b7b403e9..8ee8b952 100644--- a/internal/bridge/debugger_guard_test.go+++ b/internal/bridge/debugger_guard_test.go@@ -47,10 +47,10 @@ func TestWireTabManagerReappliesDebuggerGuardAfterReconnect(t *testing.T) {for _, tabID := range []string{"attached-tab", "reconnected-tab"} {b.TabManager = nilb.wireTabManager(context.Background())- if b.TabManager.onTabSetup == nil {+ if b.onTabSetup == nil {t.Fatalf("wireTabManager(%q) omitted target setup", tabID)}- if err := b.TabManager.onTabSetup(ctx, tabID); err != nil {+ if err := b.onTabSetup(ctx, tabID); err != nil {t.Fatalf("wired tab setup(%q): %v", tabID, err)}}@@ -145,7 +145,7 @@ func TestTabSetupFailsClosedWhenPausedTargetCannotResume(t *testing.T) {func TestManagedTargetSetupPropagatesDebuggerGuardFailure(t *testing.T) {want := errors.New("guard unavailable")- tm := NewTabManager(nil, nil, nil, nil, func(context.Context, string) error { return want })+ tm := NewTabManager(context.Background(), nil, nil, nil, func(context.Context, string) error { return want })if _, err := tm.setupManagedTarget(context.Background(), "tab", "target"); !errors.Is(err, want) {t.Fatalf("setupManagedTarget error = %v, want %v", err, want)diff --git a/internal/bridge/tab_manager_background_test.go b/internal/bridge/tab_manager_background_test.goindex 715ef270..c5151bd8 100644--- a/internal/bridge/tab_manager_background_test.go+++ b/internal/bridge/tab_manager_background_test.go@@ -25,7 +25,7 @@ func TestCreateTabRequestsRenderedTargetWithoutWindowFocus(t *testing.T) {if err != nil {return}- defer conn.Close()+ defer func() { _ = conn.Close() }()for {payload, op, err := wsutil.ReadClientData(conn)diff --git a/internal/bridgeregistry/registry.go b/internal/bridgeregistry/registry.goindex 4cdd4d68..16bde3ca 100644--- a/internal/bridgeregistry/registry.go+++ b/internal/bridgeregistry/registry.go@@ -341,9 +341,10 @@ func processStart(pid int) (int64, error) {func listenerReachable(address, port string) bool {host := strings.Trim(strings.TrimSpace(address), "[]")- if host == "" || host == "0.0.0.0" {+ switch host {+ case "", "0.0.0.0":host = "127.0.0.1"- } else if host == "::" {+ case "::":host = "::1"}conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), 250*time.Millisecond)diff --git a/internal/handlers/action_selector_modal_test.go b/internal/handlers/action_selector_modal_test.goindex 27ad74d9..897bc24d 100644--- a/internal/handlers/action_selector_modal_test.go+++ b/internal/handlers/action_selector_modal_test.go@@ -53,7 +53,7 @@ func TestActionSelectorResolutionDefaultsToTopmostDialog(t *testing.T) {cfg := &config.RuntimeConfig{ActionTimeout: 5 * time.Second, DefaultBrowser: config.BrowserChrome, StateDir: t.TempDir()}b := bridge.New(context.Background(), ctx, cfg)- b.TabManager.RegisterTab("tab-modal", ctx)+ b.RegisterTab("tab-modal", ctx)h := New(b, cfg, nil, nil, nil)req := bridge.ActionRequest{Selector: "text:Content contains"}diff --git a/internal/handlers/interstitial_dismiss_test.go b/internal/handlers/interstitial_dismiss_test.goindex cec8b8d8..f087e398 100644--- a/internal/handlers/interstitial_dismiss_test.go+++ b/internal/handlers/interstitial_dismiss_test.go@@ -25,13 +25,13 @@ func TestKnownInterstitialDismissalIsCatalogAndModalScoped(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {switch r.URL.Query().Get("case") {case "known":- fmt.Fprint(w, `<div id="payg" role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay-as-you-go billing<button id="dismiss" onclick="window.dismissals++;this.parentElement.remove()">Not now</button></div>`)+ _, _ = fmt.Fprint(w, `<div id="payg" role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay-as-you-go billing<button id="dismiss" onclick="window.dismissals++;this.parentElement.remove()">Not now</button></div>`)case "missing-control":- fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay as you go billing<button onclick="window.dismissals++">Continue</button></div>`)+ _, _ = fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Pay as you go billing<button onclick="window.dismissals++">Continue</button></div>`)default:- fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Ordinary wizard<button onclick="window.dismissals++">Continue</button></div><button id="outside" onclick="window.dismissals++">Not now</button>`)+ _, _ = fmt.Fprint(w, `<div role="dialog" aria-modal="true" style="position:fixed;inset:10px;background:white">Ordinary wizard<button onclick="window.dismissals++">Continue</button></div><button id="outside" onclick="window.dismissals++">Not now</button>`)}- fmt.Fprint(w, `<script>window.dismissals=0</script>`)+ _, _ = fmt.Fprint(w, `<script>window.dismissals=0</script>`)}))defer server.Close()serverURL, err := url.Parse(server.URL)@@ -61,7 +61,7 @@ func TestKnownInterstitialDismissalIsCatalogAndModalScoped(t *testing.T) {cfg := &config.RuntimeConfig{ActionTimeout: 5 * time.Second, DefaultBrowser: config.BrowserChrome, StateDir: t.TempDir()}b := bridge.New(context.Background(), ctx, cfg)- b.TabManager.RegisterTab("tab-interstitial", ctx)+ b.RegisterTab("tab-interstitial", ctx)h := New(b, cfg, nil, nil, nil)pageURL := func(testCase string) string {return "http://purview.microsoft.com:" + serverURL.Port() + "/?case=" + testCasediff --git a/internal/handlers/tab_policy_test.go b/internal/handlers/tab_policy_test.goindex be95f5ee..3c85bc53 100644--- a/internal/handlers/tab_policy_test.go+++ b/internal/handlers/tab_policy_test.go@@ -158,7 +158,7 @@ func TestHandleBackIgnoresCachedTabPolicyBlock(t *testing.T) {func TestExplicitTabWaitReturnsRetryableBusyWithoutLosingTab(t *testing.T) {b := &busyPolicyBridge{currentURLErr: context.DeadlineExceeded}- b.mockBridge.evaluateFn = func(_ string, result any) error {+ b.evaluateFn = func(_ string, result any) error {*(result.(*bool)) = truereturn nil}diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.goindex 2548359d..82022c2c 100644--- a/internal/orchestrator/health_test.go+++ b/internal/orchestrator/health_test.go@@ -544,3 +544,101 @@ func TestMonitor_DelaysRunningUntilWarmTabSucceeds(t *testing.T) {cmd.waitCh <- nil<-done}++// TestMonitor_ChildExitAfterRunningTransitionsToStopped covers the other half+// of monitor()'s lifecycle: once an instance has genuinely become healthy,+// the test-controlled child bridge exiting on its own (e.g. the external+// browser disconnected) must drive the instance to "stopped", not leave it+// stuck at "running" or misreport it as "error".+func TestMonitor_ChildExitAfterRunningTransitionsToStopped(t *testing.T) {+ old := processAliveFunc+ processAliveFunc = func(pid int) bool { return pid > 0 }+ defer func() { processAliveFunc = old }()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/health":+ w.WriteHeader(http.StatusOK)+ case "/tab":+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"tabId":"tab-1","url":"about:blank","title":""}`))+ case "/close":+ w.WriteHeader(http.StatusOK)+ _, _ = w.Write([]byte(`{"closed":true,"tabId":"tab-1"}`))+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }+ }))+ defer srv.Close()++ parsed, err := url.Parse(srv.URL)+ if err != nil {+ t.Fatalf("Parse(%q) error = %v", srv.URL, err)+ }+ host, portStr, ok := strings.Cut(parsed.Host, ":")+ if !ok {+ t.Fatalf("expected host:port in %q", parsed.Host)+ }+ port, err := strconv.Atoi(portStr)+ if err != nil {+ t.Fatalf("Atoi(%q) error = %v", portStr, err)+ }++ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Bind: host})+ o.client = srv.Client()++ cmd := &blockingWaitCmd{pid: 4321, waitCh: make(chan error, 1)}+ inst := &InstanceInternal{+ Instance: bridge.Instance{+ ID: "inst_1",+ Port: strconv.Itoa(port),+ Status: "starting",+ StartTime: time.Now(),+ ProfileName: "profile1",+ },+ cmd: cmd,+ }++ done := make(chan struct{})+ go func() {+ o.monitor(inst)+ close(done)+ }()++ deadline := time.Now().Add(4 * time.Second)+ for time.Now().Before(deadline) {+ o.mu.RLock()+ status := inst.Status+ o.mu.RUnlock()+ if status == "running" {+ break+ }+ time.Sleep(50 * time.Millisecond)+ }+ o.mu.RLock()+ status := inst.Status+ o.mu.RUnlock()+ if status != "running" {+ cmd.waitCh <- nil+ <-done+ t.Fatalf("status before child exit = %q, want running", status)+ }++ // Simulate the test-controlled child bridge exiting on its own now that+ // the instance is confirmed healthy.+ cmd.waitCh <- nil++ select {+ case <-done:+ case <-time.After(4 * time.Second):+ t.Fatal("monitor did not return after child exit")+ }++ o.mu.RLock()+ status = inst.Status+ o.mu.RUnlock()+ if status != "stopped" {+ t.Fatalf("status after child exit = %q, want stopped", status)+ }+}diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex d3dbc9ff..ef5146b3 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -420,7 +420,7 @@ func closedTabID(req *http.Request, resp *http.Response) string {return ""}path := strings.TrimSpace(req.URL.Path)- if path != "/close" && !(strings.HasPrefix(path, "/tabs/") && strings.HasSuffix(path, "/close")) {+ if path != "/close" && (!strings.HasPrefix(path, "/tabs/") || !strings.HasSuffix(path, "/close")) {return ""}if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {diff --git a/tests/e2e/scenarios/api/actions-extended.sh b/tests/e2e/scenarios/api/actions-extended.shindex c1f6ada8..16e19621 100644--- a/tests/e2e/scenarios/api/actions-extended.sh+++ b/tests/e2e/scenarios/api/actions-extended.sh@@ -64,6 +64,29 @@ assert_ok "hover on button"end_test+# ─────────────────────────────────────────────────────────────────+start_test "HTTP: click submit dispatches once and reports terminal post-state"++# The submit contract is deliberately distinct from a normal click: it must+# dispatch only once, avoid retry/recovery, and return the observed outcome.+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/js-submit.html\"}"+assert_ok "navigate submit fixture"++pt_post /action -d '{"kind":"fill","selector":"#username","text":"admin"}'+assert_ok "fill username"+pt_post /action -d '{"kind":"fill","selector":"#password","text":"secret"}'+assert_ok "fill password"+pt_post /action -d '{"kind":"click","selector":"#submit-btn","submit":true}'+assert_ok "submit click"+assert_result_jq '.postState.status == "pending" and .postState.signal == "no_terminal_change"' \+ "inline submit reports pending post-state" "inline submit did not report the expected pending post-state"++pt_post /evaluate -d '{"expression":"document.getElementById(\"result-success\")?.textContent"}'+assert_ok "read submit outcome"+assert_json_eq "$RESULT" '.result' 'LOGIN_SUCCESS' "submit handler ran once"++end_test+# ─────────────────────────────────────────────────────────────────start_test "pinchtab low-level mouse actions"