High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: a stale current-tab cache breaks reads and actions after a server restart (PIN-073)
Luigi Agosti27e37abdea27
diff --git a/cmd/pinchtab/cmd_cli_current_tab_test.go b/cmd/pinchtab/cmd_cli_current_tab_test.goindex 13b1c078..364b9a0d 100644--- a/cmd/pinchtab/cmd_cli_current_tab_test.go+++ b/cmd/pinchtab/cmd_cli_current_tab_test.go@@ -1,6 +1,10 @@package mainimport (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath""testing""github.com/spf13/cobra"@@ -46,6 +50,19 @@ func TestDefaultTabFlagFromStateOnlyForAnonymousCallers(t *testing.T) {t.Setenv("PINCHTAB_AGENT_ID", "")t.Setenv("PINCHTAB_SESSION", "")cliAgentID = ""++ // Pin the endpoint the probe resolves. Without this the probe reaches whatever+ // server the developer's own config points at, asks it about "tab-local", is+ // correctly told no such tab, and clears the cache — so this test would assert+ // flag-filling policy while measuring the machine.+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)+ oldResolve := resolveTabStateEndpoint+ resolveTabStateEndpoint = func() (string, string) { return srv.URL, "" }+ t.Cleanup(func() { resolveTabStateEndpoint = oldResolve })+WriteTabStateFile("tab-local")anonymous := &cobra.Command{Use: "anonymous"}@@ -75,3 +92,39 @@ func TestDefaultTabFlagFromStateOnlyForAnonymousCallers(t *testing.T) {t.Fatalf("agent tab flag = %q, want empty", got)}}++// The resolver the probe shares with the command, exercised for real rather than+// through the test seam: with no env vars set, both the port and the token must come+// from the config file. The old probe read env only and fell back to a hardcoded+// 9867, so a configured port sent it to a server that was not there — and a+// configured token meant it sent no credential at all.+func TestResolveTabStateEndpointReadsTheConfigFile(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"19771","token":"file-token"}}`), 0o600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)+ t.Setenv("PINCHTAB_SERVER", "")+ t.Setenv("PINCHTAB_TOKEN", "")+ t.Setenv("PINCHTAB_SESSION", "")+ oldServerURL := serverURL+ serverURL = ""+ t.Cleanup(func() { serverURL = oldServerURL })++ base, token := resolveTabStateEndpoint()++ if want := "http://127.0.0.1:19771"; base != want {+ t.Errorf("base = %q, want the configured port %q", base, want)+ }+ if token != "file-token" {+ t.Errorf("token = %q, want the config-file token", token)+ }++ // An explicit env var still wins, as it does for the command itself.+ t.Setenv("PINCHTAB_SERVER", "http://127.0.0.1:18000")+ t.Setenv("PINCHTAB_TOKEN", "env-token")+ if base, token = resolveTabStateEndpoint(); base != "http://127.0.0.1:18000" || token != "env-token" {+ t.Errorf("env override = (%q, %q), want the env values", base, token)+ }+}diff --git a/cmd/pinchtab/cmd_cli_register_test.go b/cmd/pinchtab/cmd_cli_register_test.goindex 3cf03b93..0494a86e 100644--- a/cmd/pinchtab/cmd_cli_register_test.go+++ b/cmd/pinchtab/cmd_cli_register_test.go@@ -1,50 +1,11 @@package mainimport (- "os"- "path/filepath""testing"- "time""github.com/spf13/cobra")-// The current-tab existence probe must be debounced: a freshly written/validated-// state file is trusted within tabProbeTTL so back-to-back commands skip the HTTP probe.-func TestTabStateRecentlyValidated(t *testing.T) {- t.Setenv("XDG_STATE_HOME", t.TempDir())- path := tabStateFile()-- if tabStateRecentlyValidated() {- t.Fatal("recentlyValidated true with no state file")- }-- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {- t.Fatalf("mkdir: %v", err)- }- if err := os.WriteFile(path, []byte("tab_x\n"), 0644); err != nil {- t.Fatalf("write: %v", err)- }- if !tabStateRecentlyValidated() {- t.Fatal("recentlyValidated false right after write")- }-- // Backdate past the TTL → stale, probe should run.- old := time.Now().Add(-2 * tabProbeTTL)- if err := os.Chtimes(path, old, old); err != nil {- t.Fatalf("chtimes: %v", err)- }- if tabStateRecentlyValidated() {- t.Fatal("recentlyValidated true after backdating past TTL")- }-- // Touch (post-validation) → fresh again.- touchTabStateFile()- if !tabStateRecentlyValidated() {- t.Fatal("recentlyValidated false after touch")- }-}-// Guard for the registration refactor: every browser root command must be in// the "browser" group, and the shared pointer-flag bundle (+ per-command extras)// must survive the helper extraction.diff --git a/cmd/pinchtab/cmd_cli_runtime.go b/cmd/pinchtab/cmd_cli_runtime.goindex c2be2797..c7e5a8b3 100644--- a/cmd/pinchtab/cmd_cli_runtime.go+++ b/cmd/pinchtab/cmd_cli_runtime.go@@ -136,6 +136,18 @@ func resolveDefaultCLIBase(cfg *config.RuntimeConfig) string {return fmt.Sprintf("http://127.0.0.1:%s", cfg.Port)}+// resolveTabStateEndpoint resolves the server the cached current tab belongs to,+// with the SAME precedence the command being guarded uses: --server/PINCHTAB_SERVER,+// else the configured port; token from PINCHTAB_SESSION/PINCHTAB_TOKEN, else the+// config file's. The tab probe used the env-only resolvers with a hardcoded 9867+// fallback, so with a configured port it probed a different server than the command+// — found nothing listening, assumed the stale tab valid, and refreshed its own+// freshness window. Same target, same credential, or the probe cannot self-heal.+var resolveTabStateEndpoint = func() (base, token string) {+ cfg := config.Load()+ return resolveBaseURL(resolveDefaultCLIBase(cfg)), resolveCLIToken(cfg)+}+// resolveBaseURL returns the server base URL from flag/env/default.// Shared by both the full CLI runtime path and the lightweight tab probe.func resolveBaseURL(defaultBase string) string {diff --git a/cmd/pinchtab/tab_state.go b/cmd/pinchtab/tab_state.goindex 9754b028..c2d3a689 100644--- a/cmd/pinchtab/tab_state.go+++ b/cmd/pinchtab/tab_state.go@@ -1,6 +1,8 @@package mainimport (+ "bytes"+ "fmt""io""net/http""os"@@ -8,6 +10,7 @@ import ("strings""time"+ "github.com/pinchtab/pinchtab/internal/cli/apiclient""github.com/spf13/cobra")@@ -23,8 +26,6 @@ type tabStateStore struct{}// the thin package-level helpers below.var defaultTabState = tabStateStore{}-const tabProbeTTL = 30 * time.Second-// useLocal reports whether anonymous local tab-state should be used. Identified// callers (PINCHTAB_SESSION, --agent-id, or PINCHTAB_AGENT_ID) defer to the// server-side scoped current-tab store instead.@@ -35,14 +36,43 @@ func (tabStateStore) useLocal() bool {return resolveCLIAgentID() == ""}-func (tabStateStore) path() string {+// path is scoped to the server the tab belongs to. A single global file made two+// ordinary servers — a daemon on the default port plus a project server — fight+// over one tab ID, so a nav against one sent its tab to the other and every read+// 404ed. The slug is derived from the resolved base URL, so switching ports (or+// restarting on a different one) reads a different file rather than a wrong tab.+func (s tabStateStore) path() string {+ return s.dir() + "/current-tab-" + s.serverSlug()+}++func (tabStateStore) dir() string {if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {- return dir + "/pinchtab/current-tab"+ return dir + "/pinchtab"}if home, err := os.UserHomeDir(); err == nil {- return home + "/.local/state/pinchtab/current-tab"+ return home + "/.local/state/pinchtab"+ }+ return "/tmp/pinchtab"+}++// serverSlug turns the resolved base URL into a filename-safe identity. It stays+// readable (127.0.0.1-9930) so an operator can tell which server a state file+// belongs to without decoding a hash.+func (tabStateStore) serverSlug() string {+ base, _ := resolveTabStateEndpoint()+ slug := strings.TrimPrefix(strings.TrimPrefix(base, "http://"), "https://")+ slug = 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(slug, "/"))+ if slug == "" {+ return "default"}- return "/tmp/pinchtab-current-tab"+ return slug}func (s tabStateStore) read() string {@@ -69,22 +99,6 @@ func (s tabStateStore) clearIfCurrent(tabID string) {_ = os.Remove(s.path())}-// recentlyValidated reports whether the saved-tab file was written or validated-// within tabProbeTTL, letting back-to-back commands skip the probe.-func (s tabStateStore) recentlyValidated() bool {- info, err := os.Stat(s.path())- if err != nil {- return false- }- return time.Since(info.ModTime()) < tabProbeTTL-}--// touch bumps the state file's mtime to mark it freshly validated.-func (s tabStateStore) touch() {- now := time.Now()- _ = os.Chtimes(s.path(), now, now)-}-// resolveArg returns the explicit positional tab argument when present, else the// locally cached current tab (for anonymous single-agent workflows).func (s tabStateStore) resolveArg(args []string) string {@@ -111,34 +125,49 @@ func (s tabStateStore) applyDefaultFlag(cmd *cobra.Command) {if tabID == "" {return}- if !s.recentlyValidated() {- if !s.probeExists(tabID) {- _ = os.Remove(s.path())- return- }- s.touch() // validated now → trusted for the next tabProbeTTL+ // Probed on every command rather than behind a freshness window. The window+ // existed to save a request, but a server restart invalidates every tab id+ // immediately, so trusting the cache for a fixed period is exactly the case that+ // broke: the first read after a restart still sent the dead id. Measured against+ // a live local server the probe costs ~1ms, and the expensive case — nothing+ // listening — never issues a request at all. Nothing refreshes a trust window+ // any more, so no inconclusive answer can keep a stale entry alive.+ if s.probe(tabID) == tabProbeGone {+ _ = os.Remove(s.path())+ return}_ = cmd.Flags().Set("tab", tabID)flag.Changed = false}-// probeExists checks whether a cached tab ID still exists on the server.-// Returns true if the tab is valid, the server is unreachable (it may auto-start-// later), or the check is inconclusive. Returns false only on a definitive 404.-func (tabStateStore) probeExists(tabID string) bool {- base := resolveBaseURL("http://127.0.0.1:9867")- token := resolveToken()+// tabProbeResult distinguishes the three answers a probe can give. The old+// boolean collapsed "the server says this tab is gone" with "I could not tell",+// and the caller then treated both as a successful validation.+type tabProbeResult int++const (+ // tabProbeInconclusive: nothing listening, a transport error, or a status that+ // does not answer the question (401 without the right credential, 5xx).+ tabProbeInconclusive tabProbeResult = iota+ tabProbeAlive+ tabProbeGone+)++// probe asks the server the cached tab belongs to whether it still exists.+func (tabStateStore) probe(tabID string) tabProbeResult {+ base, token := resolveTabStateEndpoint()- // Fast path: if the port isn't listening, skip the HTTP probe entirely.- // This avoids a 2s timeout on every CLI command when the server is down.+ // Fast path: if the port isn't listening, skip the HTTP probe entirely. This+ // avoids a 2s timeout on every CLI command when the server is down — and it is+ // inconclusive, not a validation: the server may auto-start later.if !portIsListening(base) {- return true+ return tabProbeInconclusive}client := &http.Client{Timeout: 2 * time.Second}req, err := http.NewRequest("GET", base+"/tabs/"+tabID+"/title", nil)if err != nil {- return true+ return tabProbeInconclusive}req.Header.Set("X-PinchTab-Source", "client")if token != "" {@@ -150,11 +179,38 @@ func (tabStateStore) probeExists(tabID string) bool {}resp, err := client.Do(req)if err != nil {- return true+ return tabProbeInconclusive}defer func() { _ = resp.Body.Close() }()_, _ = io.Copy(io.Discard, resp.Body)- return resp.StatusCode != http.StatusNotFound+ switch {+ case resp.StatusCode == http.StatusNotFound:+ return tabProbeGone+ case resp.StatusCode >= 200 && resp.StatusCode < 300:+ return tabProbeAlive+ default:+ // A 401 means the probe lacked the credential, not that the tab is gone.+ return tabProbeInconclusive+ }+}++// A tab-not-found 404 that names an ID the user never typed is unactionable on its+// own — the ID came from this cache, so this is the only layer that can say so.+// Clearing it here is the remedy rather than instructions to delete a file: the+// retry the message asks for is what makes it true.+func init() { apiclient.ErrorRemedy = defaultTabState.staleTabRemedy }++func (s tabStateStore) staleTabRemedy(statusCode int, body []byte) string {+ if statusCode != http.StatusNotFound || !s.useLocal() {+ return ""+ }+ cached := s.read()+ if cached == "" || !bytes.Contains(body, []byte(cached)) {+ return ""+ }+ _ = os.Remove(s.path())+ base, _ := resolveTabStateEndpoint()+ return fmt.Sprintf("that tab id is this CLI's cached current tab for %s, not something you asked for; the cache is now cleared, so retry the command (or run `pinchtab nav <url>` to open a fresh tab)", base)}// The package-level helpers below preserve the existing CLI/test API by@@ -174,7 +230,3 @@ func WriteTabStateFile(tabID string) { defaultTabState.write(tabID) }// ClearTabStateFileIfCurrent removes the cached tab only if it matches tabID.func ClearTabStateFileIfCurrent(tabID string) { defaultTabState.clearIfCurrent(tabID) }--func tabStateRecentlyValidated() bool { return defaultTabState.recentlyValidated() }--func touchTabStateFile() { defaultTabState.touch() }diff --git a/cmd/pinchtab/tab_state_test.go b/cmd/pinchtab/tab_state_test.gonew file mode 100644index 00000000..70d8219a--- /dev/null+++ b/cmd/pinchtab/tab_state_test.go@@ -0,0 +1,219 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "strings"+ "testing"++ "github.com/pinchtab/pinchtab/internal/cli/apiclient"+ "github.com/spf13/cobra"+)++// tabStateHarness points the tab-state store at a temp state dir and at a stub+// server, resolving the endpoint the way the CLI does rather than through env+// vars — the divergence between those two resolutions is the defect under test.+type tabStateHarness struct {+ base string+ token string+ statusFor func(tabID string) int+ requests []*http.Request+}++func newTabStateHarness(t *testing.T) *tabStateHarness {+ t.Helper()+ h := &tabStateHarness{token: "cfg-token", statusFor: func(string) int { return http.StatusOK }}++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ h.requests = append(h.requests, r)+ id := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/tabs/"), "/title")+ if got := r.Header.Get("Authorization"); got != "Bearer "+h.token {+ w.WriteHeader(http.StatusUnauthorized)+ _ = json.NewEncoder(w).Encode(map[string]string{"error": "unauthorized"})+ return+ }+ status := h.statusFor(id)+ w.WriteHeader(status)+ if status == http.StatusNotFound {+ _ = json.NewEncoder(w).Encode(map[string]string{"error": "tab " + id + " not found"})+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]string{"title": "ok"})+ }))+ t.Cleanup(srv.Close)+ h.base = srv.URL++ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Setenv("PINCHTAB_SESSION", "")+ t.Setenv("PINCHTAB_AGENT_ID", "")+ t.Setenv("PINCHTAB_SERVER", "")+ t.Setenv("PINCHTAB_TOKEN", "")+ oldAgent := cliAgentID+ cliAgentID = ""+ oldResolve := resolveTabStateEndpoint+ resolveTabStateEndpoint = func() (string, string) { return h.base, h.token }+ t.Cleanup(func() {+ cliAgentID = oldAgent+ resolveTabStateEndpoint = oldResolve+ })+ return h+}++func tabFlagCommand() *cobra.Command {+ cmd := &cobra.Command{Use: "read"}+ cmd.Flags().String("tab", "", "Tab ID")+ return cmd+}++// The card's failing case: nav writes the cache, the server restarts, and the very+// next read must not send the dead id. The write is fresh, which is what the old+// freshness window trusted — so this is the case a TTL-gated probe cannot catch.+func TestCachedTabClearedAfterRestartWithNoInterveningNav(t *testing.T) {+ h := newTabStateHarness(t)+ WriteTabStateFile("TAB-BEFORE-RESTART")++ // The restart: the id the cache holds is unknown to the server now.+ h.statusFor = func(string) int { return http.StatusNotFound }++ cmd := tabFlagCommand()+ defaultTabFlagFromState(cmd)++ if got, _ := cmd.Flags().GetString("tab"); got != "" {+ t.Fatalf("--tab = %q after a restart, want empty so the command targets the server's current tab", got)+ }+ if _, err := os.Stat(tabStateFile()); !os.IsNotExist(err) {+ t.Fatalf("stale state file survived: %v", err)+ }+ if len(h.requests) == 0 {+ t.Fatal("no probe was issued; a freshly written cache must still be checked")+ }+}++// The probe has to reach the same server with the same credential as the command.+// With a config-file port and token and no env vars, the old probe queried 9867+// unauthenticated: nothing listening, "assume valid", stale forever.+func TestProbeUsesTheCommandsBaseURLAndToken(t *testing.T) {+ h := newTabStateHarness(t)+ WriteTabStateFile("LIVE-TAB")+ h.statusFor = func(id string) int {+ if id == "LIVE-TAB" {+ return http.StatusOK+ }+ return http.StatusNotFound+ }++ cmd := tabFlagCommand()+ defaultTabFlagFromState(cmd)++ if got, _ := cmd.Flags().GetString("tab"); got != "LIVE-TAB" {+ t.Fatalf("--tab = %q, want the live cached tab", got)+ }+ if len(h.requests) != 1 {+ t.Fatalf("probe issued %d requests, want 1", len(h.requests))+ }+ req := h.requests[0]+ if req.Host != strings.TrimPrefix(h.base, "http://") {+ t.Errorf("probe went to %q, want the command's server %q", req.Host, h.base)+ }+ if got := req.Header.Get("Authorization"); got != "Bearer "+h.token {+ t.Errorf("probe Authorization = %q, want the config-file token", got)+ }+ if got := req.URL.Path; got != "/tabs/LIVE-TAB/title" {+ t.Errorf("probe path = %q", got)+ }+}++// Two servers, two caches. A single global file made an ordinary setup (a daemon+// plus a project server) send one server's tab id to the other.+func TestCurrentTabIsScopedPerServer(t *testing.T) {+ h := newTabStateHarness(t)++ WriteTabStateFile("TAB-ON-A")+ pathA := tabStateFile()++ h.base = "http://127.0.0.1:19999"+ WriteTabStateFile("TAB-ON-B")+ pathB := tabStateFile()++ if pathA == pathB {+ t.Fatalf("both servers share one state file: %s", pathA)+ }+ if got := defaultTabState.read(); got != "TAB-ON-B" {+ t.Fatalf("second server reads %q, want its own TAB-ON-B", got)+ }++ // The first server's cached tab must be untouched by the second server's nav.+ data, err := os.ReadFile(pathA)+ if err != nil {+ t.Fatalf("first server's state file: %v", err)+ }+ if got := strings.TrimSpace(string(data)); got != "TAB-ON-A" {+ t.Fatalf("first server's cached tab = %q, want TAB-ON-A", got)+ }+}++// An inconclusive probe must not buy the stale entry any trust: the next command+// probes again, and when that probe can finally answer, the entry is cleared. The+// old code touched the file on every assume-valid return, so back-to-back commands+// renewed the window forever.+func TestInconclusiveProbeDoesNotProtectAStaleEntry(t *testing.T) {+ h := newTabStateHarness(t)+ WriteTabStateFile("STALE-TAB")++ // Round one: the probe cannot tell — wrong credential, so 401, not 404.+ h.token = "a-different-token"+ first := tabFlagCommand()+ defaultTabFlagFromState(first)+ if got, _ := first.Flags().GetString("tab"); got != "STALE-TAB" {+ t.Fatalf("--tab = %q, want the cached tab used when the probe is inconclusive", got)+ }+ if _, err := os.Stat(tabStateFile()); err != nil {+ t.Fatalf("an inconclusive probe must not delete the cache: %v", err)+ }++ // Round two, immediately after: the credential works and the server answers 404.+ h.token = "cfg-token"+ h.statusFor = func(string) int { return http.StatusNotFound }+ second := tabFlagCommand()+ defaultTabFlagFromState(second)++ if got, _ := second.Flags().GetString("tab"); got != "" {+ t.Fatalf("--tab = %q on the second command; the first probe's inconclusive answer suppressed the second", got)+ }+ if _, err := os.Stat(tabStateFile()); !os.IsNotExist(err) {+ t.Fatal("stale entry survived a definitive 404 on the very next command")+ }+}++// A 404 naming an id the user never typed is unactionable without saying where the+// id came from. The remedy also clears the cache, so the retry it asks for works.+func TestStaleTabErrorCarriesTheCachedTabRemedy(t *testing.T) {+ newTabStateHarness(t)+ WriteTabStateFile("CACHED-TAB")++ body := []byte(`{"code":"tab_not_found","error":"tab CACHED-TAB not found"}`)+ remedy := apiclient.ErrorRemedy(http.StatusNotFound, body)++ if remedy == "" {+ t.Fatal("no remedy for a 404 naming the cached tab")+ }+ for _, want := range []string{"cached current tab", "retry", "pinchtab nav"} {+ if !strings.Contains(remedy, want) {+ t.Errorf("remedy %q does not mention %q", remedy, want)+ }+ }+ if _, err := os.Stat(tabStateFile()); !os.IsNotExist(err) {+ t.Error("the remedy claims the cache is cleared but the file survived")+ }++ // A 404 about someone else's tab is not this cache's business.+ WriteTabStateFile("CACHED-TAB")+ if got := apiclient.ErrorRemedy(http.StatusNotFound, []byte(`{"error":"tab SOMEONE-ELSE not found"}`)); got != "" {+ t.Errorf("remedy %q offered for a tab the cache never held", got)+ }+ if _, err := os.Stat(tabStateFile()); err != nil {+ t.Errorf("unrelated 404 cleared the cache: %v", err)+ }+}diff --git a/internal/cli/apiclient/apierror.go b/internal/cli/apiclient/apierror.goindex 290e68dc..8601a478 100644--- a/internal/cli/apiclient/apierror.go+++ b/internal/cli/apiclient/apierror.go@@ -65,6 +65,21 @@ func handleAPIError(statusCode int, body []byte) {fmt.Fprint(os.Stderr, renderAPIErrorBody(statusCode, body))}+// ErrorRemedy lets the command layer append a remedy the server cannot know about.+// A tab-not-found 404 naming an ID the user never typed is the case: only the CLI+// knows the ID came from its cached current tab, so only the CLI can say what to do+// about it. Unset by default; cmd/pinchtab installs one at startup.+var ErrorRemedy func(statusCode int, body []byte) string++func appendClientRemedy(b *strings.Builder, statusCode int, body []byte) {+ if ErrorRemedy == nil {+ return+ }+ if remedy := ErrorRemedy(statusCode, body); remedy != "" {+ fmt.Fprintf(b, " Remedy: %s\n", remedy)+ }+}+func renderAPIErrorBody(statusCode int, body []byte) string {var errResp struct {Error string `json:"error"`@@ -91,6 +106,7 @@ func renderAPIErrorBody(statusCode int, body []byte) string {fmt.Fprintf(&b, " Remedy: %s\n", remedy)}}+ appendClientRemedy(&b, statusCode, body)return b.String()}