High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix(e2e): rename and a few docs fixes
Luigi Agosti918c71417399
diff --git a/.github/DEFINITION_OF_DONE.md b/.github/DEFINITION_OF_DONE.mdindex 0b172eb2..97066f88 100644--- a/.github/DEFINITION_OF_DONE.md+++ b/.github/DEFINITION_OF_DONE.md@@ -3,7 +3,7 @@## Automated ✅ (CI/GitHub enforces these)These run automatically via `ci.yml`. If your PR fails them, fix and re-push.- [ ] Go formatting & linting passes (gofmt, vet, golangci-lint)-- [ ] Unit + integration tests pass (`go test ./...`)+- [ ] Unit + E2E tests pass (`go test ./...` and `./pdev e2e`)- [ ] Build succeeds (`go build`)- [ ] CodeQL security scan passes- [ ] Branch naming follows convention@@ -19,8 +19,8 @@ These run automatically via `ci.yml`. If your PR fails them, fix and re-push.- ✅ Good: `// Chrome may not be installed in CI, so empty result is valid`## Manual — Testing (Required)-- [ ] **New/changed functionality has tests** — Same-package unit tests preferred; use mockBridge for integration-- [ ] **Integration tests run locally** — If you modified handlers/bridge/tabs, run: `go test -tags integration ./tests/integration`+- [ ] **New/changed functionality has tests** — Same-package unit tests preferred+- [ ] **Docker E2E tests run locally** — If you modified handlers/bridge/tabs, run: `./pdev e2e` (Docker curl E2E) and/or `./pdev e2e cli` (Docker CLI E2E)- [ ] **npm commands work** (if npm wrapper touched):- `npm pack` in `/npm/` produces valid tarball- `npm install -g pinchtab` (or from local tarball) succeeds@@ -44,7 +44,7 @@ These run automatically via `ci.yml`. If your PR fails them, fix and re-push.## Quick Checklist (Copy/Paste for PRs)```markdown## Definition of Done-- [ ] Unit/integration tests added & passing+- [ ] Unit + Docker E2E tests added & passing- [ ] Error handling explicit (wrapped with %w)- [ ] No regressions in stealth/perf/persistence- [ ] No redundant comments (explain why, not what)diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.mdindex 5bffd934..9ccbc2a5 100644--- a/.github/PULL_REQUEST_TEMPLATE.md+++ b/.github/PULL_REQUEST_TEMPLATE.md@@ -7,11 +7,11 @@## Testing<!-- How did you test this? Include command examples if applicable -->-- [ ] Unit/integration tests added or updated+- [ ] Unit and/or Docker E2E tests added or updated- [ ] Manual testing completed (describe below)## Checklist-See [DEFINITION_OF_DONE.md](../DEFINITION_OF_DONE.md) for full checklist.+See [DEFINITION_OF_DONE.md](./DEFINITION_OF_DONE.md) for the full checklist.**Automated (CI enforces):**- [ ] gofmt + golangci-lint passesdiff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e-curl.ymlsimilarity index 90%rename from .github/workflows/e2e.ymlrename to .github/workflows/e2e-curl.ymlindex 3eb5010d..2c98409e 100644--- a/.github/workflows/e2e.yml+++ b/.github/workflows/e2e-curl.yml@@ -4,6 +4,24 @@ permissions:contents: readon:+ push:+ branches: [main]+ paths-ignore:+ - '**.md'+ - 'docs/**'+ - 'LICENSE'+ - '.gitignore'+ - 'skill/**'+ - 'plugin/**'+ pull_request:+ branches: [main]+ paths-ignore:+ - '**.md'+ - 'docs/**'+ - 'LICENSE'+ - '.gitignore'+ - 'skill/**'+ - 'plugin/**'workflow_dispatch:inputs:branch:@@ -22,6 +40,7 @@ jobs:e2e:name: E2E Curl Testsruns-on: ubuntu-latest+ if: github.event_name != 'pull_request' || github.event.pull_request.draft == falsetimeout-minutes: 15env:FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: truediff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymldeleted file mode 100644index 34d9be8f..00000000--- a/.github/workflows/integration.yml+++ /dev/null@@ -1,114 +0,0 @@-name: Integration Tests--on:- push:- branches: [main]- paths-ignore:- - '**.md'- - 'docs/**'- - 'LICENSE'- - '.gitignore'- - 'skill/**'- - 'plugin/**'- pull_request:- branches: [main]- paths-ignore:- - '**.md'- - 'docs/**'- - 'LICENSE'- - '.gitignore'- - 'skill/**'- - 'plugin/**'--permissions:- contents: read--jobs:- # Check which files changed to conditionally run integration tests- changes:- name: Detect Changes- runs-on: ubuntu-latest- if: github.event_name != 'pull_request' || github.event.pull_request.draft == false- outputs:- go: ${{ steps.filter.outputs.go }}- steps:- - uses: actions/checkout@v4- - uses: dorny/paths-filter@v3- id: filter- with:- filters: |- go:- - '**.go'- - 'go.mod'- - 'go.sum'- - 'cmd/**'- - 'internal/**'- - 'tests/integration/**'-- integration:- name: Integration Tests- needs: changes- runs-on: ubuntu-latest- timeout-minutes: 12- if: needs.changes.outputs.go == 'true'- env:- SYSTEM_REGEX: '^(TestProxy_InstanceIsolation|TestOrchestrator_(HealthCheck|HashBasedIDs|PortAllocation|PortReuse|ListInstances|FirstRequestLazyChrome|AggregateTabsEndpoint|StopNonexistent|InstanceCleanup))$'- steps:- - uses: actions/checkout@v4-- - uses: actions/setup-go@v5- with:- go-version: '1.26'-- - name: Install Google Chrome (deb, avoids snap hangs)- run: |- wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add -- echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' | sudo tee /etc/apt/sources.list.d/google-chrome.list- sudo apt-get update- sudo apt-get install -y google-chrome-stable- echo "CHROME_BINARY=/usr/bin/google-chrome" >> $GITHUB_ENV-- - name: Install gotestsum- run: go install gotest.tools/gotestsum@latest-- - name: 🧪 Run integration tests- run: |- echo "::group::Integration Tests Output"- gotestsum --format testname --jsonfile integration-events.json -- \- -tags integration -v -timeout 10m -count=1 \- -run '^Test' -skip "$SYSTEM_REGEX" ./tests/integration/- echo "::endgroup::"- env:- CI: "true"- BRIDGE_HEADLESS: "true"- BRIDGE_NO_RESTORE: "true"- PINCHTAB_TEST_PORT: "19867"- PINCHTAB_TEST_RETRY: "true"- PINCHTAB_ALLOW_EVALUATE: "true"- PINCHTAB_ALLOW_MACRO: "true"- PINCHTAB_ALLOW_DOWNLOAD: "true"- PINCHTAB_ALLOW_UPLOAD: "true"- PINCHTAB_ALLOW_SCREENCAST: "true"-- - name: 📋 Add summary- if: always()- run: |- total=0- pass=0- fail=0- skip=0-- if [ -s integration-events.json ]; then- read total pass fail skip <<<"$(jq -r 'select(.Test != null and (.Action == "pass" or .Action == "fail" or .Action == "skip")) | [.Package, .Test, .Action] | @tsv' integration-events.json \- | awk -F'\t' 'NF == 3 { key = $1 "\t" $2; status[key] = $3 } END { for (k in status) { t++; if (status[k] == "pass") p++; else if (status[k] == "fail") f++; else if (status[k] == "skip") s++; } printf "%d %d %d %d\n", t + 0, p + 0, f + 0, s + 0 }')"- fi-- echo "### ✅ Integration Tests" >> "$GITHUB_STEP_SUMMARY"- echo "- **Status**: ${{ job.status }}" >> "$GITHUB_STEP_SUMMARY"- echo "- **Runner**: ubuntu-latest" >> "$GITHUB_STEP_SUMMARY"- echo "- **Port**: 19867" >> "$GITHUB_STEP_SUMMARY"- echo "- **Skip regex**: \`$SYSTEM_REGEX\`" >> "$GITHUB_STEP_SUMMARY"- echo "- **Total tests**: $total" >> "$GITHUB_STEP_SUMMARY"- echo "- **Passed**: $pass" >> "$GITHUB_STEP_SUMMARY"- echo "- **Failed**: $fail" >> "$GITHUB_STEP_SUMMARY"- echo "- **Skipped**: $skip" >> "$GITHUB_STEP_SUMMARY"diff --git a/DEFINITION_OF_DONE.md b/DEFINITION_OF_DONE.mdindex 37d096dd..d752e01d 100644--- a/DEFINITION_OF_DONE.md+++ b/DEFINITION_OF_DONE.md@@ -1,53 +1,5 @@-# Definition of Done (PR Checklist)+# Definition of Done-## Automated ✅ (CI/GitHub enforces these)-These run automatically via `ci.yml`. If your PR fails them, fix and re-push.-- [ ] Go formatting & linting passes (gofmt, vet, golangci-lint)-- [ ] Unit + E2E tests pass (`go test ./...` and `./pdev e2e`)-- [ ] Build succeeds (`go build`)-- [ ] CodeQL security scan passes-- [ ] Branch naming follows convention+Canonical file: [`.github/DEFINITION_OF_DONE.md`](./.github/DEFINITION_OF_DONE.md)-## Manual — Code Quality (Required)-- [ ] **Error handling explicit** — All errors wrapped with `%w`, no silent failures-- [ ] **No regressions** — Verify stealth, token efficiency, session persistence work (test locally if unsure)-- [ ] **SOLID principles** — Functions do one thing, testable, no unnecessary deps-- [ ] **No redundant comments** — Comments explain *why* or *context*, not *what* the code does- - ❌ Bad: `// Loop through items` above `for _, item := range items`- - ❌ Bad: `// Return error` above `return err`- - ✅ Good: `// Prioritize chromium-browser on ARM64 (Raspberry Pi default)`- - ✅ Good: `// Chrome may not be installed in CI, so empty result is valid`--## Manual — Testing (Required)-- [ ] **New/changed functionality has tests** — Same-package unit tests preferred-- [ ] **E2E tests run locally** — If you modified handlers/bridge/tabs, run: `./pdev e2e` (curl tests) and/or `./pdev e2e cli` (CLI tests)-- [ ] **npm commands work** (if npm wrapper touched):- - `npm pack` in `/npm/` produces valid tarball- - `npm install -g pinchtab` (or from local tarball) succeeds- - `pinchtab --version` + basic commands work after install--## Manual — Documentation (Required)-- [ ] **README.md updated** — If user-facing changes (CLI, API, env vars, install)-- [ ] **/docs/ updated** — If API/architecture/perf changed (optional for small fixes)--## Manual — Review (Required)-- [ ] **PR description explains what + why** — Especially stealth/perf/compatibility impact-- [ ] **Commits are atomic** — Logical grouping, good messages-- [ ] **No breaking changes to npm** — Unless explicitly major version bump--## Conditional (Only if applicable)-- [ ] Headed-mode tested (if dashboard/UI changes)-- [ ] Breaking changes documented in PR description (if any)-------## Quick Checklist (Copy/Paste for PRs)-```markdown-## Definition of Done-- [ ] Unit + E2E tests added & passing-- [ ] Error handling explicit (wrapped with %w)-- [ ] No regressions in stealth/perf/persistence-- [ ] No redundant comments (explain why, not what)-- [ ] README/docs updated (if user-facing)-- [ ] npm install works (if npm changes)-```+Use the `.github` copy as the source of truth for PR review, templates, and agent instructions.diff --git a/cmd/pinchtab/cmd_onboard.go b/cmd/pinchtab/cmd_daemon.gosimilarity index 97%rename from cmd/pinchtab/cmd_onboard.gorename to cmd/pinchtab/cmd_daemon.goindex 3db09352..c2092be3 100644--- a/cmd/pinchtab/cmd_onboard.go+++ b/cmd/pinchtab/cmd_daemon.go@@ -66,7 +66,7 @@ func handleDaemonCommand(_ *config.RuntimeConfig, subcommand string) {switch subcommand {case "install":- configPath, _, _, err := ensureOnboardConfig(false)+ configPath, _, _, err := ensureDaemonConfig(false)if err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("daemon install failed: %v", err)))os.Exit(1)@@ -201,7 +201,7 @@ func printDaemonManagerResult(message string, err error) {}}-func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConfigStatus, error) {+func ensureDaemonConfig(force bool) (string, *config.RuntimeConfig, configBootstrapStatus, error) {_, configPath, err := config.LoadFileConfig()if err != nil {return "", nil, "", err@@ -218,9 +218,9 @@ func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConfif err := config.SaveFileConfig(&defaults, configPath); err != nil {return "", nil, "", err}- status := onboardConfigCreated+ status := configCreatedif exists {- status = onboardConfigRecovered+ status = configRecovered}return configPath, config.Load(), status, nil}@@ -228,22 +228,22 @@ func ensureOnboardConfig(force bool) (string, *config.RuntimeConfig, onboardConf// If file exists and not forced, check if it needs recovery to secure baseline_, changed, err := cli.RestoreSecurityDefaults()if err != nil {- return configPath, config.Load(), onboardConfigVerified, err+ return configPath, config.Load(), configVerified, err}- status := onboardConfigVerified+ status := configVerifiedif changed {- status = onboardConfigRecovered+ status = configRecovered}return configPath, config.Load(), status, nil}-type onboardConfigStatus string+type configBootstrapStatus stringconst (- onboardConfigCreated onboardConfigStatus = "created"- onboardConfigRecovered onboardConfigStatus = "recovered"- onboardConfigVerified onboardConfigStatus = "verified"+ configCreated configBootstrapStatus = "created"+ configRecovered configBootstrapStatus = "recovered"+ configVerified configBootstrapStatus = "verified")type commandRunner interface {diff --git a/cmd/pinchtab/cmd_onboard_test.go b/cmd/pinchtab/cmd_daemon_test.gosimilarity index 94%rename from cmd/pinchtab/cmd_onboard_test.gorename to cmd/pinchtab/cmd_daemon_test.goindex f6199a09..b455e742 100644--- a/cmd/pinchtab/cmd_onboard_test.go+++ b/cmd/pinchtab/cmd_daemon_test.go@@ -29,12 +29,12 @@ func TestEnsureOnboardConfigCreatesDefaultConfig(t *testing.T) {t.Setenv("PINCHTAB_TOKEN", "")t.Setenv("PINCHTAB_BIND", "")- gotPath, cfg, status, err := ensureOnboardConfig(false)+ gotPath, cfg, status, err := ensureDaemonConfig(false)if err != nil {- t.Fatalf("ensureOnboardConfig returned error: %v", err)+ t.Fatalf("ensureDaemonConfig returned error: %v", err)}- if status != onboardConfigCreated {- t.Fatalf("status = %q, want %q", status, onboardConfigCreated)+ if status != configCreated {+ t.Fatalf("status = %q, want %q", status, configCreated)}if gotPath != configPath {t.Fatalf("config path = %q, want %q", gotPath, configPath)@@ -82,12 +82,12 @@ func TestEnsureOnboardConfigRecoversExistingSecuritySettings(t *testing.T) {t.Fatalf("writing config file: %v", err)}- _, cfg, status, err := ensureOnboardConfig(false)+ _, cfg, status, err := ensureDaemonConfig(false)if err != nil {- t.Fatalf("ensureOnboardConfig returned error: %v", err)+ t.Fatalf("ensureDaemonConfig returned error: %v", err)}- if status != onboardConfigRecovered {- t.Fatalf("status = %q, want %q", status, onboardConfigRecovered)+ if status != configRecovered {+ t.Fatalf("status = %q, want %q", status, configRecovered)}if cfg.Bind != "127.0.0.1" {t.Fatalf("bind = %q, want 127.0.0.1", cfg.Bind)diff --git a/LITE_ENGINE_CHANGES.md b/docs/deep-dive/lite-engin-prototype.mdsimilarity index 100%rename from LITE_ENGINE_CHANGES.mdrename to docs/deep-dive/lite-engin-prototype.mddiff --git a/docs/implementations/chrome-profile-lock-recovery.md b/docs/implementations/chrome-profile-lock-recovery.mdnew file mode 100644index 00000000..a12cc313--- /dev/null+++ b/docs/implementations/chrome-profile-lock-recovery.md@@ -0,0 +1,66 @@+# Chrome Profile Lock Recovery++Chrome uses a `SingletonLock` file in its user data directory to prevent multiple instances from sharing the same profile simultaneously. If PinchTab or Chrome crashes, this lock file (and associated `SingletonSocket` and `SingletonCookie` files) can be left behind, preventing the next PinchTab startup from succeeding with the error:++> "The profile appears to be in use by another Chromium process"++This document explains how PinchTab identifies, validates, and recovers from these stale locks while ensuring multi-instance safety.++## Recovery Mechanism++The recovery process follows a multi-layered approach to distinguish between a truly active profile and a stale one left by a crashed instance.++### 1. Detection++During initialization in `internal/bridge/init.go`, if Chrome fails to start, PinchTab checks the error message for signatures of a profile lock:+- `The profile appears to be in use by another Chromium process`+- `The profile appears to be in use by another Chrome process`+- `process_singleton_posix.cc` (indicating a failure in the ProcessSingleton logic)++### 2. Validation & PinchTab PID Lock++To safely clear a lock, PinchTab must be certain no *other* active PinchTab instance is currently using that profile.++- **`pinchtab.pid`**: When a bridge starts, it writes its own PID to `$PROFILE_DIR/pinchtab.pid`.+- **Ownership Check**: Before clearing any Chrome locks, PinchTab reads this file.+ - If the PID in the file is still running **and** is verified to be a `pinchtab` process (by inspecting its command-line arguments), it assumes another PinchTab instance is active and **does not** touch the locks.+ - This verification prevents issues with PID reuse where a dead PinchTab instance's PID is reassigned to a different process.+ - If the PID is not running or is not a PinchTab process, the previous instance is considered "dead," and the profile is eligible for recovery.++### 3. Headless Fallback++If a headless PinchTab instance cannot acquire a lock on the requested profile directory (because another PinchTab instance is genuinely using it), it automatically falls back to creating a unique temporary profile directory. This allows multiple headless bridges to run concurrently even if they all default to the same profile path, while still preserving isolation and safety.++### 4. Stale Process Termination++Even if the previous PinchTab instance is dead, orphaned Chrome processes might still be holding the profile lock.++- **Process Listing**: PinchTab scans the system process list for any processes launched with the same `--user-data-dir`.+- **Aggressive Cleanup**: If the `pinchtab.pid` check confirms no active owner, PinchTab sends `SIGKILL` to any orphaned Chrome processes associated with that profile. This is necessary because Chrome's internal "singleton" logic can be extremely stubborn if it thinks another process is even partially alive.++### 4. Lock File Removal++Once stale processes are terminated, PinchTab removes the following files from the profile directory:+- `SingletonLock`+- `SingletonSocket`+- `SingletonCookie`++### 5. Automatic Retry++After clearing the stale state, `InitChrome` automatically retries the startup sequence once. This makes the recovery transparent to the user and the API caller (e.g., the first `/health` check will succeed after a brief internal recovery delay).++## Implementation Details++The logic is distributed across these components:++- **`internal/bridge/profile_lock.go`**: Core logic for detection, PID lock management (`AcquireProfileLock`), and stale file removal.+- **`internal/bridge/profile_lock_pid_*.go`**: Platform-specific implementations for PID probing and process killing (supports Unix-like systems and Windows).+- **`internal/bridge/init.go`**: Orchestrates the retry logic within `startChromeWithRecovery`.+- **`internal/server/bridge.go`**: Ensures clean shutdown via signal handling to prevent locks from being left behind in the first place.++## Multi-Instance Safety++By combining the Chrome-level `SingletonLock` with the application-level `pinchtab.pid`, PinchTab achieves:+1. **Safety**: It never kills a browser being used by a healthy PinchTab instance.+2. **Resilience**: It automatically "self-heals" after a crash or power failure.+3. **Transparency**: Users don't need to manually `rm -rf` profile directories to fix "in use" errors.diff --git a/docs/implementations/index.md b/docs/implementations/index.mdindex 1e4f7f58..7c714246 100644--- a/docs/implementations/index.md+++ b/docs/implementations/index.md@@ -6,5 +6,6 @@ Use these pages when you want lower-level detail than the architecture overview,- [Lite Engine](./lite-engine.md) — Chrome-free DOM capture using Gost-DOM- [Managed Bridge vs Managed Direct CDP](./managed-bridge-vs-managed-direct-cdp.md)+- [Chrome Profile Lock Recovery](./chrome-profile-lock-recovery.md)- [Parallel Tab Execution](./parallel-tab-execution.md)- [Docker Local Testing](./docker-local-testing.md)