Skip to content

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

fix(cli): nav/click --snap captures the snapshot's vocab token so a following ref action is not falsely 409'd (PIN-417)

Luigi Agosti0b421a11afad
diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.go
index 3ce97f09..c14bd0ca 100644
--- a/internal/cli/actions/actions_element.go
+++ b/internal/cli/actions/actions_element.go
@@ -141,7 +141,7 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C
snap, _ := cmd.Flags().GetBool("snap")
snapDiff, _ := cmd.Flags().GetBool("snap-diff")
if snap || snapDiff {
- fetchAndPrintSnapshot(client, base, token, tabID, snapDiff)
+ fetchAndPrintSnapshot(client, base, token, tabID, snapDiff, tabID == "")
}
text, _ := cmd.Flags().GetBool("text")
@@ -150,7 +150,7 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.C
}
}
-func fetchAndPrintSnapshot(client *http.Client, base, token, tabID string, diff bool) {
+func fetchAndPrintSnapshot(client *http.Client, base, token, tabID string, diff, implicit bool) {
params := "filter=interactive&format=compact"
if diff {
params += "&diff=true"
@@ -158,7 +158,7 @@ func fetchAndPrintSnapshot(client *http.Client, base, token, tabID string, diff
if tabID != "" {
params += "&tabId=" + tabID
}
- apiclient.DoGetRawAndPrint(client, base, token, "/snapshot?"+params)
+ apiclient.DoGetRawAndPrintCapturingVocab(client, base, token, "/snapshot?"+params, implicit)
}
func fetchAndPrintText(client *http.Client, base, token, tabID string) {
diff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.go
index fca42d97..c817cc7f 100644
--- a/internal/cli/actions/actions_navigate.go
+++ b/internal/cli/actions/actions_navigate.go
@@ -59,12 +59,18 @@ func historyNav(client *http.Client, base, token, action string, cmd *cobra.Comm
printPostActionOutput(client, base, token, tabID, cmd)
}
-// printPostActionOutput runs the shared --snap / --snap-diff / --text tail.
+// printPostActionOutput runs the shared --snap / --snap-diff / --text tail. The
+// snapshot is fetched for the resolved tabID, but the vocabulary token it returns
+// is filed as the CURRENT tab's only when the user named no --tab, so a later
+// implicit ref action (the common nav --snap then fill e0 flow) echoes it — the
+// resolved id is always non-empty here and keying implicit on it would never set
+// the current pointer.
func printPostActionOutput(client *http.Client, base, token, tabID string, cmd *cobra.Command) {
snap, _ := cmd.Flags().GetBool("snap")
snapDiff, _ := cmd.Flags().GetBool("snap-diff")
if snap || snapDiff {
- fetchAndPrintSnapshot(client, base, token, tabID, snapDiff)
+ userTab, _ := cmd.Flags().GetString("tab")
+ fetchAndPrintSnapshot(client, base, token, tabID, snapDiff, userTab == "")
}
if text, _ := cmd.Flags().GetBool("text"); text {
fetchAndPrintText(client, base, token, tabID)
diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.go
index 41379181..ff9ff93a 100644
--- a/internal/cli/apiclient/client.go
+++ b/internal/cli/apiclient/client.go
@@ -186,10 +186,17 @@ func DoGetRawCapturingVocab(client *http.Client, base, token, path string, param
return body
}
-// DoGetRawAndPrint fetches and prints the raw response body (for --snap flag).
-// Best-effort: it reports errors to stderr but does not exit.
-func DoGetRawAndPrint(client *http.Client, base, token, pathWithQuery string) {
- status, body, err := doRequest(client, token, request{method: "GET", url: base + pathWithQuery})
+// DoGetRawAndPrintCapturingVocab fetches and prints the raw snapshot body (for the
+// --snap / --snap-diff tail) and, on success, persists the response's vocabulary
+// token keyed by the resolved tab (implicit when the caller named no tab), so a ref
+// the snapshot printed can be acted on without a re-snapshot and without a false
+// 409. It stays best-effort — a transport or HTTP failure warns on stderr and
+// returns, never exits (unlike DoGetRawCapturingVocab, which calls exitOnAPIError):
+// 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})
if err != nil {
fmt.Fprintf(os.Stderr, "snapshot failed: %v\n", err)
return
@@ -198,6 +205,7 @@ func DoGetRawAndPrint(client *http.Client, base, token, pathWithQuery string) {
fmt.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))
}
diff --git a/internal/cli/apiclient/client_test.go b/internal/cli/apiclient/client_test.go
new file mode 100644
index 00000000..b07a8c54
--- /dev/null
+++ b/internal/cli/apiclient/client_test.go
@@ -0,0 +1,210 @@
+package apiclient_test
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/cli/actions"
+ "github.com/pinchtab/pinchtab/internal/cli/apiclient"
+ "github.com/spf13/cobra"
+)
+
+// epochServer models a server whose ref vocabulary is renumbered (a fresh token
+// minted) whenever the tab navigates. /navigate and /action bump the epoch; every
+// /snapshot returns the token of the CURRENT epoch. It records the token the last
+// action echoed so a test can see whether a ref action sent the latest snapshot's
+// token or a stale one the server would refuse 409.
+type epochServer struct {
+ mu sync.Mutex
+ tab string
+ epoch int
+ snapStatus int // >=400 makes /snapshot fail, to pin best-effort behaviour
+ lastVocab string
+ hadVocab bool
+ httpServer *httptest.Server
+}
+
+func newEpochServer(tab string) *epochServer {
+ s := &epochServer{tab: tab, epoch: 1}
+ s.httpServer = httptest.NewServer(http.HandlerFunc(s.handle))
+ return s
+}
+
+func (s *epochServer) token() string {
+ return s.tab + "-e" + itoa(s.epoch)
+}
+
+func itoa(n int) string {
+ if n == 0 {
+ return "0"
+ }
+ var b []byte
+ for n > 0 {
+ b = append([]byte{byte('0' + n%10)}, b...)
+ n /= 10
+ }
+ return string(b)
+}
+
+func (s *epochServer) handle(w http.ResponseWriter, r *http.Request) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/snapshot":
+ if s.snapStatus >= 400 {
+ w.WriteHeader(s.snapStatus)
+ _, _ = w.Write([]byte("snapshot blew up"))
+ return
+ }
+ w.Header().Set("X-PinchTab-Tab-Id", s.tab)
+ w.Header().Set("X-PinchTab-Vocab", s.token())
+ _, _ = w.Write([]byte("e0 button \"Go\"\n"))
+ case r.URL.Path == "/navigate":
+ s.epoch++ // navigation renumbers refs, minting a fresh token
+ _, _ = w.Write([]byte(`{"tabId":"` + s.tab + `","url":"http://example.test"}`))
+ default: // an action (/action or /tabs/<id>/action)
+ body, _ := io.ReadAll(r.Body)
+ var decoded map[string]any
+ _ = json.Unmarshal(body, &decoded)
+ s.lastVocab, s.hadVocab = "", false
+ if v, ok := decoded["vocab"].(string); ok {
+ s.lastVocab, s.hadVocab = v, true
+ }
+ s.epoch++ // the action changed the page, renumbering refs as a navigation would
+ _, _ = w.Write([]byte(`{"success":true}`))
+ }
+}
+
+// navCmd builds a command carrying the flags Navigate reads, so a test can drive
+// the real nav --snap / --snap-diff tail.
+func navCmd(tab string, snap, snapDiff bool) *cobra.Command {
+ cmd := &cobra.Command{}
+ cmd.Flags().String("tab", "", "")
+ cmd.Flags().Float64("timeout", 0, "")
+ for _, name := range []string{"new-tab", "block-images", "block-ads", "dismiss-banners", "json", "snap", "snap-diff", "text", "print-tab-id"} {
+ cmd.Flags().Bool(name, false, "")
+ }
+ if tab != "" {
+ _ = cmd.Flags().Set("tab", tab)
+ }
+ if snap {
+ _ = cmd.Flags().Set("snap", "true")
+ }
+ if snapDiff {
+ _ = cmd.Flags().Set("snap-diff", "true")
+ }
+ return cmd
+}
+
+// actionCmd builds a command carrying the flags an element action reads.
+func actionCmd(tab string, snap bool) *cobra.Command {
+ cmd := &cobra.Command{}
+ cmd.Flags().String("tab", "", "")
+ for _, name := range []string{"json", "snap", "snap-diff", "text"} {
+ cmd.Flags().Bool(name, false, "")
+ }
+ if tab != "" {
+ _ = cmd.Flags().Set("tab", tab)
+ }
+ if snap {
+ _ = cmd.Flags().Set("snap", "true")
+ }
+ return cmd
+}
+
+// AC-1: after `nav <url> --snap`, a ref action on a printed ref echoes the token
+// the post-nav snapshot returned — not the token of an earlier snapshot that the
+// navigation superseded. An earlier implicit snapshot files X-e1; the navigate
+// bumps the epoch to 2 and nav --snap fetches X-e2; the following implicit action
+// must echo X-e2. On HEAD the --snap tail discarded the token, so the action echoed
+// the stale X-e1 the server refuses 409.
+func TestNavSnapCapturesTokenSoNextActionIsNotRefused(t *testing.T) {
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+ srv := newEpochServer("X")
+ defer srv.httpServer.Close()
+ base, client := srv.httpServer.URL, srv.httpServer.Client()
+
+ actions.Snapshot(client, base, "", snapshotOnlyCmd(""), "") // files X-e1, current=X
+ actions.Navigate(client, base, "", "http://example.test", navCmd("", true, false))
+ actions.Action(client, base, "", "fill", "e0", actionCmd("", false))
+
+ if !srv.hadVocab {
+ t.Fatal("the action after nav --snap sent no token; a superseded ref would be resolved positionally")
+ }
+ if srv.lastVocab != "X-e2" {
+ t.Fatalf("action echoed %q, want X-e2 (the token nav --snap returned); X-e1 is the stale pre-nav token the server 409s", srv.lastVocab)
+ }
+}
+
+// AC-3: --snap-diff captures identically to --snap.
+func TestNavSnapDiffCapturesTokenToo(t *testing.T) {
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+ srv := newEpochServer("X")
+ defer srv.httpServer.Close()
+ base, client := srv.httpServer.URL, srv.httpServer.Client()
+
+ actions.Snapshot(client, base, "", snapshotOnlyCmd(""), "")
+ actions.Navigate(client, base, "", "http://example.test", navCmd("", false, true))
+ actions.Action(client, base, "", "fill", "e0", actionCmd("", false))
+
+ if srv.lastVocab != "X-e2" {
+ t.Fatalf("action after nav --snap-diff echoed %q, want X-e2", srv.lastVocab)
+ }
+}
+
+// AC-2: the post-action --snap tail captures the new token when the action itself
+// changed the epoch, so the NEXT ref action is not refused either. The click bumps
+// the epoch to 2 and its --snap tail fetches X-e2; the following action echoes X-e2.
+func TestPostActionSnapCapturesTheNewToken(t *testing.T) {
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+ srv := newEpochServer("X")
+ defer srv.httpServer.Close()
+ base, client := srv.httpServer.URL, srv.httpServer.Client()
+
+ actions.Snapshot(client, base, "", snapshotOnlyCmd(""), "") // files X-e1, current=X
+ actions.Action(client, base, "", "click", "e0", actionCmd("", true))
+ actions.Action(client, base, "", "fill", "e0", actionCmd("", false))
+
+ if srv.lastVocab != "X-e2" {
+ t.Fatalf("the second action echoed %q, want X-e2 (captured by the first click's --snap tail)", srv.lastVocab)
+ }
+}
+
+// The review note's floor: when the trailing snapshot fails, the tail stays
+// best-effort — it warns and returns rather than exiting the process, so an action
+// that already succeeded is not turned into a non-zero exit. A capture helper that
+// called exitOnAPIError here would terminate the test binary before this assertion.
+func TestSnapTailDoesNotExitWhenSnapshotFails(t *testing.T) {
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+ srv := newEpochServer("X")
+ srv.snapStatus = 500
+ defer srv.httpServer.Close()
+ base, client := srv.httpServer.URL, srv.httpServer.Client()
+
+ apiclient.DoGetRawAndPrintCapturingVocab(client, base, "", "/snapshot?filter=interactive&format=compact", true)
+
+ if tok := apiclient.VocabTokenFor(base, "X"); tok != "" {
+ t.Fatalf("a failed snapshot stored a token %q; nothing should be captured from a non-2xx", tok)
+ }
+}
+
+// snapshotOnlyCmd carries just the flags actions.Snapshot reads.
+func snapshotOnlyCmd(tab string) *cobra.Command {
+ cmd := &cobra.Command{}
+ cmd.Flags().String("tab", "", "")
+ cmd.Flags().String("selector", "", "")
+ cmd.Flags().String("max-tokens", "", "")
+ cmd.Flags().String("depth", "", "")
+ for _, name := range []string{"full", "interactive", "diff", "text", "json", "compact"} {
+ cmd.Flags().Bool(name, false, "")
+ }
+ if tab != "" {
+ _ = cmd.Flags().Set("tab", tab)
+ }
+ return cmd
+}