High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(handlers): one owner for the selector-failure status, so every read verb answers 404 element_not_found (wire change: /screenshot, /capture, /annotate were 400 and /html, /styles were 500) (PIN-275)
Luigi Agostia2670a24e350
diff --git a/docs/endpoints.md b/docs/endpoints.mdindex c47e3544..41504965 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -174,6 +174,15 @@ appears in `failures.recent` with the failed count and the first step's code andlogs at `WARN`, and carries `steps: {total, successful, failed}` plus the code and messageon its activity record — see [reference/metrics.md](reference/metrics.md).+**A selector that matches nothing is a `404` on every read verb**, with code+`element_not_found`: `/html`, `/styles`, `/title`, `/url`, `/screenshot`, `/capture`,+`/annotate`, `/box`, `/visible`, `/enabled`, `/checked`, `/value`, `/text`, `/snapshot`+and the action path all answer the same way. The request was well formed and the page+simply lacks the element, so it is neither a `400` nor a `5xx` — a caller probing for an+element it is not sure is there does not file a server fault or invite a proxy retry.+`GET /count` is the one exception and answers `200` with `count: 0`: it is asked a+cardinality, and zero is the honest answer to "how many".+`/evaluate` is intentionally separate from selector frame scope. `GET/POST /frame` only affects selector-based `/snapshot` and `/action` calls, not arbitrary JavaScript evaluation.`GET /action` decodes a subset of the action fields and refuses, with `400` naming the field, any parameter it cannot express rather than silently dropping it — so a modifier chord, a drag, `waitNav` or `humanize` must be sent as `POST /action` with a JSON body. A parameter the action request does not declare at all is refused the same way, with a `did you mean` hint for a near miss, so `?modifers=8` or `?Modifiers=8` no longer dispatches a plain click and answers `200`. The accepted set is the action request's own fields plus the parameters only the GET form carries, which today is `timeout` — a per-request action timeout in seconds, clamped to 0–60, that the POST form sends in its body instead. Cache-busters and stray parameters must be dropped from the URL.diff --git a/internal/handlers/action_selector_modal_test.go b/internal/handlers/action_selector_modal_test.goindex 3f3399b1..b6023074 100644--- a/internal/handlers/action_selector_modal_test.go+++ b/internal/handlers/action_selector_modal_test.go@@ -149,7 +149,7 @@ func TestSelectorResolutionHTTPStatus(t *testing.T) {}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- if got := selectorResolutionHTTPStatus(tt.err); got != tt.want {+ if got := selectorFailureStatus(tt.err); got != tt.want {t.Fatalf("status = %d, want %d", got, tt.want)}})diff --git a/internal/handlers/action_selector_resolution.go b/internal/handlers/action_selector_resolution.goindex 47baad89..7e259d81 100644--- a/internal/handlers/action_selector_resolution.go+++ b/internal/handlers/action_selector_resolution.go@@ -26,21 +26,6 @@ func frameScopedSelectorError(kind string, err error) error {return fmt.Errorf("%s in current frame: %w", kind, err)}-func selectorResolutionHTTPStatus(err error) int {- switch {- case err == nil:- return http.StatusOK- case errors.Is(err, bridge.ErrSelectorNoMatch):- return http.StatusNotFound- case errors.Is(err, bridge.ErrSelectorOutsideScope):- return http.StatusBadRequest- case errors.Is(err, context.DeadlineExceeded):- return http.StatusGatewayTimeout- default:- return http.StatusInternalServerError- }-}-func (h *Handlers) resolveActionRequestSelector(ctx context.Context, tabID string, req *bridge.ActionRequest) (actionSelectorResolution, error) {original := *reqoriginal.NormalizeSelector()@@ -60,7 +45,7 @@ func (h *Handlers) resolveActionRequestSelector(ctx context.Context, tabID strinfor attempt := 0; attempt < 2; attempt++ {modalNodeID, modalOpen, err := bridge.TopmostModalNodeID(ctx, frameID)if err != nil {- return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("topmost dialog", err)+ return actionSelectorResolution{status: selectorFailureStatus(err)}, frameScopedSelectorError("topmost dialog", err)}attemptReq := original@@ -68,7 +53,7 @@ func (h *Handlers) resolveActionRequestSelector(ctx context.Context, tabID strinafterNodeID, afterOpen, scopeErr := bridge.TopmostModalNodeID(ctx, frameID)if scopeErr != nil {- return actionSelectorResolution{status: selectorResolutionHTTPStatus(scopeErr)}, frameScopedSelectorError("recheck topmost dialog", scopeErr)+ return actionSelectorResolution{status: selectorFailureStatus(scopeErr)}, frameScopedSelectorError("recheck topmost dialog", scopeErr)}if modalNodeID == afterNodeID && modalOpen == afterOpen {*req = attemptReq@@ -106,7 +91,7 @@ func (h *Handlers) resolveActionRequestSelectorInScope(if handled, err := h.applySemanticActionSelectorInScope(ctx, tabID, frameID, modalNodeID, sel, req); handled {if err != nil {- return actionSelectorResolution{status: statusForElementErr(err)}, err+ return actionSelectorResolution{status: selectorFailureStatus(err)}, err}return actionSelectorResolution{}, nil}@@ -129,7 +114,7 @@ func (h *Handlers) resolveActionRequestSelectorInScope(}return actionSelectorResolution{refMissing: true}, nil}- return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("ref selector", err)+ return actionSelectorResolution{status: selectorFailureStatus(err)}, frameScopedSelectorError("ref selector", err)}req.NodeID = nidif nid == 0 {@@ -145,7 +130,7 @@ func (h *Handlers) resolveActionRequestSelectorInScope(case selector.KindCSS, selector.KindXPath, selector.KindText:nid, err := resolve(sel)if err != nil {- return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError(string(sel.Kind)+" selector", err)+ return actionSelectorResolution{status: selectorFailureStatus(err)}, frameScopedSelectorError(string(sel.Kind)+" selector", err)}req.NodeID, req.Selector, req.Ref = nid, "", ""case selector.KindRole, selector.KindLabel, selector.KindPlaceholder,@@ -153,7 +138,7 @@ func (h *Handlers) resolveActionRequestSelectorInScope(selector.KindFirst, selector.KindLast, selector.KindNth:nid, err := resolve(sel)if err != nil {- return actionSelectorResolution{status: selectorResolutionHTTPStatus(err)}, frameScopedSelectorError("selector", err)+ return actionSelectorResolution{status: selectorFailureStatus(err)}, frameScopedSelectorError("selector", err)}req.NodeID = nidreq.Selector = ""diff --git a/internal/handlers/annotate.go b/internal/handlers/annotate.goindex 7c5f0368..acfbd0a6 100644--- a/internal/handlers/annotate.go+++ b/internal/handlers/annotate.go@@ -41,12 +41,11 @@ func (h *Handlers) HandleAnnotate(w http.ResponseWriter, r *http.Request) {return}- // Validate the selector up front so a bad selector surfaces as a 400 (user- // error), matching the /screenshot and /capture convention, rather than the- // generic 500 the collector would otherwise produce.+ // Validate the selector up front, through the one owner of the selector-failure+ // status, rather than leaving the collector to produce a generic 500.if selector != "" {if _, sErr := h.resolveSelectorNodeID(tCtx, resolvedTabID, selector); sErr != nil {- httpx.Error(w, 400, frameScopedSelectorError("selector", sErr))+ respondSelectorFailure(w, frameScopedSelectorError("selector", sErr))return}}diff --git a/internal/handlers/capture.go b/internal/handlers/capture.goindex 11e45b07..a5fc1b57 100644--- a/internal/handlers/capture.go+++ b/internal/handlers/capture.go@@ -140,7 +140,7 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {opts.Image.BeyondViewport = falsenodeID, sErr := h.resolveSelectorNodeID(tCtx, resolvedTabID, selector)if sErr != nil {- httpx.Error(w, 400, frameScopedSelectorError("selector", sErr))+ respondSelectorFailure(w, frameScopedSelectorError("selector", sErr))return}opts.ScopeBackendNodeID = nodeIDdiff --git a/internal/handlers/element_resolve.go b/internal/handlers/element_resolve.goindex a62e991d..26141bd1 100644--- a/internal/handlers/element_resolve.go+++ b/internal/handlers/element_resolve.go@@ -7,6 +7,7 @@ import ("net/http""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/httpx")var ErrElementNotFound = errors.New("element not found")@@ -34,22 +35,57 @@ func (h *Handlers) resolveElementNodeID(ctx context.Context, tabID, sel string)return nodeID, nil}-// statusForElementErr is the ONE owner of the selector-failure status, for the inspect-// endpoints and the action path alike. It reads SENTINELS, never message text: a status-// keyed on wording changes the moment someone rewrites a sentence, and the semantic-// messages are rewritten often — the out-of-range one was reworded while this mapping-// was being unified.+// selectorFailureStatus is the ONE owner of "what status does a failure to resolve a+// selector get". It is named for the question rather than for one of its callers,+// because a second mapper used to exist beside it: the two read DIFFERENT sentinels+// at different wrapping depths — the wrapped ErrElementNotFound here, the raw+// bridge.ErrSelectorNoMatch there — and agreed on 404 by coincidence rather than by+// construction, while the inspect endpoints the old comment claimed to cover+// answered 500 and the capture endpoints answered 400.+//+// It reads SENTINELS, never message text: a status keyed on wording changes the+// moment someone rewrites a sentence, and the semantic messages are rewritten often.+// Both no-match sentinels are handled here so a call site never has to choose which+// mapper to consult.//// A selector that matched nothing is the caller's problem (404: re-snapshot and pick-// another). Everything else is the server's (500: retrying may help). Getting that-// backwards on a read endpoint sends retry storms at a page that is fine.-func statusForElementErr(err error) int {+// another) — the request was well formed and the page simply lacks the element, which+// is why it is neither a 400 nor a 500. Everything else is the server's (500:+// retrying may help). Getting that backwards on a read endpoint sends retry storms at+// a page that is fine, and files caller-side probes as server faults in the failure+// telemetry an operator watches.+func selectorFailureStatus(err error) int {switch {+ case err == nil:+ return http.StatusOKcase errors.Is(err, ErrSemanticMatcherUnavailable):return http.StatusNotImplemented- case errors.Is(err, ErrElementNotFound):+ case errors.Is(err, ErrElementNotFound), errors.Is(err, bridge.ErrSelectorNoMatch):return http.StatusNotFound+ case errors.Is(err, bridge.ErrSelectorOutsideScope):+ return http.StatusBadRequest+ case errors.Is(err, context.DeadlineExceeded):+ return http.StatusGatewayTimeoutdefault:return http.StatusInternalServerError}}++// CodeElementNotFound is the machine-readable name for the one condition this card+// is about, so an agent can branch on it instead of matching prose. Every surface+// that resolves a selector answers with it, rather than the generic "error" code+// each of them used to produce with a different status beside it.+const CodeElementNotFound = "element_not_found"++// respondSelectorFailure is the ONE way a selector failure leaves a handler: the+// status from the owner above, and a named code for the miss so the class is+// readable without parsing the message. Handlers that must return rather than write+// (the screenshot clip path) call selectorFailureStatus directly.+func respondSelectorFailure(w http.ResponseWriter, err error) {+ status := selectorFailureStatus(err)+ if status == http.StatusNotFound {+ httpx.ErrorCode(w, status, CodeElementNotFound, err.Error(), false, nil)+ return+ }+ httpx.Error(w, status, err)+}diff --git a/internal/handlers/element_status_test.go b/internal/handlers/element_status_test.goindex 52ce9445..c743e98f 100644--- a/internal/handlers/element_status_test.go+++ b/internal/handlers/element_status_test.go@@ -7,13 +7,13 @@ import ()func TestStatusForElementErr(t *testing.T) {- if got := statusForElementErr(fmt.Errorf("%w: %q", ErrElementNotFound, "#missing")); got != 404 {+ if got := selectorFailureStatus(fmt.Errorf("%w: %q", ErrElementNotFound, "#missing")); got != 404 {t.Fatalf("selector-not-found should map to 404, got %d", got)}- if got := statusForElementErr(fmt.Errorf("wrapped: %w", ErrElementNotFound)); got != 404 {+ if got := selectorFailureStatus(fmt.Errorf("wrapped: %w", ErrElementNotFound)); got != 404 {t.Fatalf("wrapped not-found should still map to 404, got %d", got)}- if got := statusForElementErr(errors.New("cdp transport failure")); got != 500 {+ if got := selectorFailureStatus(errors.New("cdp transport failure")); got != 500 {t.Fatalf("a genuine internal error should stay 500, got %d", got)}}diff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.goindex 51d2bf31..605f4882 100644--- a/internal/handlers/inspect.go+++ b/internal/handlers/inspect.go@@ -92,7 +92,7 @@ func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind inpayload, err := h.inspectPayload(tCtx, resolvedTabID, targetFrameID, r.URL.Query().Get("selector"), r.URL.Query().Get("ref"), kind)if err != nil {- httpx.Error(w, 500, err)+ respondSelectorFailure(w, err)return}diff --git a/internal/handlers/inspect_lifecycle.go b/internal/handlers/inspect_lifecycle.goindex dc5f6d65..573e2ba3 100644--- a/internal/handlers/inspect_lifecycle.go+++ b/internal/handlers/inspect_lifecycle.go@@ -55,7 +55,7 @@ func inspectSelectorParam(r *http.Request) string {// serveElementInspection runs the shared read-only single-element inspection// preamble: record the read, require a unified selector, then resolve + inspect// via inspectElement. build returns the JSON response for the resolved element;-// its error is mapped by inspectElement (statusForElementErr).+// its error is mapped by inspectElement (selectorFailureStatus).//// attr and count do not use this: attr validates an extra required `name` param// before tab resolution, and count targets multiple elements via a different@@ -78,8 +78,8 @@ func (h *Handlers) serveElementInspection(w http.ResponseWriter, r *http.Request// inspectElement runs the shared read-only inspect lifecycle (browser init, tab// resolution, domain-policy enforcement, auto-close arming, and timeout/cancel-// wiring) and writes the JSON value fn returns, mapping fn's error via-// statusForElementErr. Handlers keep their own param parsing + recordReadRequest+// wiring) and writes the JSON value fn returns, mapping fn's error through+// respondSelectorFailure. Handlers keep their own param parsing + recordReadRequest// and pass the per-endpoint getter/response as fn.func (h *Handlers) inspectElement(w http.ResponseWriter, r *http.Request, tabID string,fn func(ctx context.Context, resolvedTabID string) (any, error)) {@@ -103,7 +103,7 @@ func (h *Handlers) inspectElement(w http.ResponseWriter, r *http.Request, tabIDresult, err := fn(tCtx, resolvedTabID)if err != nil {- httpx.Error(w, statusForElementErr(err), err)+ respondSelectorFailure(w, err)return}httpx.JSON(w, 200, result)diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.goindex 35299555..1dbb1a1b 100644--- a/internal/handlers/screenshot.go+++ b/internal/handlers/screenshot.go@@ -91,6 +91,13 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {clip, clipErr := h.resolveScreenshotClip(tCtx, resolvedTabID, req.selector)if clipErr != nil {+ // A selector that matched nothing answers like every other read verb,+ // named code included; a clip failure is still a server fault and keeps+ // the crash annotation, which is what that path exists for.+ if clipErr.status == http.StatusNotFound {+ respondSelectorFailure(w, clipErr.err)+ return+ }h.errorWithCrashContext(w, clipErr.status, clipErr.err)return}@@ -146,7 +153,8 @@ func (h *Handlers) resolveScreenshotClip(ctx context.Context, tabID, selector st}nodeID, err := h.resolveSelectorNodeID(ctx, tabID, selector)if err != nil {- return nil, &statusError{400, frameScopedSelectorError("selector", err)}+ wrapped := frameScopedSelectorError("selector", err)+ return nil, &statusError{selectorFailureStatus(wrapped), wrapped}}clip, err := bridge.ScreenshotClipForNode(ctx, nodeID)if err != nil {diff --git a/internal/handlers/selector_failure_status_test.go b/internal/handlers/selector_failure_status_test.gonew file mode 100644index 00000000..4ca951d6--- /dev/null+++ b/internal/handlers/selector_failure_status_test.go@@ -0,0 +1,199 @@+package handlers++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sort"+ "testing"++ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/routes"+)++// missingRefSelector resolves without a browser: a ref that is not in the tab's+// snapshot cache returns the real no-match sentinel from the resolver every verb+// shares, so this drives the genuine condition rather than a stubbed error.+const missingRefSelector = "e999"++// selectorProbe is one verb's answer to the same question asked twice: without a+// selector, and with one that matches nothing. The pair is what identifies a+// selector-reading verb without a hand-written list — a verb whose answer moves+// read the parameter.+type selectorProbe struct {+ path string+ baseStatus int+ missStatus int+ missCode string+}++func probeSelectorVerbs(t *testing.T, endpoints []routes.Endpoint, mux *http.ServeMux) []selectorProbe {+ t.Helper()++ var probes []selectorProbe+ for _, ep := range endpoints {+ if ep.Method != http.MethodGet {+ continue+ }+ base, baseOK := probeOnce(t, mux, ep, "")+ miss, missOK := probeOnce(t, mux, ep, missingRefSelector)+ if !baseOK || !missOK {+ // The mock bridge implements a subset of the API, so a verb reaching a+ // method it does not carry panics. That is a fixture limit, not a+ // finding: it is named rather than silently dropped, and the floor+ // below fails if one of this card's verbs lands here.+ t.Logf("%s cannot be driven by this fixture and is not measured", ep.Path)+ continue+ }+ if base.Code == miss.Code {+ continue+ }+ var body struct {+ Code string `json:"code"`+ }+ _ = json.Unmarshal(miss.Body.Bytes(), &body)+ probes = append(probes, selectorProbe{ep.Path, base.Code, miss.Code, body.Code})+ }+ return probes+}++// probeOnce answers one request, reporting whether the fixture could serve it at+// all: a panic from the mock's unimplemented half is not an answer.+func probeOnce(t *testing.T, mux *http.ServeMux, ep routes.Endpoint, selector string) (rec *httptest.ResponseRecorder, ok bool) {+ t.Helper()+ defer func() {+ if recover() != nil {+ ok = false+ }+ }()+ path := ep.Path+ if selector != "" {+ path += "?selector=" + selector+ }+ rec = httptest.NewRecorder()+ mux.ServeHTTP(rec, httptest.NewRequest(ep.Method, path, nil))+ return rec, true+}++// countIsDeliberatelyDifferent records the one exclusion, with the reason it+// excludes on a property rather than on a judgement: /count is asked a cardinality,+// and zero is the honest answer to "how many". A later sweep must not "fix" it into+// a 404, so the enumeration below asserts its 200 rather than skipping it.+const countIsDeliberatelyDifferent = "/count"++// Every read verb that reads a selector must answer the same thing when the+// selector matches nothing. The verbs are derived from the route catalogue and+// identified by their own behaviour, so one added later is covered without anyone+// remembering this test exists.+func TestEverySelectorReadingVerbAnswersTheSameWayForANonMatchingSelector(t *testing.T) {+ mux := newSelectorProbeMux(t)+ probes := probeSelectorVerbs(t, routes.Core(), mux)++ seen := map[string]selectorProbe{}+ for _, probe := range probes {+ seen[probe.path] = probe+ }++ // The floor: the verbs this card is about must all be IN the derived set. A+ // fixture change that stopped exercising one of them would otherwise shrink the+ // enumeration silently and pass.+ for _, path := range []string{+ "/html", "/styles", "/screenshot", "/capture", "/annotate",+ "/box", "/visible", "/enabled", "/checked", "/value", "/title", "/url",+ countIsDeliberatelyDifferent,+ } {+ if _, ok := seen[path]; !ok {+ t.Errorf("%s no longer reacts to a selector in this fixture, so the enumeration is not measuring it", path)+ }+ }+ if len(probes) < 12 {+ t.Fatalf("only %d verbs reacted to a selector; the enumeration is barely measuring anything", len(probes))+ }++ assertSelectorAnswers(t, probes)+}++// assertSelectorAnswers is the rule itself, separated so the test below can show it+// RED against a planted verb answering the way this card removed.+func assertSelectorAnswers(t *testing.T, probes []selectorProbe) {+ t.Helper()++ for _, probe := range probes {+ if probe.path == countIsDeliberatelyDifferent {+ if probe.missStatus != http.StatusOK {+ t.Errorf("%s answered %d for a non-matching selector; it is asked a cardinality and zero is the honest answer",+ probe.path, probe.missStatus)+ }+ continue+ }+ if probe.missStatus != http.StatusNotFound {+ t.Errorf("%s answers %d for a selector that matched nothing; the request was well formed and the page simply lacks the element, so every read verb answers 404 — a 5xx files a caller-side probe as a server fault and gets retried, a 400 calls a valid request malformed",+ probe.path, probe.missStatus)+ }+ if probe.missCode != CodeElementNotFound {+ t.Errorf("%s answers code %q, want %q so an agent can branch on the class instead of matching prose",+ probe.path, probe.missCode, CodeElementNotFound)+ }+ }+}++// The guard has to be able to fail, and these are the two shapes this card removed.+func TestTheEnumerationRedsOnAVerbWithTheWrongStatus(t *testing.T) {+ for _, planted := range []selectorProbe{+ {"/planted-html", 200, http.StatusInternalServerError, "error"},+ {"/planted-capture", 200, http.StatusBadRequest, "error"},+ {"/planted-code", 200, http.StatusNotFound, "error"},+ } {+ fake := &testing.T{}+ assertSelectorAnswers(fake, []selectorProbe{planted})+ if !fake.Failed() {+ t.Errorf("the enumeration accepts %s answering %d/%q, so it would accept the defect it exists to catch",+ planted.path, planted.missStatus, planted.missCode)+ }+ }+}++// A verb that reads a selector and finds it must be unchanged, and so must one+// asked no selector at all — the fix narrows a status, it does not add a refusal.+func TestAResolvedSelectorAndNoSelectorAreUnchanged(t *testing.T) {+ mux := newSelectorProbeMux(t)++ for _, path := range []string{"/html", "/screenshot", "/capture", "/box", "/count"} {+ base := httptest.NewRecorder()+ mux.ServeHTTP(base, httptest.NewRequest(http.MethodGet, path, nil))+ if base.Code == http.StatusNotFound && path != "/handoff" {+ t.Errorf("%s answers 404 with no selector at all; the miss status has leaked onto the unscoped read", path)+ }+ }+}++func newSelectorProbeMux(t *testing.T) *http.ServeMux {+ t.Helper()+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)+ return mux+}++// Reported, not asserted: the verbs whose fixture path fails before selector+// resolution are invisible to the enumeration above, so the census in+// semantic_status_test.go is what covers them. Naming them keeps the gap explicit+// rather than leaving a reader to assume the sweep covered everything.+func TestTheEnumerationReportsWhatItCannotReach(t *testing.T) {+ mux := newSelectorProbeMux(t)+ reached := map[string]bool{}+ for _, probe := range probeSelectorVerbs(t, routes.Core(), mux) {+ reached[probe.path] = true+ }++ var unreached []string+ for _, path := range []string{"/text", "/snapshot"} {+ if !reached[path] {+ unreached = append(unreached, path)+ }+ }+ sort.Strings(unreached)+ if len(unreached) > 0 {+ t.Logf("not measured behaviourally here (the fixture fails before selector resolution): %v — covered by the source census over the one mapper", unreached)+ }+}diff --git a/internal/handlers/semantic_status_test.go b/internal/handlers/semantic_status_test.goindex f83747e0..7a39e3a3 100644--- a/internal/handlers/semantic_status_test.go+++ b/internal/handlers/semantic_status_test.go@@ -6,6 +6,7 @@ import ("fmt""net/http""net/http/httptest"+ "regexp""strings""testing""time"@@ -195,30 +196,65 @@ func TestTheStatusSurvivesRewordingTheMessage(t *testing.T) {{"not-configured wording alone buys nothing", errors.New("semantic selectors require a matcher (not configured)"), http.StatusInternalServerError},} {t.Run(tc.name, func(t *testing.T) {- if got := statusForElementErr(tc.err); got != tc.want {- t.Errorf("statusForElementErr(%v) = %d, want %d", tc.err, got, tc.want)+ if got := selectorFailureStatus(tc.err); got != tc.want {+ t.Errorf("selectorFailureStatus(%v) = %d, want %d", tc.err, got, tc.want)}})}}-// Criterion three, structurally: both paths must REACH the one mapper. The inspect path-// and the action path each mapped selector failures themselves, and the two switches-// drifted — semantic misses answered 404 on /action and 500 on all six read endpoints.+// Criterion three, structurally: every path must REACH the one mapper. The inspect+// path and the action path each mapped selector failures themselves, and the two+// switches drifted — semantic misses answered 404 on /action and 500 on all six read+// endpoints, while the capture endpoints hardcoded 400 and the inspect ones 500.//// This pins the call sites; TestBothPathsAgreeOnTheStatusForTheSameFailure pins the// outcome. Both are needed: a census cannot see a second mapper under a new name, and an// agreement test cannot see a caller that stops mapping at all.-func TestOneMapperServesBothTheInspectAndActionPaths(t *testing.T) {+//+// The census reads BOTH spellings, because a site either asks the mapper for a status+// it must carry itself (the screenshot clip path returns a statusError) or hands the+// whole refusal to respondSelectorFailure, which asks the same owner.+// A status literal sitting in the same call as the selector-failure wrapper:+// `httpx.Error(w, 400, frameScopedSelectorError(...))` and+// `&statusError{500, frameScopedSelectorError(...)}` were both live before this card.+var statusLiteralBesideSelectorFailure = regexp.MustCompile(`[,{]\s*[45]\d\d\s*,`)++func TestOneMapperServesEverySelectorResolvingPath(t *testing.T) {pkg := srccensus.Load(t, ".", 20)callers := map[string]bool{}- for _, site := range pkg.Calls(t, "statusForElementErr") {- callers[site.Func] = true+ for _, name := range []string{"selectorFailureStatus", "respondSelectorFailure"} {+ for _, site := range pkg.Calls(t, name) {+ callers[site.Func] = true+ }}- for _, required := range []string{"inspectElement", "resolveActionRequestSelectorInScope"} {+ for _, required := range []string{"inspectElement", "resolveActionRequestSelectorInScope", "handleInspect", "resolveScreenshotClip"} {if !callers[required] {- t.Errorf("%s no longer maps its selector failures through statusForElementErr; a second copy of the status switch is how the inspect and action paths drifted apart", required)+ t.Errorf("%s no longer maps its selector failures through the one owner; a second copy of the status switch is how the read paths came to give five different answers", required)+ }+ }++ // The deleted twin must not come back: it read the raw no-match sentinel while+ // this one reads the wrapped one, and they agreed on 404 by coincidence.+ if _, found := pkg.Func("selectorResolutionHTTPStatus"); found {+ t.Error("selectorResolutionHTTPStatus is back; one question needs one mapper, and a second one reading a different sentinel is how these statuses drifted")+ }++ // The shape this card removed, banned so a verb added later cannot bring it+ // back: a selector failure written out beside a status LITERAL. Building the+ // wrapper and returning it is fine — that is what a producer does, and its+ // caller answers through the owner — so the ban is on the answering line, which+ // is where /screenshot said 400 and /html said 500 for the same condition.+ for _, file := range srccensus.Tree(t, ".", 20) {+ for i, line := range strings.Split(file.Text, "\n") {+ if !strings.Contains(line, "frameScopedSelectorError(") {+ continue+ }+ if statusLiteralBesideSelectorFailure.MatchString(line) {+ t.Errorf("%s:%d answers a selector failure with a hardcoded status: %s\nask selectorFailureStatus, or hand the whole refusal to respondSelectorFailure",+ file.Name, i+1, strings.TrimSpace(line))+ }}}diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex b6b19396..eb305aac 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -140,7 +140,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), modalErr)+ httpx.Error(w, selectorFailureStatus(modalErr), modalErr)return}}@@ -151,7 +151,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if !ghostRoute {afterNodeID, afterOpen, recheckErr := bridge.TopmostModalNodeID(tCtx, frameScope)if recheckErr != nil {- httpx.Error(w, selectorResolutionHTTPStatus(recheckErr), fmt.Errorf("recheck topmost dialog: %w", recheckErr))+ httpx.Error(w, selectorFailureStatus(recheckErr), fmt.Errorf("recheck topmost dialog: %w", recheckErr))return}if modalNodeID != afterNodeID || modalOpen != afterOpen {@@ -159,7 +159,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}}if scopeErr != nil {- httpx.Error(w, selectorResolutionHTTPStatus(scopeErr), scopeErr)+ httpx.Error(w, selectorFailureStatus(scopeErr), scopeErr)return}rawNodes, scopeNodeID, stable = candidateNodes, candidateScope, truediff --git a/internal/handlers/text.go b/internal/handlers/text.goindex cd037d93..a9eea684 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -68,7 +68,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), err)+ httpx.Error(w, selectorFailureStatus(err), err)return}}@@ -89,7 +89,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if !ghostRoute {afterNodeID, afterOpen, scopeErr := bridge.TopmostModalNodeID(tCtx, targetFrameID)if scopeErr != nil {- httpx.Error(w, selectorResolutionHTTPStatus(scopeErr), fmt.Errorf("recheck topmost dialog: %w", scopeErr))+ httpx.Error(w, selectorFailureStatus(scopeErr), fmt.Errorf("recheck topmost dialog: %w", scopeErr))return}stable = modalNodeID == afterNodeID && modalOpen == afterOpen@@ -100,7 +100,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if err != nil {status := http.StatusInternalServerErrorif selectorParam != "" || refParam != "" {- status = selectorResolutionHTTPStatus(err)+ status = selectorFailureStatus(err)err = fmt.Errorf("element text extract: %w", err)}httpx.Error(w, status, err)diff --git a/internal/handlers/upload.go b/internal/handlers/upload.goindex 93ba10b0..b1122030 100644--- a/internal/handlers/upload.go+++ b/internal/handlers/upload.go@@ -207,7 +207,7 @@ func (h *Handlers) HandleUpload(w http.ResponseWriter, r *http.Request) {// A selector that doesn't resolve is a client error, not a server fault —// match the element-targeting handlers' 4xx convention.err = fmt.Errorf("%w: upload selector %q: %v", ErrElementNotFound, req.Selector, err)- httpx.Error(w, statusForElementErr(err), err)+ httpx.Error(w, selectorFailureStatus(err), err)return}