High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: clicking an ordinary link exits 1 with 409 after the navigation succeeded (PIN-266)
Luigi Agosti4d623f2bd06e
diff --git a/docs/reference/click.md b/docs/reference/click.mdindex f29d9e24..483e8c78 100644--- a/docs/reference/click.md+++ b/docs/reference/click.md@@ -12,6 +12,52 @@ pinchtab click e5OK```+## When the click navigates++A click that moves the page **succeeds**. There is nothing to declare in advance and+nothing to opt into: the result reports where the tab landed and that your refs are+gone.++```bash+pinchtab nav https://example.com --snap+# e1:link "Learn more"+pinchtab click e1+# OK navigated https://www.iana.org/help/example-domains+# HINT: every ref from your last snapshot is dead — run `pinchtab snap -i` before the next action+echo $? # 0+```++With `--json`, the same click carries the outcome in `result`:++```json+{+ "success": true,+ "result": {+ "clicked": true,+ "navigated": true,+ "url": "https://www.iana.org/help/example-domains",+ "previousUrl": "https://example.com/",+ "refsStale": true+ }+}+```++`navigated` is keyed on what actually happened — the URL before the action compared+against the URL after — not on the element's role or tag, so it is the same answer for+a link, a router `<button>`, and a form control that redirects. A fragment-only change+(`#section`) is not a navigation: the document is the same and your refs still resolve.++**`refsStale: true` means every ref from your previous `/snapshot` is dead.** Refs are+minted per snapshot, so take a new one before the next ref-targeted action:++```bash+pinchtab click e1 --snap # click, then print the new snapshot in one call+```++`--wait-nav` is not permission to navigate — it makes the click *wait* for the+navigation to settle before returning, which is what you want when the next action+depends on the new page having loaded.+## CLI Flags| Flag | Description |@@ -47,7 +93,7 @@ pinchtab click --x 100 --y 200 # Click at coordinates## Notes-- Element refs come from `/snapshot`+- Element refs come from `/snapshot`, and a navigation invalidates all of them — see [When the click navigates](#when-the-click-navigates)- Refs for iframe descendants can be clicked directly without frame switch- Selector lookup is limited to current frame scope (default: `main`)- Use [`/frame`](./frame.md) before selector-based iframe actionsdiff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.goindex 48111032..9138b7ef 100644--- a/internal/bridge/action_request.go+++ b/internal/bridge/action_request.go@@ -343,17 +343,39 @@ func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionReque}if checkNav && beforeURL != "" {- afterURL, uErr := urlReader(ctx)- if uErr == nil {- if navErr := checkUnexpectedNavigation(beforeURL, afterURL); navErr != nil {- return nil, navErr- }+ if afterURL, uErr := urlReader(ctx); uErr == nil && navigationChanged(beforeURL, afterURL) {+ res = withNavigationOutcome(res, beforeURL, afterURL)}}return res, nil}+// Navigated, LandedURL, PreviousURL and RefsStale are the keys a result grows+// when the action moved the page. They ride on the SUCCESSFUL result — the+// action ran, so the caller gets what it earned plus what it now needs to know:+// where it landed, and that every ref from its last snapshot is dead, because+// refs are minted per snapshot.+const (+ ResultNavigated = "navigated"+ ResultLandedURL = "url"+ ResultPreviousURL = "previousUrl"+ ResultRefsStale = "refsStale"+)++// withNavigationOutcome never drops the action's own result: it is the value the+// API used to discard, and delivering it is the whole point.+func withNavigationOutcome(res map[string]any, before, after string) map[string]any {+ if res == nil {+ res = map[string]any{}+ }+ res[ResultNavigated] = true+ res[ResultLandedURL] = after+ res[ResultPreviousURL] = before+ res[ResultRefsStale] = true+ return res+}+func (b *Bridge) AvailableActions() []string {keys := make([]string, 0, len(b.Actions))for k := range b.Actions {diff --git a/internal/bridge/guards.go b/internal/bridge/guards.goindex 861fa6af..bf38cf4d 100644--- a/internal/bridge/guards.go+++ b/internal/bridge/guards.go@@ -11,9 +11,6 @@ import ()var (- // ErrUnexpectedNavigation indicates an action was expected to keep context stable- // but the page URL changed.- ErrUnexpectedNavigation = errors.New("unexpected page navigation")// ErrElementStale indicates the targeted DOM/backend node is no longer valid.ErrElementStale = errors.New("element reference is stale")ErrInvalidActionRequest = errors.New("invalid action request")@@ -54,22 +51,35 @@ func classifyActionError(err error) error {return err}+// shouldCheckUnexpectedNavigation selects the actions whose landing URL is worth+// measuring. waitNav is not an assertion the caller made about navigation — it+// asks the action to WAIT for one — so a caller that waits already learns the+// landed URL from the wait itself and needs no second report here.func shouldCheckUnexpectedNavigation(req ActionRequest) bool {return !req.WaitNav && !IsSubmitClick(req.Kind, req)}-func checkUnexpectedNavigation(before, after string) error {+// navigationChanged reports whether an action moved the page. It used to return+// an error, and ExecuteAction returned that error INSTEAD of the successful+// result the action had already produced — so clicking an ordinary link failed+// after the click had worked. A navigation is an outcome to report, not a+// failure: the caller is told where it landed and that its refs are dead, and+// the result it earned is delivered.+//+// A fragment-only or case-of-host change is not a navigation: the document is+// the same and the refs still resolve.+func navigationChanged(before, after string) bool {before = strings.TrimSpace(before)after = strings.TrimSpace(after)if before == "" || after == "" || before == after {- return nil+ return false}if normalizedBefore, ok := normalizeGuardURL(before); ok {if normalizedAfter, ok := normalizeGuardURL(after); ok && normalizedBefore == normalizedAfter {- return nil+ return false}}- return fmt.Errorf("%w: %s -> %s", ErrUnexpectedNavigation, before, after)+ return true}func normalizeGuardURL(raw string) (string, bool) {diff --git a/internal/bridge/guards_test.go b/internal/bridge/guards_test.goindex f47c121e..02bf0f2b 100644--- a/internal/bridge/guards_test.go+++ b/internal/bridge/guards_test.go@@ -23,22 +23,23 @@ func TestClassifyActionError_PreservesTyped(t *testing.T) {}}-func TestCheckUnexpectedNavigation(t *testing.T) {- err := checkUnexpectedNavigation("https://a.example", "https://b.example")- if !errors.Is(err, ErrUnexpectedNavigation) {- t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)- }-}--func TestCheckUnexpectedNavigation_NoChange(t *testing.T) {- if err := checkUnexpectedNavigation("https://a.example", "https://a.example"); err != nil {- t.Fatalf("expected nil error, got %v", err)- }-}--func TestCheckUnexpectedNavigation_EquivalentURLs(t *testing.T) {- if err := checkUnexpectedNavigation("https://A.EXAMPLE/path?x=1#section", "https://a.example/path?x=1"); err != nil {- t.Fatalf("expected nil error for equivalent URLs, got %v", err)+func TestNavigationChanged(t *testing.T) {+ for _, tc := range []struct {+ name string+ before, after string+ want bool+ }{+ {"a different page", "https://a.example", "https://b.example", true},+ {"the same page", "https://a.example", "https://a.example", false},+ {"fragment and host case only", "https://A.EXAMPLE/path?x=1#section", "https://a.example/path?x=1", false},+ {"unreadable before", "", "https://b.example", false},+ {"unreadable after", "https://a.example", "", false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if got := navigationChanged(tc.before, tc.after); got != tc.want {+ t.Errorf("navigationChanged(%q, %q) = %v, want %v", tc.before, tc.after, got, tc.want)+ }+ })}}@@ -100,9 +101,34 @@ func TestExecuteAction_UnexpectedNavigation_WhenEnabled(t *testing.T) {},}- _, err := b.ExecuteAction(context.Background(), ActionClick, ActionRequest{})- if !errors.Is(err, ErrUnexpectedNavigation) {- t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)+ res, err := b.ExecuteAction(context.Background(), ActionClick, ActionRequest{})+ if err != nil {+ t.Fatalf("a click that ran and moved the page reported failure: %v", err)+ }+ assertNavigationOutcome(t, res, "https://a.example", "https://b.example")+}++// The whole defect in one assertion: the action's own result is what the API used+// to throw away when it returned the navigation as an error instead.+func assertNavigationOutcome(t *testing.T, res map[string]any, before, after string) {+ t.Helper()+ if res == nil {+ t.Fatal("no result delivered for an action that succeeded")+ }+ if res["ok"] != true {+ t.Errorf("the action's own result was discarded: %v", res)+ }+ if res[ResultNavigated] != true {+ t.Errorf("result does not report the navigation: %v", res)+ }+ if res[ResultLandedURL] != after {+ t.Errorf("landed url = %v, want %q", res[ResultLandedURL], after)+ }+ if res[ResultPreviousURL] != before {+ t.Errorf("previous url = %v, want %q", res[ResultPreviousURL], before)+ }+ if res[ResultRefsStale] != true {+ t.Errorf("result does not say the caller's refs are dead: %v", res)}}@@ -150,10 +176,11 @@ func TestExecuteAction_UnexpectedNavigation_WithNilConfigDefaultsEnabled(t *test},}- _, err := b.ExecuteAction(context.Background(), ActionType, ActionRequest{})- if !errors.Is(err, ErrUnexpectedNavigation) {- t.Fatalf("expected ErrUnexpectedNavigation, got %v", err)+ res, err := b.ExecuteAction(context.Background(), ActionType, ActionRequest{})+ if err != nil {+ t.Fatalf("an action that ran and moved the page reported failure: %v", err)}+ assertNavigationOutcome(t, res, "https://a.example", "https://b.example")}func TestExecuteAction_ClassifiesStaleError_WhenGuardsDisabled(t *testing.T) {diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex 63cc8733..4afd7f55 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -193,6 +193,15 @@ func printActionResult(kind string, result map[string]any) {return}if actionResult, ok := result["result"].(map[string]any); ok {+ // A click that moved the page succeeded. It used to exit 1 with a 409, which+ // is the signal every agent loop and CI harness branches on, so the natural+ // reaction — retry — re-clicked on the page the first click had reached.+ if actionResult["navigated"] == true {+ landed, _ := actionResult["url"].(string)+ output.Value("OK navigated " + landed)+ output.Hint("every ref from your last snapshot is dead — run `pinchtab snap -i` before the next action")+ return+ }if postState, ok := actionResult["postState"].(map[string]any); ok {status, _ := postState["status"].(string)signal, _ := postState["signal"].(string)diff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.goindex 440d8cb0..f2a265a8 100644--- a/internal/cli/actions/actions_element_test.go+++ b/internal/cli/actions/actions_element_test.go@@ -2,6 +2,7 @@ package actionsimport ("encoding/json"+ "strings""testing""github.com/spf13/cobra"@@ -972,3 +973,44 @@ func TestScrollPositionalWinsOverThePixelFlagsWithoutCobrasArgsHook(t *testing.T})}}++// The repro from the card: clicking an ordinary link. It used to print an error and+// exit 1 after the click had already worked; it now prints where the tab landed and+// exits 0. captureStdout would not see an exit, so the assertion is on the output —+// output.Error is the only path that exits, and reaching this branch means it did not.+func TestPrintActionResultANavigatingClickReportsWhereItLanded(t *testing.T) {+ navigated := map[string]any{+ "success": true,+ "result": map[string]any{+ "clicked": true,+ "navigated": true,+ "url": "https://www.iana.org/help/example-domains",+ "previousUrl": "https://example.com/",+ "refsStale": true,+ },+ }++ out := captureStdout(t, func() { printActionResult("click", navigated) })+ if !strings.Contains(out, "https://www.iana.org/help/example-domains") {+ t.Errorf("stdout = %q; the caller cannot see where the click landed", out)+ }++ hint := captureStderr(t, func() { printActionResult("click", navigated) })+ if !strings.Contains(hint, "snap") {+ t.Errorf("stderr = %q; nothing tells the caller its refs are dead", hint)+ }+}++// A click that did not move the page keeps the plain answer: the landed-URL line is+// the navigation report, not decoration on every click.+func TestPrintActionResultAClickThatDidNotNavigateStaysPlain(t *testing.T) {+ got := captureStdout(t, func() {+ printActionResult("click", map[string]any{+ "success": true,+ "result": map[string]any{"clicked": true},+ })+ })+ if strings.Contains(got, "navigated") {+ t.Errorf("output = %q; a click that moved nothing reported a navigation", got)+ }+}diff --git a/internal/cli/apiclient/apierror_test.go b/internal/cli/apiclient/apierror_test.goindex bdbc2530..1220fe4f 100644--- a/internal/cli/apiclient/apierror_test.go+++ b/internal/cli/apiclient/apierror_test.go@@ -88,22 +88,24 @@ func TestRenderAPIErrorKeepsApplicationErrors(t *testing.T) {}}-// The /action navigation guard reports a 409 whose details carry the way-// forward; the renderer is what puts it in front of the user.-func TestRenderAPIErrorBodyShowsNavigationChangedHintAndRemedy(t *testing.T) {- body := `{"code":"navigation_changed",` +- `"error":"unexpected page navigation: https://pinchtab.com/ -> https://pinchtab.com/docs/",` +- `"details":{"hint":"The action navigated the page; set waitNav true or submit true.",` +- `"remedy":"pinchtab click <ref> --wait-nav (use --submit instead when the click submits a form)",` +- `"url":"https://pinchtab.com/docs/"}}`-- out := renderAPIErrorBody(409, []byte(body))+// A refusal whose details carry the way forward; the renderer is what puts it in+// front of the user. The sample used to be navigation_changed, which the server no+// longer emits — a click that navigates succeeds — so it is an allowlist refusal,+// which is a code the server does still produce with the same details shape.+func TestRenderAPIErrorBodyShowsHintAndRemedy(t *testing.T) {+ body := `{"code":"idpi_domain_blocked",` ++ `"error":"navigation blocked by IDPI: domain \"evil.test\" is not in the allowed list",` ++ `"details":{"hint":"the requested URL is outside security.allowedDomains, so the request was refused.",` ++ `"remedy":"pinchtab config set security.allowedDomains \"...\" && pinchtab server restart",` ++ `"url":"https://evil.test/"}}`++ out := renderAPIErrorBody(403, []byte(body))for _, want := range []string{- "Error 409: unexpected page navigation",- "💡 The action navigated the page",- "Remedy: pinchtab click <ref> --wait-nav",- "--submit",+ "Error 403: navigation blocked by IDPI",+ "💡 the requested URL is outside security.allowedDomains",+ "Remedy: pinchtab config set security.allowedDomains",+ "server restart",} {if !strings.Contains(out, want) {t.Errorf("rendered error missing %q:\n%s", want, out)diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.goindex 1e6ff465..12f5bbfc 100644--- a/internal/handlers/action_execution.go+++ b/internal/handlers/action_execution.go@@ -263,20 +263,6 @@ func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.Actioif errors.Is(recErr, ErrStaleSubmitTarget) {return nil, "", nil, recErr}- // The action RAN: the click landed and moved the page, and the guard reports- // that navigation from inside the callback. Wrapping it as "ref not found and- // recovery failed" asserted two false things about a dispatch that happened,- // and the natural retry then repeats it. The navigation is passed through- // unwrapped so this answers what the same click answers with a fresh ref.- //- // The recovery record IS published here, unlike on the refusal above: it was- // built on the original page before the click, and it is the only disclosure- // of WHICH element received a click the caller aimed at a different ref.- // Suppressing it would leave the navigation reported with no way to learn the- // dispatch went somewhere else.- if errors.Is(recErr, bridge.ErrUnexpectedNavigation) {- return nil, "", &rr, recErr- }return nil, "", &rr, refNotFound(req.Ref)}return recRes, "", &rr, nil@@ -303,7 +289,7 @@ func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.Actio}var rr *recovery.RecoveryResult- if err != nil && !actionAlreadyDispatched(err) && !submitClick && req.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, req.Ref) {+ if err != nil && !submitClick && req.Ref != "" && h.Recovery != nil && h.Recovery.ShouldAttempt(err, req.Ref) {r2, recRes, recErr := h.Recovery.AttemptWithClassification(ctx, resolvedTabID, req.Ref, req.Kind,recovery.ClassifyFailure(err),@@ -324,14 +310,6 @@ func (h *Handlers) executeActionResilient(ctx context.Context, req *bridge.Actioreturn result, backend, rr, err}-// actionAlreadyDispatched names the one error the bridge raises only AFTER the action ran-// and succeeded, so healing it would re-match against the page the caller's own action-// navigated to and dispatch a second, unrequested action. The rest of recovery's navigation-// class — a detached frame, a crashed page — means the dispatch never landed and still heals.-func actionAlreadyDispatched(err error) bool {- return errors.Is(err, bridge.ErrUnexpectedNavigation)-}-func switchedTabFromActionResult(result map[string]any) string {if switched, ok := result["switchedToTab"].(string); ok {return strings.TrimSpace(switched)diff --git a/internal/handlers/action_navigation_success_test.go b/internal/handlers/action_navigation_success_test.gonew file mode 100644index 00000000..e7baad6f--- /dev/null+++ b/internal/handlers/action_navigation_success_test.go@@ -0,0 +1,137 @@+package handlers++import (+ "bytes"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config"+)++func navigatedActionResult() map[string]any {+ return map[string]any{+ "clicked": true,+ bridge.ResultNavigated: true,+ bridge.ResultLandedURL: "https://www.iana.org/help/example-domains",+ bridge.ResultPreviousURL: "https://example.com/",+ bridge.ResultRefsStale: true,+ }+}++// A click that succeeded in the browser must not appear in the failure telemetry.+// The assertion walks the WHOLE diagnostics envelope rather than naming today's two+// fields, so a failure counter added later inherits the rule instead of quietly+// counting successful clicks again.+func TestASuccessfulNavigatingClickIsInNoFailureField(t *testing.T) {+ ResetObservabilityForTests()++ mb := &mockBridge{availableActions: []string{bridge.ActionClick}, actionResult: navigatedActionResult()}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)+ handler := LoggingMiddleware(http.HandlerFunc(h.HandleAction))++ for i := 0; i < 2; i++ {+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click","ref":"e1","nodeId":42,"tabId":"tab1"}`)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("click %d returned %d: %s", i, w.Code, w.Body.String())+ }+ }++ for _, site := range nonZeroFailureFields(t, DiagnosticsSnapshot("bridge")) {+ t.Errorf("%s — two successful clicks were counted as failures", site)+ }+}++// The counter is real, so the sweep above is not passing on an envelope it cannot+// read: a genuine 4xx moves exactly the fields the successful clicks must not.+func TestTheFailureSweepStillSeesAGenuineFailure(t *testing.T) {+ ResetObservabilityForTests()++ mb := &mockBridge{availableActions: []string{bridge.ActionClick}, executeActionErr: refNotFound("e99")}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)+ handler := LoggingMiddleware(http.HandlerFunc(h.HandleAction))++ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click","ref":"e99","nodeId":42,"tabId":"tab1"}`)))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ handler.ServeHTTP(w, req)+ if w.Code < 400 {+ t.Fatalf("the fixture no longer produces a failure: %d %s", w.Code, w.Body.String())+ }++ if len(nonZeroFailureFields(t, DiagnosticsSnapshot("bridge"))) == 0 {+ t.Fatal("a genuine 4xx moved no failure field, so the sweep above proves nothing")+ }+}++// nonZeroFailureFields walks the envelope and names every failure-shaped field+// carrying anything. It is keyed on the field NAME rather than on a list, which is+// what makes a future failure counter inherit the rule.+func nonZeroFailureFields(t *testing.T, envelope map[string]any) []string {+ t.Helper()++ var found []string+ var walk func(path string, value any)+ walk = func(path string, value any) {+ switch typed := value.(type) {+ case map[string]any:+ for key, child := range typed {+ childPath := key+ if path != "" {+ childPath = path + "." + key+ }+ // A container named "failures" holds the fields; it is not one.+ if isContainer(child) {+ walk(childPath, child)+ continue+ }+ if strings.Contains(strings.ToLower(key), "fail") && !emptyMetric(child) {+ found = append(found, fmt.Sprintf("%s = %v", childPath, child))+ }+ }+ case []map[string]any:+ for i, child := range typed {+ walk(fmt.Sprintf("%s[%d]", path, i), child)+ }+ }+ }+ walk("", envelope)++ // The recent-failure log is the other half of the same claim and is not named+ // "fail", so it is checked by its own path rather than by the sweep.+ if failures, ok := envelope["failures"].(map[string]any); ok {+ if recent, ok := failures["recent"].([]map[string]any); ok && len(recent) > 0 {+ found = append(found, fmt.Sprintf("failures.recent has %d entries", len(recent)))+ }+ }+ return found+}++func isContainer(value any) bool {+ switch value.(type) {+ case map[string]any, []map[string]any, []any:+ return true+ }+ return false+}++func emptyMetric(value any) bool {+ switch typed := value.(type) {+ case uint64:+ return typed == 0+ case int:+ return typed == 0+ case float64:+ return typed == 0+ case nil:+ return true+ }+ return false+}diff --git a/internal/handlers/action_stale_submit_test.go b/internal/handlers/action_stale_submit_test.goindex 858d7eb3..878d5eba 100644--- a/internal/handlers/action_stale_submit_test.go+++ b/internal/handlers/action_stale_submit_test.go@@ -4,7 +4,6 @@ import ("context""encoding/json""errors"- "fmt""net/http""net/http/httptest""strings"@@ -198,27 +197,28 @@ func TestTheSubmitCheckIsWhatStopsTheOrder(t *testing.T) {}}-// The honesty half, and the half a reviewer found pinned by nothing: a stale ref whose-// recovered click NAVIGATES ran the action. Reporting it as "ref not found and recovery-// failed" asserts two false things about a dispatch that happened, and the only sane-// reaction to "not found" — retry — repeats it. This must answer the navigation itself.-func TestAStaleRefWhoseRecoveredClickNavigatesAnswersTheNavigationNotNotFound(t *testing.T) {+// A stale ref whose recovered click NAVIGATES ran the action, so it reports success:+// the click landed, the page moved, and the caller is told where it landed. The+// substitution is the one thing this must not hide — the dispatch went to whatever+// recovery matched, not to the ref the caller named.+func TestAStaleRefWhoseRecoveredClickNavigatesSucceedsAndDisclosesTheSubstitution(t *testing.T) {f := newOrderFixture(t)h, ctx, tabID := staleSubmitHandlers(t, f)- _, _, rr, err := h.executeActionResilient(ctx, &bridge.ActionRequest{Kind: bridge.ActionClick, Ref: "e3"}, h.Config, tabID, true)+ result, _, rr, err := h.executeActionResilient(ctx, &bridge.ActionRequest{Kind: bridge.ActionClick, Ref: "e3"}, h.Config, tabID, true)- if err == nil {- t.Fatalf("a recovered click that navigated reported success; the guard should surface the navigation")+ if err != nil {+ t.Fatalf("a recovered click that navigated reported failure: %v", err)}- if !errors.Is(err, bridge.ErrUnexpectedNavigation) {- t.Fatalf("error = %v, want the navigation guard's error", err)+ if result[bridge.ResultNavigated] != true {+ t.Errorf("result does not report the navigation: %v", result)}- if strings.Contains(err.Error(), "not found and recovery failed") {- t.Errorf("the navigation is reported as a lookup failure: %q — the ref WAS matched and the click DID land", err)+ if landed, _ := result[bridge.ResultLandedURL].(string); !strings.Contains(landed, "/terms") {+ t.Errorf("landed url = %v, want the link's own target", result[bridge.ResultLandedURL])+ }+ if result[bridge.ResultRefsStale] != true {+ t.Errorf("result does not say the caller's refs are dead: %v", result)}- // The click went to whatever recovery matched, not to the ref the caller named, so the- // record of that substitution is the one thing this response must not hide.if rr == nil {t.Fatal("no recovery record published for a dispatched click, so nothing says which element was clicked")}@@ -242,8 +242,8 @@ func TestTheRefusalPublishesNoRecoveryRecordWhileTheNavigationDoes(t *testing.T)}_, _, navigated, navErr := h.executeActionResilient(ctx, &bridge.ActionRequest{Kind: bridge.ActionClick, Ref: "e3"}, h.Config, tabID, true)- if !errors.Is(navErr, bridge.ErrUnexpectedNavigation) {- t.Fatalf("navigation error = %v", navErr)+ if navErr != nil {+ t.Fatalf("the navigating click reported failure: %v", navErr)}if navigated == nil {t.Error("the navigation published no recovery record, so a dispatched click discloses nothing about its target")@@ -302,9 +302,9 @@ func TestTheEndpointRefusesAStaleSubmitRefWithASnapshotRemedyAndNoOrder(t *testi}// The helper returns the record; this pins that it survives the endpoint and reaches the-// caller. Without it the 409 discloses the navigation and hides the substitution — and the+// caller. Without it the 200 reports the navigation and hides the substitution — and the// helper-level pair cannot see that, because the field is attached one layer out.-func TestTheNavigation409DisclosesWhichElementWasActuallyClicked(t *testing.T) {+func TestTheNavigationResponseDisclosesWhichElementWasActuallyClicked(t *testing.T) {f := newOrderFixture(t)h, _, tabID := staleSubmitHandlers(t, f)@@ -312,30 +312,28 @@ func TestTheNavigation409DisclosesWhichElementWasActuallyClicked(t *testing.T) {rec := httptest.NewRecorder()h.HandleAction(rec, httptest.NewRequest(http.MethodPost, "/action", strings.NewReader(body)))- if rec.Code != http.StatusConflict {- t.Fatalf("status = %d, want 409: %s", rec.Code, rec.Body.String())+ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200 for a click that ran and moved the page: %s", rec.Code, rec.Body.String())}var resp struct {- Code string `json:"code"`- Error string `json:"error"`- Details map[string]any `json:"details"`+ Success bool `json:"success"`+ Result map[string]any `json:"result"`+ Recovery map[string]any `json:"recovery"`}if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {t.Fatalf("decode navigation response: %v (%s)", err, rec.Body.String())}- if resp.Code != "navigation_changed" {- t.Errorf("code = %q, want navigation_changed", resp.Code)+ if !resp.Success {+ t.Errorf("success = false for a click that landed: %s", rec.Body.String())}- if strings.Contains(resp.Error, "not found and recovery failed") {- t.Errorf("the wire still reports the dispatch as a lookup failure: %q", resp.Error)+ if resp.Result[bridge.ResultNavigated] != true {+ t.Errorf("result does not report the navigation: %v", resp.Result)}-- published, ok := resp.Details["recovery"].(map[string]any)- if !ok {- t.Fatalf("details.recovery absent, so the 409 says the page moved without saying the click went to a different element than the caller named: %v", resp.Details)+ if resp.Recovery == nil {+ t.Fatalf("recovery absent, so the response says the page moved without saying the click went to a different element than the caller named: %s", rec.Body.String())}- if newRef, _ := published["new_ref"].(string); newRef == "" {- t.Errorf("details.recovery names no matched ref, so the substitution is still undisclosed: %v", published)+ if newRef, _ := resp.Recovery["new_ref"].(string); newRef == "" {+ t.Errorf("recovery names no matched ref, so the substitution is still undisclosed: %v", resp.Recovery)}}@@ -376,9 +374,10 @@ func TestTheStepPathTurnsTheRefusalIntoAFailedStepNamingTheSnapshot(t *testing.T// the navigation, and only the count says whether a second, unrequested click went out.type navigatingBridge struct {mockBridge- refCache *bridge.RefCache- actionErr error- dispatches int64+ refCache *bridge.RefCache+ actionErr error+ actionResult map[string]any+ dispatches int64}func (m *navigatingBridge) GetRefCache(string) *bridge.RefCache { return m.refCache }@@ -386,7 +385,7 @@ func (m *navigatingBridge) SetRefCache(string, *bridge.RefCache) {}func (m *navigatingBridge) ExecuteAction(context.Context, string, bridge.ActionRequest) (map[string]any, error) {atomic.AddInt64(&m.dispatches, 1)- return nil, m.actionErr+ return m.actionResult, m.actionErr}func navigatingHandlers(t *testing.T, actionErr error) (*navigatingBridge, *Handlers, string) {@@ -408,23 +407,35 @@ func navigatingHandlers(t *testing.T, actionErr error) (*navigatingBridge, *Handreturn mb, h, tabID}-// The card's defect: the ref resolved, the click landed, and the page moved — and recovery-// then re-matched that ref against the page the click had already navigated to and clicked-// whatever it found, driving the browser to a third page the caller never named.-func TestAnActionThatOnlyTrippedTheNavigationGuardIsNotDispatchedTwice(t *testing.T) {+// PIN-264 added a guard here that suppressed the post-execution heal when the error+// was the navigation sentinel. That sentinel no longer exists: a navigation is a+// SUCCESS now, so err is nil and the heal branch cannot run at all. The guard and its+// sentinel-shaped test were deleted together rather than left as a branch nothing can+// reach — but the property they protected is the reason this replacement exists: an+// action that ran and moved the page must dispatch exactly once.+func TestAnActionThatNavigatedIsNotDispatchedTwice(t *testing.T) {for _, kind := range []string{bridge.ActionClick, bridge.ActionHover} {t.Run(kind, func(t *testing.T) {- navErr := fmt.Errorf("%w: %s -> %s", bridge.ErrUnexpectedNavigation, "https://a.example/", "https://b.example/")- mb, h, tabID := navigatingHandlers(t, navErr)+ mb, h, tabID := navigatingHandlers(t, nil)+ mb.actionResult = map[string]any{+ "ok": true,+ bridge.ResultNavigated: true,+ bridge.ResultLandedURL: "https://b.example/",+ bridge.ResultPreviousURL: "https://a.example/",+ bridge.ResultRefsStale: true,+ }req := &bridge.ActionRequest{Kind: kind, Ref: "e6", NodeID: 18}- _, _, rr, err := h.executeActionResilient(context.Background(), req, h.Config, tabID, false)+ result, _, rr, err := h.executeActionResilient(context.Background(), req, h.Config, tabID, false)- if !errors.Is(err, bridge.ErrUnexpectedNavigation) {- t.Fatalf("error = %v, want the navigation guard's sentinel", err)+ if err != nil {+ t.Fatalf("an action that ran and moved the page reported failure: %v", err)+ }+ if result[bridge.ResultLandedURL] != "https://b.example/" {+ t.Errorf("the landed url did not reach the caller: %v", result)}if got := atomic.LoadInt64(&mb.dispatches); got != 1 {- t.Errorf("%d dispatches for one request; the guard fires only after the action succeeded, so a second one is an unrequested action on the user's browser", got)+ t.Errorf("%d dispatches for one request; re-matching a ref against the page the caller's own action navigated to is a second, unrequested action on the user's browser", got)}if rr != nil {t.Errorf("a recovery block was published for a request that clicked nothing else: %+v", rr)diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 8c686db2..a8c3a479 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -129,34 +129,6 @@ func actionFailureIsRetryable(err error, dispatchMayHaveLanded bool) bool {return !errors.Is(err, ErrTargetNotFound) && !errors.Is(err, bridge.ErrInvalidActionRequest)}-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. From the CLI those are --wait-nav and --submit."--// The ref stays a placeholder: this guard reports on an action it did not receive the ref-// for — it is reached from the post-action navigation check, which sees only the error —-// so there is no value here to interpolate. The alternative flag stays in the hint,-// because a remedy names one command to run.-var navigationChangedRemedy = remedy.Declare("pinchtab click <ref> --wait-nav")--func navigationChangedDetails(err error) map[string]any {- details := remedy.Details(navigationChangedHint, navigationChangedRemedy.Remedy())- if url := navigatedToURL(err); url != "" {- details["url"] = url- }- return details-}--func navigatedToURL(err error) string {- if err == nil {- return ""- }- message := err.Error()- idx := strings.LastIndex(message, " -> ")- if idx < 0 {- return ""- }- return strings.TrimSpace(message[idx+len(" -> "):])-}-func (h *Handlers) mapDialogBlockingError(err error, kind, tabID string) (string, *bridge.DialogState, bool) {var dialogErr *bridge.ErrDialogBlockingif errors.As(err, &dialogErr) {@@ -685,18 +657,6 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {refNotFound(req.Ref).Error(), false, staleSubmitTargetDetails())return}- if errors.Is(actionErr, bridge.ErrUnexpectedNavigation) {- details := navigationChangedDetails(actionErr)- // A navigation reported after a recovered click has to say WHICH element was- // clicked: the caller named a ref that no longer resolved, so the dispatch went- // to whatever recovery matched. Without this the 409 discloses the navigation- // and hides the substitution.- if recoveryResult != nil {- details["recovery"] = recoveryResult- }- httpx.ErrorCode(w, 409, "navigation_changed", actionErr.Error(), false, details)- return- }if browserops.IsIDPIBlocked(actionErr) {httpx.ErrorCode(w, http.StatusForbidden, "idpi_blocked", actionErr.Error(), false, nil)returndiff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.goindex b9e42ab6..b5340a36 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -647,9 +647,18 @@ func TestEnsureChromeAliasServes(t *testing.T) {}}-func TestHandleAction_NavigationChangedCarriesHintAndRemedy(t *testing.T) {- navErr := fmt.Errorf("%w: %s -> %s", bridge.ErrUnexpectedNavigation, "https://pinchtab.com/", "https://pinchtab.com/docs/")- mb := &mockBridge{executeActionErr: navErr}+// The endpoint's whole contract for a click that navigates: a success carrying where+// the caller landed and the fact that its refs are dead. It used to be a 409 whose+// hint and remedy told the caller to re-issue the click with --wait-nav — advice that+// re-clicked on the page the first click had already reached.+func TestHandleAction_ANavigatingClickIsASuccessCarryingTheLandedURL(t *testing.T) {+ mb := &mockBridge{actionResult: map[string]any{+ "clicked": true,+ bridge.ResultNavigated: true,+ bridge.ResultLandedURL: "https://pinchtab.com/docs/",+ bridge.ResultPreviousURL: "https://pinchtab.com/",+ bridge.ResultRefsStale: true,+ }}h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click"}`)))req.Header.Set("Content-Type", "application/json")@@ -657,45 +666,32 @@ func TestHandleAction_NavigationChangedCarriesHintAndRemedy(t *testing.T) {h.HandleAction(w, req)- if w.Code != 409 {- t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ if w.Code != 200 {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())}var resp struct {- Code string `json:"code"`- Details map[string]any `json:"details"`+ Success bool `json:"success"`+ Result map[string]any `json:"result"`}if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {t.Fatalf("decode response: %v", err)}- if resp.Code != "navigation_changed" {- t.Fatalf("code = %q, want navigation_changed", resp.Code)- }- for _, key := range []string{"hint", "remedy", "url"} {- value, _ := resp.Details[key].(string)- if value == "" {- t.Fatalf("details[%q] missing or empty: %#v", key, resp.Details)- }- }- hint, _ := resp.Details["hint"].(string)- for _, want := range []string{"waitNav", "submit"} {- if !strings.Contains(hint, want) {- t.Fatalf("hint %q does not name request field %q", hint, want)- }+ if !resp.Success {+ t.Fatalf("success = false: %s", w.Body.String())}- // One command, one flag: the remedy is a line a caller can run, so the alternative- // flag belongs in the hint. Naming both here is what made the field unrunnable.- line, _ := resp.Details["remedy"].(string)- if want := "pinchtab click <ref> --wait-nav"; line != want {- t.Fatalf("remedy = %q, want %q", line, want)+ // The action's own result is what the API used to discard when it answered with+ // the navigation as an error instead.+ if resp.Result["clicked"] != true {+ t.Errorf("the action's own result was dropped: %v", resp.Result)}- if strings.Contains(line, "--submit") {- t.Fatalf("remedy %q offers two flags, so it is not one command to run", line)+ if resp.Result[bridge.ResultNavigated] != true {+ t.Errorf("result does not report the navigation: %v", resp.Result)}- if !strings.Contains(hint, "--submit") {- t.Fatalf("hint %q does not name the --submit alternative the remedy dropped", hint)+ if got, _ := resp.Result[bridge.ResultLandedURL].(string); got != "https://pinchtab.com/docs/" {+ t.Errorf("result[%s] = %q, want the landed URL", bridge.ResultLandedURL, got)}- if got, _ := resp.Details["url"].(string); got != "https://pinchtab.com/docs/" {- t.Fatalf("details[url] = %q, want the resulting URL", got)+ if resp.Result[bridge.ResultRefsStale] != true {+ t.Errorf("result does not say the caller's refs are dead: %v", resp.Result)}}diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 53904b4d..6c81066c 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -31,6 +31,7 @@ type mockBridge struct {ensureBrowserCfg *config.RuntimeConfigdialogManager *bridge.DialogManagerexecuteActionErr error+ actionResult map[string]anyautoCloseArmed []stringautoCloseCanceled []stringavailableActions []string@@ -79,6 +80,9 @@ func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.if m.executeActionErr != nil {return nil, m.executeActionErr}+ if m.actionResult != nil {+ return m.actionResult, nil+ }return map[string]any{"success": true}, nil}diff --git a/internal/mcp/handlers_click_navigation_test.go b/internal/mcp/handlers_click_navigation_test.gonew file mode 100644index 00000000..54036303--- /dev/null+++ b/internal/mcp/handlers_click_navigation_test.go@@ -0,0 +1,40 @@+package mcp++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++// isError:true is the signal every agent loop branches on, and a click that+// navigated used to raise it after the click had already worked — so the natural+// reaction, retry, re-clicked on the page the first click had reached.+func TestClickThatNavigatedIsNotAnError(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(200)+ _ = json.NewEncoder(w).Encode(map[string]any{+ "success": true,+ "result": map[string]any{+ "clicked": true,+ "navigated": true,+ "url": "https://www.iana.org/help/example-domains",+ "previousUrl": "https://example.com/",+ "refsStale": true,+ },+ })+ }))+ defer srv.Close()++ result := callTool(t, "pinchtab_click", map[string]any{"ref": "e1"}, srv)++ if result.IsError {+ t.Fatalf("a click that ran and moved the page reported isError: %s", resultText(t, result))+ }+ text := resultText(t, result)+ if !strings.Contains(text, "https://www.iana.org/help/example-domains") {+ t.Errorf("result = %q; the caller cannot see where the click landed", text)+ }+}