Skip to content

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

fix: the nav fallback silently doubles tabs for session-less callers, because it re-posts anonymously and the endpoint contract creates a tab for anonymous callers (PIN-131)

Luigi Agostif3919ffac9f8
diff --git a/docs/reference/navigate.md b/docs/reference/navigate.md
index b5d60ebb..2c89008b 100644
--- a/docs/reference/navigate.md
+++ b/docs/reference/navigate.md
@@ -62,6 +62,7 @@ pinchtab nav https://example.com --block-images # Skip images
- `POST /tabs/{id}/navigate`, `POST /navigate` with `tabId`, and `pinchtab nav <url> --tab <id>` reuse the specified tab and make it the current tab for later unscoped operations.
- `--new-tab` and `newTab:true` force a new tab even if another tab is current.
- Commands that operate without `--tab` use the current tracked tab. Focusing or using a tab updates that current-tab pointer; if the pointer is stale, PinchTab falls back to the most recently used tracked tab.
+- When the saved current-tab pointer names a tab the server no longer has, `pinchtab nav` retries the navigation without the tab id. For a session or agent-id caller that retry reuses that scope's current tab. For a session-less caller the server opens a **new** tab — the documented anonymous contract — so the CLI prints a `HINT` on stderr naming both the tab that was gone and the new one, rather than reporting plain success while leaving you with two tabs on one URL. Run with `PINCHTAB_SESSION` set to keep a single work surface. An explicit `--tab` never retries: it surfaces the 404.
Rationale: the CLI keeps one obvious work surface by default. Use `--new-tab` when you intentionally want another tab, or `--tab`/`tabId` when you need a specific tab.
diff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.go
index b5c189b5..d6748ed6 100644
--- a/internal/cli/actions/actions_navigate.go
+++ b/internal/cli/actions/actions_navigate.go
@@ -81,13 +81,16 @@ func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Co
jsonOutput, _ := cmd.Flags().GetBool("json")
if jsonOutput {
- result := postNavigate(client, base, token, req, true)
+ result, usedFallback := postNavigate(client, base, token, req, true)
+ resultTabID := tabIDFromNavigateResult(result)
+ reportFallbackNewTab(usedFallback, req.tabID, resultTabID)
apiclient.SuggestNextAction("navigate", result)
- return tabIDFromNavigateResult(result)
+ return resultTabID
}
- result := postNavigate(client, base, token, req, false)
+ result, usedFallback := postNavigate(client, base, token, req, false)
resultTabID := tabIDFromNavigateResult(result)
+ reportFallbackNewTab(usedFallback, req.tabID, resultTabID)
if resultTabID != "" {
fmt.Println(resultTabID)
}
@@ -132,6 +135,10 @@ type navigateRequest struct {
path string
body map[string]any
fallbackOnNotFound bool
+ // tabID is the tab the request was scoped to, kept so a fallback can name
+ // the tab that turned out to be gone. Read once, here, rather than again at
+ // the reporting site.
+ tabID string
}
func buildNavigateRequest(url string, cmd *cobra.Command) navigateRequest {
@@ -166,21 +173,51 @@ func buildNavigateRequest(url string, cmd *cobra.Command) navigateRequest {
path: path,
body: body,
fallbackOnNotFound: fallbackOnNotFound,
+ tabID: tabID,
}
}
-func postNavigate(client *http.Client, base, token string, req navigateRequest, printResponse bool) map[string]any {
+// postNavigate returns the decoded response and whether the tab-scoped request
+// 404'd and was retried unscoped, which is the case the caller has to report.
+func postNavigate(client *http.Client, base, token string, req navigateRequest, printResponse bool) (map[string]any, bool) {
statusCode, respBody, result := apiclient.DoPostQuietWithStatus(client, base, token, req.path, req.body)
+ usedFallback := false
if statusCode == http.StatusNotFound && req.fallbackOnNotFound {
+ usedFallback = true
statusCode, respBody, result = apiclient.DoPostQuietWithStatus(client, base, token, "/navigate", req.body)
}
if statusCode >= 400 {
apiclient.ExitWithAPIError(statusCode, respBody)
}
if printResponse {
- return apiclient.PrintAndDecode(respBody)
+ return apiclient.PrintAndDecode(respBody), usedFallback
}
- return result
+ return result, usedFallback
+}
+
+// reportFallbackNewTab says so when the fallback left the caller on a second tab.
+//
+// The retry drops the tab id, which makes it an unscoped request, and the server's
+// published contract for an UNSCOPED navigate is caller-identity dependent
+// (docs/endpoints.md): an anonymous caller always gets a new tab — CurrentTabStore
+// has no entry for a global scope to adopt — while a session or agent-id caller
+// reuses that scope's current tab. So the notice is exactly as narrow as the
+// guarantee behind it: anonymous callers, where "a new tab was opened" is a fact
+// rather than an inference. An identified caller stays silent because nothing was
+// created for it to hear about.
+//
+// The remedy is deliberately absent: an anonymous navigate already prints
+// cli.NoSessionHint, which carries the run-with-a-session advice, and repeating it
+// here would be the same guidance twice on one command.
+func reportFallbackNewTab(usedFallback bool, staleTabID, newTabID string) {
+ if !usedFallback || isIdentifiedCaller() {
+ return
+ }
+ if newTabID == "" {
+ output.Hint(fmt.Sprintf("tab %s no longer exists — the server opened a new tab for this navigation", staleTabID))
+ return
+ }
+ output.Hint(fmt.Sprintf("tab %s no longer exists — opened a new tab %s for this navigation", staleTabID, newTabID))
}
func isIdentifiedCaller() bool {
diff --git a/internal/cli/actions/actions_navigate_test.go b/internal/cli/actions/actions_navigate_test.go
index 8cbfb3c6..3f434dfe 100644
--- a/internal/cli/actions/actions_navigate_test.go
+++ b/internal/cli/actions/actions_navigate_test.go
@@ -508,3 +508,170 @@ func TestNavigateTextFetchesPageText(t *testing.T) {
t.Errorf("stdout = %q, want the page text after navigation", out)
}
}
+
+// The reported defect: a stale saved tab id 404s, the CLI silently re-posts
+// without it, and the server — following its published anonymous contract —
+// opens a SECOND tab on the same URL. The navigate reported success and said
+// nothing, so an agent had a page it was not looking at.
+func TestNavigateFallbackAnnouncesTheNewTabWithoutASession(t *testing.T) {
+ t.Setenv("PINCHTAB_SESSION", "")
+ t.Setenv("PINCHTAB_AGENT_ID", "")
+
+ m := newMockServer()
+ m.setResponse(http.MethodPost, "/tabs/STALE123/navigate", http.StatusNotFound, `{"error":"tab not found"}`)
+ m.setResponse(http.MethodPost, "/navigate", http.StatusOK, `{"tabId":"NEW123","status":"ok"}`)
+ defer m.close()
+
+ stderr := captureStderr(t, func() {
+ captureStdout(t, func() {
+ Navigate(m.server.Client(), m.base(), "", "https://pinchtab.com", staleTabCmd(t, "STALE123"))
+ })
+ })
+
+ notice := fallbackNoticeLine(t, stderr)
+ for _, want := range []string{"STALE123", "NEW123", "new tab"} {
+ if !strings.Contains(notice, want) {
+ t.Errorf("notice = %q, want it to contain %q", notice, want)
+ }
+ }
+ // The retry still has to have worked — a notice about a navigation that
+ // failed would be worse than silence.
+ if len(m.requests) != 2 || m.requests[1].Path != "/navigate" {
+ t.Fatalf("requests = %+v, want the tab-scoped attempt then the unscoped retry", m.requests)
+ }
+}
+
+// The session path is the one that already works: the unscoped retry reuses the
+// session's current tab, so nothing was created and there is nothing to
+// announce. Saying "opened a new tab" here would be false.
+func TestNavigateFallbackStaysSilentForAnIdentifiedCaller(t *testing.T) {
+ t.Setenv("PINCHTAB_SESSION", "ses_something")
+
+ m := newMockServer()
+ m.setResponse(http.MethodPost, "/tabs/STALE123/navigate", http.StatusNotFound, `{"error":"tab not found"}`)
+ m.setResponse(http.MethodPost, "/navigate", http.StatusOK, `{"tabId":"SESSION_CURRENT","status":"ok"}`)
+ defer m.close()
+
+ stderr := captureStderr(t, func() {
+ captureStdout(t, func() {
+ Navigate(m.server.Client(), m.base(), "", "https://pinchtab.com", staleTabCmd(t, "STALE123"))
+ })
+ })
+
+ if strings.Contains(stderr, "new tab") {
+ t.Fatalf("stderr = %q, want no new-tab notice for a caller whose retry adopts the session's current tab", stderr)
+ }
+ // The retry itself is unchanged: still one unscoped POST, still no tab id in
+ // the body, so the server keeps owning the tab-selection policy.
+ if len(m.requests) != 2 || m.requests[1].Path != "/navigate" {
+ t.Fatalf("requests = %+v, want the fallback to still fire", m.requests)
+ }
+ var body map[string]any
+ _ = json.Unmarshal([]byte(m.requests[1].Body), &body)
+ if _, ok := body["tabId"]; ok {
+ t.Errorf("retry body = %v; the CLI must not start naming a tab, that is the server's policy", body)
+ }
+}
+
+// Absence assertion: an ordinary navigate that never hits the fallback gains no
+// extra output. Without this the notice could fire on every call and the tests
+// above would still pass.
+func TestNavigateWithoutFallbackAnnouncesNothingExtra(t *testing.T) {
+ t.Setenv("PINCHTAB_SESSION", "")
+ t.Setenv("PINCHTAB_AGENT_ID", "")
+
+ m := newMockServer()
+ m.response = `{"tabId":"ABC123","status":"ok"}`
+ defer m.close()
+
+ stderr := captureStderr(t, func() {
+ captureStdout(t, func() {
+ Navigate(m.server.Client(), m.base(), "", "https://pinchtab.com", newNavigateCmd())
+ })
+ })
+
+ if strings.Contains(stderr, "no longer exists") {
+ t.Fatalf("stderr = %q, want no fallback notice when no fallback fired", stderr)
+ }
+}
+
+// The notice must not repeat the session advice cli.NoSessionHint already
+// carries: an anonymous fallback prints both lines, and the same remedy twice on
+// one command is the shape that trains readers to skip hints.
+func TestFallbackNoticeDoesNotRepeatTheSessionRemedy(t *testing.T) {
+ t.Setenv("PINCHTAB_SESSION", "")
+ t.Setenv("PINCHTAB_AGENT_ID", "")
+
+ m := newMockServer()
+ m.setResponse(http.MethodPost, "/tabs/STALE123/navigate", http.StatusNotFound, `{"error":"tab not found"}`)
+ m.setResponse(http.MethodPost, "/navigate", http.StatusOK, `{"tabId":"NEW123","status":"ok"}`)
+ defer m.close()
+
+ stderr := captureStderr(t, func() {
+ captureStdout(t, func() {
+ Navigate(m.server.Client(), m.base(), "", "https://pinchtab.com", staleTabCmd(t, "STALE123"))
+ })
+ })
+
+ if strings.Count(stderr, cli.SessionCreateCommand) != 1 {
+ t.Errorf("stderr carries the session command %d times, want exactly once (from cli.NoSessionHint):\n%s",
+ strings.Count(stderr, cli.SessionCreateCommand), stderr)
+ }
+ if !strings.Contains(fallbackNoticeLine(t, stderr), "new tab") {
+ t.Errorf("the fallback notice itself is missing from:\n%s", stderr)
+ }
+}
+
+// stdout stays tab-id-only through a fallback: `TAB=$(pinchtab nav URL)` would
+// otherwise capture the notice.
+func TestFallbackNoticeStaysOffStdout(t *testing.T) {
+ t.Setenv("PINCHTAB_SESSION", "")
+ t.Setenv("PINCHTAB_AGENT_ID", "")
+ stdoutTerminal(t, false)
+
+ m := newMockServer()
+ m.setResponse(http.MethodPost, "/tabs/STALE123/navigate", http.StatusNotFound, `{"error":"tab not found"}`)
+ m.setResponse(http.MethodPost, "/navigate", http.StatusOK, `{"tabId":"NEW123","url":"https://pinchtab.com","status":"ok"}`)
+ defer m.close()
+
+ var out string
+ _ = captureStderr(t, func() {
+ out = captureStdout(t, func() {
+ Navigate(m.server.Client(), m.base(), "", "https://pinchtab.com", staleTabCmd(t, "STALE123"))
+ })
+ })
+
+ if strings.TrimSpace(out) != "NEW123" {
+ t.Fatalf("stdout = %q, want only the tab id", out)
+ }
+}
+
+// staleTabCmd builds the nav command shape the fallback needs: a tab id that came
+// from saved state rather than an explicit --tab, which is the only case the
+// retry is allowed to fire for.
+func staleTabCmd(t *testing.T, tabID string) *cobra.Command {
+ t.Helper()
+
+ cmd := newNavigateCmd()
+ cmd.Flags().Lookup("tab").DefValue = tabID
+ if err := cmd.Flags().Set("tab", tabID); err != nil {
+ t.Fatal(err)
+ }
+ cmd.Flags().Lookup("tab").Changed = false
+ return cmd
+}
+
+// fallbackNoticeLine returns the single HINT line about the vanished tab, failing
+// when there is none — so a test asserting on its content cannot pass against an
+// empty string.
+func fallbackNoticeLine(t *testing.T, stderr string) string {
+ t.Helper()
+
+ for _, line := range strings.Split(stderr, "\n") {
+ if strings.Contains(line, "no longer exists") {
+ return line
+ }
+ }
+ t.Fatalf("no fallback notice in stderr:\n%s", stderr)
+ return ""
+}