High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add tab close route and idle auto-close lifecycle
Luigi Agostiadb486cb0f6d
diff --git a/cmd/pinchtab/cmd_config.go b/cmd/pinchtab/cmd_config.goindex 81f9f509..0c3fd647 100644--- a/cmd/pinchtab/cmd_config.go+++ b/cmd/pinchtab/cmd_config.go@@ -134,6 +134,17 @@ func handleConfigOverview(cfg *config.RuntimeConfig) {}}+func formatTabLifecycle(cfg *config.RuntimeConfig) string {+ policy := cfg.TabLifecyclePolicy+ if policy == "" {+ policy = "keep"+ }+ if policy == "close_idle" && cfg.TabCloseDelay > 0 {+ return fmt.Sprintf("%s (%s)", policy, cfg.TabCloseDelay)+ }+ return policy+}+func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL string, running bool) string {out := ""out += cli.StyleStdout(cli.HeadingStyle, "Config") + "\n\n"@@ -141,7 +152,8 @@ func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL stout += fmt.Sprintf(" 2. %-18s %s\n", "Allocation policy", cli.StyleStdout(cli.ValueStyle, cfg.AllocationPolicy))out += fmt.Sprintf(" 3. %-18s %s\n", "Stealth level", cli.StyleStdout(cli.ValueStyle, cfg.StealthLevel))out += fmt.Sprintf(" 4. %-18s %s\n", "Tab eviction", cli.StyleStdout(cli.ValueStyle, cfg.TabEvictionPolicy))- out += fmt.Sprintf(" 5. %-18s %s\n", "Copy token", cli.StyleStdout(cli.MutedStyle, "clipboard"))+ out += fmt.Sprintf(" 5. %-18s %s\n", "Tab lifecycle", cli.StyleStdout(cli.ValueStyle, formatTabLifecycle(cfg)))+ out += fmt.Sprintf(" 6. %-18s %s\n", "Copy token", cli.StyleStdout(cli.MutedStyle, "clipboard"))out += "\n"out += cli.StyleStdout(cli.HeadingStyle, "More") + "\n\n"out += fmt.Sprintf(" %s %s\n", cli.StyleStdout(cli.MutedStyle, "File:"), cli.StyleStdout(cli.ValueStyle, configPath))@@ -153,7 +165,7 @@ func renderConfigOverview(cfg *config.RuntimeConfig, configPath, dashboardURL st}if isInteractiveTerminal() {out += "\n"- out += cli.StyleStdout(cli.MutedStyle, "Edit item (1-5, blank to exit):") + " "+ out += cli.StyleStdout(cli.MutedStyle, "Edit item (1-6, blank to exit):") + " "}out += "\n"return out@@ -183,6 +195,9 @@ func promptConfigEdit(cfg *config.RuntimeConfig) (*config.RuntimeConfig, bool, bnextCfg, changed, err := editConfigSelection("Default tab eviction", "instanceDefaults.tabEvictionPolicy", cfg.TabEvictionPolicy, config.ValidEvictionPolicies())return nextCfg, changed, false, errcase "5":+ nextCfg, changed, err := editConfigSelection("Default tab lifecycle", "instanceDefaults.tabPolicy.lifecycle", cfg.TabLifecyclePolicy, config.ValidLifecyclePolicies())+ return nextCfg, changed, false, err+ case "6":if err := copyConfigToken(cfg.Token); err != nil {return nil, false, false, err}diff --git a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx b/dashboard/src/pages/settings/DefaultsSettingsSection.tsxindex 5c1689f4..e6dbecf0 100644--- a/dashboard/src/pages/settings/DefaultsSettingsSection.tsx+++ b/dashboard/src/pages/settings/DefaultsSettingsSection.tsx@@ -140,6 +140,73 @@ export function DefaultsSettingsSection({<option value="close_lru">Close least recently used</option></Select></SettingRow>+ <SettingRow+ label="Tab lifecycle"+ description="Auto-close idle tabs after a /text, /snapshot, or /action response. The timer resets on each subsequent request and is cancelled by /navigate."+ >+ <Select+ value={+ backendConfig.instanceDefaults.tabPolicy?.lifecycle ?? "close_idle"+ }+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ tabPolicy: {+ ...(backendConfig.instanceDefaults.tabPolicy ?? {}),+ lifecycle: e.target.value as NonNullable<+ BackendConfig["instanceDefaults"]["tabPolicy"]+ >["lifecycle"],+ },+ })+ }+ >+ <option value="keep">Keep (never auto-close)</option>+ <option value="close_idle">Close idle</option>+ </Select>+ </SettingRow>+ <SettingRow+ label="Auto-close delay"+ description="Seconds of idleness before an auto-close fires. Only applies when lifecycle is 'Close idle'."+ >+ <input+ type="number"+ min={1}+ value={backendConfig.instanceDefaults.tabPolicy?.closeDelaySec ?? 300}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ tabPolicy: {+ ...(backendConfig.instanceDefaults.tabPolicy ?? {}),+ closeDelaySec: Number(e.target.value),+ },+ })+ }+ disabled={+ (backendConfig.instanceDefaults.tabPolicy?.lifecycle ??+ "close_idle") !== "close_idle"+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Restore tabs on startup"+ description="When enabled, tabs open at shutdown are reopened on the next start. Off by default — closed tabs stay closed across restarts."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.instanceDefaults.tabPolicy?.restore ?? false}+ onChange={(e) =>+ updateBackendSection("instanceDefaults", {+ tabPolicy: {+ ...(backendConfig.instanceDefaults.tabPolicy ?? {}),+ restore: e.target.checked,+ },+ })+ }+ className="h-4 w-4"+ />+ Enable+ </label>+ </SettingRow><SettingRowlabel="Max tabs"description="Maximum number of tabs per managed instance."diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex 9874bf94..cf2c26c0 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -104,6 +104,13 @@ export interface BackendBrowserConfig {extensionPaths: string[];}+export interface BackendTabPolicy {+ eviction?: "reject" | "close_oldest" | "close_lru";+ lifecycle?: "keep" | "close_idle";+ closeDelaySec?: number;+ restore?: boolean;+}+export interface BackendInstanceDefaultsConfig {mode: "headless" | "headed";noRestore: boolean;@@ -117,6 +124,7 @@ export interface BackendInstanceDefaultsConfig {noAnimations: boolean;stealthLevel: "light" | "medium" | "full";tabEvictionPolicy: "reject" | "close_oldest" | "close_lru";+ tabPolicy?: BackendTabPolicy;}export interface BackendSecurityConfig {@@ -241,6 +249,11 @@ export const defaultBackendConfig: BackendConfig = {noAnimations: false,stealthLevel: "light",tabEvictionPolicy: "close_lru",+ tabPolicy: {+ lifecycle: "close_idle",+ closeDelaySec: 300,+ restore: false,+ },},security: {allowEvaluate: false,diff --git a/docs/core-concepts.md b/docs/core-concepts.mdindex 9357a284..3e3c3322 100644--- a/docs/core-concepts.md+++ b/docs/core-concepts.md@@ -184,8 +184,19 @@ curl -X POST http://localhost:9867/tabs/$TAB/action \-d '{"kind":"click","ref":"e5"}'curl -X POST http://localhost:9867/tabs/$TAB/close++curl -X POST http://localhost:9867/close \+ -H "Content-Type: application/json" \+ -d "{\"tabId\":\"$TAB\"}"```+By default, tabs also use the `close_idle` lifecycle policy: after an authorized+`/text`, `/snapshot`, or `/action` request finishes, the tab is auto-closed+after 300 seconds unless it is touched again first. Set+`instanceDefaults.tabPolicy.lifecycle` to `keep` to disable lifecycle+auto-close, or change `instanceDefaults.tabPolicy.closeDelaySec` to adjust the+delay.+### Are tabs persistent?Usually, no.diff --git a/docs/endpoints.md b/docs/endpoints.mdindex 4c40e78d..81a79b7b 100644--- a/docs/endpoints.md+++ b/docs/endpoints.md@@ -71,6 +71,7 @@ POST /reload?tabId=<id>POST /tabs/{id}/reloadGET /tabsPOST /tab+POST /closePOST /tabs/{id}/closeGET /tabs/{id}/metricsPOST /tabs/{id}/handoff@@ -90,7 +91,8 @@ Navigation request fields:Important behavior:- `POST /navigate` creates a new tab when `tabId` is omitted-- `POST /tab` supports `new`, `close`, and `focus`+- `POST /tab` supports `new` and `focus`+- `POST /close` closes the `tabId` supplied in the JSON body, or the current/default tab when `tabId` is omitted## Handoff And Manual Interventiondiff --git a/docs/reference/cli.md b/docs/reference/cli.mdindex ddbe8a57..b58aca45 100644--- a/docs/reference/cli.md+++ b/docs/reference/cli.md@@ -209,6 +209,7 @@ pinchtab pdf --tab <id> -o page.pdf- `multiInstance.allocationPolicy`- `instanceDefaults.stealthLevel`- `instanceDefaults.tabEvictionPolicy`+- `instanceDefaults.tabPolicy.lifecycle`- the active config file path- the dashboard URL when the server is running- the masked server tokendiff --git a/docs/reference/config.md b/docs/reference/config.mdindex eefa738d..0e31cb00 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -16,6 +16,7 @@ It currently exposes these high-signal settings directly:- `multiInstance.allocationPolicy`- `instanceDefaults.stealthLevel`- `instanceDefaults.tabEvictionPolicy`+- `instanceDefaults.tabPolicy.lifecycle`It also shows:@@ -173,6 +174,11 @@ Current nested file-config shape:"noAnimations": false,"stealthLevel": "light","tabEvictionPolicy": "close_lru",+ "tabPolicy": {+ "lifecycle": "close_idle",+ "closeDelaySec": 300,+ "restore": false+ },"dialogAutoAccept": false},"security": {@@ -338,6 +344,30 @@ By default, PinchTab looks for unpacked Chrome extensions in `<server.stateDir>/You can change or clear that default with `browser.extensionPaths`.+### Tab Policy++`instanceDefaults.tabPolicy` groups tab lifecycle behavior:++```json+{+ "instanceDefaults": {+ "tabPolicy": {+ "eviction": "close_lru",+ "lifecycle": "close_idle",+ "closeDelaySec": 300,+ "restore": false+ }+ }+}+```++- `eviction` controls what happens when `maxTabs` is reached: `close_lru`, `close_oldest`, or `reject`.+- `lifecycle` controls idle lifecycle behavior: `close_idle` auto-closes a tab after it handles an authorized `/text`, `/snapshot`, or `/action` request; `keep` disables lifecycle auto-close.+- `closeDelaySec` is the idle delay for `close_idle`. The default is `300` seconds.+- `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`.+## Sections| Section | Purpose |@@ -373,6 +403,7 @@ Use `pinchtab config patch` or edit `config.json` directly for fields such as:- `server.networkBufferSize`- `browser.extensionPaths`- `instanceDefaults.dialogAutoAccept`+- `instanceDefaults.tabPolicy.*`- `security.allowClipboard`- `security.idpi.scanTimeoutSec`- `security.idpi.shieldThreshold`@@ -497,6 +528,9 @@ Use `pinchtab config init` to create the current nested format.- valid `instanceDefaults.mode`- valid `instanceDefaults.stealthLevel`- valid `instanceDefaults.tabEvictionPolicy`+- valid `instanceDefaults.tabPolicy.eviction`+- valid `instanceDefaults.tabPolicy.lifecycle`+- non-negative `instanceDefaults.tabPolicy.closeDelaySec`- `instanceDefaults.maxTabs >= 1`- `instanceDefaults.maxParallelTabs >= 0`- valid `multiInstance.strategy`@@ -517,6 +551,8 @@ Valid enum values:| `instanceDefaults.mode` | `headless`, `headed` || `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` || `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/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.mdindex 2eb6199e..0c0b07d9 100644--- a/docs/reference/mcp-tools.md+++ b/docs/reference/mcp-tools.md@@ -58,7 +58,7 @@ Selector forms include:| Tool | Key Parameters | Notes || --- | --- | --- || `pinchtab_list_tabs` | none | Lists open tabs |-| `pinchtab_close_tab` | `tabId` | Closes the given tab |+| `pinchtab_close_tab` | `tabId` optional | Closes the given tab, or the current/default tab when omitted || `pinchtab_health` | none | Checks server health || `pinchtab_cookies` | `tabId` | Reads cookies for a tab || `pinchtab_connect_profile` | `profile` required | Returns the connect URL and instance status for a profile |diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex 5c0a1fe3..03eaa667 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -24,6 +24,12 @@ 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 stops the per-tab idle close timer if any.+ CancelAutoClose(tabID string)+GetRefCache(tabID string) *RefCacheSetRefCache(tabID string, cache *RefCache)DeleteRefCache(tabID string)diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.goindex eeb5fe49..c775d453 100644--- a/internal/bridge/bridge.go+++ b/internal/bridge/bridge.go@@ -29,6 +29,11 @@ type TabEntry struct {Policy TabPolicyStateWatching boolConsoleCaptureEnabled 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}type RefTarget struct {@@ -157,6 +162,7 @@ func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridg// Only initialize TabManager if browserCtx is provided (not lazy-init case)if cfg != nil && browserCtx != nil {b.TabManager = NewTabManager(browserCtx, cfg, idMgr, logStore, b.tabSetup)+ b.SetOnAfterClose(func() { go b.SaveState() })b.SetDialogManager(b.Dialogs)b.SetNetworkMonitor(b.netMonitor)if !b.quietStealthObservers() {@@ -251,7 +257,11 @@ func (b *Bridge) CreateTab(url string) (string, context.Context, context.CancelFif err != nil {return "", nil, nil, err}- return tm.CreateTab(url)+ tabID, ctx, cancel, err := tm.CreateTab(url)+ if err == nil {+ go b.SaveState()+ }+ return tabID, ctx, cancel, err}func (b *Bridge) TabContext(tabID string) (context.Context, string, error) {@@ -275,6 +285,7 @@ func (b *Bridge) CloseTab(tabID string) error {if err != nil {return err}+ // SaveState is triggered via TabManager.onAfterClose, set during construction.return tm.CloseTab(tabID)}@@ -286,6 +297,22 @@ func (b *Bridge) FocusTab(tabID string) error {return tm.FocusTab(tabID)}+func (b *Bridge) ScheduleAutoClose(tabID string) {+ tm, err := b.tabManager()+ if err != nil {+ return+ }+ tm.ScheduleAutoClose(tabID)+}++func (b *Bridge) CancelAutoClose(tabID string) {+ tm, err := b.tabManager()+ if err != nil {+ return+ }+ tm.CancelAutoClose(tabID)+}+func (b *Bridge) Lock(tabID, owner string, ttl time.Duration) error {return b.Locks.TryLock(tabID, owner, ttl)}@@ -413,6 +440,7 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {b.LogStore = NewConsoleLogStore(1000)}b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.LogStore, b.tabSetup)+ b.SetOnAfterClose(func() { go b.SaveState() })b.SetDialogManager(b.Dialogs)b.SetNetworkMonitor(b.netMonitor)if !b.quietStealthObservers() {@@ -425,8 +453,10 @@ func (b *Bridge) EnsureChrome(cfg *config.RuntimeConfig) error {b.InitActionRegistry()}- // Restore tabs from previous session (if any saved state exists)- if b.tempProfileDir == "" {+ // Restore tabs from previous session (if any saved state exists). Opt-in+ // via instanceDefaults.tabPolicy.restore=true; otherwise tabs closed+ // before shutdown stay closed.+ if b.tempProfileDir == "" && b.Config != nil && b.Config.TabRestore {b.RestoreState()}@@ -599,6 +629,7 @@ func (b *Bridge) SetBrowserContexts(allocCtx context.Context, allocCancel contexb.LogStore = NewConsoleLogStore(1000)}b.TabManager = NewTabManager(browserCtx, b.Config, b.IdMgr, b.LogStore, b.tabSetup)+ b.SetOnAfterClose(func() { go b.SaveState() })b.SetDialogManager(b.Dialogs)b.SetNetworkMonitor(b.netMonitor)}diff --git a/internal/bridge/tab_autoclose.go b/internal/bridge/tab_autoclose.gonew file mode 100644index 00000000..8ca351fb--- /dev/null+++ b/internal/bridge/tab_autoclose.go@@ -0,0 +1,76 @@+package bridge++import (+ "log/slog"+ "time"+)++// 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" {+ return+ }+ delay := tm.config.TabCloseDelay+ if delay <= 0 {+ return+ }++ tm.mu.Lock()+ 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)+ })+ 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) {+ if tm == nil {+ return+ }+ tm.mu.Lock()+ entry, ok := tm.tabs[tabID]+ if !ok {+ tm.mu.Unlock()+ return+ }+ if entry.autoCloseTimer != nil {+ entry.autoCloseTimer.Stop()+ entry.autoCloseTimer = nil+ }+ entry.autoCloseGen+++ tm.mu.Unlock()+}++func (tm *TabManager) autoCloseFire(tabID string, gen uint64) {+ tm.mu.Lock()+ entry, ok := tm.tabs[tabID]+ if !ok || entry.autoCloseGen != gen {+ tm.mu.Unlock()+ return+ }+ entry.autoCloseTimer = nil+ tm.mu.Unlock()++ if err := tm.CloseTab(tabID); err != nil {+ slog.Debug("auto-close tab failed", "tabId", tabID, "err", err)+ return+ }+ slog.Info("tab auto-closed", "tabId", tabID, "reason", "auto_close")+}diff --git a/internal/bridge/tab_autoclose_test.go b/internal/bridge/tab_autoclose_test.gonew file mode 100644index 00000000..217ba92a--- /dev/null+++ b/internal/bridge/tab_autoclose_test.go@@ -0,0 +1,164 @@+package bridge++import (+ "context"+ "testing"+ "time"++ "github.com/pinchtab/pinchtab/internal/config"+)++// newAutoCloseTM constructs a TabManager wired with the given lifecycle policy+// and inserts a stub TabEntry under tabID.+func newAutoCloseTM(t *testing.T, policy string, delay time.Duration, tabID string) *TabManager {+ t.Helper()+ tm := NewTabManager(context.Background(), &config.RuntimeConfig{+ TabLifecyclePolicy: policy,+ TabCloseDelay: delay,+ }, nil, nil, nil)+ tm.tabs[tabID] = &TabEntry{+ CDPID: tabID,+ CreatedAt: time.Now(),+ LastUsed: time.Now(),+ }+ return tm+}++func TestScheduleAutoClose_NoOpWhenLifecycleKeep(t *testing.T) {+ tm := newAutoCloseTM(t, "keep", time.Second, "tab1")++ tm.ScheduleAutoClose("tab1")++ tm.mu.RLock()+ defer tm.mu.RUnlock()+ if tm.tabs["tab1"].autoCloseTimer != 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)+ }+}++func TestScheduleAutoClose_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.mu.RLock()+ defer tm.mu.RUnlock()+ entry := tm.tabs["tab1"]+ if entry.autoCloseTimer == 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)+ }+}++func TestScheduleAutoClose_ResetBumpsGenerationAndStopsPriorTimer(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")++ tm.ScheduleAutoClose("tab1")+ tm.mu.RLock()+ first := tm.tabs["tab1"].autoCloseTimer+ tm.mu.RUnlock()++ tm.ScheduleAutoClose("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.autoCloseTimer == nil {+ t.Fatal("timer should still be armed after reset")+ }+ if entry.autoCloseTimer == first {+ t.Fatal("expected a fresh timer instance after reset")+ }+}++func TestCancelAutoClose_StopsTimerAndBumpsGeneration(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")++ tm.ScheduleAutoClose("tab1")+ tm.CancelAutoClose("tab1")++ tm.mu.RLock()+ defer tm.mu.RUnlock()+ entry := tm.tabs["tab1"]+ if entry.autoCloseTimer != nil {+ t.Fatal("timer should be nil after cancel")+ }+ if entry.autoCloseGen != 2 {+ t.Fatalf("gen should advance on cancel; got %d", entry.autoCloseGen)+ }+}++func TestScheduleAutoClose_UnknownTabIsNoOp(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")++ // Should not panic or affect the existing tab.+ tm.ScheduleAutoClose("missing")++ tm.mu.RLock()+ defer tm.mu.RUnlock()+ if tm.tabs["tab1"].autoCloseTimer != nil {+ t.Fatal("unrelated tab must not be touched")+ }+}++func TestCancelAutoClose_UnknownTabIsNoOp(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")+ // Should not panic.+ tm.CancelAutoClose("missing")+}++func TestAutoCloseFire_StaleGenerationIsNoOp(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")++ tm.ScheduleAutoClose("tab1")+ tm.mu.RLock()+ staleGen := tm.tabs["tab1"].autoCloseGen+ tm.mu.RUnlock()++ // Cancel bumps gen, so the captured gen is now stale.+ tm.CancelAutoClose("tab1")++ // Re-arm to make sure the entry is still present and timer is set again.+ tm.ScheduleAutoClose("tab1")++ // Fire with the stale generation: must be a no-op (no CloseTab call,+ // timer untouched).+ tm.autoCloseFire("tab1", staleGen)++ tm.mu.RLock()+ defer tm.mu.RUnlock()+ entry, ok := tm.tabs["tab1"]+ if !ok {+ t.Fatal("entry should not be removed by stale fire")+ }+ if entry.autoCloseTimer == nil {+ t.Fatal("active timer should not be cleared by stale fire")+ }+}++func TestPurgeTrackedTabState_StopsAutoCloseTimer(t *testing.T) {+ tm := newAutoCloseTM(t, "close_idle", time.Hour, "tab1")+ // purge needs a Cancel func so lookupTrackedTabForCleanup returns ok=true.+ tm.tabs["tab1"].Cancel = func() {}++ tm.ScheduleAutoClose("tab1")++ if !tm.purgeTrackedTabState("tab1", "tab1") {+ t.Fatal("purgeTrackedTabState should report true for a tracked tab")+ }++ tm.mu.RLock()+ defer tm.mu.RUnlock()+ if _, ok := tm.tabs["tab1"]; ok {+ t.Fatal("entry should have been removed by purge")+ }+}diff --git a/internal/bridge/tab_manager.go b/internal/bridge/tab_manager.goindex 8586c574..85d67d4a 100644--- a/internal/bridge/tab_manager.go+++ b/internal/bridge/tab_manager.go@@ -22,21 +22,22 @@ import (type TabSetupFunc func(ctx context.Context)type TabManager struct {- browserCtx context.Context- config *config.RuntimeConfig- idMgr *ids.Manager- tabs map[string]*TabEntry- accessed map[string]bool- snapshots map[string]*RefCache- frameScope map[string]FrameScope- onTabSetup TabSetupFunc- dialogMgr *DialogManager- logStore *ConsoleLogStore- netMonitor *NetworkMonitor- currentTab string // ID of the most recently used tab- executor *TabExecutor- guardOnce sync.Once- mu sync.RWMutex+ browserCtx context.Context+ config *config.RuntimeConfig+ idMgr *ids.Manager+ tabs map[string]*TabEntry+ accessed map[string]bool+ snapshots map[string]*RefCache+ frameScope map[string]FrameScope+ onTabSetup TabSetupFunc+ onAfterClose func() // optional: invoked after any successful CloseTab+ dialogMgr *DialogManager+ logStore *ConsoleLogStore+ netMonitor *NetworkMonitor+ currentTab string // ID of the most recently used tab+ executor *TabExecutor+ guardOnce sync.Once+ mu sync.RWMutex}func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, idMgr *ids.Manager, logStore *ConsoleLogStore, onTabSetup TabSetupFunc) *TabManager {@@ -66,6 +67,15 @@ func (tm *TabManager) SetDialogManager(dm *DialogManager) {tm.dialogMgr = dm}+// SetOnAfterClose registers a callback fired whenever a tracked tab is removed+// from the manager — manual /close, eviction, auto-close lifecycle timer, or+// Chrome reporting the target gone (e.g. user closing it in a headed window).+// Used by the parent Bridge to persist session state immediately rather than+// waiting for graceful shutdown.+func (tm *TabManager) SetOnAfterClose(fn func()) {+ tm.onAfterClose = fn+}+// SetNetworkMonitor sets the network monitor for eager network capture on new tabs.func (tm *TabManager) SetNetworkMonitor(nm *NetworkMonitor) {tm.netMonitor = nm@@ -485,7 +495,6 @@ func (tm *TabManager) CloseTab(tabID string) error {slog.Debug("close target CDP", "tabId", tabID, "cdpId", cdpTargetID, "err", err)}tm.purgeTrackedTabState(tabID, cdpTargetID)-return nil}@@ -733,6 +742,11 @@ 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+++ }delete(tm.tabs, resolvedTabID)delete(tm.snapshots, resolvedTabID)delete(tm.frameScope, resolvedTabID)@@ -751,6 +765,13 @@ func (tm *TabManager) purgeTrackedTabState(tabID, cdpTargetID string) bool {if tm.logStore != nil {tm.logStore.RemoveTab(resolvedCDPID)}+ // Notify listeners (e.g. session persistence) that a tab disappeared,+ // regardless of whether the trigger was a deliberate CloseTab, an eviction,+ // the auto-close lifecycle timer, or Chrome reporting the target gone+ // (CleanStaleTabs / user closing the tab in headed Chrome directly).+ if tm.onAfterClose != nil {+ tm.onAfterClose()+ }return true}diff --git a/internal/cli/actions/actions_tabs.go b/internal/cli/actions/actions_tabs.goindex 15de420d..7a4f65c1 100644--- a/internal/cli/actions/actions_tabs.go+++ b/internal/cli/actions/actions_tabs.go@@ -68,17 +68,11 @@ func TabNew(client *http.Client, base, token string, body map[string]any, cmd *cfunc TabClose(client *http.Client, base, token string, tabID string, cmd *cobra.Command) {jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {- apiclient.DoPost(client, base, token, "/tab", map[string]any{- "action": "close",- "tabId": tabID,- })+ apiclient.DoPost(client, base, token, "/close", map[string]any{"tabId": tabID})return}- apiclient.DoPostQuiet(client, base, token, "/tab", map[string]any{- "action": "close",- "tabId": tabID,- })+ apiclient.DoPostQuiet(client, base, token, "/close", map[string]any{"tabId": tabID})output.Success()}diff --git a/internal/cli/actions/actions_tabs_test.go b/internal/cli/actions/actions_tabs_test.gonew file mode 100644index 00000000..f916f460--- /dev/null+++ b/internal/cli/actions/actions_tabs_test.go@@ -0,0 +1,29 @@+package actions++import (+ "net/http"+ "strings"+ "testing"++ "github.com/spf13/cobra"+)++func TestTabCloseUsesCloseEndpoint(t *testing.T) {+ m := newMockServer()+ defer m.close()++ cmd := &cobra.Command{}+ cmd.Flags().Bool("json", false, "")++ TabClose(http.DefaultClient, m.base(), "", "tab_123", cmd)++ if m.lastPath != "/close" {+ t.Fatalf("expected /close, got %s", m.lastPath)+ }+ if !strings.Contains(m.lastBody, `"tabId":"tab_123"`) {+ t.Fatalf("expected tabId in body, got %s", m.lastBody)+ }+ if strings.Contains(m.lastBody, "action") {+ t.Fatalf("close endpoint body should not include legacy action field, got %s", m.lastBody)+ }+}diff --git a/internal/cli/report/config_report.go b/internal/cli/report/config_report.goindex cfb89508..73a0faac 100644--- a/internal/cli/report/config_report.go+++ b/internal/cli/report/config_report.go@@ -31,6 +31,11 @@ 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" {+ fmt.Printf(" Tab Lifecycle: %s (%s)\n", cfg.TabLifecyclePolicy, cfg.TabCloseDelay)+ } else {+ fmt.Printf(" Tab Lifecycle: %s\n", cfg.TabLifecyclePolicy)+ }fmt.Printf(" Extensions: %v\n", cfg.ExtensionPaths)fmt.Println()fmt.Println(styleStdout(headingStyle, "Multi-Instance"))diff --git a/internal/config/config_file.go b/internal/config/config_file.goindex 3dccd6e3..6a07fa34 100644--- a/internal/config/config_file.go+++ b/internal/config/config_file.go@@ -205,18 +205,19 @@ type browserConfigJSON struct {}type instanceDefaultsConfigJSON struct {- Mode string `json:"mode"`- NoRestore *bool `json:"noRestore"`- Timezone string `json:"timezone"`- BlockImages *bool `json:"blockImages"`- BlockMedia *bool `json:"blockMedia"`- BlockAds *bool `json:"blockAds"`- MaxTabs *int `json:"maxTabs"`- MaxParallelTabs *int `json:"maxParallelTabs"`- UserAgent string `json:"userAgent"`- NoAnimations *bool `json:"noAnimations"`- StealthLevel string `json:"stealthLevel"`- TabEvictionPolicy string `json:"tabEvictionPolicy"`+ Mode string `json:"mode"`+ NoRestore *bool `json:"noRestore"`+ Timezone string `json:"timezone"`+ BlockImages *bool `json:"blockImages"`+ BlockMedia *bool `json:"blockMedia"`+ BlockAds *bool `json:"blockAds"`+ MaxTabs *int `json:"maxTabs"`+ MaxParallelTabs *int `json:"maxParallelTabs"`+ UserAgent string `json:"userAgent"`+ NoAnimations *bool `json:"noAnimations"`+ StealthLevel string `json:"stealthLevel"`+ TabEvictionPolicy string `json:"tabEvictionPolicy"`+ TabPolicy *TabPolicyDefaults `json:"tabPolicy,omitempty"`}type profilesConfigJSON struct {@@ -419,6 +420,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {NoAnimations: fc.InstanceDefaults.NoAnimations,StealthLevel: fc.InstanceDefaults.StealthLevel,TabEvictionPolicy: fc.InstanceDefaults.TabEvictionPolicy,+ TabPolicy: fc.InstanceDefaults.TabPolicy,},Security: securityConfigJSON{AllowEvaluate: fc.Security.AllowEvaluate,@@ -665,6 +667,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {NoAnimations: &noAnimations,StealthLevel: cfg.StealthLevel,TabEvictionPolicy: cfg.TabEvictionPolicy,+ TabPolicy: tabPolicyDefaultsFromRuntime(cfg),},Security: SecurityConfig{AllowEvaluate: &allowEvaluate,@@ -893,3 +896,32 @@ func modeToHeadless(mode string, fallback bool) bool {return fallback}}++// tabPolicyDefaultsFromRuntime emits a TabPolicyDefaults block when the runtime+// config carries any non-default tab-policy setting (lifecycle, close delay, or+// restore). Returns nil for a fully vanilla config so round-tripping doesn't+// introduce a noisy tabPolicy block.+func tabPolicyDefaultsFromRuntime(cfg *RuntimeConfig) *TabPolicyDefaults {+ if cfg == nil {+ return nil+ }+ hasLifecycle := cfg.TabLifecyclePolicy != "" &&+ (cfg.TabLifecyclePolicy != "close_idle" || cfg.TabCloseDelay != 5*time.Minute)+ hasRestore := cfg.TabRestore+ if !hasLifecycle && !hasRestore {+ return nil+ }+ out := &TabPolicyDefaults{}+ if hasLifecycle {+ out.Lifecycle = cfg.TabLifecyclePolicy+ if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay > 0 {+ sec := int(cfg.TabCloseDelay / time.Second)+ out.CloseDelaySec = &sec+ }+ }+ if hasRestore {+ v := cfg.TabRestore+ out.Restore = &v+ }+ return out+}diff --git a/internal/config/config_file_test.go b/internal/config/config_file_test.goindex e6961e39..6dc8dec4 100644--- a/internal/config/config_file_test.go+++ b/internal/config/config_file_test.go@@ -3,6 +3,7 @@ package configimport ("encoding/json""testing"+ "time")func TestDefaultFileConfig(t *testing.T) {@@ -216,6 +217,31 @@ func TestConvertLegacyConfig(t *testing.T) {}}+func TestTabPolicyDefaultsFromRuntime(t *testing.T) {+ if got := tabPolicyDefaultsFromRuntime(&RuntimeConfig{+ TabLifecyclePolicy: "close_idle",+ TabCloseDelay: 5 * time.Minute,+ }); got != nil {+ t.Fatalf("default close_idle/5m policy should not be emitted; got %#v", got)+ }++ got := tabPolicyDefaultsFromRuntime(&RuntimeConfig{+ TabLifecyclePolicy: "keep",+ TabCloseDelay: 5 * time.Minute,+ })+ if got == nil || got.Lifecycle != "keep" || got.CloseDelaySec != nil {+ t.Fatalf("keep policy = %#v, want lifecycle=keep without delay", got)+ }++ got = tabPolicyDefaultsFromRuntime(&RuntimeConfig{+ TabLifecyclePolicy: "close_idle",+ TabCloseDelay: 90 * time.Second,+ })+ if got == nil || got.Lifecycle != "close_idle" || got.CloseDelaySec == nil || *got.CloseDelaySec != 90 {+ t.Fatalf("custom close_idle policy = %#v, want lifecycle=close_idle closeDelaySec=90", got)+ }+}+// TestDefaultFileConfigJSON tests that DefaultFileConfig serializes correctly.func TestDefaultFileConfigJSON(t *testing.T) {fc := DefaultFileConfig()diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 97fd2f40..4572b0c8 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -40,25 +40,28 @@ func Load() *RuntimeConfig {MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops// Browser / instance defaults- Headless: true,- NoRestore: false,- ProfileDir: "",- ProfilesBaseDir: "",- DefaultProfile: "default",- ChromeVersion: "144.0.7559.133",- Timezone: "",- BlockImages: false,- BlockMedia: false,- BlockAds: false,- MaxTabs: 20,- MaxParallelTabs: 0,- ChromeBinary: "", // Set via config.json only- ChromeExtraFlags: "",- ExtensionPaths: []string{defaultExtensionsDir(userConfigDir())},- UserAgent: "",- NoAnimations: false,- StealthLevel: "light",- TabEvictionPolicy: "close_lru",+ Headless: true,+ NoRestore: false,+ ProfileDir: "",+ ProfilesBaseDir: "",+ DefaultProfile: "default",+ ChromeVersion: "144.0.7559.133",+ Timezone: "",+ BlockImages: false,+ BlockMedia: false,+ BlockAds: false,+ MaxTabs: 20,+ MaxParallelTabs: 0,+ ChromeBinary: "", // Set via config.json only+ ChromeExtraFlags: "",+ ExtensionPaths: []string{defaultExtensionsDir(userConfigDir())},+ UserAgent: "",+ NoAnimations: false,+ StealthLevel: "light",+ TabEvictionPolicy: "close_lru",+ TabLifecyclePolicy: "close_idle",+ TabCloseDelay: 5 * time.Minute,+ TabRestore: false,// Timeout defaultsActionTimeout: 30 * time.Second,@@ -403,6 +406,24 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.InstanceDefaults.TabEvictionPolicy != "" {cfg.TabEvictionPolicy = fc.InstanceDefaults.TabEvictionPolicy}+ if tp := fc.InstanceDefaults.TabPolicy; tp != nil {+ if tp.Eviction != "" {+ cfg.TabEvictionPolicy = tp.Eviction+ }+ if tp.Lifecycle != "" {+ cfg.TabLifecyclePolicy = tp.Lifecycle+ }+ if tp.CloseDelaySec != nil && *tp.CloseDelaySec > 0 {+ cfg.TabCloseDelay = time.Duration(*tp.CloseDelaySec) * time.Second+ }+ if tp.Restore != nil {+ cfg.TabRestore = *tp.Restore+ }+ }+ // Clamp to a sane minimum to avoid races between handler return and timer fire.+ if cfg.TabLifecyclePolicy == "close_idle" && cfg.TabCloseDelay < time.Second {+ cfg.TabCloseDelay = time.Second+ }if fc.InstanceDefaults.DialogAutoAccept != nil {cfg.DialogAutoAccept = *fc.InstanceDefaults.DialogAutoAccept}diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex ac41621b..83ebc410 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -770,3 +770,103 @@ func clearConfigEnvVars(t *testing.T) {_ = os.Unsetenv(v)}}++func writeTestConfig(t *testing.T, body string) {+ t.Helper()+ tmpDir := t.TempDir()+ path := filepath.Join(tmpDir, "config.json")+ if err := os.WriteFile(path, []byte(body), 0644); err != nil {+ t.Fatal(err)+ }+ _ = os.Setenv("PINCHTAB_CONFIG", path)+ t.Cleanup(func() { _ = os.Unsetenv("PINCHTAB_CONFIG") })+}++func TestLoadConfig_TabLifecycleDefaults(t *testing.T) {+ clearConfigEnvVars(t)+ _ = os.Setenv("PINCHTAB_CONFIG", filepath.Join(t.TempDir(), "nonexistent.json"))+ defer func() { _ = os.Unsetenv("PINCHTAB_CONFIG") }()++ cfg := Load()+ if cfg.TabLifecyclePolicy != "close_idle" {+ t.Errorf("default TabLifecyclePolicy = %q, want close_idle", cfg.TabLifecyclePolicy)+ }+ if cfg.TabCloseDelay != 5*time.Minute {+ t.Errorf("default TabCloseDelay = %v, want 5m", cfg.TabCloseDelay)+ }+}++func TestLoadConfig_TabPolicyBlockPopulatesFields(t *testing.T) {+ clearConfigEnvVars(t)+ writeTestConfig(t, `{+ "instanceDefaults": {+ "tabPolicy": {+ "eviction": "reject",+ "lifecycle": "close_idle",+ "closeDelaySec": 30+ }+ }+ }`)++ cfg := Load()+ if cfg.TabEvictionPolicy != "reject" {+ t.Errorf("TabEvictionPolicy = %q, want reject", cfg.TabEvictionPolicy)+ }+ if cfg.TabLifecyclePolicy != "close_idle" {+ t.Errorf("TabLifecyclePolicy = %q, want close_idle", cfg.TabLifecyclePolicy)+ }+ if cfg.TabCloseDelay != 30*time.Second {+ t.Errorf("TabCloseDelay = %v, want 30s", cfg.TabCloseDelay)+ }+}++func TestLoadConfig_LegacyTabEvictionPolicyStillHonored(t *testing.T) {+ clearConfigEnvVars(t)+ writeTestConfig(t, `{+ "instanceDefaults": {+ "tabEvictionPolicy": "close_oldest"+ }+ }`)++ cfg := Load()+ if cfg.TabEvictionPolicy != "close_oldest" {+ t.Errorf("legacy tabEvictionPolicy not honored; got %q", cfg.TabEvictionPolicy)+ }+ // Lifecycle defaults preserved (default is close_idle).+ if cfg.TabLifecyclePolicy != "close_idle" {+ t.Errorf("legacy-only config should leave lifecycle at default close_idle; got %q", cfg.TabLifecyclePolicy)+ }+}++func TestLoadConfig_TabPolicyWinsOverLegacyEviction(t *testing.T) {+ clearConfigEnvVars(t)+ writeTestConfig(t, `{+ "instanceDefaults": {+ "tabEvictionPolicy": "close_oldest",+ "tabPolicy": {+ "eviction": "reject"+ }+ }+ }`)++ cfg := Load()+ if cfg.TabEvictionPolicy != "reject" {+ t.Errorf("tabPolicy.eviction should override legacy field; got %q", cfg.TabEvictionPolicy)+ }+}++func TestLoadConfig_TabCloseDelayPreservesDefaultWhenAbsent(t *testing.T) {+ clearConfigEnvVars(t)+ writeTestConfig(t, `{+ "instanceDefaults": {+ "tabPolicy": {+ "lifecycle": "close_idle"+ }+ }+ }`)++ cfg := Load()+ if cfg.TabCloseDelay != 5*time.Minute {+ t.Errorf("TabCloseDelay = %v, want 5m default", cfg.TabCloseDelay)+ }+}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 8914d01a..731b1837 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -41,27 +41,30 @@ type RuntimeConfig struct {TrustedResolveCIDRs []string // CIDRs/IPs allowed when a navigation target resolves to non-public addresses// Browser/instance settings- Headless bool- HeadlessSet bool // true when explicitly set via config or flag- NoRestore bool- ProfileDir string- ProfilesBaseDir string- DefaultProfile string- ChromeVersion string- Timezone string- BlockImages bool- BlockMedia bool- BlockAds bool- MaxTabs int- MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU- ChromeBinary string- ChromeDebugPort int- ChromeExtraFlags string- ExtensionPaths []string- UserAgent string- NoAnimations bool- StealthLevel string- TabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest"+ Headless bool+ HeadlessSet bool // true when explicitly set via config or flag+ NoRestore bool+ ProfileDir string+ ProfilesBaseDir string+ DefaultProfile string+ ChromeVersion string+ Timezone string+ BlockImages bool+ BlockMedia bool+ BlockAds bool+ MaxTabs int+ MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU+ ChromeBinary string+ ChromeDebugPort int+ ChromeExtraFlags string+ ExtensionPaths []string+ UserAgent string+ NoAnimations bool+ StealthLevel string+ TabEvictionPolicy string // "close_lru" (default), "reject", "close_oldest" — fires on MaxTabs pressure+ TabLifecyclePolicy string // "close_idle" (default), "keep" — fires on idle after read/action+ TabCloseDelay time.Duration // applies when TabLifecyclePolicy == "close_idle" (default 5m)+ TabRestore bool // restore previously open tabs from sessions.json on startup (default false)// Timeout settingsActionTimeout time.Duration@@ -278,19 +281,29 @@ type BrowserConfig struct {}type InstanceDefaultsConfig struct {- Mode string `json:"mode,omitempty"`- NoRestore *bool `json:"noRestore,omitempty"`- Timezone string `json:"timezone,omitempty"`- BlockImages *bool `json:"blockImages,omitempty"`- BlockMedia *bool `json:"blockMedia,omitempty"`- BlockAds *bool `json:"blockAds,omitempty"`- MaxTabs *int `json:"maxTabs,omitempty"`- MaxParallelTabs *int `json:"maxParallelTabs,omitempty"`- UserAgent string `json:"userAgent,omitempty"`- NoAnimations *bool `json:"noAnimations,omitempty"`- StealthLevel string `json:"stealthLevel,omitempty"`- TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"`- DialogAutoAccept *bool `json:"dialogAutoAccept,omitempty"`+ Mode string `json:"mode,omitempty"`+ NoRestore *bool `json:"noRestore,omitempty"`+ Timezone string `json:"timezone,omitempty"`+ BlockImages *bool `json:"blockImages,omitempty"`+ BlockMedia *bool `json:"blockMedia,omitempty"`+ BlockAds *bool `json:"blockAds,omitempty"`+ MaxTabs *int `json:"maxTabs,omitempty"`+ MaxParallelTabs *int `json:"maxParallelTabs,omitempty"`+ UserAgent string `json:"userAgent,omitempty"`+ NoAnimations *bool `json:"noAnimations,omitempty"`+ StealthLevel string `json:"stealthLevel,omitempty"`+ TabEvictionPolicy string `json:"tabEvictionPolicy,omitempty"` // Deprecated: use TabPolicy.Eviction+ TabPolicy *TabPolicyDefaults `json:"tabPolicy,omitempty"`+ DialogAutoAccept *bool `json:"dialogAutoAccept,omitempty"`+}++// TabPolicyDefaults groups eviction (cap pressure) and lifecycle (idle) policies+// 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+ Restore *bool `json:"restore,omitempty"` // restore tabs from sessions.json on startup; default false}type ProfilesConfig struct {diff --git a/internal/config/editor_get.go b/internal/config/editor_get.goindex 2c4d6061..e81e3fd4 100644--- a/internal/config/editor_get.go+++ b/internal/config/editor_get.go@@ -146,6 +146,9 @@ func getDashboardSessionField(s *DashboardSessionFileConfig, field string) (stri}func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string, error) {+ if after, ok := strings.CutPrefix(field, "tabPolicy."); ok {+ return getTabPolicyField(c.TabPolicy, after)+ }switch field {case "mode":return c.Mode, nil@@ -176,6 +179,22 @@ func getInstanceDefaultsField(c *InstanceDefaultsConfig, field string) (string,}}+func getTabPolicyField(tp *TabPolicyDefaults, field string) (string, error) {+ if tp == nil {+ tp = &TabPolicyDefaults{}+ }+ switch field {+ case "eviction":+ return tp.Eviction, nil+ case "lifecycle":+ return tp.Lifecycle, nil+ case "closeDelaySec":+ return formatIntPtr(tp.CloseDelaySec), nil+ default:+ return "", fmt.Errorf("unknown field instanceDefaults.tabPolicy.%s", field)+ }+}+func getSecurityField(s *SecurityConfig, field string) (string, error) {if strings.HasPrefix(field, "attach.") {return getAttachField(&s.Attach, strings.TrimPrefix(field, "attach."))diff --git a/internal/config/editor_set.go b/internal/config/editor_set.goindex ae6d0231..1a46d1f4 100644--- a/internal/config/editor_set.go+++ b/internal/config/editor_set.go@@ -205,6 +205,12 @@ func setDashboardSessionField(s *DashboardSessionFileConfig, field, value string}func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) error {+ if strings.HasPrefix(field, "tabPolicy.") {+ if c.TabPolicy == nil {+ c.TabPolicy = &TabPolicyDefaults{}+ }+ return setTabPolicyField(c.TabPolicy, strings.TrimPrefix(field, "tabPolicy."), value)+ }switch field {case "mode":c.Mode = value@@ -264,6 +270,24 @@ func setInstanceDefaultsField(c *InstanceDefaultsConfig, field, value string) erreturn nil}+func setTabPolicyField(tp *TabPolicyDefaults, field, value string) error {+ switch field {+ case "eviction":+ tp.Eviction = value+ case "lifecycle":+ tp.Lifecycle = value+ case "closeDelaySec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("instanceDefaults.tabPolicy.closeDelaySec must be a number: %w", err)+ }+ tp.CloseDelaySec = &n+ default:+ return fmt.Errorf("unknown field instanceDefaults.tabPolicy.%s", field)+ }+ return nil+}+func setSecurityField(s *SecurityConfig, field, value string) error {if strings.HasPrefix(field, "attach.") {return setAttachField(&s.Attach, strings.TrimPrefix(field, "attach."), value)diff --git a/internal/config/validate.go b/internal/config/validate.goindex 2c85105b..ffc47204 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -105,6 +105,26 @@ func ValidateFileConfig(fc *FileConfig) []error {})}}+ if tp := fc.InstanceDefaults.TabPolicy; tp != nil {+ if tp.Eviction != "" && !isValidEvictionPolicy(tp.Eviction) {+ errs = append(errs, ValidationError{+ Field: "instanceDefaults.tabPolicy.eviction",+ Message: fmt.Sprintf("invalid value %q (must be reject, close_oldest, or close_lru)", tp.Eviction),+ })+ }+ 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),+ })+ }+ if tp.CloseDelaySec != nil && *tp.CloseDelaySec < 0 {+ errs = append(errs, ValidationError{+ Field: "instanceDefaults.tabPolicy.closeDelaySec",+ Message: fmt.Sprintf("must be >= 0 (got %d)", *tp.CloseDelaySec),+ })+ }+ }if fc.InstanceDefaults.MaxTabs != nil && *fc.InstanceDefaults.MaxTabs < 1 {errs = append(errs, ValidationError{Field: "instanceDefaults.maxTabs",@@ -330,6 +350,19 @@ func isValidEvictionPolicy(policy string) bool {}}+func isValidLifecyclePolicy(policy string) bool {+ switch policy {+ case "keep", "close_idle":+ return true+ default:+ return false+ }+}++func ValidLifecyclePolicies() []string {+ return []string{"keep", "close_idle"}+}+func isValidStrategy(strategy string) bool {switch strategy {case "simple", "explicit", "simple-autorestart", "always-on", "no-instance":diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex ce46cfa8..de2257cd 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -872,3 +872,38 @@ func TestValidateIDPIConfig_ScanTimeoutSec(t *testing.T) {}})}++func TestValidateFileConfig_TabPolicyBlock(t *testing.T) {+ negative := -1+ zero := 0+ positive := 100+ tests := []struct {+ name string+ tp TabPolicyDefaults+ wantErr bool+ }{+ {"all empty", TabPolicyDefaults{}, false},+ {"valid lifecycle", TabPolicyDefaults{Lifecycle: "close_idle"}, false},+ {"keep lifecycle", TabPolicyDefaults{Lifecycle: "keep"}, false},+ {"valid eviction", TabPolicyDefaults{Eviction: "reject"}, false},+ {"bad lifecycle", TabPolicyDefaults{Lifecycle: "burn"}, true},+ {"bad eviction", TabPolicyDefaults{Eviction: "drop"}, true},+ {"negative delay", TabPolicyDefaults{Lifecycle: "close_idle", CloseDelaySec: &negative}, true},+ {"zero delay ok", TabPolicyDefaults{Lifecycle: "close_idle", CloseDelaySec: &zero}, false},+ {"positive delay ok", TabPolicyDefaults{Lifecycle: "close_idle", CloseDelaySec: &positive}, false},+ }++ for _, tt := range tests {+ tt := tt+ t.Run(tt.name, func(t *testing.T) {+ fc := &FileConfig{+ InstanceDefaults: InstanceDefaultsConfig{TabPolicy: &tt.tp},+ }+ errs := ValidateFileConfig(fc)+ hasErr := len(errs) > 0+ if hasErr != tt.wantErr {+ t.Errorf("got errs=%v, want error=%v", errs, tt.wantErr)+ }+ })+ }+}diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 50a5bf07..52c20515 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -182,6 +182,7 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {httpx.ErrorCode(w, 409, "tab_paused_handoff", err.Error(), false, h.handoffErrorDetails(resolvedTabID))return}+ defer h.armAutoCloseIfEnabled(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 10b10f53..36830b6d 100644--- a/internal/handlers/actions_test.go+++ b/internal/handlers/actions_test.go@@ -459,6 +459,25 @@ func TestHandleAction_InvalidJSON(t *testing.T) {}}+func TestHandleAction_AutoCloseArmedAfterActionError(t *testing.T) {+ mb := &mockBridge{executeActionErr: fmt.Errorf("boom")}+ h := New(mb, &config.RuntimeConfig{+ ActionTimeout: time.Second,+ TabLifecyclePolicy: "close_idle",+ }, nil, nil, nil)+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`{"kind":"click"}`)))+ w := httptest.NewRecorder()++ h.HandleAction(w, req)++ if w.Code != 500 {+ t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String())+ }+ if got := mb.autoCloseArmed; len(got) != 1 || got[0] != "tab1" {+ t.Fatalf("autoCloseArmed = %#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/handlers.go b/internal/handlers/handlers.goindex 749758b8..2b2fe560 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -129,6 +129,31 @@ func (h *Handlers) ensureChromeOrRespond(w http.ResponseWriter) bool {return 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+ }+ 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+ }+ if h.Config == nil || h.Config.TabLifecyclePolicy != "close_idle" {+ return+ }+ h.Bridge.CancelAutoClose(tabID)+}+func (h *Handlers) bridgeRestartStatus() (bool, time.Duration) {provider, ok := h.Bridge.(restartStatusProvider)if !ok {@@ -202,6 +227,8 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /actions", h.HandleActions)mux.HandleFunc("POST /macro", h.HandleMacro)mux.HandleFunc("POST /tab", h.HandleTab)+ mux.HandleFunc("POST /close", h.HandleClose)+ mux.HandleFunc("POST /tabs/{id}/close", h.HandleTabClose)mux.HandleFunc("POST /lock", h.HandleTabLock)mux.HandleFunc("POST /unlock", h.HandleTabUnlock)mux.HandleFunc("POST /tabs/{id}/lock", h.HandleTabLockByID)diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex 8da9f29c..13559747 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -13,21 +13,25 @@ import ("time""github.com/chromedp/cdproto/target"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge""github.com/pinchtab/pinchtab/internal/config")type mockBridge struct {bridge.BridgeAPI- failTab bool- createTabURLs []string- lastConsoleLimit int- lastErrorLimit int- fingerprintTabs map[string]bool- frameScopes map[string]bridge.FrameScope- ensureChromeErr error- ensureChromeCall int- dialogManager *bridge.DialogManager+ failTab bool+ createTabURLs []string+ lastConsoleLimit int+ lastErrorLimit int+ fingerprintTabs map[string]bool+ frameScopes map[string]bridge.FrameScope+ ensureChromeErr error+ ensureChromeCall int+ dialogManager *bridge.DialogManager+ executeActionErr error+ autoCloseArmed []string+ autoCloseCanceled []string}func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {@@ -48,6 +52,9 @@ func (m *mockBridge) AvailableActions() []string {}func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {+ if m.executeActionErr != nil {+ return nil, m.executeActionErr+ }return map[string]any{"success": true}, nil}@@ -72,6 +79,13 @@ func (m *mockBridge) FocusTab(tabID string) error {return nil}+func (m *mockBridge) ScheduleAutoClose(tabID string) {+ m.autoCloseArmed = append(m.autoCloseArmed, tabID)+}+func (m *mockBridge) CancelAutoClose(tabID string) {+ m.autoCloseCanceled = append(m.autoCloseCanceled, tabID)+}+func (m *mockBridge) EnsureChrome(cfg *config.RuntimeConfig) error {m.ensureChromeCall++return m.ensureChromeErr@@ -359,14 +373,110 @@ func TestHandleTab(t *testing.T) {if m.createTabURLs[0] != "" {t.Fatalf("expected HandleTab to create a blank tab first, got %q", m.createTabURLs[0])}+}- // Close Tab- body = `{"action": "close", "tabId": "tab1"}`- req = httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))- w = httptest.NewRecorder()- h.HandleTab(w, req)- if w.Code != 200 {- t.Errorf("expected 200, got %d", w.Code)+func TestHandleTabCloseByID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/tabs/tab1/close", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab1" {+ t.Fatalf("expected %s=tab1, got %q", activity.HeaderPTTabID, got)+ }++ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["closed"] != true || resp["tabId"] != "tab1" {+ t.Fatalf("unexpected response: %#v", resp)+ }+}++func TestHandleClose(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/close", bytes.NewReader([]byte(`{"tabId":"tab1"}`)))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab1" {+ t.Fatalf("expected %s=tab1, got %q", activity.HeaderPTTabID, got)+ }++ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["closed"] != true || resp["tabId"] != "tab1" {+ t.Fatalf("unexpected response: %#v", resp)+ }+}++func TestHandleCloseUsesDefaultTabWhenTabIDIsMissing(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/close", bytes.NewReader([]byte(`{}`)))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab1" {+ t.Fatalf("expected %s=tab1, got %q", activity.HeaderPTTabID, got)+ }+ var resp map[string]any+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ if resp["closed"] != true || resp["tabId"] != "tab1" {+ t.Fatalf("unexpected response: %#v", resp)+ }+}++func TestHandleCloseUsesDefaultTabWithEmptyBody(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/close", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := w.Header().Get(activity.HeaderPTTabID); got != "tab1" {+ t.Fatalf("expected %s=tab1, got %q", activity.HeaderPTTabID, got)+ }+}++func TestHandleTabCloseByIDRejectsMismatchedBodyTabID(t *testing.T) {+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)+ mux := http.NewServeMux()+ h.RegisterRoutes(mux, nil)++ req := httptest.NewRequest(http.MethodPost, "/tabs/tab1/close", bytes.NewReader([]byte(`{"tabId":"tab2"}`)))+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())}}diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 919ca357..dce16f09 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -386,6 +386,10 @@ func (m *MockBridge) FocusTab(tabID string) error {return nil}+func (m *MockBridge) ScheduleAutoClose(tabID string) {}++func (m *MockBridge) CancelAutoClose(tabID string) {}+func (m *MockBridge) GetRefCache(tabID string) *bridge.RefCache {return nil}diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.goindex 0b860d6b..0e1d303d 100644--- a/internal/handlers/navigation.go+++ b/internal/handlers/navigation.go@@ -261,6 +261,9 @@ func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 404, err)return}+ // Navigate signals fresh work on this tab — drop any pending auto-close+ // timer; the next read/action will re-arm.+ h.cancelAutoCloseIfEnabled(resolvedTabID)tCtx, tCancel := context.WithTimeout(ctx, navTimeout)defer tCancel()@@ -359,10 +362,7 @@ func (h *Handlers) HandleTabNavigate(w http.ResponseWriter, r *http.Request) {h.HandleNavigate(w, req)}-const (- tabActionNew = "new"- tabActionClose = "close"-)+const tabActionNew = "new"func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {var req struct {@@ -446,7 +446,7 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {httpx.JSON(w, 200, map[string]any{"tabId": newTabID, "url": curURL, "title": title})- case tabActionClose:+ case "focus":if req.TabID == "" {httpx.Error(w, 400, fmt.Errorf("tabId required"))return@@ -454,36 +454,83 @@ func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {if !h.ensureChromeOrRespond(w) {return}-- if err := h.Bridge.CloseTab(req.TabID); err != nil {- httpx.Error(w, 500, err)+ if err := h.Bridge.FocusTab(req.TabID); err != nil {+ httpx.Error(w, 404, err)return}- h.recordActivity(r, activity.Update{Action: "tab.close", TabID: req.TabID})+ h.recordActivity(r, activity.Update{Action: "tab.focus", TabID: req.TabID})- httpx.JSON(w, 200, map[string]any{"closed": true})+ httpx.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})- case "focus":- if req.TabID == "" {- httpx.Error(w, 400, fmt.Errorf("tabId required"))+ default:+ httpx.Error(w, 400, fmt.Errorf("action must be 'new' or 'focus'; use /close to close a tab"))+ }+}++// HandleTabClose closes the tab identified by the path. It is the tab-scoped+// equivalent of POST /close and exists so orchestrator dashboard commands can+// use the common /tabs/{id}/... proxy path.+func (h *Handlers) HandleTabClose(w http.ResponseWriter, r *http.Request) {+ tabID := strings.TrimSpace(r.PathValue("id"))+ if tabID == "" {+ httpx.Error(w, 400, fmt.Errorf("tab id required"))+ return+ }++ if r.Body != nil && r.Body != http.NoBody && r.ContentLength != 0 {+ var req struct {+ TabID string `json:"tabId"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))return}- if !h.ensureChromeOrRespond(w) {+ if req.TabID != "" && req.TabID != tabID {+ httpx.Error(w, 400, fmt.Errorf("tabId in body does not match path id"))return}- if err := h.Bridge.FocusTab(req.TabID); err != nil {+ }++ h.closeTab(w, r, tabID)+}++// HandleClose closes the tab identified by the JSON body, or the current/default+// tab when tabId is omitted. It is the shorthand form of POST /tabs/{id}/close.+func (h *Handlers) HandleClose(w http.ResponseWriter, r *http.Request) {+ var req struct {+ TabID string `json:"tabId"`+ }+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil && !errors.Is(err, io.EOF) {+ httpx.Error(w, 400, fmt.Errorf("decode: %w", err))+ return+ }++ h.closeTab(w, r, strings.TrimSpace(req.TabID))+}++func (h *Handlers) closeTab(w http.ResponseWriter, r *http.Request, tabID string) {+ if !h.ensureChromeOrRespond(w) {+ return+ }+ if tabID == "" {+ _, resolvedTabID, err := h.tabContext(r, "")+ if err != nil {httpx.Error(w, 404, err)return}+ tabID = resolvedTabID+ }- h.recordActivity(r, activity.Update{Action: "tab.focus", TabID: req.TabID})+ if err := h.Bridge.CloseTab(tabID); err != nil {+ httpx.Error(w, 500, err)+ return+ }- httpx.JSON(w, 200, map[string]any{"focused": true, "tabId": req.TabID})+ h.recordActivity(r, activity.Update{Action: "tab.close", TabID: tabID})+ w.Header().Set(activity.HeaderPTTabID, tabID)- default:- httpx.Error(w, 400, fmt.Errorf("action must be 'new', 'close', or 'focus'"))- }+ httpx.JSON(w, 200, map[string]any{"closed": true, "tabId": tabID})}// HandleTabBack navigates a specific tab back in history.diff --git a/internal/handlers/navigation_test.go b/internal/handlers/navigation_test.goindex 21738640..b9aca214 100644--- a/internal/handlers/navigation_test.go+++ b/internal/handlers/navigation_test.go@@ -401,7 +401,7 @@ func TestHandleTab_InvalidAction(t *testing.T) {}}-func TestHandleTab_CloseMissingID(t *testing.T) {+func TestHandleTab_CloseActionUnsupported(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)body := `{"action":"close"}`req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))@@ -410,6 +410,9 @@ func TestHandleTab_CloseMissingID(t *testing.T) {if w.Code != 400 {t.Errorf("expected 400, got %d", w.Code)}+ if !strings.Contains(w.Body.String(), "/close") {+ t.Fatalf("expected /close hint, got %s", w.Body.String())+ }}func TestHandleTab_RejectsUnsupportedScheme(t *testing.T) {diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex f1373e61..73017df1 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -44,6 +44,7 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"/health": map[string]any{"get": map[string]any{"summary": "Health"}},"/browser/restart": map[string]any{"post": map[string]any{"summary": "Soft restart the browser process without restarting the bridge"}},"/tabs": map[string]any{"get": map[string]any{"summary": "List tabs"}},+ "/tabs/{id}/close": map[string]any{"post": map[string]any{"summary": "Close a specific tab"}},"/tabs/{id}/handoff": map[string]any{"post": map[string]any{"summary": "Pause tab automation for human handoff"}, "get": map[string]any{"summary": "Get tab handoff status"}},"/tabs/{id}/resume": map[string]any{"post": map[string]any{"summary": "Resume tab automation after handoff"}},"/metrics": map[string]any{"get": map[string]any{"summary": "Runtime metrics"}},@@ -51,6 +52,7 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"/text": map[string]any{"get": map[string]any{"summary": "Extract text", "parameters": []map[string]any{{"name": "maxChars", "in": "query", "schema": map[string]string{"type": "integer"}}, {"name": "format", "in": "query", "schema": map[string]string{"type": "string"}}, {"name": "mode", "in": "query", "schema": map[string]string{"type": "string"}}, {"name": "frameId", "in": "query", "schema": map[string]string{"type": "string"}}}}},"/navigate": map[string]any{"post": map[string]any{"summary": "Navigate"}, "get": map[string]any{"summary": "Navigate (query params)"}},"/nav": map[string]any{"get": map[string]any{"summary": "Navigate alias"}},+ "/close": map[string]any{"post": map[string]any{"summary": "Close a tab by tabId, or the current/default tab when omitted"}},"/action": map[string]any{"post": map[string]any{"summary": "Single action"}, "get": map[string]any{"summary": "Single action (query params)"}},"/actions": map[string]any{"post": map[string]any{"summary": "Batch actions"}},"/snapshot": map[string]any{"get": map[string]any{"summary": "Accessibility snapshot"}},diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex bf15b664..1466d3ca 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -127,6 +127,7 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {return}+ defer h.armAutoCloseIfEnabled(resolvedTabID)tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)defer tCancel()go httpx.CancelOnClientDone(r.Context(), tCancel)diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex 348c8b1b..e2294547 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -68,6 +68,7 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {if _, ok := h.enforceCurrentTabDomainPolicy(w, r, ctx, resolvedTabID); !ok {return}+ defer h.armAutoCloseIfEnabled(resolvedTabID)tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)defer tCancel()diff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.goindex a381bf6d..4e5eb531 100644--- a/internal/instance/bridge_client.go+++ b/internal/instance/bridge_client.go@@ -111,8 +111,8 @@ func (bc *BridgeClient) NavigateTab(ctx context.Context, port, tabID, url string// CloseTab closes a tab on a bridge instance.func (bc *BridgeClient) CloseTab(ctx context.Context, port, tabID string) error {- body := fmt.Sprintf(`{"action":"close","tabId":%q}`, tabID)- req, err := http.NewRequestWithContext(ctx, http.MethodPost, bridgeURL(port, "/tab"), strings.NewReader(body))+ body := fmt.Sprintf(`{"tabId":%q}`, tabID)+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, bridgeURL(port, "/close"), strings.NewReader(body))if err != nil {return fmt.Errorf("close tab request: %w", err)}diff --git a/internal/mcp/handlers_tabs.go b/internal/mcp/handlers_tabs.goindex 8b69fc8f..b36f6b0b 100644--- a/internal/mcp/handlers_tabs.go+++ b/internal/mcp/handlers_tabs.go@@ -21,11 +21,11 @@ func handleListTabs(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.func handleCloseTab(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {- payload := map[string]any{"action": "close"}- if tabID := optString(r, "tabId"); tabID != "" {+ payload := map[string]any{}+ if tabID := optTrimmedString(r, "tabId"); tabID != "" {payload["tabId"] = tabID}- body, code, err := c.Post(ctx, "/tab", payload)+ body, code, err := c.Post(ctx, "/close", payload)if err != nil {return mcp.NewToolResultError(err.Error()), nil}diff --git a/internal/mcp/handlers_tabs_test.go b/internal/mcp/handlers_tabs_test.goindex 71cce839..7c870aac 100644--- a/internal/mcp/handlers_tabs_test.go+++ b/internal/mcp/handlers_tabs_test.go@@ -35,6 +35,37 @@ func TestHandleCloseTab(t *testing.T) {if !strings.Contains(text, "close") {t.Errorf("expected close, got %s", text)}+ if !strings.Contains(text, `"/close"`) {+ t.Errorf("expected /close path, got %s", text)+ }+}++func TestHandleCloseTabAllowsMissingTabID(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_close_tab", map[string]any{}, srv)+ if r.IsError {+ t.Fatalf("unexpected error: %s", resultText(t, r))+ }+ resp := resultJSON(t, r)+ if resp["path"] != "/close" {+ t.Fatalf("path = %v, want /close", resp["path"])+ }+}++func TestHandleCloseTabTreatsBlankTabIDAsDefault(t *testing.T) {+ srv := mockPinchTab()+ defer srv.Close()++ r := callTool(t, "pinchtab_close_tab", map[string]any{"tabId": " "}, srv)+ if r.IsError {+ t.Fatalf("unexpected error: %s", resultText(t, r))+ }+ resp := resultJSON(t, r)+ if resp["path"] != "/close" {+ t.Fatalf("path = %v, want /close", resp["path"])+ }}func TestHandleHealth(t *testing.T) {diff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex 6322821c..c8184e4f 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -178,7 +178,7 @@ func allTools() []mcp.Tool {),mcp.NewTool("pinchtab_close_tab",mcp.WithDescription("Close a browser tab"),- mcp.WithString("tabId", mcp.Description("ID of the tab to close")),+ mcp.WithString("tabId", mcp.Description("ID of the tab to close; uses the current/default tab when omitted")),),mcp.NewTool("pinchtab_health",mcp.WithDescription("Check PinchTab server health status"),diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex 41e433dc..7e623865 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -57,11 +57,8 @@ func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {registerCapabilityRoute(mux, "GET /instances/{id}/proxy/screencast", o.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", o.handleProxyScreencast)registerCapabilityRoute(mux, "GET /instances/{id}/screencast", o.AllowsScreencast(), "screencast", "security.allowScreencast", "screencast_disabled", o.proxyToInstance)- // Tab operations - custom handlers- mux.HandleFunc("POST /tabs/{id}/close", o.handleTabClose)-// Tab operations - generic proxy (all route to the appropriate instance).- // Sourced from routes.Core() catalogue to stay in sync with bridge and strategy.+ // Sourced from the shared route catalogue to stay in sync with bridge and strategy.for _, route := range routes.TabScopedRoutes() {mux.HandleFunc(route, o.proxyTabRequest)}diff --git a/internal/orchestrator/handlers_tabs.go b/internal/orchestrator/handlers_tabs.goindex b5d6b232..944419de 100644--- a/internal/orchestrator/handlers_tabs.go+++ b/internal/orchestrator/handlers_tabs.go@@ -6,59 +6,10 @@ import ("fmt""io""net/http"- "time""github.com/pinchtab/pinchtab/internal/httpx")-// handleTabClose closes a tab by finding its instance and sending a close request.-// This has custom logic (constructs a different request body) so it's not genericized.-func (o *Orchestrator) handleTabClose(w http.ResponseWriter, r *http.Request) {- tabID := r.PathValue("id")- if tabID == "" {- httpx.Error(w, 400, fmt.Errorf("tab id required"))- return- }-- inst, err := o.findRunningInstanceByTabID(tabID)- if err != nil {- httpx.Error(w, 404, err)- return- }-- // Construct request body for the bridge's /tab endpoint- reqBody, _ := json.Marshal(map[string]string{- "action": "close",- "tabId": tabID,- })-- targetURL, err := o.instancePathURL(inst, "/tab", "")- if err != nil {- httpx.Error(w, 502, err)- return- }- proxyReq, err := http.NewRequestWithContext(r.Context(), "POST", targetURL.String(), bytes.NewReader(reqBody))- if err != nil {- httpx.Error(w, 500, err)- return- }- proxyReq.Header.Set("Content-Type", "application/json")- o.applyInstanceAuth(proxyReq, inst)-- client := &http.Client{Timeout: 30 * time.Second}- resp, err := client.Do(proxyReq)- if err != nil {- httpx.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))- return- }- defer func() { _ = resp.Body.Close() }()-- body, _ := io.ReadAll(resp.Body)- w.Header().Set("Content-Type", "application/json")- w.WriteHeader(resp.StatusCode)- _, _ = w.Write(body)-}-// handleInstanceTabOpen opens a new tab in a specific instance.// This has custom logic so it's not genericized.func (o *Orchestrator) handleInstanceTabOpen(w http.ResponseWriter, r *http.Request) {diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex a46ddb9e..38ee6e04 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -134,7 +134,8 @@ func (o *Orchestrator) proxyToURL(w http.ResponseWriter, r *http.Request, targeto.applyInstanceAuth(req, inst)}},- OnResponse: enrichActivityFromResponse,+ OnResponseHeaders: o.handleProxyResponseHeaders,+ OnResponse: enrichActivityFromResponse,})}@@ -348,6 +349,34 @@ func enrichActivityFromResponse(origReq *http.Request, body []byte) {}}+func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *http.Response) {+ if o == nil || o.instanceMgr == nil || origReq == nil || resp == nil {+ return+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return+ }+ if tabID := tabClosePathID(origReq); tabID != "" {+ o.instanceMgr.InvalidateTab(tabID)+ return+ }+ if origReq.Method == http.MethodPost && strings.TrimSpace(origReq.URL.Path) == "/close" {+ if tabID := strings.TrimSpace(resp.Header.Get(activity.HeaderPTTabID)); tabID != "" {+ o.instanceMgr.InvalidateTab(tabID)+ }+ }+}++func tabClosePathID(r *http.Request) string {+ if r == nil || r.Method != http.MethodPost {+ return ""+ }+ if !strings.HasPrefix(r.URL.Path, "/tabs/") || !strings.HasSuffix(r.URL.Path, "/close") {+ return ""+ }+ return strings.TrimSpace(r.PathValue("id"))+}+func (o *Orchestrator) singleRunningInstance() *InstanceInternal {o.mu.RLock()defer o.mu.RUnlock()diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.goindex 4e8d5ef1..60463038 100644--- a/internal/orchestrator/proxy_test.go+++ b/internal/orchestrator/proxy_test.go@@ -6,8 +6,12 @@ import ("net""net/http""net/http/httptest"+ "net/url"+ "strings"+ "sync/atomic""testing"+ "github.com/pinchtab/pinchtab/internal/activity""github.com/pinchtab/pinchtab/internal/bridge")@@ -54,6 +58,106 @@ func TestProxyTabRequest_FallsBackToOnlyRunningInstance(t *testing.T) {}}+func TestRegisterHandlers_TabCloseUsesGenericProxyAndInvalidatesCache(t *testing.T) {+ var closed atomic.Bool+ var closePath atomic.Value+ var closeAuth atomic.Value++ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/tabs":+ w.Header().Set("Content-Type", "application/json")+ if closed.Load() {+ _, _ = io.WriteString(w, `{"tabs":[]}`)+ return+ }+ _, _ = io.WriteString(w, `{"tabs":[{"id":"tab-close","url":"about:blank"}]}`)+ case "/tabs/tab-close/close":+ closePath.Store(r.URL.Path)+ closeAuth.Store(r.Header.Get("Authorization"))+ closed.Store(true)+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"closed":true,"tabId":"tab-close"}`)+ default:+ http.NotFound(w, r)+ }+ }))+ defer backend.Close()++ o := NewOrchestrator(t.TempDir())+ o.client = backend.Client()+ o.childAuthToken = "child-token"+ inst := bridge.Instance{ID: "inst_1", Status: "running", URL: backend.URL}+ o.instances["inst_1"] = &InstanceInternal{+ Instance: inst,+ URL: backend.URL,+ cmd: &mockCmd{pid: 1234, isAlive: true},+ }+ o.instanceMgr.Repo.Add(&inst)+ o.instanceMgr.RegisterTab("tab-close", "inst_1")++ mux := http.NewServeMux()+ o.RegisterHandlers(mux)++ req := httptest.NewRequest(http.MethodPost, "/tabs/tab-close/close", nil)+ w := httptest.NewRecorder()+ mux.ServeHTTP(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ if got, _ := closePath.Load().(string); got != "/tabs/tab-close/close" {+ t.Fatalf("close path = %q, want /tabs/tab-close/close", got)+ }+ if got, _ := closeAuth.Load().(string); got != "Bearer child-token" {+ t.Fatalf("authorization = %q, want Bearer child-token", got)+ }+ if _, err := o.instanceMgr.FindInstanceByTabID("tab-close"); err == nil {+ t.Fatal("expected closed tab to be invalidated from locator cache")+ }+}++func TestProxyToURL_CloseShorthandInvalidatesCacheFromResponseHeader(t *testing.T) {+ backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/close" {+ http.NotFound(w, r)+ return+ }+ w.Header().Set(activity.HeaderPTTabID, "tab-close")+ w.Header().Set("Content-Type", "application/json")+ _, _ = io.WriteString(w, `{"closed":true,"tabId":"tab-close"}`)+ }))+ defer backend.Close()++ o := NewOrchestrator(t.TempDir())+ o.client = backend.Client()+ inst := bridge.Instance{ID: "inst_1", Status: "running", URL: backend.URL}+ o.instances["inst_1"] = &InstanceInternal{+ Instance: inst,+ URL: backend.URL,+ cmd: &mockCmd{pid: 1234, isAlive: true},+ }+ o.instanceMgr.Repo.Add(&inst)+ o.instanceMgr.RegisterTab("tab-close", "inst_1")++ targetURL, err := url.Parse(backend.URL + "/close")+ if err != nil {+ t.Fatalf("parse target: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/close", strings.NewReader(`{"tabId":"tab-close"}`))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()++ o.proxyToURL(w, req, targetURL)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ if _, err := o.instanceMgr.FindInstanceByTabID("tab-close"); err == nil {+ t.Fatal("expected closed tab to be invalidated from locator cache")+ }+}+func TestSingleRunningInstance_MultipleInstancesReturnsNil(t *testing.T) {o := NewOrchestrator(t.TempDir())o.instances["inst_1"] = &InstanceInternal{Instance: bridge.Instance{ID: "inst_1", Status: "running"}, cmd: &mockCmd{pid: 1, isAlive: true}}diff --git a/internal/proxy/proxy.go b/internal/proxy/proxy.goindex d63bf3db..0987d8c8 100644--- a/internal/proxy/proxy.go+++ b/internal/proxy/proxy.go@@ -23,9 +23,10 @@ import (var DefaultClient = &http.Client{Timeout: 60 * time.Second}type Options struct {- Client *http.Client- AllowedURL func(*url.URL) bool- RewriteRequest func(*http.Request)+ Client *http.Client+ AllowedURL func(*url.URL) bool+ RewriteRequest func(*http.Request)+ OnResponseHeaders func(origReq *http.Request, resp *http.Response)// OnResponse is called with the upstream response body for non-streaming// responses (Content-Type application/json, body ≤ 64 KB). The original// request is passed so callers can enrich activity context.@@ -101,6 +102,9 @@ func Forward(w http.ResponseWriter, r *http.Request, targetURL *url.URL, opts Op// Enrich activity from response headers (always available, regardless of body size).enrichActivityFromHeaders(r, resp.Header)+ if opts.OnResponseHeaders != nil {+ opts.OnResponseHeaders(r, resp)+ }// For small JSON responses, buffer to allow OnResponse to inspect the body.if opts.OnResponse != nil && isSmallJSON(resp) {diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex 2edd1ed8..b532d4f0 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -68,6 +68,7 @@ var coreEndpoints = []Endpoint{// Tab management{"POST", "/tab", "Open or switch tab", CapNone, false},+ {"POST", "/close", "Close tab", CapNone, true},{"POST", "/lock", "Lock tab", CapNone, true},{"POST", "/unlock", "Unlock tab", CapNone, true},diff --git a/internal/routes/routes_test.go b/internal/routes/routes_test.goindex 0b053200..2c6591c6 100644--- a/internal/routes/routes_test.go+++ b/internal/routes/routes_test.go@@ -37,6 +37,30 @@ func TestFrameEndpointsAreShorthandAndTabScoped(t *testing.T) {}}+func TestCloseRoutesAreShorthandAndTabScoped(t *testing.T) {+ found := false+ for _, route := range TabScopedRoutes() {+ if route == "POST /tabs/{id}/close" {+ found = true+ break+ }+ }+ if !found {+ t.Fatal("TabScopedRoutes() missing POST /tabs/{id}/close")+ }++ found = false+ for _, route := range ShorthandRoutes() {+ if route == "POST /close" {+ found = true+ break+ }+ }+ if !found {+ t.Fatal("ShorthandRoutes() missing POST /close")+ }+}+func TestNoDuplicateRoutes(t *testing.T) {seen := make(map[string]bool)for _, ep := range Core() {diff --git a/plugin/tools/browser.ts b/plugin/tools/browser.tsindex e07747ed..afaeb353 100644--- a/plugin/tools/browser.ts+++ b/plugin/tools/browser.ts@@ -125,6 +125,13 @@ export async function executeBrowserAction(cfg: PluginConfig, params: any): Promif (tabAction === "list") {return textResult(await pinchtabFetch(cfg, "/tabs"));}+ if (tabAction === "close") {+ const body: any = {};+ if (params.tabId) body.tabId = params.tabId;+ const result = await pinchtabFetch(cfg, "/close", { body });+ if (params.tabId && params.tabId === getLastTabId()) setLastTabId(undefined);+ return textResult(result);+ }const body: any = { action: tabAction };if (params.url) body.url = params.url;if (params.tabId) body.tabId = params.tabId;diff --git a/plugin/tools/pinchtab.ts b/plugin/tools/pinchtab.tsindex 8a482e43..8a5637ef 100644--- a/plugin/tools/pinchtab.ts+++ b/plugin/tools/pinchtab.ts@@ -235,6 +235,13 @@ export async function executePinchtabAction(cfg: PluginConfig, params: any): Proconst instanceTabs = await pinchtabFetch(cfg, `/instances/${running.id}/tabs`);return textResult({ source: "instance-fallback", instanceId: running.id, tabs: instanceTabs?.tabs ?? instanceTabs });}+ if (tabAction === "close") {+ const body: any = {};+ if (normalized.tabId) body.tabId = normalized.tabId;+ const result = await pinchtabFetch(cfg, "/close", { body });+ if (normalized.tabId && normalized.tabId === getLastTabId()) setLastTabId(undefined);+ return textResult(result);+ }const body: any = { action: tabAction };if (normalized.url) body.url = normalized.url;if (normalized.tabId) body.tabId = normalized.tabId;diff --git a/skills/pinchtab/references/api.md b/skills/pinchtab/references/api.mdindex 3e11f01d..70daa56b 100644--- a/skills/pinchtab/references/api.md+++ b/skills/pinchtab/references/api.md@@ -328,8 +328,13 @@ curl -X POST /tab -H 'Content-Type: application/json' \-d '{"action": "new", "url": "https://pinchtab.com"}'# Close tab-curl -X POST /tab -H 'Content-Type: application/json' \- -d '{"action": "close", "tabId": "TARGET_ID"}'+curl -X POST /close -H 'Content-Type: application/json' \+ -d '{"tabId": "TARGET_ID"}'+# Omit tabId to close the current/default tab.+curl -X POST /close -H 'Content-Type: application/json' -d '{}'++# Or use the tab-scoped route+curl -X POST /tabs/TARGET_ID/close```Multi-tab: pass `?tabId=TARGET_ID` to snapshot/screenshot/text, or `"tabId"` in POST body.diff --git a/skills/pinchtab/references/mcp.md b/skills/pinchtab/references/mcp.mdindex 73aeaeb8..5f64f258 100644--- a/skills/pinchtab/references/mcp.md+++ b/skills/pinchtab/references/mcp.md@@ -87,7 +87,7 @@ All tool names are prefixed with `pinchtab_`.| Tool | Description ||------|-------------|| `pinchtab_list_tabs` | List all open tabs. No params. |-| `pinchtab_close_tab` | Close a tab. Optional: `tabId` (closes current if omitted). |+| `pinchtab_close_tab` | Close a tab. Optional: `tabId` (uses current/default tab when omitted). || `pinchtab_health` | Check server health. No params. || `pinchtab_cookies` | Get cookies for current page. Optional: `tabId`. || `pinchtab_connect_profile` | Return connect status for a profile. Required: `profile`. |diff --git a/tests/e2e/config/pinchtab-autoclose.json b/tests/e2e/config/pinchtab-autoclose.jsonnew file mode 100644index 00000000..bcf2ae56--- /dev/null+++ b/tests/e2e/config/pinchtab-autoclose.json@@ -0,0 +1,41 @@+{+ "server": {+ "bind": "0.0.0.0",+ "port": "9999",+ "token": "e2e-token"+ },+ "browser": {+ "extensionPaths": [+ "/extensions/test-extension"+ ]+ },+ "instanceDefaults": {+ "maxTabs": 10,+ "stealthLevel": "light",+ "tabPolicy": {+ "lifecycle": "close_idle",+ "closeDelaySec": 1+ }+ },+ "multiInstance": {+ "strategy": "always-on",+ "allocationPolicy": "fcfs"+ },+ "security": {+ "allowEvaluate": true,+ "allowDownload": true,+ "allowedDomains": [+ "localhost",+ "127.0.0.1",+ "::1",+ "fixtures"+ ],+ "idpi": {+ "enabled": true,+ "strictMode": false,+ "scanContent": true,+ "wrapContent": false,+ "shieldThreshold": 30+ }+ }+}diff --git a/tests/e2e/docker-compose-multi.yml b/tests/e2e/docker-compose-multi.ymlindex 12d08c70..757270cf 100644--- a/tests/e2e/docker-compose-multi.yml+++ b/tests/e2e/docker-compose-multi.yml@@ -39,6 +39,24 @@ services:retries: 20start_period: 15s+ pinchtab-autoclose:+ build:+ context: ../..+ dockerfile: Dockerfile+ environment:+ PINCHTAB_CONFIG: /data/e2e-config/pinchtab-autoclose.json+ volumes:+ - ./config/pinchtab-autoclose.json:/fixture-config/pinchtab-autoclose.json:ro+ - ./fixtures/test-extension:/extensions/test-extension+ command: ["/bin/sh", "-lc", "mkdir -p /data/e2e-config && cp /fixture-config/pinchtab-autoclose.json /data/e2e-config/pinchtab-autoclose.json && exec /usr/local/bin/docker-entrypoint.sh pinchtab"]+ shm_size: '2gb'+ healthcheck:+ test: ["CMD-SHELL", "wget --header='Authorization: Bearer e2e-token' -q -O /dev/null http://localhost:9999/health"]+ interval: 3s+ timeout: 10s+ retries: 20+ start_period: 15s+pinchtab-medium:build:context: ../..@@ -154,6 +172,8 @@ services:condition: service_healthypinchtab-secure:condition: service_healthy+ pinchtab-autoclose:+ condition: service_healthypinchtab-medium:condition: service_healthypinchtab-full:@@ -167,6 +187,7 @@ services:environment:- E2E_SERVER=http://pinchtab:9999- E2E_SECURE_SERVER=http://pinchtab-secure:9999+ - E2E_AUTOCLOSE_SERVER=http://pinchtab-autoclose:9999- E2E_MEDIUM_SERVER=http://pinchtab-medium:9999- E2E_FULL_SERVER=http://pinchtab-full:9999- E2E_LITE_SERVER=http://pinchtab-lite:9999diff --git a/tests/e2e/run.sh b/tests/e2e/run.shindex b54c82b0..d971b3c0 100644--- a/tests/e2e/run.sh+++ b/tests/e2e/run.sh@@ -228,6 +228,9 @@ if [ "$SUITE_KIND" = "api" ]; thenwait_for_instance_ready "${E2E_SERVER}"if [ "$RUN_EXTENDED" = "true" ]; thenwait_for_instance_ready "${E2E_SECURE_SERVER}"+ if [ -n "${E2E_AUTOCLOSE_SERVER:-}" ]; then+ wait_for_instance_ready "${E2E_AUTOCLOSE_SERVER}"+ fiif [ -n "${E2E_MEDIUM_SERVER:-}" ]; thenwait_for_instance_ready "${E2E_MEDIUM_SERVER}"fidiff --git a/tests/e2e/scenarios/api/tabs-autoclose-extended.sh b/tests/e2e/scenarios/api/tabs-autoclose-extended.shnew file mode 100755index 00000000..cbbe66d4--- /dev/null+++ b/tests/e2e/scenarios/api/tabs-autoclose-extended.sh@@ -0,0 +1,176 @@+#!/bin/bash+# tabs-autoclose-extended.sh — verifies the auto-close-after-use lifecycle policy.+#+# Requires the server to be started with tests/e2e/config/pinchtab-autoclose.json+# (lifecycle=close_idle, closeDelaySec=1). The default e2e config uses the+# production 5-minute auto-close delay, which is too slow for these assertions.+#+# Behaviour under test:+# 1. /text on a tab arms an auto-close timer; the tab disappears after the delay.+# 2. A second /text within the delay window resets the timer (tab survives).+# 3. /navigate cancels a pending auto-close (tab survives until next read).+# 4. /snapshot and /action also arm the timer.++GROUP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+source "${GROUP_DIR}/../../helpers/api.sh"++AUTOCLOSE_ORIG_SERVER="$E2E_SERVER"+if [ -n "${E2E_AUTOCLOSE_SERVER:-}" ]; then+ E2E_SERVER="$E2E_AUTOCLOSE_SERVER"+fi++AUTOCLOSE_CONFIG=$(e2e_curl -sf "${E2E_SERVER}/api/config" 2>/dev/null || true)+if ! echo "$AUTOCLOSE_CONFIG" | jq -e '(.config // .).instanceDefaults.tabPolicy.lifecycle == "close_idle" and ((.config // .).instanceDefaults.tabPolicy.closeDelaySec | tonumber) == 1' >/dev/null 2>&1; then+ echo -e " ${YELLOW}⚠${NC} auto-close lifecycle server not configured at ${E2E_SERVER}, skipping"+ E2E_SERVER="$AUTOCLOSE_ORIG_SERVER"+ return 0 2>/dev/null || exit 0+fi++# Auto-close delay in seconds (must match closeDelaySec in pinchtab-autoclose.json).+CLOSE_DELAY=1+# A safety margin past the delay before asserting the tab is gone.+PAST_CLOSE_WAIT=1.8+# A short interval well under the delay, used to verify reset semantics.+WITHIN_DELAY=0.4++tab_id_exists() {+ local tab_id="$1"+ local tabs_json+ tabs_json=$(e2e_curl -sf "${E2E_SERVER}/tabs" 2>/dev/null || true)+ if [ -z "$tabs_json" ]; then+ return 2+ fi++ echo "$tabs_json" | jq -e --arg id "$tab_id" 'any(.tabs[]?; .id == $id)' >/dev/null 2>&1+}++assert_tab_id_open() {+ local tab_id="$1"+ local desc="${2:-tab is open}"++ tab_id_exists "$tab_id"+ local status=$?+ if [ "$status" -eq 0 ]; then+ echo -e " ${GREEN}✓${NC} ${desc}: ${tab_id:0:12}..."+ ((ASSERTIONS_PASSED++)) || true+ elif [ "$status" -eq 1 ]; then+ echo -e " ${RED}✗${NC} ${desc}: tab ${tab_id:0:12}... is missing"+ ((ASSERTIONS_FAILED++)) || true+ else+ echo -e " ${RED}✗${NC} ${desc}: unable to fetch tab list"+ ((ASSERTIONS_FAILED++)) || true+ fi+}++wait_for_tab_id_closed() {+ local tab_id="$1"+ local desc="${2:-tab closed}"+ local attempts="${3:-20}"+ local delay="${4:-0.25}"++ for _ in $(seq 1 "$attempts"); do+ tab_id_exists "$tab_id"+ local status=$?+ if [ "$status" -eq 1 ]; then+ echo -e " ${GREEN}✓${NC} ${desc}: ${tab_id:0:12}..."+ ((ASSERTIONS_PASSED++)) || true+ return 0+ fi+ sleep "$delay"+ done++ echo -e " ${RED}✗${NC} ${desc}: tab ${tab_id:0:12}... is still open"+ ((ASSERTIONS_FAILED++)) || true+ return 1+}++# ─────────────────────────────────────────────────────────────────+start_test "auto-close: /text arms a timer that fires after the delay"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"+TAB_ID=$(get_tab_id)+show_tab "created" "$TAB_ID"++pt_get "/text?tabId=${TAB_ID}&format=text"+assert_ok "tab text (arms auto-close)"++wait_for_tab_id_closed "$TAB_ID" "tab closed after /text"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "auto-close: a second /text within the delay window resets the timer"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"+TAB_ID=$(get_tab_id)++pt_get "/text?tabId=${TAB_ID}&format=text"+assert_ok "first /text"++# Second /text well within the delay — must reset the timer.+sleep "$WITHIN_DELAY"+pt_get "/text?tabId=${TAB_ID}&format=text"+assert_ok "second /text resets timer"++# Wait less than (CLOSE_DELAY + WITHIN_DELAY) but more than CLOSE_DELAY since+# the first /text — if reset worked, the tab is still alive here.+sleep "$WITHIN_DELAY"+assert_tab_id_open "$TAB_ID" "tab still open after reset"++# Now wait past the second timer's deadline; the tab should be gone.+wait_for_tab_id_closed "$TAB_ID" "tab closed after reset deadline"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "auto-close: /navigate cancels a pending timer"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"+TAB_ID=$(get_tab_id)++pt_get "/text?tabId=${TAB_ID}&format=text"+assert_ok "/text arms auto-close"++# Re-navigate well within the close delay — should cancel the pending timer.+sleep "$WITHIN_DELAY"+pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/form.html\",\"tabId\":\"${TAB_ID}\"}"+assert_ok "/navigate cancels pending close"++# Wait past the original deadline; the tab must still be alive because+# /navigate dropped the timer and no further /text re-armed it.+sleep "$PAST_CLOSE_WAIT"+assert_tab_id_open "$TAB_ID" "tab survived after /navigate cancel"++# Clean up: explicit close so this test doesn't leak a tab into the next.+pt_post "/tabs/${TAB_ID}/close" -d '{}' >/dev/null++end_test++# ─────────────────────────────────────────────────────────────────+start_test "auto-close: /snapshot also arms the timer"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/index.html\"}"+TAB_ID=$(get_tab_id)++pt_get "/snapshot?tabId=${TAB_ID}"+assert_ok "/snapshot arms auto-close"++wait_for_tab_id_closed "$TAB_ID" "tab closed after /snapshot"++end_test++# ─────────────────────────────────────────────────────────────────+start_test "auto-close: /action also arms the timer"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"+TAB_ID=$(get_tab_id)++# A read-style action: pressing a key is sufficient to mark the tab "used".+pt_post /action -d "{\"kind\":\"press\",\"key\":\"Tab\",\"tabId\":\"${TAB_ID}\"}"+assert_ok "/action arms auto-close"++wait_for_tab_id_closed "$TAB_ID" "tab closed after /action"++end_test++E2E_SERVER="$AUTOCLOSE_ORIG_SERVER"diff --git a/tests/e2e/scenarios/api/tabs-basic.sh b/tests/e2e/scenarios/api/tabs-basic.shindex 6a734544..55d9bd71 100644--- a/tests/e2e/scenarios/api/tabs-basic.sh+++ b/tests/e2e/scenarios/api/tabs-basic.sh@@ -46,6 +46,22 @@ assert_tab_closed "$AFTER_CREATE"end_test+# ─────────────────────────────────────────────────────────────────+start_test "pinchtab close shorthand"++pt_post /navigate -d "{\"url\":\"${FIXTURES_URL}/buttons.html\"}"+TAB_ID=$(get_tab_id)+AFTER_CREATE=$(get_tab_count)++pt_post /close -d "{\"tabId\":\"${TAB_ID}\"}"+assert_ok "shorthand close"+assert_json_contains "$RESULT" ".tabId" "$TAB_ID" "close response contains tabId"++sleep 1+assert_tab_closed "$AFTER_CREATE"++end_test+# ─────────────────────────────────────────────────────────────────start_test "Focus tab by ID"diff --git a/tests/e2e/scenarios/api/tabs-extended.sh b/tests/e2e/scenarios/api/tabs-extended.shindex bcd0d5ea..b479f2cf 100644--- a/tests/e2e/scenarios/api/tabs-extended.sh+++ b/tests/e2e/scenarios/api/tabs-extended.sh@@ -195,16 +195,21 @@ pt_post /tab "{\"action\":\"new\",\"url\":\"${FIXTURES_URL}/index.html\"}"assert_ok "new tab"NEW_TAB=$(echo "$RESULT" | jq -r '.tabId')-pt_post /tab "{\"action\":\"close\",\"tabId\":\"${NEW_TAB}\"}"+pt_post /close "{\"tabId\":\"${NEW_TAB}\"}"assert_ok "close tab"end_test# ─────────────────────────────────────────────────────────────────-start_test "tabs: close without tabId → 400"+start_test "tabs: close without tabId closes default tab"-pt_post /tab '{"action":"close"}'-assert_http_status "400" "rejects close without tabId"+pt_post /tab "{\"action\":\"new\",\"url\":\"${FIXTURES_URL}/index.html\"}"+assert_ok "new default tab"+DEFAULT_CLOSE_TAB=$(echo "$RESULT" | jq -r '.tabId')++pt_post /close '{}'+assert_ok "close default tab"+assert_result_eq '.tabId' "$DEFAULT_CLOSE_TAB" "default close returned the created tabId"end_test@@ -223,7 +228,7 @@ pt_post /tab '{"action":"new","url":"about:blank"}'assert_ok "new tab"assert_tab_id "new tab returns tabId"-pt_post /tab "{\"action\":\"close\",\"tabId\":\"${TAB_ID}\"}"+pt_post /close "{\"tabId\":\"${TAB_ID}\"}"end_testdiff --git a/tests/e2e/scenarios/infra/system-basic.sh b/tests/e2e/scenarios/infra/system-basic.shindex fe811180..e55606ca 100644--- a/tests/e2e/scenarios/infra/system-basic.sh+++ b/tests/e2e/scenarios/infra/system-basic.sh@@ -25,7 +25,7 @@ else((ASSERTIONS_FAILED++)) || truefi-pt_post /tab "{\"tabId\":\"$TAB_ID\",\"action\":\"close\"}" >/dev/null 2>&1+pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1end_test@@ -66,7 +66,7 @@ else((ASSERTIONS_FAILED++)) || truefi-pt_post /tab "{\"tabId\":\"$TAB_ID\",\"action\":\"close\"}" >/dev/null 2>&1+pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1end_test@@ -82,7 +82,7 @@ pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"document.title\"}"assert_ok "evaluate"assert_json_exists "$RESULT" ".result" "got title result"-pt_post /tab "{\"tabId\":\"$TAB_ID\",\"action\":\"close\"}" >/dev/null 2>&1+pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1end_test@@ -100,7 +100,7 @@ pt_post /evaluate "{\"tabId\":\"$TAB_ID\",\"expression\":\"window.location.href\assert_ok "evaluate"assert_json_exists "$RESULT" ".result" "got location result"-pt_post /tab "{\"tabId\":\"$TAB_ID\",\"action\":\"close\"}" >/dev/null 2>&1+pt_post /close "{\"tabId\":\"$TAB_ID\"}" >/dev/null 2>&1end_testdiff --git a/tests/e2e/scenarios/infra/system-extended.sh b/tests/e2e/scenarios/infra/system-extended.shindex b47252af..5e650dc8 100644--- a/tests/e2e/scenarios/infra/system-extended.sh+++ b/tests/e2e/scenarios/infra/system-extended.sh@@ -193,9 +193,9 @@ idpi_setup() {idpi_cleanup() {local base_url="$1" tab_id="$2"- e2e_curl -sf -X POST "${base_url}/tab" \+ e2e_curl -sf -X POST "${base_url}/close" \-H "Content-Type: application/json" \- -d "{\"tabId\":\"$tab_id\",\"action\":\"close\"}" >/dev/null 2>&1 || true+ -d "{\"tabId\":\"$tab_id\"}" >/dev/null 2>&1 || true}# Usage: idpi_request POST <base_url> <path> <body> <header_name>diff --git a/tests/e2e/scenarios/plugin/plugin-basic.sh b/tests/e2e/scenarios/plugin/plugin-basic.shindex 9fee653e..ae28a0e1 100644--- a/tests/e2e/scenarios/plugin/plugin-basic.sh+++ b/tests/e2e/scenarios/plugin/plugin-basic.sh@@ -132,7 +132,7 @@ end_test# ─────────────────────────────────────────────────────────────────start_test "plugin: tab close"-pt_post /tab -d "{\"action\":\"close\",\"tabId\":\"${NEW_TAB}\"}"+pt_post /close -d "{\"tabId\":\"${NEW_TAB}\"}"assert_ok "close tab"end_testdiff --git a/tests/tools/runner/shell.go b/tests/tools/runner/shell.goindex 1396e051..a1dbe602 100644--- a/tests/tools/runner/shell.go+++ b/tests/tools/runner/shell.go@@ -59,7 +59,7 @@ func NewPersistentShell(workDir string) (*PersistentShell, error) {errChan: make(chan error, 1),}- go ps.readLoop()+ go ps.readLoop(stdout, ps.outChan, ps.errChan)// Wait for shell to be readytime.Sleep(100 * time.Millisecond)@@ -67,15 +67,15 @@ func NewPersistentShell(workDir string) (*PersistentShell, error) {return ps, nil}-func (ps *PersistentShell) readLoop() {+func (ps *PersistentShell) readLoop(stdout io.Reader, outChan chan<- string, errChan chan<- error) {buf := make([]byte, 4096)for {- n, err := ps.stdout.Read(buf)+ n, err := stdout.Read(buf)if n > 0 {- ps.outChan <- string(buf[:n])+ outChan <- string(buf[:n])}if err != nil {- ps.errChan <- err+ errChan <- errreturn}}@@ -199,7 +199,7 @@ func (ps *PersistentShell) resetLocked() error {ps.outChan = make(chan string, 100)ps.errChan = make(chan error, 1)- go ps.readLoop()+ go ps.readLoop(stdout, ps.outChan, ps.errChan)time.Sleep(100 * time.Millisecond)return nildiff --git a/tests/tools/runner/shell_test.go b/tests/tools/runner/shell_test.goindex f33936fe..2a55b011 100644--- a/tests/tools/runner/shell_test.go+++ b/tests/tools/runner/shell_test.go@@ -151,9 +151,7 @@ func TestShellAutoReset(t *testing.T) {t.Errorf("first command: code=%d output=%q", code1, out1)}- ps.mu.Lock()- ps.closed = true- ps.mu.Unlock()+ ps.Close(true)out2, code2, err := ps.Run("echo after", 5*time.Second)if err != nil {