High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: idle tabs keep full CPU and memory because background throttling is off for every tab; add a freeze_idle lifecycle that freezes instead of closing (PIN-369)
Luigi Agosti371f08cbf7ec
diff --git a/cmd/pinchtab/cmd_config_overview.go b/cmd/pinchtab/cmd_config_overview.goindex 1682ed40..6499b2cd 100644--- a/cmd/pinchtab/cmd_config_overview.go+++ b/cmd/pinchtab/cmd_config_overview.go@@ -52,7 +52,7 @@ func formatTabLifecycle(cfg *config.RuntimeConfig) string {if policy == "" {policy = "keep"}- if policy == "close_idle" && cfg.TabCloseDelay > 0 {+ if config.IdleTabLifecycle(policy) && cfg.TabCloseDelay > 0 {return fmt.Sprintf("%s (%s)", policy, cfg.TabCloseDelay)}return policydiff --git a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx b/dashboard/src/pages/settings/DefaultsSettingsSection.tsxindex 212d2cb3..3e9b9048 100644--- a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx+++ b/dashboard/src/pages/settings/DefaultsSettingsSection.tsx@@ -142,7 +142,7 @@ export function DefaultsSettingsSection({</SettingRow><SettingRowlabel="Tab lifecycle"- description="Optionally auto-close idle tabs after a /text, /snapshot, or /action response. The timer resets on each subsequent request and is cancelled by /navigate."+ description="Optionally close or freeze idle tabs after a /text, /snapshot, or /action response. The timer resets on each subsequent request and is cancelled by /navigate; a frozen tab unfreezes on its next request."><Selectvalue={backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "keep"}@@ -159,11 +159,12 @@ export function DefaultsSettingsSection({><option value="keep">Keep (never auto-close)</option><option value="close_idle">Close idle</option>+ <option value="freeze_idle">Freeze idle</option></Select></SettingRow><SettingRowlabel="Auto-close delay"- description="Seconds of idleness before an auto-close fires. Only applies when lifecycle is 'Close idle'."+ description="Seconds of idleness before an idle tab is closed or frozen. Only applies when lifecycle is 'Close idle' or 'Freeze idle'."><inputtype="number"@@ -178,8 +179,8 @@ export function DefaultsSettingsSection({})}disabled={- (backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "keep") !==- "close_idle"+ (backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "keep") ===+ "keep"}className={fieldClass}/>diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex c1a9b898..bec09ea5 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -122,7 +122,7 @@ export interface BackendBrowserConfig {export interface BackendTabPolicy {eviction?: "reject" | "close_oldest" | "close_lru";- lifecycle?: "keep" | "close_idle";+ lifecycle?: "keep" | "close_idle" | "freeze_idle";closeDelaySec?: number;restore?: boolean;}diff --git a/docs/core-concepts.md b/docs/core-concepts.mdindex 54df7b58..e7ea6ef9 100644--- a/docs/core-concepts.md+++ b/docs/core-concepts.md@@ -193,8 +193,12 @@ curl -X POST http://localhost:9867/close \By default, tabs use the `keep` lifecycle policy and are not auto-closed afterreads or actions. Set `instanceDefaults.tabPolicy.lifecycle` to `close_idle` toauto-close a tab after an authorized `/text`, `/snapshot`, or `/action` request-finishes. `instanceDefaults.tabPolicy.closeDelaySec` adjusts the idle delay-when `close_idle` is enabled.+finishes. Set it to `freeze_idle` to freeze the tab instead: its timers and+JavaScript stop, while its DOM, session and URL survive, and the next request+that touches the tab unfreezes it before running. A tab paused for handoff,+streaming a screencast, or holding network interception rules is never frozen.+`instanceDefaults.tabPolicy.closeDelaySec` adjusts the idle delay when+`close_idle` or `freeze_idle` is enabled.### Are tabs persistent?diff --git a/docs/reference/config.md b/docs/reference/config.mdindex 05d83305..022bfa52 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -511,8 +511,8 @@ 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.-- `closeDelaySec` is the idle delay for `close_idle`. The default is `300` seconds when auto-close is enabled.+- `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` freezes it at the same point instead (timers and JavaScript stop, the page and session stay), and any later request on the tab unfreezes it first. Tabs paused for handoff, streaming a screencast, or holding network interception rules are never frozen.+- `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`.`instanceDefaults.tabEvictionPolicy` is still accepted for compatibility. New configs should use `instanceDefaults.tabPolicy.eviction`.@@ -770,7 +770,7 @@ Valid enum values:| `instanceDefaults.stealthLevel` | `light`, `medium`, `full` || `instanceDefaults.tabEvictionPolicy` | `reject`, `close_oldest`, `close_lru` || `instanceDefaults.tabPolicy.eviction` | `reject`, `close_oldest`, `close_lru` |-| `instanceDefaults.tabPolicy.lifecycle` | `keep`, `close_idle` |+| `instanceDefaults.tabPolicy.lifecycle` | `keep`, `close_idle`, `freeze_idle` || `multiInstance.strategy` | `simple`, `explicit`, `simple-autorestart`, `always-on`, `no-instance` || `multiInstance.allocationPolicy` | `fcfs`, `round_robin`, `random` || `security.attach.allowSchemes` | `ws`, `wss`, `http`, `https` |diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex 7fcb77b6..3647501d 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -32,10 +32,8 @@ type BridgeAPI interface {CloseTab(tabID string) errorFocusTab(tabID string) error- // ScheduleAutoClose (re)arms the per-tab idle close timer when the- // lifecycle policy is "close_idle". No-op otherwise.- ScheduleAutoClose(tabID string)- CancelAutoClose(tabID string)+ ScheduleIdleLifecycle(tabID string)+ CancelIdleLifecycle(tabID string)GetRefCache(tabID string) *RefCacheSetRefCache(tabID string, cache *RefCache)diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex 25ab9495..56acc8d0 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -214,6 +214,7 @@ func (b *Bridge) wireTabManager(browserCtx context.Context) {// wire, so no cross-reinit duplication). External hooks recorded on the// bridge are re-applied so they survive the TabManager swap.b.TabManager.AddTabRemovedHook(b.dropFetchPauseSuppression)+ b.SetFreezeVeto(b.tabHandoffPaused)b.tabRemovedHooksMu.Lock()hooks := make([]func(string), len(b.externalTabRemovedHooks))copy(hooks, b.externalTabRemovedHooks)@@ -312,20 +313,20 @@ func (b *Bridge) FocusTab(tabID string) error {return tm.FocusTab(tabID)}-func (b *Bridge) ScheduleAutoClose(tabID string) {+func (b *Bridge) ScheduleIdleLifecycle(tabID string) {tm, err := b.tabManager()if err != nil {return}- tm.ScheduleAutoClose(tabID)+ tm.ScheduleIdleLifecycle(tabID)}-func (b *Bridge) CancelAutoClose(tabID string) {+func (b *Bridge) CancelIdleLifecycle(tabID string) {tm, err := b.tabManager()if err != nil {return}- tm.CancelAutoClose(tabID)+ tm.CancelIdleLifecycle(tabID)}func (b *Bridge) Lock(tabID, owner string, ttl time.Duration) error {diff --git a/internal/bridge/bridge_types.go b/internal/bridge/bridge_types.goindex f1b6f612..19967bc2 100644--- a/internal/bridge/bridge_types.go+++ b/internal/bridge/bridge_types.go@@ -25,10 +25,10 @@ type TabEntry struct {CreatorScope stringUsedByOtherScope bool- // Lifecycle auto-close timer. autoCloseGen is bumped on every (re)schedule- // so a fire that races with a reset/cancel can detect itself and bail.- autoCloseTimer *time.Timer- autoCloseGen uint64+ idleTimer *time.Timer+ idleGen uint64+ frozen bool+ awakeHolds int}type RefTarget struct {diff --git a/internal/bridge/cdpops/lifecycle.go b/internal/bridge/cdpops/lifecycle.gonew file mode 100644index 00000000..3e372dc6--- /dev/null+++ b/internal/bridge/cdpops/lifecycle.go@@ -0,0 +1,15 @@+package cdpops++import (+ "context"++ "github.com/chromedp/cdproto/page"+)++func SetPageFrozen(ctx context.Context, frozen bool) error {+ state := page.SetWebLifecycleStateStateActive+ if frozen {+ state = page.SetWebLifecycleStateStateFrozen+ }+ return page.SetWebLifecycleState(state).Do(ctx)+}diff --git a/internal/bridge/cdpops/navigation.go b/internal/bridge/cdpops/navigation.goindex 426d57b8..032c415d 100644--- a/internal/bridge/cdpops/navigation.go+++ b/internal/bridge/cdpops/navigation.go@@ -42,7 +42,7 @@ func dispatchBackgroundNavigation(ctx context.Context, url string, replaceInitiaif err := emulation.SetFocusEmulationEnabled(true).Do(ctx); err != nil {return fmt.Errorf("enable background focus emulation: %w", err)}- if err := page.SetWebLifecycleState(page.SetWebLifecycleStateStateActive).Do(ctx); err != nil {+ if err := SetPageFrozen(ctx, false); err != nil {return fmt.Errorf("activate background web lifecycle: %w", err)}return startNavigation(ctx, url, replaceInitialBlank)diff --git a/internal/bridge/handoff.go b/internal/bridge/handoff.goindex 8aad4faa..5e5308b2 100644--- a/internal/bridge/handoff.go+++ b/internal/bridge/handoff.go@@ -75,3 +75,8 @@ func (b *Bridge) TabHandoffState(tabID string) (TabHandoffState, bool) {}return state, ok}++func (b *Bridge) tabHandoffPaused(tabID string) bool {+ _, paused := b.TabHandoffState(tabID)+ return paused+}diff --git a/internal/bridge/screencast.go b/internal/bridge/screencast.goindex da9ac740..55039c61 100644--- a/internal/bridge/screencast.go+++ b/internal/bridge/screencast.go@@ -23,10 +23,29 @@ import (// mode. Polling is used for headless browsers and providers whose CDP proxy// does not support Page.startScreencast (e.g. Cloak).func (b *Bridge) StartScreencast(ctx context.Context, opts ScreencastOpts) (*ScreencastStream, error) {+ release := b.holdTabAwake(ctx)+ start := b.startScreencastEventDrivenif b.shouldUsePollingScreencast() {- return b.startScreencastPolling(ctx, opts)+ start = b.startScreencastPolling}- return b.startScreencastEventDriven(ctx, opts)+ stream, err := start(ctx, opts)+ if err != nil {+ release()+ return nil, err+ }+ go func() {+ <-stream.Done()+ release()+ }()+ return stream, nil+}++func (b *Bridge) holdTabAwake(ctx context.Context) (release func()) {+ c := chromedp.FromContext(ctx)+ if b.TabManager == nil || c == nil || c.Target == nil {+ return func() {}+ }+ return b.HoldAwake(b.IdMgr.TabIDFromCDPTarget(string(c.Target.TargetID)))}func (b *Bridge) shouldUsePollingScreencast() bool {diff --git a/internal/bridge/tab_adopt.go b/internal/bridge/tab_adopt.goindex 1f9b95a8..b55a2a57 100644--- a/internal/bridge/tab_adopt.go+++ b/internal/bridge/tab_adopt.go@@ -123,12 +123,7 @@ func (tm *TabManager) adoptExistingTarget(targetID target.ID, enforceLimit bool)if entry == nil || entry.Ctx == nil {return "", fmt.Errorf("tab %s has no active context", tabID)}- tm.mu.Lock()- tm.accessed[tabID] = true- if entry != nil {- entry.LastUsed = time.Now()- }- tm.mu.Unlock()+ tm.touchTab(tabID)return tabID, nil}diff --git a/internal/bridge/tab_autoclose.go b/internal/bridge/tab_autoclose.goindex 8ca351fb..831e4b10 100644--- a/internal/bridge/tab_autoclose.go+++ b/internal/bridge/tab_autoclose.go@@ -3,16 +3,12 @@ package bridgeimport ("log/slog""time"++ "github.com/pinchtab/pinchtab/internal/config")-// ScheduleAutoClose (re)arms the per-tab idle close timer when the lifecycle-// policy is "close_idle". Idempotent: any prior timer for the tab is-// stopped first. Safe to call from handler goroutines.-func (tm *TabManager) ScheduleAutoClose(tabID string) {- if tm == nil || tm.config == nil {- return- }- if tm.config.TabLifecyclePolicy != "close_idle" {+func (tm *TabManager) ScheduleIdleLifecycle(tabID string) {+ if tm == nil || tm.config == nil || !config.IdleTabLifecycle(tm.config.TabLifecyclePolicy) {return}delay := tm.config.TabCloseDelay@@ -21,51 +17,53 @@ func (tm *TabManager) ScheduleAutoClose(tabID string) {}tm.mu.Lock()+ defer tm.mu.Unlock()entry, ok := tm.tabs[tabID]if !ok {- tm.mu.Unlock()return}- if entry.autoCloseTimer != nil {- entry.autoCloseTimer.Stop()- }- entry.autoCloseGen++- gen := entry.autoCloseGen- entry.autoCloseTimer = time.AfterFunc(delay, func() {- tm.autoCloseFire(tabID, gen)+ entry.stopIdleTimer()+ gen := entry.idleGen+ entry.idleTimer = time.AfterFunc(delay, func() {+ tm.idleFire(tabID, gen)})- tm.mu.Unlock()}-// CancelAutoClose stops the per-tab idle close timer if any. Safe to call when-// no timer is armed; bumps the generation so an already-fired-but-not-yet-run-// callback will recognise itself as stale.-func (tm *TabManager) CancelAutoClose(tabID string) {+func (tm *TabManager) CancelIdleLifecycle(tabID string) {if tm == nil {return}tm.mu.Lock()- entry, ok := tm.tabs[tabID]- if !ok {- tm.mu.Unlock()- return+ defer tm.mu.Unlock()+ if entry, ok := tm.tabs[tabID]; ok {+ entry.stopIdleTimer()}- if entry.autoCloseTimer != nil {- entry.autoCloseTimer.Stop()- entry.autoCloseTimer = nil+}++func (e *TabEntry) stopIdleTimer() {+ if e.idleTimer != nil {+ e.idleTimer.Stop()+ e.idleTimer = nil}- entry.autoCloseGen++- tm.mu.Unlock()+ e.idleGen++}-func (tm *TabManager) autoCloseFire(tabID string, gen uint64) {+func (tm *TabManager) freezesIdleTabs() bool {+ return tm.config != nil && tm.config.TabLifecyclePolicy == "freeze_idle"+}++func (tm *TabManager) idleFire(tabID string, gen uint64) {+ if tm.freezesIdleTabs() {+ tm.freezeIdleTab(tabID, gen)+ return+ }tm.mu.Lock()entry, ok := tm.tabs[tabID]- if !ok || entry.autoCloseGen != gen {+ if !ok || entry.idleGen != gen {tm.mu.Unlock()return}- entry.autoCloseTimer = nil+ entry.idleTimer = niltm.mu.Unlock()if err := tm.CloseTab(tabID); err != nil {diff --git a/internal/bridge/tab_autoclose_test.go b/internal/bridge/tab_autoclose_test.goindex 217ba92a..8cc3ff5a 100644--- a/internal/bridge/tab_autoclose_test.go+++ b/internal/bridge/tab_autoclose_test.go@@ -24,115 +24,115 @@ func newAutoCloseTM(t *testing.T, policy string, delay time.Duration, tabID strireturn tm}-func TestScheduleAutoClose_NoOpWhenLifecycleKeep(t *testing.T) {+func TestScheduleIdleLifecycle_NoOpWhenLifecycleKeep(t *testing.T) {tm := newAutoCloseTM(t, "keep", time.Second, "tab1")- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")tm.mu.RLock()defer tm.mu.RUnlock()- if tm.tabs["tab1"].autoCloseTimer != nil {+ if tm.tabs["tab1"].idleTimer != nil {t.Fatal("timer should not be armed when lifecycle is 'keep'")}- if tm.tabs["tab1"].autoCloseGen != 0 {- t.Fatalf("gen should not advance on no-op; got %d", tm.tabs["tab1"].autoCloseGen)+ if tm.tabs["tab1"].idleGen != 0 {+ t.Fatalf("gen should not advance on no-op; got %d", tm.tabs["tab1"].idleGen)}}-func TestScheduleAutoClose_ArmsWhenCloseAfterUse(t *testing.T) {+func TestScheduleIdleLifecycle_ArmsWhenCloseAfterUse(t *testing.T) {// Use a long delay so the timer doesn't fire during the assertions.tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")tm.mu.RLock()defer tm.mu.RUnlock()entry := tm.tabs["tab1"]- if entry.autoCloseTimer == nil {+ if entry.idleTimer == nil {t.Fatal("timer should be armed when lifecycle is close_idle")}- if entry.autoCloseGen != 1 {- t.Fatalf("gen should advance to 1 on first schedule; got %d", entry.autoCloseGen)+ if entry.idleGen != 1 {+ t.Fatalf("gen should advance to 1 on first schedule; got %d", entry.idleGen)}}-func TestScheduleAutoClose_ResetBumpsGenerationAndStopsPriorTimer(t *testing.T) {+func TestScheduleIdleLifecycle_ResetBumpsGenerationAndStopsPriorTimer(t *testing.T) {tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")tm.mu.RLock()- first := tm.tabs["tab1"].autoCloseTimer+ first := tm.tabs["tab1"].idleTimertm.mu.RUnlock()- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")tm.mu.RLock()defer tm.mu.RUnlock()entry := tm.tabs["tab1"]- if entry.autoCloseGen != 2 {- t.Fatalf("gen should advance to 2 on reset; got %d", entry.autoCloseGen)+ if entry.idleGen != 2 {+ t.Fatalf("gen should advance to 2 on reset; got %d", entry.idleGen)}- if entry.autoCloseTimer == nil {+ if entry.idleTimer == nil {t.Fatal("timer should still be armed after reset")}- if entry.autoCloseTimer == first {+ if entry.idleTimer == first {t.Fatal("expected a fresh timer instance after reset")}}-func TestCancelAutoClose_StopsTimerAndBumpsGeneration(t *testing.T) {+func TestCancelIdleLifecycle_StopsTimerAndBumpsGeneration(t *testing.T) {tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")- tm.ScheduleAutoClose("tab1")- tm.CancelAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")+ tm.CancelIdleLifecycle("tab1")tm.mu.RLock()defer tm.mu.RUnlock()entry := tm.tabs["tab1"]- if entry.autoCloseTimer != nil {+ if entry.idleTimer != nil {t.Fatal("timer should be nil after cancel")}- if entry.autoCloseGen != 2 {- t.Fatalf("gen should advance on cancel; got %d", entry.autoCloseGen)+ if entry.idleGen != 2 {+ t.Fatalf("gen should advance on cancel; got %d", entry.idleGen)}}-func TestScheduleAutoClose_UnknownTabIsNoOp(t *testing.T) {+func TestScheduleIdleLifecycle_UnknownTabIsNoOp(t *testing.T) {tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")// Should not panic or affect the existing tab.- tm.ScheduleAutoClose("missing")+ tm.ScheduleIdleLifecycle("missing")tm.mu.RLock()defer tm.mu.RUnlock()- if tm.tabs["tab1"].autoCloseTimer != nil {+ if tm.tabs["tab1"].idleTimer != nil {t.Fatal("unrelated tab must not be touched")}}-func TestCancelAutoClose_UnknownTabIsNoOp(t *testing.T) {+func TestCancelIdleLifecycle_UnknownTabIsNoOp(t *testing.T) {tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")// Should not panic.- tm.CancelAutoClose("missing")+ tm.CancelIdleLifecycle("missing")}func TestAutoCloseFire_StaleGenerationIsNoOp(t *testing.T) {tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")tm.mu.RLock()- staleGen := tm.tabs["tab1"].autoCloseGen+ staleGen := tm.tabs["tab1"].idleGentm.mu.RUnlock()// Cancel bumps gen, so the captured gen is now stale.- tm.CancelAutoClose("tab1")+ tm.CancelIdleLifecycle("tab1")// Re-arm to make sure the entry is still present and timer is set again.- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")// Fire with the stale generation: must be a no-op (no CloseTab call,// timer untouched).- tm.autoCloseFire("tab1", staleGen)+ tm.idleFire("tab1", staleGen)tm.mu.RLock()defer tm.mu.RUnlock()@@ -140,7 +140,7 @@ func TestAutoCloseFire_StaleGenerationIsNoOp(t *testing.T) {if !ok {t.Fatal("entry should not be removed by stale fire")}- if entry.autoCloseTimer == nil {+ if entry.idleTimer == nil {t.Fatal("active timer should not be cleared by stale fire")}}@@ -150,7 +150,7 @@ func TestPurgeTrackedTabState_StopsAutoCloseTimer(t *testing.T) {// purge needs a Cancel func so lookupTrackedTabForCleanup returns ok=true.tm.tabs["tab1"].Cancel = func() {}- tm.ScheduleAutoClose("tab1")+ tm.ScheduleIdleLifecycle("tab1")if !tm.purgeTrackedTabState("tab1", "tab1") {t.Fatal("purgeTrackedTabState should report true for a tracked tab")diff --git a/internal/bridge/tab_cleanup.go b/internal/bridge/tab_cleanup.goindex 1981d421..75e642d2 100644--- a/internal/bridge/tab_cleanup.go+++ b/internal/bridge/tab_cleanup.go@@ -106,10 +106,8 @@ func (tm *TabManager) purgeTrackedTabState(tabID, cdpTargetID string) bool {}tm.mu.Lock()- if entry, ok := tm.tabs[resolvedTabID]; ok && entry.autoCloseTimer != nil {- entry.autoCloseTimer.Stop()- entry.autoCloseTimer = nil- entry.autoCloseGen+++ if entry, ok := tm.tabs[resolvedTabID]; ok {+ entry.stopIdleTimer()}delete(tm.tabs, resolvedTabID)delete(tm.snapshots, resolvedTabID)diff --git a/internal/bridge/tab_freeze.go b/internal/bridge/tab_freeze.gonew file mode 100644index 00000000..2cd0117e--- /dev/null+++ b/internal/bridge/tab_freeze.go@@ -0,0 +1,116 @@+package bridge++import (+ "context"+ "log/slog"+ "time"++ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/bridge/cdpops"+)++func setTabFrozen(ctx context.Context, frozen bool) error {+ return chromedp.Run(ctx, chromedp.ActionFunc(func(c context.Context) error {+ return cdpops.SetPageFrozen(c, frozen)+ }))+}++func (tm *TabManager) SetFreezeVeto(veto func(tabID string) bool) {+ tm.freezeVeto = veto+}++func (tm *TabManager) keepsAwake(tabID string) bool {+ if tm.freezeVeto != nil && tm.freezeVeto(tabID) {+ return true+ }+ return len(tm.routeMgr.List(tabID)) > 0+}++func (tm *TabManager) HoldAwake(tabID string) (release func()) {+ tm.mu.Lock()+ entry, ok := tm.tabs[tabID]+ if ok {+ entry.awakeHolds+++ }+ tm.mu.Unlock()+ if !ok {+ return func() {}+ }+ return func() {+ tm.mu.Lock()+ entry.awakeHolds--+ tm.mu.Unlock()+ }+}++func (tm *TabManager) TabFrozen(tabID string) bool {+ tm.mu.RLock()+ defer tm.mu.RUnlock()+ entry, ok := tm.tabs[tabID]+ return ok && entry.frozen+}++func (tm *TabManager) freezeIdleTab(tabID string, gen uint64) {+ if tm.keepsAwake(tabID) {+ return+ }+ tm.lifecycleMu.Lock()+ defer tm.lifecycleMu.Unlock()++ tm.mu.Lock()+ entry, ok := tm.tabs[tabID]+ if !ok || entry.idleGen != gen || entry.Ctx == nil || entry.awakeHolds > 0 {+ tm.mu.Unlock()+ return+ }+ entry.idleTimer = nil+ entry.frozen = true+ ctx := entry.Ctx+ tm.mu.Unlock()++ if err := tm.setFrozen(ctx, true); err != nil {+ tm.mu.Lock()+ entry.frozen = false+ tm.mu.Unlock()+ slog.Debug("freeze idle tab failed", "tabId", tabID, "err", err)+ return+ }+ slog.Info("tab frozen", "tabId", tabID, "reason", "freeze_idle")+}++func (tm *TabManager) thawTab(tabID string) {+ tm.lifecycleMu.Lock()+ defer tm.lifecycleMu.Unlock()++ tm.mu.Lock()+ entry, ok := tm.tabs[tabID]+ if !ok || !entry.frozen {+ tm.mu.Unlock()+ return+ }+ entry.frozen = false+ ctx := entry.Ctx+ tm.mu.Unlock()++ if err := tm.setFrozen(ctx, false); err != nil {+ slog.Warn("unfreeze tab failed", "tabId", tabID, "err", err)+ }+}++func (tm *TabManager) touchTab(tabID string) {+ tm.mu.Lock()+ tm.accessed[tabID] = true+ entry, ok := tm.tabs[tabID]+ frozen := false+ if ok {+ entry.LastUsed = time.Now()+ if tm.freezesIdleTabs() {+ entry.stopIdleTimer()+ }+ frozen = entry.frozen+ }+ tm.mu.Unlock()+ if frozen {+ tm.thawTab(tabID)+ }+}diff --git a/internal/bridge/tab_freeze_browser_test.go b/internal/bridge/tab_freeze_browser_test.gonew file mode 100644index 00000000..8158c21f--- /dev/null+++ b/internal/bridge/tab_freeze_browser_test.go@@ -0,0 +1,95 @@+package bridge++import (+ "context"+ "encoding/base64"+ "testing"+ "time"++ "github.com/chromedp/cdproto/target"+ "github.com/chromedp/chromedp"+ "github.com/pinchtab/pinchtab/internal/config"+ "github.com/pinchtab/pinchtab/internal/ids"+ "github.com/pinchtab/pinchtab/internal/testbrowser"+)++const freezeProbePage = `<button id="b" onclick="document.title='clicked'">go</button>+<script>+window.__froze = false; window.__resumed = false;+document.addEventListener('freeze', () => { window.__froze = true; });+document.addEventListener('resume', () => { window.__resumed = true; });+</script>`++func TestFreezeIdleFreezesARealTabAndAnActionUnfreezesIt(t *testing.T) {+ alloc, cancelAlloc := chromedp.NewExecAllocator(context.Background(), append(+ chromedp.DefaultExecAllocatorOptions[:],+ chromedp.ExecPath(testbrowser.Path(t)),+ chromedp.UserDataDir(testbrowser.ProfileDir(t)),+ chromedp.Flag("headless", true),+ chromedp.Flag("no-sandbox", true),+ )...)+ defer cancelAlloc()+ browserCtx, cancelBrowser := chromedp.NewContext(alloc)+ defer cancelBrowser()+ if err := chromedp.Run(browserCtx); err != nil {+ t.Fatalf("start browser: %v", err)+ }++ dataURL := "data:text/html;base64," + base64.StdEncoding.EncodeToString([]byte(freezeProbePage))+ var raw target.ID+ if err := chromedp.Run(browserCtx, chromedp.ActionFunc(func(ctx context.Context) error {+ id, err := target.CreateTarget(dataURL).WithBackground(true).Do(ctx)+ raw = id+ return err+ })); err != nil {+ t.Fatalf("create background target: %v", err)+ }+ tabCtx, cancelTab := chromedp.NewContext(browserCtx, chromedp.WithTargetID(raw))+ defer cancelTab()+ if err := chromedp.Run(tabCtx); err != nil {+ t.Fatalf("attach: %v", err)+ }++ tm := NewTabManager(browserCtx, &config.RuntimeConfig{TabLifecyclePolicy: "freeze_idle", TabCloseDelay: 50 * time.Millisecond}, nil, nil, nil)+ tabID := string(raw)+ tm.tabs[tabID] = &TabEntry{Ctx: tabCtx, CDPID: tabID, CreatedAt: time.Now(), LastUsed: time.Now()}++ b := &Bridge{TabManager: tm, IdMgr: ids.NewManager()}+ release := b.holdTabAwake(tabCtx)+ if tm.tabs[tabID].awakeHolds != 1 {+ t.Fatal("a screencast on the tab context did not hold the tab awake")+ }+ release()++ tm.ScheduleIdleLifecycle(tabID)+ deadline := time.Now().Add(5 * time.Second)+ for !tm.TabFrozen(tabID) && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ if !tm.TabFrozen(tabID) {+ t.Fatal("tab was not frozen after closeDelay")+ }++ ctx, _, err := tm.TabContext(tabID)+ if err != nil {+ t.Fatalf("tab lookup: %v", err)+ }+ actCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()+ var title string+ var froze, resumed bool+ if err := chromedp.Run(actCtx,+ chromedp.Click("#b", chromedp.ByQuery),+ chromedp.Title(&title),+ chromedp.Evaluate(`window.__froze`, &froze),+ chromedp.Evaluate(`window.__resumed`, &resumed),+ ); err != nil {+ t.Fatalf("action on a frozen tab: %v", err)+ }+ if !froze || !resumed {+ t.Fatalf("page lifecycle froze=%v resumed=%v, want both", froze, resumed)+ }+ if title != "clicked" {+ t.Fatalf("title = %q, want clicked", title)+ }+}diff --git a/internal/bridge/tab_freeze_test.go b/internal/bridge/tab_freeze_test.gonew file mode 100644index 00000000..b6ec49fd--- /dev/null+++ b/internal/bridge/tab_freeze_test.go@@ -0,0 +1,188 @@+package bridge++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/chromedp/cdproto/target"+ "github.com/pinchtab/pinchtab/internal/config"+)++type frozenRecorder struct {+ mu sync.Mutex+ calls []bool+}++func (r *frozenRecorder) set(_ context.Context, frozen bool) error {+ r.mu.Lock()+ defer r.mu.Unlock()+ r.calls = append(r.calls, frozen)+ return nil+}++func (r *frozenRecorder) snapshot() []bool {+ r.mu.Lock()+ defer r.mu.Unlock()+ return append([]bool(nil), r.calls...)+}++func newFreezeTM(t *testing.T, policy string, delay time.Duration) (*TabManager, *frozenRecorder) {+ t.Helper()+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{+ TabLifecyclePolicy: policy,+ TabCloseDelay: delay,+ }, nil, nil, nil)+ rec := &frozenRecorder{}+ tm.setFrozen = rec.set+ tm.tabs["tab1"] = &TabEntry{Ctx: context.Background(), CDPID: "tab1", CreatedAt: time.Now(), LastUsed: time.Now()}+ return tm, rec+}++func frozenOrTimeout(tm *TabManager, want bool, within time.Duration) bool {+ deadline := time.Now().Add(within)+ for time.Now().Before(deadline) {+ if tm.TabFrozen("tab1") == want {+ return true+ }+ time.Sleep(5 * time.Millisecond)+ }+ return tm.TabFrozen("tab1") == want+}++func freezeNow(t *testing.T, tm *TabManager) {+ t.Helper()+ tm.mu.RLock()+ gen := tm.tabs["tab1"].idleGen+ tm.mu.RUnlock()+ tm.freezeIdleTab("tab1", gen)+ if !tm.TabFrozen("tab1") {+ t.Fatal("tab should be frozen before the access under test")+ }+}++func TestFreezeIdleFreezesTheTabAfterTheDelay(t *testing.T) {+ tm, rec := newFreezeTM(t, "freeze_idle", 20*time.Millisecond)++ tm.ScheduleIdleLifecycle("tab1")++ if !frozenOrTimeout(tm, true, time.Second) {+ t.Fatal("tab was not frozen after closeDelay")+ }+ if got := rec.snapshot(); len(got) != 1 || !got[0] {+ t.Fatalf("lifecycle calls = %v, want [frozen]", got)+ }+ if _, ok := tm.tabs["tab1"]; !ok {+ t.Fatal("freeze_idle must keep the tab open")+ }+}++func TestCloseIdleStillClosesInsteadOfFreezing(t *testing.T) {+ tm, rec := newFreezeTM(t, "close_idle", time.Hour)+ tm.ScheduleIdleLifecycle("tab1")+ tm.mu.RLock()+ gen := tm.tabs["tab1"].idleGen+ tm.mu.RUnlock()++ tm.idleFire("tab1", gen)++ if got := rec.snapshot(); len(got) != 0 {+ t.Fatalf("close_idle froze the tab: %v", got)+ }+}++func TestEveryAccessPathUnfreezesAFrozenTab(t *testing.T) {+ cases := []struct {+ name string+ access func(tm *TabManager) error+ }{+ {"tab lookup", func(tm *TabManager) error { _, _, err := tm.TabContext("tab1"); return err }},+ {"focus", func(tm *TabManager) error { _ = tm.FocusTab("tab1"); return nil }},+ {"adopt tracked target", func(tm *TabManager) error {+ _, err := tm.adoptExistingTarget(target.ID("tab1"), false)+ return err+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ tm, rec := newFreezeTM(t, "freeze_idle", time.Hour)+ freezeNow(t, tm)++ if err := tc.access(tm); err != nil {+ t.Fatalf("access: %v", err)+ }++ if tm.TabFrozen("tab1") {+ t.Fatal("tab still frozen after access")+ }+ if got := rec.snapshot(); len(got) != 2 || got[1] {+ t.Fatalf("lifecycle calls = %v, want [frozen active]", got)+ }+ })+ }+}++func TestAccessCancelsAPendingFreeze(t *testing.T) {+ tm, rec := newFreezeTM(t, "freeze_idle", 30*time.Millisecond)+ tm.ScheduleIdleLifecycle("tab1")++ if _, _, err := tm.TabContext("tab1"); err != nil {+ t.Fatalf("access: %v", err)+ }+ time.Sleep(90 * time.Millisecond)++ if got := rec.snapshot(); len(got) != 0 {+ t.Fatalf("a tab in use was frozen: %v", got)+ }+}++func TestTabsDoingUnpolledWorkAreNeverFrozen(t *testing.T) {+ cases := []struct {+ name string+ setup func(t *testing.T, b *Bridge)+ }{+ {"handoff paused", func(t *testing.T, b *Bridge) {+ if err := b.SetTabHandoff("tab1", "", 0); err != nil {+ t.Fatal(err)+ }+ }},+ {"screencast streaming", func(t *testing.T, b *Bridge) {+ t.Cleanup(b.HoldAwake("tab1"))+ }},+ {"network interception rules", func(t *testing.T, b *Bridge) {+ b.routeMgr.mu.Lock()+ b.routeMgr.perTab["tab1"] = &tabRouteState{rules: []RouteRule{{Pattern: "*", Action: RouteActionAbort}}}+ b.routeMgr.mu.Unlock()+ }},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ b := New(context.TODO(), nil, &config.RuntimeConfig{TabLifecyclePolicy: "freeze_idle", TabCloseDelay: 10 * time.Millisecond})+ b.wireTabManager(context.Background())+ rec := &frozenRecorder{}+ b.setFrozen = rec.set+ b.tabs["tab1"] = &TabEntry{Ctx: context.Background(), CDPID: "tab1"}+ tc.setup(t, b)++ b.ScheduleIdleLifecycle("tab1")+ time.Sleep(60 * time.Millisecond)++ if got := rec.snapshot(); len(got) != 0 {+ t.Fatalf("tab was frozen: %v", got)+ }+ })+ }+}++func TestReleasedScreencastHoldLetsTheTabFreeze(t *testing.T) {+ tm, _ := newFreezeTM(t, "freeze_idle", 10*time.Millisecond)+ release := tm.HoldAwake("tab1")+ release()++ tm.ScheduleIdleLifecycle("tab1")++ if !frozenOrTimeout(tm, true, time.Second) {+ t.Fatal("tab never froze after the hold was released")+ }+}diff --git a/internal/bridge/tab_lookup.go b/internal/bridge/tab_lookup.goindex 1f7b7136..6269c2d5 100644--- a/internal/bridge/tab_lookup.go+++ b/internal/bridge/tab_lookup.go@@ -10,11 +10,8 @@ import ()func (tm *TabManager) markAccessed(tabID string) {+ tm.touchTab(tabID)tm.mu.Lock()- tm.accessed[tabID] = true- if entry, ok := tm.tabs[tabID]; ok {- entry.LastUsed = time.Now()- }tm.currentTab = tabIDtm.mu.Unlock()}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 86508014..9d5a2cc5 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -50,6 +50,9 @@ type TabManager struct {guardOnce sync.OnceguardActive boolmu sync.RWMutex+ lifecycleMu sync.Mutex+ freezeVeto func(tabID string) bool+ setFrozen func(ctx context.Context, frozen bool) error// pendingClicks tracks in-flight click actions that may open a popup.// Keyed by the opener tab's raw CDP target ID. Read by the popup guard@@ -76,6 +79,7 @@ func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgronTabSetup: onTabSetup,logStore: logStore,executor: NewTabExecutor(maxParallel),+ setFrozen: setTabFrozen,}}@@ -356,7 +360,7 @@ func (tm *TabManager) FocusTab(tabID string) error {if tm == nil {return fmt.Errorf("tab manager not initialized")}- ctx, resolvedID, err := tm.TabContext(tabID)+ ctx, _, err := tm.TabContext(tabID)if err != nil {return err}@@ -366,14 +370,6 @@ func (tm *TabManager) FocusTab(tabID string) error {})); err != nil {return fmt.Errorf("bring to front: %w", err)}-- tm.mu.Lock()- tm.currentTab = resolvedID- if entry, ok := tm.tabs[resolvedID]; ok {- entry.LastUsed = time.Now()- }- tm.mu.Unlock()-return nil}diff --git a/internal/cli/report/config_report.go b/internal/cli/report/config_report.goindex 4fe3f666..56908bdd 100644--- a/internal/cli/report/config_report.go+++ b/internal/cli/report/config_report.go@@ -41,7 +41,7 @@ func HandleConfigShow(cfg *config.RuntimeConfig) {fmt.Printf(" Max Tabs: %d\n", cfg.MaxTabs)fmt.Printf(" Stealth: %s\n", cfg.StealthLevel)fmt.Printf(" Tab Eviction: %s\n", cfg.TabEvictionPolicy)- if cfg.TabLifecyclePolicy == "close_idle" {+ if config.IdleTabLifecycle(cfg.TabLifecyclePolicy) {fmt.Printf(" Tab Lifecycle: %s (%s)\n", cfg.TabLifecyclePolicy, cfg.TabCloseDelay)} else {fmt.Printf(" Tab Lifecycle: %s\n", cfg.TabLifecyclePolicy)diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.goindex 6153b0ff..e4150a45 100644--- a/internal/config/config_file_marshal.go+++ b/internal/config/config_file_marshal.go@@ -134,7 +134,7 @@ func tabPolicyDefaultsFromRuntime(cfg *RuntimeConfig) *TabPolicyDefaults {out := &TabPolicyDefaults{}if hasLifecycle {out.Lifecycle = cfg.TabLifecyclePolicy- if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay > 0 && cfg.TabCloseDelay != 5*time.Minute {+ if IdleTabLifecycle(cfg.TabLifecyclePolicy) && cfg.TabCloseDelay > 0 && cfg.TabCloseDelay != 5*time.Minute {sec := int(cfg.TabCloseDelay / time.Second)out.CloseDelaySec = &sec}diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex cf1fb9cc..3beeaab6 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -380,6 +380,36 @@ func TestTabPolicyDefaultsFromRuntime(t *testing.T) {}}+func TestFreezeIdleRoundTripsThroughFileConfigFromRuntime(t *testing.T) {+ for _, tc := range []struct {+ name string+ delay time.Duration+ wantDelay *int+ }{+ {"default delay", 5 * time.Minute, nil},+ {"custom delay", 90 * time.Second, intPtr(90)},+ } {+ t.Run(tc.name, func(t *testing.T) {+ rt := &RuntimeConfig{TabLifecyclePolicy: "freeze_idle", TabCloseDelay: tc.delay}++ fc := FileConfigFromRuntime(rt)+ got := fc.InstanceDefaults.TabPolicy+ if got == nil || got.Lifecycle != "freeze_idle" {+ t.Fatalf("tabPolicy = %#v, want lifecycle=freeze_idle", got)+ }+ if (got.CloseDelaySec == nil) != (tc.wantDelay == nil) || (got.CloseDelaySec != nil && *got.CloseDelaySec != *tc.wantDelay) {+ t.Fatalf("closeDelaySec = %v, want %v", got.CloseDelaySec, tc.wantDelay)+ }++ back := &RuntimeConfig{TabCloseDelay: 5 * time.Minute}+ ApplyFileConfigToRuntime(back, &fc)+ if back.TabLifecyclePolicy != "freeze_idle" || back.TabCloseDelay != tc.delay {+ t.Fatalf("round trip = %q %v, want freeze_idle %v", back.TabLifecyclePolicy, back.TabCloseDelay, tc.delay)+ }+ })+ }+}+func TestDefaultFileConfigJSON(t *testing.T) {fc := DefaultFileConfig()data, err := json.MarshalIndent(fc, "", " ")diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 3215babe..9af3e561 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -725,7 +725,7 @@ func applyInstanceDefaultsConfig(cfg *RuntimeConfig, d *InstanceDefaultsConfig)cfg.TabRestore = *tp.Restore}}- if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay < time.Second {+ if IdleTabLifecycle(cfg.TabLifecyclePolicy) && cfg.TabCloseDelay < time.Second {cfg.TabCloseDelay = time.Second}if d.DialogAutoAccept != nil {diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 890ef0d2..2005fc4e 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -102,8 +102,8 @@ type RuntimeConfig struct {Humanize bool // when true, mouse moves and clicks use a humanized bezier path with per-step jitter and pre-press delays; default false (raw, fast input)StealthLevel stringTabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest" — fires on MaxTabs pressure- TabLifecyclePolicy string // "keep" (default), "close_idle" — fires on idle after read/action- TabCloseDelay time.Duration // applies when TabLifecyclePolicy == "close_idle" (default 5m when enabled)+ TabLifecyclePolicy string // "keep" (default), "close_idle", "freeze_idle" — fires on idle after read/action+ TabCloseDelay time.Duration // applies when TabLifecyclePolicy is close_idle or freeze_idle (default 5m when enabled)TabRestore bool // restore previously open tabs from sessions.json on startup (default false)ActionTimeout time.Duration@@ -429,8 +429,8 @@ type InstanceDefaultsConfig struct {// in instance-defaults configs. Either sub-field may be omitted.type TabPolicyDefaults struct {Eviction string `json:"eviction,omitempty"` // "close_lru" | "reject" | "close_oldest"- Lifecycle string `json:"lifecycle,omitempty"` // "keep" | "close_idle"- CloseDelaySec *int `json:"closeDelaySec,omitempty"` // applies to close_idle; default 300 when enabled+ Lifecycle string `json:"lifecycle,omitempty"` // "keep" | "close_idle" | "freeze_idle"+ CloseDelaySec *int `json:"closeDelaySec,omitempty"` // applies to close_idle and freeze_idle; default 300 when enabledRestore *bool `json:"restore,omitempty"` // restore tabs from sessions.json on startup; default false}diff --git a/internal/config/validate.go b/internal/config/validate.goindex 2e2c16ad..2688e05f 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -200,7 +200,7 @@ func ValidateFileConfig(fc *FileConfig) []error {if tp.Lifecycle != "" && !isValidLifecyclePolicy(tp.Lifecycle) {errs = append(errs, ValidationError{Field: "instanceDefaults.tabPolicy.lifecycle",- Message: fmt.Sprintf("invalid value %q (must be keep or close_idle)", tp.Lifecycle),+ Message: fmt.Sprintf("invalid value %q (must be keep, close_idle, or freeze_idle)", tp.Lifecycle),})}if tp.CloseDelaySec != nil && *tp.CloseDelaySec < 0 {@@ -490,7 +490,7 @@ var (cloakPlatforms = []string{"windows", "macos", "linux"}stealthLevels = []string{"light", "medium", "full"}evictionPolicies = []string{"reject", "close_oldest", "close_lru"}- lifecyclePolicies = []string{"keep", "close_idle"}+ lifecyclePolicies = []string{"keep", "close_idle", "freeze_idle"}strategies = []string{"simple", "explicit", "simple-autorestart", "always-on", "no-instance"}allocationPolicies = []string{"fcfs", "round_robin", "random"}attachSchemes = []string{"ws", "wss", "http", "https"}@@ -512,6 +512,10 @@ func isValidLifecyclePolicy(policy string) bool {return slices.Contains(lifecyclePolicies, policy)}+func IdleTabLifecycle(policy string) bool {+ return policy == "close_idle" || policy == "freeze_idle"+}+func ValidLifecyclePolicies() []string {return slices.Clone(lifecyclePolicies)}diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex 31abc50f..1cf93b9f 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -1022,6 +1022,7 @@ func TestValidateFileConfig_TabPolicyBlock(t *testing.T) {{"all empty", TabPolicyDefaults{}, false},{"valid lifecycle", TabPolicyDefaults{Lifecycle: "close_idle"}, false},{"keep lifecycle", TabPolicyDefaults{Lifecycle: "keep"}, false},+ {"freeze lifecycle", TabPolicyDefaults{Lifecycle: "freeze_idle"}, false},{"valid eviction", TabPolicyDefaults{Eviction: "reject"}, false},{"bad lifecycle", TabPolicyDefaults{Lifecycle: "burn"}, true},{"bad eviction", TabPolicyDefaults{Eviction: "drop"}, true},diff --git a/internal/handlers/a11y_audit.go b/internal/handlers/a11y_audit.goindex f5cb5902..4420aa68 100644--- a/internal/handlers/a11y_audit.go+++ b/internal/handlers/a11y_audit.go@@ -22,7 +22,7 @@ func (h *Handlers) HandleA11yAudit(w http.ResponseWriter, r *http.Request) {if !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()h.waitForReadyState(tCtx)diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 5f7ecd61..059acf7f 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -502,7 +502,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {if _, ok := h.applyTabGuards(w, r, ctx, resolvedTabID, guardDialogBlocked|guardDomainPolicy|guardHandoffPause); !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)}h.recordResolvedTab(r, resolvedTabID)w.Header().Set(activity.HeaderPTTabID, resolvedTabID)diff --git a/internal/handlers/actions_test.go b/internal/handlers/actions_test.goindex b5340a36..dc02f25f 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -481,6 +481,22 @@ func TestHandleAction_AutoCloseArmedAfterActionError(t *testing.T) {}}+func TestHandleAction_IdleLifecycleArmedUnderEveryIdlePolicy(t *testing.T) {+ for _, policy := range []string{"close_idle", "freeze_idle"} {+ t.Run(policy, func(t *testing.T) {+ mb := &mockBridge{}+ h := New(mb, &config.RuntimeConfig{ActionTimeout: time.Second, TabLifecyclePolicy: policy}, nil, nil, nil)+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click"}`)))++ h.HandleAction(httptest.NewRecorder(), req)++ if got := mb.autoCloseArmed; len(got) != 1 || got[0] != "tab1" {+ t.Fatalf("idle timer armed for %#v, want [tab1]", got)+ }+ })+ }+}+func TestHandleAction_PostRejectsInvalidDialogAction(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click","selector":"#btn","dialogAction":"maybe"}`)))diff --git a/internal/handlers/capture.go b/internal/handlers/capture.goindex a5fc1b57..a9c19c01 100644--- a/internal/handlers/capture.go+++ b/internal/handlers/capture.go@@ -113,7 +113,7 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {if !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()opts := bridge.CaptureOpts{diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 5d09f085..67b70f23 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -236,29 +236,20 @@ func (h *Handlers) ensureBrowserOrRespond(w http.ResponseWriter, cfg *config.Runreturn true}-// armAutoCloseIfEnabled (re)arms the per-tab idle close timer when the-// instance has lifecycle policy "close_idle". Call when an authorized-// read/action request has finished using the tab.-func (h *Handlers) armAutoCloseIfEnabled(tabID string) {- if h == nil || h.Bridge == nil || tabID == "" {- return- }- if h.Config == nil || h.Config.TabLifecyclePolicy != "close_idle" {- return+func (h *Handlers) armIdleLifecycle(tabID string) {+ if h.idleLifecycleActive(tabID) {+ h.Bridge.ScheduleIdleLifecycle(tabID)}- h.Bridge.ScheduleAutoClose(tabID)}-// cancelAutoCloseIfEnabled stops a pending auto-close timer. Call from-// /navigate to indicate fresh work on the tab.-func (h *Handlers) cancelAutoCloseIfEnabled(tabID string) {- if h == nil || h.Bridge == nil || tabID == "" {- return+func (h *Handlers) cancelIdleLifecycle(tabID string) {+ if h.idleLifecycleActive(tabID) {+ h.Bridge.CancelIdleLifecycle(tabID)}- if h.Config == nil || h.Config.TabLifecyclePolicy != "close_idle" {- return- }- h.Bridge.CancelAutoClose(tabID)+}++func (h *Handlers) idleLifecycleActive(tabID string) bool {+ return h != nil && h.Bridge != nil && tabID != "" && h.Config != nil && config.IdleTabLifecycle(h.Config.TabLifecyclePolicy)}// clearTabFrameScope drops any active frame scope on a tab. Call fromdiff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex caaa585f..4836c1f9 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -119,10 +119,10 @@ func (m *mockBridge) FocusTab(tabID string) error {return nil}-func (m *mockBridge) ScheduleAutoClose(tabID string) {+func (m *mockBridge) ScheduleIdleLifecycle(tabID string) {m.autoCloseArmed = append(m.autoCloseArmed, tabID)}-func (m *mockBridge) CancelAutoClose(tabID string) {+func (m *mockBridge) CancelIdleLifecycle(tabID string) {m.autoCloseCanceled = append(m.autoCloseCanceled, tabID)}diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 478e2f49..2f582a07 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -363,9 +363,9 @@ func (m *MockBridge) FocusTab(tabID string) error {return nil}-func (m *MockBridge) ScheduleAutoClose(tabID string) {}+func (m *MockBridge) ScheduleIdleLifecycle(tabID string) {}-func (m *MockBridge) CancelAutoClose(tabID string) {}+func (m *MockBridge) CancelIdleLifecycle(tabID string) {}func (m *MockBridge) GetRefCache(tabID string) *bridge.RefCache {return nildiff --git a/internal/handlers/inspect.go b/internal/handlers/inspect.goindex c074d262..2b0f78d2 100644--- a/internal/handlers/inspect.go+++ b/internal/handlers/inspect.go@@ -85,7 +85,7 @@ func (h *Handlers) handleInspect(w http.ResponseWriter, r *http.Request, kind inif !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()targetFrameID := h.resolveTargetFrameID(r, resolvedTabID)diff --git a/internal/handlers/inspect_lifecycle.go b/internal/handlers/inspect_lifecycle.goindex b937f6c5..10bb12c4 100644--- a/internal/handlers/inspect_lifecycle.go+++ b/internal/handlers/inspect_lifecycle.go@@ -96,7 +96,7 @@ func (h *Handlers) inspectElement(w http.ResponseWriter, r *http.Request, tabIDif !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)defer tCancel()diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex c7a917b2..49518781 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -440,7 +440,7 @@ func (h *Handlers) executeNavigate(w http.ResponseWriter, r *http.Request, req n}// Navigate signals fresh work on this tab — drop any pending auto-close// timer; the next read/action will re-arm.- h.cancelAutoCloseIfEnabled(resolvedTabID)+ h.cancelIdleLifecycle(resolvedTabID)tCtx, tCancel := context.WithTimeout(ctx, navTimeout)defer tCancel()diff --git a/internal/handlers/read_prelude.go b/internal/handlers/read_prelude.goindex 5fae1bc1..5c75874f 100644--- a/internal/handlers/read_prelude.go+++ b/internal/handlers/read_prelude.go@@ -39,7 +39,7 @@ func (h *Handlers) resolveReadRouting(w http.ResponseWriter, r *http.Request, ta// defer in this registration order so the LIFO semantics hold (cancel runs// before auto-close arming)://-// defer h.armAutoCloseIfEnabled(resolvedTabID)+// defer h.armIdleLifecycle(resolvedTabID)// defer cancel()func (h *Handlers) resolveReadContext(w http.ResponseWriter, r *http.Request, tabID string, actionTimeout time.Duration) (resolvedTabID string, tCtx context.Context, cancel context.CancelFunc, ok bool) {ctx, resolvedTabID, ok := h.guardedTabContextWithHeader(w, r, tabID, guardDialogBlocked|guardDomainPolicy)diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex ee8f1f1f..d97ac842 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -112,7 +112,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()if reqNoAnim && !h.Config.NoAnimations {diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex ce665df9..92702b3c 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -49,7 +49,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()targetFrameID := h.resolveTargetFrameID(r, resolvedTabID)diff --git a/internal/handlers/timing.go b/internal/handlers/timing.goindex 43f519a5..3d5d85ff 100644--- a/internal/handlers/timing.go+++ b/internal/handlers/timing.go@@ -22,7 +22,7 @@ func (h *Handlers) HandleTiming(w http.ResponseWriter, r *http.Request) {if !ok {return}- defer h.armAutoCloseIfEnabled(resolvedTabID)+ defer h.armIdleLifecycle(resolvedTabID)defer cancel()// Paint metrics (FCP/LCP) only fire on visible pages; background tabsdiff --git a/internal/schema/config.json b/internal/schema/config.jsonindex 95afc680..cc04fd2d 100644--- a/internal/schema/config.json+++ b/internal/schema/config.json@@ -423,7 +423,8 @@"enum": ["","keep",- "close_idle"+ "close_idle",+ "freeze_idle"]},"closeDelaySec": {diff --git a/plugins/grok/skills/pinchtab/TRUST.md b/plugins/grok/skills/pinchtab/TRUST.mdindex fe1d2c74..67e8230c 100644--- a/plugins/grok/skills/pinchtab/TRUST.md+++ b/plugins/grok/skills/pinchtab/TRUST.md@@ -55,7 +55,7 @@ The background daemon (`pinchtab daemon install`) is a convenience for persistenAs an alternative to the daemon, run `pinchtab server` in the foreground — it stops when the terminal closes.-Agent sessions expire after **30 minutes of idle** by default (`sessions.agent.idleTimeoutSec`), and tabs can auto-close via `tabPolicy.lifecycle: "close_idle"`.+Agent sessions expire after **30 minutes of idle** by default (`sessions.agent.idleTimeoutSec`), and tabs can auto-close via `tabPolicy.lifecycle: "close_idle"` or freeze via `"freeze_idle"`.## Builds & Verificationdiff --git a/skills/pinchtab/TRUST.md b/skills/pinchtab/TRUST.mdindex fe1d2c74..67e8230c 100644--- a/skills/pinchtab/TRUST.md+++ b/skills/pinchtab/TRUST.md@@ -55,7 +55,7 @@ The background daemon (`pinchtab daemon install`) is a convenience for persistenAs an alternative to the daemon, run `pinchtab server` in the foreground — it stops when the terminal closes.-Agent sessions expire after **30 minutes of idle** by default (`sessions.agent.idleTimeoutSec`), and tabs can auto-close via `tabPolicy.lifecycle: "close_idle"`.+Agent sessions expire after **30 minutes of idle** by default (`sessions.agent.idleTimeoutSec`), and tabs can auto-close via `tabPolicy.lifecycle: "close_idle"` or freeze via `"freeze_idle"`.## Builds & Verification