Skip to content

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

fix(vocab): batch /actions, /macro and semantic selectors on element reads re-epoch refs without publishing X-PinchTab-Vocab, so the next ref action 409s vocab_superseded (PIN-433)

Luigi Agostia1f679f132c6
diff --git a/internal/handlers/action_vocab_test.go b/internal/handlers/action_vocab_test.go
index 79a0348d..1a242997 100644
--- a/internal/handlers/action_vocab_test.go
+++ b/internal/handlers/action_vocab_test.go
@@ -8,7 +8,9 @@ import (
"go/token"
"net/http"
"net/http/httptest"
+ "path"
"path/filepath"
+ "strconv"
"strings"
"testing"
"time"
@@ -285,6 +287,107 @@ func TestEveryReEpochSitePublishesTheVocabularyOnItsResponse(t *testing.T) {
t.Errorf("%s sets the vocab header directly; publication goes through publishVocab so every publisher also names the tab the token belongs to", file)
}
}
+
+ graph := handlerCallGraph(t, files)
+ reEpochs := []string{"bridge.EpochRefs", "refreshRefCache"}
+ reachingHandlers := 0
+ for name := range graph.handlers {
+ if !graph.reaches(name, reEpochs...) {
+ continue
+ }
+ reachingHandlers++
+ if !graph.reaches(name, publishHelpers...) {
+ t.Errorf("%s can re-epoch a tab's refs (%s) but its response never reaches a vocab publish helper, so the client's next ref action is refused vocab_superseded", name, strings.Join(graph.pathTo(name, reEpochs...), " -> "))
+ }
+ }
+ if reachingHandlers < 20 {
+ t.Errorf("only %d handlers reach a re-epoch site; the call graph has lost the semantic-selector paths (count, attr, actions, macro …)", reachingHandlers)
+ }
+}
+
+type packageCallGraph struct {
+ refs map[string]map[string]bool
+ handlers map[string]bool
+}
+
+func handlerCallGraph(t *testing.T, files []string) packageCallGraph {
+ t.Helper()
+ g := packageCallGraph{refs: map[string]map[string]bool{}, handlers: map[string]bool{}}
+ for _, file := range files {
+ if strings.HasSuffix(file, "_test.go") {
+ continue
+ }
+ f := parseHandlerFile(t, file)
+ imported := map[string]bool{}
+ for _, spec := range f.Imports {
+ p, _ := strconv.Unquote(spec.Path.Value)
+ name := path.Base(p)
+ if spec.Name != nil {
+ name = spec.Name.Name
+ }
+ imported[name] = true
+ }
+ for _, decl := range f.Decls {
+ fd, ok := decl.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ name := fd.Name.Name
+ if fd.Recv != nil && strings.HasPrefix(name, "Handle") {
+ g.handlers[name] = true
+ }
+ if g.refs[name] == nil {
+ g.refs[name] = map[string]bool{}
+ }
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ switch x := n.(type) {
+ case *ast.SelectorExpr:
+ if id, ok := x.X.(*ast.Ident); ok && imported[id.Name] {
+ g.refs[name][id.Name+"."+x.Sel.Name] = true
+ } else {
+ g.refs[name][x.Sel.Name] = true
+ }
+ case *ast.CallExpr:
+ fun := x.Fun
+ if ix, ok := fun.(*ast.IndexExpr); ok {
+ fun = ix.X
+ }
+ if id, ok := fun.(*ast.Ident); ok {
+ g.refs[name][id.Name] = true
+ }
+ }
+ return true
+ })
+ }
+ }
+ return g
+}
+
+func (g packageCallGraph) reaches(from string, targets ...string) bool {
+ return g.pathTo(from, targets...) != nil
+}
+
+func (g packageCallGraph) pathTo(from string, targets ...string) []string {
+ seen := map[string]bool{from: true}
+ var walk func(string) []string
+ walk = func(name string) []string {
+ for _, target := range targets {
+ if name == target {
+ return []string{name}
+ }
+ }
+ for next := range g.refs[name] {
+ if seen[next] {
+ continue
+ }
+ seen[next] = true
+ if rest := walk(next); rest != nil {
+ return append([]string{name}, rest...)
+ }
+ }
+ return nil
+ }
+ return walk(from)
}
func fileCallsAnyIdent(t *testing.T, name string, idents ...string) bool {
@@ -442,3 +545,75 @@ func TestFindPublishesTheVocabularyItsAutoRefreshMinted(t *testing.T) {
t.Errorf("tab header = %q, want tab1 so a client keys the token to the resolved tab", got)
}
}
+
+func TestAMultiStepRunThatReEpochsTheTabPublishesTheNewVocabulary(t *testing.T) {
+ for _, surface := range []struct {
+ name string
+ path string
+ body string
+ serve func(*Handlers) http.HandlerFunc
+ }{
+ {"batch", "/actions", `{"tabId":"tab1","actions":[{"kind":"click","x":10,"y":20}]}`, func(h *Handlers) http.HandlerFunc { return h.HandleActions }},
+ {"macro", "/macro", `{"tabId":"tab1","steps":[{"kind":"click","x":10,"y":20}]}`, func(h *Handlers) http.HandlerFunc { return h.HandleMacro }},
+ } {
+ for _, tc := range []struct {
+ name string
+ next *bridge.RefCache
+ want string
+ }{
+ {"re-epoched", &bridge.RefCache{DomEpoch: "fresh"}, "fresh"},
+ {"untouched", nil, ""},
+ } {
+ t.Run(surface.name+"/"+tc.name, func(t *testing.T) {
+ mb := &reepochingVocabBridge{
+ vocabMockBridge: vocabMockBridge{
+ mockBridge: mockBridge{availableActions: []string{bridge.ActionClick}},
+ refCache: &bridge.RefCache{DomEpoch: "current"},
+ },
+ next: tc.next,
+ }
+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second, AllowMacro: true}, nil, nil, nil)
+ w := httptest.NewRecorder()
+ surface.serve(h)(w, httptest.NewRequest("POST", surface.path, strings.NewReader(surface.body)))
+ if !mb.executeCalled {
+ t.Fatalf("the step did not reach ExecuteAction (status %d): %s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get(vocabHeader); got != tc.want {
+ t.Errorf("vocab header = %q, want %q", got, tc.want)
+ }
+ if tc.want != "" && w.Header().Get(activity.HeaderPTTabID) != "tab1" {
+ t.Errorf("tab header = %q, want tab1 so a client keys the token to the tab", w.Header().Get(activity.HeaderPTTabID))
+ }
+ })
+ }
+ }
+}
+
+func TestASemanticElementReadPublishesOnlyTheVocabularyItsResolutionMinted(t *testing.T) {
+ fresh := &bridge.RefCache{
+ DomEpoch: "ep_fresh",
+ Nodes: []bridge.A11yNode{{Ref: "e11", Role: "link", Name: "Go page 2"}},
+ Refs: map[string]int64{"e11": 11},
+ }
+ for _, tc := range []struct {
+ name string
+ bridge bridge.BridgeAPI
+ want string
+ }{
+ {"auto-refreshed", &autoRefreshFindBridge{fresh: fresh}, "ep_fresh"},
+ {"cache already current", &findMockBridge{refCache: fresh}, ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ h := New(tc.bridge, &config.RuntimeConfig{ActionTimeout: 10 * time.Second}, nil, nil, nil)
+ h.Matcher = semantic.NewLexicalMatcher()
+ w := httptest.NewRecorder()
+ h.HandleCount(w, httptest.NewRequest("GET", "/count?selector=find:Go%20page%202", nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())
+ }
+ if got := w.Header().Get(vocabHeader); got != tc.want {
+ t.Errorf("vocab header = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
index 90411b1c..9db88e36 100644
--- a/internal/handlers/actions.go
+++ b/internal/handlers/actions.go
@@ -882,6 +882,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
continue
}
}
+ run.enterTab(resolvedTabID, h.tabVocab(resolvedTabID))
if _, ok := h.applyTabGuards(w, r, ctx, resolvedTabID, guardDomainPolicy); !ok {
return
}
@@ -902,6 +903,7 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, re
}
batchRoute := routeMetadataFor(routing)
+ h.publishMultiStepVocab(w, run, resolvedTabID)
h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, run.results, len(req.Actions), batchRoute, nil)
}
@@ -927,10 +929,23 @@ type multiStepRun struct {
results []actionResult
stopOnError bool
stopped bool
+ vocabBefore map[string]string
}
func newMultiStepRun(steps int, stopOnError bool) *multiStepRun {
- return &multiStepRun{results: make([]actionResult, 0, steps), stopOnError: stopOnError}
+ return &multiStepRun{results: make([]actionResult, 0, steps), stopOnError: stopOnError, vocabBefore: map[string]string{}}
+}
+
+func (m *multiStepRun) enterTab(tabID, vocab string) {
+ if _, seen := m.vocabBefore[tabID]; !seen {
+ m.vocabBefore[tabID] = vocab
+ }
+}
+
+func (h *Handlers) publishMultiStepVocab(w http.ResponseWriter, run *multiStepRun, tabID string) {
+ if before, seen := run.vocabBefore[tabID]; seen {
+ h.publishVocabIfReepoched(w, tabID, before)
+ }
}
func (m *multiStepRun) record(result actionResult) {
@@ -1140,6 +1155,7 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
if step.TabID == "" {
step.TabID = resolvedTabID
}
+ run.enterTab(resolvedTabID, h.tabVocab(resolvedTabID))
if _, ok := h.applyTabGuards(w, r, ctx, resolvedTabID, guardDomainPolicy); !ok {
return
}
@@ -1175,5 +1191,6 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {
EffectiveCfg: macroEffectiveCfg,
Decision: macroHandleDecision,
})
+ h.publishMultiStepVocab(w, run, resolvedTabID)
h.writeMultiStepActionResult(w, r, ctx, resolvedTabID, run.results, len(req.Steps), macroRoute, map[string]any{"kind": "macro"})
}
diff --git a/internal/handlers/frame.go b/internal/handlers/frame.go
index 47b80f75..8c32f13f 100644
--- a/internal/handlers/frame.go
+++ b/internal/handlers/frame.go
@@ -433,7 +433,9 @@ func (h *Handlers) HandleFrame(w http.ResponseWriter, r *http.Request) {
defer cancel()
go httpx.CancelOnClientDone(r.Context(), cancel)
+ vocabBefore := h.tabVocab(resolvedTabID)
scope, resetToMain, err := h.resolveFrameScope(tCtx, resolvedTabID, req.Target)
+ h.publishVocabIfReepoched(w, resolvedTabID, vocabBefore)
if err != nil {
httpx.Error(w, 400, err)
return
diff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.go
index 2b0f78d2..d0bb97b3 100644
--- a/internal/handlers/inspect.go
+++ b/internal/handlers/inspect.go
@@ -90,7 +90,9 @@ func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind in
targetFrameID := h.resolveTargetFrameID(r, resolvedTabID)
+ vocabBefore := h.tabVocab(resolvedTabID)
payload, err := h.inspectPayload(tCtx, resolvedTabID, targetFrameID, r.URL.Query().Get("selector"), r.URL.Query().Get("ref"), kind)
+ h.publishVocabIfReepoched(w, resolvedTabID, vocabBefore)
if err != nil {
respondSelectorFailure(w, err)
return
diff --git a/internal/handlers/inspect_lifecycle.go b/internal/handlers/inspect_lifecycle.go
index 03aae650..e0b120b8 100644
--- a/internal/handlers/inspect_lifecycle.go
+++ b/internal/handlers/inspect_lifecycle.go
@@ -102,7 +102,9 @@ func (h *Handlers) inspectElement(w http.ResponseWriter, r *http.Request, tabID
defer tCancel()
go httpx.CancelOnClientDone(r.Context(), tCancel)
+ vocabBefore := h.tabVocab(resolvedTabID)
result, err := fn(tCtx, resolvedTabID)
+ h.publishVocabIfReepoched(w, resolvedTabID, vocabBefore)
if err != nil {
respondSelectorFailure(w, err)
return
diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.go
index 46ce57c8..e3b5cb67 100644
--- a/internal/handlers/screenshot.go
+++ b/internal/handlers/screenshot.go
@@ -89,7 +89,9 @@ func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
return
}
+ vocabBefore := h.tabVocab(resolvedTabID)
clip, clipErr := h.resolveScreenshotClip(tCtx, resolvedTabID, req.selector)
+ h.publishVocabIfReepoched(w, resolvedTabID, vocabBefore)
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
diff --git a/tests/e2e/config/pinchtab.json b/tests/e2e/config/pinchtab.json
index 131bbc5b..cc882028 100644
--- a/tests/e2e/config/pinchtab.json
+++ b/tests/e2e/config/pinchtab.json
@@ -44,6 +44,7 @@
"allowClipboard": true,
"allowStateExport": true,
"allowMemory": true,
+ "allowMacro": true,
"allowedDomains": [
"localhost",
"127.0.0.1",
diff --git a/tests/e2e/scenarios/api/vocab-reepoch-basic.sh b/tests/e2e/scenarios/api/vocab-reepoch-basic.sh
index 6e21ad5c..c2ba1804 100755
--- a/tests/e2e/scenarios/api/vocab-reepoch-basic.sh
+++ b/tests/e2e/scenarios/api/vocab-reepoch-basic.sh
@@ -2,8 +2,9 @@
# vocab-reepoch-basic.sh — every response that re-epochs a tab's ref cache
# publishes the new vocabulary token (X-PinchTab-Vocab) and the tab it belongs
# to (X-PinchTab-Tab-Id): /find, /tabs/{id}/find, /annotate,
-# /screenshot?annotate and an action whose semantic selector refreshed the
-# cache. The published token is the one the tab's next /snapshot reports, an
+# /screenshot?annotate, an action, batch or macro whose semantic selector
+# refreshed the cache, and a semantic element read. A response that did not
+# re-epoch publishes nothing. The published token is the one the tab's next /snapshot reports, an
# action echoing it is accepted, and a stale one is refused 409.
GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -131,3 +132,71 @@ fi
assert_token_is_live "$TOKEN" "$REF" "semantic hover"
end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "vocab: POST /actions whose semantic step refreshed the cache publishes the token"
+
+fresh_page
+vocab_request POST /actions -d '{"actions":[{"kind":"hover","selector":"semantic:Increment"}]}'
+assert_ok "batch hover semantic:Increment"
+assert_json_eq "$RESULT" '.successful' '1' "the semantic batch step succeeded"
+assert_published "semantic batch"
+TOKEN="$HDR_VOCAB"
+vocab_request POST /find -d '{"query":"Increment"}'
+assert_token_is_live "$TOKEN" "$(echo "$RESULT" | jq -r '.best_ref')" "semantic batch"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "vocab: POST /macro whose semantic step refreshed the cache publishes the token"
+
+fresh_page
+vocab_request POST /macro -d '{"steps":[{"kind":"hover","selector":"semantic:Increment"}]}'
+assert_ok "macro hover semantic:Increment"
+assert_json_eq "$RESULT" '.successful' '1' "the semantic macro step succeeded"
+assert_published "semantic macro"
+TOKEN="$HDR_VOCAB"
+vocab_request POST /find -d '{"query":"Increment"}'
+assert_token_is_live "$TOKEN" "$(echo "$RESULT" | jq -r '.best_ref')" "semantic macro"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "vocab: a semantic element read publishes only the token its resolution minted"
+
+fresh_page
+vocab_request GET "/count?selector=semantic:Increment"
+assert_ok "count semantic:Increment"
+assert_published "semantic /count"
+TOKEN="$HDR_VOCAB"
+
+vocab_request GET "/attr?selector=semantic:Increment&name=id"
+assert_ok "attr semantic:Increment on the now-current vocabulary"
+assert_json_eq "$RESULT" '.value' 'increment' "attr resolved the Increment button"
+if [ -z "$HDR_VOCAB" ]; then
+ pass_assert "a semantic /attr that did not re-epoch publishes no token"
+else
+ fail_assert "a semantic /attr that did not re-epoch published '$HDR_VOCAB'"
+fi
+
+vocab_request POST /find -d '{"query":"Increment"}'
+assert_token_is_live "$TOKEN" "$(echo "$RESULT" | jq -r '.best_ref')" "semantic count"
+
+end_test
+
+# ─────────────────────────────────────────────────────────────────
+start_test "vocab: a batch that did not re-epoch publishes no token"
+
+fresh_page
+vocab_request GET "/snapshot?filter=interactive"
+assert_ok "snapshot"
+TOKEN="$HDR_VOCAB"
+vocab_request POST /actions -d '{"actions":[{"kind":"hover","selector":"semantic:Increment"}]}'
+assert_ok "batch hover on the snapshotted vocabulary"
+if [ -z "$HDR_VOCAB" ]; then
+ pass_assert "a batch on an unchanged vocabulary publishes no token"
+else
+ fail_assert "a batch on an unchanged vocabulary published '$HDR_VOCAB' (snapshot token '$TOKEN')"
+fi
+
+end_test