Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: MCP pinchtab_fill silently writes nothing and reports success, because the layer collects value while the bridge action reads text (PIN-120)

Luigi Agostica96bbbf8657
diff --git a/docs/endpoints.md b/docs/endpoints.md
index 8fcd43a1..f4e5f22b 100644
--- a/docs/endpoints.md
+++ b/docs/endpoints.md
@@ -186,6 +186,10 @@ Action targeting fields:
- `dialogAction` and `dialogText`
- `humanize`
+`fill` and `type` write the string in `text`; `fill` also accepts it as `value`, which is the
+field `select` reads. A `fill` carrying neither is rejected — send `"text": ""` to clear a
+field, so clearing stays distinct from a request whose text never arrived.
+
`humanize` is a per-action override for input style. When omitted, actions use `instanceDefaults.humanize`, which defaults to `false`. Use `kind:"click"` or `kind:"type"` with `humanize:true` when a page needs the slower human-like pointer or typing path.
Pointer fallback behavior:
diff --git a/internal/bridge/action_fill_text_test.go b/internal/bridge/action_fill_text_test.go
new file mode 100644
index 00000000..85ad4f1c
--- /dev/null
+++ b/internal/bridge/action_fill_text_test.go
@@ -0,0 +1,133 @@
+package bridge
+
+import (
+ "context"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+// fill reads Text while select reads Value, and no surface declared which — so a caller
+// sending the other spelling wrote nothing and was told it had succeeded. FillText is the
+// one owner of that resolution, and the second return is what separates "clear this field"
+// from "the text never arrived", which used to be the same request.
+func TestFillTextResolvesEitherSpellingAndReportsWhetherAnyWasSupplied(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ req ActionRequest
+ want string
+ wantSupplied bool
+ }{
+ {"text", ActionRequest{Text: "FILLED"}, "FILLED", true},
+ {"value", ActionRequest{Value: "FILLED"}, "FILLED", true},
+ {"both, text wins", ActionRequest{Text: "FROM_TEXT", Value: "FROM_VALUE"}, "FROM_TEXT", true},
+ {"explicit empty text clears", ActionRequest{HasText: true}, "", true},
+ {"nothing supplied", ActionRequest{}, "", false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ got, supplied := FillText(tc.req)
+ if got != tc.want {
+ t.Errorf("FillText() text = %q, want %q", got, tc.want)
+ }
+ if supplied != tc.wantSupplied {
+ t.Errorf("FillText() supplied = %v, want %v", supplied, tc.wantSupplied)
+ }
+ })
+ }
+}
+
+// The pair the whole card turns on: clearing stays legal, and a fill that carries no text
+// under any spelling is refused instead of answering filled:true with len:0.
+func TestValidateFillActionRefusesOnlyWhenNoTextWasSupplied(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ kind string
+ req ActionRequest
+ wantErr bool
+ }{
+ {"nothing supplied", ActionFill, ActionRequest{Selector: "#q"}, true},
+ {"explicit clear", ActionFill, ActionRequest{Selector: "#q", HasText: true}, false},
+ {"text", ActionFill, ActionRequest{Selector: "#q", Text: "X"}, false},
+ {"value only", ActionFill, ActionRequest{Selector: "#q", Value: "X"}, false},
+ {"another kind is not fill's business", ActionType, ActionRequest{Selector: "#q"}, false},
+ {"select keeps its own guard", ActionSelect, ActionRequest{Selector: "#q"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ err := ValidateFillAction(tc.kind, tc.req)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatal("want a refusal: this request writes nothing and used to report success")
+ }
+ for _, want := range []string{"text", "value", `"text": ""`} {
+ if !strings.Contains(err.Error(), want) {
+ t.Errorf("refusal = %q, want it to mention %q", err, want)
+ }
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("ValidateFillAction() error = %v, want none", err)
+ }
+ })
+ }
+}
+
+// Presence has to survive the wire and the internal forwarding hop, which is why Text and
+// Value are omitempty: re-marshaling used to re-introduce "text":"" and make every
+// forwarded request look supplied, exactly as the X/Y comment describes for coordinates.
+func TestTextPresenceSurvivesDecodeAndReMarshal(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body string
+ wantSupplied bool
+ wantText string
+ }{
+ {"text supplied", `{"kind":"fill","text":"X"}`, true, "X"},
+ {"empty text supplied", `{"kind":"fill","text":""}`, true, ""},
+ {"empty value supplied", `{"kind":"fill","value":""}`, true, ""},
+ {"nothing supplied", `{"kind":"fill","nodeId":7}`, false, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ var req ActionRequest
+ if err := json.Unmarshal([]byte(tc.body), &req); err != nil {
+ t.Fatalf("Unmarshal() error = %v", err)
+ }
+ text, supplied := FillText(req)
+ if supplied != tc.wantSupplied || text != tc.wantText {
+ t.Fatalf("decoded FillText() = (%q, %v), want (%q, %v)", text, supplied, tc.wantText, tc.wantSupplied)
+ }
+
+ forwarded, err := json.Marshal(req)
+ if err != nil {
+ t.Fatalf("Marshal() error = %v", err)
+ }
+ var again ActionRequest
+ if err := json.Unmarshal(forwarded, &again); err != nil {
+ t.Fatalf("re-Unmarshal() error = %v", err)
+ }
+ text, supplied = FillText(again)
+ if supplied != tc.wantSupplied || text != tc.wantText {
+ t.Fatalf("after re-marshal FillText() = (%q, %v), want (%q, %v); forwarded body was %s", text, supplied, tc.wantText, tc.wantSupplied, forwarded)
+ }
+ })
+ }
+}
+
+// ExecuteAction is the in-process entry, so the refusal has to happen there too — and
+// before dispatch, since the action itself cannot tell the two empty requests apart.
+func TestExecuteActionRefusesAFillWithNoTextBeforeDispatch(t *testing.T) {
+ b := &Bridge{}
+ b.InitActionRegistry()
+
+ _, err := b.ExecuteAction(context.Background(), ActionFill, ActionRequest{Selector: "#q"})
+ if err == nil || !strings.Contains(err.Error(), "fill requires") {
+ t.Fatalf("ExecuteAction() error = %v, want the missing-text refusal", err)
+ }
+
+ // The control: an explicit clear must get past validation and fail later, at the browser
+ // it has no connection to — never with the refusal above.
+ _, err = b.ExecuteAction(context.Background(), ActionFill, ActionRequest{Selector: "#q", HasText: true})
+ if err != nil && strings.Contains(err.Error(), "fill requires") {
+ t.Errorf("an explicit clear was refused as missing text: %v", err)
+ }
+}
diff --git a/internal/bridge/action_request.go b/internal/bridge/action_request.go
index bae70e01..5b5edb84 100644
--- a/internal/bridge/action_request.go
+++ b/internal/bridge/action_request.go
@@ -34,10 +34,22 @@ type ActionRequest struct {
Kind string `json:"kind"`
Ref string `json:"ref,omitempty"`
Selector string `json:"selector,omitempty"`
- Text string `json:"text"`
- Key string `json:"key"`
- Value string `json:"value"`
- NodeID int64 `json:"nodeId"`
+
+ // Text/Value use omitempty, and HasText records that one of them was
+ // SUPPLIED, for the same reason X/Y do below: an empty fill is a
+ // legitimate request to clear the field, so absent and empty must not
+ // share a representation. While they did, `fill` could not refuse a
+ // request whose text never arrived — it wrote "" and answered
+ // filled:true, len:0 — and its read-back verification, gated on a
+ // non-empty Text, switched itself off in exactly that case. Re-marshaling
+ // without omitempty would re-introduce "text":"" and make every forwarded
+ // request look supplied.
+ Text string `json:"text,omitempty"`
+ Value string `json:"value,omitempty"`
+ HasText bool `json:"hasText,omitempty"`
+
+ Key string `json:"key"`
+ NodeID int64 `json:"nodeId"`
// X/Y use omitempty so that re-marshaling an ActionRequest without
// explicit coordinates (e.g. when the tab-scoped handler forwards to
@@ -137,6 +149,7 @@ func (r *ActionRequest) UnmarshalJSON(data []byte) error {
*r = ActionRequest(alias)
r.Kind = CanonicalActionKind(r.Kind)
r.HasXY = r.HasXY || hasJSONKey(raw, "x") || hasJSONKey(raw, "y")
+ r.HasText = r.HasText || hasJSONKey(raw, "text") || hasJSONKey(raw, "value")
if hasJSONKey(raw, "deltaX") {
if err := json.Unmarshal(raw["deltaX"], &r.DeltaX); err != nil {
return err
@@ -200,6 +213,37 @@ func ValidateSubmitAction(kind string, req ActionRequest) error {
}
}
+// FillText is the one owner of what a fill writes: text, falling back to value,
+// the same tolerance actionSelect has had in the other direction. Both are
+// published request fields and no surface declared which one fill reads, so a
+// caller sending the other spelling wrote nothing and was told it succeeded.
+//
+// The second return says whether anything was asked for at all, which is not the
+// same as a non-empty answer: a supplied empty string clears the field.
+func FillText(req ActionRequest) (string, bool) {
+ if req.Text != "" {
+ return req.Text, true
+ }
+ if req.Value != "" {
+ return req.Value, true
+ }
+ return "", req.HasText
+}
+
+// ValidateFillAction refuses a fill that carries no text under any spelling. That
+// request used to write "" and answer filled:true with len:0 — indistinguishable
+// from clearing a field on purpose, which is why it stayed invisible. Clearing
+// stays available by sending the key explicitly.
+func ValidateFillAction(kind string, req ActionRequest) error {
+ if CanonicalActionKind(kind) != ActionFill {
+ return nil
+ }
+ if _, supplied := FillText(req); !supplied {
+ return fmt.Errorf(`fill requires "text" (or "value"); send "text": "" to clear the field`)
+ }
+ return nil
+}
+
func hasJSONKey(raw map[string]json.RawMessage, key string) bool {
_, ok := raw[key]
return ok
@@ -214,6 +258,9 @@ func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionReque
if err := ValidateSubmitAction(kind, req); err != nil {
return nil, err
}
+ if err := ValidateFillAction(kind, req); err != nil {
+ return nil, err
+ }
if kind == ActionClick && b.effectiveHumanize(req) && strings.TrimSpace(req.Mode) != "" {
return nil, fmt.Errorf("mode and humanize are mutually exclusive")
}
diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.go
index 09a37e32..40e1417f 100644
--- a/internal/bridge/action_text.go
+++ b/internal/bridge/action_text.go
@@ -37,21 +37,25 @@ func (b *Bridge) actionType(ctx context.Context, req ActionRequest) (map[string]
}
func (b *Bridge) actionFill(ctx context.Context, req ActionRequest) (map[string]any, error) {
- result := textEntryResult("filled", req.Text)
+ text, _ := FillText(req)
+ result := textEntryResult("filled", text)
if req.Selector != "" {
if err := chromedp.Run(ctx,
chromedp.Focus(req.Selector, chromedp.ByQuery),
- chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery),
+ chromedp.SetValue(req.Selector, text, chromedp.ByQuery),
); err != nil {
return nil, err
}
return finishFill(ctx, result, req.Submit)
}
if req.NodeID > 0 {
- if err := FillByNodeID(ctx, req.NodeID, req.Text); err != nil {
+ if err := FillByNodeID(ctx, req.NodeID, text); err != nil {
return nil, err
}
- if actual, err := ReadInputValue(ctx, req.NodeID); err == nil && req.Text != "" && actual != req.Text {
+ // Compared against what was asked for rather than against "", so a clear that
+ // did not land is reported too. ValidateFillAction has already refused the
+ // nothing-was-supplied case, which is what used to disable this check.
+ if actual, err := ReadInputValue(ctx, req.NodeID); err == nil && actual != text {
result["warning"] = "fill may not have been picked up by the page (e.g. React controlled input); try 'type' instead"
}
return finishFill(ctx, result, req.Submit)
diff --git a/internal/handlers/action_fill_test.go b/internal/handlers/action_fill_test.go
new file mode 100644
index 00000000..bdc75886
--- /dev/null
+++ b/internal/handlers/action_fill_test.go
@@ -0,0 +1,90 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// fillCapture drives HandleAction and reports what the handler forwarded, so the two
+// requests that look identical inside the bridge — clear this field, and the text never
+// arrived — can be told apart at the boundary that still knows.
+func fillCapture(t *testing.T, body string) (*submitActionBridge, int, string, bridge.ActionRequest) {
+ t.Helper()
+
+ parentCtx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ b := newSubmitActionBridge(parentCtx)
+ b.availableActions = []string{bridge.ActionFill}
+ var forwarded bridge.ActionRequest
+ b.executeActionFn = func(_ context.Context, _ string, req bridge.ActionRequest) (map[string]any, error) {
+ forwarded = req
+ text, _ := bridge.FillText(req)
+ return map[string]any{"filled": true, "len": len(text)}, nil
+ }
+
+ h := New(b, &config.RuntimeConfig{ActionTimeout: time.Second}, nil, nil, nil)
+ w := postSubmitRequest(t, h, body)
+ return b, w.Code, w.Body.String(), forwarded
+}
+
+// The silent no-op, closed at the handler rather than in the action: the ghost-chrome proxy
+// answers fill from its static browser before the Chrome action runs, so a check that lived
+// only in actionFill would still be bypassed for that provider.
+func TestHandleActionRefusesAFillCarryingNoTextAtAll(t *testing.T) {
+ b, code, body, _ := fillCapture(t, `{"kind":"fill","tabId":"tab1","nodeId":42}`)
+
+ if code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400; this request writes nothing and used to answer filled:true with len:0\n%s", code, body)
+ }
+ if !strings.Contains(body, "missing_fill_text") {
+ t.Errorf("body = %s, want the missing_fill_text code", body)
+ }
+ if b.actionCalls != 0 {
+ t.Errorf("the refused fill still reached the browser %d time(s)", b.actionCalls)
+ }
+}
+
+// Clearing a field is a real operation and must survive the refusal above, which is the
+// whole reason presence is carried separately from emptiness.
+func TestHandleActionStillClearsOnAnExplicitEmptyText(t *testing.T) {
+ b, code, body, forwarded := fillCapture(t, `{"kind":"fill","tabId":"tab1","nodeId":42,"text":""}`)
+
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 for an explicit clear\n%s", code, body)
+ }
+ if b.actionCalls != 1 {
+ t.Fatalf("action calls = %d, want the clear to be executed", b.actionCalls)
+ }
+ text, supplied := bridge.FillText(forwarded)
+ if !supplied || text != "" {
+ t.Errorf("forwarded FillText() = (%q, %v), want the empty clear to arrive as supplied", text, supplied)
+ }
+}
+
+// The raw HTTP API is public and nothing documented which spelling fill reads, so a caller
+// POSTing value gets the write rather than a silent empty one.
+func TestHandleActionFillAcceptsValueAsWellAsText(t *testing.T) {
+ b, code, body, forwarded := fillCapture(t, `{"kind":"fill","tabId":"tab1","nodeId":42,"value":"FROM_VALUE"}`)
+
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200\n%s", code, body)
+ }
+ if b.actionCalls != 1 {
+ t.Fatalf("action calls = %d, want the fill to be executed", b.actionCalls)
+ }
+ if text, _ := bridge.FillText(forwarded); text != "FROM_VALUE" {
+ t.Errorf("forwarded FillText() = %q, want the value the caller supplied", text)
+ }
+
+ var resp map[string]any
+ if err := json.Unmarshal([]byte(body), &resp); err != nil {
+ t.Fatalf("response is not JSON (%v): %s", err, body)
+ }
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 5f3f28f9..9a286cf8 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -199,6 +199,7 @@ func decodeActionRequest(w http.ResponseWriter, r *http.Request) (bridge.ActionR
req.Selector = q.Get("selector")
req.Text = q.Get("text")
req.Value = q.Get("value")
+ req.HasText = d.present("text") || d.present("value")
req.Key = q.Get("key")
req.DialogAction = strings.ToLower(strings.TrimSpace(q.Get("dialogAction")))
req.DialogText = q.Get("dialogText")
@@ -271,6 +272,13 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
httpx.ErrorCode(w, http.StatusBadRequest, "invalid_submit_action", err.Error(), false, nil)
return
}
+ // Here rather than only inside the bridge action: the ghost-chrome proxy answers
+ // fill from its static browser before the Chrome action runs, so a check living in
+ // actionFill alone would be bypassed for one provider.
+ if err := bridge.ValidateFillAction(req.Kind, req); err != nil {
+ httpx.ErrorCode(w, http.StatusBadRequest, "missing_fill_text", err.Error(), false, nil)
+ return
+ }
h.recordActionRequest(r, req)
if available := h.Bridge.AvailableActions(); len(available) > 0 {
known := false
diff --git a/internal/mcp/action_payload_contract_test.go b/internal/mcp/action_payload_contract_test.go
new file mode 100644
index 00000000..b12aafb2
--- /dev/null
+++ b/internal/mcp/action_payload_contract_test.go
@@ -0,0 +1,592 @@
+package mcp
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "reflect"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+// consumedElsewhere records the payload keys the bridge ACTION never reads because another
+// layer owns them, with that owner. They are the reason this census can be strict about the
+// rest: everything not listed here has to be read by the action it is sent to.
+var consumedElsewhere = map[string]string{
+ "tabId": "resolved into a tab context by the handler before dispatch",
+ "nodeId": "resolved from selector/ref by the handler; the action reads NodeID it sets",
+ "selector": "normalised and resolved to a node by the handler",
+ "waitNav": "the handler waits for navigation around the action",
+ "dialogAction": "the handler arms the dialog watcher around the action",
+ "dialogText": "the handler arms the dialog watcher around the action",
+}
+
+// A payload key that is a real ActionRequest field but not one the target action READS is
+// invisible to every structural check: the key is spelled correctly, the field exists, and
+// the write silently does nothing. That is how fill posted its text under "value" — the
+// field select reads — and answered filled:true with len:0. So the contract this pins is
+// key-to-CONSUMING-ACTION, not key-to-struct.
+func TestEveryMCPActionPayloadKeyIsReadByTheActionItIsSentTo(t *testing.T) {
+ keysByKind := mcpPayloadKeysByKind(t)
+ if len(keysByKind) < 5 {
+ t.Fatalf("found payload keys for only %d action kinds, so this census is not reading the handler", len(keysByKind))
+ }
+ fieldByKey := actionRequestFieldsByJSONKey()
+ readsByKind := actionRequestReadsByKind(t)
+ if !readsByKind[bridge.ActionFill]["Text"] {
+ t.Fatalf("the fill action is not seen reading Text, so the bridge side of this census read nothing useful: %v", readsByKind[bridge.ActionFill])
+ }
+
+ checked := 0
+ for _, kind := range sortedKeys(keysByKind) {
+ entry := keysByKind[kind]
+ for _, key := range entry.keys {
+ if _, ok := consumedElsewhere[key]; ok {
+ continue
+ }
+ field, ok := fieldByKey[key]
+ if !ok {
+ t.Errorf("%s posts %q, which is not a field of bridge.ActionRequest at all", kind, key)
+ continue
+ }
+ checked++
+ read := readByAnyDispatchableKind(readsByKind, entry.dispatchesTo, field)
+ reason, accounted := postedButUnread[kind+"/"+key]
+ switch {
+ case read && accounted:
+ t.Errorf("%s posts %q and the action now reads ActionRequest.%s; drop its entry so this census keeps meaning what it says", kind, key, field)
+ case read:
+ case accounted:
+ t.Logf("accounted: %s posts %q (ActionRequest.%s) unread — %s", kind, key, field, reason)
+ default:
+ t.Errorf("%s posts %q (ActionRequest.%s), which no action it dispatches to (%v) reads; the write would be silently dropped",
+ kind, key, field, entry.dispatchesTo)
+ }
+ }
+ }
+ if checked < 5 {
+ t.Fatalf("only %d payload keys were checked against a consuming action, so this census proves little", checked)
+ }
+
+ for key := range consumedElsewhere {
+ if !anyKindPosts(keysByKind, key) {
+ t.Errorf("%q is recorded as consumed by another layer but nothing posts it any more; drop the entry", key)
+ }
+ }
+}
+
+type payloadCase struct {
+ keys []string
+ // dispatchesTo is the kind itself plus any kind the handler rewrites payload["kind"]
+ // to, since the scroll case turns itself into mouse-wheel for the wheel form.
+ dispatchesTo []string
+}
+
+// gatedByDeclaringSet covers the keys whose per-kind gate the walker cannot see, because the
+// handler computes a local flag under the gate and writes the key under the flag. Naming the
+// SET rather than the kinds keeps it derived: shrink xyAction and this narrows with it.
+var gatedByDeclaringSet = map[string]string{
+ "x": "xyAction",
+ "y": "xyAction",
+ "hasXY": "xyAction",
+}
+
+// postedButUnread records keys a tool forwards that its action does not read — the same
+// class as this card's defect, found by this census and filed separately rather than fixed
+// here. Each entry names the card, and it reds again the moment the action starts reading.
+var postedButUnread = map[string]string{
+ "hover/humanize": "PIN-186: pinchtab_hover forwards humanize but actionHover has no humanized variant, so the flag is ignored",
+}
+
+// declaringSets are the per-kind argument gates this handler uses, read from the package
+// itself so the census follows them: a key inside `if humanizeAction[kind]` belongs to the
+// kinds that map declares and to no others. A gate this test does not know about is a
+// failure, not a silent widening.
+var declaringSets = map[string]map[string]bool{
+ "humanizeAction": humanizeAction,
+ "xyAction": xyAction,
+}
+
+// mcpPayloadKeysByKind reads the handler rather than a hand-written list: a tool that starts
+// posting a new key has to be measured, and a list would simply not mention it. Keys set
+// before the switch belong to every kind the tool set can send, which is itself derived from
+// the handler registration.
+func mcpPayloadKeysByKind(t *testing.T) map[string]payloadCase {
+ t.Helper()
+
+ fn := findFuncDecl(t, parseGoFile(t, "handlers_interaction.go"), "handleAction")
+ keys := map[string]map[string]bool{}
+ rewrites := map[string]map[string]bool{}
+ collectPayloadKeys(t, fn.Body, mcpActionKinds(t), keys, rewrites)
+
+ for key, setName := range gatedByDeclaringSet {
+ set, known := declaringSets[setName]
+ if !known {
+ t.Fatalf("%q is recorded as gated by the unknown declaring set %q", key, setName)
+ }
+ for kind := range keys {
+ if !set[kind] {
+ delete(keys[kind], key)
+ }
+ }
+ }
+
+ out := map[string]payloadCase{}
+ for kind, set := range keys {
+ entry := payloadCase{dispatchesTo: []string{kind}}
+ for key := range set {
+ entry.keys = append(entry.keys, key)
+ }
+ for rewritten := range rewrites[kind] {
+ if rewritten != kind {
+ entry.dispatchesTo = append(entry.dispatchesTo, rewritten)
+ }
+ }
+ sort.Strings(entry.keys)
+ sort.Strings(entry.dispatchesTo)
+ out[kind] = entry
+ }
+ return out
+}
+
+// mcpActionKinds is the set of kinds handleAction is instantiated with, taken from the tool
+// registration so a new action tool joins this census by existing.
+func mcpActionKinds(t *testing.T) []string {
+ t.Helper()
+
+ var kinds []string
+ ast.Inspect(parseGoFile(t, "handlers.go"), func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok || !isIdent(call.Fun, "handleAction") || len(call.Args) != 2 {
+ return true
+ }
+ if kind, ok := stringLit(call.Args[1]); ok {
+ kinds = append(kinds, kind)
+ }
+ return true
+ })
+ if len(kinds) < 5 {
+ t.Fatalf("found only %d action tools, so this census is not reading the tool registration", len(kinds))
+ }
+ sort.Strings(kinds)
+ return kinds
+}
+
+// collectPayloadKeys walks the handler body carrying the kinds the current statement applies
+// to. A `switch kind` case narrows it to that case's kinds, an `if kind == "x"` to x, and a
+// declaring-set lookup to the kinds that set declares — which is what keeps `mode`, gated on
+// click inside a clause shared with hover and focus, from being attributed to all three.
+func collectPayloadKeys(t *testing.T, node ast.Node, kinds []string, keys, rewrites map[string]map[string]bool) {
+ t.Helper()
+
+ switch n := node.(type) {
+ case nil:
+ return
+ case *ast.AssignStmt:
+ for i, lhs := range n.Lhs {
+ index, ok := lhs.(*ast.IndexExpr)
+ if !ok || !isIdent(index.X, "payload") {
+ continue
+ }
+ key, ok := stringLit(index.Index)
+ if !ok {
+ continue
+ }
+ for _, kind := range kinds {
+ if key == "kind" {
+ if i < len(n.Rhs) {
+ if rewritten, ok := stringLit(n.Rhs[i]); ok {
+ addTo(rewrites, kind, rewritten)
+ }
+ }
+ continue
+ }
+ addTo(keys, kind, key)
+ }
+ }
+ case *ast.IfStmt:
+ body := kinds
+ if restricted, ok := restrictKinds(t, n.Cond, kinds, assignsPayload(n.Body)); ok {
+ body = restricted
+ }
+ collectPayloadKeys(t, n.Body, body, keys, rewrites)
+ if n.Else != nil {
+ collectPayloadKeys(t, n.Else, kinds, keys, rewrites)
+ }
+ return
+ case *ast.SwitchStmt:
+ if isIdent(n.Tag, "kind") {
+ for _, stmt := range n.Body.List {
+ clause, ok := stmt.(*ast.CaseClause)
+ if !ok {
+ continue
+ }
+ caseKinds := []string{}
+ for _, expr := range clause.List {
+ if kind, ok := stringLit(expr); ok && contains(kinds, kind) {
+ caseKinds = append(caseKinds, kind)
+ }
+ }
+ for _, stmt := range clause.Body {
+ collectPayloadKeys(t, stmt, caseKinds, keys, rewrites)
+ }
+ }
+ return
+ }
+ }
+
+ for _, child := range childNodes(node) {
+ collectPayloadKeys(t, child, kinds, keys, rewrites)
+ }
+}
+
+// restrictKinds narrows the applicable kinds for a conditional: `kind == "x"` to x, and a
+// declaring-set lookup to that set's members.
+func restrictKinds(t *testing.T, cond ast.Expr, kinds []string, gatesPayload bool) ([]string, bool) {
+ t.Helper()
+
+ switch c := cond.(type) {
+ case *ast.BinaryExpr:
+ switch c.Op {
+ case token.EQL:
+ if isIdent(c.X, "kind") {
+ if kind, ok := stringLit(c.Y); ok {
+ return intersect(kinds, []string{kind}), true
+ }
+ }
+ case token.LOR:
+ left, okLeft := restrictKinds(t, c.X, kinds, gatesPayload)
+ right, okRight := restrictKinds(t, c.Y, kinds, gatesPayload)
+ if okLeft && okRight {
+ return union(left, right), true
+ }
+ }
+ case *ast.IndexExpr:
+ name := calleeName(c.X)
+ if !isIdent(c.Index, "kind") {
+ return nil, false
+ }
+ set, known := declaringSets[name]
+ if !known {
+ if gatesPayload {
+ t.Fatalf("payload keys are gated on the unknown declaring set %q; register it in declaringSets so this census keeps meaning what it says", name)
+ }
+ return nil, false
+ }
+ declared := []string{}
+ for kind := range set {
+ declared = append(declared, kind)
+ }
+ return intersect(kinds, declared), true
+ case *ast.ParenExpr:
+ return restrictKinds(t, c.X, kinds, gatesPayload)
+ }
+ return nil, false
+}
+
+// assignsPayload reports whether a subtree writes any payload key, so an unknown per-kind
+// gate is a failure only when it actually decides one.
+func assignsPayload(node ast.Node) bool {
+ found := false
+ ast.Inspect(node, func(n ast.Node) bool {
+ assign, ok := n.(*ast.AssignStmt)
+ if !ok {
+ return true
+ }
+ for _, lhs := range assign.Lhs {
+ if index, ok := lhs.(*ast.IndexExpr); ok && isIdent(index.X, "payload") {
+ found = true
+ }
+ }
+ return true
+ })
+ return found
+}
+
+func childNodes(node ast.Node) []ast.Node {
+ var out []ast.Node
+ ast.Inspect(node, func(n ast.Node) bool {
+ if n == nil || n == node {
+ return true
+ }
+ out = append(out, n)
+ return false
+ })
+ return out
+}
+
+func addTo(m map[string]map[string]bool, outer, inner string) {
+ if m[outer] == nil {
+ m[outer] = map[string]bool{}
+ }
+ m[outer][inner] = true
+}
+
+func contains(haystack []string, needle string) bool {
+ for _, item := range haystack {
+ if item == needle {
+ return true
+ }
+ }
+ return false
+}
+
+func intersect(a, b []string) []string {
+ out := []string{}
+ for _, item := range a {
+ if contains(b, item) {
+ out = append(out, item)
+ }
+ }
+ return out
+}
+
+func union(a, b []string) []string {
+ out := append([]string(nil), a...)
+ for _, item := range b {
+ if !contains(out, item) {
+ out = append(out, item)
+ }
+ }
+ return out
+}
+
+func findFuncDecl(t *testing.T, file *ast.File, name string) *ast.FuncDecl {
+ t.Helper()
+ for _, decl := range file.Decls {
+ if fn, ok := decl.(*ast.FuncDecl); ok && fn.Name.Name == name && fn.Body != nil {
+ return fn
+ }
+ }
+ t.Fatalf("no %s function found, so this census has nothing to read", name)
+ return nil
+}
+
+func actionRequestFieldsByJSONKey() map[string]string {
+ out := map[string]string{}
+ typ := reflect.TypeOf(bridge.ActionRequest{})
+ for i := 0; i < typ.NumField(); i++ {
+ field := typ.Field(i)
+ tag := strings.Split(field.Tag.Get("json"), ",")[0]
+ if tag == "" || tag == "-" {
+ continue
+ }
+ out[tag] = field.Name
+ }
+ return out
+}
+
+// actionRequestReadsByKind answers, per action kind, which ActionRequest fields that kind's
+// action reads — transitively, since actions delegate (humanized type, the pointer helpers)
+// and pass the same request down. The kind-to-function mapping comes from the live registry,
+// so rewiring an action moves the census with it.
+func actionRequestReadsByKind(t *testing.T) map[string]map[string]bool {
+ t.Helper()
+
+ reads, calls := bridgeRequestReads(t)
+
+ b := &bridge.Bridge{}
+ b.InitActionRegistry()
+ if len(b.Actions) == 0 {
+ t.Fatal("the action registry is empty, so this census has no kinds to check")
+ }
+
+ out := map[string]map[string]bool{}
+ for kind, fn := range b.Actions {
+ name := methodName(fn)
+ if name == "" {
+ t.Fatalf("cannot resolve the function behind action %q", kind)
+ }
+ out[kind] = transitiveReads(name, reads, calls, map[string]bool{})
+ }
+ return out
+}
+
+func transitiveReads(name string, reads map[string]map[string]bool, calls map[string]map[string]bool, seen map[string]bool) map[string]bool {
+ out := map[string]bool{}
+ if seen[name] {
+ return out
+ }
+ seen[name] = true
+ for field := range reads[name] {
+ out[field] = true
+ }
+ for callee := range calls[name] {
+ for field := range transitiveReads(callee, reads, calls, seen) {
+ out[field] = true
+ }
+ }
+ return out
+}
+
+// bridgeRequestReads parses the bridge package for every function taking an ActionRequest,
+// recording the fields it reads off that parameter and the functions it hands the whole
+// request to.
+func bridgeRequestReads(t *testing.T) (reads map[string]map[string]bool, calls map[string]map[string]bool) {
+ t.Helper()
+
+ reads = map[string]map[string]bool{}
+ calls = map[string]map[string]bool{}
+
+ dir := filepath.Join("..", "bridge")
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("ReadDir(%s): %v", dir, err)
+ }
+ parsed := 0
+ for _, entry := range entries {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ parsed++
+ file := parseGoFile(t, filepath.Join(dir, name))
+ for _, decl := range file.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ param := actionRequestParamName(fn)
+ if param == "" {
+ continue
+ }
+ reads[fn.Name.Name] = map[string]bool{}
+ calls[fn.Name.Name] = map[string]bool{}
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ switch node := n.(type) {
+ case *ast.SelectorExpr:
+ if isIdent(node.X, param) {
+ reads[fn.Name.Name][node.Sel.Name] = true
+ }
+ case *ast.CallExpr:
+ for _, arg := range node.Args {
+ if isRequestArg(arg, param) {
+ calls[fn.Name.Name][calleeName(node.Fun)] = true
+ }
+ }
+ }
+ return true
+ })
+ }
+ }
+ if parsed == 0 {
+ t.Fatalf("no non-test Go files parsed from %s", dir)
+ }
+ return reads, calls
+}
+
+func actionRequestParamName(fn *ast.FuncDecl) string {
+ if fn.Type.Params == nil {
+ return ""
+ }
+ for _, field := range fn.Type.Params.List {
+ if !isActionRequestType(field.Type) || len(field.Names) == 0 {
+ continue
+ }
+ return field.Names[0].Name
+ }
+ return ""
+}
+
+func isActionRequestType(expr ast.Expr) bool {
+ switch t := expr.(type) {
+ case *ast.Ident:
+ return t.Name == "ActionRequest"
+ case *ast.StarExpr:
+ return isActionRequestType(t.X)
+ }
+ return false
+}
+
+func isRequestArg(arg ast.Expr, param string) bool {
+ switch a := arg.(type) {
+ case *ast.Ident:
+ return a.Name == param
+ case *ast.UnaryExpr:
+ return isIdent(a.X, param)
+ }
+ return false
+}
+
+func calleeName(fun ast.Expr) string {
+ switch f := fun.(type) {
+ case *ast.Ident:
+ return f.Name
+ case *ast.SelectorExpr:
+ return f.Sel.Name
+ }
+ return ""
+}
+
+// methodName turns a bound method value from the registry back into its declared name, so
+// the census follows the registry instead of a second list of action functions.
+func methodName(fn bridge.ActionFunc) string {
+ full := runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name()
+ full = strings.TrimSuffix(full, "-fm")
+ if at := strings.LastIndex(full, "."); at >= 0 {
+ return full[at+1:]
+ }
+ return full
+}
+
+func readByAnyDispatchableKind(readsByKind map[string]map[string]bool, kinds []string, field string) bool {
+ for _, kind := range kinds {
+ if readsByKind[kind][field] {
+ return true
+ }
+ }
+ return false
+}
+
+func anyKindPosts(keysByKind map[string]payloadCase, key string) bool {
+ for _, entry := range keysByKind {
+ for _, posted := range entry.keys {
+ if posted == key {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+func parseGoFile(t *testing.T, path string) *ast.File {
+ t.Helper()
+ file, err := parser.ParseFile(token.NewFileSet(), path, nil, 0)
+ if err != nil {
+ t.Fatalf("ParseFile(%s): %v", path, err)
+ }
+ return file
+}
+
+func isIdent(expr ast.Expr, name string) bool {
+ ident, ok := expr.(*ast.Ident)
+ return ok && ident.Name == name
+}
+
+func stringLit(expr ast.Expr) (string, bool) {
+ lit, ok := expr.(*ast.BasicLit)
+ if !ok || lit.Kind != token.STRING {
+ return "", false
+ }
+ value, err := strconv.Unquote(lit.Value)
+ if err != nil {
+ return "", false
+ }
+ return value, true
+}
+
+func sortedKeys(m map[string]payloadCase) []string {
+ out := make([]string, 0, len(m))
+ for key := range m {
+ out = append(out, key)
+ }
+ sort.Strings(out)
+ return out
+}
diff --git a/internal/mcp/handlers_interaction.go b/internal/mcp/handlers_interaction.go
index aa40594b..97579c57 100644
--- a/internal/mcp/handlers_interaction.go
+++ b/internal/mcp/handlers_interaction.go
@@ -192,7 +192,10 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequ
if value == "" {
return mcp.NewToolResultError("required parameter 'value' is missing"), nil
}
- payload["value"] = value
+ // "text" is the field actionFill reads. Posting the same string under "value"
+ // reached a real ActionRequest field that fill ignores, so the write was empty
+ // and the tool still answered filled:true.
+ payload["text"] = value
}
body, code, err := c.Post(ctx, routedPathWithBody(r, "/action", payload), payload)
diff --git a/internal/mcp/handlers_interaction_test.go b/internal/mcp/handlers_interaction_test.go
index 84f550df..8738f0e2 100644
--- a/internal/mcp/handlers_interaction_test.go
+++ b/internal/mcp/handlers_interaction_test.go
@@ -466,3 +466,55 @@ func TestCoordinatesReachTheWireOnlyForTheToolsThatDeclareThem(t *testing.T) {
})
}
}
+
+// pinchtab_fill posted the caller's string under "value", a real ActionRequest field that
+// actionFill does not read, so the write was empty and the tool answered filled:true with
+// len:0. The tool surface is the only place this is visible — the bridge action was always
+// correct, and no unit test at that layer could see it.
+func TestHandleFillForwardsTheFieldTheFillActionReads(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_fill", map[string]any{
+ "ref": "e0",
+ "value": "FILLED",
+ }, srv)
+
+ body, _ := resultJSON(t, r)["body"].(map[string]any)
+ if got, _ := body["text"].(string); got != "FILLED" {
+ t.Fatalf("forwarded text = %q, want the caller's value; payload was %v", got, body)
+ }
+ if _, leftover := body["value"]; leftover {
+ t.Errorf("payload still carries a value key that fill ignores: %v", body)
+ }
+}
+
+// The discriminator: two tools, the same client argument name, and opposite consumers —
+// actionSelect reads Value, actionFill reads Text. Both must post to the field their own
+// action reads, which is what a shared "value" key silently got wrong for one of them.
+func TestFillAndSelectEachPostToTheFieldTheirActionReads(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ fill, _ := resultJSON(t, callTool(t, "pinchtab_fill", map[string]any{"ref": "e0", "value": "ZZZ"}, srv))["body"].(map[string]any)
+ sel, _ := resultJSON(t, callTool(t, "pinchtab_select", map[string]any{"ref": "e1", "value": "y"}, srv))["body"].(map[string]any)
+
+ if got, _ := fill["text"].(string); got != "ZZZ" {
+ t.Errorf("fill payload = %v, want text=ZZZ", fill)
+ }
+ if got, _ := sel["value"].(string); got != "y" {
+ t.Errorf("select payload = %v, want value=y", sel)
+ }
+}
+
+// The other spelling still works, since the tool has always accepted both.
+func TestHandleFillAcceptsTheTextSpellingToo(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_fill", map[string]any{"ref": "e0", "text": "FROM_TEXT"}, srv)
+ body, _ := resultJSON(t, r)["body"].(map[string]any)
+ if got, _ := body["text"].(string); got != "FROM_TEXT" {
+ t.Fatalf("forwarded text = %q, want FROM_TEXT; payload was %v", got, body)
+ }
+}