Skip to content

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

fix: quarantined profiles accumulate forever: prune older siblings at quarantine time, keeping the most recent per profile (PIN-043)

Luigi Agosti5ad1faaf23aa
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 4f6b8848..d826d09f 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -266,7 +266,8 @@ Current nested file-config shape:
},
"profiles": {
"baseDir": "/path/to/profiles",
- "defaultProfile": "default"
+ "defaultProfile": "default",
+ "quarantineKeep": 1
},
"multiInstance": {
"strategy": "always-on",
@@ -649,6 +650,29 @@ headers correctly.
`security.attach.forwardProxyAuth` controls whether PinchTab may send configured proxy authentication credentials over remote CDP attach. It defaults to `false`; enable it only when the attached browser process and CDP transport are trusted.
+### Quarantined Profile Retention
+
+When a browser profile turns out to be unusable, PinchTab renames it aside as
+`<profile>.quarantine-<unix>` and starts fresh. PinchTab keeps the most recent
+quarantined copy of each profile and prunes the older ones at the moment a new quarantine
+is created — the newest is the copy most likely to relate to a problem being investigated
+now, and nothing in the product reads the older ones. Every removal is logged with the
+path and the bytes reclaimed.
+
+```json
+{
+ "profiles": {
+ "quarantineKeep": 1
+ }
+}
+```
+
+`profiles.quarantineKeep` defaults to `1`. Set it to `0` to keep every quarantined
+profile, which is exactly the behaviour before this setting existed. Pruning only ever
+runs when a new quarantine is created, never on startup or a timer, so quarantined copies
+of a profile that never fails again are left alone — clearing that backlog is a separate,
+explicit operation.
+
### Activity Retention
```json
diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.go
index b8439de1..4e49ef87 100644
--- a/internal/bridge/profile_lock.go
+++ b/internal/bridge/profile_lock.go
@@ -17,11 +17,14 @@ package bridge
import (
"bytes"
"fmt"
+ "io/fs"
"log/slog"
"os"
"os/exec"
"path/filepath"
"regexp"
+ "sort"
+ "strconv"
"strings"
"time"
)
@@ -127,20 +130,173 @@ var quarantineExitWait = 5 * time.Second
const quarantineSuffix = ".quarantine-"
-var quarantineDirName = regexp.MustCompile(regexp.QuoteMeta(quarantineSuffix) + `\d+$`)
+var quarantineDirName = regexp.MustCompile(`^(.+)` + regexp.QuoteMeta(quarantineSuffix) + `(\d+)$`)
+
+// SplitQuarantineName reads a quarantine directory name back into the profile it was
+// made from and the timestamp it carries. It is the one owner of the pattern: the
+// predicate below and the prune both go through it, so a reader cannot drift from what
+// quarantine writes.
+func SplitQuarantineName(dirName string) (profile string, stamp int64, ok bool) {
+ match := quarantineDirName.FindStringSubmatch(dirName)
+ if match == nil {
+ return "", 0, false
+ }
+ stamp, err := strconv.ParseInt(match[2], 10, 64)
+ if err != nil {
+ return "", 0, false
+ }
+ return match[1], stamp, true
+}
// IsQuarantinedProfileDir reports whether a directory name is one quarantine
// produced. Only the "<name>.quarantine-<unix>" suffix decides, so a profile a
// user named after the word stays an ordinary profile.
func IsQuarantinedProfileDir(dirName string) bool {
- return quarantineDirName.MatchString(dirName)
+ _, _, ok := SplitQuarantineName(dirName)
+ return ok
+}
+
+// QuarantineRemoval is one directory a prune reclaimed, for the caller to log and
+// for a user-invoked reclaim to report.
+type QuarantineRemoval struct {
+ Path string
+ Bytes int64
+}
+
+// KeepAllQuarantinedProfiles is the keep count that turns pruning off, restoring
+// the behaviour of keeping every quarantined profile for ever.
+const KeepAllQuarantinedProfiles = 0
+
+// PruneQuarantinedProfiles keeps the newest `keep` quarantined siblings of one
+// profile and removes the rest, returning what it reclaimed. It is the only
+// deleter of quarantined profiles, so a user-invoked reclaim reuses it rather
+// than growing a second one.
+//
+// Two things bound what it can touch. Eligibility goes through
+// IsQuarantinedProfileDir, the predicate quarantine's own writer uses, so a live
+// profile directory sitting beside them is not a candidate — and because the
+// pattern demands the "<name>.quarantine-<digits>" suffix, a profile a user named
+// after the word is not one either. A user who names a profile exactly
+// "<something>.quarantine-1700000000" IS indistinguishable on disk from a real
+// quarantine; what stops it being deleted is the sibling scope, since it would
+// have to sit in the profiles base dir under the name of ANOTHER profile with
+// that suffix, and it is still never the newest-kept entry of its own name.
+//
+// justCreated is excluded by path, not by being newest: quarantine may proceed
+// while a dying browser still holds the directory, so the entry that can still be
+// written to must never be a candidate even if a same-second timestamp ties it
+// with an older one.
+func PruneQuarantinedProfiles(profileDir, justCreated string, keep int) ([]QuarantineRemoval, error) {
+ if keep <= KeepAllQuarantinedProfiles {
+ return nil, nil
+ }
+ profileDir = strings.TrimSpace(profileDir)
+ if profileDir == "" {
+ return nil, nil
+ }
+
+ siblings, err := quarantinedSiblings(profileDir)
+ if err != nil {
+ return nil, err
+ }
+ // Newest first, so keeping a prefix keeps the freshest artefacts — the ones
+ // most likely to relate to a problem being investigated now.
+ sort.Slice(siblings, func(i, j int) bool { return siblings[i].stamp > siblings[j].stamp })
+
+ // The just-created directory takes the first slot before anything else is
+ // considered, so keep=1 means exactly one quarantined profile survives and it is
+ // that one. Reserving rather than ranking is what makes this independent of the
+ // timestamp order: two quarantines in the same second tie, and the entry a dying
+ // browser may still be writing to must not lose a coin toss.
+ budget := keep
+ for _, sibling := range siblings {
+ if sibling.path == justCreated {
+ budget--
+ break
+ }
+ }
+
+ var removals []QuarantineRemoval
+ for _, sibling := range siblings {
+ if sibling.path == justCreated {
+ continue
+ }
+ if budget > 0 {
+ budget--
+ continue
+ }
+ reclaimed := dirBytes(sibling.path)
+ if err := os.RemoveAll(sibling.path); err != nil {
+ slog.Warn("could not prune quarantined profile", "profile", sibling.path, "err", err)
+ continue
+ }
+ removals = append(removals, QuarantineRemoval{Path: sibling.path, Bytes: reclaimed})
+ }
+ return removals, nil
+}
+
+type quarantinedSibling struct {
+ path string
+ stamp int64
+}
+
+// quarantinedSiblings finds the quarantined directories belonging to one profile: same
+// parent, same profile name. Both halves have exactly one owner — SplitQuarantineName
+// decides whether a name is a quarantine at all, and the profile it reports decides whose
+// it is, which is what keeps one profile's prune away from another profile's evidence.
+func quarantinedSiblings(profileDir string) ([]quarantinedSibling, error) {
+ parent := filepath.Dir(profileDir)
+ profileName := filepath.Base(profileDir)
+ entries, err := os.ReadDir(parent)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("read profiles dir: %w", err)
+ }
+
+ var siblings []quarantinedSibling
+ for _, entry := range entries {
+ if !entry.IsDir() {
+ continue
+ }
+ profile, stamp, ok := SplitQuarantineName(entry.Name())
+ if !ok {
+ continue
+ }
+ if profile != profileName {
+ continue
+ }
+ siblings = append(siblings, quarantinedSibling{path: filepath.Join(parent, entry.Name()), stamp: stamp})
+ }
+ return siblings, nil
+}
+
+func dirBytes(path string) int64 {
+ var total int64
+ _ = filepath.WalkDir(path, func(_ string, entry fs.DirEntry, err error) error {
+ if err != nil || entry.IsDir() {
+ return nil
+ }
+ if info, err := entry.Info(); err == nil {
+ total += info.Size()
+ }
+ return nil
+ })
+ return total
}
// quarantineCorruptedProfile renames profileDir to "<profileDir>.quarantine-<ts>"
// and recreates an empty directory at the original path. Used to recover
// from silent CDP attach failures where CloakBrowser refuses to ingest
// existing profile state.
-func quarantineCorruptedProfile(profileDir string) (string, error) {
+//
+// keep bounds how many quarantined siblings of this profile survive, newest first,
+// pruned here rather than on a startup sweep: a sweep would delete directories the
+// operator never asked about, while this only reclaims as the same profile keeps
+// failing. Directories belonging to profiles that never quarantine again are
+// therefore never reclaimed by this path.
+func quarantineCorruptedProfile(profileDir string, keep int) (string, error) {
profileDir = strings.TrimSpace(profileDir)
if profileDir == "" {
return "", fmt.Errorf("empty profile dir")
@@ -170,6 +326,14 @@ func quarantineCorruptedProfile(profileDir string) (string, error) {
if err := os.MkdirAll(profileDir, 0700); err != nil {
return quarantinePath, fmt.Errorf("recreate profile dir: %w", err)
}
+ // After the rename, so a failed quarantine never costs an older artefact.
+ removals, err := PruneQuarantinedProfiles(profileDir, quarantinePath, keep)
+ if err != nil {
+ slog.Warn("could not prune older quarantined profiles", "profile", profileDir, "err", err)
+ }
+ for _, removal := range removals {
+ slog.Info("pruned older quarantined profile", "profile", removal.Path, "bytesReclaimed", removal.Bytes, "keep", keep)
+ }
return quarantinePath, nil
}
diff --git a/internal/bridge/profile_lock_test.go b/internal/bridge/profile_lock_test.go
index 870133bc..7b3dd793 100644
--- a/internal/bridge/profile_lock_test.go
+++ b/internal/bridge/profile_lock_test.go
@@ -22,7 +22,7 @@ func TestQuarantineCorruptedProfile(t *testing.T) {
t.Fatalf("write marker: %v", err)
}
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantineCorruptedProfile: %v", err)
}
@@ -54,7 +54,7 @@ func TestQuarantineCorruptedProfile(t *testing.T) {
func TestQuarantineCorruptedProfile_MissingDir(t *testing.T) {
t.Parallel()
- path, err := quarantineCorruptedProfile(filepath.Join(t.TempDir(), "does-not-exist"))
+ path, err := quarantineCorruptedProfile(filepath.Join(t.TempDir(), "does-not-exist"), KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("missing dir should not error: %v", err)
}
@@ -66,10 +66,10 @@ func TestQuarantineCorruptedProfile_MissingDir(t *testing.T) {
func TestQuarantineCorruptedProfile_EmptyPath(t *testing.T) {
t.Parallel()
- if _, err := quarantineCorruptedProfile(""); err == nil {
+ if _, err := quarantineCorruptedProfile("", KeepAllQuarantinedProfiles); err == nil {
t.Fatal("expected error for empty profile dir")
}
- if _, err := quarantineCorruptedProfile(" "); err == nil {
+ if _, err := quarantineCorruptedProfile(" ", KeepAllQuarantinedProfiles); err == nil {
t.Fatal("expected error for blank profile dir")
}
}
@@ -345,7 +345,7 @@ func TestQuarantineCorruptedProfile_WaitsForBrowserExit(t *testing.T) {
chromeExitPollInterval = oldPoll
})
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantineCorruptedProfile: %v", err)
}
@@ -382,7 +382,7 @@ func TestQuarantineCorruptedProfile_ProceedsAfterWaitTimeout(t *testing.T) {
chromeExitPollInterval = oldPoll
})
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantine should proceed (with a warning) after the wait times out: %v", err)
}
@@ -407,7 +407,7 @@ func TestQuarantineDropsTheStaleProfileMetadata(t *testing.T) {
t.Fatalf("setup metadata: %v", err)
}
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantineCorruptedProfile: %v", err)
}
@@ -433,7 +433,7 @@ func TestQuarantineWithoutMetadataStillSucceeds(t *testing.T) {
t.Fatalf("setup: %v", err)
}
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantineCorruptedProfile: %v", err)
}
@@ -466,7 +466,7 @@ func TestQuarantineCorruptedProfileProducesAFlaggedName(t *testing.T) {
t.Fatal(err)
}
- quarantinePath, err := quarantineCorruptedProfile(profileDir)
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles)
if err != nil {
t.Fatalf("quarantineCorruptedProfile: %v", err)
}
diff --git a/internal/bridge/quarantine_prune_test.go b/internal/bridge/quarantine_prune_test.go
new file mode 100644
index 00000000..c7727e9c
--- /dev/null
+++ b/internal/bridge/quarantine_prune_test.go
@@ -0,0 +1,244 @@
+package bridge
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+)
+
+func writeProfileDir(t *testing.T, path string, bytes int) {
+ t.Helper()
+ if err := os.MkdirAll(path, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if bytes > 0 {
+ if err := os.WriteFile(filepath.Join(path, "State"), make([]byte, bytes), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func dirNames(t *testing.T, root string) []string {
+ t.Helper()
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var names []string
+ for _, entry := range entries {
+ names = append(names, entry.Name())
+ }
+ sort.Strings(names)
+ return names
+}
+
+func quarantinePathAt(profileDir string, stamp int64) string {
+ return fmt.Sprintf("%s%s%d", profileDir, quarantineSuffix, stamp)
+}
+
+// The policy: keep the newest quarantined copy of a profile and prune its older
+// siblings when a new one is created. Nothing in the product reads a quarantined
+// profile, so the freshest is the only one with a plausible use.
+func TestPruneKeepsTheNewestQuarantinedSibling(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 0)
+ for _, stamp := range []int64{1700000001, 1700000002, 1700000003} {
+ writeProfileDir(t, quarantinePathAt(profileDir, stamp), 64)
+ }
+ newest := quarantinePathAt(profileDir, 1700000004)
+ writeProfileDir(t, newest, 8)
+
+ removals, err := PruneQuarantinedProfiles(profileDir, newest, 1)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 3 {
+ t.Fatalf("removals = %v, want the three older siblings", removals)
+ }
+ for _, removal := range removals {
+ if removal.Bytes != 64 {
+ t.Errorf("%s reported %d bytes reclaimed, want the 64 it held", removal.Path, removal.Bytes)
+ }
+ }
+ if got := dirNames(t, root); len(got) != 2 || got[0] != "default" || got[1] != filepath.Base(newest) {
+ t.Errorf("profiles dir = %v, want the live profile and the newest quarantine only", got)
+ }
+}
+
+// keep=2 keeps the just-created one plus the next newest, so the setting means what
+// it says rather than "one plus keep".
+func TestPruneKeepCountIncludesTheJustCreatedDirectory(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 0)
+ for _, stamp := range []int64{1700000001, 1700000002} {
+ writeProfileDir(t, quarantinePathAt(profileDir, stamp), 16)
+ }
+ newest := quarantinePathAt(profileDir, 1700000003)
+ writeProfileDir(t, newest, 16)
+
+ removals, err := PruneQuarantinedProfiles(profileDir, newest, 2)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 1 || filepath.Base(removals[0].Path) != filepath.Base(quarantinePathAt(profileDir, 1700000001)) {
+ t.Fatalf("removals = %v, want only the oldest", removals)
+ }
+}
+
+// Quarantine may proceed while a dying browser still holds the directory, so the
+// just-created entry is the one that can still be written to. It is excluded by path,
+// not by being newest: two quarantines in the same second tie on the timestamp.
+func TestPruneNeverRemovesTheJustCreatedDirectoryEvenOnATimestampTie(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 0)
+ justCreated := quarantinePathAt(profileDir, 1700000009)
+ writeProfileDir(t, justCreated, 4)
+ // A sibling that sorts equal-or-newer, which would otherwise spend the only slot.
+ tie := quarantinePathAt(profileDir, 1700000009) + "0"
+ writeProfileDir(t, tie, 4)
+
+ removals, err := PruneQuarantinedProfiles(profileDir, justCreated, 1)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 1 || removals[0].Path != tie {
+ t.Fatalf("removals = %v, want the other sibling and never the just-created one", removals)
+ }
+ if _, err := os.Stat(justCreated); err != nil {
+ t.Fatalf("the just-created quarantine was removed: %v", err)
+ }
+}
+
+// Only quarantine-suffixed siblings of the SAME profile are eligible: a live profile
+// standing beside them, and another profile's quarantines, are both out of reach.
+func TestPruneLeavesLiveProfilesAndOtherProfilesQuarantinesAlone(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 32)
+ writeProfileDir(t, filepath.Join(root, "work"), 32)
+ writeProfileDir(t, quarantinePathAt(filepath.Join(root, "work"), 1700000001), 32)
+ writeProfileDir(t, filepath.Join(root, "default.quarantine-notanumber"), 32)
+ writeProfileDir(t, filepath.Join(root, "default-quarantine-1700000001"), 32)
+ writeProfileDir(t, quarantinePathAt(profileDir, 1700000001), 32)
+ newest := quarantinePathAt(profileDir, 1700000002)
+ writeProfileDir(t, newest, 32)
+
+ removals, err := PruneQuarantinedProfiles(profileDir, newest, 1)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 1 || removals[0].Path != quarantinePathAt(profileDir, 1700000001) {
+ t.Fatalf("removals = %v, want only this profile's older quarantine", removals)
+ }
+ for _, name := range []string{"default", "work", "work.quarantine-1700000001", "default.quarantine-notanumber", "default-quarantine-1700000001"} {
+ if _, err := os.Stat(filepath.Join(root, name)); err != nil {
+ t.Errorf("%s was removed and must not have been: %v", name, err)
+ }
+ }
+}
+
+// Eligibility comes from the predicate quarantine's writer uses, not a second copy of
+// the pattern: every name this prune accepts must be one that predicate accepts.
+func TestPruneEligibilityAgreesWithTheQuarantinePredicate(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 0)
+ for _, name := range []string{
+ "default.quarantine-1700000001",
+ "default.quarantine-notanumber",
+ "default-quarantine-1700000002",
+ "default.quarantine-",
+ } {
+ writeProfileDir(t, filepath.Join(root, name), 8)
+ }
+
+ siblings, err := quarantinedSiblings(profileDir)
+ if err != nil {
+ t.Fatalf("quarantinedSiblings() error = %v", err)
+ }
+ if len(siblings) != 1 {
+ t.Fatalf("siblings = %v, want only the well-formed quarantine name", siblings)
+ }
+ for _, sibling := range siblings {
+ if !IsQuarantinedProfileDir(filepath.Base(sibling.path)) {
+ t.Errorf("%s is a prune candidate the quarantine predicate rejects", sibling.path)
+ }
+ }
+}
+
+// Keep-everything is the way back to the old behaviour, and it has to be exact: no
+// directory is touched and nothing is reported as reclaimed.
+func TestPruneKeepAllRemovesNothing(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 0)
+ for _, stamp := range []int64{1700000001, 1700000002, 1700000003} {
+ writeProfileDir(t, quarantinePathAt(profileDir, stamp), 8)
+ }
+ before := dirNames(t, root)
+
+ removals, err := PruneQuarantinedProfiles(profileDir, "", KeepAllQuarantinedProfiles)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 0 {
+ t.Fatalf("removals = %v, want none when every quarantine is kept", removals)
+ }
+ if got := dirNames(t, root); strings.Join(got, ",") != strings.Join(before, ",") {
+ t.Errorf("profiles dir = %v, want it unchanged at %v", got, before)
+ }
+}
+
+// The whole point is that pruning happens when a new quarantine is created, not on a
+// sweep — so it has to be reachable through the quarantine path itself.
+func TestQuarantineCorruptedProfilePrunesOlderSiblings(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 16)
+ for _, stamp := range []int64{1700000001, 1700000002} {
+ writeProfileDir(t, quarantinePathAt(profileDir, stamp), 16)
+ }
+
+ quarantinePath, err := quarantineCorruptedProfile(profileDir, 1)
+ if err != nil {
+ t.Fatalf("quarantineCorruptedProfile() error = %v", err)
+ }
+ if quarantinePath == "" {
+ t.Fatal("no quarantine path returned")
+ }
+
+ got := dirNames(t, root)
+ if len(got) != 2 {
+ t.Fatalf("profiles dir = %v, want the recreated profile and the new quarantine only", got)
+ }
+ if _, err := os.Stat(quarantinePath); err != nil {
+ t.Errorf("the new quarantine is gone: %v", err)
+ }
+ if _, err := os.Stat(profileDir); err != nil {
+ t.Errorf("the profile directory was not recreated: %v", err)
+ }
+}
+
+// Keeping everything through the quarantine path leaves exactly what was there plus
+// the new directory, which is what "restores today's behaviour" has to mean.
+func TestQuarantineCorruptedProfileKeepsEverythingWhenConfigured(t *testing.T) {
+ root := t.TempDir()
+ profileDir := filepath.Join(root, "default")
+ writeProfileDir(t, profileDir, 16)
+ for _, stamp := range []int64{1700000001, 1700000002} {
+ writeProfileDir(t, quarantinePathAt(profileDir, stamp), 16)
+ }
+
+ if _, err := quarantineCorruptedProfile(profileDir, KeepAllQuarantinedProfiles); err != nil {
+ t.Fatalf("quarantineCorruptedProfile() error = %v", err)
+ }
+ if got := dirNames(t, root); len(got) != 4 {
+ t.Fatalf("profiles dir = %v, want both older quarantines kept alongside the new one", got)
+ }
+}
diff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.go
index 543ee7e0..303eb4de 100644
--- a/internal/bridge/runtime/init.go
+++ b/internal/bridge/runtime/init.go
@@ -42,8 +42,10 @@ type Hooks struct {
// QuarantineCorruptedProfile moves profileDir aside and recreates an
// empty dir at the same path. Used to recover from silent CDP attach
// failures (observed with CloakBrowser when the profile dir holds
- // state it cannot ingest). Returns the quarantine path on success.
- QuarantineCorruptedProfile func(profileDir string) (string, error)
+ // state it cannot ingest). Returns the quarantine path on success. keep is how
+ // many quarantined siblings of that profile survive, newest first, with 0
+ // meaning keep every one.
+ QuarantineCorruptedProfile func(profileDir string, keep int) (string, error)
}
// InitBrowser initializes a browser for a Bridge instance.
diff --git a/internal/bridge/runtime/quarantine_keep_wiring_test.go b/internal/bridge/runtime/quarantine_keep_wiring_test.go
new file mode 100644
index 00000000..44ed5c59
--- /dev/null
+++ b/internal/bridge/runtime/quarantine_keep_wiring_test.go
@@ -0,0 +1,88 @@
+package runtime
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+// The retention count is a config setting, and a setting that never reaches the deleter is
+// decorative. The recovery path is the only caller of the quarantine hook and cannot be
+// driven from a unit test — reaching it needs a provider that classifies a silent CDP drop
+// and a real browser launch — so the wiring is pinned at the source instead: the call must
+// hand the hook the configured count, in the argument position the hook reads it from.
+//
+// Receiver-name-blind on purpose: renaming the config variable must not red this, only
+// dropping or replacing the value must.
+func TestQuarantineHookReceivesTheConfiguredKeepCount(t *testing.T) {
+ const field = "ProfileQuarantineKeep"
+
+ fset := token.NewFileSet()
+ files, err := os.ReadDir(".")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ scanned, calls := 0, 0
+ for _, entry := range files {
+ name := entry.Name()
+ if entry.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ scanned++
+ file, err := parser.ParseFile(fset, name, nil, 0)
+ if err != nil {
+ t.Fatalf("ParseFile(%s): %v", name, err)
+ }
+ ast.Inspect(file, func(node ast.Node) bool {
+ call, ok := node.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ selector, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok || selector.Sel.Name != "QuarantineCorruptedProfile" {
+ return true
+ }
+ calls++
+ position := fset.Position(call.Pos())
+ if len(call.Args) != 2 {
+ t.Errorf("%s:%d calls QuarantineCorruptedProfile with %d arguments, want the profile dir and the keep count",
+ filepath.Base(position.Filename), position.Line, len(call.Args))
+ return true
+ }
+ keep, ok := call.Args[1].(*ast.SelectorExpr)
+ if !ok || keep.Sel.Name != field {
+ t.Errorf("%s:%d passes %s as the keep count; it must pass the configured %s, or the setting changes nothing",
+ filepath.Base(position.Filename), position.Line, exprText(fset, call.Args[1]), field)
+ }
+ return true
+ })
+ }
+
+ if scanned < 3 {
+ t.Fatalf("scanned only %d non-test files in this package, so this census read almost nothing", scanned)
+ }
+ if calls == 0 {
+ t.Fatalf("no call to QuarantineCorruptedProfile in this package; the guard has nothing to check — re-point it at whatever quarantines a profile now rather than deleting it")
+ }
+}
+
+func exprText(fset *token.FileSet, expr ast.Expr) string {
+ var out strings.Builder
+ switch e := expr.(type) {
+ case *ast.SelectorExpr:
+ out.WriteString(exprText(fset, e.X))
+ out.WriteString("." + e.Sel.Name)
+ case *ast.Ident:
+ out.WriteString(e.Name)
+ case *ast.BasicLit:
+ out.WriteString(e.Value)
+ default:
+ out.WriteString(fset.Position(expr.Pos()).String())
+ }
+ return out.String()
+}
diff --git a/internal/bridge/runtime/recovery.go b/internal/bridge/runtime/recovery.go
index fa225615..e5c8ec3c 100644
--- a/internal/bridge/runtime/recovery.go
+++ b/internal/bridge/runtime/recovery.go
@@ -77,7 +77,7 @@ func startBrowserWithRecovery(parentCtx context.Context, cfg *config.RuntimeConf
}
if silentDrop && !retriedProfileCorruption && hooks.QuarantineCorruptedProfile != nil && strings.TrimSpace(cfg.ProfileDir) != "" {
- if quarantinePath, qerr := hooks.QuarantineCorruptedProfile(cfg.ProfileDir); qerr == nil {
+ if quarantinePath, qerr := hooks.QuarantineCorruptedProfile(cfg.ProfileDir, cfg.ProfileQuarantineKeep); qerr == nil {
slog.Warn("browser silently dropped CDP attach; quarantined profile and retrying with fresh profile",
"provider", browserID,
"originalProfile", cfg.ProfileDir,
diff --git a/internal/bridge/runtime/recovery_test.go b/internal/bridge/runtime/recovery_test.go
index afe71cf1..fa97aabb 100644
--- a/internal/bridge/runtime/recovery_test.go
+++ b/internal/bridge/runtime/recovery_test.go
@@ -33,7 +33,7 @@ func TestStartBrowserWithRecovery_ProfileLockClearedOnce(t *testing.T) {
clearCalls.Add(1)
return true, nil
},
- QuarantineCorruptedProfile: func(profileDir string) (string, error) {
+ QuarantineCorruptedProfile: func(profileDir string, _ int) (string, error) {
quarantineCalls.Add(1)
return profileDir + ".quarantine", nil
},
diff --git a/internal/config/config_file.go b/internal/config/config_file.go
index e87c6d04..3cbe1dc9 100644
--- a/internal/config/config_file.go
+++ b/internal/config/config_file.go
@@ -111,6 +111,7 @@ func compareSemver(a, b [3]int) int {
func DefaultFileConfig() FileConfig {
start := 9868
end := 9968
+ quarantineKeep := DefaultProfileQuarantineKeep
restartMaxRestarts := 20
restartInitBackoffSec := 2
restartMaxBackoffSec := 60
@@ -220,6 +221,7 @@ func DefaultFileConfig() FileConfig {
// defaults to userConfigDir().
Profiles: ProfilesConfig{
DefaultProfile: "default",
+ QuarantineKeep: &quarantineKeep,
},
MultiInstance: MultiInstanceConfig{
Strategy: "always-on",
diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.go
index 88bb3b5a..71fe565d 100644
--- a/internal/config/config_file_json.go
+++ b/internal/config/config_file_json.go
@@ -77,6 +77,7 @@ type instanceDefaultsConfigJSON struct {
type profilesConfigJSON struct {
BaseDir string `json:"baseDir"`
DefaultProfile string `json:"defaultProfile"`
+ QuarantineKeep *int `json:"quarantineKeep,omitempty"`
}
type securityConfigJSON struct {
diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.go
index c7112771..448a09d1 100644
--- a/internal/config/config_file_marshal.go
+++ b/internal/config/config_file_marshal.go
@@ -249,6 +249,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
Profiles: profilesConfigJSON{
BaseDir: fc.Profiles.BaseDir,
DefaultProfile: fc.Profiles.DefaultProfile,
+ QuarantineKeep: fc.Profiles.QuarantineKeep,
},
MultiInstance: multiInstanceConfigJSON{
Strategy: fc.MultiInstance.Strategy,
@@ -419,6 +420,8 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
autoSolverRetryMaxDelayMs := cfg.AutoSolver.RetryMaxDelayMs
autoSolverLLMFallback := cfg.AutoSolver.LLMFallback
+ quarantineKeep := cfg.ProfileQuarantineKeep
+
mode := "headless"
if !cfg.Headless {
mode = "headed"
@@ -523,6 +526,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
Profiles: ProfilesConfig{
BaseDir: cfg.ProfilesBaseDir,
DefaultProfile: cfg.DefaultProfile,
+ QuarantineKeep: &quarantineKeep,
},
MultiInstance: MultiInstanceConfig{
Strategy: cfg.Strategy,
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index 70c3c661..bcde617c 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -221,6 +221,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {
ProfileDir: "",
ProfilesBaseDir: "",
DefaultProfile: "default",
+ ProfileQuarantineKeep: DefaultProfileQuarantineKeep,
BrowserVersion: "144.0.7559.133",
Timezone: "",
BlockImages: false,
@@ -725,6 +726,9 @@ func applyProfilesConfig(cfg *RuntimeConfig, p ProfilesConfig) {
if p.DefaultProfile != "" {
cfg.DefaultProfile = p.DefaultProfile
}
+ if p.QuarantineKeep != nil && *p.QuarantineKeep >= 0 {
+ cfg.ProfileQuarantineKeep = *p.QuarantineKeep
+ }
cfg.ProfileDir = ""
}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index fc2dd14b..72562ef6 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -52,16 +52,18 @@ type RuntimeConfig struct {
ProfileDir string
ProfilesBaseDir string
DefaultProfile string
- BrowserVersion string
- Timezone string
- BlockImages bool
- BlockMedia bool
- BlockAds bool
- MaxTabs int
- MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
- BrowserBinary string
- BrowserDebugPort int
- BrowserExtraFlags string
+ // ProfileQuarantineKeep bounds quarantined copies of one profile; 0 keeps all.
+ ProfileQuarantineKeep int
+ BrowserVersion string
+ Timezone string
+ BlockImages bool
+ BlockMedia bool
+ BlockAds bool
+ MaxTabs int
+ MaxParallelTabs int // 0 = auto-detect from runtime.NumCPU
+ BrowserBinary string
+ BrowserDebugPort int
+ BrowserExtraFlags string
// CDPAttachURL: when set, the bridge skips launching its own Chrome and
// connects to an already-running Chrome whose browser-level CDP
// WebSocket URL is provided here (e.g.
@@ -409,9 +411,21 @@ type TabPolicyDefaults struct {
Restore *bool `json:"restore,omitempty"` // restore tabs from sessions.json on startup; default false
}
+// DefaultProfileQuarantineKeep is how many quarantined copies of one profile PinchTab
+// keeps when a new quarantine is created. One keeps the freshest forensic artefact —
+// the only reason to keep any, since nothing in the product reads them — while
+// bounding growth. Zero in the config means keep every one.
+const DefaultProfileQuarantineKeep = 1
+
type ProfilesConfig struct {
BaseDir string `json:"baseDir,omitempty"`
DefaultProfile string `json:"defaultProfile,omitempty"`
+
+ // QuarantineKeep is how many quarantined copies of one profile survive when a new
+ // quarantine is created, newest first. A pointer because 0 is a real value here —
+ // it means keep every one, the behaviour before this was bounded — so absent must
+ // not read as 0.
+ QuarantineKeep *int `json:"quarantineKeep,omitempty"`
}
type SecurityConfig struct {
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index b3213e88..9a2d72e5 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -353,6 +353,11 @@ func getProfilesField(p *ProfilesConfig, field string) (string, error) {
return p.BaseDir, nil
case "defaultProfile":
return p.DefaultProfile, nil
+ case "quarantineKeep":
+ if p.QuarantineKeep == nil {
+ return "", nil
+ }
+ return strconv.Itoa(*p.QuarantineKeep), nil
default:
return "", fmt.Errorf("unknown field profiles.%s", field)
}
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index a8545ebc..a9709364 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -535,6 +535,15 @@ func setProfilesField(p *ProfilesConfig, field, value string) error {
p.BaseDir = value
case "defaultProfile":
p.DefaultProfile = value
+ case "quarantineKeep":
+ n, err := strconv.Atoi(value)
+ if err != nil {
+ return fmt.Errorf("profiles.quarantineKeep must be a number: %w", err)
+ }
+ if n < 0 {
+ return fmt.Errorf("profiles.quarantineKeep must be >= 0 (0 keeps every quarantined profile)")
+ }
+ p.QuarantineKeep = &n
default:
return fmt.Errorf("unknown field profiles.%s", field)
}
diff --git a/internal/profiles/quarantine_listing_test.go b/internal/profiles/quarantine_listing_test.go
new file mode 100644
index 00000000..7243e94c
--- /dev/null
+++ b/internal/profiles/quarantine_listing_test.go
@@ -0,0 +1,75 @@
+package profiles
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func writeListableProfile(t *testing.T, baseDir, name string) string {
+ t.Helper()
+
+ path := filepath.Join(baseDir, name)
+ if err := os.MkdirAll(filepath.Join(path, "Default"), 0o700); err != nil {
+ t.Fatal(err)
+ }
+ return path
+}
+
+func countQuarantined(t *testing.T, pm *ProfileManager) (live, quarantined int) {
+ t.Helper()
+
+ listed, err := pm.List()
+ if err != nil {
+ t.Fatalf("List() error = %v", err)
+ }
+ for _, profile := range listed {
+ if profile.Quarantined {
+ quarantined++
+ continue
+ }
+ live++
+ }
+ return live, quarantined
+}
+
+// The listing and the /health counters derived from it read the directory each time and
+// flag entries through the same predicate the prune goes through, so a prune is visible
+// immediately and no count can outlive the disk. This drives both halves together, which
+// is the only way to see a cache if one were ever introduced.
+func TestTheProfileListingFollowsDiskAfterAQuarantinePrune(t *testing.T) {
+ baseDir := t.TempDir()
+ profileDir := writeListableProfile(t, baseDir, "default")
+ writeListableProfile(t, baseDir, "default.quarantine-1700000001")
+ writeListableProfile(t, baseDir, "default.quarantine-1700000002")
+ newest := writeListableProfile(t, baseDir, "default.quarantine-1700000003")
+
+ pm := NewProfileManager(baseDir)
+ live, quarantined := countQuarantined(t, pm)
+ if live != 1 || quarantined != 3 {
+ t.Fatalf("before the prune: live=%d quarantined=%d, want 1 and 3", live, quarantined)
+ }
+
+ removals, err := bridge.PruneQuarantinedProfiles(profileDir, newest, 1)
+ if err != nil {
+ t.Fatalf("PruneQuarantinedProfiles() error = %v", err)
+ }
+ if len(removals) != 2 {
+ t.Fatalf("removals = %v, want the two older quarantines", removals)
+ }
+
+ live, quarantined = countQuarantined(t, pm)
+ if live != 1 || quarantined != 1 {
+ t.Errorf("after the prune: live=%d quarantined=%d, want 1 and 1 — the listing must agree with the disk", live, quarantined)
+ }
+
+ entries, err := os.ReadDir(baseDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(entries) != live+quarantined {
+ t.Errorf("the listing reports %d profiles but %d directories remain on disk", live+quarantined, len(entries))
+ }
+}
diff --git a/internal/schema/config.json b/internal/schema/config.json
index 1c98dcf2..cc05c4b9 100644
--- a/internal/schema/config.json
+++ b/internal/schema/config.json
@@ -444,6 +444,12 @@
"defaultProfile": {
"type": "string",
"default": "default"
+ },
+ "quarantineKeep": {
+ "type": "integer",
+ "minimum": 0,
+ "default": 1,
+ "description": "How many quarantined copies of one profile to keep when a new quarantine is created, newest first. 0 keeps every one."
}
}
},