Skip to content

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

fix(bridge): a tab that cannot be unfrozen answers a retryable 503 tab_unfreeze_failed and keeps the session's current tab, instead of reading as a gone tab (PIN-369)

Luigi Agosti011752d453ba
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 5029c6fe..ea2eaf48 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -511,7 +511,7 @@ You can change or clear that default with `browser.extensionPaths`.
```
- `eviction` controls what happens when `maxTabs` is reached: `close_lru`, `close_oldest`, or `reject`.
-- `lifecycle` controls idle lifecycle behavior: `keep` disables lifecycle auto-close and is the default; `close_idle` auto-closes a tab after it handles an authorized `/text`, `/snapshot`, or `/action` request; `freeze_idle` instead freezes a tab no request has touched for the idle delay (timers and JavaScript stop, the page and session stay); every request restarts that clock and unfreezes the tab first. A tab is never frozen while a request on it is running (including a screencast stream), while it is paused for handoff, or while it holds network interception rules.
+- `lifecycle` controls idle lifecycle behavior: `keep` disables lifecycle auto-close and is the default; `close_idle` auto-closes a tab after it handles an authorized `/text`, `/snapshot`, or `/action` request; `freeze_idle` instead freezes a tab no request has touched for the idle delay (timers and JavaScript stop, the page and session stay); every request restarts that clock and unfreezes the tab first. If the renderer does not accept the unfreeze, the request answers `503` with code `tab_unfreeze_failed` and `retryable: true`; the tab and a session's current-tab pointer are kept, and the next request retries. A tab is never frozen while a request on it is running (including a screencast stream), while it is paused for handoff, or while it holds network interception rules.
- `closeDelaySec` is the idle delay for `close_idle` and `freeze_idle`. The default is `300` seconds when either is enabled.
- `restore` controls whether session tabs are restored on startup. The default is `false`.
diff --git a/internal/bridge/tab_freeze.go b/internal/bridge/tab_freeze.go
index 2fc47973..1fdecd2e 100644
--- a/internal/bridge/tab_freeze.go
+++ b/internal/bridge/tab_freeze.go
@@ -13,6 +13,21 @@ import (
const lifecycleCallTimeout = 5 * time.Second
+type TabUnfreezeError struct {
+ TabID string
+ Err error
+}
+
+func (e *TabUnfreezeError) Error() string {
+ return fmt.Sprintf("tab %s could not be unfrozen: %v", e.TabID, e.Err)
+}
+
+func (e *TabUnfreezeError) Unwrap() error { return e.Err }
+
+func (tm *TabManager) SetLifecycleWriterForTests(write func(ctx context.Context, frozen bool) error) {
+ tm.setFrozen = write
+}
+
func setTabFrozen(ctx context.Context, frozen bool) error {
return chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {
return cdpops.SetPageFrozen(c, frozen)
@@ -121,7 +136,7 @@ func (tm *TabManager) thawTab(tabID string, entry *TabEntry) error {
return nil
}
if err := tm.applyFrozen(ctx, false); err != nil {
- return fmt.Errorf("tab %s could not be unfrozen: %w", tabID, err)
+ return &TabUnfreezeError{TabID: tabID, Err: err}
}
tm.mu.Lock()
entry.frozen = false
diff --git a/internal/bridge/tab_freeze_test.go b/internal/bridge/tab_freeze_test.go
index e70d66da..32ef43ea 100644
--- a/internal/bridge/tab_freeze_test.go
+++ b/internal/bridge/tab_freeze_test.go
@@ -238,8 +238,9 @@ func TestAFailedThawFailsTheRequestAndTheNextAccessRetries(t *testing.T) {
}
_, _, err := tm.TabContext("tab1")
- if err == nil || !strings.Contains(err.Error(), "could not be unfrozen") {
- t.Fatalf("first access err = %v, want could not be unfrozen", err)
+ var unfreeze *TabUnfreezeError
+ if !errors.As(err, &unfreeze) || unfreeze.TabID != "tab1" || !strings.Contains(err.Error(), "could not be unfrozen") {
+ t.Fatalf("first access err = %v, want a TabUnfreezeError for tab1", err)
}
if !tm.TabFrozen("tab1") {
t.Fatal("a failed thaw was recorded as awake")
diff --git a/internal/handlers/activity_helpers.go b/internal/handlers/activity_helpers.go
index 809ca823..45209c4b 100644
--- a/internal/handlers/activity_helpers.go
+++ b/internal/handlers/activity_helpers.go
@@ -2,6 +2,7 @@ package handlers
import (
"context"
+ "errors"
"net/http"
"strings"
@@ -23,7 +24,8 @@ func (h *Handlers) tabContext(r *http.Request, tabID string) (context.Context, s
}
ctx, resolvedID, err := h.Bridge.TabContext(tabID)
- if err != nil && !explicitTab && !scope.IsGlobal() {
+ var unfreeze *bridge.TabUnfreezeError
+ if err != nil && !explicitTab && !scope.IsGlobal() && !errors.As(err, &unfreeze) {
h.CurrentTabs.Clear(scope)
return nil, "", noCurrentTabError(scope.Description())
}
diff --git a/internal/handlers/empty_pointer_policy.go b/internal/handlers/empty_pointer_policy.go
index 1489dc88..19a4aa75 100644
--- a/internal/handlers/empty_pointer_policy.go
+++ b/internal/handlers/empty_pointer_policy.go
@@ -56,6 +56,11 @@ func WriteTabContextError(w http.ResponseWriter, err error, notFoundStatus int)
httpx.ErrorCode(w, http.StatusConflict, "no_current_tab", err.Error(), false, nil)
return
}
+ var unfreeze *bridge.TabUnfreezeError
+ if errors.As(err, &unfreeze) {
+ httpx.ErrorCode(w, http.StatusServiceUnavailable, "tab_unfreeze_failed", err.Error(), true, nil)
+ return
+ }
if notFoundStatus == 0 {
notFoundStatus = http.StatusNotFound
}
diff --git a/internal/handlers/empty_pointer_policy_test.go b/internal/handlers/empty_pointer_policy_test.go
index 9d2d91f8..d009e6ae 100644
--- a/internal/handlers/empty_pointer_policy_test.go
+++ b/internal/handlers/empty_pointer_policy_test.go
@@ -2,6 +2,7 @@ package handlers
import (
"bytes"
+ "encoding/json"
"errors"
"fmt"
"net/http"
@@ -9,6 +10,7 @@ import (
"testing"
"github.com/pinchtab/pinchtab/internal/activity"
+ "github.com/pinchtab/pinchtab/internal/bridge"
)
func TestIsNoCurrentTab(t *testing.T) {
@@ -39,6 +41,29 @@ func TestWriteTabContextError_NoCurrentTabIs409(t *testing.T) {
}
}
+func TestWriteTabContextError_AFailedUnfreezeIsARetryable503(t *testing.T) {
+ for name, err := range map[string]error{
+ "typed": &bridge.TabUnfreezeError{TabID: "tab1", Err: errors.New("renderer busy")},
+ "wrapped": fmt.Errorf("resolve: %w", &bridge.TabUnfreezeError{TabID: "tab1", Err: errors.New("renderer busy")}),
+ } {
+ t.Run(name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ WriteTabContextError(w, err, http.StatusNotFound)
+
+ var body struct {
+ Code string `json:"code"`
+ Retryable bool `json:"retryable"`
+ }
+ if jsonErr := json.Unmarshal(w.Body.Bytes(), &body); jsonErr != nil {
+ t.Fatal(jsonErr)
+ }
+ if w.Code != http.StatusServiceUnavailable || body.Code != "tab_unfreeze_failed" || !body.Retryable {
+ t.Fatalf("got %d %+v, want 503 tab_unfreeze_failed retryable", w.Code, body)
+ }
+ })
+ }
+}
+
func TestWriteTabContextError_OtherErrorsUseFallbackStatus(t *testing.T) {
w := httptest.NewRecorder()
WriteTabContextError(w, errors.New("tab not found"), http.StatusBadRequest)
diff --git a/internal/handlers/tab_awake_hold_test.go b/internal/handlers/tab_awake_hold_test.go
index a398b773..841f7bc1 100644
--- a/internal/handlers/tab_awake_hold_test.go
+++ b/internal/handlers/tab_awake_hold_test.go
@@ -2,17 +2,23 @@ package handlers
import (
"context"
+ "encoding/json"
+ "errors"
+ "net/http"
"net/http/httptest"
+ "sync/atomic"
"testing"
"time"
"github.com/chromedp/chromedp"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/session"
"github.com/pinchtab/pinchtab/internal/testbrowser"
)
-func TestATabResolvedForARequestStaysAwakeUntilTheRequestEnds(t *testing.T) {
+func newFreezeIdleFixture(t *testing.T, delay time.Duration) (*bridge.Bridge, *Handlers) {
+ t.Helper()
alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(
chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(testbrowser.Path(t)),
@@ -26,10 +32,14 @@ func TestATabResolvedForARequestStaysAwakeUntilTheRequestEnds(t *testing.T) {
if err := chromedp.Run(tabCtx); err != nil {
t.Fatalf("start browser: %v", err)
}
- cfg := &config.RuntimeConfig{TabLifecyclePolicy: "freeze_idle", TabCloseDelay: 20 * time.Millisecond, StateDir: t.TempDir()}
+ cfg := &config.RuntimeConfig{TabLifecyclePolicy: "freeze_idle", TabCloseDelay: delay, ActionTimeout: 10 * time.Second, StateDir: t.TempDir()}
b := bridge.New(context.Background(), tabCtx, cfg)
b.RegisterTab("tabA", tabCtx)
- h := New(b, cfg, nil, nil, nil)
+ return b, New(b, cfg, nil, nil, nil)
+}
+
+func TestATabResolvedForARequestStaysAwakeUntilTheRequestEnds(t *testing.T) {
+ b, h := newFreezeIdleFixture(t, 20*time.Millisecond)
reqCtx, endRequest := context.WithCancel(context.Background())
req := httptest.NewRequest("GET", "/snapshot", nil).WithContext(reqCtx)
@@ -51,3 +61,49 @@ func TestATabResolvedForARequestStaysAwakeUntilTheRequestEnds(t *testing.T) {
t.Fatal("tab never froze after its request ended")
}
}
+
+func TestAFailedUnfreezeIsARetryable503AndKeepsTheSessionsCurrentTab(t *testing.T) {
+ b, h := newFreezeIdleFixture(t, 30*time.Millisecond)
+ var failThaw atomic.Bool
+ failThaw.Store(true)
+ b.SetLifecycleWriterForTests(func(_ context.Context, frozen bool) error {
+ if !frozen && failThaw.Swap(false) {
+ return errors.New("renderer busy")
+ }
+ return nil
+ })
+ scope := scopedCurrentTab(currentTabScopeSession, "ses_frozen")
+ h.CurrentTabs.Set(scope, "tabA")
+ b.ScheduleIdleLifecycle("tabA")
+ deadline := time.Now().Add(time.Second)
+ for !b.TabFrozen("tabA") && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if !b.TabFrozen("tabA") {
+ t.Fatal("tab never froze")
+ }
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+ text := func() *httptest.ResponseRecorder {
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, session.WithSession(httptest.NewRequest(http.MethodGet, "/text", nil), &session.Session{ID: "ses_frozen"}))
+ return w
+ }
+
+ first := text()
+ var body struct {
+ Code string `json:"code"`
+ Retryable bool `json:"retryable"`
+ }
+ _ = json.Unmarshal(first.Body.Bytes(), &body)
+ if first.Code != http.StatusServiceUnavailable || body.Code != "tab_unfreeze_failed" || !body.Retryable {
+ t.Fatalf("failed unfreeze answered %d %s, want 503 tab_unfreeze_failed retryable", first.Code, first.Body.String())
+ }
+ if got, ok := h.CurrentTabs.Get(scope); !ok || got != "tabA" {
+ t.Fatalf("session current tab = %q %v after a failed unfreeze, want tabA kept", got, ok)
+ }
+
+ if second := text(); second.Code != http.StatusOK {
+ t.Fatalf("retry after the renderer recovered answered %d %s, want 200", second.Code, second.Body.String())
+ }
+}