High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(find): find, annotate, annotated screenshots and re-epoching actions publish the ref vocabulary through one helper, and the CLI and MCP capture it, so find then click on a fresh page no longer 409s vocab_superseded (PIN-424)
Luigi Agosti36c405c7c6e3
diff --git a/internal/cli/actions/actions_annotate.go b/internal/cli/actions/actions_annotate.goindex f64f688c..4f382d2e 100644--- a/internal/cli/actions/actions_annotate.go+++ b/internal/cli/actions/actions_annotate.go@@ -32,7 +32,7 @@ func Annotate(client *http.Client, base, token string, cmd *cobra.Command) {return}- raw := apiclient.DoGetRaw(client, base, token, "/annotate", params)+ raw := apiclient.DoGetRaw(client, base, token, "/annotate", params, apiclient.CaptureVocab(params.Get("tabId") == ""))if raw == nil {return}diff --git a/internal/cli/actions/actions_capture.go b/internal/cli/actions/actions_capture.goindex d1711e00..be846968 100644--- a/internal/cli/actions/actions_capture.go+++ b/internal/cli/actions/actions_capture.go@@ -74,7 +74,7 @@ func Capture(client *http.Client, base, token string, cmd *cobra.Command) {params.Set("tabId", v)}- raw := apiclient.DoGetRaw(client, base, token, "/capture", params)+ raw := apiclient.DoGetRaw(client, base, token, "/capture", params, apiclient.CaptureVocab(params.Get("tabId") == ""))if raw == nil {return}diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex c14bd0ca..ba49d23d 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -128,13 +128,14 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C}}+ capture := apiclient.CaptureVocab(tabID == "")jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {- apiclient.DoPostWithHeaders(client, base, token, path, body, headers)+ apiclient.DoPostWithHeaders(client, base, token, path, body, headers, capture)return}- result := apiclient.DoPostQuietWithHeaders(client, base, token, path, body, headers)+ result := apiclient.DoPostQuietWithHeaders(client, base, token, path, body, headers, capture)kind, _ := body["kind"].(string)printActionResult(kind, result)diff --git a/internal/cli/actions/actions_find.go b/internal/cli/actions/actions_find.goindex 80bade3e..ed710d74 100644--- a/internal/cli/actions/actions_find.go+++ b/internal/cli/actions/actions_find.go@@ -42,9 +42,10 @@ func Find(client *http.Client, base, token string, query string, cmd *cobra.Commif tabID != "" {path = "/tabs/" + tabID + "/find"}+ capture := apiclient.CaptureVocab(tabID == "")if refOnly {- result := apiclient.DoPostQuiet(client, base, token, path, body)+ result := apiclient.DoPostQuiet(client, base, token, path, body, capture)if ref, ok := result["best_ref"].(string); ok && ref != "" {fmt.Println(ref)return@@ -53,12 +54,12 @@ func Find(client *http.Client, base, token string, query string, cmd *cobra.Comm}if jsonOutput {- apiclient.DoPost(client, base, token, path, body)+ apiclient.DoPost(client, base, token, path, body, capture)return}// Terse: one line per match: <ref>\t<role>\t"<name>"- result := apiclient.DoPostQuiet(client, base, token, path, body)+ result := apiclient.DoPostQuiet(client, base, token, path, body, capture)matches, ok := result["matches"].([]any)if !ok || len(matches) == 0 {// Single result formatdiff --git a/internal/cli/actions/actions_screenshot.go b/internal/cli/actions/actions_screenshot.goindex df41c340..e52cc647 100644--- a/internal/cli/actions/actions_screenshot.go+++ b/internal/cli/actions/actions_screenshot.go@@ -72,7 +72,7 @@ func Screenshot(client *http.Client, base, token string, cmd *cobra.Command) {if annotate {params.Set("annotate", "true")- raw := apiclient.DoGetRaw(client, base, token, "/screenshot", params)+ raw := apiclient.DoGetRaw(client, base, token, "/screenshot", params, apiclient.CaptureVocab(params.Get("tabId") == ""))if raw == nil {return}diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex ff9ff93a..06f47284 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -42,12 +42,7 @@ type vocabStore struct {// is delivered as a response header so it survives every snapshot format,// including the compact text the CLI defaults to.func DoGetCapturingVocab(client *http.Client, base, token, path string, params url.Values, implicit bool) map[string]any {- var headers http.Header- r := request{method: "GET", url: buildURL(base, path, params), respHeaders: &headers}- status, body := mustRequest(client, token, r)- exitOnAPIError(r, status, body)- storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader), implicit)- return printAndDecode(body)+ return DoGet(client, base, token, path, params, CaptureVocab(implicit))}// VocabForAction returns the tab id to tag and the token to echo for an action.@@ -160,12 +155,12 @@ func doAndRender(client *http.Client, token string, r request) map[string]any {return printAndDecode(body)}-func DoGet(client *http.Client, base, token, path string, params url.Values) map[string]any {- return doAndRender(client, token, request{method: "GET", url: buildURL(base, path, params)})+func DoGet(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) map[string]any {+ return doAndRender(client, token, newRequest("GET", base, buildURL(base, path, params), nil, nil, opts))}-func DoGetRaw(client *http.Client, base, token, path string, params url.Values) []byte {- r := request{method: "GET", url: buildURL(base, path, params)}+func DoGetRaw(client *http.Client, base, token, path string, params url.Values, opts ...RequestOption) []byte {+ r := newRequest("GET", base, buildURL(base, path, params), nil, nil, opts)status, body := mustRequest(client, token, r)exitOnAPIError(r, status, body)return body@@ -178,12 +173,7 @@ func DoGetRaw(client *http.Client, base, token, path string, params url.Values)// ref cache, so an action on a returned ref would be refused 409 against a stale// token if the CLI never captured the fresh one.func DoGetRawCapturingVocab(client *http.Client, base, token, path string, params url.Values, implicit bool) []byte {- var headers http.Header- r := request{method: "GET", url: buildURL(base, path, params), respHeaders: &headers}- status, body := mustRequest(client, token, r)- exitOnAPIError(r, status, body)- storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader), implicit)- return body+ return DoGetRaw(client, base, token, path, params, CaptureVocab(implicit))}// DoGetRawAndPrintCapturingVocab fetches and prints the raw snapshot body (for the@@ -195,8 +185,7 @@ func DoGetRawCapturingVocab(client *http.Client, base, token, path string, param// this tail runs after an action that already succeeded, so a cosmetic snapshot// failure must not turn a successful action into a non-zero exit.func DoGetRawAndPrintCapturingVocab(client *http.Client, base, token, pathWithQuery string, implicit bool) {- var headers http.Header- status, body, err := doRequest(client, token, request{method: "GET", url: base + pathWithQuery, respHeaders: &headers})+ status, body, err := doRequest(client, token, newRequest("GET", base, base+pathWithQuery, nil, nil, []RequestOption{CaptureVocab(implicit)}))if err != nil {fmt.Fprintf(os.Stderr, "snapshot failed: %v\n", err)return@@ -205,19 +194,18 @@ func DoGetRawAndPrintCapturingVocab(client *http.Client, base, token, pathWithQufmt.Fprintf(os.Stderr, "snapshot error %d: %s\n", status, string(body))return}- storeVocabToken(base, headers.Get(vocabTabIDHeader), headers.Get(vocabHeader), implicit)fmt.Println(string(body))}-func DoPost(client *http.Client, base, token, path string, body map[string]any) map[string]any {- return DoPostWithHeaders(client, base, token, path, body, nil)+func DoPost(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) map[string]any {+ return DoPostWithHeaders(client, base, token, path, body, nil, opts...)}// DoPostQuiet is like DoPost but does not print the response body. Callers are// responsible for rendering whatever output is appropriate (e.g. a single// field for machine-friendly piping).-func DoPostQuiet(client *http.Client, base, token, path string, body map[string]any) map[string]any {- return DoPostQuietWithHeaders(client, base, token, path, body, nil)+func DoPostQuiet(client *http.Client, base, token, path string, body map[string]any, opts ...RequestOption) map[string]any {+ return DoPostQuietWithHeaders(client, base, token, path, body, nil, opts...)}// DoPostRaw sends a POST and returns the raw response body without printing.@@ -262,14 +250,14 @@ func DoPostQuietWithStatus(client *http.Client, base, token, path string, body m}// DoPostQuietWithHeaders is like DoPostQuiet but allows custom headers.-func DoPostQuietWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) map[string]any {- statusCode, respBody, result := doPostQuietWithStatus(client, base, token, path, body, headers)+func DoPostQuietWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) map[string]any {+ statusCode, respBody, result := doPostQuietWithStatus(client, base, token, path, body, headers, opts...)exitOnAPIError(request{method: "POST", url: base + path, body: body, headers: headers}, statusCode, respBody)return result}-func doPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) (int, []byte, map[string]any) {- status, respBody := mustRequest(client, token, request{method: "POST", url: base + path, body: body, headers: headers})+func doPostQuietWithStatus(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) (int, []byte, map[string]any) {+ status, respBody := mustRequest(client, token, newRequest("POST", base, base+path, body, headers, opts))var result map[string]anyif status < 400 {@@ -280,8 +268,8 @@ func doPostQuietWithStatus(client *http.Client, base, token, path string, body mreturn status, respBody, result}-func DoPostWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string) map[string]any {- return doAndRender(client, token, request{method: "POST", url: base + path, body: body, headers: headers})+func DoPostWithHeaders(client *http.Client, base, token, path string, body map[string]any, headers map[string]string, opts ...RequestOption) map[string]any {+ return doAndRender(client, token, newRequest("POST", base, base+path, body, headers, opts))}// DoDelete sends a DELETE request with an optional JSON body (e.g. for ?name= query params, pass nil body and handle params in path).diff --git a/internal/cli/apiclient/transport.go b/internal/cli/apiclient/transport.goindex eb2e12e4..6b96ca9d 100644--- a/internal/cli/apiclient/transport.go+++ b/internal/cli/apiclient/transport.go@@ -20,10 +20,26 @@ type request struct {url stringbody map[string]anyheaders map[string]string- // respHeaders, when non-nil, receives the response headers so a caller can- // read one (the vocabulary token) without changing doRequest's return shape,- // which mustRequest and the other verbs share.- respHeaders *http.Header+ base string+ vocab *vocabCapture+}++type vocabCapture struct {+ implicit bool+}++type RequestOption func(*request)++func CaptureVocab(implicit bool) RequestOption {+ return func(r *request) { r.vocab = &vocabCapture{implicit: implicit} }+}++func newRequest(method, base, url string, body map[string]any, headers map[string]string, opts []RequestOption) request {+ r := request{method: method, url: url, body: body, headers: headers, base: base}+ for _, opt := range opts {+ opt(&r)+ }+ return r}func buildURL(base, path string, params url.Values) string {@@ -62,9 +78,6 @@ func doRequest(client *http.Client, token string, r request) (int, []byte, errorreturn 0, nil, err}defer func() { _ = resp.Body.Close() }()- if r.respHeaders != nil {- *r.respHeaders = resp.Header- }// A short read is a failed request, never a body: a connection dropping// mid-response would otherwise reach the caller as a fragment carrying its// status, and the CLI would parse or print the fragment as the answer.@@ -72,6 +85,9 @@ func doRequest(client *http.Client, token string, r request) (int, []byte, errorif err != nil {return resp.StatusCode, nil, fmt.Errorf("read response from %s: %w", r.url, err)}+ if r.vocab != nil && resp.StatusCode < http.StatusBadRequest {+ storeVocabToken(r.base, resp.Header.Get(vocabTabIDHeader), resp.Header.Get(vocabHeader), r.vocab.implicit)+ }return resp.StatusCode, body, nil}diff --git a/internal/cli/apiclient/transport_test.go b/internal/cli/apiclient/transport_test.goindex cba1195f..1551a7e8 100644--- a/internal/cli/apiclient/transport_test.go+++ b/internal/cli/apiclient/transport_test.go@@ -94,3 +94,32 @@ func TestAnUnbuildableRequestFailsBeforeTheWire(t *testing.T) {})}}++func TestCaptureVocabStoresOnlyASuccessfulResponsesToken(t *testing.T) {+ for _, tc := range []struct {+ name string+ status int+ want string+ }{+ {"success", http.StatusOK, "ep_new"},+ {"refused", http.StatusConflict, ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set(vocabTabIDHeader, "tab1")+ w.Header().Set(vocabHeader, "ep_new")+ w.WriteHeader(tc.status)+ }))+ defer srv.Close()++ r := newRequest(http.MethodPost, srv.URL, srv.URL+"/find", map[string]any{"query": "x"}, nil, []RequestOption{CaptureVocab(true)})+ if _, _, err := doRequest(srv.Client(), "", r); err != nil {+ t.Fatal(err)+ }+ if got := VocabTokenFor(srv.URL, "tab1"); got != tc.want {+ t.Errorf("stored token = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/internal/cli/apiclient/vocab_test.go b/internal/cli/apiclient/vocab_test.goindex 7c0769e7..03126ae9 100644--- a/internal/cli/apiclient/vocab_test.go+++ b/internal/cli/apiclient/vocab_test.go@@ -8,6 +8,7 @@ import ("net/http/httptest""os""path/filepath"+ "strings""sync""testing"@@ -66,6 +67,17 @@ func (s *vocabServer) handle(w http.ResponseWriter, r *http.Request) {return}+ if r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/find") {+ resolved := s.current+ if tab := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/tabs/"), "/find"); tab != "" {+ resolved = tab+ }+ w.Header().Set("X-PinchTab-Tab-Id", resolved)+ w.Header().Set("X-PinchTab-Vocab", s.tokenFor(resolved))+ _, _ = w.Write([]byte(`{"best_ref":"e11","matches":[]}`))+ return+ }+body, _ := io.ReadAll(r.Body)var decoded map[string]any_ = json.Unmarshal(body, &decoded)@@ -144,6 +156,51 @@ func TestImplicitClickSendsTheCurrentTabsTaggedToken(t *testing.T) {}}+func findCmd(tab string, flag string) *cobra.Command {+ cmd := &cobra.Command{}+ cmd.Flags().String("tab", "", "")+ cmd.Flags().String("threshold", "", "")+ cmd.Flags().Bool("explain", false, "")+ cmd.Flags().Bool("ref-only", false, "")+ cmd.Flags().Bool("json", false, "")+ if tab != "" {+ _ = cmd.Flags().Set("tab", tab)+ }+ if flag != "" {+ _ = cmd.Flags().Set(flag, "true")+ }+ return cmd+}++func TestFindCapturesTheVocabularyItMintedSoTheNextClickEchoesIt(t *testing.T) {+ for _, tc := range []struct {+ name string+ tab string+ flag string+ }{+ {"ref-only", "", "ref-only"},+ {"json", "", "json"},+ {"terse", "", ""},+ {"explicit tab", "X", "ref-only"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ srv := newVocabServer("X")+ defer srv.httpServer.Close()+ base, client := srv.httpServer.URL, srv.httpServer.Client()++ actions.Snapshot(client, base, "", snapCmd(tc.tab), "")+ srv.bumpEpoch("X")+ actions.Find(client, base, "", "Go page 2", findCmd(tc.tab, tc.flag))+ actions.Action(client, base, "", "click", "e11", clickCmd(tc.tab))++ if srv.lastVocab != "X-e2" || srv.lastVocabTab != "X" {+ t.Fatalf("click after find sent vocab %q tagged %q, want the token find published (X-e2) tagged X", srv.lastVocab, srv.lastVocabTab)+ }+ })+ }+}+// AC-3: the per-tab files are replaced by one bounded file per server, written// 0600, holding at most the N most recent tabs plus the current pointer.func TestVocabStoreIsOneBoundedFilePerServer(t *testing.T) {diff --git a/internal/handlers/a11y_axe.go b/internal/handlers/a11y_axe.goindex 687e81fd..c837818a 100644--- a/internal/handlers/a11y_axe.go+++ b/internal/handlers/a11y_axe.go@@ -44,7 +44,7 @@ func (h *Handlers) runAxeAudit(w http.ResponseWriter, r *http.Request, tCtx contreport := audit.BuildAxeReport(raw, assets.AxeVersion, includeIncomplete)vocab := h.fillAxeRefs(tCtx, resolvedTabID, &report)- w.Header().Set(vocabHeader, vocab)+ publishVocab(w, resolvedTabID, vocab)httpx.JSON(w, 200, struct {TabID string `json:"tabId"`diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.goindex 12f5bbfc..d2bf8632 100644--- a/internal/handlers/action_execution.go+++ b/internal/handlers/action_execution.go@@ -4,9 +4,11 @@ import ("context""errors""fmt"+ "net/http""strings""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/selector"@@ -445,6 +447,33 @@ func (h *Handlers) refreshRefCache(ctx context.Context, tabID string) {h.Bridge.SetRefCache(tabID, bridge.EpochRefs(h.Bridge.GetRefCache(tabID), flat))}+func publishVocab(w http.ResponseWriter, tabID, vocab string) {+ if vocab == "" {+ return+ }+ if tabID != "" {+ w.Header().Set(activity.HeaderPTTabID, tabID)+ }+ w.Header().Set(vocabHeader, vocab)+}++func (h *Handlers) tabVocab(tabID string) string {+ if cache := h.Bridge.GetRefCache(tabID); cache != nil {+ return cache.DomEpoch+ }+ return ""+}++func (h *Handlers) publishTabVocab(w http.ResponseWriter, tabID string) {+ publishVocab(w, tabID, h.tabVocab(tabID))+}++func (h *Handlers) publishVocabIfReepoched(w http.ResponseWriter, tabID, before string) {+ if vocab := h.tabVocab(tabID); vocab != before {+ publishVocab(w, tabID, vocab)+ }+}+func isTimeoutWithPendingDialog(err error, tabID string, b bridge.BridgeAPI) bool {if err == nil {return falsediff --git a/internal/handlers/action_vocab_test.go b/internal/handlers/action_vocab_test.goindex d1855f2e..79a0348d 100644--- a/internal/handlers/action_vocab_test.go+++ b/internal/handlers/action_vocab_test.go@@ -8,12 +8,15 @@ import ("go/token""net/http""net/http/httptest"+ "path/filepath""strings""testing""time"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/semantic")type vocabMockBridge struct {@@ -226,31 +229,80 @@ func TestEveryRefPublishSiteRoutesThroughTheEpochRefBook(t *testing.T) {}}- if !fileMentionsIdent(t, "snapshot.go", "vocabHeader") {+ if !fileCallsAnyIdent(t, "snapshot.go", "publishVocab") {t.Error("snapshot.go does not emit the token in a response header, so a client reading a compact/text snapshot cannot obtain it")}if !fileMentionsString(t, "snapshot.go", "vocabularyToken") {t.Error("snapshot.go does not carry the token in its JSON body, so a JSON snapshot consumer cannot echo it")}- if !fileMentionsIdent(t, "capture.go", "vocabHeader") {+ if !fileCallsAnyIdent(t, "capture.go", "publishVocab") {t.Error("capture.go does not emit the token in a response header, so a /capture client cannot obtain it uniformly with /snapshot")}}-func parseHandlerFile(t *testing.T, name string) *ast.File {- t.Helper()- f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0)+func TestEveryReEpochSitePublishesTheVocabularyOnItsResponse(t *testing.T) {+ publishers := map[string][]string{+ "snapshot.go": {"snapshot.go"},+ "capture.go": {"capture.go"},+ "extract.go": {"extract.go"},+ "a11y_axe.go": {"a11y_axe.go"},+ "find.go": {"find.go", "actions.go"},+ "screenshot_annotate.go": {"screenshot.go", "annotate.go"},+ "action_execution.go": {"actions.go"},+ "handlers.go": {"actions.go"},+ "actions.go": {"actions.go"},+ }+ publishHelpers := []string{"publishVocab", "publishTabVocab", "publishVocabIfReepoched"}++ files, err := filepath.Glob("*.go")if err != nil {- t.Fatalf("parse %s: %v", name, err)+ t.Fatal(err)+ }+ for _, file := range files {+ if strings.HasSuffix(file, "_test.go") {+ continue+ }+ if !fileCallsSelector(t, file, "EpochRefs") && !fileCallsSelector(t, file, "refreshRefCache") {+ continue+ }+ answering, ok := publishers[file]+ if !ok {+ t.Errorf("%s re-epochs a tab's refs but no response is recorded as publishing the vocabulary for it; publish through publishVocab and add a row", file)+ continue+ }+ for _, pub := range answering {+ if !fileCallsAnyIdent(t, pub, publishHelpers...) {+ t.Errorf("%s answers for the re-epoch in %s but never calls a vocab publish helper, so its response leaves the client echoing a superseded token", pub, file)+ }+ }+ }++ for _, file := range files {+ if strings.HasSuffix(file, "_test.go") || file == "action_execution.go" {+ continue+ }+ if fileSetsHeader(t, file, "vocabHeader") {+ t.Errorf("%s sets the vocab header directly; publication goes through publishVocab so every publisher also names the tab the token belongs to", file)+ }}- return f}-func fileCallsSelector(t *testing.T, name, sel string) bool {+func fileCallsAnyIdent(t *testing.T, name string, idents ...string) bool {found := falseast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {- if call, ok := n.(*ast.CallExpr); ok {- if se, ok := call.Fun.(*ast.SelectorExpr); ok && se.Sel.Name == sel {+ call, ok := n.(*ast.CallExpr)+ if !ok {+ return true+ }+ var got string+ switch fn := call.Fun.(type) {+ case *ast.Ident:+ got = fn.Name+ case *ast.SelectorExpr:+ got = fn.Sel.Name+ }+ for _, id := range idents {+ if got == id {found = true}}@@ -259,10 +311,17 @@ func fileCallsSelector(t *testing.T, name, sel string) bool {return found}-func fileMentionsIdent(t *testing.T, name, ident string) bool {+func fileSetsHeader(t *testing.T, name, headerIdent string) bool {found := falseast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {- if id, ok := n.(*ast.Ident); ok && id.Name == ident {+ call, ok := n.(*ast.CallExpr)+ if !ok || len(call.Args) == 0 {+ return true+ }+ if se, ok := call.Fun.(*ast.SelectorExpr); !ok || se.Sel.Name != "Set" {+ return true+ }+ if id, ok := call.Args[0].(*ast.Ident); ok && id.Name == headerIdent {found = true}return true@@ -270,6 +329,28 @@ func fileMentionsIdent(t *testing.T, name, ident string) bool {return found}+func parseHandlerFile(t *testing.T, name string) *ast.File {+ t.Helper()+ f, err := parser.ParseFile(token.NewFileSet(), name, nil, 0)+ if err != nil {+ t.Fatalf("parse %s: %v", name, err)+ }+ return f+}++func fileCallsSelector(t *testing.T, name, sel string) bool {+ found := false+ ast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {+ if call, ok := n.(*ast.CallExpr); ok {+ if se, ok := call.Fun.(*ast.SelectorExpr); ok && se.Sel.Name == sel {+ found = true+ }+ }+ return true+ })+ return found+}+func fileMentionsString(t *testing.T, name, lit string) bool {found := falseast.Inspect(parseHandlerFile(t, name), func(n ast.Node) bool {@@ -280,3 +361,84 @@ func fileMentionsString(t *testing.T, name, lit string) bool {})return found}++type reepochingVocabBridge struct {+ vocabMockBridge+ next *bridge.RefCache+}++func (m *reepochingVocabBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {+ if m.next != nil {+ m.refCache = m.next+ }+ return m.vocabMockBridge.ExecuteAction(ctx, kind, req)+}++func TestAnActionThatReEpochsTheTabPublishesTheNewVocabulary(t *testing.T) {+ for _, tc := range []struct {+ name string+ next *bridge.RefCache+ want string+ }{+ {"re-epoched", &bridge.RefCache{DomEpoch: "fresh"}, "fresh"},+ {"untouched", nil, ""},+ } {+ t.Run(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}, nil, nil, nil)+ w, _ := postVocabAction(h, `{"kind":"click","x":10,"y":20,"tabId":"tab1"}`, "")+ if !mb.executeCalled {+ t.Fatalf("the action 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)+ }+ })+ }+}++type autoRefreshFindBridge struct {+ findMockBridge+ fresh *bridge.RefCache+ reads int+}++func (m *autoRefreshFindBridge) GetRefCache(string) *bridge.RefCache {+ m.reads+++ if m.reads == 1 {+ return nil+ }+ return m.fresh+}++func TestFindPublishesTheVocabularyItsAutoRefreshMinted(t *testing.T) {+ mb := &autoRefreshFindBridge{fresh: &bridge.RefCache{+ DomEpoch: "ep_fresh",+ Nodes: []bridge.A11yNode{{Ref: "e11", Role: "link", Name: "Go page 2"}},+ Refs: map[string]int64{"e11": 11},+ }}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: 10 * time.Second}, nil, nil, nil)+ h.Matcher = semantic.NewLexicalMatcher()++ w := httptest.NewRecorder()+ h.HandleFind(w, httptest.NewRequest("POST", "/find", strings.NewReader(`{"query":"Go page 2"}`)))++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d: %s", w.Code, w.Body.String())+ }+ if mb.reads < 2 {+ t.Fatalf("find read the ref cache %d time(s); the auto-refresh path was not taken", mb.reads)+ }+ if got := w.Header().Get(vocabHeader); got != "ep_fresh" {+ t.Errorf("vocab header = %q, want the token the refresh minted", got)+ }+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab1" {+ t.Errorf("tab header = %q, want tab1 so a client keys the token to the resolved tab", got)+ }+}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex dc8d3286..90411b1c 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -588,6 +588,8 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {}}+ vocabBefore := h.tabVocab(resolvedTabID)+actionTimeout := effectiveCfg.ActionTimeoutif r.Method == http.MethodGet {if v := r.URL.Query().Get("timeout"); v != "" {@@ -671,6 +673,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {}result, actionBackend, recoveryResult, actionErr := h.executeActionResilient(tCtx, &req, effectiveCfg, resolvedTabID, refMissing)+ h.publishVocabIfReepoched(w, resolvedTabID, vocabBefore)submitTimeoutWithDialog := submitClick && isTimeoutWithPendingDialog(actionErr, resolvedTabID, h.Bridge)if submitClick && !submitTimeoutWithDialog && (actionErr == nil || errors.Is(actionErr, context.DeadlineExceeded)) {actionTimedOut := errors.Is(actionErr, context.DeadlineExceeded)diff --git a/internal/handlers/annotate.go b/internal/handlers/annotate.goindex acfbd0a6..ef6d34de 100644--- a/internal/handlers/annotate.go+++ b/internal/handlers/annotate.go@@ -59,6 +59,7 @@ func (h *Handlers) HandleAnnotate(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 500, fmt.Errorf("annotate: %w", err))return}+ h.publishTabVocab(w, resolvedTabID)if err := cdptk.InjectInteractiveOverlay(tCtx, items); err != nil {httpx.Error(w, 500, fmt.Errorf("annotate inject: %w", err))returndiff --git a/internal/handlers/capture.go b/internal/handlers/capture.goindex a9c19c01..08cddd2a 100644--- a/internal/handlers/capture.go+++ b/internal/handlers/capture.go@@ -174,7 +174,7 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {cache := bridge.EpochRefs(h.Bridge.GetRefCache(resolvedTabID), result.Nodes)h.Bridge.SetRefCache(resolvedTabID, cache)- w.Header().Set(vocabHeader, cache.DomEpoch)+ publishVocab(w, resolvedTabID, cache.DomEpoch)imageInfo := map[string]any{"format": result.ImageFormat,diff --git a/internal/handlers/extract.go b/internal/handlers/extract.goindex 6886cb0c..e6636771 100644--- a/internal/handlers/extract.go+++ b/internal/handlers/extract.go@@ -95,7 +95,7 @@ func (h *Handlers) acquireExtractNodes(w http.ResponseWriter, ctx context.Contex}cache := bridge.EpochRefs(h.Bridge.GetRefCache(tabID), result.Nodes)h.Bridge.SetRefCache(tabID, cache)- w.Header().Set(vocabHeader, cache.DomEpoch)+ publishVocab(w, tabID, cache.DomEpoch)return result.Nodes, nil}diff --git a/internal/handlers/find.go b/internal/handlers/find.goindex eddfbf7f..0810e985 100644--- a/internal/handlers/find.go+++ b/internal/handlers/find.go@@ -85,6 +85,7 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {httpx.Error(w, serr.status, serr.err)return}+ h.publishTabVocab(w, resolvedTabID)descs := semanticDescriptorsFromNodes(nodes)diff --git a/internal/handlers/screenshot.go b/internal/handlers/screenshot.goindex 1dbb1a1b..46ce57c8 100644--- a/internal/handlers/screenshot.go+++ b/internal/handlers/screenshot.go@@ -169,6 +169,7 @@ func (h *Handlers) serveAnnotatedScreenshot(w http.ResponseWriter, ctx context.Chttpx.Error(w, 500, fmt.Errorf("annotate: %w", err))return}+ h.publishTabVocab(w, tabID)if req.raw {writeRawImage(w, img, imageContentType(outFormat), "annotated screenshot write")returndiff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex d97ac842..9d268989 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -237,7 +237,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {cache := bridge.EpochRefs(prev, flat)h.Bridge.SetRefCache(resolvedTabID, cache)- w.Header().Set(vocabHeader, cache.DomEpoch)+ publishVocab(w, resolvedTabID, cache.DomEpoch)h.recordResolvedURL(r, url)diff --git a/internal/mcp/client.go b/internal/mcp/client.goindex b5d4ab7d..ab2da977 100644--- a/internal/mcp/client.go+++ b/internal/mcp/client.go@@ -203,20 +203,40 @@ func (c *Client) Delete(ctx context.Context, path string, query url.Values) ([]b// Post performs a POST request with a JSON body.func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, int, error) {+ req, err := c.newPostRequest(ctx, path, payload)+ if err != nil {+ return nil, 0, err+ }+ return c.do(req)+}++func (c *Client) PostCapturingVocab(ctx context.Context, path string, payload any, tabKey string) ([]byte, int, error) {+ req, err := c.newPostRequest(ctx, path, payload)+ if err != nil {+ return nil, 0, err+ }+ body, code, hdr, err := c.doWithHeaders(req)+ if err == nil && code < 400 {+ c.vocab.set(tabKey, hdr.Get(vocabHeader))+ }+ return body, code, err+}++func (c *Client) newPostRequest(ctx context.Context, path string, payload any) (*http.Request, error) {var body io.Readerif payload != nil {b, err := json.Marshal(payload)if err != nil {- return nil, 0, fmt.Errorf("marshal payload: %w", err)+ return nil, fmt.Errorf("marshal payload: %w", err)}body = bytes.NewReader(b)}req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url(path), body)if err != nil {- return nil, 0, err+ return nil, err}if payload != nil {req.Header.Set("Content-Type", "application/json")}- return c.do(req)+ return req, nil}diff --git a/internal/mcp/handlers_content.go b/internal/mcp/handlers_content.goindex 6c6b73d4..41ef01f6 100644--- a/internal/mcp/handlers_content.go+++ b/internal/mcp/handlers_content.go@@ -53,10 +53,11 @@ func handleFind(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.Callreturn mcp.NewToolResultError(err.Error()), nil}payload := map[string]any{"query": query}- if tabID := optString(r, "tabId"); tabID != "" {+ tabID := optString(r, "tabId")+ if tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/find", payload)+ body, code, err := c.PostCapturingVocab(ctx, "/find", payload, tabID)if err != nil {return mcp.NewToolResultError(err.Error()), nil}diff --git a/internal/mcp/vocab_echo_test.go b/internal/mcp/vocab_echo_test.goindex e8cd2ed6..7ca9902d 100644--- a/internal/mcp/vocab_echo_test.go+++ b/internal/mcp/vocab_echo_test.go@@ -112,6 +112,43 @@ func TestTheEchoedTokenIsScopedToItsTab(t *testing.T) {}}+func TestFindStoresTheVocabularyItsResponseCarriesSoTheNextClickEchoesIt(t *testing.T) {+ for _, tabID := range []string{"t1", ""} {+ t.Run("tab="+tabID, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/find" {+ w.Header().Set(vocabHeader, "vocab-find")+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{"best_ref":"e11","matches":[]}`))+ return+ }+ body, _ := io.ReadAll(r.Body)+ var parsed map[string]any+ _ = json.Unmarshal(body, &parsed)+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{"path": r.URL.Path, "body": parsed})+ }))+ defer srv.Close()+ c := NewClient(srv.URL, "")++ args := map[string]any{"query": "Go page 2"}+ clickArgs := map[string]any{"ref": "e11"}+ if tabID != "" {+ args["tabId"] = tabID+ clickArgs["tabId"] = tabID+ }+ callSharedTool(t, c, "pinchtab_find", args)+ if got := c.VocabToken(tabID); got != "vocab-find" {+ t.Fatalf("store holds %q for tab %q after find, want the token find returned", got, tabID)+ }+ got, ok := actionVocabSent(t, callSharedTool(t, c, "pinchtab_click", clickArgs))+ if !ok || got != "vocab-find" {+ t.Errorf("click after find echoed vocab %q (sent=%v), want vocab-find", got, ok)+ }+ })+ }+}+// rotatingVocabServer hands out a fresh token on each /snapshot and records the// query every snapshot request carried, so a test can see both which token the// client kept and which instance it asked.