High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: CLI persists each snapshot's vocabulary token per tab and echoes it on the next action (PIN-084)
Luigi Agosti3fcf58802d22
diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex 27e85fe4..63cc8733 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -121,6 +121,12 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.Cpath = "/tabs/" + tabID + "/action"}+ if _, ok := body["vocab"]; !ok {+ if tok := apiclient.VocabTokenFor(base, tabID); tok != "" {+ body["vocab"] = tok+ }+ }+jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {apiclient.DoPostWithHeaders(client, base, token, path, body, headers)diff --git a/internal/cli/actions/actions_snapshot.go b/internal/cli/actions/actions_snapshot.goindex 52aacc92..b6c899c0 100644--- a/internal/cli/actions/actions_snapshot.go+++ b/internal/cli/actions/actions_snapshot.go@@ -39,6 +39,6 @@ func Snapshot(client *http.Client, base, token string, cmd *cobra.Command, selecif v, _ := cmd.Flags().GetString("tab"); v != "" {params.Set("tabId", v)}- result := apiclient.DoGet(client, base, token, "/snapshot", params)+ result := apiclient.DoGetCapturingVocab(client, base, token, "/snapshot", params, params.Get("tabId"))apiclient.SuggestNextAction("snapshot", result)}diff --git a/internal/cli/actions/vocab_echo_test.go b/internal/cli/actions/vocab_echo_test.gonew file mode 100644index 00000000..0f07689c--- /dev/null+++ b/internal/cli/actions/vocab_echo_test.go@@ -0,0 +1,106 @@+package actions++import (+ "encoding/json"+ "io"+ "net/http"+ "net/http/httptest"+ "testing"+)++// vocabEchoServer stamps a vocabulary token on every /snapshot response and records+// the last /action body so a test can read back what the interaction sent.+func vocabEchoServer(t *testing.T, token string, lastActionBody *string) *httptest.Server {+ t.Helper()+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path == "/snapshot" {+ w.Header().Set("X-PinchTab-Vocab", token)+ _, _ = w.Write([]byte(`{"status":"ok"}`))+ return+ }+ body, _ := io.ReadAll(r.Body)+ *lastActionBody = string(body)+ _, _ = w.Write([]byte(`{"status":"ok","success":true}`))+ }))+ t.Cleanup(srv.Close)+ return srv+}++func actionBodyVocab(t *testing.T, raw string) (string, bool) {+ t.Helper()+ var body map[string]any+ if err := json.Unmarshal([]byte(raw), &body); err != nil {+ t.Fatalf("action body was not JSON: %v (%q)", err, raw)+ }+ v, ok := body["vocab"]+ if !ok {+ return "", false+ }+ s, _ := v.(string)+ return s, true+}++// A snapshot's vocabulary token is persisted and echoed on the next CLI action for the+// same tab, across the two separate process-like invocations, so the server can refuse+// a ref a later snapshot has renumbered rather than clicking the wrong node. The token+// rides in the response header because the CLI's default snapshot is compact text, which+// has no JSON body to carry it.+func TestCLISnapshotVocabTokenIsEchoedOnTheNextAction(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ var lastActionBody string+ srv := vocabEchoServer(t, "cli-tok-1", &lastActionBody)+ client := srv.Client()++ snap := newSnapshotCmd()+ _ = snap.Flags().Set("tab", "t1")+ Snapshot(client, srv.URL, "", snap, "")++ act := newActionCmd()+ _ = act.Flags().Set("tab", "t1")+ Action(client, srv.URL, "", "click", "e5", act)++ got, ok := actionBodyVocab(t, lastActionBody)+ if !ok {+ t.Fatal("the CLI action carried no vocab token, so a superseded ref would still be mis-resolved")+ }+ if got != "cli-tok-1" {+ t.Errorf("action echoed vocab %q, want the token the snapshot returned", got)+ }+}++// Absence: without a prior snapshot there is nothing to echo, so the action stays+// unchanged — the token is optional and no existing flow gains a spurious refusal.+func TestCLIActionWithoutAPriorSnapshotSendsNoToken(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ var lastActionBody string+ srv := vocabEchoServer(t, "cli-tok-1", &lastActionBody)++ act := newActionCmd()+ _ = act.Flags().Set("tab", "t1")+ Action(srv.Client(), srv.URL, "", "click", "e5", act)++ if got, ok := actionBodyVocab(t, lastActionBody); ok {+ t.Errorf("an action with no prior snapshot echoed a token %q", got)+ }+}++// The token is stored per tab, so a snapshot of one tab does not attach its vocabulary to+// an action on another — that would refuse the second tab's valid refs.+func TestCLIEchoedTokenIsScopedToItsTab(t *testing.T) {+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ var lastActionBody string+ srv := vocabEchoServer(t, "cli-tok-1", &lastActionBody)+ client := srv.Client()++ snap := newSnapshotCmd()+ _ = snap.Flags().Set("tab", "t1")+ Snapshot(client, srv.URL, "", snap, "")++ act := newActionCmd()+ _ = act.Flags().Set("tab", "t2")+ Action(client, srv.URL, "", "click", "e5", act)++ if got, ok := actionBodyVocab(t, lastActionBody); ok {+ t.Errorf("an action on t2 echoed t1's vocabulary token %q", got)+ }+}diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 2c2dd7b3..c28dff6e 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -6,10 +6,77 @@ import ("net/http""net/url""os"+ "path/filepath""strings""time")+const vocabHeader = "X-PinchTab-Vocab"++// DoGetCapturingVocab performs a GET like DoGet and, on success, persists the+// response's vocabulary token for (base, tabKey) so a later action on that tab+// echoes it and a ref renumbered by an intervening snapshot is refused rather+// than mis-resolved. The token 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, tabKey string) 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, tabKey, headers.Get(vocabHeader))+ return printAndDecode(body)+}++// VocabTokenFor returns the last vocabulary token stored for (base, tabKey), or "".+func VocabTokenFor(base, tabKey string) string {+ data, err := os.ReadFile(vocabTokenPath(base, tabKey))+ if err != nil {+ return ""+ }+ return strings.TrimSpace(string(data))+}++func storeVocabToken(base, tabKey, token string) {+ if token == "" {+ return+ }+ path := vocabTokenPath(base, tabKey)+ _ = os.MkdirAll(filepath.Dir(path), 0755)+ _ = os.WriteFile(path, []byte(token+"\n"), 0644)+}++func vocabTokenPath(base, tabKey string) string {+ dir := os.Getenv("XDG_STATE_HOME")+ if dir != "" {+ dir += "/pinchtab"+ } else if home, err := os.UserHomeDir(); err == nil {+ dir = home + "/.local/state/pinchtab"+ } else {+ dir = "/tmp/pinchtab"+ }+ key := tabKey+ if key == "" {+ key = "default"+ }+ return filepath.Join(dir, "vocab-"+fileSlug(base)+"-"+fileSlug(key))+}++func fileSlug(s string) string {+ s = strings.TrimPrefix(strings.TrimPrefix(s, "http://"), "https://")+ s = strings.Map(func(r rune) rune {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '.', r == '-':+ return r+ default:+ return '-'+ }+ }, strings.Trim(s, "/"))+ if s == "" {+ return "default"+ }+ return s+}+// doAndRender runs the request with the standard fatal-on-transport-error +// exit-on-HTTP-error policy, then pretty-prints and decodes the body.func doAndRender(client *http.Client, token string, r request) map[string]any {diff --git a/internal/cli/apiclient/transport.go b/internal/cli/apiclient/transport.goindex 391266f6..5c00ced1 100644--- a/internal/cli/apiclient/transport.go+++ b/internal/cli/apiclient/transport.go@@ -17,6 +17,10 @@ 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}func buildURL(base, path string, params url.Values) string {@@ -49,6 +53,9 @@ 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+ }body, _ := io.ReadAll(resp.Body)return resp.StatusCode, body, nil}