High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: harden navigation timeout handling
Luigi Agosti76ddb34782f7
diff --git a/cmd/pinchtab/cmd_cli_register_test.go b/cmd/pinchtab/cmd_cli_register_test.goindex 0494a86e..72d7adb8 100644--- a/cmd/pinchtab/cmd_cli_register_test.go+++ b/cmd/pinchtab/cmd_cli_register_test.go@@ -38,6 +38,16 @@ func TestCaptureCommandRegistersTabFlag(t *testing.T) {}}+func TestNavigateCommandRegistersTimeoutInSeconds(t *testing.T) {+ flag := navCmd.Flags().Lookup("timeout")+ if flag == nil {+ t.Fatal("navCmd missing --timeout flag")+ }+ if flag.DefValue != "0" || flag.Usage != "Navigation timeout in seconds (max 120); overrides the 30s new-tab ceiling" {+ t.Fatalf("--timeout default/usage = %q / %q", flag.DefValue, flag.Usage)+ }+}+// TestPostActionFlagsBundle pins the exact usage strings the shared// addPostActionFlags helper interpolates per verb, so a future verb edit cannot// silently drift the --help text, and verifies the one no-text command omits it.diff --git a/docs/commands.md b/docs/commands.mdindex e1df7df8..43fb9596 100644--- a/docs/commands.md+++ b/docs/commands.md@@ -51,6 +51,7 @@ bridge. Orchestrator-spawned bridges inherit the level through their child confipinchtab nav <url> # Navigate current tab, or create one if neededpinchtab nav <url> --tab <id> # Reuse a specific tabpinchtab nav <url> --new-tab # Explicitly force a new tab+pinchtab nav <url> --timeout 90 # Allow up to 90s (maximum 120s)pinchtab nav <url> --block-images # Block images for this navigationpinchtab nav <url> --block-ads # Block ads for this navigationpinchtab nav <url> --snap # Navigate and output interactive snapshotdiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex 0560f7fb..72dee80e 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -151,6 +151,7 @@ Common commands:| Command | Purpose || --- | --- || `pinchtab nav <url>` | Navigate current tracked tab, or create one if needed |+| `pinchtab nav <url> --timeout 90` | Override the navigation timeout in seconds (maximum 120) || `pinchtab nav <url> --snap` | Navigate and output an interactive compact snapshot || `pinchtab snap [selector]` | Accessibility snapshot for the current tab, optionally scoped || `pinchtab frame [target\|main]` | Show or set selector frame scope |diff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.goindex 07826219..02f88a49 100644--- a/internal/cli/actions/actions_navigate.go+++ b/internal/cli/actions/actions_navigate.go@@ -1,15 +1,17 @@package actionsimport (- "time""fmt"+ "math""net/http""os""strings"+ "time""github.com/pinchtab/pinchtab/internal/cli""github.com/pinchtab/pinchtab/internal/cli/apiclient""github.com/pinchtab/pinchtab/internal/cli/output"+ "github.com/pinchtab/pinchtab/internal/httpx""github.com/spf13/cobra""github.com/spf13/pflag")@@ -81,10 +83,8 @@ func landedURL(result map[string]any) string {func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Command) string {req := buildNavigateRequest(url, cmd)- // A per-request timeout can exceed the shared client budget; mirror the- // longClient pattern used by scrape/audit so the HTTP client outlives it.- if v, err := cmd.Flags().GetFloat64("timeout"); err == nil && v > 0 {- client = &http.Client{Transport: client.Transport, Timeout: time.Duration((v + 15) * float64(time.Second))}+ if timeoutSeconds, ok := req.body["timeout"].(float64); ok {+ client = navigationHTTPClient(client, timeoutSeconds)}jsonOutput, _ := cmd.Flags().GetBool("json")@@ -155,8 +155,8 @@ func buildNavigateRequest(url string, cmd *cobra.Command) navigateRequest {if newTab {body["newTab"] = true}- if v, err := cmd.Flags().GetFloat64("timeout"); err == nil && v > 0 {- body["timeout"] = v+ if timeoutSeconds := navigationTimeoutSeconds(cmd); timeoutSeconds > 0 {+ body["timeout"] = timeoutSeconds}if v, _ := cmd.Flags().GetBool("block-images"); v {body["blockImages"] = true@@ -188,6 +188,23 @@ func buildNavigateRequest(url string, cmd *cobra.Command) navigateRequest {}}+func navigationTimeoutSeconds(cmd *cobra.Command) float64 {+ timeoutSeconds, err := cmd.Flags().GetFloat64("timeout")+ if err != nil || timeoutSeconds <= 0 || math.IsNaN(timeoutSeconds) {+ return 0+ }+ if timeoutSeconds > httpx.MaxNavigationTimeout.Seconds() {+ return httpx.MaxNavigationTimeout.Seconds()+ }+ return timeoutSeconds+}++func navigationHTTPClient(client *http.Client, timeoutSeconds float64) *http.Client {+ clone := *client+ clone.Timeout = time.Duration(timeoutSeconds*float64(time.Second)) + httpx.NavigationTransportGrace+ return &clone+}+// 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) {diff --git a/internal/cli/actions/actions_navigate_test.go b/internal/cli/actions/actions_navigate_test.goindex bcd0fa02..b6a4f2da 100644--- a/internal/cli/actions/actions_navigate_test.go+++ b/internal/cli/actions/actions_navigate_test.go@@ -3,10 +3,13 @@ package actionsimport ("encoding/json""net/http"+ "net/http/cookiejar""strings""testing"+ "time""github.com/pinchtab/pinchtab/internal/cli"+ "github.com/pinchtab/pinchtab/internal/httpx""github.com/spf13/cobra")@@ -16,11 +19,77 @@ func newNavigateCmd() *cobra.Command {cmd.Flags().Bool("block-images", false, "")cmd.Flags().Bool("block-ads", false, "")cmd.Flags().Bool("dismiss-banners", false, "")+ cmd.Flags().Float64("timeout", 0, "")cmd.Flags().String("tab", "", "")cmd.Flags().Bool("print-tab-id", false, "")return cmd}+func TestNavigateTimeoutIsSentAndClampedToTheAPICeiling(t *testing.T) {+ for _, tc := range []struct {+ name string+ value string+ want float64+ set bool+ }{+ {name: "omitted"},+ {name: "explicit", value: "90.5", want: 90.5, set: true},+ {name: "over maximum", value: "121", want: httpx.MaxNavigationTimeout.Seconds(), set: true},+ {name: "infinite", value: "+Inf", want: httpx.MaxNavigationTimeout.Seconds(), set: true},+ {name: "not a number", value: "NaN", set: true},+ {name: "negative", value: "-1", set: true},+ } {+ t.Run(tc.name, func(t *testing.T) {+ cmd := newNavigateCmd()+ if tc.set {+ if err := cmd.Flags().Set("timeout", tc.value); err != nil {+ t.Fatal(err)+ }+ }++ req := buildNavigateRequest("https://pinchtab.com", cmd)+ got, present := req.body["timeout"].(float64)+ if tc.want == 0 {+ if present {+ t.Fatalf("timeout = %v, want omitted", got)+ }+ return+ }+ if !present || got != tc.want {+ t.Fatalf("timeout = %v (present %v), want %v", got, present, tc.want)+ }+ })+ }+}++func TestNavigationHTTPClientPreservesCallerPolicy(t *testing.T) {+ jar, err := cookiejar.New(nil)+ if err != nil {+ t.Fatal(err)+ }+ base := &http.Client{+ Transport: http.DefaultTransport,+ Jar: jar,+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },+ Timeout: time.Minute,+ }++ got := navigationHTTPClient(base, 90.5)+ if got == base {+ t.Fatal("navigation client mutated the shared client instead of cloning it")+ }+ if base.Timeout != time.Minute {+ t.Fatalf("shared client timeout changed to %v", base.Timeout)+ }+ if got.Transport != base.Transport || got.Jar != base.Jar || got.CheckRedirect == nil {+ t.Fatal("navigation client dropped caller transport, cookie jar, or redirect policy")+ }+ wantTimeout := 90*time.Second + 500*time.Millisecond + httpx.NavigationTransportGrace+ if got.Timeout != wantTimeout {+ t.Fatalf("timeout = %v, want %v", got.Timeout, wantTimeout)+ }+}+func newHistoryCmd() *cobra.Command {cmd := &cobra.Command{}cmd.Flags().String("tab", "", "")diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex db4e3785..1e5b2e84 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -29,7 +29,7 @@ import (// @Param url string body URL to navigate to (required)// @Param newTab bool body Force create new tab (optional, default: false)// @Param waitTitle float64 body Wait for title change (ms) (optional, default: 0)-// @Param timeout float64 body Timeout for navigation (ms) (optional, default: 30000)+// @Param timeout float64 body Timeout for navigation in seconds (optional, max: 120)//// @Response 200 application/json Returns {tabId, url, title}// @Response 400 application/json Invalid URL or parameters@@ -375,8 +375,9 @@ func (h *Handlers) executeNavigate(w http.ResponseWriter, r *http.Request, req nnavTimeout := effectiveCfg.NavigateTimeoutif req.Timeout > 0 {- if req.Timeout > 120 {- req.Timeout = 120+ maxTimeoutSeconds := httpx.MaxNavigationTimeout.Seconds()+ if req.Timeout > maxTimeoutSeconds {+ req.Timeout = maxTimeoutSeconds}navTimeout = time.Duration(req.Timeout * float64(time.Second))}diff --git a/internal/httpx/httpx.go b/internal/httpx/httpx.goindex facc7808..6675abf5 100644--- a/internal/httpx/httpx.go+++ b/internal/httpx/httpx.go@@ -17,6 +17,10 @@ import (const (DefaultMaxJSONBodyBytes = 1 << 20maxErrorMessageBytes = 1024++ MaxNavigationTimeout = 120 * time.Second+ NavigationTransportGrace = 15 * time.Second+ MaxNavigationHTTPDuration = MaxNavigationTimeout + NavigationTransportGrace)type ProblemDetails struct {diff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.goindex 45ff4f53..8f797269 100644--- a/internal/instance/bridge_client.go+++ b/internal/instance/bridge_client.go@@ -7,7 +7,6 @@ import ("io""net/http""strings"- "time""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/httpx"@@ -22,7 +21,7 @@ type BridgeClient struct {// NewBridgeClient creates a BridgeClient.func NewBridgeClient() *BridgeClient {return &BridgeClient{- client: &http.Client{Timeout: 135 * time.Second},+ client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},}}diff --git a/internal/instance/bridge_client_timeout_test.go b/internal/instance/bridge_client_timeout_test.gonew file mode 100644index 00000000..9ed0bca1--- /dev/null+++ b/internal/instance/bridge_client_timeout_test.go@@ -0,0 +1,14 @@+package instance++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/httpx"+)++func TestBridgeClientAllowsTheFullNavigationBudget(t *testing.T) {+ got := NewBridgeClient().client.Timeout+ if got != httpx.MaxNavigationHTTPDuration {+ t.Fatalf("timeout = %v, want %v", got, httpx.MaxNavigationHTTPDuration)+ }+}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex 0cb146d4..0d6ee12a 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -14,6 +14,7 @@ import ("github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/httpx""github.com/pinchtab/pinchtab/internal/ids""github.com/pinchtab/pinchtab/internal/instance""github.com/pinchtab/pinchtab/internal/profiles"@@ -145,20 +146,11 @@ func NewOrchestrator(baseDir string) *Orchestrator {func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator {orch := &Orchestrator{- instances: make(map[string]*InstanceInternal),- baseDir: baseDir,- binary: resolveStableBinary(baseDir),- runner: runner,- // Client timeout for proxying to instances: 60 seconds- // Why so high?- // - First request to an instance triggers lazy Chrome initialization (8-20+ seconds)- // - Navigation can take up to 60s (NavigateTimeout in bridge config)- // - Proxied requests (e.g., POST /tabs/{tabId}/navigate) must wait for:- // 1. Instance /health handler to initialize the browser- // 2. Tab operations to complete (navigate, snapshot, actions, etc.)- // - Short timeout (<5s) would break first-request scenarios- // See: internal/orchestrator/health.go (monitor), internal/bridge/init.go (InitBrowser)- client: &http.Client{Timeout: 135 * time.Second},+ instances: make(map[string]*InstanceInternal),+ baseDir: baseDir,+ binary: resolveStableBinary(baseDir),+ runner: runner,+ client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},childAuthToken: "",allowEvaluate: false,internalToken: generateInternalToken(),diff --git a/internal/orchestrator/orchestrator_timeout_test.go b/internal/orchestrator/orchestrator_timeout_test.gonew file mode 100644index 00000000..29c01155--- /dev/null+++ b/internal/orchestrator/orchestrator_timeout_test.go@@ -0,0 +1,14 @@+package orchestrator++import (+ "testing"++ "github.com/pinchtab/pinchtab/internal/httpx"+)++func TestOrchestratorAllowsTheFullNavigationBudget(t *testing.T) {+ orchestrator := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{})+ if orchestrator.client.Timeout != httpx.MaxNavigationHTTPDuration {+ t.Fatalf("timeout = %v, want %v", orchestrator.client.Timeout, httpx.MaxNavigationHTTPDuration)+ }+}diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex b7e2f458..19328aa7 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -10,16 +10,12 @@ import ("net/http""net/url""strings"- "time""github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/httpx")-// DefaultClient is the shared HTTP client for proxy requests.-// A 60-second timeout accommodates lazy Chrome initialization (8-20s)-// and tab navigation (up to 60s for NavigateTimeout in bridge config).-var DefaultClient = &http.Client{Timeout: 135 * time.Second}+var DefaultClient = &http.Client{Timeout: httpx.MaxNavigationHTTPDuration}type Options struct {Client *http.Clientdiff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.goindex be9583ac..b66a7d31 100644--- a/internal/proxy/proxy_test.go+++ b/internal/proxy/proxy_test.go@@ -4,9 +4,9 @@ import ("encoding/json""net/http""net/http/httptest"+ "testing""github.com/pinchtab/pinchtab/internal/httpx"- "testing")func fakeBridge(t *testing.T) *httptest.Server {@@ -149,8 +149,8 @@ func TestHTTP_UsesSharedClient(t *testing.T) {if DefaultClient == nil {t.Fatal("DefaultClient should not be nil")}- if DefaultClient.Timeout != 60*1e9 { // 60 seconds in nanoseconds- t.Errorf("expected 60s timeout, got %s", DefaultClient.Timeout)+ if DefaultClient.Timeout != httpx.MaxNavigationHTTPDuration {+ t.Errorf("timeout = %s, want %s", DefaultClient.Timeout, httpx.MaxNavigationHTTPDuration)}}diff --git a/internal/server/bridge.go b/internal/server/bridge.goindex 3e1b1e3c..204a9f59 100644--- a/internal/server/bridge.go+++ b/internal/server/bridge.go@@ -97,10 +97,10 @@ func RunBridgeServer(cfg *config.RuntimeConfig, version string) {),),MaxHeaderBytes: maxHeaderBytes,- ReadHeaderTimeout: 10 * time.Second,- ReadTimeout: 30 * time.Second,- WriteTimeout: 135 * time.Second,- IdleTimeout: 120 * time.Second,+ ReadHeaderTimeout: serverReadHeaderTimeout,+ ReadTimeout: serverReadTimeout,+ WriteTimeout: serverWriteTimeout,+ IdleTimeout: serverIdleTimeout,}listener, err := net.Listen("tcp", listenAddr)diff --git a/internal/server/server.go b/internal/server/server.goindex c2c217ab..5fef181b 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -307,10 +307,10 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {Addr: cfg.Bind + ":" + dashPort,Handler: handler,MaxHeaderBytes: maxHeaderBytes,- ReadHeaderTimeout: 10 * time.Second,- ReadTimeout: 30 * time.Second,- WriteTimeout: 135 * time.Second,- IdleTimeout: 120 * time.Second,+ ReadHeaderTimeout: serverReadHeaderTimeout,+ ReadTimeout: serverReadTimeout,+ WriteTimeout: serverWriteTimeout,+ IdleTimeout: serverIdleTimeout,}if err := activeStrategy.Start(context.Background()); err != nil {diff --git a/internal/server/timeouts.go b/internal/server/timeouts.gonew file mode 100644index 00000000..b47b03f0--- /dev/null+++ b/internal/server/timeouts.go@@ -0,0 +1,14 @@+package server++import (+ "time"++ "github.com/pinchtab/pinchtab/internal/httpx"+)++const (+ serverReadHeaderTimeout = 10 * time.Second+ serverReadTimeout = 30 * time.Second+ serverWriteTimeout = httpx.MaxNavigationHTTPDuration+ serverIdleTimeout = 120 * time.Second+)diff --git a/internal/server/timeouts_test.go b/internal/server/timeouts_test.goindex 5fed96a2..bede5720 100644--- a/internal/server/timeouts_test.go+++ b/internal/server/timeouts_test.go@@ -4,28 +4,26 @@ import ("net/http""net/http/httptest""testing"- "time""github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/browsersession""github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/handlers"+ "github.com/pinchtab/pinchtab/internal/httpx")-func TestServerTimeoutOrdering(t *testing.T) {- readHeader := 10 * time.Second- read := 30 * time.Second- write := 60 * time.Second- idle := 120 * time.Second-- if readHeader >= read {- t.Errorf("ReadHeaderTimeout (%v) should be less than ReadTimeout (%v)", readHeader, read)+func TestServerTimeoutBudgets(t *testing.T) {+ if serverReadHeaderTimeout >= serverReadTimeout {+ t.Errorf("ReadHeaderTimeout (%v) should be less than ReadTimeout (%v)", serverReadHeaderTimeout, serverReadTimeout)+ }+ if serverReadTimeout >= serverWriteTimeout {+ t.Errorf("ReadTimeout (%v) should be less than WriteTimeout (%v)", serverReadTimeout, serverWriteTimeout)}- if read >= write {- t.Errorf("ReadTimeout (%v) should be less than WriteTimeout (%v)", read, write)+ if serverWriteTimeout < httpx.MaxNavigationHTTPDuration {+ t.Errorf("WriteTimeout (%v) cuts off the navigation HTTP budget (%v)", serverWriteTimeout, httpx.MaxNavigationHTTPDuration)}- if write >= idle {- t.Errorf("WriteTimeout (%v) should be less than IdleTimeout (%v)", write, idle)+ if serverIdleTimeout <= 0 {+ t.Errorf("IdleTimeout must be positive, got %v", serverIdleTimeout)}}diff --git a/skills/pinchtab/SKILL.md b/skills/pinchtab/SKILL.mdindex 8e903405..e2002da6 100644--- a/skills/pinchtab/SKILL.md+++ b/skills/pinchtab/SKILL.md@@ -128,7 +128,7 @@ The optional background daemon is for local convenience, not normal agent workfl### Navigation and tabs```bash-pinchtab nav <url> # auto-starts default local server; flags: --snap, --new-tab, --tab <id>, --block-images, --block-ads, --dismiss-banners, --print-tab-id+pinchtab nav <url> # auto-starts default local server; flags: --snap, --new-tab, --tab <id>, --timeout <seconds>, --block-images, --block-ads, --dismiss-banners, --print-tab-idpinchtab back | forward | reload # all support --snap, --snap-diff, --text, --dismiss-bannerspinchtab tab # list tabspinchtab tab <tab-id> # focus tabdiff --git a/skills/pinchtab/references/commands.md b/skills/pinchtab/references/commands.mdindex ea160a47..119b7187 100644--- a/skills/pinchtab/references/commands.md+++ b/skills/pinchtab/references/commands.md@@ -49,6 +49,7 @@ Navigate the current tracked tab to a URL, or create one when no current tab ispinchtab nav https://pinchtab.compinchtab nav https://pinchtab.com --new-tabpinchtab nav https://pinchtab.com --snap+pinchtab nav https://pinchtab.com --timeout 90pinchtab nav https://pinchtab.com --block-imagespinchtab nav https://pinchtab.com --tab <tabId>```@@ -58,6 +59,7 @@ pinchtab nav https://pinchtab.com --tab <tabId>| `--new-tab` | Explicitly force a new tab || `--tab <id>` | Reuse a specific tab || `--snap` | Navigate and print an interactive compact snapshot |+| `--timeout <seconds>` | Override the navigation timeout (maximum 120 seconds) || `--block-images` | Block image loading (faster, fewer tokens) || `--block-ads` | Block ads for this navigation || `--print-tab-id` | Print only the tab ID |diff --git a/tests/e2e/scenarios/cli/browser-basic.sh b/tests/e2e/scenarios/cli/browser-basic.shindex 935cd44a..af1351a7 100644--- a/tests/e2e/scenarios/cli/browser-basic.sh+++ b/tests/e2e/scenarios/cli/browser-basic.sh@@ -40,6 +40,13 @@ assert_tab_id "returns tab ID"end_test# ─────────────────────────────────────────────────────────────────+start_test "pinchtab nav --timeout <seconds>"++pt_ok nav "${FIXTURES_URL}/index.html" --timeout 5+assert_tab_id "accepts a per-request timeout"++end_test+start_test "pinchtab nav (empty URL)"pt_fail nav ""