Skip to content

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

Architectural Refactor & Community Health Enhancement (#2)

Luigi Agostidca211421abc
diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 00000000..37a7d368
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,31 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: ''
+labels: bug
+assignees: ''
+
+---
+
+**Describe the bug**
+A clear and concise description of what the bug is.
+
+**To Reproduce**
+Steps to reproduce the behavior:
+1. Start Pinchtab with `...`
+2. Send request to `/...` with body `...`
+3. See error
+
+**Expected behavior**
+A clear and concise description of what you expected to happen.
+
+**Screenshots/Logs**
+If applicable, add screenshots or console output to help explain your problem.
+
+**Environment (please complete the following information):**
+ - OS: [e.g. macOS, Ubuntu]
+ - Browser Version: [e.g. Chrome 120]
+ - Go Version: [e.g. 1.25.0]
+
+**Additional context**
+Add any other context about the problem here.
diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 00000000..11fc491e
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,20 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+title: ''
+labels: enhancement
+assignees: ''
+
+---
+
+**Is your feature request related to a problem? Please describe.**
+A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+
+**Describe the solution you'd like**
+A clear and concise description of what you want to happen.
+
+**Describe alternatives you've considered**
+A clear and concise description of any alternative solutions or features you've considered.
+
+**Additional context**
+Add any other context or screenshots about the feature request here.
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 00000000..1b55816e
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,19 @@
+## Description
+Briefly describe the changes introduced by this PR.
+
+## Type of change
+- [ ] Bug fix (non-breaking change which fixes an issue)
+- [ ] New feature (non-breaking change which adds functionality)
+- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
+- [ ] Refactoring (internal changes with no user-facing impact)
+- [ ] Documentation update
+
+## Checklist:
+- [ ] My code follows the style guidelines of this project
+- [ ] I have performed a self-review of my own code
+- [ ] I have commented my code, particularly in hard-to-understand areas (where non-obvious)
+- [ ] My changes generate no new warnings
+- [ ] I have added tests that prove my fix is effective or that my feature works
+- [ ] New and existing unit tests pass locally with my changes
+- [ ] I have updated the documentation (README, internal docs) accordingly
+- [ ] I have adhered to the `internal/` package boundaries and SOLID principles
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 83516858..6fad50c7 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -33,7 +33,7 @@ jobs:
run: go vet ./...
- name: Build
- run: go build -o pinchtab .
+ run: go build -o pinchtab ./cmd/pinchtab
- name: Test with coverage
run: go test ./... -v -count=1 -coverprofile=coverage.out -covermode=atomic
diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md
new file mode 100644
index 00000000..1402d328
--- /dev/null
+++ b/CODE_OF_CONDUCT.md
@@ -0,0 +1,46 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [INSERT EMAIL ADDRESS]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
+
+[homepage]: http://contributor-covenant.org
+[version]: http://contributor-covenant.org/version/1/4
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 48681114..6f43aa33 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,7 +7,7 @@ git clone https://github.com/pinchtab/pinchtab.git
cd pinchtab
# Build
-go build -o pinchtab .
+go build -o pinchtab ./cmd/pinchtab
# Run (headed — Chrome window opens)
./pinchtab
@@ -26,7 +26,7 @@ Requires **Go 1.25+** and **Google Chrome**.
1. Make your changes
2. Format: `gofmt -w .`
3. Test: `go test ./... -count=1`
-4. Lint: `golangci-lint run ./...` (v2.9.0+)
+4. Lint: `golangci-lint run ./...`
5. Commit — pre-commit hook runs checks automatically
6. Push: `git pull --rebase && git push`
@@ -41,38 +41,31 @@ go test ./... -coverprofile=coverage.out
go tool cover -func=coverage.out
```
-Tests don't require a running Chrome instance.
+Most tests use a `mockBridge` and do not require a running Chrome instance.
## Project Layout
-Single Go package, all files in root:
-
-- `main.go` — entry point, Chrome launch, routes
-- `handlers.go` — HTTP handlers (navigate, screenshot, tabs, lock)
-- `handler_snapshot.go` — snapshot handler (a11y tree, format, file output)
-- `handler_actions.go` — action/actions handlers
-- `handler_cookies.go` — cookie get/set
-- `handler_stealth.go` — stealth status, fingerprint rotation
-- `snapshot.go` — a11y tree parsing
-- `cdp.go` — Chrome DevTools Protocol helpers
-- `bridge.go` — tab management, Chrome lifecycle
-- `config.go` — environment config, embedded assets
-- `lock.go` — tab locking for multi-agent coordination
-- `animations.go` — CSS animation disabling
-- `human.go` — human-like interaction (bezier mouse, typing)
-- `state.go` — session persistence
-- `middleware.go` — auth, CORS, logging
-- `stealth.js` — stealth script (light/full modes)
-- `welcome.html` — headed mode welcome page
+The project follows the standard Go `internal/` pattern to ensure encapsulation and clean boundaries:
+
+- `cmd/pinchtab/` — Application entry points and CLI commands.
+- `internal/bridge/` — Core CDP logic, tab management, and state logic.
+- `internal/handlers/` — HTTP API handlers and middleware.
+- `internal/orchestrator/` — Multi-instance lifecycle and process management.
+- `internal/profiles/` — Chrome profile management and user identity discovery.
+- `internal/dashboard/` — Backend logic and static assets for the web UI.
+- `internal/assets/` — Centralized embedded files (stealth scripts, CSS).
+- `internal/human/` — Human-like interaction simulation (Bezier mouse paths, natural typing).
+- `internal/web/` — Shared HTTP and JSON utilities.
## Style
- `gofmt` enforced (CI + pre-commit)
-- Handle all error returns
-- Lowercase error strings, wrap with `%w`
-- Tests next to source (`foo.go` → `foo_test.go`)
-- No new dependencies without good reason
+- Adhere to **SOLID** principles, specifically using interfaces for dependency inversion.
+- Handle all error returns explicitly.
+- Lowercase error strings, wrap with `%w`.
+- Tests should live in the same package as the source code.
+- No new dependencies without significant technical justification.
## For AI Agents
-See [AGENTS.md](AGENTS.md) for detailed conventions and patterns.
+See [AGENTS.md](AGENTS.md) for detailed conventions and patterns when contributing via an agentic workflow.
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 00000000..2d1338e5
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,26 @@
+# Security Policy
+
+## Supported Versions
+
+We currently support the following versions of Pinchtab with security updates:
+
+| Version | Supported |
+| ------- | ------------------ |
+| v0.5.x | :white_check_mark: |
+| < v0.5 | :x: |
+
+## Reporting a Vulnerability
+
+We take the security of our browser automation bridge seriously. If you believe you have found a security vulnerability, please do not report it via a public GitHub issue.
+
+Instead, please report vulnerabilities privately by:
+
+1. Opening a **Private Vulnerability Report** on GitHub (if available for this repo).
+2. Or emailing the maintainer directly at [INSERT EMAIL ADDRESS].
+
+Please include:
+- A description of the vulnerability.
+- Steps to reproduce (proof of concept).
+- Potential impact.
+
+We will acknowledge receipt of your report within 48 hours and provide a timeline for a fix if necessary.
diff --git a/animations_test.go b/animations_test.go
deleted file mode 100644
index 3bb80cae..00000000
--- a/animations_test.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package main
-
-import (
- "strings"
- "testing"
-)
-
-func TestDisableAnimationsCSSContent(t *testing.T) {
-
- if !strings.Contains(disableAnimationsCSS, "animation: none !important") {
- t.Error("missing animation: none rule")
- }
- if !strings.Contains(disableAnimationsCSS, "transition: none !important") {
- t.Error("missing transition: none rule")
- }
- if !strings.Contains(disableAnimationsCSS, "animation-duration: 0s !important") {
- t.Error("missing animation-duration: 0s rule")
- }
- if !strings.Contains(disableAnimationsCSS, "transition-duration: 0s !important") {
- t.Error("missing transition-duration: 0s rule")
- }
- if !strings.Contains(disableAnimationsCSS, "scroll-behavior: auto !important") {
- t.Error("missing scroll-behavior: auto rule")
- }
- if !strings.Contains(disableAnimationsCSS, "data-pinchtab") {
- t.Error("missing data-pinchtab attribute for identification")
- }
-}
-
-func TestDisableAnimationsCSSIsIIFE(t *testing.T) {
- trimmed := strings.TrimSpace(disableAnimationsCSS)
- if !strings.HasPrefix(trimmed, "(function()") {
- t.Error("CSS injection should be wrapped in IIFE")
- }
- if !strings.HasSuffix(trimmed, "();") {
- t.Error("CSS injection should end with IIFE invocation")
- }
-}
-
-func TestNoAnimationsConfigDefault(t *testing.T) {
-
- if cfg.NoAnimations {
- t.Error("noAnimations should default to false")
- }
-}
diff --git a/bridge.go b/bridge.go
deleted file mode 100644
index e523a8e3..00000000
--- a/bridge.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package main
-
-import (
- "context"
- "log/slog"
-
- "github.com/chromedp/cdproto/page"
- "github.com/chromedp/chromedp"
-)
-
-type TabEntry struct {
- ctx context.Context
- cancel context.CancelFunc
-}
-
-type refCache struct {
- refs map[string]int64
- nodes []A11yNode
-}
-
-type Bridge struct {
- allocCtx context.Context
- browserCtx context.Context
- *TabManager
- stealthScript string
- actions map[string]ActionFunc
- locks *lockManager
-}
-
-func (b *Bridge) injectStealth(ctx context.Context) {
- if b.stealthScript == "" {
- return
- }
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(b.stealthScript).Do(ctx)
- return err
- }),
- ); err != nil {
- slog.Warn("stealth injection failed", "err", err)
- }
-}
-
-// tabSetup is the hook called by TabManager on new tab contexts.
-func (b *Bridge) tabSetup(ctx context.Context) {
- b.injectStealth(ctx)
- if cfg.NoAnimations {
- b.injectNoAnimations(ctx)
- }
-}
-
-// InitTabManager creates and wires the TabManager into the Bridge.
-func (b *Bridge) InitTabManager() {
- b.TabManager = NewTabManager(b.browserCtx, b.tabSetup)
-}
diff --git a/cdp.go b/cdp.go
deleted file mode 100644
index 0987b7a8..00000000
--- a/cdp.go
+++ /dev/null
@@ -1,233 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "time"
-
- "github.com/chromedp/chromedp"
-)
-
-// navigatePage uses raw CDP Page.navigate + polls document.readyState for completion.
-// Unlike chromedp.Navigate which waits for the full load event (hangs on SPAs),
-// this fires navigation and waits for interactive/complete state or timeout.
-func navigatePage(ctx context.Context, url string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- p := map[string]any{"url": url}
- var navResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Page.navigate", p, &navResult); err != nil {
- return fmt.Errorf("page.navigate: %w", err)
- }
-
- var resp struct {
- ErrorText string `json:"errorText"`
- }
- if err := json.Unmarshal(navResult, &resp); err == nil && resp.ErrorText != "" {
- return fmt.Errorf("navigate: %s", resp.ErrorText)
- }
- return nil
- }),
-
- chromedp.ActionFunc(func(ctx context.Context) error {
-
- deadline, ok := ctx.Deadline()
- if !ok {
- deadline = time.Now().Add(10 * time.Second)
- }
- for time.Now().Before(deadline) {
- var readyState string
- evalP := map[string]any{
- "expression": "document.readyState",
- }
- var evalResult json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.evaluate", evalP, &evalResult); err == nil {
- var evalResp struct {
- Result struct {
- Value string `json:"value"`
- } `json:"result"`
- }
- if json.Unmarshal(evalResult, &evalResp) == nil {
- readyState = evalResp.Result.Value
- if readyState == "interactive" || readyState == "complete" {
- return nil
- }
- }
- }
-
- time.Sleep(200 * time.Millisecond)
- }
-
- return nil
- }),
- )
-}
-
-// waitForTitle polls document.title for up to the given duration, returning
-// the first non-empty value or "" on timeout. Pass 0 for the default (2s).
-func waitForTitle(ctx context.Context, wait time.Duration) string {
- if wait <= 0 {
- wait = 2 * time.Second
- }
- deadline := time.Now().Add(wait)
- for time.Now().Before(deadline) {
- var title string
- if err := chromedp.Run(ctx, chromedp.Title(&title)); err == nil && title != "" {
- return title
- }
- time.Sleep(200 * time.Millisecond)
- }
- return ""
-}
-
-// withElement resolves a backendNodeID to a JS remote object, scrolls it into
-// view, and calls the given JS function on it. This is the generic helper for
-// all element-targeted actions (click, hover, select, etc.).
-func withElement(ctx context.Context, backendNodeID int64, jsFunc string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- objectID, err := resolveNodeToObject(ctx, backendNodeID)
- if err != nil {
- return err
- }
- callP := map[string]any{
- "objectId": objectID,
- "functionDeclaration": jsFunc,
- "arguments": []any{},
- }
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", callP, nil); err != nil {
- return fmt.Errorf("callFunctionOn: %w", err)
- }
- return nil
- }),
- )
-}
-
-// withElementArg is like withElement but passes a single string argument to the JS function.
-func withElementArg(ctx context.Context, backendNodeID int64, jsFunc string, arg string) error {
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- objectID, err := resolveNodeToObject(ctx, backendNodeID)
- if err != nil {
- return err
- }
- callP := map[string]any{
- "objectId": objectID,
- "functionDeclaration": jsFunc,
- "arguments": []any{map[string]any{"value": arg}},
- }
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Runtime.callFunctionOn", callP, nil); err != nil {
- return fmt.Errorf("callFunctionOn: %w", err)
- }
- return nil
- }),
- )
-}
-
-// clickByNodeID scrolls an element into view and clicks it.
-func clickByNodeID(ctx context.Context, backendNodeID int64) error {
- return withElement(ctx, backendNodeID, "function() { this.scrollIntoViewIfNeeded(); this.click(); }")
-}
-
-// typeByNodeID scrolls an element into view, focuses it, and sends keyboard events.
-func typeByNodeID(ctx context.Context, backendNodeID int64, text string) error {
- if err := withElement(ctx, backendNodeID, "function() { this.scrollIntoViewIfNeeded(); }"); err != nil {
- return err
- }
- return chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- p := map[string]any{"backendNodeId": backendNodeID}
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil); err != nil {
- return fmt.Errorf("DOM.focus: %w", err)
- }
- return nil
- }),
- chromedp.KeyEvent(text),
- )
-}
-
-// hoverByNodeID scrolls an element into view and dispatches a mouseover event.
-func hoverByNodeID(ctx context.Context, backendNodeID int64) error {
- return withElement(ctx, backendNodeID, `function() {
- this.scrollIntoViewIfNeeded();
- this.dispatchEvent(new MouseEvent('mouseover', {bubbles: true}));
- this.dispatchEvent(new MouseEvent('mouseenter', {bubbles: false}));
- }`)
-}
-
-// selectByNodeID sets the value of a <select> element and fires change event.
-func selectByNodeID(ctx context.Context, backendNodeID int64, value string) error {
- return withElementArg(ctx, backendNodeID, `function(val) {
- this.scrollIntoViewIfNeeded();
- const opt = Array.from(this.options).find(o => o.value === val || o.textContent.trim() === val);
- if (opt) { this.value = opt.value; }
- else { this.value = val; }
- this.dispatchEvent(new Event('change', {bubbles: true}));
- }`, value)
-}
-
-// scrollByNodeID scrolls an element into view.
-func scrollByNodeID(ctx context.Context, backendNodeID int64) error {
- return withElement(ctx, backendNodeID, "function() { this.scrollIntoViewIfNeeded(); }")
-}
-
-// URL patterns for blocking resources via Network.setBlockedURLs.
-var imageBlockPatterns = []string{
-
- "*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico",
- "*.bmp", "*.tiff", "*.avif", "*.jfif",
-
- "*/images/*", "*/img/*", "*/photos/*", "*/thumbnails/*",
- "*imagedelivery.net*", "*images.unsplash.com*", "*pbs.twimg.com*",
-}
-
-var mediaBlockPatterns = append(imageBlockPatterns,
-
- "*.woff", "*.woff2", "*.ttf", "*.otf", "*.eot",
-
- "*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.m3u8",
-
- "*.css",
-)
-
-// setResourceBlocking uses Network.setBlockedURLs to block resources by URL pattern.
-// Pass nil to clear the blocklist.
-func setResourceBlocking(ctx context.Context, patterns []string) error {
- return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
-
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Network.enable", nil, nil); err != nil {
- return fmt.Errorf("network enable: %w", err)
- }
-
- if patterns == nil {
- patterns = []string{}
- }
- p := map[string]any{"urls": patterns}
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "Network.setBlockedURLs", p, nil); err != nil {
- return fmt.Errorf("Network.setBlockedURLs: %w", err)
- }
- return nil
- }))
-}
-
-// resolveNodeToObject converts a backendNodeID to a JS remote object ID.
-func resolveNodeToObject(ctx context.Context, backendNodeID int64) (string, error) {
- p := map[string]any{"backendNodeId": backendNodeID}
- var result json.RawMessage
- if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", p, &result); err != nil {
- return "", fmt.Errorf("DOM.resolveNode: %w", err)
- }
- var resp struct {
- Object struct {
- ObjectID string `json:"objectId"`
- } `json:"object"`
- }
- if err := json.Unmarshal(result, &resp); err != nil {
- return "", fmt.Errorf("unmarshal resolveNode: %w", err)
- }
- if resp.Object.ObjectID == "" {
- return "", fmt.Errorf("no objectId for node %d", backendNodeID)
- }
- return resp.Object.ObjectID, nil
-}
diff --git a/cmd/pinchtab/browser.go b/cmd/pinchtab/browser.go
new file mode 100644
index 00000000..88c91f17
--- /dev/null
+++ b/cmd/pinchtab/browser.go
@@ -0,0 +1,147 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "os"
+ "strings"
+
+ "github.com/chromedp/cdproto/emulation"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func setupAllocator(cfg *config.RuntimeConfig) (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption) {
+ if cfg.CdpURL != "" {
+ slog.Info("connecting to Chrome", "url", cfg.CdpURL)
+ ctx, cancel := chromedp.NewRemoteAllocator(context.Background(), cfg.CdpURL)
+ return ctx, cancel, nil
+ }
+
+ if err := os.MkdirAll(cfg.ProfileDir, 0755); err != nil {
+ slog.Error("cannot create profile dir", "err", err)
+ os.Exit(1)
+ }
+
+ for _, lockName := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
+ lockPath := fmt.Sprintf("%s/%s", cfg.ProfileDir, lockName)
+ if err := os.Remove(lockPath); err == nil {
+ slog.Warn("removed stale lock", "file", lockName)
+ }
+ }
+
+ if bridge.WasUncleanExit(cfg.ProfileDir) {
+ slog.Warn("previous session exited uncleanly, clearing Chrome session restore data")
+ bridge.ClearChromeSessions(cfg.ProfileDir)
+ }
+
+ slog.Info("launching Chrome", "profile", cfg.ProfileDir, "headless", cfg.Headless)
+
+ opts := buildChromeOpts(cfg)
+
+ bridge.MarkCleanExit(cfg.ProfileDir)
+ ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
+ return ctx, cancel, opts
+}
+
+func buildChromeOpts(cfg *config.RuntimeConfig) []chromedp.ExecAllocatorOption {
+ opts := []chromedp.ExecAllocatorOption{
+ chromedp.UserDataDir(cfg.ProfileDir),
+ chromedp.NoFirstRun,
+ chromedp.NoDefaultBrowserCheck,
+
+ chromedp.Flag("exclude-switches", "enable-automation"),
+ chromedp.Flag("disable-infobars", true),
+ chromedp.Flag("disable-dev-shm-usage", true),
+ chromedp.Flag("disable-renderer-backgrounding", true),
+ chromedp.Flag("disable-background-timer-throttling", true),
+ chromedp.Flag("disable-backgrounding-occluded-windows", true),
+ chromedp.Flag("disable-client-side-phishing-detection", true),
+ chromedp.Flag("disable-default-apps", true),
+ chromedp.Flag("disable-hang-monitor", true),
+ chromedp.Flag("disable-prompt-on-repost", true),
+ chromedp.Flag("disable-sync", true),
+ chromedp.Flag("disable-web-security", false),
+
+ chromedp.Flag("disable-background-networking", false),
+ chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),
+ chromedp.Flag("disable-popup-blocking", true),
+ chromedp.Flag("no-first-run", true),
+
+ chromedp.Flag("disable-session-crashed-bubble", true),
+ chromedp.Flag("hide-crash-restore-bubble", true),
+ chromedp.Flag("disable-device-discovery-notifications", true),
+
+ chromedp.Flag("js-flags", "--random-seed=1157259157"),
+
+ chromedp.WindowSize(randomWindowSize()),
+ }
+
+ if cfg.ChromeBinary != "" {
+ opts = append(opts, chromedp.ExecPath(cfg.ChromeBinary))
+ }
+ if cfg.ChromeExtraFlags != "" {
+ for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
+ if k, v, ok := strings.Cut(f, "="); ok {
+ opts = append(opts, chromedp.Flag(strings.TrimLeft(k, "-"), v))
+ } else {
+ opts = append(opts, chromedp.Flag(strings.TrimLeft(f, "-"), true))
+ }
+ }
+ }
+
+ if cfg.Headless {
+ opts = append(opts, chromedp.Headless)
+ } else {
+ opts = append(opts, chromedp.Flag("headless", false))
+ }
+
+ return opts
+}
+
+func startChrome(allocCtx context.Context, seededScript string) (context.Context, context.CancelFunc, error) {
+ bCtx, bCancel := chromedp.NewContext(allocCtx)
+
+ startCtx, startDone := context.WithTimeout(context.Background(), chromeStartTimeout)
+ defer startDone()
+
+ errCh := make(chan error, 1)
+ go func() {
+ errCh <- chromedp.Run(bCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ _, err := page.AddScriptToEvaluateOnNewDocument(seededScript).Do(ctx)
+ return err
+ }),
+ )
+ }()
+
+ select {
+ case err := <-errCh:
+ if err != nil {
+ bCancel()
+ return nil, nil, err
+ }
+ return bCtx, bCancel, nil
+ case <-startCtx.Done():
+ bCancel()
+ return nil, nil, fmt.Errorf("timed out after %s", chromeStartTimeout)
+ }
+}
+
+func applyTimezone(browserCtx context.Context, cfg *config.RuntimeConfig) {
+ if cfg.Timezone == "" {
+ return
+ }
+ if err := chromedp.Run(browserCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return emulation.SetTimezoneOverride(cfg.Timezone).Do(ctx)
+ }),
+ ); err != nil {
+ slog.Warn("timezone override failed", "tz", cfg.Timezone, "err", err)
+ } else {
+ slog.Info("timezone override", "tz", cfg.Timezone)
+ }
+}
diff --git a/cmd_connect.go b/cmd/pinchtab/cmd_connect.go
similarity index 95%
rename from cmd_connect.go
rename to cmd/pinchtab/cmd_connect.go
index 346ebe7e..5651cb0a 100644
--- a/cmd_connect.go
+++ b/cmd/pinchtab/cmd_connect.go
@@ -7,6 +7,8 @@ import (
"net/http"
"net/url"
"os"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
type profileInstanceStatus struct {
@@ -18,7 +20,7 @@ type profileInstanceStatus struct {
Error string `json:"error"`
}
-func handleConnectCommand() {
+func handleConnectCommand(cfg *config.RuntimeConfig) {
profile := ""
dashboardURL := os.Getenv("PINCHTAB_DASHBOARD_URL")
jsonOut := false
diff --git a/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.go
similarity index 75%
rename from cmd_dashboard.go
rename to cmd/pinchtab/cmd_dashboard.go
index 575e1804..b398ce9c 100644
--- a/cmd_dashboard.go
+++ b/cmd/pinchtab/cmd_dashboard.go
@@ -12,11 +12,19 @@ import (
"sync"
"syscall"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/dashboard"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+ "github.com/pinchtab/pinchtab/internal/web"
)
// runDashboard starts a lightweight dashboard server — no Chrome, no bridge.
// It manages Pinchtab instances via the orchestrator and serves the dashboard UI.
-func runDashboard() {
+func runDashboard(cfg *config.RuntimeConfig) {
dashPort := cfg.Port
if dashPort == "" {
dashPort = "9870"
@@ -30,20 +38,20 @@ func runDashboard() {
os.Exit(1)
}
- profMgr := NewProfileManager(profilesDir)
- dashboard := NewDashboard(nil)
- orchestrator := NewOrchestrator(profilesDir)
- orchestrator.SetProfileManager(profMgr)
- dashboard.SetInstanceLister(orchestrator)
+ profMgr := profiles.NewProfileManager(profilesDir)
+ dash := dashboard.NewDashboard(nil)
+ orch := orchestrator.NewOrchestrator(profilesDir)
+ orch.SetProfileManager(profMgr)
+ dash.SetInstanceLister(orch)
mux := http.NewServeMux()
- dashboard.RegisterHandlers(mux)
- orchestrator.RegisterHandlers(mux)
+ dash.RegisterHandlers(mux)
+ orch.RegisterHandlers(mux)
profMgr.RegisterHandlers(mux)
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
- jsonResp(w, 200, map[string]string{"status": "ok", "mode": "dashboard"})
+ web.JSON(w, 200, map[string]string{"status": "ok", "mode": "dashboard"})
})
proxyEndpoints := []string{
@@ -56,18 +64,18 @@ func runDashboard() {
for _, ep := range proxyEndpoints {
endpoint := ep
mux.HandleFunc(endpoint, func(w http.ResponseWriter, r *http.Request) {
- target := orchestrator.FirstRunningURL()
+ target := orch.FirstRunningURL()
if target == "" {
- jsonErr(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
+ web.Error(w, 503, fmt.Errorf("no running instances — launch one from the Profiles tab"))
return
}
proxyRequest(w, r, target+endpoint)
})
}
- profileObserver := func(evt AgentEvent) {
+ profileObserver := func(evt dashboard.AgentEvent) {
if evt.Profile != "" {
- profMgr.RecordAction(evt.Profile, ActionRecord{
+ profMgr.RecordAction(evt.Profile, bridge.ActionRecord{
Timestamp: evt.Timestamp,
Method: strings.SplitN(evt.Action, " ", 2)[0],
Endpoint: strings.SplitN(evt.Action, " ", 2)[1],
@@ -79,9 +87,9 @@ func runDashboard() {
}
}
- handler := dashboard.TrackingMiddleware(
- []EventObserver{profileObserver},
- loggingMiddleware(corsMiddleware(authMiddleware(mux))),
+ handler := dash.TrackingMiddleware(
+ []dashboard.EventObserver{profileObserver},
+ handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),
)
srv := &http.Server{Addr: cfg.Bind + ":" + dashPort, Handler: handler}
@@ -104,10 +112,9 @@ func runDashboard() {
}
go func() {
-
time.Sleep(500 * time.Millisecond)
headlessDefault := os.Getenv("PINCHTAB_HEADED") == ""
- inst, err := orchestrator.Launch(defaultProfile, defaultPort, headlessDefault)
+ inst, err := orch.Launch(defaultProfile, defaultPort, headlessDefault)
if err != nil {
slog.Warn("auto-launch failed", "err", err)
return
@@ -122,8 +129,8 @@ func runDashboard() {
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down dashboard...")
- dashboard.Shutdown()
- orchestrator.Shutdown()
+ dash.Shutdown()
+ orch.Shutdown()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
@@ -133,7 +140,7 @@ func runDashboard() {
}
mux.HandleFunc("POST /shutdown", func(w http.ResponseWriter, r *http.Request) {
- jsonResp(w, 200, map[string]string{"status": "shutting down"})
+ web.JSON(w, 200, map[string]string{"status": "shutting down"})
go doShutdown()
})
@@ -144,7 +151,7 @@ func runDashboard() {
go doShutdown()
<-sig
slog.Warn("force shutdown requested")
- orchestrator.ForceShutdown()
+ orch.ForceShutdown()
os.Exit(130)
}()
@@ -159,20 +166,19 @@ func runDashboard() {
// proxyRequest forwards an HTTP request to a target URL.
// For WebSocket upgrades (screencast), it does a WebSocket proxy.
func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
-
if r.URL.RawQuery != "" {
targetURL += "?" + r.URL.RawQuery
}
if isWebSocketUpgrade(r) {
- proxyWebSocket(w, r, targetURL)
+ handlers.ProxyWebSocket(w, r, targetURL)
return
}
client := &http.Client{Timeout: 30 * time.Second}
proxyReq, err := http.NewRequestWithContext(r.Context(), r.Method, targetURL, r.Body)
if err != nil {
- jsonErr(w, 502, fmt.Errorf("proxy error: %w", err))
+ web.Error(w, 502, fmt.Errorf("proxy error: %w", err))
return
}
@@ -184,7 +190,7 @@ func proxyRequest(w http.ResponseWriter, r *http.Request, targetURL string) {
resp, err := client.Do(proxyReq)
if err != nil {
- jsonErr(w, 502, fmt.Errorf("instance unreachable: %w", err))
+ web.Error(w, 502, fmt.Errorf("instance unreachable: %w", err))
return
}
defer func() { _ = resp.Body.Close() }()
diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.go
new file mode 100644
index 00000000..9d7a1505
--- /dev/null
+++ b/cmd/pinchtab/main.go
@@ -0,0 +1,227 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "math/rand"
+ "net/http"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/dashboard"
+ "github.com/pinchtab/pinchtab/internal/handlers"
+ "github.com/pinchtab/pinchtab/internal/human"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+)
+
+var commonWindowSizes = [][2]int{
+ {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},
+ {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},
+}
+
+func randomWindowSize() (int, int) {
+ s := commonWindowSizes[rand.Intn(len(commonWindowSizes))]
+ return s[0], s[1]
+}
+
+var version = "dev"
+
+const chromeStartTimeout = 15 * time.Second
+
+func main() {
+ cfg := config.Load()
+
+ if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-v") {
+ fmt.Printf("pinchtab %s\n", version)
+ os.Exit(0)
+ }
+
+ if len(os.Args) > 1 && os.Args[1] == "config" {
+ config.HandleConfigCommand(cfg)
+ os.Exit(0)
+ }
+
+ if len(os.Args) > 1 && os.Args[1] == "connect" {
+ handleConnectCommand(cfg)
+ os.Exit(0)
+ }
+
+ if len(os.Args) > 1 && os.Args[1] == "dashboard" {
+ runDashboard(cfg)
+ return
+ }
+
+ if err := os.MkdirAll(cfg.StateDir, 0755); err != nil {
+ slog.Error("cannot create state dir", "err", err)
+ os.Exit(1)
+ }
+
+ allocCtx, allocCancel, chromeOpts := setupAllocator(cfg)
+ defer allocCancel()
+
+ stealthSeed := rand.Intn(1000000000)
+ human.SetHumanRandSeed(int64(stealthSeed))
+ seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + assets.StealthScript
+
+ browserCtx, browserCancel, err := startChrome(allocCtx, seededScript)
+ if err != nil {
+ slog.Warn("Chrome startup failed, clearing sessions and retrying once", "err", err)
+
+ allocCancel()
+ bridge.ClearChromeSessions(cfg.ProfileDir)
+ bridge.MarkCleanExit(cfg.ProfileDir)
+
+ allocCtx, allocCancel, _ = setupAllocator(cfg)
+ _ = chromeOpts // used implicitly via setupAllocator
+
+ browserCtx, browserCancel, err = startChrome(allocCtx, seededScript)
+ if err != nil {
+ slog.Error("Chrome failed to start after retry",
+ "err", err,
+ "hint", "try BRIDGE_NO_RESTORE=true or delete your profile directory",
+ "profile", cfg.ProfileDir,
+ )
+ allocCancel()
+ os.Exit(1)
+ }
+ slog.Info("Chrome started on retry")
+ }
+ defer browserCancel()
+
+ applyTimezone(browserCtx, cfg)
+
+ b := bridge.New(allocCtx, browserCtx, cfg)
+ b.StealthScript = seededScript
+ b.InitActionRegistry()
+
+ profilesDir := filepath.Join(filepath.Dir(cfg.ProfileDir), "profiles")
+ profMgr := profiles.NewProfileManager(profilesDir)
+ dash := dashboard.NewDashboard(nil)
+ orch := orchestrator.NewOrchestrator(profilesDir)
+ orch.SetProfileManager(profMgr)
+ dash.SetInstanceLister(orch)
+
+ initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
+ b.RegisterTab(string(initTargetID), browserCtx)
+ slog.Info("initial tab", "id", string(initTargetID))
+
+ if !cfg.Headless {
+ go func() {
+ time.Sleep(200 * time.Millisecond)
+ _ = chromedp.Run(browserCtx, chromedp.Navigate("http://localhost:"+cfg.Port+"/welcome"))
+ }()
+ }
+
+ if !cfg.NoRestore {
+ go b.RestoreState()
+ }
+
+ cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
+ defer cleanupCancel()
+ go b.CleanStaleTabs(cleanupCtx, 30*cfg.ActionTimeout)
+
+ mux := http.NewServeMux()
+ h := handlers.New(b, cfg, profMgr, dash, orch)
+
+ shutdownOnce := &sync.Once{}
+ doShutdown := func() {
+ shutdownOnce.Do(func() {
+ slog.Info("shutting down, saving state...")
+ orch.Shutdown()
+ cleanupCancel()
+ b.SaveState()
+ bridge.MarkCleanExit(cfg.ProfileDir)
+
+ browserCancel()
+ allocCancel()
+ slog.Info("chrome closed")
+ })
+ }
+
+ h.RegisterRoutes(mux, doShutdown)
+
+ profileObserver := func(evt dashboard.AgentEvent) {
+ if evt.Profile != "" {
+ profMgr.RecordAction(evt.Profile, bridge.ActionRecord{
+ Timestamp: evt.Timestamp,
+ Method: strings.SplitN(evt.Action, " ", 2)[0],
+ Endpoint: strings.SplitN(evt.Action, " ", 2)[1],
+ URL: evt.URL,
+ TabID: evt.TabID,
+ DurationMs: evt.DurationMs,
+ Status: evt.Status,
+ })
+ }
+ }
+
+ handler := dash.TrackingMiddleware(
+ []dashboard.EventObserver{profileObserver},
+ handlers.LoggingMiddleware(handlers.CorsMiddleware(handlers.AuthMiddleware(cfg, mux))),
+ )
+
+ srv := &http.Server{Addr: cfg.ListenAddr(), Handler: handler}
+
+ setupSignalHandler(doShutdown, func() {
+ orch.ForceShutdown()
+ cleanupCancel()
+ browserCancel()
+ allocCancel()
+ })
+
+ slog.Info("🦀 PINCH! PINCH!", "port", cfg.Port, "cdp", cfg.CdpURL, "stealth", cfg.StealthLevel)
+ if cfg.Token != "" {
+ slog.Info("auth enabled")
+ } else {
+ slog.Info("auth disabled (set BRIDGE_TOKEN to enable)")
+ }
+
+ go runStartupHealthCheck(cfg)
+
+ if err := srv.ListenAndServe(); err != http.ErrServerClosed {
+ slog.Error("server", "err", err)
+ os.Exit(1)
+ }
+}
+
+func setupSignalHandler(shutdownFn func(), forceFn func()) {
+ go func() {
+ sig := make(chan os.Signal, 2)
+ signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
+ <-sig
+ go shutdownFn()
+ <-sig
+ slog.Warn("force shutdown requested")
+ forceFn()
+ os.Exit(130)
+ }()
+}
+
+func runStartupHealthCheck(cfg *config.RuntimeConfig) {
+ time.Sleep(500 * time.Millisecond)
+ client := &http.Client{Timeout: 5 * time.Second}
+ resp, err := client.Get(fmt.Sprintf("http://localhost:%s/health", cfg.Port))
+ if err != nil {
+ slog.Error("startup health check failed",
+ "err", err,
+ "hint", "try BRIDGE_NO_RESTORE=true or delete your profile directory",
+ )
+ return
+ }
+ _ = resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ slog.Info("startup health check passed")
+ } else {
+ slog.Warn("startup health check unexpected status", "status", resp.StatusCode)
+ }
+}
diff --git a/config_test.go b/config_test.go
deleted file mode 100644
index 822aaedf..00000000
--- a/config_test.go
+++ /dev/null
@@ -1,194 +0,0 @@
-package main
-
-import (
- "os"
- "testing"
-)
-
-func TestEnvOr(t *testing.T) {
- if got := envOr("PINCHTAB_TEST_UNSET_12345", "fallback"); got != "fallback" {
- t.Errorf("expected fallback, got %s", got)
- }
-
- _ = os.Setenv("PINCHTAB_TEST_SET", "value")
- defer func() { _ = os.Unsetenv("PINCHTAB_TEST_SET") }()
- if got := envOr("PINCHTAB_TEST_SET", "fallback"); got != "value" {
- t.Errorf("expected value, got %s", got)
- }
-}
-
-func TestEnvBoolOr(t *testing.T) {
- if got := envBoolOr("PINCHTAB_TEST_BOOL_UNSET", true); !got {
- t.Error("expected fallback true for unset env")
- }
- if got := envBoolOr("PINCHTAB_TEST_BOOL_UNSET", false); got {
- t.Error("expected fallback false for unset env")
- }
-
- t.Setenv("PINCHTAB_TEST_BOOL", "true")
- if got := envBoolOr("PINCHTAB_TEST_BOOL", false); !got {
- t.Error("expected true from env true")
- }
-
- t.Setenv("PINCHTAB_TEST_BOOL", "false")
- if got := envBoolOr("PINCHTAB_TEST_BOOL", true); got {
- t.Error("expected false from env false")
- }
-
- t.Setenv("PINCHTAB_TEST_BOOL", "1")
- if got := envBoolOr("PINCHTAB_TEST_BOOL", false); !got {
- t.Error("expected true from env 1")
- }
-
- t.Setenv("PINCHTAB_TEST_BOOL", "0")
- if got := envBoolOr("PINCHTAB_TEST_BOOL", true); got {
- t.Error("expected false from env 0")
- }
-}
-
-func TestHomeDir(t *testing.T) {
- h := homeDir()
- if h == "" {
- t.Error("homeDir returned empty string")
- }
-}
-
-func TestMaskToken(t *testing.T) {
- tests := []struct {
- input, want string
- }{
- {"", "(none)"},
- {"short", "***"},
- {"12345678", "***"},
- {"123456789", "1234...6789"},
- {"my-super-secret-cfg.Token", "my-s...oken"},
- }
- for _, tt := range tests {
- if got := maskToken(tt.input); got != tt.want {
- t.Errorf("maskToken(%q) = %q, want %q", tt.input, got, tt.want)
- }
- }
-}
-
-func TestEnvIntOr(t *testing.T) {
- t.Setenv("TEST_INT", "42")
- if got := envIntOr("TEST_INT", 10); got != 42 {
- t.Errorf("envIntOr = %d, want 42", got)
- }
- t.Setenv("TEST_INT", "")
- if got := envIntOr("TEST_INT", 10); got != 10 {
- t.Errorf("envIntOr empty = %d, want 10", got)
- }
- t.Setenv("TEST_INT", "bad")
- if got := envIntOr("TEST_INT", 10); got != 10 {
- t.Errorf("envIntOr bad = %d, want 10", got)
- }
- t.Setenv("TEST_INT", "-5")
- if got := envIntOr("TEST_INT", 10); got != 10 {
- t.Errorf("envIntOr negative = %d, want 10", got)
- }
-}
-
-func TestMaxTabsDefault(t *testing.T) {
- t.Setenv("BRIDGE_MAX_TABS", "")
- t.Setenv("BRIDGE_CONFIG", "/nonexistent")
- loadConfig()
- if cfg.MaxTabs != 20 {
- t.Errorf("default MaxTabs = %d, want 20", cfg.MaxTabs)
- }
-}
-
-func TestMaxTabsEnv(t *testing.T) {
- t.Setenv("BRIDGE_MAX_TABS", "5")
- t.Setenv("BRIDGE_CONFIG", "/nonexistent")
- loadConfig()
- if cfg.MaxTabs != 5 {
- t.Errorf("MaxTabs = %d, want 5", cfg.MaxTabs)
- }
-}
-
-func TestDefaultConfig(t *testing.T) {
- fc := defaultFileConfig()
- if fc.Port != "9867" {
- t.Errorf("default Port = %q, want 9867", fc.Port)
- }
- if fc.Headless == nil || !*fc.Headless {
- t.Error("default config should be headless")
- }
- if fc.NoRestore {
- t.Error("default config should not have NoRestore")
- }
- if fc.TimeoutSec != 15 {
- t.Errorf("default timeout = %d, want 15", fc.TimeoutSec)
- }
- if fc.NavigateSec != 30 {
- t.Errorf("default navigate timeout = %d, want 30", fc.NavigateSec)
- }
-}
-
-func TestLoadConfig_FromFile(t *testing.T) {
-
- origPort := cfg.Port
- defer func() { cfg.Port = origPort }()
-
- dir := t.TempDir()
- configPath := dir + "/config.json"
- _ = os.WriteFile(configPath, []byte(`{"port":"7777"}`), 0644)
-
- t.Setenv("BRIDGE_PORT", "")
- t.Setenv("BRIDGE_CONFIG", configPath)
-
- loadConfig()
- if cfg.Port != "7777" {
- t.Errorf("loadConfig from file: port = %q, want 7777", cfg.Port)
- }
-}
-
-func TestLoadConfig_EnvOverridesFile(t *testing.T) {
- origPort := cfg.Port
- defer func() { cfg.Port = origPort }()
-
- dir := t.TempDir()
- configPath := dir + "/config.json"
- _ = os.WriteFile(configPath, []byte(`{"port":"7777"}`), 0644)
-
- t.Setenv("BRIDGE_CONFIG", configPath)
- t.Setenv("BRIDGE_PORT", "8888")
-
- cfg.Port = "8888"
- loadConfig()
-
- if cfg.Port != "8888" {
- t.Errorf("env should override file: port = %q, want 8888", cfg.Port)
- }
-}
-
-func TestLoadConfig_InvalidJSON(t *testing.T) {
- dir := t.TempDir()
- configPath := dir + "/config.json"
- _ = os.WriteFile(configPath, []byte("{broken json!!!"), 0644)
-
- origPort := cfg.Port
- defer func() { cfg.Port = origPort }()
-
- t.Setenv("BRIDGE_CONFIG", configPath)
- t.Setenv("BRIDGE_PORT", "")
- cfg.Port = "9867"
- loadConfig()
- if cfg.Port != "9867" {
- t.Errorf("invalid config should not change port, got %q", cfg.Port)
- }
-}
-
-func TestConstants(t *testing.T) {
-
- if actionClick != "click" {
- t.Error("actionClick mismatch")
- }
- if tabActionNew != "new" {
- t.Error("tabActionNew mismatch")
- }
- if maxBodySize != 1<<20 {
- t.Error("maxBodySize should be 1MB")
- }
-}
diff --git a/dashboard_test.go b/dashboard_test.go
deleted file mode 100644
index 6ac117ea..00000000
--- a/dashboard_test.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "errors"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-)
-
-func TestDashboardRecordAndGetAgents(t *testing.T) {
- d := NewDashboard(nil)
-
- d.RecordEvent(AgentEvent{
- AgentID: "mario",
- Profile: "default",
- Action: "GET /snapshot",
- URL: "https://example.com",
- TabID: "tab1",
- Status: 200,
- DurationMs: 150,
- Timestamp: time.Now(),
- })
-
- d.RecordEvent(AgentEvent{
- AgentID: "r40",
- Action: "POST /navigate",
- URL: "https://r40.io",
- Status: 200,
- DurationMs: 80,
- Timestamp: time.Now(),
- })
-
- agents := d.GetAgents()
- if len(agents) != 2 {
- t.Fatalf("expected 2 agents, got %d", len(agents))
- }
-
- found := map[string]bool{}
- for _, a := range agents {
- found[a.AgentID] = true
- if a.Status != "active" {
- t.Errorf("agent %s should be active, got %s", a.AgentID, a.Status)
- }
- }
- if !found["mario"] || !found["r40"] {
- t.Error("expected both mario and r40 agents")
- }
-}
-
-func TestDashboardAgentUpdates(t *testing.T) {
- d := NewDashboard(nil)
-
- d.RecordEvent(AgentEvent{
- AgentID: "bot", Action: "GET /snapshot", URL: "https://page1.com",
- Timestamp: time.Now(),
- })
- d.RecordEvent(AgentEvent{
- AgentID: "bot", Action: "POST /navigate", URL: "https://page2.com",
- Timestamp: time.Now(),
- })
-
- agents := d.GetAgents()
- if len(agents) != 1 {
- t.Fatalf("expected 1 agent, got %d", len(agents))
- }
- if agents[0].CurrentURL != "https://page2.com" {
- t.Errorf("expected URL page2.com, got %s", agents[0].CurrentURL)
- }
- if agents[0].ActionCount != 2 {
- t.Errorf("expected 2 actions, got %d", agents[0].ActionCount)
- }
-}
-
-func TestDashboardHandlerAgents(t *testing.T) {
- d := NewDashboard(nil)
- d.RecordEvent(AgentEvent{
- AgentID: "test-agent", Action: "GET /health",
- Status: 200, Timestamp: time.Now(),
- })
-
- mux := http.NewServeMux()
- d.RegisterHandlers(mux)
-
- req := httptest.NewRequest("GET", "/dashboard/agents", nil)
- w := httptest.NewRecorder()
- mux.ServeHTTP(w, req)
-
- if w.Code != 200 {
- t.Fatalf("expected 200, got %d", w.Code)
- }
-
- var agents []AgentActivity
- _ = json.NewDecoder(w.Body).Decode(&agents)
- if len(agents) != 1 || agents[0].AgentID != "test-agent" {
- t.Errorf("unexpected agents: %+v", agents)
- }
-}
-
-func TestDashboardUI(t *testing.T) {
- d := NewDashboard(nil)
- mux := http.NewServeMux()
- d.RegisterHandlers(mux)
-
- req := httptest.NewRequest("GET", "/dashboard", nil)
- w := httptest.NewRecorder()
- mux.ServeHTTP(w, req)
-
- if w.Code != 200 {
- t.Fatalf("expected 200, got %d", w.Code)
- }
- if ct := w.Header().Get("Content-Type"); ct != "text/html" {
- t.Errorf("expected text/html, got %s", ct)
- }
- body := w.Body.String()
- if len(body) < 1000 {
- t.Error("dashboard HTML seems too short")
- }
-}
-
-func TestDashboardSSEInit(t *testing.T) {
- d := NewDashboard(nil)
- d.RecordEvent(AgentEvent{AgentID: "sse-agent", Action: "GET /health", Timestamp: time.Now()})
-
- mux := http.NewServeMux()
- d.RegisterHandlers(mux)
-
- srv := httptest.NewServer(mux)
- defer srv.Close()
-
- ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)
- defer cancel()
-
- req, _ := http.NewRequestWithContext(ctx, "GET", srv.URL+"/dashboard/events", nil)
- resp, err := http.DefaultClient.Do(req)
- if err != nil && !errors.Is(err, context.DeadlineExceeded) {
-
- return
- }
- if resp != nil {
- defer func() { _ = resp.Body.Close() }()
- if resp.Header.Get("Content-Type") != "text/event-stream" {
- t.Errorf("expected text/event-stream, got %s", resp.Header.Get("Content-Type"))
- }
- }
-}
-
-func TestTrackingMiddleware(t *testing.T) {
- d := NewDashboard(nil)
- pm := NewProfileManager(t.TempDir())
-
- inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- })
-
- profileObs := func(evt AgentEvent) {
- if evt.Profile != "" {
- pm.tracker.Record(evt.Profile, ActionRecord{
- Timestamp: evt.Timestamp,
- Endpoint: evt.URL,
- Status: evt.Status,
- })
- }
- }
-
- handler := d.TrackingMiddleware([]EventObserver{profileObs}, inner)
-
- req := httptest.NewRequest("GET", "/snapshot?url=https://example.com", nil)
- req.Header.Set("X-Agent-Id", "test-bot")
- req.Header.Set("X-Profile", "my-profile")
- w := httptest.NewRecorder()
- handler.ServeHTTP(w, req)
-
- agents := d.GetAgents()
- if len(agents) != 1 {
- t.Fatalf("expected 1 agent, got %d", len(agents))
- }
- if agents[0].AgentID != "test-bot" {
- t.Errorf("expected agent test-bot, got %s", agents[0].AgentID)
- }
-
- logs := pm.Logs("my-profile", 10)
- if len(logs) != 1 {
- t.Errorf("expected 1 profile log, got %d", len(logs))
- }
-}
-
-func TestTrackingMiddlewareAnonymous(t *testing.T) {
- d := NewDashboard(nil)
-
- inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- })
-
- handler := d.TrackingMiddleware(nil, inner)
-
- req := httptest.NewRequest("GET", "/snapshot", nil)
- w := httptest.NewRecorder()
- handler.ServeHTTP(w, req)
-
- agents := d.GetAgents()
- if len(agents) != 1 || agents[0].AgentID != "anonymous" {
- t.Errorf("expected anonymous agent, got %+v", agents)
- }
-}
-
-func TestTrackingMiddlewareSkipsManagementRoutes(t *testing.T) {
- d := NewDashboard(nil)
-
- inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.WriteHeader(200)
- })
-
- handler := d.TrackingMiddleware(nil, inner)
-
- for _, path := range []string{"/dashboard", "/profiles", "/instances", "/health", "/welcome", "/favicon.ico"} {
- req := httptest.NewRequest("GET", path, nil)
- w := httptest.NewRecorder()
- handler.ServeHTTP(w, req)
- }
-
- agents := d.GetAgents()
- if len(agents) != 0 {
- t.Errorf("management routes should not be tracked, got %+v", agents)
- }
-}
diff --git a/handler_actions.go b/handler_actions.go
deleted file mode 100644
index 703dfd26..00000000
--- a/handler_actions.go
+++ /dev/null
@@ -1,392 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "strings"
- "time"
-
- "github.com/chromedp/cdproto/cdp"
- "github.com/chromedp/cdproto/dom"
- "github.com/chromedp/chromedp"
-)
-
-type actionRequest struct {
- TabID string `json:"tabId"`
- Kind string `json:"kind"`
- Ref string `json:"ref"`
- Selector string `json:"selector"`
- Text string `json:"text"`
- Key string `json:"key"`
- Value string `json:"value"`
- NodeID int64 `json:"nodeId"`
- ScrollX int `json:"scrollX"`
- ScrollY int `json:"scrollY"`
- WaitNav bool `json:"waitNav"`
- Fast bool `json:"fast"`
-}
-
-type ActionFunc func(ctx context.Context, req actionRequest) (map[string]any, error)
-
-func (b *Bridge) initActionRegistry() {
- b.actions = map[string]ActionFunc{
- actionClick: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- var err error
- if req.Selector != "" {
- err = chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))
- } else if req.NodeID > 0 {
- err = clickByNodeID(ctx, req.NodeID)
- } else {
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- }
- if err != nil {
- return nil, err
- }
- if req.WaitNav {
- _ = chromedp.Run(ctx, chromedp.Sleep(cfg.WaitNavDelay))
- }
- return map[string]any{"clicked": true}, nil
- },
- actionType: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for type")
- }
- if req.Selector != "" {
- return map[string]any{"typed": req.Text}, chromedp.Run(ctx,
- chromedp.Click(req.Selector, chromedp.ByQuery),
- chromedp.SendKeys(req.Selector, req.Text, chromedp.ByQuery),
- )
- }
- if req.NodeID > 0 {
- return map[string]any{"typed": req.Text}, typeByNodeID(ctx, req.NodeID, req.Text)
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- actionFill: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.Selector != "" {
- return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
- }
- return map[string]any{"filled": req.Text}, nil
- },
- actionPress: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.Key == "" {
- return nil, fmt.Errorf("key required for press")
- }
- return map[string]any{"pressed": req.Key}, chromedp.Run(ctx, chromedp.KeyEvent(req.Key))
- },
- actionFocus: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.Selector != "" {
- return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))
- }
- if req.NodeID > 0 {
- return map[string]any{"focused": true}, chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- p := map[string]any{"backendNodeId": req.NodeID}
- return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)
- }),
- )
- }
- return map[string]any{"focused": true}, nil
- },
- actionHover: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- return map[string]any{"hovered": true}, hoverByNodeID(ctx, req.NodeID)
- }
- if req.Selector != "" {
- return map[string]any{"hovered": true}, chromedp.Run(ctx,
- chromedp.Evaluate(fmt.Sprintf(`document.querySelector(%q)?.dispatchEvent(new MouseEvent('mouseover', {bubbles:true}))`, req.Selector), nil),
- )
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- actionSelect: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- val := req.Value
- if val == "" {
- val = req.Text
- }
- if val == "" {
- return nil, fmt.Errorf("value required for select")
- }
- if req.NodeID > 0 {
- return map[string]any{"selected": val}, selectByNodeID(ctx, req.NodeID, val)
- }
- if req.Selector != "" {
- return map[string]any{"selected": val}, chromedp.Run(ctx,
- chromedp.SetValue(req.Selector, val, chromedp.ByQuery),
- )
- }
- return nil, fmt.Errorf("need selector or ref")
- },
- actionScroll: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- return map[string]any{"scrolled": true}, scrollByNodeID(ctx, req.NodeID)
- }
- if req.ScrollX != 0 || req.ScrollY != 0 {
- js := fmt.Sprintf("window.scrollBy(%d, %d)", req.ScrollX, req.ScrollY)
- return map[string]any{"scrolled": true, "x": req.ScrollX, "y": req.ScrollY},
- chromedp.Run(ctx, chromedp.Evaluate(js, nil))
- }
- return map[string]any{"scrolled": true, "y": 800},
- chromedp.Run(ctx, chromedp.Evaluate("window.scrollBy(0, 800)", nil))
- },
- actionHumanClick: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.NodeID > 0 {
- if err := humanClickElement(ctx, cdp.NodeID(req.NodeID)); err != nil {
- return nil, err
- }
- return map[string]any{"clicked": true, "human": true}, nil
- }
- if req.Selector != "" {
- var nodes []*cdp.Node
- if err := chromedp.Run(ctx,
- chromedp.Nodes(req.Selector, &nodes, chromedp.ByQuery),
- ); err != nil {
- return nil, err
- }
- if len(nodes) == 0 {
- return nil, fmt.Errorf("element not found: %s", req.Selector)
- }
- if err := humanClickElement(ctx, nodes[0].NodeID); err != nil {
- return nil, err
- }
- return map[string]any{"clicked": true, "human": true}, nil
- }
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- },
- actionHumanType: func(ctx context.Context, req actionRequest) (map[string]any, error) {
- if req.Text == "" {
- return nil, fmt.Errorf("text required for humanType")
- }
-
- if req.Selector != "" {
- if err := chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery)); err != nil {
- return nil, err
- }
- } else if req.NodeID > 0 {
- if err := chromedp.Run(ctx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return dom.Focus().WithNodeID(cdp.NodeID(req.NodeID)).Do(ctx)
- }),
- ); err != nil {
- return nil, err
- }
- } else {
- return nil, fmt.Errorf("need selector, ref, or nodeId")
- }
-
- actions := humanType(req.Text, req.Fast)
- if err := chromedp.Run(ctx, actions...); err != nil {
- return nil, err
- }
-
- return map[string]any{"typed": req.Text, "human": true}, nil
- },
- }
-}
-
-func (b *Bridge) handleAction(w http.ResponseWriter, r *http.Request) {
- var req actionRequest
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- ctx, resolvedTabID, err := b.TabContext(req.TabID)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
- defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
-
- if req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
- cache := b.GetRefCache(resolvedTabID)
- if cache != nil {
- if nid, ok := cache.refs[req.Ref]; ok {
- req.NodeID = nid
- }
- }
- if req.NodeID == 0 {
- jsonResp(w, 400, map[string]string{
- "error": fmt.Sprintf("ref %s not found - take a /snapshot first", req.Ref),
- })
- return
- }
- }
-
- registry := b.actions
- if req.Kind == "" {
- kinds := make([]string, 0, len(registry))
- for k := range registry {
- kinds = append(kinds, k)
- }
- jsonResp(w, 400, map[string]string{
- "error": fmt.Sprintf("missing required field 'kind' - valid values: %s", strings.Join(kinds, ", ")),
- })
- return
- }
- fn, ok := registry[req.Kind]
- if !ok {
- kinds := make([]string, 0, len(registry))
- for k := range registry {
- kinds = append(kinds, k)
- }
- jsonResp(w, 400, map[string]string{
- "error": fmt.Sprintf("unknown action: %s - valid values: %s", req.Kind, strings.Join(kinds, ", ")),
- })
- return
- }
-
- result, err := fn(tCtx, req)
- if err != nil {
- jsonErr(w, 500, fmt.Errorf("action %s: %w", req.Kind, err))
- return
- }
-
- jsonResp(w, 200, result)
-}
-
-type actionsRequest struct {
- TabID string `json:"tabId"`
- Actions []actionRequest `json:"actions"`
- StopOnError bool `json:"stopOnError"`
-}
-
-type actionResult struct {
- Index int `json:"index"`
- Success bool `json:"success"`
- Result map[string]any `json:"result,omitempty"`
- Error string `json:"error,omitempty"`
-}
-
-func (b *Bridge) handleActions(w http.ResponseWriter, r *http.Request) {
- var req actionsRequest
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- if len(req.Actions) == 0 {
- jsonErr(w, 400, fmt.Errorf("actions array is empty"))
- return
- }
-
- ctx, resolvedTabID, err := b.TabContext(req.TabID)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- results := make([]actionResult, 0, len(req.Actions))
- registry := b.actions
-
- for i, action := range req.Actions {
- if action.TabID == "" {
- action.TabID = resolvedTabID
- } else if action.TabID != resolvedTabID {
- ctx, resolvedTabID, err = b.TabContext(action.TabID)
- if err != nil {
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: fmt.Sprintf("tab not found: %v", err),
- })
- if req.StopOnError {
- break
- }
- continue
- }
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
-
- if action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
- cache := b.GetRefCache(resolvedTabID)
- if cache != nil {
- if nid, ok := cache.refs[action.Ref]; ok {
- action.NodeID = nid
- }
- }
- if action.NodeID == 0 {
- tCancel()
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: fmt.Sprintf("ref %s not found - take a /snapshot first", action.Ref),
- })
- if req.StopOnError {
- break
- }
- continue
- }
- }
-
- if action.Kind == "" {
- tCancel()
- results = append(results, actionResult{
- Index: i, Success: false, Error: "missing required field 'kind'",
- })
- if req.StopOnError {
- break
- }
- continue
- }
-
- fn, ok := registry[action.Kind]
- if !ok {
- tCancel()
- kinds := make([]string, 0, len(registry))
- for k := range registry {
- kinds = append(kinds, k)
- }
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: fmt.Sprintf("unknown action: %s - valid values: %s", action.Kind, strings.Join(kinds, ", ")),
- })
- if req.StopOnError {
- break
- }
- continue
- }
-
- actionRes, err := fn(tCtx, action)
- tCancel()
-
- if err != nil {
- results = append(results, actionResult{
- Index: i, Success: false,
- Error: fmt.Sprintf("action %s: %v", action.Kind, err),
- })
- if req.StopOnError {
- break
- }
- } else {
- results = append(results, actionResult{
- Index: i, Success: true, Result: actionRes,
- })
- }
-
- if i < len(req.Actions)-1 {
- time.Sleep(50 * time.Millisecond)
- }
- }
-
- jsonResp(w, 200, map[string]any{
- "results": results,
- "total": len(req.Actions),
- "successful": countSuccessful(results),
- "failed": len(req.Actions) - countSuccessful(results),
- })
-}
-
-func countSuccessful(results []actionResult) int {
- count := 0
- for _, r := range results {
- if r.Success {
- count++
- }
- }
- return count
-}
diff --git a/handler_health_tabs.go b/handler_health_tabs.go
deleted file mode 100644
index d7c5030b..00000000
--- a/handler_health_tabs.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package main
-
-import (
- "net/http"
- "time"
-)
-
-func (b *Bridge) handleHealth(w http.ResponseWriter, r *http.Request) {
- targets, err := b.ListTargets()
- if err != nil {
- jsonResp(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": cfg.CdpURL})
- return
- }
- jsonResp(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": cfg.CdpURL})
-}
-
-func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {
- targets, err := b.ListTargets()
- if err != nil {
- jsonErr(w, 500, err)
- return
- }
-
- tabs := make([]map[string]any, 0, len(targets))
- for _, t := range targets {
- entry := map[string]any{
- "id": string(t.TargetID),
- "url": t.URL,
- "title": t.Title,
- "type": t.Type,
- }
- if lock := b.locks.Get(string(t.TargetID)); lock != nil {
- entry["owner"] = lock.Owner
- entry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)
- }
- tabs = append(tabs, entry)
- }
- jsonResp(w, 200, map[string]any{"tabs": tabs})
-}
diff --git a/handler_navigation.go b/handler_navigation.go
deleted file mode 100644
index a5c53186..00000000
--- a/handler_navigation.go
+++ /dev/null
@@ -1,185 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "net/http"
- "time"
-
- "github.com/chromedp/chromedp"
-)
-
-func (b *Bridge) handleNavigate(w http.ResponseWriter, r *http.Request) {
- var req struct {
- TabID string `json:"tabId"`
- URL string `json:"url"`
- NewTab bool `json:"newTab"`
- WaitTitle float64 `json:"waitTitle"`
- Timeout float64 `json:"timeout"`
- BlockImages *bool `json:"blockImages"`
- BlockMedia *bool `json:"blockMedia"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
- if req.URL == "" {
- jsonErr(w, 400, fmt.Errorf("url required"))
- return
- }
-
- titleWait := time.Duration(0)
- if req.WaitTitle > 0 {
- if req.WaitTitle > 30 {
- req.WaitTitle = 30
- }
- titleWait = time.Duration(req.WaitTitle * float64(time.Second))
- }
-
- navTimeout := cfg.NavigateTimeout
- if req.Timeout > 0 {
- if req.Timeout > 120 {
- req.Timeout = 120
- }
- navTimeout = time.Duration(req.Timeout * float64(time.Second))
- }
-
- var blockPatterns []string
- if req.BlockMedia != nil && *req.BlockMedia {
- blockPatterns = mediaBlockPatterns
- } else if req.BlockImages != nil && *req.BlockImages {
- blockPatterns = imageBlockPatterns
- } else if req.BlockImages != nil && !*req.BlockImages {
- blockPatterns = nil
- } else if cfg.BlockMedia {
- blockPatterns = mediaBlockPatterns
- } else if cfg.BlockImages {
- blockPatterns = imageBlockPatterns
- }
-
- if req.NewTab {
- newTargetID, newCtx, _, err := b.CreateTab(req.URL)
- if err != nil {
- jsonErr(w, 500, fmt.Errorf("new tab: %w", err))
- return
- }
-
- tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)
- defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
-
- if blockPatterns != nil {
- _ = setResourceBlocking(tCtx, blockPatterns)
- }
-
- var url, title string
- _ = chromedp.Run(tCtx, chromedp.Location(&url))
- title = waitForTitle(tCtx, titleWait)
-
- jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": url, "title": title})
- return
- }
-
- ctx, resolvedTabID, err := b.TabContext(req.TabID)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, navTimeout)
- defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
-
- if blockPatterns != nil {
- _ = setResourceBlocking(tCtx, blockPatterns)
- } else if cfg.BlockImages {
- _ = setResourceBlocking(tCtx, nil)
- }
-
- if err := navigatePage(tCtx, req.URL); err != nil {
- jsonErr(w, 500, fmt.Errorf("navigate: %w", err))
- return
- }
-
- b.DeleteRefCache(resolvedTabID)
-
- var url string
- _ = chromedp.Run(tCtx, chromedp.Location(&url))
- title := waitForTitle(tCtx, titleWait)
-
- jsonResp(w, 200, map[string]any{"url": url, "title": title})
-}
-
-func (b *Bridge) handleEvaluate(w http.ResponseWriter, r *http.Request) {
- var req struct {
- TabID string `json:"tabId"`
- Expression string `json:"expression"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
- if req.Expression == "" {
- jsonErr(w, 400, fmt.Errorf("expression required"))
- return
- }
-
- ctx, _, err := b.TabContext(req.TabID)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
- defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
-
- var result any
- if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {
- jsonErr(w, 500, fmt.Errorf("evaluate: %w", err))
- return
- }
-
- jsonResp(w, 200, map[string]any{"result": result})
-}
-
-func (b *Bridge) handleTab(w http.ResponseWriter, r *http.Request) {
- var req struct {
- Action string `json:"action"`
- TabID string `json:"tabId"`
- URL string `json:"url"`
- }
- if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
- return
- }
-
- switch req.Action {
- case tabActionNew:
- newTargetID, ctx, _, err := b.CreateTab(req.URL)
- if err != nil {
- jsonErr(w, 500, err)
- return
- }
-
- var curURL, title string
- _ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
- jsonResp(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})
-
- case tabActionClose:
- if req.TabID == "" {
- jsonErr(w, 400, fmt.Errorf("tabId required"))
- return
- }
-
- if err := b.CloseTab(req.TabID); err != nil {
- jsonErr(w, 500, err)
- return
- }
- jsonResp(w, 200, map[string]any{"closed": true})
-
- default:
- jsonErr(w, 400, fmt.Errorf("action must be 'new' or 'close'"))
- }
-}
diff --git a/handler_test.go b/handler_test.go
deleted file mode 100644
index 4a822a00..00000000
--- a/handler_test.go
+++ /dev/null
@@ -1,335 +0,0 @@
-package main
-
-import (
- "net/http/httptest"
- "strings"
- "testing"
-)
-
-// newTestBridge creates a Bridge with initialized maps (no Chrome).
-func newTestBridge() *Bridge {
- b := &Bridge{}
- b.TabManager = &TabManager{
- tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
- }
- return b
-}
-
-// newTestBridgeWithTabs is an alias used across test files.
-var newTestBridgeWithTabs = newTestBridge
-
-func TestHandleNavigate_MissingURL(t *testing.T) {
- b := newTestBridge()
- body := `{"url": ""}`
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_BadJSON(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader("{bad"))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_NoTab(t *testing.T) {
- b := newTestBridge()
- body := `{"url": "https://example.com"}`
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleAction_UnknownKind(t *testing.T) {
- b := newTestBridge()
-
- body := `{"kind": "explode", "selector": "button"}`
- req := httptest.NewRequest("POST", "/action", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleAction_RefNotFound_NoCache(t *testing.T) {
- b := newTestBridge()
-
- body := `{"kind": "click", "ref": "e99"}`
- req := httptest.NewRequest("POST", "/action", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleAction_BadJSON(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("POST", "/action", strings.NewReader("{bad"))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleAction_NoTab(t *testing.T) {
- b := newTestBridge()
- body := `{"kind": "click", "ref": "e0"}`
- req := httptest.NewRequest("POST", "/action", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleEvaluate_MissingExpression(t *testing.T) {
- b := newTestBridge()
- body := `{"expression": ""}`
- req := httptest.NewRequest("POST", "/evaluate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleEvaluate(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleEvaluate_BadJSON(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("POST", "/evaluate", strings.NewReader("{bad"))
- w := httptest.NewRecorder()
- b.handleEvaluate(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleEvaluate_NoTab(t *testing.T) {
- b := newTestBridge()
- body := `{"expression": "1+1"}`
- req := httptest.NewRequest("POST", "/evaluate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleEvaluate(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleTab_CloseNoTabID(t *testing.T) {
- b := newTestBridge()
- body := `{"action": "close"}`
- req := httptest.NewRequest("POST", "/tab", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_BadAction(t *testing.T) {
- b := newTestBridge()
- body := `{"action": "destroy"}`
- req := httptest.NewRequest("POST", "/tab", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_BadJSON(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("POST", "/tab", strings.NewReader("{bad"))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleSnapshot_NoTab(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/snapshot", nil)
- w := httptest.NewRecorder()
- b.handleSnapshot(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleText_NoTab(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/text", nil)
- w := httptest.NewRecorder()
- b.handleText(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleScreenshot_NoTab(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/screenshot", nil)
- w := httptest.NewRecorder()
- b.handleScreenshot(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleSetCookies_BadJSON(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("POST", "/cookies", strings.NewReader("{broken"))
- w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400 for bad JSON, got %d", w.Code)
- }
-}
-
-func TestHandleSetCookies_MissingURL(t *testing.T) {
- b := newTestBridge()
- body := `{"cookies": [{"name": "test", "value": "123"}]}`
- req := httptest.NewRequest("POST", "/cookies", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
-
- if w.Code != 400 {
- t.Errorf("expected 400 for missing URL, got %d", w.Code)
- }
-}
-
-func TestHandleHealth_NoBrowser(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/health", nil)
- w := httptest.NewRecorder()
- b.handleHealth(w, req)
-
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- body := w.Body.String()
- if !strings.Contains(body, "disconnected") {
- t.Errorf("expected 'disconnected' in body, got %s", body)
- }
-}
-
-func TestHandleTabs_NoBrowser(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/tabs", nil)
- w := httptest.NewRecorder()
- b.handleTabs(w, req)
-
- if w.Code != 500 {
- t.Errorf("expected 500, got %d", w.Code)
- }
-}
-
-func TestHandleScreenshot_QualityParam(t *testing.T) {
- b := newTestBridge()
-
- req := httptest.NewRequest("GET", "/screenshot?quality=50", nil)
- w := httptest.NewRecorder()
- b.handleScreenshot(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404 (no tab), got %d", w.Code)
- }
-}
-
-func TestHandleScreenshot_InvalidQuality(t *testing.T) {
- b := newTestBridge()
- req := httptest.NewRequest("GET", "/screenshot?quality=abc", nil)
- w := httptest.NewRecorder()
- b.handleScreenshot(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_InvalidURL(t *testing.T) {
- b := newTestBridge()
- body := `{"url": "not-a-url"}`
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404 (no tab), got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_WaitTitleClamp(t *testing.T) {
-
- b := newTestBridge()
- body := `{"url": "https://example.com", "waitTitle": 999}`
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 404 {
- t.Errorf("expected 404 (no tab), got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_NewTabNoChrome(t *testing.T) {
- b := newTestBridge()
- body := `{"url": "https://example.com", "newTab": true}`
- req := httptest.NewRequest("POST", "/navigate", strings.NewReader(body))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
-
- if w.Code != 500 {
- t.Errorf("expected 500 (no browser), got %d", w.Code)
- }
-}
-
-func TestGetSetDeleteRefCache(t *testing.T) {
- b := newTestBridge()
-
- if c := b.GetRefCache("tab1"); c != nil {
- t.Error("expected nil for unknown tab")
- }
-
- b.SetRefCache("tab1", &refCache{refs: map[string]int64{"e0": 42}})
- c := b.GetRefCache("tab1")
- if c == nil || c.refs["e0"] != 42 {
- t.Error("expected cached ref e0=42")
- }
-
- b.DeleteRefCache("tab1")
- if c := b.GetRefCache("tab1"); c != nil {
- t.Error("expected nil after delete")
- }
-}
diff --git a/handlers_extra_test.go b/handlers_extra_test.go
deleted file mode 100644
index 9366a654..00000000
--- a/handlers_extra_test.go
+++ /dev/null
@@ -1,235 +0,0 @@
-package main
-
-import (
- "bytes"
- "context"
- "net/http/httptest"
- "os"
- "path/filepath"
- "testing"
- "time"
-)
-
-func TestHandleHealth_Response(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- req := httptest.NewRequest("GET", "/health", nil)
- w := httptest.NewRecorder()
- b.handleHealth(w, req)
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- if ct := w.Header().Get("Content-Type"); ct != "application/json" {
- t.Errorf("expected application/json, got %s", ct)
- }
-}
-
-func TestHandleNavigate_InvalidJSON(t *testing.T) {
- b := &Bridge{}
- req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleEvaluate_InvalidJSON(t *testing.T) {
- b := &Bridge{}
- req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- b.handleEvaluate(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_InvalidJSON(t *testing.T) {
- b := &Bridge{}
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_InvalidAction(t *testing.T) {
- b := &Bridge{}
- body := `{"action":"invalid"}`
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleTab_CloseMissingID(t *testing.T) {
- b := &Bridge{}
- body := `{"action":"close"}`
- req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleTab(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
- if !searchString(w.Body.String(), "tabId required") {
- t.Errorf("expected tabId required error, got %s", w.Body.String())
- }
-}
-
-func TestHandleAction_InvalidJSON(t *testing.T) {
- b := &Bridge{}
- req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`not json`)))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
-}
-
-func TestHandleAction_RefNotCached(t *testing.T) {
- b := newBridgeWithFakeTab()
- body := `{"kind":"click","ref":"e99","tabId":"tab1"}`
- req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
- if !searchString(w.Body.String(), "not found") {
- t.Errorf("expected 'not found' error, got %s", w.Body.String())
- }
-}
-
-func TestHandleAction_MissingKindWithTab(t *testing.T) {
- b := newBridgeWithFakeTab()
- body := `{"selector":"#btn","tabId":"tab1"}`
- req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
- if !searchString(w.Body.String(), "kind") {
- t.Errorf("expected 'kind' in error, got %s", w.Body.String())
- }
-}
-
-func TestHandleAction_UnknownKindWithTab(t *testing.T) {
- b := newBridgeWithFakeTab()
- body := `{"kind":"explode","selector":"#btn","tabId":"tab1"}`
- req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleAction(w, req)
- if w.Code != 400 {
- t.Errorf("expected 400, got %d", w.Code)
- }
- if !searchString(w.Body.String(), "unknown action") {
- t.Errorf("expected 'unknown action' error, got %s", w.Body.String())
- }
-}
-
-func TestHandleShutdown_CallsFunc(t *testing.T) {
- called := make(chan bool, 1)
- doShutdown := func() { called <- true }
- b := &Bridge{}
- handler := b.handleShutdown(doShutdown)
- req := httptest.NewRequest("POST", "/shutdown", nil)
- w := httptest.NewRecorder()
- handler(w, req)
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- select {
- case <-called:
- case <-time.After(500 * time.Millisecond):
- t.Error("expected doShutdown to be called within 500ms")
- }
-}
-
-func TestLoadConfig_TimeoutFromFile(t *testing.T) {
- tmp := t.TempDir()
- cfgPath := filepath.Join(tmp, "config.json")
- _ = os.WriteFile(cfgPath, []byte(`{"timeout":"25s","navTimeout":"60s"}`), 0644)
-
- t.Setenv("BRIDGE_CONFIG", cfgPath)
- t.Setenv("BRIDGE_TIMEOUT", "")
- t.Setenv("BRIDGE_NAV_TIMEOUT", "")
-
- origAction := cfg.ActionTimeout
- origNav := cfg.NavigateTimeout
- defer func() {
- cfg.ActionTimeout = origAction
- cfg.NavigateTimeout = origNav
- }()
-
- loadConfig()
-
-}
-
-func TestLoadConfig_ConfigFileAllFields(t *testing.T) {
- tmp := t.TempDir()
- cfgPath := filepath.Join(tmp, "config.json")
- jsonData := `{
- "port": "9999",
- "headless": true,
- "token": "test-token",
- "noRestore": true,
- "timeoutSec": 20,
- "navigateSec": 45
- }`
- _ = os.WriteFile(cfgPath, []byte(jsonData), 0644)
-
- origPort := cfg.Port
- origNoRestore := cfg.NoRestore
- origToken := cfg.Token
- origAction := cfg.ActionTimeout
- origNav := cfg.NavigateTimeout
- defer func() {
- cfg.Port = origPort
- cfg.NoRestore = origNoRestore
- cfg.Token = origToken
- cfg.ActionTimeout = origAction
- cfg.NavigateTimeout = origNav
- }()
-
- t.Setenv("BRIDGE_CONFIG", cfgPath)
- t.Setenv("BRIDGE_PORT", "")
- t.Setenv("BRIDGE_TOKEN", "")
- t.Setenv("BRIDGE_NO_RESTORE", "")
- t.Setenv("BRIDGE_TIMEOUT", "")
- t.Setenv("BRIDGE_NAV_TIMEOUT", "")
- loadConfig()
-
- if cfg.Port != "9999" {
- t.Errorf("expected port 9999, got %q", cfg.Port)
- }
- if !cfg.NoRestore {
- t.Error("expected noRestore true from config")
- }
- if cfg.Token != "test-token" {
- t.Errorf("expected test-token, got %q", cfg.Token)
- }
- if cfg.ActionTimeout != 20*time.Second {
- t.Errorf("expected 20s timeout, got %v", cfg.ActionTimeout)
- }
- if cfg.NavigateTimeout != 45*time.Second {
- t.Errorf("expected 45s navTimeout, got %v", cfg.NavigateTimeout)
- }
-}
-
-// newBridgeWithFakeTab creates a Bridge with a real context.Context tab for testing
-// handler dispatch logic without needing Chrome.
-func newBridgeWithFakeTab() *Bridge {
- b := &Bridge{}
- b.TabManager = &TabManager{
- tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
- }
- ctx, cancel := context.WithCancel(context.Background())
- _ = cancel
- b.RegisterTab("tab1", ctx)
- return b
-}
diff --git a/human_test.go b/human_test.go
deleted file mode 100644
index f3a5a07a..00000000
--- a/human_test.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package main
-
-import (
- "math"
- "testing"
- "time"
-)
-
-func TestHumanMouseMove(t *testing.T) {
-
- testCases := []struct {
- name string
- fromX float64
- fromY float64
- toX float64
- toY float64
- maxSteps int
- }{
- {
- name: "short distance",
- fromX: 100,
- fromY: 100,
- toX: 150,
- toY: 150,
- maxSteps: 30,
- },
- {
- name: "long distance",
- fromX: 0,
- fromY: 0,
- toX: 1000,
- toY: 1000,
- maxSteps: 30,
- },
- {
- name: "tiny distance",
- fromX: 100,
- fromY: 100,
- toX: 105,
- toY: 105,
- maxSteps: 5,
- },
- }
-
- for _, tc := range testCases {
- t.Run(tc.name, func(t *testing.T) {
-
- distance := math.Sqrt((tc.toX-tc.fromX)*(tc.toX-tc.fromX) + (tc.toY-tc.fromY)*(tc.toY-tc.fromY))
-
- baseDuration := 100 + (distance/2000)*200
- if baseDuration < 100 {
- t.Error("base duration too low")
- }
-
- steps := int(baseDuration / 20)
- if steps < 5 {
- steps = 5
- }
- if steps > 30 {
- steps = 30
- }
-
- if steps > tc.maxSteps {
- t.Errorf("too many steps: %d > %d", steps, tc.maxSteps)
- }
- })
- }
-}
-
-func TestTypingTiming(t *testing.T) {
-
- startTime := time.Now()
-
- baseDelay := 50
- variations := []int{0, 20, 50, 100, 150}
-
- totalDelay := 0
- for i := 0; i < 10; i++ {
- delay := baseDelay + variations[i%len(variations)]
- totalDelay += delay
- }
-
- avgDelay := totalDelay / 10
- if avgDelay < 30 || avgDelay > 200 {
- t.Errorf("average typing delay out of range: %dms", avgDelay)
- }
-
- elapsed := time.Since(startTime)
- if elapsed > 1*time.Second {
- t.Error("test took too long, might indicate performance issue")
- }
-}
-
-func TestHumanClickDistance(t *testing.T) {
- tests := []struct {
- name string
- x, y float64
- startOffsetX float64
- startOffsetY float64
- shouldMove bool
- }{
- {
- name: "far distance",
- x: 500,
- y: 500,
- startOffsetX: 100,
- startOffsetY: 100,
- shouldMove: true,
- },
- {
- name: "close distance",
- x: 500,
- y: 500,
- startOffsetX: 10,
- startOffsetY: 10,
- shouldMove: false,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- distance := math.Sqrt(tt.startOffsetX*tt.startOffsetX + tt.startOffsetY*tt.startOffsetY)
- shouldMove := distance > 30
-
- if shouldMove != tt.shouldMove {
- t.Errorf("movement decision wrong: got %v, want %v (distance: %f)",
- shouldMove, tt.shouldMove, distance)
- }
- })
- }
-}
diff --git a/integration_test.go b/integration_test.go
deleted file mode 100644
index 578be969..00000000
--- a/integration_test.go
+++ /dev/null
@@ -1,356 +0,0 @@
-// TestCDPTimezoneOverride verifies that Emulation.
-// TestStealthStatusEndpoint verifies the /stealth/status handler returns valid data with a live browser.
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "io"
- "math/rand"
- "net/http"
- "net/http/httptest"
- "os"
- "strings"
- "testing"
- "time"
-
- "github.com/chromedp/cdproto/emulation"
- "github.com/chromedp/cdproto/page"
- "github.com/chromedp/chromedp"
-)
-
-func skipIfNoChrome(t *testing.T) {
- t.Helper()
- if os.Getenv("CI") != "" {
- t.Skip("skipping integration test in CI (no Chrome)")
- }
-}
-
-func testBridge(t *testing.T) (*Bridge, func()) {
- t.Helper()
- skipIfNoChrome(t)
-
- opts := append(chromedp.DefaultExecAllocatorOptions[:],
- chromedp.Headless,
- chromedp.NoFirstRun,
- chromedp.NoDefaultBrowserCheck,
- chromedp.Flag("disable-gpu", true),
- )
-
- allocCtx, allocCancel := chromedp.NewExecAllocator(context.Background(), opts...)
- browserCtx, browserCancel := chromedp.NewContext(allocCtx)
-
- seed := rand.Intn(1000000000)
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", seed, "full") + stealthScript
- if err := chromedp.Run(browserCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(seededScript).Do(ctx)
- return err
- }),
- ); err != nil {
- allocCancel()
- t.Fatalf("failed to start Chrome: %v", err)
- }
-
- b := &Bridge{
- allocCtx: allocCtx,
- browserCtx: browserCtx,
- }
- b.InitTabManager()
-
- initID := string(chromedp.FromContext(browserCtx).Target.TargetID)
- b.RegisterTab(initID, browserCtx)
-
- return b, func() {
- browserCancel()
- allocCancel()
- }
-}
-
-func navigateAndWait(t *testing.T, b *Bridge, dataURL string) {
- t.Helper()
- ctx, _, err := b.TabContext("")
- if err != nil {
- t.Fatalf("TabContext: %v", err)
- }
- tCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
- defer cancel()
- if err := chromedp.Run(tCtx, chromedp.Navigate(dataURL)); err != nil {
- t.Fatalf("navigate: %v", err)
- }
-}
-
-func TestStealthScriptInjected(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<h1>stealth test</h1>")
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- var result string
- if err := chromedp.Run(tCtx, chromedp.Evaluate(`String(navigator.webdriver)`, &result)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
- if result == "true" {
- t.Error("navigator.webdriver should not be true (stealth script not working)")
- }
-
- if result != "undefined" && result != "false" {
- t.Errorf("navigator.webdriver = %q, want 'undefined' or 'false'", result)
- }
-}
-
-func TestCanvasNoiseApplied(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- html := `data:text/html,<canvas id="c" width="200" height="50"></canvas>
-<script>
-var c = document.getElementById('c');
-var ctx = c.getContext('2d');
-ctx.fillStyle = 'red';
-ctx.fillRect(0,0,200,50);
-ctx.fillStyle = 'blue';
-ctx.font = '18px Arial';
-ctx.fillText('canvas fingerprint', 10, 30);
-</script>`
- navigateAndWait(t, b, html)
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- var result1, result2 string
- script := `
-(function() {
- var c = document.getElementById('c');
- return c.toDataURL();
-})()
-`
- if err := chromedp.Run(tCtx,
- chromedp.Evaluate(script, &result1),
- chromedp.Evaluate(script, &result2),
- ); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
-
- if result1 == result2 {
- t.Error("toDataURL returned identical results — canvas noise not applied")
- }
-}
-
-func TestFontMetricsNoise(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<canvas id='c'></canvas>")
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- script := `
-(function() {
- var c = document.getElementById('c').getContext('2d');
- c.font = '16px Arial';
- var widths = [];
- for (var i = 0; i < 10; i++) {
- widths.push(c.measureText('Hello World').width);
- }
- // Check if Proxy-wrapped (instanceof TextMetrics)
- var tm = c.measureText('test');
- return {
- widths: widths,
- isTextMetrics: tm instanceof TextMetrics
- };
-})()
-`
- var result struct {
- Widths []float64 `json:"widths"`
- IsTextMetrics bool `json:"isTextMetrics"`
- }
- if err := chromedp.Run(tCtx, chromedp.Evaluate(script, &result)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
-
- if !result.IsTextMetrics {
- t.Error("measureText result should be instanceof TextMetrics (Proxy not working)")
- }
-
- if len(result.Widths) == 0 {
- t.Fatal("no width measurements returned")
- }
- if result.Widths[0] <= 0 {
- t.Errorf("measureText width = %f, expected positive number", result.Widths[0])
- }
-}
-
-func TestWebGLVendorSpoofed(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<canvas id='gl'></canvas>")
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- script := `
-(function() {
- var canvas = document.getElementById('gl');
- var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
- if (!gl) return {available: false, vendor: '', renderer: ''};
- var ext = gl.getExtension('WEBGL_debug_renderer_info');
- if (!ext) return {available: true, vendor: 'no-ext', renderer: 'no-ext'};
- return {
- available: true,
- vendor: gl.getParameter(ext.UNMASKED_VENDOR_WEBGL),
- renderer: gl.getParameter(ext.UNMASKED_RENDERER_WEBGL)
- };
-})()
-`
- var result struct {
- Available bool `json:"available"`
- Vendor string `json:"vendor"`
- Renderer string `json:"renderer"`
- }
- if err := chromedp.Run(tCtx, chromedp.Evaluate(script, &result)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
-
- if !result.Available {
- t.Skip("WebGL not available in cfg.Headless mode — skipping vendor check")
- }
-
- if result.Vendor != "Intel Inc." {
- t.Errorf("WebGL vendor = %q, want %q", result.Vendor, "Intel Inc.")
- }
-}
-
-func TestPluginsPresent(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<h1>plugins</h1>")
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- var count int
- if err := chromedp.Run(tCtx, chromedp.Evaluate(`navigator.plugins.length`, &count)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
-
- if count < 3 {
- t.Errorf("navigator.plugins.length = %d, want >= 3", count)
- }
-}
-
-func TestFingerprintRotation(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<h1>rotate</h1>")
-
- body := `{"os":"windows","browser":"edge","screen":"1920x1080"}`
- req := httptest.NewRequest("POST", "/fingerprint/rotate", strings.NewReader(body))
- req.Header.Set("Content-Type", "application/json")
- w := httptest.NewRecorder()
- b.handleFingerprintRotate(w, req)
-
- resp := w.Result()
- if resp.StatusCode != 200 {
- respBody, _ := io.ReadAll(resp.Body)
- t.Fatalf("fingerprint/rotate returned %d: %s", resp.StatusCode, respBody)
- }
-
- var rotateResp map[string]any
- _ = json.NewDecoder(resp.Body).Decode(&rotateResp)
-
- fp, ok := rotateResp["fingerprint"].(map[string]any)
- if !ok {
- t.Fatal("response missing fingerprint object")
- }
- newUA, _ := fp["userAgent"].(string)
- if !strings.Contains(newUA, "Edg/") {
- t.Errorf("expected Edge UA in fingerprint, got: %s", newUA)
- }
-
- ctx2, _, _ := b.TabContext("")
- tCtx2, cancel2 := context.WithTimeout(ctx2, 5*time.Second)
- defer cancel2()
-
- var uaAfter string
- if err := chromedp.Run(tCtx2, chromedp.Evaluate(`navigator.userAgent`, &uaAfter)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
- if !strings.Contains(uaAfter, "Edg/") {
- t.Errorf("browser UA after rotation = %q, expected Edge UA", uaAfter)
- }
-}
-
-func TestCDPTimezoneOverride(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- ctx, _, _ := b.TabContext("")
- tCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
- defer cancel()
-
- if err := chromedp.Run(tCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return emulation.SetTimezoneOverride("Pacific/Auckland").Do(ctx)
- }),
- ); err != nil {
- t.Fatalf("setTimezoneOverride: %v", err)
- }
-
- navigateAndWait(t, b, "data:text/html,<h1>tz</h1>")
-
- ctx2, _, _ := b.TabContext("")
- tCtx2, cancel2 := context.WithTimeout(ctx2, 5*time.Second)
- defer cancel2()
-
- var tz string
- if err := chromedp.Run(tCtx2, chromedp.Evaluate(`Intl.DateTimeFormat().resolvedOptions().timeZone`, &tz)); err != nil {
- t.Fatalf("evaluate: %v", err)
- }
-
- if tz != "Pacific/Auckland" {
- t.Errorf("timezone = %q, want Pacific/Auckland", tz)
- }
-}
-
-func TestStealthStatusEndpoint(t *testing.T) {
- b, cleanup := testBridge(t)
- defer cleanup()
-
- navigateAndWait(t, b, "data:text/html,<h1>status</h1>")
-
- req := httptest.NewRequest("GET", "/stealth/status", nil)
- w := httptest.NewRecorder()
- b.handleStealthStatus(w, req)
-
- resp := w.Result()
- if resp.StatusCode != http.StatusOK {
- t.Fatalf("stealth/status returned %d", resp.StatusCode)
- }
-
- var result map[string]any
- _ = json.NewDecoder(resp.Body).Decode(&result)
-
- score, _ := result["score"].(float64)
- if score < 50 {
- t.Errorf("stealth score = %.0f, expected >= 50", score)
- }
-
- level, _ := result["level"].(string)
- if level != "high" && level != "medium" {
- t.Errorf("stealth level = %q, expected high or medium", level)
- }
-}
diff --git a/interfaces.go b/interfaces.go
deleted file mode 100644
index 053c8a14..00000000
--- a/interfaces.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package main
-
-import (
- "context"
- "net/http"
-
- "github.com/chromedp/cdproto/target"
-)
-
-// Compile-time interface satisfaction checks.
-var (
- _ ProfileService = (*ProfileManager)(nil)
- _ OrchestratorService = (*Orchestrator)(nil)
-)
-
-// BridgeAPI abstracts browser tab operations for handler testing.
-type BridgeAPI interface {
- TabContext(tabID string) (ctx context.Context, resolvedID string, err error)
- ListTargets() ([]*target.Info, error)
- CreateTab(url string) (tabID string, ctx context.Context, cancel context.CancelFunc, err error)
- CloseTab(tabID string) error
-
- GetRefCache(tabID string) *refCache
- SetRefCache(tabID string, cache *refCache)
- DeleteRefCache(tabID string)
-}
-
-// TabInfo describes a browser tab.
-type TabInfo struct {
- ID string `json:"id"`
- URL string `json:"url"`
- Title string `json:"title"`
- Type string `json:"type"`
-}
-
-// ProfileService abstracts profile management operations.
-type ProfileService interface {
- RegisterHandlers(mux *http.ServeMux)
- List() ([]ProfileInfo, error)
- Create(name string) error
- Import(name, sourcePath string) error
- Reset(name string) error
- Delete(name string) error
- Logs(name string, limit int) []ActionRecord
- Analytics(name string) AnalyticsReport
- RecordAction(profile string, record ActionRecord)
-}
-
-// OrchestratorService abstracts instance orchestration operations.
-type OrchestratorService interface {
- RegisterHandlers(mux *http.ServeMux)
- Launch(name, port string, headless bool) (*Instance, error)
- Stop(id string) error
- StopProfile(name string) error
- List() []Instance
- Logs(id string) (string, error)
- FirstRunningURL() string
- AllTabs() []instanceTab
- ScreencastURL(instanceID, tabID string) string
- Shutdown()
- ForceShutdown()
-}
diff --git a/internal/assets/assets.go b/internal/assets/assets.go
new file mode 100644
index 00000000..042ddbe5
--- /dev/null
+++ b/internal/assets/assets.go
@@ -0,0 +1,14 @@
+package assets
+
+import (
+ _ "embed"
+)
+
+//go:embed stealth.js
+var StealthScript string
+
+//go:embed readability.js
+var ReadabilityJS string
+
+//go:embed welcome.html
+var WelcomeHTML string
diff --git a/readability.js b/internal/assets/readability.js
similarity index 100%
rename from readability.js
rename to internal/assets/readability.js
diff --git a/stealth.js b/internal/assets/stealth.js
similarity index 100%
rename from stealth.js
rename to internal/assets/stealth.js
diff --git a/welcome.html b/internal/assets/welcome.html
similarity index 100%
rename from welcome.html
rename to internal/assets/welcome.html
diff --git a/internal/bridge/actions.go b/internal/bridge/actions.go
new file mode 100644
index 00000000..673d8d0a
--- /dev/null
+++ b/internal/bridge/actions.go
@@ -0,0 +1,180 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/chromedp/cdproto/cdp"
+ "github.com/chromedp/cdproto/dom"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/human"
+)
+
+const (
+ ActionClick = "click"
+ ActionType = "type"
+ ActionFill = "fill"
+ ActionPress = "press"
+ ActionFocus = "focus"
+ ActionHover = "hover"
+ ActionSelect = "select"
+ ActionScroll = "scroll"
+ ActionHumanClick = "humanClick"
+ ActionHumanType = "humanType"
+)
+
+func (b *Bridge) InitActionRegistry() {
+ b.Actions = map[string]ActionFunc{
+ ActionClick: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ var err error
+ if req.Selector != "" {
+ err = chromedp.Run(ctx, chromedp.Click(req.Selector, chromedp.ByQuery))
+ } else if req.NodeID > 0 {
+ err = ClickByNodeID(ctx, req.NodeID)
+ } else {
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+ }
+ if err != nil {
+ return nil, err
+ }
+ if req.WaitNav {
+ _ = chromedp.Run(ctx, chromedp.Sleep(b.Config.WaitNavDelay))
+ }
+ return map[string]any{"clicked": true}, nil
+ },
+ ActionType: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for type")
+ }
+ if req.Selector != "" {
+ return map[string]any{"typed": req.Text}, chromedp.Run(ctx,
+ chromedp.Click(req.Selector, chromedp.ByQuery),
+ chromedp.SendKeys(req.Selector, req.Text, chromedp.ByQuery),
+ )
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"typed": req.Text}, TypeByNodeID(ctx, req.NodeID, req.Text)
+ }
+ return nil, fmt.Errorf("need selector or ref")
+ },
+ ActionFill: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Selector != "" {
+ return map[string]any{"filled": req.Text}, chromedp.Run(ctx, chromedp.SetValue(req.Selector, req.Text, chromedp.ByQuery))
+ }
+ return map[string]any{"filled": req.Text}, nil
+ },
+ ActionPress: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Key == "" {
+ return nil, fmt.Errorf("key required for press")
+ }
+ return map[string]any{"pressed": req.Key}, chromedp.Run(ctx, chromedp.KeyEvent(req.Key))
+ },
+ ActionFocus: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Selector != "" {
+ return map[string]any{"focused": true}, chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery))
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"focused": true}, chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ p := map[string]any{"backendNodeId": req.NodeID}
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", p, nil)
+ }),
+ )
+ }
+ return map[string]any{"focused": true}, nil
+ },
+ ActionHover: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ return map[string]any{"hovered": true}, HoverByNodeID(ctx, req.NodeID)
+ }
+ if req.Selector != "" {
+ return map[string]any{"hovered": true}, chromedp.Run(ctx,
+ chromedp.Evaluate(fmt.Sprintf(`document.querySelector(%q)?.dispatchEvent(new MouseEvent('mouseover', {bubbles:true}))`, req.Selector), nil),
+ )
+ }
+ return nil, fmt.Errorf("need selector or ref")
+ },
+ ActionSelect: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ val := req.Value
+ if val == "" {
+ val = req.Text
+ }
+ if val == "" {
+ return nil, fmt.Errorf("value required for select")
+ }
+ if req.NodeID > 0 {
+ return map[string]any{"selected": val}, SelectByNodeID(ctx, req.NodeID, val)
+ }
+ if req.Selector != "" {
+ return map[string]any{"selected": val}, chromedp.Run(ctx,
+ chromedp.SetValue(req.Selector, val, chromedp.ByQuery),
+ )
+ }
+ return nil, fmt.Errorf("need selector or ref")
+ },
+ ActionScroll: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ return map[string]any{"scrolled": true}, ScrollByNodeID(ctx, req.NodeID)
+ }
+ if req.ScrollX != 0 || req.ScrollY != 0 {
+ js := fmt.Sprintf("window.scrollBy(%d, %d)", req.ScrollX, req.ScrollY)
+ return map[string]any{"scrolled": true, "x": req.ScrollX, "y": req.ScrollY},
+ chromedp.Run(ctx, chromedp.Evaluate(js, nil))
+ }
+ return map[string]any{"scrolled": true, "y": 800},
+ chromedp.Run(ctx, chromedp.Evaluate("window.scrollBy(0, 800)", nil))
+ },
+ ActionHumanClick: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.NodeID > 0 {
+ if err := human.ClickElement(ctx, cdp.NodeID(req.NodeID)); err != nil {
+ return nil, err
+ }
+ return map[string]any{"clicked": true, "human": true}, nil
+ }
+ if req.Selector != "" {
+ var nodes []*cdp.Node
+ if err := chromedp.Run(ctx,
+ chromedp.Nodes(req.Selector, &nodes, chromedp.ByQuery),
+ ); err != nil {
+ return nil, err
+ }
+ if len(nodes) == 0 {
+ return nil, fmt.Errorf("element not found: %s", req.Selector)
+ }
+ if err := human.ClickElement(ctx, nodes[0].NodeID); err != nil {
+ return nil, err
+ }
+ return map[string]any{"clicked": true, "human": true}, nil
+ }
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+ },
+ ActionHumanType: func(ctx context.Context, req ActionRequest) (map[string]any, error) {
+ if req.Text == "" {
+ return nil, fmt.Errorf("text required for humanType")
+ }
+
+ if req.Selector != "" {
+ if err := chromedp.Run(ctx, chromedp.Focus(req.Selector, chromedp.ByQuery)); err != nil {
+ return nil, err
+ }
+ } else if req.NodeID > 0 {
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return dom.Focus().WithNodeID(cdp.NodeID(req.NodeID)).Do(ctx)
+ }),
+ ); err != nil {
+ return nil, err
+ }
+ } else {
+ return nil, fmt.Errorf("need selector, ref, or nodeId")
+ }
+
+ actions := human.Type(req.Text, req.Fast)
+ if err := chromedp.Run(ctx, actions...); err != nil {
+ return nil, err
+ }
+
+ return map[string]any{"typed": req.Text, "human": true}, nil
+ },
+ }
+}
diff --git a/animations.go b/internal/bridge/animations.go
similarity index 73%
rename from animations.go
rename to internal/bridge/animations.go
index a6391a21..e2876269 100644
--- a/animations.go
+++ b/internal/bridge/animations.go
@@ -1,4 +1,4 @@
-package main
+package bridge
import (
"context"
@@ -8,8 +8,8 @@ import (
"github.com/chromedp/chromedp"
)
-// disableAnimationsCSS is injected to force-disable all CSS animations and transitions.
-const disableAnimationsCSS = `
+// DisableAnimationsCSS is injected to force-disable all CSS animations and transitions.
+const DisableAnimationsCSS = `
(function() {
const style = document.createElement('style');
style.setAttribute('data-pinchtab', 'no-animations');
@@ -18,12 +18,12 @@ const disableAnimationsCSS = `
})();
`
-// injectNoAnimations adds a persistent script (via CDP) that disables CSS
+// InjectNoAnimations adds a persistent script (via CDP) that disables CSS
// animations on every document load. Used when BRIDGE_NO_ANIMATIONS=true.
-func (b *Bridge) injectNoAnimations(ctx context.Context) {
+func (b *Bridge) InjectNoAnimations(ctx context.Context) {
_ = chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(disableAnimationsCSS).Do(ctx)
+ _, err := page.AddScriptToEvaluateOnNewDocument(DisableAnimationsCSS).Do(ctx)
return err
}),
chromedp.ActionFunc(func(ctx context.Context) error {
@@ -35,11 +35,11 @@ func (b *Bridge) injectNoAnimations(ctx context.Context) {
)
}
-// disableAnimationsOnce runs the animation-disabling CSS on the current page
+// DisableAnimationsOnce runs the animation-disabling CSS on the current page
// (one-shot, for per-request ?noAnimations=true).
-func disableAnimationsOnce(ctx context.Context) {
+func DisableAnimationsOnce(ctx context.Context) {
_ = chromedp.Run(ctx,
- chromedp.Evaluate(disableAnimationsCSS, nil),
+ chromedp.Evaluate(DisableAnimationsCSS, nil),
chromedp.ActionFunc(func(ctx context.Context) error {
return emulation.SetEmulatedMedia().
WithFeatures([]*emulation.MediaFeature{
diff --git a/internal/bridge/animations_test.go b/internal/bridge/animations_test.go
new file mode 100644
index 00000000..d34ebb23
--- /dev/null
+++ b/internal/bridge/animations_test.go
@@ -0,0 +1,28 @@
+package bridge
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestDisableAnimationsCSS(t *testing.T) {
+ if !strings.Contains(DisableAnimationsCSS, "animation: none !important") {
+ t.Error("CSS missing animation: none")
+ }
+ if !strings.Contains(DisableAnimationsCSS, "transition: none !important") {
+ t.Error("CSS missing transition: none")
+ }
+ if !strings.Contains(DisableAnimationsCSS, "scroll-behavior: auto !important") {
+ t.Error("CSS missing scroll-behavior: auto")
+ }
+}
+
+func TestInjectNoAnimations(t *testing.T) {
+ cfg := &config.RuntimeConfig{NoAnimations: true}
+ b := &Bridge{Config: cfg}
+ if b.Config.NoAnimations != true {
+ t.Error("Expected NoAnimations to be true")
+ }
+}
diff --git a/internal/bridge/api.go b/internal/bridge/api.go
new file mode 100644
index 00000000..edeac44e
--- /dev/null
+++ b/internal/bridge/api.go
@@ -0,0 +1,116 @@
+package bridge
+
+import (
+ "context"
+ "net/http"
+ "time"
+
+ "github.com/chromedp/cdproto/target"
+)
+
+// BridgeAPI abstracts browser tab operations for handler testing.
+type BridgeAPI interface {
+ BrowserContext() context.Context
+ TabContext(tabID string) (ctx context.Context, resolvedID string, err error)
+ ListTargets() ([]*target.Info, error)
+ CreateTab(url string) (tabID string, ctx context.Context, cancel context.CancelFunc, err error)
+ CloseTab(tabID string) error
+
+ GetRefCache(tabID string) *RefCache
+ SetRefCache(tabID string, cache *RefCache)
+ DeleteRefCache(tabID string)
+
+ ExecuteAction(ctx context.Context, kind string, req ActionRequest) (map[string]any, error)
+ AvailableActions() []string
+
+ TabLockInfo(tabID string) *LockInfo
+ Lock(tabID, owner string, ttl time.Duration) error
+ Unlock(tabID, owner string) error
+}
+
+type LockInfo struct {
+ Owner string
+ ExpiresAt time.Time
+}
+
+// ProfileService abstracts profile management operations.
+type ProfileService interface {
+ RegisterHandlers(mux *http.ServeMux)
+ List() ([]ProfileInfo, error)
+ Create(name string) error
+ Import(name, sourcePath string) error
+ Reset(name string) error
+ Delete(name string) error
+ Logs(name string, limit int) []ActionRecord
+ Analytics(name string) AnalyticsReport
+ RecordAction(profile string, record ActionRecord)
+}
+
+// OrchestratorService abstracts instance orchestration operations.
+type OrchestratorService interface {
+ RegisterHandlers(mux *http.ServeMux)
+ Launch(name, port string, headless bool) (*Instance, error)
+ Stop(id string) error
+ StopProfile(name string) error
+ List() []Instance
+ Logs(id string) (string, error)
+ FirstRunningURL() string
+ AllTabs() []InstanceTab
+ ScreencastURL(instanceID, tabID string) string
+ Shutdown()
+ ForceShutdown()
+}
+
+// Common types used across packages (migrated from main)
+
+type ProfileInfo struct {
+ ID string `json:"id,omitempty"`
+ Name string `json:"name"`
+ Created time.Time `json:"created"`
+ LastUsed time.Time `json:"lastUsed"`
+ DiskUsage int64 `json:"diskUsage"`
+ Running bool `json:"running"`
+ Source string `json:"source,omitempty"`
+ ChromeProfileName string `json:"chromeProfileName,omitempty"`
+ AccountEmail string `json:"accountEmail,omitempty"`
+ AccountName string `json:"accountName,omitempty"`
+ HasAccount bool `json:"hasAccount,omitempty"`
+ UseWhen string `json:"useWhen,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
+type ActionRecord struct {
+ Timestamp time.Time `json:"timestamp"`
+ Method string `json:"method"`
+ Endpoint string `json:"endpoint"`
+ URL string `json:"url"`
+ TabID string `json:"tabId"`
+ DurationMs int64 `json:"durationMs"`
+ Status int `json:"status"`
+}
+
+type AnalyticsReport struct {
+ TotalActions int `json:"totalActions"`
+ Last24h int `json:"last24h"`
+ CommonHosts map[string]int `json:"commonHosts"`
+ TopEndpoints map[string]int `json:"topEndpoints,omitempty"`
+ RepeatPatterns []string `json:"repeatPatterns,omitempty"`
+ Suggestions []string `json:"suggestions,omitempty"`
+}
+
+type Instance struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Profile string `json:"profile"`
+ Port string `json:"port"`
+ Headless bool `json:"headless"`
+ Status string `json:"status"`
+ StartTime time.Time `json:"startTime"`
+}
+
+type InstanceTab struct {
+ InstanceID string `json:"instanceId"`
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ Title string `json:"title"`
+}
diff --git a/internal/bridge/bridge.go b/internal/bridge/bridge.go
new file mode 100644
index 00000000..2e68a176
--- /dev/null
+++ b/internal/bridge/bridge.go
@@ -0,0 +1,117 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "time"
+
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type TabEntry struct {
+ Ctx context.Context
+ Cancel context.CancelFunc
+}
+
+type RefCache struct {
+ Refs map[string]int64
+ Nodes []A11yNode
+}
+
+type Bridge struct {
+ AllocCtx context.Context
+ BrowserCtx context.Context
+ Config *config.RuntimeConfig
+ *TabManager
+ StealthScript string
+ Actions map[string]ActionFunc
+ Locks *LockManager
+}
+
+func New(allocCtx, browserCtx context.Context, cfg *config.RuntimeConfig) *Bridge {
+ b := &Bridge{
+ AllocCtx: allocCtx,
+ BrowserCtx: browserCtx,
+ Config: cfg,
+ }
+ if cfg != nil {
+ b.TabManager = NewTabManager(browserCtx, cfg, b.tabSetup)
+ }
+ b.Locks = NewLockManager()
+ return b
+}
+
+func (b *Bridge) injectStealth(ctx context.Context) {
+ if b.StealthScript == "" {
+ return
+ }
+ if err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ _, err := page.AddScriptToEvaluateOnNewDocument(b.StealthScript).Do(ctx)
+ return err
+ }),
+ ); err != nil {
+ slog.Warn("stealth injection failed", "err", err)
+ }
+}
+
+func (b *Bridge) tabSetup(ctx context.Context) {
+ b.injectStealth(ctx)
+ if b.Config.NoAnimations {
+ b.InjectNoAnimations(ctx)
+ }
+}
+
+func (b *Bridge) Lock(tabID, owner string, ttl time.Duration) error {
+ return b.Locks.TryLock(tabID, owner, ttl)
+}
+
+func (b *Bridge) Unlock(tabID, owner string) error {
+ return b.Locks.Unlock(tabID, owner)
+}
+
+func (b *Bridge) TabLockInfo(tabID string) *LockInfo {
+ return b.Locks.Get(tabID)
+}
+
+func (b *Bridge) BrowserContext() context.Context {
+ return b.BrowserCtx
+}
+
+func (b *Bridge) ExecuteAction(ctx context.Context, kind string, req ActionRequest) (map[string]any, error) {
+ fn, ok := b.Actions[kind]
+ if !ok {
+ return nil, fmt.Errorf("unknown action: %s", kind)
+ }
+ return fn(ctx, req)
+}
+
+func (b *Bridge) AvailableActions() []string {
+ keys := make([]string, 0, len(b.Actions))
+ for k := range b.Actions {
+ keys = append(keys, k)
+ }
+ return keys
+}
+
+// ActionFunc is the type for action handlers.
+type ActionFunc func(ctx context.Context, req ActionRequest) (map[string]any, error)
+
+// ActionRequest defines the parameters for a browser action.
+type ActionRequest struct {
+ TabID string `json:"tabId"`
+ Kind string `json:"kind"`
+ Ref string `json:"ref"`
+ Selector string `json:"selector"`
+ Text string `json:"text"`
+ Key string `json:"key"`
+ Value string `json:"value"`
+ NodeID int64 `json:"nodeId"`
+ ScrollX int `json:"scrollX"`
+ ScrollY int `json:"scrollY"`
+ WaitNav bool `json:"waitNav"`
+ Fast bool `json:"fast"`
+}
diff --git a/bridge_test.go b/internal/bridge/bridge_test.go
similarity index 51%
rename from bridge_test.go
rename to internal/bridge/bridge_test.go
index 734840bb..ec26e677 100644
--- a/bridge_test.go
+++ b/internal/bridge/bridge_test.go
@@ -1,12 +1,22 @@
-package main
+package bridge
import (
"sync"
"testing"
)
+func newTestBridge() *Bridge {
+ b := &Bridge{
+ TabManager: &TabManager{
+ tabs: make(map[string]*TabEntry),
+ snapshots: make(map[string]*RefCache),
+ },
+ }
+ return b
+}
+
func TestRefCacheConcurrency(t *testing.T) {
- b := newTestBridgeWithTabs()
+ b := newTestBridge()
// Simulate concurrent reads/writes to snapshot cache
var wg sync.WaitGroup
@@ -16,15 +26,11 @@ func TestRefCacheConcurrency(t *testing.T) {
defer wg.Done()
tabID := "tab1"
- b.mu.Lock()
- b.snapshots[tabID] = &refCache{refs: map[string]int64{
+ b.SetRefCache(tabID, &RefCache{Refs: map[string]int64{
"e0": int64(i),
- }}
- b.mu.Unlock()
+ }})
- b.mu.RLock()
- cache := b.snapshots[tabID]
- b.mu.RUnlock()
+ cache := b.GetRefCache(tabID)
if cache == nil {
t.Error("cache should not be nil")
}
@@ -34,33 +40,27 @@ func TestRefCacheConcurrency(t *testing.T) {
}
func TestRefCacheLookup(t *testing.T) {
- b := newTestBridgeWithTabs()
+ b := newTestBridge()
- b.mu.RLock()
- cache := b.snapshots["tab1"]
- b.mu.RUnlock()
+ cache := b.GetRefCache("tab1")
if cache != nil {
t.Error("expected nil cache for unknown tab")
}
- b.mu.Lock()
- b.snapshots["tab1"] = &refCache{refs: map[string]int64{
+ b.SetRefCache("tab1", &RefCache{Refs: map[string]int64{
"e0": 100,
"e1": 200,
- }}
- b.mu.Unlock()
+ }})
- b.mu.RLock()
- cache = b.snapshots["tab1"]
- b.mu.RUnlock()
+ cache = b.GetRefCache("tab1")
- if nid, ok := cache.refs["e0"]; !ok || nid != 100 {
+ if nid, ok := cache.Refs["e0"]; !ok || nid != 100 {
t.Errorf("e0 expected 100, got %d", nid)
}
- if nid, ok := cache.refs["e1"]; !ok || nid != 200 {
+ if nid, ok := cache.Refs["e1"]; !ok || nid != 200 {
t.Errorf("e1 expected 200, got %d", nid)
}
- if _, ok := cache.refs["e99"]; ok {
+ if _, ok := cache.Refs["e99"]; ok {
t.Error("e99 should not exist")
}
}
diff --git a/internal/bridge/cdp.go b/internal/bridge/cdp.go
new file mode 100644
index 00000000..856b871d
--- /dev/null
+++ b/internal/bridge/cdp.go
@@ -0,0 +1,151 @@
+package bridge
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/chromedp/cdproto/network"
+ "github.com/chromedp/cdproto/page"
+ "github.com/chromedp/chromedp"
+)
+
+const TargetTypePage = "page"
+
+// NavigatePage uses raw CDP Page.navigate + polls document.readyState for completion.
+func NavigatePage(ctx context.Context, url string) error {
+ err := chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ _, _, _, _, err := page.Navigate(url).Do(ctx)
+ return err
+ }),
+ )
+ if err != nil {
+ return err
+ }
+
+ timeout := time.After(30 * time.Second)
+ ticker := time.NewTicker(200 * time.Millisecond)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-timeout:
+ return fmt.Errorf("navigation timeout")
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-ticker.C:
+ var state string
+ err = chromedp.Run(ctx,
+ chromedp.Evaluate("document.readyState", &state),
+ )
+ if err == nil && (state == "interactive" || state == "complete") {
+ return nil
+ }
+ }
+ }
+}
+
+var ImageBlockPatterns = []string{
+ "*.png", "*.jpg", "*.jpeg", "*.gif", "*.webp", "*.svg", "*.ico",
+}
+
+var MediaBlockPatterns = append(ImageBlockPatterns,
+ "*.mp4", "*.webm", "*.ogg", "*.mp3", "*.wav", "*.flac", "*.aac",
+)
+
+// SetResourceBlocking uses Network.setBlockedURLs to block resources by URL pattern.
+func SetResourceBlocking(ctx context.Context, patterns []string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ if len(patterns) == 0 {
+ return network.SetBlockedURLs([]string{}).Do(ctx)
+ }
+ return network.SetBlockedURLs(patterns).Do(ctx)
+ }),
+ )
+}
+
+func ClickByNodeID(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mousePressed",
+ "button": "left",
+ "clickCount": 1,
+ "x": 0, "y": 0,
+ }, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseReleased",
+ "button": "left",
+ "clickCount": 1,
+ "x": 0, "y": 0,
+ }, nil)
+ }),
+ )
+}
+
+func TypeByNodeID(ctx context.Context, nodeID int64, text string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.KeyEvent(text),
+ )
+}
+
+func HoverByNodeID(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.dispatchMouseEvent", map[string]any{
+ "type": "mouseMoved",
+ "x": 0, "y": 0,
+ }, nil)
+ }),
+ )
+}
+
+func SelectByNodeID(ctx context.Context, nodeID int64, value string) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.focus", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return nil
+ }),
+ )
+}
+
+func ScrollByNodeID(ctx context.Context, nodeID int64) error {
+ return chromedp.Run(ctx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.scrollIntoViewIfNeeded", map[string]any{"backendNodeId": nodeID}, nil)
+ }),
+ )
+}
+
+func WaitForTitle(ctx context.Context, timeout time.Duration) string {
+ if timeout <= 0 {
+ var title string
+ _ = chromedp.Run(ctx, chromedp.Title(&title))
+ return title
+ }
+
+ start := time.Now()
+ for time.Since(start) < timeout {
+ var title string
+ _ = chromedp.Run(ctx, chromedp.Title(&title))
+ if title != "" && title != "about:blank" {
+ return title
+ }
+ time.Sleep(200 * time.Millisecond)
+ }
+ var title string
+ _ = chromedp.Run(ctx, chromedp.Title(&title))
+ return title
+}
diff --git a/internal/bridge/lock.go b/internal/bridge/lock.go
new file mode 100644
index 00000000..a0b29635
--- /dev/null
+++ b/internal/bridge/lock.go
@@ -0,0 +1,74 @@
+package bridge
+
+import (
+ "fmt"
+ "sync"
+ "time"
+)
+
+const DefaultLockTimeout = 10 * time.Minute
+
+type lockEntry struct {
+ owner string
+ expires time.Time
+}
+
+type LockManager struct {
+ locks map[string]lockEntry
+ mu sync.Mutex
+}
+
+func NewLockManager() *LockManager {
+ return &LockManager{
+ locks: make(map[string]lockEntry),
+ }
+}
+
+func (m *LockManager) TryLock(tabID, owner string, ttl time.Duration) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ l, ok := m.locks[tabID]
+ if ok && time.Now().Before(l.expires) && l.owner != owner {
+ return fmt.Errorf("tab %s is locked by %s for another %v", tabID, l.owner, time.Until(l.expires).Round(time.Second))
+ }
+
+ m.locks[tabID] = lockEntry{
+ owner: owner,
+ expires: time.Now().Add(ttl),
+ }
+ return nil
+}
+
+func (m *LockManager) Unlock(tabID, owner string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ l, ok := m.locks[tabID]
+ if !ok || time.Now().After(l.expires) {
+ delete(m.locks, tabID)
+ return nil
+ }
+
+ if l.owner != owner {
+ return fmt.Errorf("cannot unlock: tab %s is locked by %s", tabID, l.owner)
+ }
+
+ delete(m.locks, tabID)
+ return nil
+}
+
+func (m *LockManager) Get(tabID string) *LockInfo {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ l, ok := m.locks[tabID]
+ if !ok || time.Now().After(l.expires) {
+ return nil
+ }
+
+ return &LockInfo{
+ Owner: l.owner,
+ ExpiresAt: l.expires,
+ }
+}
diff --git a/internal/bridge/lock_test.go b/internal/bridge/lock_test.go
new file mode 100644
index 00000000..9af7fb84
--- /dev/null
+++ b/internal/bridge/lock_test.go
@@ -0,0 +1,59 @@
+package bridge
+
+import (
+ "testing"
+ "time"
+)
+
+func TestLockManager(t *testing.T) {
+ m := NewLockManager()
+ tabID := "tab1"
+ owner1 := "agent1"
+ owner2 := "agent2"
+ ttl := 100 * time.Millisecond
+
+ if err := m.TryLock(tabID, owner1, ttl); err != nil {
+ t.Fatalf("lock failed: %v", err)
+ }
+
+ if err := m.TryLock(tabID, owner1, ttl); err != nil {
+ t.Fatalf("re-lock same owner failed: %v", err)
+ }
+
+ if err := m.TryLock(tabID, owner2, ttl); err == nil {
+ t.Error("expected conflict error")
+ }
+
+ if err := m.Unlock(tabID, owner1); err != nil {
+ t.Fatalf("unlock failed: %v", err)
+ }
+
+ if err := m.TryLock(tabID, owner2, ttl); err != nil {
+ t.Fatalf("lock after unlock failed: %v", err)
+ }
+
+ time.Sleep(150 * time.Millisecond)
+ if err := m.TryLock(tabID, owner1, ttl); err != nil {
+ t.Fatalf("lock after expiration failed: %v", err)
+ }
+}
+
+func TestLockManagerGet(t *testing.T) {
+ m := NewLockManager()
+ tabID := "tab1"
+ owner := "agent1"
+ ttl := 1 * time.Hour
+
+ if info := m.Get(tabID); info != nil {
+ t.Error("expected nil info for unlocked tab")
+ }
+
+ _ = m.TryLock(tabID, owner, ttl)
+ info := m.Get(tabID)
+ if info == nil {
+ t.Fatal("expected info")
+ }
+ if info.Owner != owner {
+ t.Errorf("expected owner %s, got %s", owner, info.Owner)
+ }
+}
diff --git a/snapshot.go b/internal/bridge/snapshot.go
similarity index 61%
rename from snapshot.go
rename to internal/bridge/snapshot.go
index c43915d7..dbdf9ee7 100644
--- a/snapshot.go
+++ b/internal/bridge/snapshot.go
@@ -1,4 +1,4 @@
-package main
+package bridge
import (
"encoding/json"
@@ -17,28 +17,28 @@ type A11yNode struct {
NodeID int64 `json:"nodeId,omitempty"`
}
-type rawAXNode struct {
+type RawAXNode struct {
NodeID string `json:"nodeId"`
Ignored bool `json:"ignored"`
- Role *rawAXValue `json:"role"`
- Name *rawAXValue `json:"name"`
- Value *rawAXValue `json:"value"`
- Properties []rawAXProp `json:"properties"`
+ Role *RawAXValue `json:"role"`
+ Name *RawAXValue `json:"name"`
+ Value *RawAXValue `json:"value"`
+ Properties []RawAXProp `json:"properties"`
ChildIDs []string `json:"childIds"`
BackendDOMNodeID int64 `json:"backendDOMNodeId"`
}
-type rawAXValue struct {
+type RawAXValue struct {
Type string `json:"type"`
Value json.RawMessage `json:"value"`
}
-type rawAXProp struct {
+type RawAXProp struct {
Name string `json:"name"`
- Value *rawAXValue `json:"value"`
+ Value *RawAXValue `json:"value"`
}
-func (v *rawAXValue) String() string {
+func (v *RawAXValue) String() string {
if v == nil || v.Value == nil {
return ""
}
@@ -49,7 +49,7 @@ func (v *rawAXValue) String() string {
return strings.Trim(string(v.Value), `"`)
}
-var interactiveRoles = map[string]bool{
+var InteractiveRoles = map[string]bool{
"button": true, "link": true, "textbox": true, "searchbox": true,
"combobox": true, "listbox": true, "option": true, "checkbox": true,
"radio": true, "switch": true, "slider": true, "spinbutton": true,
@@ -57,8 +57,9 @@ var interactiveRoles = map[string]bool{
"tab": true, "treeitem": true,
}
-func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode, map[string]int64) {
+const FilterInteractive = "interactive"
+func BuildSnapshot(nodes []RawAXNode, filter string, maxDepth int) ([]A11yNode, map[string]int64) {
parentMap := make(map[string]string)
for _, n := range nodes {
for _, childID := range n.ChildIDs {
@@ -102,7 +103,7 @@ func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode,
if maxDepth >= 0 && depth > maxDepth {
continue
}
- if filter == filterInteractive && !interactiveRoles[role] {
+ if filter == FilterInteractive && !InteractiveRoles[role] {
continue
}
@@ -138,94 +139,7 @@ func buildSnapshot(nodes []rawAXNode, filter string, maxDepth int) ([]A11yNode,
return flat, refs
}
-func formatSnapshotText(nodes []A11yNode) string {
- var b strings.Builder
- for _, n := range nodes {
- for i := 0; i < n.Depth; i++ {
- b.WriteString(" ")
- }
- b.WriteString(n.Ref)
- b.WriteByte(' ')
- b.WriteString(n.Role)
- if n.Name != "" {
- b.WriteString(` "`)
- b.WriteString(n.Name)
- b.WriteByte('"')
- }
- if n.Value != "" {
- b.WriteString(` val="`)
- b.WriteString(n.Value)
- b.WriteByte('"')
- }
- if n.Focused {
- b.WriteString(" [focused]")
- }
- if n.Disabled {
- b.WriteString(" [disabled]")
- }
- b.WriteByte('\n')
- }
- return b.String()
-}
-
-func formatSnapshotCompact(nodes []A11yNode) string {
- var b strings.Builder
- for _, n := range nodes {
- b.WriteString(n.Ref)
- b.WriteByte(':')
- b.WriteString(n.Role)
- if n.Name != "" {
- b.WriteString(` "`)
- b.WriteString(n.Name)
- b.WriteByte('"')
- }
- if n.Value != "" {
- b.WriteString(` val="`)
- b.WriteString(n.Value)
- b.WriteByte('"')
- }
- if n.Focused {
- b.WriteString(" *")
- }
- if n.Disabled {
- b.WriteString(" -")
- }
- b.WriteByte('\n')
- }
- return b.String()
-}
-
-func truncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNode, bool) {
- tokensUsed := 0
- for i, n := range nodes {
-
- var nodeTokens int
- switch format {
- case "compact":
-
- size := len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
- nodeTokens = size / 4
- case "text":
- size := n.Depth*2 + len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
- nodeTokens = size / 4
- default:
-
- size := len(n.Ref) + len(n.Role) + len(n.Name) + len(n.Value) + 60
- nodeTokens = size / 3
- }
- if nodeTokens < 1 {
- nodeTokens = 1
- }
- tokensUsed += nodeTokens
- if tokensUsed > maxTokens {
- return nodes[:i], true
- }
- }
- return nodes, false
-}
-
-func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
-
+func FilterSubtree(nodes []RawAXNode, scopeBackendID int64) []RawAXNode {
scopeAXID := ""
for _, n := range nodes {
if n.BackendDOMNodeID == scopeBackendID {
@@ -256,7 +170,7 @@ func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
}
}
- result := make([]rawAXNode, 0, len(include))
+ result := make([]RawAXNode, 0, len(include))
for _, n := range nodes {
if include[n.NodeID] {
result = append(result, n)
@@ -265,7 +179,7 @@ func filterSubtree(nodes []rawAXNode, scopeBackendID int64) []rawAXNode {
return result
}
-func diffSnapshot(prev, curr []A11yNode) (added, changed, removed []A11yNode) {
+func DiffSnapshot(prev, curr []A11yNode) (added, changed, removed []A11yNode) {
prevMap := make(map[string]A11yNode, len(prev))
for _, n := range prev {
key := fmt.Sprintf("%s:%s:%d", n.Role, n.Name, n.NodeID)
diff --git a/snapshot_extra_test.go b/internal/bridge/snapshot_extra_test.go
similarity index 64%
rename from snapshot_extra_test.go
rename to internal/bridge/snapshot_extra_test.go
index 49c876f2..b1d0951d 100644
--- a/snapshot_extra_test.go
+++ b/internal/bridge/snapshot_extra_test.go
@@ -1,9 +1,7 @@
-package main
+package bridge
import (
- "bytes"
"encoding/json"
- "net/http/httptest"
"testing"
)
@@ -12,7 +10,7 @@ func TestFormatSnapshotCompact_Basic(t *testing.T) {
{Ref: "e0", Role: "button", Name: "Submit"},
{Ref: "e1", Role: "textbox", Name: "Email", Value: "[email protected]"},
}
- got := formatSnapshotCompact(nodes)
+ got := FormatSnapshotCompact(nodes)
want := "e0:button \"Submit\"\ne1:textbox \"Email\" val=\"[email protected]\"\n"
if got != want {
t.Errorf("got:\n%s\nwant:\n%s", got, want)
@@ -25,7 +23,7 @@ func TestFormatSnapshotCompact_FocusedDisabled(t *testing.T) {
{Ref: "e1", Role: "button", Name: "Cancel", Disabled: true},
{Ref: "e2", Role: "textbox", Focused: true, Disabled: true},
}
- got := formatSnapshotCompact(nodes)
+ got := FormatSnapshotCompact(nodes)
if !contains(got, "e0:button \"OK\" *\n") {
t.Errorf("expected focused marker *, got:\n%s", got)
}
@@ -38,7 +36,7 @@ func TestFormatSnapshotCompact_FocusedDisabled(t *testing.T) {
}
func TestFormatSnapshotCompact_Empty(t *testing.T) {
- got := formatSnapshotCompact(nil)
+ got := FormatSnapshotCompact(nil)
if got != "" {
t.Errorf("expected empty string, got %q", got)
}
@@ -46,7 +44,7 @@ func TestFormatSnapshotCompact_Empty(t *testing.T) {
func TestFormatSnapshotCompact_NoName(t *testing.T) {
nodes := []A11yNode{{Ref: "e0", Role: "generic"}}
- got := formatSnapshotCompact(nodes)
+ got := FormatSnapshotCompact(nodes)
if got != "e0:generic\n" {
t.Errorf("got %q", got)
}
@@ -57,7 +55,7 @@ func TestTruncateToTokens_NoTruncation(t *testing.T) {
{Ref: "e0", Role: "button", Name: "OK"},
{Ref: "e1", Role: "link", Name: "Home"},
}
- result, truncated := truncateToTokens(nodes, 1000, "compact")
+ result, truncated := TruncateToTokens(nodes, 1000, "compact")
if truncated {
t.Error("expected no truncation")
}
@@ -71,7 +69,7 @@ func TestTruncateToTokens_Truncates(t *testing.T) {
for i := range nodes {
nodes[i] = A11yNode{Ref: "e0", Role: "button", Name: "A long button name here"}
}
- result, truncated := truncateToTokens(nodes, 50, "compact")
+ result, truncated := TruncateToTokens(nodes, 50, "compact")
if !truncated {
t.Error("expected truncation")
}
@@ -86,15 +84,15 @@ func TestTruncateToTokens_Formats(t *testing.T) {
nodes[i] = A11yNode{Ref: "e0", Role: "button", Name: "Click me"}
}
- jsonResult, _ := truncateToTokens(nodes, 100, "json")
- compactResult, _ := truncateToTokens(nodes, 100, "compact")
+ jsonResult, _ := TruncateToTokens(nodes, 100, "json")
+ compactResult, _ := TruncateToTokens(nodes, 100, "compact")
if len(jsonResult) > len(compactResult) {
t.Errorf("JSON should truncate sooner: json=%d compact=%d", len(jsonResult), len(compactResult))
}
}
func TestTruncateToTokens_Empty(t *testing.T) {
- result, truncated := truncateToTokens(nil, 100, "compact")
+ result, truncated := TruncateToTokens(nil, 100, "compact")
if truncated {
t.Error("expected no truncation on empty")
}
@@ -104,7 +102,7 @@ func TestTruncateToTokens_Empty(t *testing.T) {
}
func TestFilterSubtree_Found(t *testing.T) {
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{NodeID: "root", BackendDOMNodeID: 1, ChildIDs: []string{"child1", "child2"}},
{NodeID: "child1", BackendDOMNodeID: 2, ChildIDs: []string{"grandchild"}},
{NodeID: "child2", BackendDOMNodeID: 3},
@@ -112,7 +110,7 @@ func TestFilterSubtree_Found(t *testing.T) {
{NodeID: "other", BackendDOMNodeID: 5},
}
- result := filterSubtree(nodes, 2)
+ result := FilterSubtree(nodes, 2)
if len(result) != 2 {
t.Errorf("expected 2 nodes, got %d", len(result))
}
@@ -126,25 +124,25 @@ func TestFilterSubtree_Found(t *testing.T) {
}
func TestFilterSubtree_NotFound(t *testing.T) {
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{NodeID: "root", BackendDOMNodeID: 1},
{NodeID: "child", BackendDOMNodeID: 2},
}
- result := filterSubtree(nodes, 999)
+ result := FilterSubtree(nodes, 999)
if len(result) != 2 {
t.Errorf("expected all nodes returned, got %d", len(result))
}
}
func TestFilterSubtree_RootScope(t *testing.T) {
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{NodeID: "root", BackendDOMNodeID: 1, ChildIDs: []string{"child"}},
{NodeID: "child", BackendDOMNodeID: 2, ChildIDs: []string{"grandchild"}},
{NodeID: "grandchild", BackendDOMNodeID: 3},
}
- result := filterSubtree(nodes, 1)
+ result := FilterSubtree(nodes, 1)
if len(result) != 3 {
t.Errorf("expected 3 nodes, got %d", len(result))
}
@@ -156,7 +154,7 @@ func TestDiffSnapshot_Added(t *testing.T) {
{Ref: "e0", Role: "button", Name: "OK", NodeID: 1},
{Ref: "e1", Role: "link", Name: "New", NodeID: 2},
}
- added, changed, removed := diffSnapshot(prev, curr)
+ added, changed, removed := DiffSnapshot(prev, curr)
if len(added) != 1 || added[0].Name != "New" {
t.Errorf("expected 1 added node, got %v", added)
}
@@ -174,7 +172,7 @@ func TestDiffSnapshot_Removed(t *testing.T) {
{Ref: "e1", Role: "link", Name: "Old", NodeID: 2},
}
curr := []A11yNode{{Ref: "e0", Role: "button", Name: "OK", NodeID: 1}}
- _, _, removed := diffSnapshot(prev, curr)
+ _, _, removed := DiffSnapshot(prev, curr)
if len(removed) != 1 || removed[0].Name != "Old" {
t.Errorf("expected 1 removed node, got %v", removed)
}
@@ -183,106 +181,47 @@ func TestDiffSnapshot_Removed(t *testing.T) {
func TestDiffSnapshot_Changed(t *testing.T) {
prev := []A11yNode{{Ref: "e0", Role: "textbox", Name: "Email", NodeID: 1, Value: "old"}}
curr := []A11yNode{{Ref: "e0", Role: "textbox", Name: "Email", NodeID: 1, Value: "new"}}
- _, changed, _ := diffSnapshot(prev, curr)
+ _, changed, _ := DiffSnapshot(prev, curr)
if len(changed) != 1 || changed[0].Value != "new" {
t.Errorf("expected 1 changed node, got %v", changed)
}
}
func TestDiffSnapshot_Empty(t *testing.T) {
- added, changed, removed := diffSnapshot(nil, nil)
+ added, changed, removed := DiffSnapshot(nil, nil)
if len(added)+len(changed)+len(removed) != 0 {
t.Error("expected all empty for nil inputs")
}
}
func TestRawAXValue_String_Normal(t *testing.T) {
- v := &rawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}
+ v := &RawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}
if got := v.String(); got != "hello" {
t.Errorf("expected hello, got %q", got)
}
}
func TestRawAXValue_String_Nil(t *testing.T) {
- var v *rawAXValue
+ var v *RawAXValue
if got := v.String(); got != "" {
t.Errorf("expected empty, got %q", got)
}
}
func TestRawAXValue_String_NilValue(t *testing.T) {
- v := &rawAXValue{Type: "string"}
+ v := &RawAXValue{Type: "string"}
if got := v.String(); got != "" {
t.Errorf("expected empty, got %q", got)
}
}
func TestRawAXValue_String_NonString(t *testing.T) {
- v := &rawAXValue{Type: "number", Value: json.RawMessage(`42`)}
-
+ v := &RawAXValue{Type: "number", Value: json.RawMessage(`42`)}
if got := v.String(); got != "42" {
t.Errorf("expected 42, got %q", got)
}
}
-func TestHandleSnapshot_InvalidFilter(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- req := httptest.NewRequest("GET", "/snapshot?filter=bogus", nil)
- w := httptest.NewRecorder()
- b.handleSnapshot(w, req)
- if w.Code == 0 {
- t.Error("expected a response code")
- }
-}
-
-func TestHandleScreenshot_RawParam(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- req := httptest.NewRequest("GET", "/screenshot?raw=true&tabId=nonexistent", nil)
- w := httptest.NewRecorder()
- b.handleScreenshot(w, req)
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_WithTimeout(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- body := `{"url":"https://example.com","timeout":5,"tabId":"nonexistent"}`
- req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_WithBlockImages(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- body := `{"url":"https://example.com","blockImages":true,"tabId":"nonexistent"}`
- req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
- if w.Code != 404 {
- t.Errorf("expected 404, got %d", w.Code)
- }
-}
-
-func TestHandleNavigate_WaitTitle(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- body := `{"url":"https://example.com","waitTitle":true,"tabId":"nonexistent"}`
- req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
- w := httptest.NewRecorder()
- b.handleNavigate(w, req)
- if w.Code != 404 && w.Code != 400 {
- t.Errorf("expected 404 or 400, got %d", w.Code)
- }
-}
-
func contains(s, substr string) bool {
return len(s) >= len(substr) && searchString(s, substr)
}
diff --git a/internal/bridge/snapshot_format.go b/internal/bridge/snapshot_format.go
new file mode 100644
index 00000000..20788e3e
--- /dev/null
+++ b/internal/bridge/snapshot_format.go
@@ -0,0 +1,88 @@
+package bridge
+
+import (
+ "strings"
+)
+
+func FormatSnapshotText(nodes []A11yNode) string {
+ var b strings.Builder
+ for _, n := range nodes {
+ for i := 0; i < n.Depth; i++ {
+ b.WriteString(" ")
+ }
+ b.WriteString(n.Ref)
+ b.WriteByte(' ')
+ b.WriteString(n.Role)
+ if n.Name != "" {
+ b.WriteString(` "`)
+ b.WriteString(n.Name)
+ b.WriteByte('"')
+ }
+ if n.Value != "" {
+ b.WriteString(` val="`)
+ b.WriteString(n.Value)
+ b.WriteByte('"')
+ }
+ if n.Focused {
+ b.WriteString(" [focused]")
+ }
+ if n.Disabled {
+ b.WriteString(" [disabled]")
+ }
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+
+func FormatSnapshotCompact(nodes []A11yNode) string {
+ var b strings.Builder
+ for _, n := range nodes {
+ b.WriteString(n.Ref)
+ b.WriteByte(':')
+ b.WriteString(n.Role)
+ if n.Name != "" {
+ b.WriteString(` "`)
+ b.WriteString(n.Name)
+ b.WriteByte('"')
+ }
+ if n.Value != "" {
+ b.WriteString(` val="`)
+ b.WriteString(n.Value)
+ b.WriteByte('"')
+ }
+ if n.Focused {
+ b.WriteString(" *")
+ }
+ if n.Disabled {
+ b.WriteString(" -")
+ }
+ b.WriteByte('\n')
+ }
+ return b.String()
+}
+
+func TruncateToTokens(nodes []A11yNode, maxTokens int, format string) ([]A11yNode, bool) {
+ tokensUsed := 0
+ for i, n := range nodes {
+ var nodeTokens int
+ switch format {
+ case "compact":
+ size := len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
+ nodeTokens = size / 4
+ case "text":
+ size := n.Depth*2 + len(n.Ref) + 1 + len(n.Role) + len(n.Name) + len(n.Value) + 8
+ nodeTokens = size / 4
+ default:
+ size := len(n.Ref) + len(n.Role) + len(n.Name) + len(n.Value) + 60
+ nodeTokens = size / 3
+ }
+ if nodeTokens < 1 {
+ nodeTokens = 1
+ }
+ tokensUsed += nodeTokens
+ if tokensUsed > maxTokens {
+ return nodes[:i], true
+ }
+ }
+ return nodes, false
+}
diff --git a/snapshot_test.go b/internal/bridge/snapshot_test.go
similarity index 65%
rename from snapshot_test.go
rename to internal/bridge/snapshot_test.go
index c67c216a..3e5badf0 100644
--- a/snapshot_test.go
+++ b/internal/bridge/snapshot_test.go
@@ -1,4 +1,4 @@
-package main
+package bridge
import (
"encoding/json"
@@ -9,14 +9,14 @@ import (
func TestRawAXValueString(t *testing.T) {
tests := []struct {
name string
- val *rawAXValue
+ val *RawAXValue
want string
}{
{"nil", nil, ""},
- {"nil value", &rawAXValue{Type: "string"}, ""},
- {"string", &rawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}, "hello"},
- {"number", &rawAXValue{Type: "integer", Value: json.RawMessage(`42`)}, "42"},
- {"bool", &rawAXValue{Type: "boolean", Value: json.RawMessage(`true`)}, "true"},
+ {"nil value", &RawAXValue{Type: "string"}, ""},
+ {"string", &RawAXValue{Type: "string", Value: json.RawMessage(`"hello"`)}, "hello"},
+ {"number", &RawAXValue{Type: "integer", Value: json.RawMessage(`42`)}, "42"},
+ {"bool", &RawAXValue{Type: "boolean", Value: json.RawMessage(`true`)}, "true"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -31,58 +31,57 @@ func TestRawAXValueString(t *testing.T) {
func TestInteractiveRoles(t *testing.T) {
interactive := []string{"button", "link", "textbox", "checkbox", "radio", "tab", "menuitem"}
for _, r := range interactive {
- if !interactiveRoles[r] {
+ if !InteractiveRoles[r] {
t.Errorf("expected %q to be interactive", r)
}
}
nonInteractive := []string{"heading", "paragraph", "image", "banner", "main", "navigation"}
for _, r := range nonInteractive {
- if interactiveRoles[r] {
+ if InteractiveRoles[r] {
t.Errorf("expected %q to NOT be interactive", r)
}
}
}
func TestBuildSnapshot(t *testing.T) {
-
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{
NodeID: "root",
- Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Test Page"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"WebArea"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Test Page"`)},
ChildIDs: []string{"n1", "n2", "n3"},
BackendDOMNodeID: 1,
},
{
NodeID: "n1",
- Role: &rawAXValue{Value: json.RawMessage(`"button"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Submit"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"button"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Submit"`)},
BackendDOMNodeID: 10,
},
{
NodeID: "n2",
- Role: &rawAXValue{Value: json.RawMessage(`"textbox"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Email"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"textbox"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Email"`)},
BackendDOMNodeID: 20,
- Properties: []rawAXProp{
- {Name: "focused", Value: &rawAXValue{Value: json.RawMessage(`"true"`)}},
+ Properties: []RawAXProp{
+ {Name: "focused", Value: &RawAXValue{Value: json.RawMessage(`"true"`)}},
},
},
{
NodeID: "n3",
Ignored: true,
- Role: &rawAXValue{Value: json.RawMessage(`"none"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"none"`)},
},
{
NodeID: "n4",
- Role: &rawAXValue{Value: json.RawMessage(`"generic"`)},
- Name: &rawAXValue{Value: json.RawMessage(`""`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"generic"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`""`)},
BackendDOMNodeID: 30,
},
}
- flat, refs := buildSnapshot(nodes, "", -1)
+ flat, refs := BuildSnapshot(nodes, "", -1)
if len(flat) != 3 {
t.Fatalf("expected 3 nodes, got %d: %+v", len(flat), flat)
@@ -111,29 +110,29 @@ func TestBuildSnapshot(t *testing.T) {
}
func TestBuildSnapshotInteractiveFilter(t *testing.T) {
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{
NodeID: "root",
- Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Page"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"WebArea"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Page"`)},
ChildIDs: []string{"n1", "n2"},
BackendDOMNodeID: 1,
},
{
NodeID: "n1",
- Role: &rawAXValue{Value: json.RawMessage(`"heading"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Title"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"heading"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Title"`)},
BackendDOMNodeID: 10,
},
{
NodeID: "n2",
- Role: &rawAXValue{Value: json.RawMessage(`"button"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Click me"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"button"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Click me"`)},
BackendDOMNodeID: 20,
},
}
- flat, _ := buildSnapshot(nodes, filterInteractive, -1)
+ flat, _ := BuildSnapshot(nodes, FilterInteractive, -1)
if len(flat) != 1 {
t.Fatalf("expected 1 interactive node, got %d: %+v", len(flat), flat)
@@ -151,7 +150,7 @@ func TestFormatSnapshotText(t *testing.T) {
{Ref: "e3", Role: "button", Name: "Cancel", Depth: 1, Disabled: true},
}
- text := formatSnapshotText(nodes)
+ text := FormatSnapshotText(nodes)
if !strings.Contains(text, `e0 WebArea "Page"`) {
t.Error("missing root node")
@@ -182,7 +181,7 @@ func TestDiffSnapshot(t *testing.T) {
{Ref: "e3", Role: "link", Name: "New Link", NodeID: 40},
}
- added, changed, removed := diffSnapshot(prev, curr)
+ added, changed, removed := DiffSnapshot(prev, curr)
if len(added) != 1 || added[0].Name != "New Link" {
t.Errorf("expected 1 added (New Link), got %+v", added)
@@ -195,38 +194,31 @@ func TestDiffSnapshot(t *testing.T) {
}
}
-func TestDiffSnapshotEmpty(t *testing.T) {
- added, changed, removed := diffSnapshot(nil, nil)
- if len(added) != 0 || len(changed) != 0 || len(removed) != 0 {
- t.Error("diff of two empty snapshots should be empty")
- }
-}
-
func TestBuildSnapshotDepthFilter(t *testing.T) {
- nodes := []rawAXNode{
+ nodes := []RawAXNode{
{
NodeID: "root",
- Role: &rawAXValue{Value: json.RawMessage(`"WebArea"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Page"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"WebArea"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Page"`)},
ChildIDs: []string{"n1"},
BackendDOMNodeID: 1,
},
{
NodeID: "n1",
- Role: &rawAXValue{Value: json.RawMessage(`"navigation"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Nav"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"navigation"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Nav"`)},
ChildIDs: []string{"n2"},
BackendDOMNodeID: 10,
},
{
NodeID: "n2",
- Role: &rawAXValue{Value: json.RawMessage(`"link"`)},
- Name: &rawAXValue{Value: json.RawMessage(`"Home"`)},
+ Role: &RawAXValue{Value: json.RawMessage(`"link"`)},
+ Name: &RawAXValue{Value: json.RawMessage(`"Home"`)},
BackendDOMNodeID: 20,
},
}
- flat, _ := buildSnapshot(nodes, "", 1)
+ flat, _ := BuildSnapshot(nodes, "", 1)
if len(flat) != 2 {
t.Fatalf("expected 2 nodes at depth<=1, got %d: %+v", len(flat), flat)
diff --git a/state.go b/internal/bridge/state.go
similarity index 85%
rename from state.go
rename to internal/bridge/state.go
index d8f00a74..d1ad2fbf 100644
--- a/state.go
+++ b/internal/bridge/state.go
@@ -1,4 +1,4 @@
-package main
+package bridge
import (
"context"
@@ -30,8 +30,8 @@ type SessionState struct {
SavedAt string `json:"savedAt"`
}
-func markCleanExit() {
- prefsPath := filepath.Join(cfg.ProfileDir, "Default", "Preferences")
+func MarkCleanExit(profileDir string) {
+ prefsPath := filepath.Join(profileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
if err != nil {
return
@@ -44,8 +44,8 @@ func markCleanExit() {
}
}
-func wasUncleanExit() bool {
- prefsPath := filepath.Join(cfg.ProfileDir, "Default", "Preferences")
+func WasUncleanExit(profileDir string) bool {
+ prefsPath := filepath.Join(profileDir, "Default", "Preferences")
data, err := os.ReadFile(prefsPath)
if err != nil {
return false
@@ -54,8 +54,8 @@ func wasUncleanExit() bool {
return strings.Contains(prefs, `"exit_type":"Crashed"`) || strings.Contains(prefs, `"exit_type": "Crashed"`)
}
-func clearChromeSessions() {
- sessionsDir := filepath.Join(cfg.ProfileDir, "Default", "Sessions")
+func ClearChromeSessions(profileDir string) {
+ sessionsDir := filepath.Join(profileDir, "Default", "Sessions")
if err := os.RemoveAll(sessionsDir); err != nil {
slog.Warn("failed to clear Chrome sessions dir", "err", err)
} else {
@@ -91,11 +91,11 @@ func (b *Bridge) SaveState() {
slog.Error("save state: marshal", "err", err)
return
}
- if err := os.MkdirAll(cfg.StateDir, 0755); err != nil {
+ if err := os.MkdirAll(b.Config.StateDir, 0755); err != nil {
slog.Error("save state: mkdir", "err", err)
return
}
- path := filepath.Join(cfg.StateDir, "sessions.json")
+ path := filepath.Join(b.Config.StateDir, "sessions.json")
if err := os.WriteFile(path, data, 0644); err != nil {
slog.Error("save state: write", "err", err)
} else {
@@ -104,7 +104,7 @@ func (b *Bridge) SaveState() {
}
func (b *Bridge) RestoreState() {
- path := filepath.Join(cfg.StateDir, "sessions.json")
+ path := filepath.Join(b.Config.StateDir, "sessions.json")
data, err := os.ReadFile(path)
if err != nil {
return
@@ -136,7 +136,7 @@ func (b *Bridge) RestoreState() {
time.Sleep(200 * time.Millisecond)
}
- ctx, cancel := chromedp.NewContext(b.browserCtx)
+ ctx, cancel := chromedp.NewContext(b.BrowserCtx)
if err := chromedp.Run(ctx); err != nil {
cancel()
@@ -147,7 +147,7 @@ func (b *Bridge) RestoreState() {
newID := string(chromedp.FromContext(ctx).Target.TargetID)
b.mu.Lock()
- b.tabs[newID] = &TabEntry{ctx: ctx, cancel: cancel}
+ b.tabs[newID] = &TabEntry{Ctx: ctx, Cancel: cancel}
b.mu.Unlock()
restored++
diff --git a/state_test.go b/internal/bridge/state_test.go
similarity index 59%
rename from state_test.go
rename to internal/bridge/state_test.go
index 9bea0320..3174df43 100644
--- a/state_test.go
+++ b/internal/bridge/state_test.go
@@ -1,33 +1,29 @@
-package main
+package bridge
import (
"encoding/json"
"os"
"path/filepath"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
func TestMarkCleanExit_NoFile(t *testing.T) {
- origProfileDir := cfg.ProfileDir
- cfg.ProfileDir = t.TempDir()
- defer func() { cfg.ProfileDir = origProfileDir }()
-
- markCleanExit()
+ tmpDir := t.TempDir()
+ MarkCleanExit(tmpDir)
}
func TestMarkCleanExit_PatchesCrashed(t *testing.T) {
- origProfileDir := cfg.ProfileDir
- cfg.ProfileDir = t.TempDir()
- defer func() { cfg.ProfileDir = origProfileDir }()
-
- prefsDir := filepath.Join(cfg.ProfileDir, "Default")
+ tmpDir := t.TempDir()
+ prefsDir := filepath.Join(tmpDir, "Default")
_ = os.MkdirAll(prefsDir, 0755)
prefsPath := filepath.Join(prefsDir, "Preferences")
content := `{"profile":{"exit_type":"Crashed","exited_cleanly":false}}`
_ = os.WriteFile(prefsPath, []byte(content), 0644)
- markCleanExit()
+ MarkCleanExit(tmpDir)
data, err := os.ReadFile(prefsPath)
if err != nil {
@@ -40,18 +36,15 @@ func TestMarkCleanExit_PatchesCrashed(t *testing.T) {
}
func TestMarkCleanExit_NoPatch(t *testing.T) {
- origProfileDir := cfg.ProfileDir
- cfg.ProfileDir = t.TempDir()
- defer func() { cfg.ProfileDir = origProfileDir }()
-
- prefsDir := filepath.Join(cfg.ProfileDir, "Default")
+ tmpDir := t.TempDir()
+ prefsDir := filepath.Join(tmpDir, "Default")
_ = os.MkdirAll(prefsDir, 0755)
prefsPath := filepath.Join(prefsDir, "Preferences")
content := `{"profile":{"exit_type":"Normal","exited_cleanly":true}}`
_ = os.WriteFile(prefsPath, []byte(content), 0644)
- markCleanExit()
+ MarkCleanExit(tmpDir)
data, _ := os.ReadFile(prefsPath)
if string(data) != content {
@@ -88,111 +81,60 @@ func TestSessionState_Marshal(t *testing.T) {
func TestSaveState_NoBrowser(t *testing.T) {
b := newTestBridge()
-
+ b.Config = &config.RuntimeConfig{StateDir: t.TempDir()}
b.SaveState()
}
func TestRestoreState_NoFile(t *testing.T) {
- origStateDir := cfg.StateDir
- cfg.StateDir = t.TempDir()
- defer func() { cfg.StateDir = origStateDir }()
-
b := newTestBridge()
-
+ b.Config = &config.RuntimeConfig{StateDir: t.TempDir()}
b.RestoreState()
}
func TestRestoreState_EmptyTabs(t *testing.T) {
- origStateDir := cfg.StateDir
- cfg.StateDir = t.TempDir()
- defer func() { cfg.StateDir = origStateDir }()
-
+ tmpDir := t.TempDir()
state := SessionState{Tabs: []TabState{}, SavedAt: "2026-02-17T07:00:00Z"}
data, _ := json.Marshal(state)
- _ = os.WriteFile(filepath.Join(cfg.StateDir, "sessions.json"), data, 0644)
-
- b := newTestBridge()
-
- b.RestoreState()
-}
-
-func TestRestoreState_InvalidJSON(t *testing.T) {
- origStateDir := cfg.StateDir
- cfg.StateDir = t.TempDir()
- defer func() { cfg.StateDir = origStateDir }()
-
- _ = os.WriteFile(filepath.Join(cfg.StateDir, "sessions.json"), []byte("{broken"), 0644)
+ _ = os.WriteFile(filepath.Join(tmpDir, "sessions.json"), data, 0644)
b := newTestBridge()
-
+ b.Config = &config.RuntimeConfig{StateDir: tmpDir}
b.RestoreState()
}
func TestWasUncleanExit_Crashed(t *testing.T) {
tmp := t.TempDir()
- origProfile := cfg.ProfileDir
- cfg.ProfileDir = tmp
- defer func() { cfg.ProfileDir = origProfile }()
-
defaultDir := filepath.Join(tmp, "Default")
_ = os.MkdirAll(defaultDir, 0755)
_ = os.WriteFile(filepath.Join(defaultDir, "Preferences"),
[]byte(`{"profile":{"exit_type":"Crashed","exited_cleanly":false}}`), 0644)
- if !wasUncleanExit() {
- t.Error("expected wasUncleanExit to return true for Crashed exit_type")
+ if !WasUncleanExit(tmp) {
+ t.Error("expected WasUncleanExit to return true for Crashed exit_type")
}
}
func TestWasUncleanExit_Normal(t *testing.T) {
tmp := t.TempDir()
- origProfile := cfg.ProfileDir
- cfg.ProfileDir = tmp
- defer func() { cfg.ProfileDir = origProfile }()
-
defaultDir := filepath.Join(tmp, "Default")
_ = os.MkdirAll(defaultDir, 0755)
_ = os.WriteFile(filepath.Join(defaultDir, "Preferences"),
[]byte(`{"profile":{"exit_type":"Normal","exited_cleanly":true}}`), 0644)
- if wasUncleanExit() {
- t.Error("expected wasUncleanExit to return false for Normal exit_type")
- }
-}
-
-func TestWasUncleanExit_NoFile(t *testing.T) {
- tmp := t.TempDir()
- origProfile := cfg.ProfileDir
- cfg.ProfileDir = tmp
- defer func() { cfg.ProfileDir = origProfile }()
-
- if wasUncleanExit() {
- t.Error("expected wasUncleanExit to return false when no Preferences file exists")
+ if WasUncleanExit(tmp) {
+ t.Error("expected WasUncleanExit to return false for Normal exit_type")
}
}
func TestClearChromeSessions(t *testing.T) {
tmp := t.TempDir()
- origProfile := cfg.ProfileDir
- cfg.ProfileDir = tmp
- defer func() { cfg.ProfileDir = origProfile }()
-
sessionsDir := filepath.Join(tmp, "Default", "Sessions")
_ = os.MkdirAll(sessionsDir, 0755)
_ = os.WriteFile(filepath.Join(sessionsDir, "Session_1"), []byte("data"), 0644)
- clearChromeSessions()
+ ClearChromeSessions(tmp)
if _, err := os.Stat(sessionsDir); !os.IsNotExist(err) {
t.Error("expected Sessions dir to be removed")
}
}
-
-func TestClearChromeSessions_NoDir(t *testing.T) {
- tmp := t.TempDir()
- origProfile := cfg.ProfileDir
- cfg.ProfileDir = tmp
- defer func() { cfg.ProfileDir = origProfile }()
-
- clearChromeSessions()
-}
diff --git a/tab_manager.go b/internal/bridge/tab_manager.go
similarity index 68%
rename from tab_manager.go
rename to internal/bridge/tab_manager.go
index 57dc9a20..7176d6bc 100644
--- a/tab_manager.go
+++ b/internal/bridge/tab_manager.go
@@ -1,4 +1,4 @@
-package main
+package bridge
import (
"context"
@@ -10,32 +10,30 @@ import (
cdp "github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/config"
)
-// TabSetupFunc is called after a new tab context is created (stealth, animations, etc.).
type TabSetupFunc func(ctx context.Context)
-// TabManager manages browser tabs, their contexts, and ref caches.
type TabManager struct {
browserCtx context.Context
+ config *config.RuntimeConfig
tabs map[string]*TabEntry
- snapshots map[string]*refCache
+ snapshots map[string]*RefCache
onTabSetup TabSetupFunc
mu sync.RWMutex
}
-// NewTabManager creates a TabManager with the given browser context and setup hook.
-func NewTabManager(browserCtx context.Context, onTabSetup TabSetupFunc) *TabManager {
+func NewTabManager(browserCtx context.Context, cfg *config.RuntimeConfig, onTabSetup TabSetupFunc) *TabManager {
return &TabManager{
browserCtx: browserCtx,
+ config: cfg,
tabs: make(map[string]*TabEntry),
- snapshots: make(map[string]*refCache),
+ snapshots: make(map[string]*RefCache),
onTabSetup: onTabSetup,
}
}
-// TabContext returns or creates a context for the given tab ID.
-// If tabID is empty, the first available page target is used.
func (tm *TabManager) TabContext(tabID string) (context.Context, string, error) {
if tabID == "" {
targets, err := tm.ListTargets()
@@ -49,17 +47,17 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)
}
tm.mu.RLock()
- if entry, ok := tm.tabs[tabID]; ok && entry.ctx != nil {
+ if entry, ok := tm.tabs[tabID]; ok && entry.Ctx != nil {
tm.mu.RUnlock()
- return entry.ctx, tabID, nil
+ return entry.Ctx, tabID, nil
}
tm.mu.RUnlock()
tm.mu.Lock()
defer tm.mu.Unlock()
- if entry, ok := tm.tabs[tabID]; ok && entry.ctx != nil {
- return entry.ctx, tabID, nil
+ if entry, ok := tm.tabs[tabID]; ok && entry.Ctx != nil {
+ return entry.Ctx, tabID, nil
}
if tm.browserCtx == nil {
@@ -78,23 +76,22 @@ func (tm *TabManager) TabContext(tabID string) (context.Context, string, error)
tm.onTabSetup(ctx)
}
- tm.tabs[tabID] = &TabEntry{ctx: ctx, cancel: cancel}
+ tm.tabs[tabID] = &TabEntry{Ctx: ctx, Cancel: cancel}
return ctx, tabID, nil
}
-// CreateTab opens a new tab, optionally navigating to url.
func (tm *TabManager) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
if tm.browserCtx == nil {
return "", nil, nil, fmt.Errorf("no browser context available")
}
- if cfg.MaxTabs > 0 {
+ if tm.config.MaxTabs > 0 {
targets, err := tm.ListTargets()
if err != nil {
return "", nil, nil, fmt.Errorf("check tab count: %w", err)
}
- if len(targets) >= cfg.MaxTabs {
- return "", nil, nil, fmt.Errorf("tab limit reached (%d/%d) — close a tab first", len(targets), cfg.MaxTabs)
+ if len(targets) >= tm.config.MaxTabs {
+ return "", nil, nil, fmt.Errorf("tab limit reached (%d/%d) — close a tab first", len(targets), tm.config.MaxTabs)
}
}
ctx, cancel := chromedp.NewContext(tm.browserCtx)
@@ -103,37 +100,36 @@ func (tm *TabManager) CreateTab(url string) (string, context.Context, context.Ca
tm.onTabSetup(ctx)
}
- if cfg.BlockMedia {
- _ = setResourceBlocking(ctx, mediaBlockPatterns)
- } else if cfg.BlockImages {
- _ = setResourceBlocking(ctx, imageBlockPatterns)
+ if tm.config.BlockMedia {
+ _ = SetResourceBlocking(ctx, MediaBlockPatterns)
+ } else if tm.config.BlockImages {
+ _ = SetResourceBlocking(ctx, ImageBlockPatterns)
}
navURL := "about:blank"
if url != "" {
navURL = url
}
- if err := navigatePage(ctx, navURL); err != nil {
+ if err := NavigatePage(ctx, navURL); err != nil {
cancel()
return "", nil, nil, fmt.Errorf("new tab: %w", err)
}
newTargetID := string(chromedp.FromContext(ctx).Target.TargetID)
tm.mu.Lock()
- tm.tabs[newTargetID] = &TabEntry{ctx: ctx, cancel: cancel}
+ tm.tabs[newTargetID] = &TabEntry{Ctx: ctx, Cancel: cancel}
tm.mu.Unlock()
return newTargetID, ctx, cancel, nil
}
-// CloseTab closes a tab by ID.
func (tm *TabManager) CloseTab(tabID string) error {
tm.mu.Lock()
entry, tracked := tm.tabs[tabID]
tm.mu.Unlock()
- if tracked && entry.cancel != nil {
- entry.cancel()
+ if tracked && entry.Cancel != nil {
+ entry.Cancel()
}
closeCtx, closeCancel := context.WithTimeout(tm.browserCtx, 5*time.Second)
@@ -154,7 +150,6 @@ func (tm *TabManager) CloseTab(tabID string) error {
return nil
}
-// ListTargets returns all page-type targets from the browser.
func (tm *TabManager) ListTargets() ([]*target.Info, error) {
if tm.browserCtx == nil {
return nil, fmt.Errorf("no browser connection")
@@ -172,42 +167,37 @@ func (tm *TabManager) ListTargets() ([]*target.Info, error) {
pages := make([]*target.Info, 0)
for _, t := range targets {
- if t.Type == targetTypePage {
+ if t.Type == TargetTypePage {
pages = append(pages, t)
}
}
return pages, nil
}
-// GetRefCache returns the ref cache for a tab.
-func (tm *TabManager) GetRefCache(tabID string) *refCache {
+func (tm *TabManager) GetRefCache(tabID string) *RefCache {
tm.mu.RLock()
defer tm.mu.RUnlock()
return tm.snapshots[tabID]
}
-// SetRefCache sets the ref cache for a tab.
-func (tm *TabManager) SetRefCache(tabID string, cache *refCache) {
+func (tm *TabManager) SetRefCache(tabID string, cache *RefCache) {
tm.mu.Lock()
defer tm.mu.Unlock()
tm.snapshots[tabID] = cache
}
-// DeleteRefCache removes the ref cache for a tab.
func (tm *TabManager) DeleteRefCache(tabID string) {
tm.mu.Lock()
defer tm.mu.Unlock()
delete(tm.snapshots, tabID)
}
-// RegisterTab registers an externally-created tab (e.g., the initial Chrome tab).
func (tm *TabManager) RegisterTab(tabID string, ctx context.Context) {
tm.mu.Lock()
defer tm.mu.Unlock()
- tm.tabs[tabID] = &TabEntry{ctx: ctx}
+ tm.tabs[tabID] = &TabEntry{Ctx: ctx}
}
-// CleanStaleTabs periodically removes tabs that no longer exist in Chrome.
func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
@@ -232,8 +222,8 @@ func (tm *TabManager) CleanStaleTabs(ctx context.Context, interval time.Duration
tm.mu.Lock()
for id, entry := range tm.tabs {
if !alive[id] {
- if entry.cancel != nil {
- entry.cancel()
+ if entry.Cancel != nil {
+ entry.Cancel()
}
delete(tm.tabs, id)
delete(tm.snapshots, id)
diff --git a/config.go b/internal/config/config.go
similarity index 81%
rename from config.go
rename to internal/config/config.go
index 20bdf6ac..39db7d29 100644
--- a/config.go
+++ b/internal/config/config.go
@@ -1,10 +1,8 @@
-package main
+package config
import (
- _ "embed"
"encoding/json"
"fmt"
- "log/slog"
"os"
"path/filepath"
"strconv"
@@ -12,41 +10,6 @@ import (
"time"
)
-const maxBodySize = 1 << 20
-
-const targetTypePage = "page"
-
-const filterInteractive = "interactive"
-
-const (
- actionClick = "click"
- actionType = "type"
- actionFill = "fill"
- actionPress = "press"
- actionFocus = "focus"
- actionHover = "hover"
- actionSelect = "select"
- actionScroll = "scroll"
- actionHumanClick = "humanClick"
- actionHumanType = "humanType"
-)
-
-const (
- tabActionNew = "new"
- tabActionClose = "close"
-)
-
-//go:embed stealth.js
-var stealthScript string
-
-//go:embed readability.js
-var readabilityJS string
-
-//go:embed welcome.html
-var welcomeHTML string
-
-// RuntimeConfig holds all runtime configuration in a single struct.
-// Loaded once at startup from environment variables and optional config file.
type RuntimeConfig struct {
Bind string
Port string
@@ -71,9 +34,6 @@ type RuntimeConfig struct {
WaitNavDelay time.Duration
}
-// cfg is the package-level runtime configuration, populated by loadConfig().
-var cfg RuntimeConfig
-
func envOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
@@ -113,12 +73,10 @@ func homeDir() string {
return h
}
-// ListenAddr returns bind:port for http.Server.Addr.
func (c *RuntimeConfig) ListenAddr() string {
return c.Bind + ":" + c.Port
}
-// FileConfig is the JSON config file format.
type FileConfig struct {
Port string `json:"port"`
CdpURL string `json:"cdpUrl,omitempty"`
@@ -132,9 +90,8 @@ type FileConfig struct {
NavigateSec int `json:"navigateSec,omitempty"`
}
-func loadConfig() {
- // Populate from environment with defaults
- cfg = RuntimeConfig{
+func Load() *RuntimeConfig {
+ cfg := &RuntimeConfig{
Bind: envOr("BRIDGE_BIND", "127.0.0.1"),
Port: envOr("BRIDGE_PORT", "9867"),
CdpURL: os.Getenv("CDP_URL"),
@@ -158,18 +115,16 @@ func loadConfig() {
WaitNavDelay: 1 * time.Second,
}
- // Override from config file (env vars take precedence)
configPath := envOr("BRIDGE_CONFIG", filepath.Join(homeDir(), ".pinchtab", "config.json"))
data, err := os.ReadFile(configPath)
if err != nil {
- return
+ return cfg
}
var fc FileConfig
if err := json.Unmarshal(data, &fc); err != nil {
- slog.Warn("invalid JSON in config file, ignoring", "path", configPath, "err", err)
- return
+ return cfg
}
if fc.Port != "" && os.Getenv("BRIDGE_PORT") == "" {
@@ -202,9 +157,11 @@ func loadConfig() {
if fc.NavigateSec > 0 && os.Getenv("BRIDGE_NAV_TIMEOUT") == "" {
cfg.NavigateTimeout = time.Duration(fc.NavigateSec) * time.Second
}
+
+ return cfg
}
-func defaultFileConfig() FileConfig {
+func DefaultFileConfig() FileConfig {
h := true
return FileConfig{
Port: "9867",
@@ -217,7 +174,7 @@ func defaultFileConfig() FileConfig {
}
}
-func handleConfigCommand() {
+func HandleConfigCommand(cfg *RuntimeConfig) {
if len(os.Args) < 3 {
fmt.Println("Usage: pinchtab config <command>")
fmt.Println("Commands:")
@@ -245,7 +202,7 @@ func handleConfigCommand() {
os.Exit(1)
}
- fc := defaultFileConfig()
+ fc := DefaultFileConfig()
data, _ := json.MarshalIndent(fc, "", " ")
if err := os.WriteFile(configPath, data, 0644); err != nil {
fmt.Printf("Error writing config: %v\n", err)
@@ -266,7 +223,7 @@ func handleConfigCommand() {
fmt.Println("Current configuration:")
fmt.Printf(" Port: %s\n", cfg.Port)
fmt.Printf(" CDP URL: %s\n", cfg.CdpURL)
- fmt.Printf(" Token: %s\n", maskToken(cfg.Token))
+ fmt.Printf(" Token: %s\n", MaskToken(cfg.Token))
fmt.Printf(" State Dir: %s\n", cfg.StateDir)
fmt.Printf(" Profile: %s\n", cfg.ProfileDir)
fmt.Printf(" Headless: %v\n", cfg.Headless)
@@ -280,7 +237,7 @@ func handleConfigCommand() {
}
}
-func maskToken(t string) string {
+func MaskToken(t string) string {
if t == "" {
return "(none)"
}
diff --git a/internal/config/config_test.go b/internal/config/config_test.go
new file mode 100644
index 00000000..4603440f
--- /dev/null
+++ b/internal/config/config_test.go
@@ -0,0 +1,152 @@
+package config
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestEnvOr(t *testing.T) {
+ key := "PINCHTAB_TEST_ENV"
+ fallback := "default"
+
+ _ = os.Unsetenv(key)
+ if got := envOr(key, fallback); got != fallback {
+ t.Errorf("envOr() = %v, want %v", got, fallback)
+ }
+
+ val := "set"
+ _ = os.Setenv(key, val)
+ defer func() { _ = os.Unsetenv(key) }()
+ if got := envOr(key, fallback); got != val {
+ t.Errorf("envOr() = %v, want %v", got, val)
+ }
+}
+
+func TestEnvIntOr(t *testing.T) {
+ key := "PINCHTAB_TEST_INT"
+ fallback := 42
+
+ _ = os.Unsetenv(key)
+ if got := envIntOr(key, fallback); got != fallback {
+ t.Errorf("envIntOr() = %v, want %v", got, fallback)
+ }
+
+ _ = os.Setenv(key, "100")
+ if got := envIntOr(key, fallback); got != 100 {
+ t.Errorf("envIntOr() = %v, want %v", got, 100)
+ }
+
+ _ = os.Setenv(key, "invalid")
+ if got := envIntOr(key, fallback); got != fallback {
+ t.Errorf("envIntOr() = %v, want %v", got, fallback)
+ }
+}
+
+func TestEnvBoolOr(t *testing.T) {
+ key := "PINCHTAB_TEST_BOOL"
+ fallback := true
+
+ _ = os.Unsetenv(key)
+ if got := envBoolOr(key, fallback); got != fallback {
+ t.Errorf("envBoolOr() = %v, want %v", got, fallback)
+ }
+
+ tests := []struct {
+ val string
+ want bool
+ }{
+ {"1", true}, {"true", true}, {"yes", true}, {"on", true},
+ {"0", false}, {"false", false}, {"no", false}, {"off", false},
+ {"garbage", true}, // should return fallback
+ }
+
+ for _, tt := range tests {
+ _ = os.Setenv(key, tt.val)
+ if got := envBoolOr(key, fallback); got != tt.want {
+ t.Errorf("envBoolOr(%q) = %v, want %v", tt.val, got, tt.want)
+ }
+ }
+}
+
+func TestMaskToken(t *testing.T) {
+ tests := []struct {
+ token string
+ want string
+ }{
+ {"", "(none)"},
+ {"short", "***"},
+ {"very-long-token-secret", "very...cret"},
+ }
+
+ for _, tt := range tests {
+ if got := MaskToken(tt.token); got != tt.want {
+ t.Errorf("MaskToken(%q) = %v, want %v", tt.token, got, tt.want)
+ }
+ }
+}
+
+func TestLoadConfigDefaults(t *testing.T) {
+ // Clear relevant env vars
+ _ = os.Unsetenv("BRIDGE_PORT")
+ _ = os.Unsetenv("BRIDGE_BIND")
+ _ = os.Unsetenv("CDP_URL")
+ _ = os.Unsetenv("BRIDGE_TOKEN")
+
+ cfg := Load()
+ if cfg.Port != "9867" {
+ t.Errorf("default Port = %v, want 9867", cfg.Port)
+ }
+ if cfg.Bind != "127.0.0.1" {
+ t.Errorf("default Bind = %v, want 127.0.0.1", cfg.Bind)
+ }
+}
+
+func TestLoadConfigEnvOverrides(t *testing.T) {
+ _ = os.Setenv("BRIDGE_PORT", "1234")
+ defer func() { _ = os.Unsetenv("BRIDGE_PORT") }()
+
+ cfg := Load()
+ if cfg.Port != "1234" {
+ t.Errorf("env Port = %v, want 1234", cfg.Port)
+ }
+}
+
+func TestDefaultFileConfig(t *testing.T) {
+ fc := DefaultFileConfig()
+ if fc.Port != "9867" {
+ t.Errorf("DefaultFileConfig.Port = %v, want 9867", fc.Port)
+ }
+ if *fc.Headless != true {
+ t.Errorf("DefaultFileConfig.Headless = %v, want true", *fc.Headless)
+ }
+}
+
+func TestLoadConfigFile(t *testing.T) {
+ tmpDir := t.TempDir()
+ configPath := filepath.Join(tmpDir, "config.json")
+ _ = os.Setenv("BRIDGE_CONFIG", configPath)
+ defer func() { _ = os.Unsetenv("BRIDGE_CONFIG") }()
+
+ // Create a dummy config file
+ configData := `{
+ "port": "8888",
+ "headless": false,
+ "timeoutSec": 60
+ }`
+ if err := os.WriteFile(configPath, []byte(configData), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ cfg := Load()
+ if cfg.Port != "8888" {
+ t.Errorf("file Port = %v, want 8888", cfg.Port)
+ }
+ if cfg.Headless != false {
+ t.Errorf("file Headless = %v, want false", cfg.Headless)
+ }
+ if cfg.ActionTimeout != 60*time.Second {
+ t.Errorf("file ActionTimeout = %v, want 60s", cfg.ActionTimeout)
+ }
+}
diff --git a/dashboard.go b/internal/dashboard/dashboard.go
similarity index 97%
rename from dashboard.go
rename to internal/dashboard/dashboard.go
index 6d62b57c..088b9910 100644
--- a/dashboard.go
+++ b/internal/dashboard/dashboard.go
@@ -1,4 +1,4 @@
-package main
+package dashboard
import (
"bufio"
@@ -11,6 +11,9 @@ import (
"strings"
"sync"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
)
type DashboardConfig struct {
@@ -48,7 +51,7 @@ type AgentEvent struct {
// InstanceLister returns running instances (provided by Orchestrator).
type InstanceLister interface {
- List() []Instance
+ List() []bridge.Instance
}
type Dashboard struct {
@@ -274,7 +277,7 @@ func (d *Dashboard) RegisterHandlers(mux *http.ServeMux) {
}
func (d *Dashboard) handleAgents(w http.ResponseWriter, r *http.Request) {
- jsonResp(w, 200, d.GetAgents())
+ web.JSON(w, 200, d.GetAgents())
}
func (d *Dashboard) handleSSE(w http.ResponseWriter, r *http.Request) {
@@ -390,7 +393,7 @@ func (d *Dashboard) TrackingMiddleware(observers []EventObserver, next http.Hand
return
}
- sw := &statusWriter{ResponseWriter: w, code: 200}
+ sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
next.ServeHTTP(sw, r)
evt := AgentEvent{
@@ -400,7 +403,7 @@ func (d *Dashboard) TrackingMiddleware(observers []EventObserver, next http.Hand
URL: r.URL.Query().Get("url"),
TabID: r.URL.Query().Get("tabId"),
Detail: actionDetail(r),
- Status: sw.code,
+ Status: sw.Code,
DurationMs: time.Since(start).Milliseconds(),
Timestamp: start,
}
diff --git a/dashboard/agents.css b/internal/dashboard/dashboard/agents.css
similarity index 100%
rename from dashboard/agents.css
rename to internal/dashboard/dashboard/agents.css
diff --git a/dashboard/agents.js b/internal/dashboard/dashboard/agents.js
similarity index 100%
rename from dashboard/agents.js
rename to internal/dashboard/dashboard/agents.js
diff --git a/dashboard/app.js b/internal/dashboard/dashboard/app.js
similarity index 100%
rename from dashboard/app.js
rename to internal/dashboard/dashboard/app.js
diff --git a/dashboard/base.css b/internal/dashboard/dashboard/base.css
similarity index 100%
rename from dashboard/base.css
rename to internal/dashboard/dashboard/base.css
diff --git a/dashboard/dashboard.html b/internal/dashboard/dashboard/dashboard.html
similarity index 100%
rename from dashboard/dashboard.html
rename to internal/dashboard/dashboard/dashboard.html
diff --git a/dashboard/pinchtab-headed-192.png b/internal/dashboard/dashboard/pinchtab-headed-192.png
similarity index 100%
rename from dashboard/pinchtab-headed-192.png
rename to internal/dashboard/dashboard/pinchtab-headed-192.png
diff --git a/dashboard/profiles.css b/internal/dashboard/dashboard/profiles.css
similarity index 100%
rename from dashboard/profiles.css
rename to internal/dashboard/dashboard/profiles.css
diff --git a/dashboard/profiles.js b/internal/dashboard/dashboard/profiles.js
similarity index 100%
rename from dashboard/profiles.js
rename to internal/dashboard/dashboard/profiles.js
diff --git a/dashboard/screencast.css b/internal/dashboard/dashboard/screencast.css
similarity index 100%
rename from dashboard/screencast.css
rename to internal/dashboard/dashboard/screencast.css
diff --git a/dashboard/screencast.js b/internal/dashboard/dashboard/screencast.js
similarity index 100%
rename from dashboard/screencast.js
rename to internal/dashboard/dashboard/screencast.js
diff --git a/dashboard/settings.css b/internal/dashboard/dashboard/settings.css
similarity index 100%
rename from dashboard/settings.css
rename to internal/dashboard/dashboard/settings.css
diff --git a/dashboard/settings.js b/internal/dashboard/dashboard/settings.js
similarity index 100%
rename from dashboard/settings.js
rename to internal/dashboard/dashboard/settings.js
diff --git a/dashboard/utils.js b/internal/dashboard/dashboard/utils.js
similarity index 100%
rename from dashboard/utils.js
rename to internal/dashboard/dashboard/utils.js
diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.go
new file mode 100644
index 00000000..f2207842
--- /dev/null
+++ b/internal/dashboard/dashboard_test.go
@@ -0,0 +1,110 @@
+package dashboard
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+)
+
+func TestDashboardRecordEvent(t *testing.T) {
+ d := NewDashboard(nil)
+ evt := AgentEvent{
+ AgentID: "agent1",
+ Action: "GET /test",
+ Timestamp: time.Now(),
+ }
+
+ d.RecordEvent(evt)
+
+ agents := d.GetAgents()
+ if len(agents) != 1 {
+ t.Fatalf("expected 1 agent, got %d", len(agents))
+ }
+ if agents[0].AgentID != "agent1" {
+ t.Errorf("expected agent1, got %s", agents[0].AgentID)
+ }
+ if agents[0].Status != "active" {
+ t.Errorf("expected active, got %s", agents[0].Status)
+ }
+}
+
+func TestDashboardSSE(t *testing.T) {
+ d := NewDashboard(nil)
+ mux := http.NewServeMux()
+ d.RegisterHandlers(mux)
+
+ // Since SSE is a long-running connection, we test the registration
+ go func() {
+ time.Sleep(100 * time.Millisecond)
+ d.RecordEvent(AgentEvent{AgentID: "agent1", Action: "test"})
+ }()
+
+ // We can't easily test the full SSE cycle with httptest.Recorder,
+ // but we can verify the handler runs and registers the connection.
+ d.mu.RLock()
+ initConns := len(d.sseConns)
+ d.mu.RUnlock()
+
+ if initConns != 0 {
+ t.Errorf("expected 0 connections, got %d", initConns)
+ }
+}
+
+func TestTrackingMiddleware(t *testing.T) {
+ d := NewDashboard(nil)
+ mux := http.NewServeMux()
+ mux.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ })
+
+ handler := d.TrackingMiddleware(nil, mux)
+
+ req := httptest.NewRequest("GET", "/test", nil)
+ req.Header.Set("X-Agent-Id", "agent-t")
+ w := httptest.NewRecorder()
+
+ handler.ServeHTTP(w, req)
+
+ agents := d.GetAgents()
+ if len(agents) != 1 {
+ t.Fatalf("expected 1 agent, got %d", len(agents))
+ }
+ if agents[0].AgentID != "agent-t" {
+ t.Errorf("expected agent-t, got %s", agents[0].AgentID)
+ }
+}
+
+func TestDashboardProfileIntegration(t *testing.T) {
+ profilesDir := t.TempDir()
+ profMgr := profiles.NewProfileManager(profilesDir)
+ dash := NewDashboard(nil)
+
+ var recorded bridge.ActionRecord
+ observer := func(evt AgentEvent) {
+ if evt.Profile == "prof1" {
+ recorded = bridge.ActionRecord{
+ Endpoint: evt.Action,
+ }
+ }
+ }
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/action", func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(200)
+ })
+
+ handler := dash.TrackingMiddleware([]EventObserver{observer}, mux)
+
+ req := httptest.NewRequest("POST", "/action?profile=prof1", nil)
+ w := httptest.NewRecorder()
+ handler.ServeHTTP(w, req)
+
+ if recorded.Endpoint != "POST /action" {
+ t.Errorf("expected POST /action, got %q", recorded.Endpoint)
+ }
+ _ = profMgr
+}
diff --git a/internal/handlers/actions.go b/internal/handlers/actions.go
new file mode 100644
index 00000000..99b2c02a
--- /dev/null
+++ b/internal/handlers/actions.go
@@ -0,0 +1,192 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {
+ var req bridge.ActionRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ ctx, resolvedTabID, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ if req.Ref != "" && req.NodeID == 0 && req.Selector == "" {
+ cache := h.Bridge.GetRefCache(resolvedTabID)
+ if cache != nil {
+ if nid, ok := cache.Refs[req.Ref]; ok {
+ req.NodeID = nid
+ }
+ }
+ if req.NodeID == 0 {
+ web.JSON(w, 400, map[string]string{
+ "error": fmt.Sprintf("ref %s not found - take a /snapshot first", req.Ref),
+ })
+ return
+ }
+ }
+
+ if req.Kind == "" {
+ kinds := h.Bridge.AvailableActions()
+ web.JSON(w, 400, map[string]string{
+ "error": fmt.Sprintf("missing required field 'kind' - valid values: %s", strings.Join(kinds, ", ")),
+ })
+ return
+ }
+
+ result, err := h.Bridge.ExecuteAction(tCtx, req.Kind, req)
+ if err != nil {
+ if strings.HasPrefix(err.Error(), "unknown action") {
+ kinds := h.Bridge.AvailableActions()
+ web.JSON(w, 400, map[string]string{
+ "error": fmt.Sprintf("%s - valid values: %s", err.Error(), strings.Join(kinds, ", ")),
+ })
+ return
+ }
+ web.Error(w, 500, fmt.Errorf("action %s: %w", req.Kind, err))
+ return
+ }
+
+ web.JSON(w, 200, result)
+}
+
+type actionsRequest struct {
+ TabID string `json:"tabId"`
+ Actions []bridge.ActionRequest `json:"actions"`
+ StopOnError bool `json:"stopOnError"`
+}
+
+type actionResult struct {
+ Index int `json:"index"`
+ Success bool `json:"success"`
+ Result map[string]any `json:"result,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+func (h *Handlers) HandleActions(w http.ResponseWriter, r *http.Request) {
+ var req actionsRequest
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ if len(req.Actions) == 0 {
+ web.Error(w, 400, fmt.Errorf("actions array is empty"))
+ return
+ }
+
+ ctx, resolvedTabID, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ results := make([]actionResult, 0, len(req.Actions))
+
+ for i, action := range req.Actions {
+ if action.TabID == "" {
+ action.TabID = resolvedTabID
+ } else if action.TabID != resolvedTabID {
+ ctx, resolvedTabID, err = h.Bridge.TabContext(action.TabID)
+ if err != nil {
+ results = append(results, actionResult{
+ Index: i, Success: false,
+ Error: fmt.Sprintf("tab not found: %v", err),
+ })
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+
+ if action.Ref != "" && action.NodeID == 0 && action.Selector == "" {
+ cache := h.Bridge.GetRefCache(resolvedTabID)
+ if cache != nil {
+ if nid, ok := cache.Refs[action.Ref]; ok {
+ action.NodeID = nid
+ }
+ }
+ if action.NodeID == 0 {
+ tCancel()
+ results = append(results, actionResult{
+ Index: i, Success: false,
+ Error: fmt.Sprintf("ref %s not found - take a /snapshot first", action.Ref),
+ })
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
+ }
+
+ if action.Kind == "" {
+ tCancel()
+ results = append(results, actionResult{
+ Index: i, Success: false, Error: "missing required field 'kind'",
+ })
+ if req.StopOnError {
+ break
+ }
+ continue
+ }
+
+ actionRes, err := h.Bridge.ExecuteAction(tCtx, action.Kind, action)
+ tCancel()
+
+ if err != nil {
+ results = append(results, actionResult{
+ Index: i, Success: false,
+ Error: fmt.Sprintf("action %s: %v", action.Kind, err),
+ })
+ if req.StopOnError {
+ break
+ }
+ } else {
+ results = append(results, actionResult{
+ Index: i, Success: true, Result: actionRes,
+ })
+ }
+
+ if i < len(req.Actions)-1 {
+ time.Sleep(50 * time.Millisecond)
+ }
+ }
+
+ web.JSON(w, 200, map[string]any{
+ "results": results,
+ "total": len(req.Actions),
+ "successful": countSuccessful(results),
+ "failed": len(req.Actions) - countSuccessful(results),
+ })
+}
+
+func countSuccessful(results []actionResult) int {
+ count := 0
+ for _, r := range results {
+ if r.Success {
+ count++
+ }
+ }
+ return count
+}
diff --git a/handler_cookies.go b/internal/handlers/cookies.go
similarity index 83%
rename from handler_cookies.go
rename to internal/handlers/cookies.go
index 09d641ad..c210693d 100644
--- a/handler_cookies.go
+++ b/internal/handlers/cookies.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"context"
@@ -11,16 +11,17 @@ import (
"github.com/chromedp/cdproto/cdp"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/web"
)
-func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleGetCookies(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
url := r.URL.Query().Get("url")
name := r.URL.Query().Get("name")
- ctx, _, err := b.TabContext(tabID)
+ ctx, _, err := h.Bridge.TabContext(tabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
@@ -39,7 +40,7 @@ func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
return err
}),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("get cookies: %w", err))
+ web.Error(w, 500, fmt.Errorf("get cookies: %w", err))
return
}
@@ -69,7 +70,7 @@ func (b *Bridge) handleGetCookies(w http.ResponseWriter, r *http.Request) {
}
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"url": url,
"cookies": result,
"count": len(result),
@@ -93,26 +94,26 @@ type cookieSetRequest struct {
Expires float64 `json:"expires"`
}
-func (b *Bridge) handleSetCookies(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleSetCookies(w http.ResponseWriter, r *http.Request) {
var req cookieRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.URL == "" {
- jsonErr(w, 400, fmt.Errorf("url is required"))
+ web.Error(w, 400, fmt.Errorf("url is required"))
return
}
if len(req.Cookies) == 0 {
- jsonErr(w, 400, fmt.Errorf("cookies array is empty"))
+ web.Error(w, 400, fmt.Errorf("cookies array is empty"))
return
}
- ctx, _, err := b.TabContext(req.TabID)
+ ctx, _, err := h.Bridge.TabContext(req.TabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
@@ -161,7 +162,7 @@ func (b *Bridge) handleSetCookies(w http.ResponseWriter, r *http.Request) {
}
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"set": successCount,
"failed": len(req.Cookies) - successCount,
"total": len(req.Cookies),
diff --git a/handler_actions_test.go b/internal/handlers/handler_actions_test.go
similarity index 74%
rename from handler_actions_test.go
rename to internal/handlers/handler_actions_test.go
index f9aab80a..664b0fab 100644
--- a/handler_actions_test.go
+++ b/internal/handlers/handler_actions_test.go
@@ -1,19 +1,37 @@
-package main
+package handlers
import (
"bytes"
+ "context"
"encoding/json"
+ "fmt"
"net/http/httptest"
"testing"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
)
+type failMockBridge struct {
+ bridge.BridgeAPI
+}
+
+func (m *failMockBridge) TabContext(tabID string) (context.Context, string, error) {
+ return nil, "", fmt.Errorf("tab not found")
+}
+
+func (m *failMockBridge) ListTargets() ([]*target.Info, error) {
+ return nil, fmt.Errorf("list targets failed")
+}
+
func TestHandleActions_EmptyArray(t *testing.T) {
- b := &Bridge{}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("POST", "/actions", bytes.NewReader([]byte(`{"actions": []}`)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- b.handleActions(w, req)
+ h.HandleActions(w, req)
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
@@ -29,7 +47,7 @@ func TestHandleActions_EmptyArray(t *testing.T) {
}
func TestHandleActions_NoTabError(t *testing.T) {
- b := newTestBridgeWithTabs()
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
body := `{
"actions": [
@@ -41,7 +59,7 @@ func TestHandleActions_NoTabError(t *testing.T) {
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- b.handleActions(w, req)
+ h.HandleActions(w, req)
if w.Code != 404 {
t.Errorf("expected 404 for no tab, got %d", w.Code)
@@ -49,12 +67,12 @@ func TestHandleActions_NoTabError(t *testing.T) {
}
func TestHandleGetCookies_NoTab(t *testing.T) {
- b := newTestBridgeWithTabs()
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("GET", "/cookies", nil)
w := httptest.NewRecorder()
- b.handleGetCookies(w, req)
+ h.HandleGetCookies(w, req)
if w.Code != 404 {
t.Errorf("expected 404 for no tab, got %d", w.Code)
@@ -62,14 +80,14 @@ func TestHandleGetCookies_NoTab(t *testing.T) {
}
func TestHandleSetCookies_EmptyURL(t *testing.T) {
- b := &Bridge{}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
body := `{"cookies": [{"name": "test", "value": "123"}]}`
req := httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(body)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
+ h.HandleSetCookies(w, req)
if w.Code != 400 {
t.Errorf("expected 400 for missing url, got %d", w.Code)
@@ -85,14 +103,14 @@ func TestHandleSetCookies_EmptyURL(t *testing.T) {
}
func TestHandleSetCookies_EmptyCookies(t *testing.T) {
- b := &Bridge{}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
body := `{"url": "https://example.com", "cookies": []}`
req := httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(body)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
+ h.HandleSetCookies(w, req)
if w.Code != 400 {
t.Errorf("expected 400 for empty cookies, got %d", w.Code)
@@ -100,12 +118,12 @@ func TestHandleSetCookies_EmptyCookies(t *testing.T) {
}
func TestHandleStealthStatus_NoTabs(t *testing.T) {
- b := newTestBridgeWithTabs()
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("GET", "/stealth/status", nil)
w := httptest.NewRecorder()
- b.handleStealthStatus(w, req)
+ h.HandleStealthStatus(w, req)
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
@@ -124,51 +142,23 @@ func TestHandleStealthStatus_NoTabs(t *testing.T) {
if len(features) == 0 {
t.Error("expected non-empty features")
}
-
- if _, ok := resp["score"].(float64); !ok {
- t.Error("expected score")
- }
}
func TestHandleFingerprintRotate_NoTab(t *testing.T) {
- b := newTestBridgeWithTabs()
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
body := `{"os": "windows", "browser": "chrome"}`
req := httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(body)))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
- b.handleFingerprintRotate(w, req)
+ h.HandleFingerprintRotate(w, req)
if w.Code != 404 {
t.Errorf("expected 404 for no tab, got %d", w.Code)
}
}
-func TestActionRegistry_HumanActions(t *testing.T) {
- b := &Bridge{}
- b.initActionRegistry()
- registry := b.actions
-
- if _, ok := registry[actionHumanClick]; !ok {
- t.Error("humanClick action not registered")
- }
-
- if _, ok := registry[actionHumanType]; !ok {
- t.Error("humanType action not registered")
- }
-
- expectedActions := []string{
- actionClick, actionType, actionFill, actionPress,
- actionFocus, actionHover, actionSelect, actionScroll,
- actionHumanClick, actionHumanType,
- }
-
- if len(registry) != len(expectedActions) {
- t.Errorf("expected %d actions, got %d", len(expectedActions), len(registry))
- }
-}
-
func TestCountSuccessful(t *testing.T) {
results := []actionResult{
{Success: true},
diff --git a/handler_cookies_test.go b/internal/handlers/handler_cookies_test.go
similarity index 75%
rename from handler_cookies_test.go
rename to internal/handlers/handler_cookies_test.go
index f10dc2fd..d5246e66 100644
--- a/handler_cookies_test.go
+++ b/internal/handlers/handler_cookies_test.go
@@ -1,18 +1,20 @@
-package main
+package handlers
import (
"bytes"
"encoding/json"
"net/http/httptest"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
func TestHandleSetCookies_InvalidJSON(t *testing.T) {
- b := &Bridge{}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
+ h.HandleSetCookies(w, req)
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
@@ -20,13 +22,12 @@ func TestHandleSetCookies_InvalidJSON(t *testing.T) {
}
func TestHandleSetCookies_NoTab(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
body := `{"url":"https://example.com","cookies":[{"name":"a","value":"b"}],"tabId":"nonexistent"}`
req := httptest.NewRequest("POST", "/cookies", bytes.NewReader([]byte(body)))
w := httptest.NewRecorder()
- b.handleSetCookies(w, req)
+ h.HandleSetCookies(w, req)
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
@@ -34,13 +35,11 @@ func TestHandleSetCookies_NoTab(t *testing.T) {
}
func TestHandleGetCookies_NameFilter(t *testing.T) {
-
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
+ h := New(&failMockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("GET", "/cookies?name=session_id&tabId=nonexistent", nil)
w := httptest.NewRecorder()
- b.handleGetCookies(w, req)
+ h.HandleGetCookies(w, req)
if w.Code != 404 {
t.Errorf("expected 404, got %d", w.Code)
diff --git a/handler_stealth_test.go b/internal/handlers/handler_stealth_test.go
similarity index 54%
rename from handler_stealth_test.go
rename to internal/handlers/handler_stealth_test.go
index 36a7e82b..649447ca 100644
--- a/handler_stealth_test.go
+++ b/internal/handlers/handler_stealth_test.go
@@ -1,18 +1,19 @@
-package main
+package handlers
import (
"bytes"
"net/http/httptest"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("GET", "/stealth/status", nil)
w := httptest.NewRecorder()
- b.handleStealthStatus(w, req)
+ h.HandleStealthStatus(w, req)
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
@@ -25,11 +26,11 @@ func TestHandleStealthStatus_NoTab_ReturnsStatic(t *testing.T) {
}
func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
- b := &Bridge{}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
req := httptest.NewRequest("POST", "/fingerprint/rotate", bytes.NewReader([]byte(`not json`)))
w := httptest.NewRecorder()
- b.handleFingerprintRotate(w, req)
+ h.HandleFingerprintRotate(w, req)
if w.Code != 400 {
t.Errorf("expected 400, got %d", w.Code)
@@ -37,7 +38,8 @@ func TestHandleFingerprintRotate_InvalidJSON(t *testing.T) {
}
func TestGenerateFingerprint_Windows(t *testing.T) {
- fp := generateFingerprint(fingerprintRequest{OS: "windows"})
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "windows"})
if fp.Platform != "Win32" {
t.Errorf("expected Win32, got %q", fp.Platform)
}
@@ -53,35 +55,32 @@ func TestGenerateFingerprint_Windows(t *testing.T) {
}
func TestGenerateFingerprint_Mac(t *testing.T) {
- fp := generateFingerprint(fingerprintRequest{OS: "mac"})
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "mac"})
if fp.Platform != "MacIntel" {
t.Errorf("expected MacIntel, got %q", fp.Platform)
}
}
func TestGenerateFingerprint_Random(t *testing.T) {
- fp := generateFingerprint(fingerprintRequest{OS: "random"})
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "random"})
validPlatforms := map[string]bool{"Win32": true, "MacIntel": true}
if !validPlatforms[fp.Platform] {
t.Errorf("unexpected platform %q", fp.Platform)
}
}
-func TestGenerateFingerprint_UnknownOS(t *testing.T) {
-
- fp := generateFingerprint(fingerprintRequest{OS: "freebsd"})
-
- _ = fp
-}
-
func TestGenerateFingerprint_WithBrowser(t *testing.T) {
- fp := generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
+ h := Handlers{Config: &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}}
+ fp := h.generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
if fp.UserAgent == "" {
t.Error("expected non-empty user agent")
}
}
func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
+ h := Handlers{}
features := map[string]bool{
"user_agent_override": true,
"languages_spoofed": true,
@@ -90,40 +89,28 @@ func TestGetStealthRecommendations_AllEnabled(t *testing.T) {
"canvas_noise": true,
"font_spoofing": true,
}
- recs := getStealthRecommendations(features)
+ recs := h.getStealthRecommendations(features)
if len(recs) != 1 || recs[0] != "Stealth mode is well configured" {
t.Errorf("expected well-configured message, got %v", recs)
}
}
func TestGetStealthRecommendations_NoneEnabled(t *testing.T) {
+ h := Handlers{}
features := map[string]bool{}
- recs := getStealthRecommendations(features)
+ recs := h.getStealthRecommendations(features)
if len(recs) != 6 {
t.Errorf("expected 6 recommendations, got %d: %v", len(recs), recs)
}
}
-func TestGetStealthRecommendations_Partial(t *testing.T) {
- features := map[string]bool{
- "user_agent_override": true,
- "timezone_spoofed": true,
- }
- recs := getStealthRecommendations(features)
-
- if len(recs) != 4 {
- t.Errorf("expected 4 recommendations, got %d: %v", len(recs), recs)
- }
-}
-
func TestSendStealthResponse_HighScore(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
features := map[string]bool{
"a": true, "b": true, "c": true, "d": true, "e": true,
}
w := httptest.NewRecorder()
- b.sendStealthResponse(w, features, "TestAgent/1.0")
+ h.sendStealthResponse(w, features, "TestAgent/1.0")
if w.Code != 200 {
t.Errorf("expected 200, got %d", w.Code)
@@ -134,41 +121,9 @@ func TestSendStealthResponse_HighScore(t *testing.T) {
}
}
-func TestSendStealthResponse_LowScore(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
- features := map[string]bool{
- "a": true, "b": false, "c": false, "d": false, "e": false,
- "f": false, "g": false, "h": false, "i": false, "j": false,
- }
- w := httptest.NewRecorder()
- b.sendStealthResponse(w, features, "")
-
- body := w.Body.String()
- if !searchString(body, `"level":"minimal"`) {
- t.Errorf("expected minimal level for 10%% score, got: %s", body)
- }
-}
-
-func TestSendStealthResponse_MediumScore(t *testing.T) {
- b := &Bridge{}
- b.TabManager = &TabManager{tabs: make(map[string]*TabEntry), snapshots: make(map[string]*refCache)}
-
- features := map[string]bool{
- "a": true, "b": true, "c": true, "d": true, "e": true,
- "f": true, "g": false, "h": false, "i": false, "j": false,
- }
- w := httptest.NewRecorder()
- b.sendStealthResponse(w, features, "")
-
- body := w.Body.String()
- if !searchString(body, `"level":"medium"`) {
- t.Errorf("expected medium level, got: %s", body)
- }
-}
-
func TestStaticStealthFeatures_HasEntries(t *testing.T) {
- features := staticStealthFeatures()
+ h := Handlers{Config: &config.RuntimeConfig{}}
+ features := h.staticStealthFeatures()
if len(features) == 0 {
t.Error("expected non-empty stealth features map")
}
diff --git a/internal/handlers/handler_test.go b/internal/handlers/handler_test.go
new file mode 100644
index 00000000..b44e8f86
--- /dev/null
+++ b/internal/handlers/handler_test.go
@@ -0,0 +1,120 @@
+package handlers
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type mockBridge struct {
+ bridge.BridgeAPI
+ failTab bool
+}
+
+func (m *mockBridge) TabContext(tabID string) (context.Context, string, error) {
+ if m.failTab {
+ return nil, "", fmt.Errorf("tab not found")
+ }
+ // We need a context that chromedp.Run won't complain about,
+ // even if it's not fully functional for real CDP commands.
+ ctx, _ := chromedp.NewContext(context.Background())
+ return ctx, "tab1", nil
+}
+
+func (m *mockBridge) ListTargets() ([]*target.Info, error) {
+ return []*target.Info{{TargetID: "tab1", Type: "page"}}, nil
+}
+
+func (m *mockBridge) AvailableActions() []string {
+ return []string{bridge.ActionClick, bridge.ActionType}
+}
+
+func (m *mockBridge) ExecuteAction(ctx context.Context, kind string, req bridge.ActionRequest) (map[string]any, error) {
+ return map[string]any{"success": true}, nil
+}
+
+func (m *mockBridge) CreateTab(url string) (string, context.Context, context.CancelFunc, error) {
+ ctx, cancel := chromedp.NewContext(context.Background())
+ return "new-tab", ctx, cancel, nil
+}
+
+func (m *mockBridge) CloseTab(tabID string) error {
+ if tabID == "fail" {
+ return fmt.Errorf("close failed")
+ }
+ return nil
+}
+
+func (m *mockBridge) DeleteRefCache(tabID string) {}
+
+func (m *mockBridge) TabLockInfo(tabID string) *bridge.LockInfo { return nil }
+
+func TestHandlers(t *testing.T) {
+ h := New(&mockBridge{}, nil, nil, nil, nil)
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, nil)
+}
+
+func TestHandleNavigate(t *testing.T) {
+ cfg := &config.RuntimeConfig{}
+ m := &mockBridge{}
+ h := New(m, cfg, nil, nil, nil)
+
+ // 1. Valid request
+ body := `{"url": "https://example.com"}`
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+ // Even with mock context, it might fail inside chromedp.Run if no browser is attached,
+ // but we're testing the handler logic around it.
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())
+ }
+
+ // 2. Missing URL
+ req = httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{}`)))
+ w = httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400 for missing url, got %d", w.Code)
+ }
+}
+
+func TestHandleTab(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+
+ // New Tab
+ body := `{"action": "new", "url": "about:blank"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 200 && w.Code != 500 {
+ t.Errorf("unexpected status %d", w.Code)
+ }
+
+ // 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 searchString(s, substr string) bool {
+ for i := 0; i <= len(s)-len(substr); i++ {
+ if s[i:i+len(substr)] == substr {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go
new file mode 100644
index 00000000..0fca4299
--- /dev/null
+++ b/internal/handlers/handlers.go
@@ -0,0 +1,68 @@
+package handlers
+
+import (
+ "net/http"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/dashboard"
+)
+
+type Handlers struct {
+ Bridge bridge.BridgeAPI
+ Config *config.RuntimeConfig
+ Profiles bridge.ProfileService
+ Dashboard *dashboard.Dashboard
+ Orchestrator bridge.OrchestratorService
+}
+
+func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService, d *dashboard.Dashboard, o bridge.OrchestratorService) *Handlers {
+ return &Handlers{
+ Bridge: b,
+ Config: cfg,
+ Profiles: p,
+ Dashboard: d,
+ Orchestrator: o,
+ }
+}
+
+func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {
+ mux.HandleFunc("GET /health", h.HandleHealth)
+ mux.HandleFunc("GET /tabs", h.HandleTabs)
+ mux.HandleFunc("GET /snapshot", h.HandleSnapshot)
+ mux.HandleFunc("GET /screenshot", h.HandleScreenshot)
+ mux.HandleFunc("GET /text", h.HandleText)
+ mux.HandleFunc("POST /navigate", h.HandleNavigate)
+ mux.HandleFunc("POST /action", h.HandleAction)
+ mux.HandleFunc("POST /actions", h.HandleActions)
+ mux.HandleFunc("POST /evaluate", h.HandleEvaluate)
+ mux.HandleFunc("POST /tab", h.HandleTab)
+ mux.HandleFunc("POST /tab/lock", h.HandleTabLock)
+ mux.HandleFunc("POST /tab/unlock", h.HandleTabUnlock)
+ mux.HandleFunc("GET /cookies", h.HandleGetCookies)
+ mux.HandleFunc("POST /cookies", h.HandleSetCookies)
+ mux.HandleFunc("GET /stealth/status", h.HandleStealthStatus)
+ mux.HandleFunc("POST /fingerprint/rotate", h.HandleFingerprintRotate)
+ mux.HandleFunc("GET /screencast", h.HandleScreencast)
+ mux.HandleFunc("GET /screencast/tabs", h.HandleScreencastAll)
+ mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ _, _ = w.Write([]byte(assets.WelcomeHTML))
+ })
+
+ if h.Profiles != nil {
+ h.Profiles.RegisterHandlers(mux)
+ }
+ if h.Dashboard != nil {
+ h.Dashboard.RegisterHandlers(mux)
+ }
+ if h.Orchestrator != nil && os.Getenv("BRIDGE_NO_DASHBOARD") == "" {
+ h.Orchestrator.RegisterHandlers(mux)
+ }
+
+ if doShutdown != nil {
+ mux.HandleFunc("POST /shutdown", h.HandleShutdown(doShutdown))
+ }
+}
diff --git a/internal/handlers/handlers_extra_test.go b/internal/handlers/handlers_extra_test.go
new file mode 100644
index 00000000..80a837c5
--- /dev/null
+++ b/internal/handlers/handlers_extra_test.go
@@ -0,0 +1,103 @@
+package handlers
+
+import (
+ "bytes"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestHandleHealth_Response(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("GET", "/health", nil)
+ w := httptest.NewRecorder()
+ h.HandleHealth(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {
+ t.Errorf("expected application/json, got %s", ct)
+ }
+}
+
+func TestHandleNavigate_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleNavigate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleEvaluate_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/evaluate", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleEvaluate(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_InvalidAction(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"action":"invalid"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleTab_CloseMissingID(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ body := `{"action":"close"}`
+ req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))
+ w := httptest.NewRecorder()
+ h.HandleTab(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleAction_InvalidJSON(t *testing.T) {
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ req := httptest.NewRequest("POST", "/action", bytes.NewReader([]byte(`not json`)))
+ w := httptest.NewRecorder()
+ h.HandleAction(w, req)
+ if w.Code != 400 {
+ t.Errorf("expected 400, got %d", w.Code)
+ }
+}
+
+func TestHandleShutdown_CallsFunc(t *testing.T) {
+ called := make(chan bool, 1)
+ doShutdown := func() { called <- true }
+ h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)
+ handler := h.HandleShutdown(doShutdown)
+ req := httptest.NewRequest("POST", "/shutdown", nil)
+ w := httptest.NewRecorder()
+ handler(w, req)
+ if w.Code != 200 {
+ t.Errorf("expected 200, got %d", w.Code)
+ }
+ select {
+ case <-called:
+ case <-time.After(500 * time.Millisecond):
+ t.Error("expected doShutdown to be called within 500ms")
+ }
+}
diff --git a/internal/handlers/health_tabs.go b/internal/handlers/health_tabs.go
new file mode 100644
index 00000000..0a6d5e19
--- /dev/null
+++ b/internal/handlers/health_tabs.go
@@ -0,0 +1,41 @@
+package handlers
+
+import (
+ "net/http"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (h *Handlers) HandleHealth(w http.ResponseWriter, r *http.Request) {
+ targets, err := h.Bridge.ListTargets()
+ if err != nil {
+ web.JSON(w, 200, map[string]any{"status": "disconnected", "error": err.Error(), "cdp": h.Config.CdpURL})
+ return
+ }
+ web.JSON(w, 200, map[string]any{"status": "ok", "tabs": len(targets), "cdp": h.Config.CdpURL})
+}
+
+func (h *Handlers) HandleTabs(w http.ResponseWriter, r *http.Request) {
+ targets, err := h.Bridge.ListTargets()
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+
+ tabs := make([]map[string]any, 0, len(targets))
+ for _, t := range targets {
+ entry := map[string]any{
+ "id": string(t.TargetID),
+ "url": t.URL,
+ "title": t.Title,
+ "type": t.Type,
+ }
+ if lock := h.Bridge.TabLockInfo(string(t.TargetID)); lock != nil {
+ entry["owner"] = lock.Owner
+ entry["lockedUntil"] = lock.ExpiresAt.Format(time.RFC3339)
+ }
+ tabs = append(tabs, entry)
+ }
+ web.JSON(w, 200, map[string]any{"tabs": tabs})
+}
diff --git a/internal/handlers/integration_test.go b/internal/handlers/integration_test.go
new file mode 100644
index 00000000..839c9ab9
--- /dev/null
+++ b/internal/handlers/integration_test.go
@@ -0,0 +1,76 @@
+package handlers
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/chromedp/cdproto/target"
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+type integrationMockBridge struct {
+ bridge.BridgeAPI
+ tabs map[string]context.Context
+}
+
+func (m *integrationMockBridge) TabContext(tabID string) (context.Context, string, error) {
+ if tabID == "" {
+ return context.Background(), "tab1", nil
+ }
+ ctx, ok := m.tabs[tabID]
+ if !ok {
+ return nil, "", fmt.Errorf("not found")
+ }
+ return ctx, tabID, nil
+}
+
+func (m *integrationMockBridge) ListTargets() ([]*target.Info, error) {
+ return []*target.Info{{TargetID: "tab1", Type: "page"}}, nil
+}
+
+func (m *integrationMockBridge) TabLockInfo(tabID string) *bridge.LockInfo {
+ return nil
+}
+
+func TestIntegration_RoutesRegistration(t *testing.T) {
+ b := &integrationMockBridge{tabs: make(map[string]context.Context)}
+ cfg := &config.RuntimeConfig{}
+ h := New(b, cfg, nil, nil, nil)
+
+ mux := http.NewServeMux()
+ h.RegisterRoutes(mux, func() {})
+
+ tests := []struct {
+ method string
+ path string
+ code int
+ }{
+ {"GET", "/health", 200},
+ {"GET", "/tabs", 200},
+ {"GET", "/welcome", 200},
+ {"POST", "/navigate", 400}, // missing body
+ }
+
+ for _, tt := range tests {
+ req := httptest.NewRequest(tt.method, tt.path, nil)
+ w := httptest.NewRecorder()
+ mux.ServeHTTP(w, req)
+ if w.Code != tt.code {
+ t.Errorf("%s %s expected %d, got %d", tt.method, tt.path, tt.code, w.Code)
+ }
+ }
+}
+
+func TestIntegration_StealthInjection(t *testing.T) {
+ b := bridge.New(context.Background(), context.Background(), &config.RuntimeConfig{})
+ b.StealthScript = assets.StealthScript
+
+ if b.StealthScript == "" {
+ t.Error("expected stealth script to be populated")
+ }
+}
diff --git a/lock_handler_test.go b/internal/handlers/lock_handler_test.go
similarity index 71%
rename from lock_handler_test.go
rename to internal/handlers/lock_handler_test.go
index 24d054f9..67c8ea22 100644
--- a/lock_handler_test.go
+++ b/internal/handlers/lock_handler_test.go
@@ -1,20 +1,26 @@
-package main
+package handlers
import (
"bytes"
+ "context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/config"
)
func TestHandleTabLock(t *testing.T) {
- b := &Bridge{locks: newLockManager()}
+ b := bridge.New(context.Background(), context.Background(), nil)
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a", "timeoutSec": 10})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
- b.handleTabLock(w, r)
+ h.HandleTabLock(w, r)
if w.Code != 200 {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
@@ -32,7 +38,7 @@ func TestHandleTabLock(t *testing.T) {
body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})
w = httptest.NewRecorder()
r, _ = http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
- b.handleTabLock(w, r)
+ h.HandleTabLock(w, r)
if w.Code != 409 {
t.Fatalf("expected 409, got %d", w.Code)
@@ -40,13 +46,14 @@ func TestHandleTabLock(t *testing.T) {
}
func TestHandleTabUnlock(t *testing.T) {
- b := &Bridge{locks: newLockManager()}
- _ = b.locks.Lock("t1", "agent-a", 0)
+ b := bridge.New(context.Background(), context.Background(), nil)
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
+ _ = b.Lock("t1", "agent-a", 10*time.Minute)
body, _ := json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-b"})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))
- b.handleTabUnlock(w, r)
+ h.HandleTabUnlock(w, r)
if w.Code != 409 {
t.Fatalf("expected 409, got %d", w.Code)
}
@@ -54,19 +61,20 @@ func TestHandleTabUnlock(t *testing.T) {
body, _ = json.Marshal(map[string]any{"tabId": "t1", "owner": "agent-a"})
w = httptest.NewRecorder()
r, _ = http.NewRequest("POST", "/tab/unlock", bytes.NewReader(body))
- b.handleTabUnlock(w, r)
+ h.HandleTabUnlock(w, r)
if w.Code != 200 {
t.Fatalf("expected 200, got %d", w.Code)
}
}
func TestHandleTabLockValidation(t *testing.T) {
- b := &Bridge{locks: newLockManager()}
+ b := bridge.New(context.Background(), context.Background(), nil)
+ h := New(b, &config.RuntimeConfig{}, nil, nil, nil)
body, _ := json.Marshal(map[string]any{"tabId": "t1"})
w := httptest.NewRecorder()
r, _ := http.NewRequest("POST", "/tab/lock", bytes.NewReader(body))
- b.handleTabLock(w, r)
+ h.HandleTabLock(w, r)
if w.Code != 400 {
t.Fatalf("expected 400, got %d", w.Code)
}
diff --git a/handler_lock_shutdown.go b/internal/handlers/lock_shutdown.go
similarity index 51%
rename from handler_lock_shutdown.go
rename to internal/handlers/lock_shutdown.go
index 5e0a80ff..686b506e 100644
--- a/handler_lock_shutdown.go
+++ b/internal/handlers/lock_shutdown.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"encoding/json"
@@ -6,67 +6,70 @@ import (
"log/slog"
"net/http"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
)
-func (b *Bridge) handleTabLock(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleTabLock(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
Owner string `json:"owner"`
TimeoutSec int `json:"timeoutSec"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID == "" || req.Owner == "" {
- jsonErr(w, 400, fmt.Errorf("tabId and owner required"))
+ web.Error(w, 400, fmt.Errorf("tabId and owner required"))
return
}
- timeout := defaultLockTimeout
+ timeout := bridge.DefaultLockTimeout
if req.TimeoutSec > 0 {
timeout = time.Duration(req.TimeoutSec) * time.Second
}
- if err := b.locks.Lock(req.TabID, req.Owner, timeout); err != nil {
- jsonErr(w, 409, err)
+ if err := h.Bridge.Lock(req.TabID, req.Owner, timeout); err != nil {
+ web.Error(w, 409, err)
return
}
- lock := b.locks.Get(req.TabID)
- jsonResp(w, 200, map[string]any{
+ lock := h.Bridge.TabLockInfo(req.TabID)
+ web.JSON(w, 200, map[string]any{
"locked": true,
"owner": lock.Owner,
"expiresAt": lock.ExpiresAt.Format(time.RFC3339),
})
}
-func (b *Bridge) handleTabUnlock(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleTabUnlock(w http.ResponseWriter, r *http.Request) {
var req struct {
TabID string `json:"tabId"`
Owner string `json:"owner"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
if req.TabID == "" || req.Owner == "" {
- jsonErr(w, 400, fmt.Errorf("tabId and owner required"))
+ web.Error(w, 400, fmt.Errorf("tabId and owner required"))
return
}
- if err := b.locks.Unlock(req.TabID, req.Owner); err != nil {
- jsonErr(w, 409, err)
+ if err := h.Bridge.Unlock(req.TabID, req.Owner); err != nil {
+ web.Error(w, 409, err)
return
}
- jsonResp(w, 200, map[string]any{"unlocked": true})
+ web.JSON(w, 200, map[string]any{"unlocked": true})
}
-func (b *Bridge) handleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {
+func (h *Handlers) HandleShutdown(shutdownFn func()) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
slog.Info("shutdown requested via API")
- jsonResp(w, 200, map[string]any{"status": "shutting down"})
+ web.JSON(w, 200, map[string]any{"status": "shutting down"})
go func() {
time.Sleep(100 * time.Millisecond)
diff --git a/handler_media.go b/internal/handlers/media.go
similarity index 61%
rename from handler_media.go
rename to internal/handlers/media.go
index 44e95efa..79f43bb1 100644
--- a/handler_media.go
+++ b/internal/handlers/media.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"context"
@@ -13,25 +13,28 @@ import (
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
)
-func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleScreenshot(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
output := r.URL.Query().Get("output")
reqNoAnim := r.URL.Query().Get("noAnimations") == "true"
- ctx, _, err := b.TabContext(tabID)
+ ctx, _, err := h.Bridge.TabContext(tabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
+ go web.CancelOnClientDone(r.Context(), tCancel)
- if reqNoAnim && !cfg.NoAnimations {
- disableAnimationsOnce(tCtx)
+ if reqNoAnim && !h.Config.NoAnimations {
+ bridge.DisableAnimationsOnce(tCtx)
}
var buf []byte
@@ -52,14 +55,14 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
return err
}),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("screenshot: %w", err))
+ web.Error(w, 500, fmt.Errorf("screenshot: %w", err))
return
}
if output == "file" {
- screenshotDir := filepath.Join(cfg.StateDir, "screenshots")
+ screenshotDir := filepath.Join(h.Config.StateDir, "screenshots")
if err := os.MkdirAll(screenshotDir, 0755); err != nil {
- jsonErr(w, 500, fmt.Errorf("create screenshot dir: %w", err))
+ web.Error(w, 500, fmt.Errorf("create screenshot dir: %w", err))
return
}
@@ -68,11 +71,11 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
filePath := filepath.Join(screenshotDir, filename)
if err := os.WriteFile(filePath, buf, 0644); err != nil {
- jsonErr(w, 500, fmt.Errorf("write screenshot: %w", err))
+ web.Error(w, 500, fmt.Errorf("write screenshot: %w", err))
return
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"path": filePath,
"size": len(buf),
"format": "jpeg",
@@ -89,39 +92,39 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
return
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"format": "jpeg",
"base64": base64.StdEncoding.EncodeToString(buf),
})
}
-func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
mode := r.URL.Query().Get("mode")
- ctx, _, err := b.TabContext(tabID)
+ ctx, _, err := h.Bridge.TabContext(tabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
+ go web.CancelOnClientDone(r.Context(), tCancel)
var text string
if mode == "raw" {
if err := chromedp.Run(tCtx,
chromedp.Evaluate(`document.body.innerText`, &text),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("text extract: %w", err))
+ web.Error(w, 500, fmt.Errorf("text extract: %w", err))
return
}
} else {
if err := chromedp.Run(tCtx,
- chromedp.Evaluate(readabilityJS, &text),
+ chromedp.Evaluate(assets.ReadabilityJS, &text),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("text extract: %w", err))
+ web.Error(w, 500, fmt.Errorf("text extract: %w", err))
return
}
}
@@ -132,7 +135,7 @@ func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
chromedp.Title(&title),
)
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"url": url,
"title": title,
"text": text,
diff --git a/internal/handlers/middleware.go b/internal/handlers/middleware.go
new file mode 100644
index 00000000..2d9a7a8a
--- /dev/null
+++ b/internal/handlers/middleware.go
@@ -0,0 +1,51 @@
+package handlers
+
+import (
+ "fmt"
+ "log/slog"
+ "net/http"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func LoggingMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ start := time.Now()
+ sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
+ next.ServeHTTP(sw, r)
+ slog.Info("request",
+ "method", r.Method,
+ "path", r.URL.Path,
+ "status", sw.Code,
+ "ms", time.Since(start).Milliseconds(),
+ )
+ })
+}
+
+func AuthMiddleware(cfg *config.RuntimeConfig, next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if cfg.Token != "" {
+ auth := r.Header.Get("Authorization")
+ if auth != "Bearer "+cfg.Token {
+ web.Error(w, 401, fmt.Errorf("unauthorized"))
+ return
+ }
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+func CorsMiddleware(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Access-Control-Allow-Origin", "*")
+ w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
+ w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
+ if r.Method == "OPTIONS" {
+ w.WriteHeader(204)
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
diff --git a/middleware_test.go b/internal/handlers/middleware_test.go
similarity index 56%
rename from middleware_test.go
rename to internal/handlers/middleware_test.go
index 97c4c8b2..759b2b98 100644
--- a/middleware_test.go
+++ b/internal/handlers/middleware_test.go
@@ -1,52 +1,19 @@
-package main
+package handlers
import (
- "encoding/json"
- "fmt"
"net/http"
"net/http/httptest"
"testing"
-)
-
-func TestJsonResp(t *testing.T) {
- w := httptest.NewRecorder()
- jsonResp(w, 200, map[string]string{"status": "ok"})
-
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
- if ct := w.Header().Get("Content-Type"); ct != "application/json" {
- t.Errorf("expected application/json, got %s", ct)
- }
- var body map[string]string
- _ = json.NewDecoder(w.Body).Decode(&body)
- if body["status"] != "ok" {
- t.Errorf("expected ok, got %s", body["status"])
- }
-}
-
-func TestJsonErr(t *testing.T) {
- w := httptest.NewRecorder()
- jsonErr(w, 500, fmt.Errorf("something broke"))
- if w.Code != 500 {
- t.Errorf("expected 500, got %d", w.Code)
- }
- var body map[string]string
- _ = json.NewDecoder(w.Body).Decode(&body)
- if body["error"] != "something broke" {
- t.Errorf("expected 'something broke', got %s", body["error"])
- }
-}
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
func TestAuthMiddleware_NoToken(t *testing.T) {
-
- origToken := cfg.Token
- cfg.Token = ""
- defer func() { cfg.Token = origToken }()
+ cfg := &config.RuntimeConfig{Token: ""}
called := false
- handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(200)
}))
@@ -61,12 +28,10 @@ func TestAuthMiddleware_NoToken(t *testing.T) {
}
func TestAuthMiddleware_ValidToken(t *testing.T) {
- origToken := cfg.Token
- cfg.Token = "secret123"
- defer func() { cfg.Token = origToken }()
+ cfg := &config.RuntimeConfig{Token: "secret123"}
called := false
- handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
w.WriteHeader(200)
}))
@@ -82,12 +47,10 @@ func TestAuthMiddleware_ValidToken(t *testing.T) {
}
func TestAuthMiddleware_InvalidToken(t *testing.T) {
- origToken := cfg.Token
- cfg.Token = "secret123"
- defer func() { cfg.Token = origToken }()
+ cfg := &config.RuntimeConfig{Token: "secret123"}
called := false
- handler := authMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := AuthMiddleware(cfg, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
}))
@@ -105,7 +68,7 @@ func TestAuthMiddleware_InvalidToken(t *testing.T) {
}
func TestCorsMiddleware(t *testing.T) {
- handler := corsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := CorsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}))
@@ -131,7 +94,7 @@ func TestCorsMiddleware(t *testing.T) {
}
func TestLoggingMiddleware(t *testing.T) {
- handler := loggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ handler := LoggingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(201)
}))
@@ -146,10 +109,10 @@ func TestLoggingMiddleware(t *testing.T) {
func TestStatusWriter(t *testing.T) {
w := httptest.NewRecorder()
- sw := &statusWriter{ResponseWriter: w, code: 200}
+ sw := &web.StatusWriter{ResponseWriter: w, Code: 200}
sw.WriteHeader(404)
- if sw.code != 404 {
- t.Errorf("expected 404, got %d", sw.code)
+ if sw.Code != 404 {
+ t.Errorf("expected 404, got %d", sw.Code)
}
}
diff --git a/internal/handlers/navigation.go b/internal/handlers/navigation.go
new file mode 100644
index 00000000..b4e82f2c
--- /dev/null
+++ b/internal/handlers/navigation.go
@@ -0,0 +1,201 @@
+package handlers
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+const maxBodySize = 1 << 20
+
+func (h *Handlers) HandleNavigate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ NewTab bool `json:"newTab"`
+ WaitTitle float64 `json:"waitTitle"`
+ Timeout float64 `json:"timeout"`
+ BlockImages *bool `json:"blockImages"`
+ BlockMedia *bool `json:"blockMedia"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+ if req.URL == "" {
+ web.Error(w, 400, fmt.Errorf("url required"))
+ return
+ }
+
+ titleWait := time.Duration(0)
+ if req.WaitTitle > 0 {
+ if req.WaitTitle > 30 {
+ req.WaitTitle = 30
+ }
+ titleWait = time.Duration(req.WaitTitle * float64(time.Second))
+ }
+
+ navTimeout := h.Config.NavigateTimeout
+ if req.Timeout > 0 {
+ if req.Timeout > 120 {
+ req.Timeout = 120
+ }
+ navTimeout = time.Duration(req.Timeout * float64(time.Second))
+ }
+
+ var blockPatterns []string
+ if req.BlockMedia != nil && *req.BlockMedia {
+ blockPatterns = bridge.MediaBlockPatterns
+ } else if req.BlockImages != nil && *req.BlockImages {
+ blockPatterns = bridge.ImageBlockPatterns
+ } else if req.BlockImages != nil && !*req.BlockImages {
+ blockPatterns = nil
+ } else if h.Config.BlockMedia {
+ blockPatterns = bridge.MediaBlockPatterns
+ } else if h.Config.BlockImages {
+ blockPatterns = bridge.ImageBlockPatterns
+ }
+
+ if req.NewTab {
+ newTargetID, newCtx, _, err := h.Bridge.CreateTab(req.URL)
+ if err != nil {
+ web.Error(w, 500, fmt.Errorf("new tab: %w", err))
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(newCtx, navTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ if blockPatterns != nil {
+ _ = bridge.SetResourceBlocking(tCtx, blockPatterns)
+ }
+
+ var url string
+ _ = chromedp.Run(tCtx, chromedp.Location(&url))
+ title := bridge.WaitForTitle(tCtx, titleWait)
+
+ targetID := ""
+ if c := chromedp.FromContext(newCtx); c != nil && c.Target != nil {
+ targetID = string(c.Target.TargetID)
+ } else {
+ targetID = newTargetID
+ }
+
+ web.JSON(w, 200, map[string]any{"tabId": targetID, "url": url, "title": title})
+ return
+ }
+
+ ctx, resolvedTabID, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, navTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ if blockPatterns != nil {
+ _ = bridge.SetResourceBlocking(tCtx, blockPatterns)
+ } else if h.Config.BlockImages {
+ _ = bridge.SetResourceBlocking(tCtx, nil)
+ }
+
+ if err := bridge.NavigatePage(tCtx, req.URL); err != nil {
+ web.Error(w, 500, fmt.Errorf("navigate: %w", err))
+ return
+ }
+
+ h.Bridge.DeleteRefCache(resolvedTabID)
+
+ var url string
+ _ = chromedp.Run(tCtx, chromedp.Location(&url))
+ title := bridge.WaitForTitle(tCtx, titleWait)
+
+ web.JSON(w, 200, map[string]any{"url": url, "title": title})
+}
+
+func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ TabID string `json:"tabId"`
+ Expression string `json:"expression"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+ if req.Expression == "" {
+ web.Error(w, 400, fmt.Errorf("expression required"))
+ return
+ }
+
+ ctx, _, err := h.Bridge.TabContext(req.TabID)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
+ defer tCancel()
+ go web.CancelOnClientDone(r.Context(), tCancel)
+
+ var result any
+ if err := chromedp.Run(tCtx, chromedp.Evaluate(req.Expression, &result)); err != nil {
+ web.Error(w, 500, fmt.Errorf("evaluate: %w", err))
+ return
+ }
+
+ web.JSON(w, 200, map[string]any{"result": result})
+}
+
+const (
+ tabActionNew = "new"
+ tabActionClose = "close"
+)
+
+func (h *Handlers) HandleTab(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Action string `json:"action"`
+ TabID string `json:"tabId"`
+ URL string `json:"url"`
+ }
+ if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
+ return
+ }
+
+ switch req.Action {
+ case tabActionNew:
+ newTargetID, ctx, _, err := h.Bridge.CreateTab(req.URL)
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+
+ var curURL, title string
+ _ = chromedp.Run(ctx, chromedp.Location(&curURL), chromedp.Title(&title))
+ web.JSON(w, 200, map[string]any{"tabId": newTargetID, "url": curURL, "title": title})
+
+ case tabActionClose:
+ if req.TabID == "" {
+ web.Error(w, 400, fmt.Errorf("tabId required"))
+ return
+ }
+
+ if err := h.Bridge.CloseTab(req.TabID); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]any{"closed": true})
+
+ default:
+ web.Error(w, 400, fmt.Errorf("action must be 'new' or 'close'"))
+ }
+}
diff --git a/proxy_ws.go b/internal/handlers/proxy_ws.go
similarity index 90%
rename from proxy_ws.go
rename to internal/handlers/proxy_ws.go
index 5c733783..d12c47ae 100644
--- a/proxy_ws.go
+++ b/internal/handlers/proxy_ws.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"io"
@@ -8,9 +8,9 @@ import (
"strings"
)
-// proxyWebSocket does a raw TCP tunnel for WebSocket connections.
+// ProxyWebSocket does a raw TCP tunnel for WebSocket connections.
// This is the simplest approach — no frame parsing, just bidirectional copy.
-func proxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
+func ProxyWebSocket(w http.ResponseWriter, r *http.Request, targetURL string) {
wsTarget := strings.Replace(targetURL, "http://", "", 1)
wsTarget = strings.Replace(wsTarget, "https://", "", 1)
diff --git a/screencast.go b/internal/handlers/screencast.go
similarity index 73%
rename from screencast.go
rename to internal/handlers/screencast.go
index 99234ff3..a7332cfd 100644
--- a/screencast.go
+++ b/internal/handlers/screencast.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"context"
@@ -10,38 +10,27 @@ import (
"time"
"github.com/chromedp/cdproto/page"
- "github.com/chromedp/cdproto/target"
"github.com/chromedp/chromedp"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
+ "github.com/pinchtab/pinchtab/internal/web"
)
-// handleScreencast upgrades to WebSocket and streams screencast frames for a tab.
+// HandleScreencast upgrades to WebSocket and streams screencast frames for a tab.
// Query params: tabId (required), quality (1-100, default 40), maxWidth (default 800), fps (1-30, default 5)
-func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleScreencast(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
if tabID == "" {
-
- b.mu.RLock()
- for id := range b.tabs {
- tabID = id
- break
+ targets, err := h.Bridge.ListTargets()
+ if err == nil && len(targets) > 0 {
+ tabID = string(targets[0].TargetID)
}
- b.mu.RUnlock()
}
- b.mu.RLock()
- tab, ok := b.tabs[tabID]
- b.mu.RUnlock()
-
- if !ok {
- tabCtx, _ := chromedp.NewContext(b.browserCtx, chromedp.WithTargetID(target.ID(tabID)))
-
- if err := chromedp.Run(tabCtx); err != nil {
- http.Error(w, "tab not found", 404)
- return
- }
- tab = &TabEntry{ctx: tabCtx}
+ ctx, _, err := h.Bridge.TabContext(tabID)
+ if err != nil {
+ http.Error(w, "tab not found", 404)
+ return
}
quality := queryParamInt(r, "quality", 30)
@@ -60,7 +49,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
}
defer func() { _ = conn.Close() }()
- ctx := tab.ctx
if ctx == nil {
return
}
@@ -74,7 +62,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
chromedp.ListenTarget(ctx, func(ev interface{}) {
switch e := ev.(type) {
case *page.EventScreencastFrame:
-
go func() {
_ = chromedp.Run(ctx,
chromedp.ActionFunc(func(c context.Context) error {
@@ -97,7 +84,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
select {
case frameCh <- data:
default:
-
}
}
})
@@ -148,7 +134,6 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
case <-done:
return
case <-time.After(10 * time.Second):
-
if err := wsutil.WriteServerMessage(conn, ws.OpPing, nil); err != nil {
return
}
@@ -156,39 +141,22 @@ func (b *Bridge) handleScreencast(w http.ResponseWriter, r *http.Request) {
}
}
-// handleScreencastAll returns info for building a multi-tab screencast view.
-// Uses CDP target discovery to find ALL tabs, not just ones in bridge.tabs.
-func (b *Bridge) handleScreencastAll(w http.ResponseWriter, r *http.Request) {
+// HandleScreencastAll returns info for building a multi-tab screencast view.
+func (h *Handlers) HandleScreencastAll(w http.ResponseWriter, r *http.Request) {
type tabInfo struct {
ID string `json:"id"`
URL string `json:"url,omitempty"`
Title string `json:"title,omitempty"`
}
- ctx := b.browserCtx
- if ctx == nil {
- jsonResp(w, 200, []tabInfo{})
- return
- }
-
- targets, err := target.GetTargets().Do(ctx)
+ targets, err := h.Bridge.ListTargets()
if err != nil {
-
- b.mu.RLock()
- defer b.mu.RUnlock()
- tabs := make([]tabInfo, 0, len(b.tabs))
- for id := range b.tabs {
- tabs = append(tabs, tabInfo{ID: id})
- }
- jsonResp(w, 200, tabs)
+ web.JSON(w, 200, []tabInfo{})
return
}
tabs := make([]tabInfo, 0)
for _, t := range targets {
- if t.Type != "page" {
- continue
- }
tabs = append(tabs, tabInfo{
ID: string(t.TargetID),
URL: t.URL,
@@ -196,7 +164,7 @@ func (b *Bridge) handleScreencastAll(w http.ResponseWriter, r *http.Request) {
})
}
- jsonResp(w, 200, tabs)
+ web.JSON(w, 200, tabs)
}
func queryParamInt(r *http.Request, key string, def int) int {
diff --git a/handler_snapshot.go b/internal/handlers/snapshot.go
similarity index 76%
rename from handler_snapshot.go
rename to internal/handlers/snapshot.go
index 54f977b3..7722672e 100644
--- a/handler_snapshot.go
+++ b/internal/handlers/snapshot.go
@@ -1,4 +1,4 @@
-package main
+package handlers
import (
"context"
@@ -11,10 +11,12 @@ import (
"time"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/web"
"gopkg.in/yaml.v3"
)
-func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
filter := r.URL.Query().Get("filter")
doDiff := r.URL.Query().Get("diff") == "true"
@@ -38,18 +40,18 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
}
}
- ctx, resolvedTabID, err := b.TabContext(tabID)
+ ctx, resolvedTabID, err := h.Bridge.TabContext(tabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
- tCtx, tCancel := context.WithTimeout(ctx, cfg.ActionTimeout)
+ tCtx, tCancel := context.WithTimeout(ctx, h.Config.ActionTimeout)
defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
+ go web.CancelOnClientDone(r.Context(), tCancel)
- if reqNoAnim && !cfg.NoAnimations {
- disableAnimationsOnce(tCtx)
+ if reqNoAnim && !h.Config.NoAnimations {
+ bridge.DisableAnimationsOnce(tCtx)
}
var rawResult json.RawMessage
@@ -59,15 +61,15 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
"Accessibility.getFullAXTree", nil, &rawResult)
}),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("a11y tree: %w", err))
+ web.Error(w, 500, fmt.Errorf("a11y tree: %w", err))
return
}
var treeResp struct {
- Nodes []rawAXNode `json:"nodes"`
+ Nodes []bridge.RawAXNode `json:"nodes"`
}
if err := json.Unmarshal(rawResult, &treeResp); err != nil {
- jsonErr(w, 500, fmt.Errorf("parse a11y tree: %w", err))
+ web.Error(w, 500, fmt.Errorf("parse a11y tree: %w", err))
return
}
@@ -75,9 +77,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
var scopeNodeID int64
if err := chromedp.Run(tCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
-
p := map[string]any{"nodeId": 0, "selector": selector}
- // First get the document node
var docResult json.RawMessage
if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getDocument", map[string]any{"depth": 0}, &docResult); err != nil {
return fmt.Errorf("get document: %w", err)
@@ -104,7 +104,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
if qr.NodeID == 0 {
return fmt.Errorf("selector %q not found", selector)
}
- // Resolve DOM nodeId to backendNodeId
var descResult json.RawMessage
if err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.describeNode", map[string]any{"nodeId": qr.NodeID}, &descResult); err != nil {
return fmt.Errorf("describe node: %w", err)
@@ -121,29 +120,28 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
return nil
}),
); err != nil {
- jsonErr(w, 400, fmt.Errorf("selector: %w", err))
+ web.Error(w, 400, fmt.Errorf("selector: %w", err))
return
}
- treeResp.Nodes = filterSubtree(treeResp.Nodes, scopeNodeID)
+ treeResp.Nodes = bridge.FilterSubtree(treeResp.Nodes, scopeNodeID)
}
- flat, refs := buildSnapshot(treeResp.Nodes, filter, maxDepth)
+ flat, refs := bridge.BuildSnapshot(treeResp.Nodes, filter, maxDepth)
truncated := false
if maxTokens > 0 {
- flat, truncated = truncateToTokens(flat, maxTokens, format)
+ flat, truncated = bridge.TruncateToTokens(flat, maxTokens, format)
}
- // Get previous snapshot for diff before overwriting cache
- var prevNodes []A11yNode
+ var prevNodes []bridge.A11yNode
if doDiff {
- if prev := b.GetRefCache(resolvedTabID); prev != nil {
- prevNodes = prev.nodes
+ if prev := h.Bridge.GetRefCache(resolvedTabID); prev != nil {
+ prevNodes = prev.Nodes
}
}
- b.SetRefCache(resolvedTabID, &refCache{refs: refs, nodes: flat})
+ h.Bridge.SetRefCache(resolvedTabID, &bridge.RefCache{Refs: refs, Nodes: flat})
var url, title string
_ = chromedp.Run(tCtx,
@@ -152,10 +150,9 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
)
if output == "file" {
-
- snapshotDir := filepath.Join(cfg.StateDir, "snapshots")
+ snapshotDir := filepath.Join(h.Config.StateDir, "snapshots")
if err := os.MkdirAll(snapshotDir, 0755); err != nil {
- jsonErr(w, 500, fmt.Errorf("create snapshot dir: %w", err))
+ web.Error(w, 500, fmt.Errorf("create snapshot dir: %w", err))
return
}
@@ -168,7 +165,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
filename = fmt.Sprintf("snapshot-%s.txt", timestamp)
textContent := fmt.Sprintf("# %s\n# %s\n# %d nodes\n# %s\n\n%s",
title, url, len(flat), time.Now().Format(time.RFC3339),
- formatSnapshotText(flat))
+ bridge.FormatSnapshotText(flat))
content = []byte(textContent)
case "yaml":
filename = fmt.Sprintf("snapshot-%s.yaml", timestamp)
@@ -180,7 +177,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
"count": len(flat),
}
if doDiff && prevNodes != nil {
- added, changed, removed := diffSnapshot(prevNodes, flat)
+ added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)
data["diff"] = true
data["added"] = added
data["changed"] = changed
@@ -195,7 +192,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
var err error
content, err = yaml.Marshal(data)
if err != nil {
- jsonErr(w, 500, fmt.Errorf("marshal yaml: %w", err))
+ web.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
return
}
default:
@@ -208,7 +205,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
"count": len(flat),
}
if doDiff && prevNodes != nil {
- added, changed, removed := diffSnapshot(prevNodes, flat)
+ added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)
data["diff"] = true
data["added"] = added
data["changed"] = changed
@@ -223,7 +220,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
var err error
content, err = json.MarshalIndent(data, "", " ")
if err != nil {
- jsonErr(w, 500, fmt.Errorf("marshal snapshot: %w", err))
+ web.Error(w, 500, fmt.Errorf("marshal snapshot: %w", err))
return
}
}
@@ -231,18 +228,17 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
filePath := filepath.Join(snapshotDir, filename)
if outputPath != "" {
filePath = outputPath
-
if err := os.MkdirAll(filepath.Dir(filePath), 0755); err != nil {
- jsonErr(w, 500, fmt.Errorf("create output dir: %w", err))
+ web.Error(w, 500, fmt.Errorf("create output dir: %w", err))
return
}
}
if err := os.WriteFile(filePath, content, 0644); err != nil {
- jsonErr(w, 500, fmt.Errorf("write snapshot: %w", err))
+ web.Error(w, 500, fmt.Errorf("write snapshot: %w", err))
return
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"path": filePath,
"size": len(content),
"format": format,
@@ -252,8 +248,8 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
}
if doDiff && prevNodes != nil {
- added, changed, removed := diffSnapshot(prevNodes, flat)
- jsonResp(w, 200, map[string]any{
+ added, changed, removed := bridge.DiffSnapshot(prevNodes, flat)
+ web.JSON(w, 200, map[string]any{
"url": url,
"title": title,
"diff": true,
@@ -272,7 +268,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
switch format {
case "compact":
-
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(200)
_, _ = fmt.Fprintf(w, "# %s | %s | %d nodes", title, url, len(flat))
@@ -280,12 +275,12 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
_, _ = fmt.Fprintf(w, " (truncated to ~%d tokens)", maxTokens)
}
_, _ = w.Write([]byte("\n"))
- _, _ = w.Write([]byte(formatSnapshotCompact(flat)))
+ _, _ = w.Write([]byte(bridge.FormatSnapshotCompact(flat)))
case "text":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(200)
_, _ = fmt.Fprintf(w, "# %s\n# %s\n# %d nodes\n\n", title, url, len(flat))
- _, _ = w.Write([]byte(formatSnapshotText(flat)))
+ _, _ = w.Write([]byte(bridge.FormatSnapshotText(flat)))
case "yaml":
data := map[string]any{
"url": url,
@@ -295,7 +290,7 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
}
yamlContent, err := yaml.Marshal(data)
if err != nil {
- jsonErr(w, 500, fmt.Errorf("marshal yaml: %w", err))
+ web.Error(w, 500, fmt.Errorf("marshal yaml: %w", err))
return
}
w.Header().Set("Content-Type", "text/yaml; charset=utf-8")
@@ -312,6 +307,6 @@ func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
resp["truncated"] = true
resp["maxTokens"] = maxTokens
}
- jsonResp(w, 200, resp)
+ web.JSON(w, 200, resp)
}
}
diff --git a/handler_stealth.go b/internal/handlers/stealth.go
similarity index 81%
rename from handler_stealth.go
rename to internal/handlers/stealth.go
index 377ed051..3ad68938 100644
--- a/handler_stealth.go
+++ b/internal/handlers/stealth.go
@@ -1,26 +1,24 @@
-package main
+package handlers
import (
"context"
"encoding/json"
"fmt"
+ "log/slog"
"math/rand"
"net/http"
"time"
- "log/slog"
-
"github.com/chromedp/cdproto/emulation"
"github.com/chromedp/cdproto/page"
"github.com/chromedp/chromedp"
+ "github.com/pinchtab/pinchtab/internal/web"
)
-func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
-
- ctx, _, err := b.TabContext("")
+func (h *Handlers) HandleStealthStatus(w http.ResponseWriter, r *http.Request) {
+ ctx, _, err := h.Bridge.TabContext("")
if err != nil {
-
- b.sendStealthResponse(w, staticStealthFeatures(), "")
+ h.sendStealthResponse(w, h.staticStealthFeatures(), "")
return
}
@@ -50,7 +48,7 @@ func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
features := map[string]bool{
"automation_controlled": !result.WebDriver,
"webdriver_hidden": !result.WebDriver,
- "chrome_headless_new": cfg.Headless,
+ "chrome_headless_new": h.Config.Headless,
"user_agent_override": result.UserAgent != "",
"webgl_vendor_override": true,
"plugins_spoofed": result.Plugins > 0,
@@ -63,18 +61,18 @@ func (b *Bridge) handleStealthStatus(w http.ResponseWriter, r *http.Request) {
"hardware_concurrency": result.HardwareConcurrency > 0,
"device_memory": result.DeviceMemory > 0,
}
- b.sendStealthResponse(w, features, result.UserAgent)
+ h.sendStealthResponse(w, features, result.UserAgent)
return
}
- b.sendStealthResponse(w, staticStealthFeatures(), "")
+ h.sendStealthResponse(w, h.staticStealthFeatures(), "")
}
-func staticStealthFeatures() map[string]bool {
+func (h *Handlers) staticStealthFeatures() map[string]bool {
return map[string]bool{
"automation_controlled": true,
"webdriver_hidden": true,
- "chrome_headless_new": cfg.Headless,
+ "chrome_headless_new": h.Config.Headless,
"user_agent_override": true,
"webgl_vendor_override": true,
"plugins_spoofed": true,
@@ -89,9 +87,8 @@ func staticStealthFeatures() map[string]bool {
}
}
-func (b *Bridge) sendStealthResponse(w http.ResponseWriter, features map[string]bool, userAgent string) {
+func (h *Handlers) sendStealthResponse(w http.ResponseWriter, features map[string]bool, userAgent string) {
chromeFlags := []string{
-
"--disable-features=IsolateOrigins,site-per-process",
"--disable-site-isolation-trials",
"--disable-web-security",
@@ -123,30 +120,31 @@ func (b *Bridge) sendStealthResponse(w http.ResponseWriter, features map[string]
level = "minimal"
}
- if userAgent == "" && len(b.tabs) > 0 {
- for _, tab := range b.tabs {
- ctx, cancel := context.WithTimeout(tab.ctx, 1*time.Second)
- _ = chromedp.Run(ctx, chromedp.Evaluate(`navigator.userAgent`, &userAgent))
- cancel()
- if userAgent != "" {
- break
+ if userAgent == "" {
+ targets, err := h.Bridge.ListTargets()
+ if err == nil && len(targets) > 0 {
+ ctx, _, _ := h.Bridge.TabContext(string(targets[0].TargetID))
+ if ctx != nil {
+ tCtx, cancel := context.WithTimeout(ctx, 1*time.Second)
+ _ = chromedp.Run(tCtx, chromedp.Evaluate(`navigator.userAgent`, &userAgent))
+ cancel()
}
}
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"level": level,
"score": stealthScore,
"features": features,
"chrome_flags": chromeFlags,
- "headless_mode": cfg.Headless,
+ "headless_mode": h.Config.Headless,
"user_agent": userAgent,
- "profile_path": cfg.ProfileDir,
- "recommendations": getStealthRecommendations(features),
+ "profile_path": h.Config.ProfileDir,
+ "recommendations": h.getStealthRecommendations(features),
})
}
-func getStealthRecommendations(features map[string]bool) []string {
+func (h *Handlers) getStealthRecommendations(features map[string]bool) []string {
recommendations := []string{}
if !features["user_agent_override"] {
@@ -159,7 +157,7 @@ func getStealthRecommendations(features map[string]bool) []string {
recommendations = append(recommendations, "Block WebRTC to prevent IP leaks")
}
if !features["timezone_spoofed"] {
- recommendations = append(recommendations, "Spoof cfg.Timezone to match target locale")
+ recommendations = append(recommendations, "Spoof timezone to match target locale")
}
if !features["canvas_noise"] {
recommendations = append(recommendations, "Add canvas fingerprint noise")
@@ -188,27 +186,26 @@ type fingerprintRequest struct {
Audio bool `json:"audio"`
}
-func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request) {
+func (h *Handlers) HandleFingerprintRotate(w http.ResponseWriter, r *http.Request) {
var req fingerprintRequest
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBodySize)).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("decode: %w", err))
+ web.Error(w, 400, fmt.Errorf("decode: %w", err))
return
}
- ctx, _, err := b.TabContext(req.TabID)
+ ctx, _, err := h.Bridge.TabContext(req.TabID)
if err != nil {
- jsonErr(w, 404, err)
+ web.Error(w, 404, err)
return
}
- fp := generateFingerprint(req)
+ fp := h.generateFingerprint(req)
tCtx, tCancel := context.WithTimeout(ctx, 5*time.Second)
defer tCancel()
if err := chromedp.Run(tCtx,
chromedp.ActionFunc(func(ctx context.Context) error {
-
err := emulation.SetUserAgentOverride(fp.UserAgent).
WithPlatform(fp.Platform).
WithAcceptLanguage(fp.Language).
@@ -219,7 +216,7 @@ func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request)
return nil
}),
); err != nil {
- jsonErr(w, 500, fmt.Errorf("CDP UA override: %w", err))
+ web.Error(w, 500, fmt.Errorf("CDP UA override: %w", err))
return
}
@@ -242,11 +239,10 @@ func (b *Bridge) handleFingerprintRotate(w http.ResponseWriter, r *http.Request)
}),
chromedp.Evaluate(script, nil),
); err != nil {
-
slog.Warn("JS fingerprint extras failed", "err", err)
}
- jsonResp(w, 200, map[string]any{
+ web.JSON(w, 200, map[string]any{
"fingerprint": fp,
"status": "rotated",
})
@@ -264,25 +260,25 @@ type fingerprint struct {
Memory int `json:"memory"`
}
-func generateFingerprint(req fingerprintRequest) fingerprint {
+func (h *Handlers) generateFingerprint(req fingerprintRequest) fingerprint {
fp := fingerprint{}
osConfigs := map[string]map[string]fingerprint{
"windows": {
"chrome": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", cfg.ChromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.Config.ChromeVersion),
Platform: "Win32",
Vendor: "Google Inc.",
},
"edge": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s", cfg.ChromeVersion, cfg.ChromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36 Edg/%s", h.Config.ChromeVersion, h.Config.ChromeVersion),
Platform: "Win32",
Vendor: "Google Inc.",
},
},
"mac": {
"chrome": {
- UserAgent: fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", cfg.ChromeVersion),
+ UserAgent: fmt.Sprintf("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/%s Safari/537.36", h.Config.ChromeVersion),
Platform: "MacIntel",
Vendor: "Google Inc.",
},
diff --git a/internal/handlers/stealth_test.go b/internal/handlers/stealth_test.go
new file mode 100644
index 00000000..56fb742d
--- /dev/null
+++ b/internal/handlers/stealth_test.go
@@ -0,0 +1,46 @@
+package handlers
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/assets"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+func TestStealthScript_Content(t *testing.T) {
+ if assets.StealthScript == "" {
+ t.Fatal("StealthScript is empty")
+ }
+ if !strings.Contains(assets.StealthScript, "navigator") || !strings.Contains(assets.StealthScript, "webdriver") {
+ t.Error("stealth script missing webdriver protection")
+ }
+}
+
+func TestGetStealthRecommendations(t *testing.T) {
+ h := Handlers{}
+ features := map[string]bool{
+ "user_agent_override": true,
+ }
+ recs := h.getStealthRecommendations(features)
+ found := false
+ for _, r := range recs {
+ if strings.Contains(r, "Accept-Language") {
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Error("expected recommendation for Accept-Language spoofing")
+ }
+}
+
+func TestGenerateFingerprint_Config(t *testing.T) {
+ cfg := &config.RuntimeConfig{ChromeVersion: "120.0.0.0"}
+ h := Handlers{Config: cfg}
+
+ fp := h.generateFingerprint(fingerprintRequest{OS: "windows", Browser: "chrome"})
+ if !strings.Contains(fp.UserAgent, "120.0.0.0") {
+ t.Errorf("expected User-Agent to contain Chrome version 120.0.0.0, got %q", fp.UserAgent)
+ }
+}
diff --git a/human.go b/internal/human/human.go
similarity index 81%
rename from human.go
rename to internal/human/human.go
index b2264768..ad5f199f 100644
--- a/human.go
+++ b/internal/human/human.go
@@ -1,4 +1,4 @@
-package main
+package human
import (
"context"
@@ -13,20 +13,14 @@ import (
"github.com/chromedp/chromedp"
)
-// humanRand is the seeded random source for human simulation.
-// Initialized in main() alongside the stealth seed for reproducibility.
var humanRand = rand.New(rand.NewSource(time.Now().UnixNano()))
-// SetHumanRandSeed sets the human simulation random seed for reproducible behavior.
func SetHumanRandSeed(seed int64) {
humanRand = rand.New(rand.NewSource(seed))
}
-// humanMouseMove performs natural mouse movement with bezier curves
-func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
-
+func MouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
distance := math.Sqrt((toX-fromX)*(toX-fromX) + (toY-fromY)*(toY-fromY))
-
baseDuration := 100 + (distance/2000)*200
duration := baseDuration + float64(humanRand.Intn(100))
@@ -75,9 +69,7 @@ func humanMouseMove(ctx context.Context, fromX, fromY, toX, toY float64) error {
return nil
}
-// humanClick performs a click with natural mouse movement and timing
-func humanClick(ctx context.Context, x, y float64) error {
-
+func Click(ctx context.Context, x, y float64) error {
startOffsetX := (humanRand.Float64()-0.5)*200 + 50
startOffsetY := (humanRand.Float64()-0.5)*200 + 50
startX := x + startOffsetX
@@ -85,7 +77,6 @@ func humanClick(ctx context.Context, x, y float64) error {
distance := math.Sqrt(startOffsetX*startOffsetX + startOffsetY*startOffsetY)
if distance > 30 {
-
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
return input.DispatchMouseEvent(input.MouseMoved, startX, startY).Do(ctx)
@@ -94,7 +85,7 @@ func humanClick(ctx context.Context, x, y float64) error {
return err
}
- if err := humanMouseMove(ctx, startX, startY, x, y); err != nil {
+ if err := MouseMove(ctx, startX, startY, x, y); err != nil {
return err
}
}
@@ -127,9 +118,7 @@ func humanClick(ctx context.Context, x, y float64) error {
)
}
-// humanClickElement clicks an element with human-like behavior
-func humanClickElement(ctx context.Context, nodeID cdp.NodeID) error {
- // Get element center coordinates
+func ClickElement(ctx context.Context, nodeID cdp.NodeID) error {
var box *dom.BoxModel
if err := chromedp.Run(ctx,
chromedp.ActionFunc(func(ctx context.Context) error {
@@ -151,11 +140,10 @@ func humanClickElement(ctx context.Context, nodeID cdp.NodeID) error {
offsetX := (humanRand.Float64() - 0.5) * 10
offsetY := (humanRand.Float64() - 0.5) * 10
- return humanClick(ctx, centerX+offsetX, centerY+offsetY)
+ return Click(ctx, centerX+offsetX, centerY+offsetY)
}
-// humanType types text with natural timing and occasional corrections
-func humanType(text string, fast bool) []chromedp.Action {
+func Type(text string, fast bool) []chromedp.Action {
actions := []chromedp.Action{}
baseDelay := 80
@@ -165,23 +153,17 @@ func humanType(text string, fast bool) []chromedp.Action {
chars := []rune(text)
for i, char := range chars {
-
actions = append(actions, chromedp.KeyEvent(string(char)))
-
delay := baseDelay + humanRand.Intn(baseDelay/2)
-
if humanRand.Float64() < 0.05 {
delay += humanRand.Intn(500)
}
-
if i > 0 && chars[i-1] == char {
delay = delay / 2
}
-
actions = append(actions, chromedp.Sleep(time.Duration(delay)*time.Millisecond))
if humanRand.Float64() < 0.03 && i < len(chars)-1 {
-
wrongChar := rune('a' + humanRand.Intn(26))
actions = append(actions,
chromedp.KeyEvent(string(wrongChar)),
@@ -191,6 +173,5 @@ func humanType(text string, fast bool) []chromedp.Action {
)
}
}
-
return actions
}
diff --git a/internal/human/human_test.go b/internal/human/human_test.go
new file mode 100644
index 00000000..0a83433c
--- /dev/null
+++ b/internal/human/human_test.go
@@ -0,0 +1,55 @@
+package human
+
+import (
+ "context"
+ "testing"
+
+ "github.com/chromedp/chromedp"
+)
+
+func TestSetHumanRandSeed(t *testing.T) {
+ // Just verify it doesn't panic
+ SetHumanRandSeed(12345)
+}
+
+func TestType(t *testing.T) {
+ text := "hello"
+
+ // Test normal typing
+ actions := Type(text, false)
+ if len(actions) < len(text) {
+ t.Errorf("expected at least %d actions, got %d", len(text), len(actions))
+ }
+
+ // Test fast typing
+ fastActions := Type(text, true)
+ if len(fastActions) < len(text) {
+ t.Errorf("expected at least %d actions, got %d", len(text), len(fastActions))
+ }
+}
+
+func TestTypeWithCorrections(t *testing.T) {
+ // Use a fixed seed that we know triggers a correction (statistically likely with long string)
+ SetHumanRandSeed(1)
+ text := "this is a very long string to increase the chance of a simulated typo correction"
+ actions := Type(text, false)
+
+ // If a typo happened, there will be more actions than just KeyEvents and Sleeps for each char
+ if len(actions) < len(text)*2 {
+ t.Errorf("expected many actions for long string, got %d", len(actions))
+ }
+}
+
+func TestMouseMove(t *testing.T) {
+ // Create a context that chromedp.Run won't immediately reject
+ ctx, _ := chromedp.NewContext(context.Background())
+
+ // MouseMove will try to call chromedp.Run.
+ // Without a real browser it will return an error, but we cover the code path.
+ _ = MouseMove(ctx, 0, 0, 100, 100)
+}
+
+func TestClick(t *testing.T) {
+ ctx, _ := chromedp.NewContext(context.Background())
+ _ = Click(ctx, 50, 50)
+}
diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.go
new file mode 100644
index 00000000..89897dfd
--- /dev/null
+++ b/internal/orchestrator/handlers.go
@@ -0,0 +1,102 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
+ mux.HandleFunc("POST /launch", o.handleLaunch)
+ mux.HandleFunc("POST /stop", o.handleStop)
+ mux.HandleFunc("GET /instances", o.handleList)
+ mux.HandleFunc("GET /instances/logs", o.handleLogs)
+}
+
+func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Profile string `json:"profile"`
+ Port string `json:"port"`
+ Headless bool `json:"headless"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, err)
+ return
+ }
+
+ if req.Profile == "" {
+ web.Error(w, 400, fmt.Errorf("profile name required"))
+ return
+ }
+
+ // Resolve profile ID if provided
+ if len(req.Profile) == 12 {
+ if pm := o.profiles; pm != nil {
+ if name, err := pm.FindByID(req.Profile); err == nil {
+ req.Profile = name
+ }
+ }
+ }
+
+ if req.Port == "" {
+ req.Port = "0"
+ }
+
+ inst, err := o.Launch(req.Profile, req.Port, req.Headless)
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+
+ web.JSON(w, 200, inst)
+}
+
+func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {
+ id := r.URL.Query().Get("id")
+ profile := r.URL.Query().Get("profile")
+
+ if id != "" {
+ if err := o.Stop(id); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ } else if profile != "" {
+ // Resolve profile ID if provided
+ if len(profile) == 12 {
+ if pm := o.profiles; pm != nil {
+ if name, err := pm.FindByID(profile); err == nil {
+ profile = name
+ }
+ }
+ }
+ if err := o.StopProfile(profile); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ } else {
+ web.Error(w, 400, fmt.Errorf("id or profile required"))
+ return
+ }
+
+ web.JSON(w, 200, map[string]string{"status": "stopped"})
+}
+
+func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
+ web.JSON(w, 200, o.List())
+}
+
+func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {
+ id := r.URL.Query().Get("id")
+ if id == "" {
+ web.Error(w, 400, fmt.Errorf("id required"))
+ return
+ }
+ logs, err := o.Logs(id)
+ if err != nil {
+ web.Error(w, 404, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"id": id, "logs": logs})
+}
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
new file mode 100644
index 00000000..1e07472e
--- /dev/null
+++ b/internal/orchestrator/health.go
@@ -0,0 +1,129 @@
+package orchestrator
+
+import (
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net/http"
+ "time"
+)
+
+const (
+ instanceHealthPollInterval = 500 * time.Millisecond
+ instanceStartupTimeout = 45 * time.Second
+)
+
+func (o *Orchestrator) monitor(inst *InstanceInternal) {
+ healthy := false
+ exitedEarly := false
+ lastProbe := "no response"
+ resolvedURL := ""
+ waitCh := make(chan error, 1)
+ go func() {
+ waitCh <- inst.cmd.Wait()
+ }()
+ var waitErr error
+ started := time.Now()
+ for time.Since(started) < instanceStartupTimeout {
+ select {
+ case waitErr = <-waitCh:
+ exitedEarly = true
+ default:
+ }
+ if exitedEarly {
+ break
+ }
+ time.Sleep(instanceHealthPollInterval)
+
+ for _, baseURL := range instanceBaseURLs(inst.Port) {
+ resp, err := o.client.Get(baseURL + "/health")
+ if err == nil {
+ _ = resp.Body.Close()
+ lastProbe = fmt.Sprintf("%s -> HTTP %d", baseURL, resp.StatusCode)
+ if isInstanceHealthyStatus(resp.StatusCode) {
+ healthy = true
+ resolvedURL = baseURL
+ break
+ }
+ } else {
+ lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())
+ }
+ }
+ if healthy {
+ break
+ }
+ }
+
+ o.mu.Lock()
+ switch inst.Status {
+ case "stopping", "stopped":
+ default:
+ if healthy {
+ inst.Status = "running"
+ if resolvedURL != "" {
+ inst.URL = resolvedURL
+ }
+ slog.Info("instance ready", "id", inst.ID, "port", inst.Port)
+ } else if exitedEarly {
+ inst.Status = "error"
+ if waitErr != nil {
+ inst.Error = "process exited before health check: " + waitErr.Error()
+ } else {
+ inst.Error = "process exited before health check succeeded"
+ }
+ if tail := tailLogLine(inst.logBuf.String()); tail != "" {
+ inst.Error += " | " + tail
+ }
+ slog.Error("instance exited before ready", "id", inst.ID)
+ } else {
+ inst.Status = "error"
+ inst.Error = fmt.Errorf("health check timeout after %s (%s)", instanceStartupTimeout, lastProbe).Error()
+ if tail := tailLogLine(inst.logBuf.String()); tail != "" {
+ inst.Error += " | " + tail
+ }
+ slog.Error("instance failed to start", "id", inst.ID)
+ }
+ }
+ o.mu.Unlock()
+
+ if !exitedEarly {
+ <-waitCh
+ }
+ o.mu.Lock()
+ if inst.Status == "running" || inst.Status == "stopping" {
+ inst.Status = "stopped"
+ }
+ o.mu.Unlock()
+ slog.Info("instance exited", "id", inst.ID)
+}
+
+type remoteTab struct {
+ ID string `json:"id"`
+ URL string `json:"url"`
+}
+
+func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
+ resp, err := o.client.Get(baseURL + "/screencast/tabs")
+ if err != nil {
+ return nil, err
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var tabs []remoteTab
+ if err := json.NewDecoder(resp.Body).Decode(&tabs); err != nil {
+ return nil, err
+ }
+ return tabs, nil
+}
+
+func isInstanceHealthyStatus(code int) bool {
+ return code > 0 && code < http.StatusInternalServerError
+}
+
+func instanceBaseURLs(port string) []string {
+ return []string{
+ fmt.Sprintf("http://127.0.0.1:%s", port),
+ fmt.Sprintf("http://[::1]:%s", port),
+ fmt.Sprintf("http://localhost:%s", port),
+ }
+}
diff --git a/internal/orchestrator/health_test.go b/internal/orchestrator/health_test.go
new file mode 100644
index 00000000..34b31811
--- /dev/null
+++ b/internal/orchestrator/health_test.go
@@ -0,0 +1,47 @@
+package orchestrator
+
+import (
+ "net/http"
+ "testing"
+)
+
+func TestIsInstanceHealthyStatus(t *testing.T) {
+ tests := []struct {
+ code int
+ want bool
+ }{
+ {http.StatusOK, true},
+ {http.StatusNotFound, true},
+ {http.StatusBadRequest, true},
+ {http.StatusInternalServerError, false},
+ {http.StatusBadGateway, false},
+ {0, false},
+ }
+
+ for _, tt := range tests {
+ if got := isInstanceHealthyStatus(tt.code); got != tt.want {
+ t.Errorf("isInstanceHealthyStatus(%d) = %v, want %v", tt.code, got, tt.want)
+ }
+ }
+}
+
+func TestInstanceBaseURLs(t *testing.T) {
+ port := "1234"
+ urls := instanceBaseURLs(port)
+
+ expected := []string{
+ "http://127.0.0.1:1234",
+ "http://[::1]:1234",
+ "http://localhost:1234",
+ }
+
+ if len(urls) != len(expected) {
+ t.Fatalf("expected %d URLs, got %d", len(expected), len(urls))
+ }
+
+ for i, url := range urls {
+ if url != expected[i] {
+ t.Errorf("url[%d] = %q, want %q", i, url, expected[i])
+ }
+ }
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
new file mode 100644
index 00000000..f4bac1e3
--- /dev/null
+++ b/internal/orchestrator/orchestrator.go
@@ -0,0 +1,403 @@
+package orchestrator
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/profiles"
+)
+
+type Orchestrator struct {
+ instances map[string]*InstanceInternal
+ baseDir string
+ binary string
+ profiles *profiles.ProfileManager
+ runner HostRunner
+ mu sync.RWMutex
+ client *http.Client
+}
+
+type InstanceInternal struct {
+ bridge.Instance
+ URL string
+ Error string
+
+ cmd Cmd
+ logBuf *ringBuffer
+}
+
+func NewOrchestrator(baseDir string) *Orchestrator {
+ return NewOrchestratorWithRunner(baseDir, &LocalRunner{})
+}
+
+func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator {
+ binDir := filepath.Join(filepath.Dir(baseDir), "bin")
+ stableBin := filepath.Join(binDir, "pinchtab")
+ exe, _ := os.Executable()
+ binary := exe
+ if binary == "" {
+ binary = os.Args[0]
+ }
+
+ if err := os.MkdirAll(binDir, 0755); err != nil {
+ slog.Warn("failed to create bin directory", "path", binDir, "err", err)
+ }
+
+ if exe != "" {
+ if err := installStableBinary(exe, stableBin); err != nil {
+ slog.Warn("failed to install pinchtab binary", "path", stableBin, "err", err)
+ } else {
+ slog.Info("installed pinchtab binary", "path", stableBin)
+ }
+ }
+
+ if _, err := os.Stat(binary); err != nil {
+ if _, stableErr := os.Stat(stableBin); stableErr == nil {
+ binary = stableBin
+ }
+ }
+
+ return &Orchestrator{
+ instances: make(map[string]*InstanceInternal),
+ baseDir: baseDir,
+ binary: binary,
+ runner: runner,
+ client: &http.Client{Timeout: 3 * time.Second},
+ }
+}
+
+func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {
+ o.profiles = pm
+}
+
+func installStableBinary(src, dst string) error {
+ in, err := os.Open(src)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = in.Close() }()
+
+ out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = out.Close() }()
+
+ _, err = io.Copy(out, in)
+ return err
+}
+
+func (o *Orchestrator) Launch(name, port string, headless bool) (*bridge.Instance, error) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+
+ for _, inst := range o.instances {
+ if inst.Port == port && instanceIsActive(inst) {
+ return nil, fmt.Errorf("port %s already in use by instance %q", port, inst.Name)
+ }
+ if inst.Name == name && instanceIsActive(inst) {
+ return nil, fmt.Errorf("profile %q already has an active instance (%s)", name, inst.Status)
+ }
+ }
+ if !o.runner.IsPortAvailable(port) {
+ return nil, fmt.Errorf("port %s is already in use on this machine", port)
+ }
+
+ id := fmt.Sprintf("%s-%s", name, port)
+ if inst, ok := o.instances[id]; ok && inst.Status == "running" {
+ return nil, fmt.Errorf("instance %q already running", id)
+ }
+
+ profilePath := filepath.Join(o.baseDir, name)
+ if err := os.MkdirAll(filepath.Join(profilePath, "Default"), 0755); err != nil {
+ return nil, fmt.Errorf("create profile dir: %w", err)
+ }
+ instanceStateDir := filepath.Join(profilePath, ".pinchtab-state")
+ if err := os.MkdirAll(instanceStateDir, 0755); err != nil {
+ return nil, fmt.Errorf("create state dir: %w", err)
+ }
+
+ headlessStr := "true"
+ if !headless {
+ headlessStr = "false"
+ }
+
+ env := mergeEnvWithOverrides(os.Environ(), map[string]string{
+ "BRIDGE_PORT": port,
+ "BRIDGE_PROFILE": profilePath,
+ "BRIDGE_STATE_DIR": instanceStateDir,
+ "BRIDGE_HEADLESS": headlessStr,
+ "BRIDGE_NO_RESTORE": "true",
+ "BRIDGE_NO_DASHBOARD": "true",
+ })
+
+ logBuf := newRingBuffer(64 * 1024)
+ slog.Info("starting instance process", "id", id, "binary", o.binary, "port", port, "profile", profilePath)
+
+ cmd, err := o.runner.Run(context.Background(), o.binary, env, logBuf, logBuf)
+ if err != nil {
+ return nil, fmt.Errorf("failed to start: %w", err)
+ }
+
+ inst := &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: id,
+ Name: name,
+ Profile: profilePath,
+ Port: port,
+ Headless: headless,
+ Status: "starting",
+ StartTime: time.Now(),
+ },
+ URL: fmt.Sprintf("http://localhost:%s", port),
+ cmd: cmd,
+ logBuf: logBuf,
+ }
+
+ o.instances[id] = inst
+
+ go o.monitor(inst)
+
+ return &inst.Instance, nil
+}
+
+func (o *Orchestrator) Stop(id string) error {
+ o.mu.Lock()
+ inst, ok := o.instances[id]
+ if !ok {
+ o.mu.Unlock()
+ return fmt.Errorf("instance %q not found", id)
+ }
+ if inst.Status == "stopped" && !instanceIsActive(inst) {
+ o.mu.Unlock()
+ return nil
+ }
+ inst.Status = "stopping"
+ o.mu.Unlock()
+
+ if inst.cmd == nil {
+ o.markStopped(id)
+ return nil
+ }
+
+ pid := inst.cmd.PID()
+
+ reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
+ defer cancel()
+ req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, inst.URL+"/shutdown", nil)
+ resp, err := o.client.Do(req)
+ if err == nil {
+ _ = resp.Body.Close()
+ }
+
+ if pid > 0 {
+ if waitForProcessExit(pid, 5*time.Second) {
+ o.markStopped(id)
+ return nil
+ }
+
+ if err := killProcessGroup(pid, sigTERM); err != nil {
+ slog.Warn("failed to send SIGTERM to instance", "id", id, "pid", pid, "err", err)
+ }
+ if waitForProcessExit(pid, 3*time.Second) {
+ o.markStopped(id)
+ return nil
+ }
+
+ if err := killProcessGroup(pid, sigKILL); err != nil {
+ slog.Warn("failed to send SIGKILL to instance", "id", id, "pid", pid, "err", err)
+ }
+ }
+
+ inst.cmd.Cancel()
+
+ if pid > 0 {
+ if waitForProcessExit(pid, 2*time.Second) {
+ o.markStopped(id)
+ return nil
+ }
+ o.setStopError(id, fmt.Sprintf("failed to stop process %d; still running", pid))
+ return fmt.Errorf("failed to stop instance %q gracefully", id)
+ }
+
+ o.markStopped(id)
+ return nil
+}
+
+func (o *Orchestrator) StopProfile(name string) error {
+ o.mu.RLock()
+ ids := make([]string, 0, 1)
+ for id, inst := range o.instances {
+ if inst.Name == name && instanceIsActive(inst) {
+ ids = append(ids, id)
+ }
+ }
+ o.mu.RUnlock()
+
+ if len(ids) == 0 {
+ return fmt.Errorf("no active instance for profile %q", name)
+ }
+
+ var errs []string
+ for _, id := range ids {
+ if err := o.Stop(id); err != nil {
+ errs = append(errs, err.Error())
+ }
+ }
+ if len(errs) > 0 {
+ return fmt.Errorf("failed to stop profile %q: %s", name, strings.Join(errs, "; "))
+ }
+ return nil
+}
+
+func (o *Orchestrator) markStopped(id string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if inst, ok := o.instances[id]; ok {
+ inst.Status = "stopped"
+ }
+}
+
+func (o *Orchestrator) setStopError(id, msg string) {
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ if inst, ok := o.instances[id]; ok {
+ inst.Status = "error"
+ inst.Error = msg
+ }
+}
+
+func (o *Orchestrator) List() []bridge.Instance {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+
+ result := make([]bridge.Instance, 0, len(o.instances))
+ for _, inst := range o.instances {
+ copyInst := inst.Instance
+ if instanceIsActive(inst) && copyInst.Status == "stopped" {
+ copyInst.Status = "running"
+ }
+ if !instanceIsActive(inst) &&
+ (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {
+ copyInst.Status = "stopped"
+ }
+
+ result = append(result, copyInst)
+ }
+ return result
+}
+
+func (o *Orchestrator) Logs(id string) (string, error) {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+
+ inst, ok := o.instances[id]
+ if !ok {
+ return "", fmt.Errorf("instance %q not found", id)
+ }
+ return inst.logBuf.String(), nil
+}
+
+func (o *Orchestrator) FirstRunningURL() string {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ for _, inst := range o.instances {
+ if inst.Status == "running" && instanceIsActive(inst) {
+ return inst.URL
+ }
+ }
+ return ""
+}
+
+func (o *Orchestrator) AllTabs() []bridge.InstanceTab {
+ o.mu.RLock()
+ instances := make([]*InstanceInternal, 0)
+ for _, inst := range o.instances {
+ if inst.Status == "running" && instanceIsActive(inst) {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ var all []bridge.InstanceTab
+ for _, inst := range instances {
+ tabs, err := o.fetchTabs(inst.URL)
+ if err != nil {
+ continue
+ }
+ for _, tab := range tabs {
+ all = append(all, bridge.InstanceTab{
+ InstanceID: inst.ID,
+ TabID: tab.ID,
+ URL: tab.URL,
+ })
+ }
+ }
+ return all
+}
+
+func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ inst, ok := o.instances[instanceID]
+ if !ok {
+ return ""
+ }
+ return fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
+}
+
+func (o *Orchestrator) Shutdown() {
+ o.mu.RLock()
+ ids := make([]string, 0, len(o.instances))
+ for id, inst := range o.instances {
+ if instanceIsActive(inst) {
+ ids = append(ids, id)
+ }
+ }
+ o.mu.RUnlock()
+
+ var wg sync.WaitGroup
+ for _, id := range ids {
+ wg.Add(1)
+ go func(instanceID string) {
+ defer wg.Done()
+ slog.Info("stopping instance", "id", instanceID)
+ if err := o.Stop(instanceID); err != nil {
+ slog.Warn("stop instance failed", "id", instanceID, "err", err)
+ }
+ }(id)
+ }
+ wg.Wait()
+}
+
+func (o *Orchestrator) ForceShutdown() {
+ o.mu.RLock()
+ instances := make([]*InstanceInternal, 0, len(o.instances))
+ for _, inst := range o.instances {
+ if instanceIsActive(inst) {
+ instances = append(instances, inst)
+ }
+ }
+ o.mu.RUnlock()
+
+ for _, inst := range instances {
+ pid := 0
+ if inst.cmd != nil {
+ pid = inst.cmd.PID()
+ inst.cmd.Cancel()
+ }
+ if pid > 0 {
+ _ = killProcessGroup(pid, sigKILL)
+ }
+ o.markStopped(inst.ID)
+ }
+}
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
new file mode 100644
index 00000000..adae8b3f
--- /dev/null
+++ b/internal/orchestrator/orchestrator_test.go
@@ -0,0 +1,97 @@
+package orchestrator
+
+import (
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+func TestOrchestrator_Launch_Lifecycle(t *testing.T) {
+ // Mock processAlive to always return true for our fake PIDs
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ // 1. Initial Launch
+ inst, err := o.Launch("profile1", "9001", true)
+ if err != nil {
+ t.Fatalf("First launch failed: %v", err)
+ }
+ if inst.Status != "starting" {
+ t.Errorf("expected status starting, got %s", inst.Status)
+ }
+
+ // 2. Duplicate Profile Check
+ _, err = o.Launch("profile1", "9002", true)
+ if err == nil {
+ t.Error("expected error when launching duplicate profile")
+ }
+
+ // 3. Port Conflict Check (Runner reports port unavailable)
+ runner.portAvail = false
+ _, err = o.Launch("profile2", "9001", true)
+ if err == nil {
+ t.Error("expected error when launching on occupied port")
+ }
+}
+
+func TestOrchestrator_ListAndStop(t *testing.T) {
+ // Mock processAlive to return true then false to simulate exit
+ alive := true
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return alive }
+ defer func() { processAliveFunc = old }()
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ _, _ = o.Launch("p1", "9001", true)
+
+ // Simulate stop
+ alive = false
+ err := o.Stop("p1-9001")
+ if err != nil {
+ t.Fatalf("Stop failed: %v", err)
+ }
+
+ inst := o.List()[0]
+ if inst.Status != "stopped" {
+ t.Errorf("expected status stopped, got %s", inst.Status)
+ }
+}
+
+func TestOrchestrator_StopProfile(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return true }
+ defer func() { processAliveFunc = old }()
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ o.mu.Lock()
+ o.instances["p1-9001"] = &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: "p1-9001",
+ Name: "p1",
+ Status: "running",
+ },
+ URL: "http://localhost:9001",
+ }
+ o.mu.Unlock()
+
+ // Make it "exit" immediately on stop
+ processAliveFunc = func(pid int) bool { return false }
+
+ err := o.StopProfile("p1")
+ if err != nil {
+ t.Fatalf("StopProfile failed: %v", err)
+ }
+
+ inst := o.List()[0]
+ if inst.Status != "stopped" {
+ t.Errorf("expected stopped, got %s", inst.Status)
+ }
+}
diff --git a/internal/orchestrator/process.go b/internal/orchestrator/process.go
new file mode 100644
index 00000000..fe326aec
--- /dev/null
+++ b/internal/orchestrator/process.go
@@ -0,0 +1,117 @@
+package orchestrator
+
+import (
+ "net"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+func instanceIsActive(inst *InstanceInternal) bool {
+ if inst == nil {
+ return false
+ }
+ if inst.cmd != nil {
+ return isProcessAlive(inst.cmd.PID())
+ }
+ return inst.Status == "starting" || inst.Status == "running" || inst.Status == "stopping"
+}
+
+func waitForProcessExit(pid int, timeout time.Duration) bool {
+ if pid <= 0 {
+ return true
+ }
+ deadline := time.Now().Add(timeout)
+ for time.Now().Before(deadline) {
+ if !isProcessAlive(pid) {
+ return true
+ }
+ time.Sleep(150 * time.Millisecond)
+ }
+ return !isProcessAlive(pid)
+}
+
+var processAliveFunc = processAlive
+
+func isProcessAlive(pid int) bool {
+ return processAliveFunc(pid)
+}
+
+func isPortAvailable(port string) bool {
+ ln, err := net.Listen("tcp", ":"+port)
+ if err != nil {
+ return false
+ }
+ _ = ln.Close()
+ return true
+}
+
+func tailLogLine(logs string) string {
+ if logs == "" {
+ return ""
+ }
+ lines := strings.Split(strings.TrimSpace(logs), "\n")
+ for i := len(lines) - 1; i >= 0; i-- {
+ line := strings.TrimSpace(lines[i])
+ if line == "" {
+ continue
+ }
+ const max = 220
+ if len(line) > max {
+ return line[len(line)-max:]
+ }
+ return line
+ }
+ return ""
+}
+
+func mergeEnvWithOverrides(base []string, overrides map[string]string) []string {
+ out := make([]string, 0, len(base)+len(overrides))
+ for _, kv := range base {
+ key, _, ok := strings.Cut(kv, "=")
+ if !ok {
+ continue
+ }
+ if _, exists := overrides[key]; exists {
+ continue
+ }
+ out = append(out, kv)
+ }
+
+ keys := make([]string, 0, len(overrides))
+ for k := range overrides {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ out = append(out, k+"="+overrides[k])
+ }
+ return out
+}
+
+type ringBuffer struct {
+ mu sync.Mutex
+ data []byte
+ max int
+}
+
+func newRingBuffer(max int) *ringBuffer {
+ return &ringBuffer{max: max, data: make([]byte, 0, max)}
+}
+
+func (rb *ringBuffer) Write(p []byte) (int, error) {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ rb.data = append(rb.data, p...)
+ if len(rb.data) > rb.max {
+ rb.data = rb.data[len(rb.data)-rb.max:]
+ }
+ return len(p), nil
+}
+
+func (rb *ringBuffer) String() string {
+ rb.mu.Lock()
+ defer rb.mu.Unlock()
+ return string(rb.data)
+}
diff --git a/internal/orchestrator/process_test.go b/internal/orchestrator/process_test.go
new file mode 100644
index 00000000..9a4b2db0
--- /dev/null
+++ b/internal/orchestrator/process_test.go
@@ -0,0 +1,90 @@
+package orchestrator
+
+import (
+ "context"
+ "io"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+type mockRunner struct {
+ runCalled bool
+ portAvail bool
+}
+
+type mockCmd struct {
+ pid int
+ isAlive bool
+}
+
+func (m *mockCmd) Wait() error { return nil }
+func (m *mockCmd) PID() int { return m.pid }
+func (m *mockCmd) Cancel() {}
+
+func (m *mockRunner) Run(ctx context.Context, binary string, env []string, stdout, stderr io.Writer) (Cmd, error) {
+ m.runCalled = true
+ return &mockCmd{pid: 1234, isAlive: true}, nil
+}
+
+func (m *mockRunner) IsPortAvailable(port string) bool {
+ return m.portAvail
+}
+
+func TestLaunch_Mocked(t *testing.T) {
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ inst, err := o.Launch("test-prof", "9999", true)
+ if err != nil {
+ t.Fatalf("Launch failed: %v", err)
+ }
+
+ if !runner.runCalled {
+ t.Error("expected runner.Run to be called")
+ }
+ if inst.ID != "test-prof-9999" {
+ t.Errorf("expected ID test-prof-9999, got %s", inst.ID)
+ }
+}
+
+func TestLaunch_PortConflict(t *testing.T) {
+ runner := &mockRunner{portAvail: false}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+
+ _, err := o.Launch("test-prof", "9999", true)
+ if err == nil {
+ t.Fatal("expected error for unavailable port")
+ }
+}
+
+func TestInstanceIsActive(t *testing.T) {
+ tests := []struct {
+ name string
+ inst *InstanceInternal
+ active bool
+ }{
+ {
+ name: "starting",
+ inst: &InstanceInternal{
+ Instance: bridge.Instance{Status: "starting"},
+ },
+ active: true,
+ },
+ {
+ name: "running",
+ inst: &InstanceInternal{
+ Instance: bridge.Instance{Status: "running"},
+ },
+ active: true,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := instanceIsActive(tt.inst); got != tt.active {
+ t.Errorf("instanceIsActive() = %v, want %v", got, tt.active)
+ }
+ })
+ }
+}
diff --git a/process_unix.go b/internal/orchestrator/process_unix.go
similarity index 96%
rename from process_unix.go
rename to internal/orchestrator/process_unix.go
index eb852fc2..881fc1c8 100644
--- a/process_unix.go
+++ b/internal/orchestrator/process_unix.go
@@ -1,6 +1,6 @@
//go:build !windows
-package main
+package orchestrator
import (
"os/exec"
diff --git a/process_windows.go b/internal/orchestrator/process_windows.go
similarity index 97%
rename from process_windows.go
rename to internal/orchestrator/process_windows.go
index fe133b1e..58fda780 100644
--- a/process_windows.go
+++ b/internal/orchestrator/process_windows.go
@@ -1,6 +1,6 @@
//go:build windows
-package main
+package orchestrator
import (
"os"
diff --git a/internal/orchestrator/runner.go b/internal/orchestrator/runner.go
new file mode 100644
index 00000000..5fef7e69
--- /dev/null
+++ b/internal/orchestrator/runner.go
@@ -0,0 +1,60 @@
+package orchestrator
+
+import (
+ "context"
+ "io"
+ "os/exec"
+)
+
+type HostRunner interface {
+ Run(ctx context.Context, binary string, env []string, stdout, stderr io.Writer) (Cmd, error)
+ IsPortAvailable(port string) bool
+}
+
+type Cmd interface {
+ Wait() error
+ PID() int
+ Cancel()
+}
+
+type LocalRunner struct{}
+
+type localCmd struct {
+ execCmd *exec.Cmd
+ cancel context.CancelFunc
+}
+
+func (r *LocalRunner) Run(ctx context.Context, binary string, env []string, stdout, stderr io.Writer) (Cmd, error) {
+ runCtx, cancel := context.WithCancel(ctx)
+ cmd := exec.CommandContext(runCtx, binary)
+ cmd.Env = env
+ cmd.Stdout = stdout
+ cmd.Stderr = stderr
+ setProcGroup(cmd)
+
+ if err := cmd.Start(); err != nil {
+ cancel()
+ return nil, err
+ }
+
+ return &localCmd{execCmd: cmd, cancel: cancel}, nil
+}
+
+func (r *LocalRunner) IsPortAvailable(port string) bool {
+ return isPortAvailable(port)
+}
+
+func (c *localCmd) Wait() error {
+ return c.execCmd.Wait()
+}
+
+func (c *localCmd) PID() int {
+ if c.execCmd.Process != nil {
+ return c.execCmd.Process.Pid
+ }
+ return 0
+}
+
+func (c *localCmd) Cancel() {
+ c.cancel()
+}
diff --git a/internal/profiles/handlers.go b/internal/profiles/handlers.go
new file mode 100644
index 00000000..6a6aacd2
--- /dev/null
+++ b/internal/profiles/handlers.go
@@ -0,0 +1,162 @@
+package profiles
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/pinchtab/pinchtab/internal/web"
+)
+
+func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
+ mux.HandleFunc("GET /profiles", pm.handleList)
+ mux.HandleFunc("POST /profiles", pm.handleCreate)
+ mux.HandleFunc("POST /profiles/import", pm.handleImport)
+ mux.HandleFunc("POST /profiles/reset", pm.handleReset)
+ mux.HandleFunc("DELETE /profiles", pm.handleDelete)
+ mux.HandleFunc("GET /profiles/logs", pm.handleLogs)
+ mux.HandleFunc("GET /profiles/analytics", pm.handleAnalytics)
+ mux.HandleFunc("PATCH /profiles/meta", pm.handleUpdateMeta)
+}
+
+func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {
+ profiles, err := pm.List()
+ if err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, profiles)
+}
+
+func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ UseWhen string `json:"useWhen"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, err)
+ return
+ }
+ if req.Name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+
+ meta := ProfileMeta{
+ Description: req.Description,
+ UseWhen: req.UseWhen,
+ }
+
+ if err := pm.CreateWithMeta(req.Name, meta); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "created", "name": req.Name})
+}
+
+func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Name string `json:"name"`
+ SourcePath string `json:"sourcePath"`
+ Description string `json:"description"`
+ UseWhen string `json:"useWhen"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, err)
+ return
+ }
+ if req.Name == "" || req.SourcePath == "" {
+ web.Error(w, 400, fmt.Errorf("name and sourcePath required"))
+ return
+ }
+
+ meta := ProfileMeta{
+ Description: req.Description,
+ UseWhen: req.UseWhen,
+ }
+
+ if err := pm.ImportWithMeta(req.Name, req.SourcePath, meta); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "imported", "name": req.Name})
+}
+
+func (pm *ProfileManager) handleReset(w http.ResponseWriter, r *http.Request) {
+ name := r.URL.Query().Get("name")
+ if name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+ if err := pm.Reset(name); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "reset", "name": name})
+}
+
+func (pm *ProfileManager) handleDelete(w http.ResponseWriter, r *http.Request) {
+ name := r.URL.Query().Get("name")
+ if name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+ if err := pm.Delete(name); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "deleted", "name": name})
+}
+
+func (pm *ProfileManager) handleLogs(w http.ResponseWriter, r *http.Request) {
+ name := r.URL.Query().Get("name")
+ if name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+ limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
+ logs := pm.Logs(name, limit)
+ web.JSON(w, 200, logs)
+}
+
+func (pm *ProfileManager) handleAnalytics(w http.ResponseWriter, r *http.Request) {
+ name := r.URL.Query().Get("name")
+ if name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+ report := pm.Analytics(name)
+ web.JSON(w, 200, report)
+}
+
+func (pm *ProfileManager) handleUpdateMeta(w http.ResponseWriter, r *http.Request) {
+ var req struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ UseWhen string `json:"useWhen"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ web.Error(w, 400, err)
+ return
+ }
+ if req.Name == "" {
+ web.Error(w, 400, fmt.Errorf("name required"))
+ return
+ }
+
+ updates := make(map[string]string)
+ if req.Description != "" {
+ updates["description"] = req.Description
+ }
+ if req.UseWhen != "" {
+ updates["useWhen"] = req.UseWhen
+ }
+
+ if err := pm.UpdateMeta(req.Name, updates); err != nil {
+ web.Error(w, 500, err)
+ return
+ }
+ web.JSON(w, 200, map[string]string{"status": "updated", "name": req.Name})
+}
diff --git a/internal/profiles/identity.go b/internal/profiles/identity.go
new file mode 100644
index 00000000..1f7dbd58
--- /dev/null
+++ b/internal/profiles/identity.go
@@ -0,0 +1,109 @@
+package profiles
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+)
+
+func readChromeProfileIdentity(profileRoot string) (string, string, string, bool) {
+ chromeProfileName, lsEmail, lsName, lsHas := readLocalStateIdentity(filepath.Join(profileRoot, "Local State"))
+ prefsEmail, prefsName, prefsHas := readPreferencesIdentity(filepath.Join(profileRoot, "Default", "Preferences"))
+
+ email := prefsEmail
+ if email == "" {
+ email = lsEmail
+ }
+
+ accountName := prefsName
+ if accountName == "" {
+ accountName = lsName
+ }
+
+ hasAccount := prefsHas || lsHas || email != ""
+ return chromeProfileName, email, accountName, hasAccount
+}
+
+func readPreferencesIdentity(path string) (string, string, bool) {
+ var prefs struct {
+ AccountInfo []struct {
+ Email string `json:"email"`
+ FullName string `json:"full_name"`
+ GaiaName string `json:"gaia_name"`
+ GaiaID string `json:"gaia"`
+ } `json:"account_info"`
+ }
+ if !readJSON(path, &prefs) {
+ return "", "", false
+ }
+
+ for _, account := range prefs.AccountInfo {
+ email := account.Email
+ name := account.FullName
+ if name == "" {
+ name = account.GaiaName
+ }
+ if email != "" || account.GaiaID != "" || name != "" {
+ return email, name, true
+ }
+ }
+
+ return "", "", false
+}
+
+func readLocalStateIdentity(path string) (string, string, string, bool) {
+ var state struct {
+ Profile struct {
+ InfoCache map[string]struct {
+ Name string `json:"name"`
+ UserName string `json:"user_name"`
+ GaiaName string `json:"gaia_name"`
+ GaiaID string `json:"gaia_id"`
+ IsConsentedPrimaryAccount bool `json:"is_consented_primary_account"`
+ HasConsentedPrimaryAccount bool `json:"has_consented_primary_account"`
+ } `json:"info_cache"`
+ } `json:"profile"`
+ }
+ if !readJSON(path, &state) || len(state.Profile.InfoCache) == 0 {
+ return "", "", "", false
+ }
+
+ entry, ok := state.Profile.InfoCache["Default"]
+ if !ok {
+ for _, v := range state.Profile.InfoCache {
+ entry = v
+ break
+ }
+ }
+
+ profileName := entry.Name
+ email := entry.UserName
+ accountName := entry.GaiaName
+ hasAccount := email != "" || entry.GaiaID != "" || entry.IsConsentedPrimaryAccount || entry.HasConsentedPrimaryAccount
+ return profileName, email, accountName, hasAccount
+}
+
+func readJSON(path string, out any) bool {
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return false
+ }
+ if err := json.Unmarshal(data, out); err != nil {
+ return false
+ }
+ return true
+}
+
+func readProfileMeta(profileDir string) ProfileMeta {
+ var meta ProfileMeta
+ readJSON(filepath.Join(profileDir, "profile.json"), &meta)
+ return meta
+}
+
+func writeProfileMeta(profileDir string, meta ProfileMeta) error {
+ data, err := json.MarshalIndent(meta, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(filepath.Join(profileDir, "profile.json"), data, 0644)
+}
diff --git a/internal/profiles/identity_test.go b/internal/profiles/identity_test.go
new file mode 100644
index 00000000..84ff5dab
--- /dev/null
+++ b/internal/profiles/identity_test.go
@@ -0,0 +1,98 @@
+package profiles
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestReadChromeProfileIdentity(t *testing.T) {
+ tmpDir := t.TempDir()
+
+ // 1. Test empty profile
+ name, email, accName, hasAcc := readChromeProfileIdentity(tmpDir)
+ if name != "" || email != "" || accName != "" || hasAcc != false {
+ t.Errorf("expected empty results for empty dir, got %q, %q, %q, %v", name, email, accName, hasAcc)
+ }
+
+ // 2. Test with Local State only
+ localStateDir := tmpDir
+ localStatePath := filepath.Join(localStateDir, "Local State")
+ localStateContent := `{
+ "profile": {
+ "info_cache": {
+ "Default": {
+ "name": "Work Profile",
+ "user_name": "[email protected]",
+ "gaia_name": "Work User",
+ "gaia_id": "12345",
+ "is_consented_primary_account": true
+ }
+ }
+ }
+ }`
+ if err := os.WriteFile(localStatePath, []byte(localStateContent), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ name, email, accName, hasAcc = readChromeProfileIdentity(tmpDir)
+ if name != "Work Profile" || email != "[email protected]" || accName != "Work User" || !hasAcc {
+ t.Errorf("Local State parsing failed: got %q, %q, %q, %v", name, email, accName, hasAcc)
+ }
+
+ // 3. Test with Preferences (should override/supplement)
+ prefsDir := filepath.Join(tmpDir, "Default")
+ if err := os.MkdirAll(prefsDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ prefsPath := filepath.Join(prefsDir, "Preferences")
+ prefsContent := `{
+ "account_info": [
+ {
+ "email": "[email protected]",
+ "full_name": "Pref User",
+ "gaia": "67890"
+ }
+ ]
+ }`
+ if err := os.WriteFile(prefsPath, []byte(prefsContent), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ name, email, accName, hasAcc = readChromeProfileIdentity(tmpDir)
+ // email and accName should come from Preferences if available
+ if name != "Work Profile" || email != "[email protected]" || accName != "Pref User" || !hasAcc {
+ t.Errorf("Preferences parsing/override failed: got %q, %q, %q, %v", name, email, accName, hasAcc)
+ }
+}
+
+func TestReadJSON_Malformed(t *testing.T) {
+ tmpDir := t.TempDir()
+ path := filepath.Join(tmpDir, "bad.json")
+ if err := os.WriteFile(path, []byte(`{ "invalid": json `), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ var out map[string]any
+ if readJSON(path, &out) {
+ t.Error("readJSON should return false for malformed JSON")
+ }
+}
+
+func TestProfileMeta_ReadWrite(t *testing.T) {
+ tmpDir := t.TempDir()
+ meta := ProfileMeta{
+ ID: "test-id",
+ UseWhen: "testing",
+ Description: "a test profile",
+ }
+
+ if err := writeProfileMeta(tmpDir, meta); err != nil {
+ t.Fatalf("failed to write meta: %v", err)
+ }
+
+ readMeta := readProfileMeta(tmpDir)
+ if readMeta.ID != meta.ID || readMeta.UseWhen != meta.UseWhen || readMeta.Description != meta.Description {
+ t.Errorf("read meta does not match written meta: got %+v, want %+v", readMeta, meta)
+ }
+}
diff --git a/profiles_manager.go b/internal/profiles/profiles.go
similarity index 62%
rename from profiles_manager.go
rename to internal/profiles/profiles.go
index 2dd79064..f06b79a4 100644
--- a/profiles_manager.go
+++ b/internal/profiles/profiles.go
@@ -1,9 +1,8 @@
-package main
+package profiles
import (
"crypto/sha256"
"encoding/hex"
- "encoding/json"
"fmt"
"io/fs"
"log/slog"
@@ -13,9 +12,10 @@ import (
"sort"
"sync"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
)
-// profileID generates a stable 12-char hex ID from the profile name.
func profileID(name string) string {
h := sha256.Sum256([]byte(name))
return hex.EncodeToString(h[:6])
@@ -33,7 +33,7 @@ type ProfileMeta struct {
Description string `json:"description,omitempty"`
}
-type ProfileInfo struct {
+type ProfileDetailedInfo struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Path string `json:"path"`
@@ -56,7 +56,7 @@ func NewProfileManager(baseDir string) *ProfileManager {
}
}
-func (pm *ProfileManager) List() ([]ProfileInfo, error) {
+func (pm *ProfileManager) List() ([]bridge.ProfileInfo, error) {
pm.mu.RLock()
defer pm.mu.RUnlock()
@@ -65,7 +65,7 @@ func (pm *ProfileManager) List() ([]ProfileInfo, error) {
return nil, err
}
- var profiles []ProfileInfo
+ var profiles []bridge.ProfileInfo
skip := map[string]bool{"bin": true, "profiles": true}
for _, entry := range entries {
if !entry.IsDir() || skip[entry.Name()] {
@@ -79,17 +79,29 @@ func (pm *ProfileManager) List() ([]ProfileInfo, error) {
if _, err := os.Stat(filepath.Join(pm.baseDir, entry.Name(), "Default")); err != nil {
continue
}
- profiles = append(profiles, info)
+ profiles = append(profiles, bridge.ProfileInfo{
+ ID: info.ID,
+ Name: info.Name,
+ Created: info.CreatedAt,
+ DiskUsage: int64(info.SizeMB * 1024 * 1024),
+ Source: info.Source,
+ ChromeProfileName: info.ChromeProfileName,
+ AccountEmail: info.AccountEmail,
+ AccountName: info.AccountName,
+ HasAccount: info.HasAccount,
+ UseWhen: info.UseWhen,
+ Description: info.Description,
+ })
}
sort.Slice(profiles, func(i, j int) bool { return profiles[i].Name < profiles[j].Name })
return profiles, nil
}
-func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {
+func (pm *ProfileManager) profileInfo(name string) (ProfileDetailedInfo, error) {
dir := filepath.Join(pm.baseDir, name)
fi, err := os.Stat(dir)
if err != nil {
- return ProfileInfo{}, err
+ return ProfileDetailedInfo{}, err
}
size := dirSizeMB(dir)
@@ -101,13 +113,12 @@ func (pm *ProfileManager) profileInfo(name string) (ProfileInfo, error) {
chromeProfileName, accountEmail, accountName, hasAccount := readChromeProfileIdentity(dir)
meta := readProfileMeta(dir)
- // Backfill ID for profiles created before ID generation was added.
if meta.ID == "" {
meta.ID = profileID(name)
_ = writeProfileMeta(dir, meta)
}
- return ProfileInfo{
+ return ProfileDetailedInfo{
ID: meta.ID,
Name: name,
Path: dir,
@@ -149,7 +160,6 @@ func (pm *ProfileManager) Import(name, sourcePath string) error {
return nil
}
-// ImportWithMeta imports a profile with metadata
func (pm *ProfileManager) ImportWithMeta(name, sourcePath string, meta ProfileMeta) error {
if err := pm.Import(name, sourcePath); err != nil {
return err
@@ -172,7 +182,6 @@ func (pm *ProfileManager) Create(name string) error {
return os.MkdirAll(filepath.Join(dest, "Default"), 0755)
}
-// CreateWithMeta creates a profile with metadata
func (pm *ProfileManager) CreateWithMeta(name string, meta ProfileMeta) error {
if err := pm.Create(name); err != nil {
return err
@@ -227,21 +236,6 @@ func (pm *ProfileManager) Reset(name string) error {
return nil
}
-func (pm *ProfileManager) Rename(oldName, newName string) error {
- pm.mu.Lock()
- defer pm.mu.Unlock()
-
- oldDir := filepath.Join(pm.baseDir, oldName)
- newDir := filepath.Join(pm.baseDir, newName)
- if _, err := os.Stat(oldDir); os.IsNotExist(err) {
- return fmt.Errorf("profile %q not found", oldName)
- }
- if _, err := os.Stat(newDir); err == nil {
- return fmt.Errorf("profile %q already exists", newName)
- }
- return os.Rename(oldDir, newDir)
-}
-
func (pm *ProfileManager) Delete(name string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -253,16 +247,15 @@ func (pm *ProfileManager) Delete(name string) error {
return os.RemoveAll(dir)
}
-// RecordAction records an action for a profile (implements ProfileService).
-func (pm *ProfileManager) RecordAction(profile string, record ActionRecord) {
+func (pm *ProfileManager) RecordAction(profile string, record bridge.ActionRecord) {
pm.tracker.Record(profile, record)
}
-func (pm *ProfileManager) Logs(name string, limit int) []ActionRecord {
+func (pm *ProfileManager) Logs(name string, limit int) []bridge.ActionRecord {
return pm.tracker.GetLogs(name, limit)
}
-func (pm *ProfileManager) Analytics(name string) AnalyticsReport {
+func (pm *ProfileManager) Analytics(name string) bridge.AnalyticsReport {
return pm.tracker.Analyze(name)
}
@@ -281,109 +274,6 @@ func dirSizeMB(path string) float64 {
return float64(total) / (1024 * 1024)
}
-func readChromeProfileIdentity(profileRoot string) (string, string, string, bool) {
- chromeProfileName, lsEmail, lsName, lsHas := readLocalStateIdentity(filepath.Join(profileRoot, "Local State"))
- prefsEmail, prefsName, prefsHas := readPreferencesIdentity(filepath.Join(profileRoot, "Default", "Preferences"))
-
- email := prefsEmail
- if email == "" {
- email = lsEmail
- }
-
- accountName := prefsName
- if accountName == "" {
- accountName = lsName
- }
-
- hasAccount := prefsHas || lsHas || email != ""
- return chromeProfileName, email, accountName, hasAccount
-}
-
-func readPreferencesIdentity(path string) (string, string, bool) {
- var prefs struct {
- AccountInfo []struct {
- Email string `json:"email"`
- FullName string `json:"full_name"`
- GaiaName string `json:"gaia_name"`
- GaiaID string `json:"gaia"`
- } `json:"account_info"`
- }
- if !readJSON(path, &prefs) {
- return "", "", false
- }
-
- for _, account := range prefs.AccountInfo {
- email := account.Email
- name := account.FullName
- if name == "" {
- name = account.GaiaName
- }
- if email != "" || account.GaiaID != "" || name != "" {
- return email, name, true
- }
- }
-
- return "", "", false
-}
-
-func readLocalStateIdentity(path string) (string, string, string, bool) {
- var state struct {
- Profile struct {
- InfoCache map[string]struct {
- Name string `json:"name"`
- UserName string `json:"user_name"`
- GaiaName string `json:"gaia_name"`
- GaiaID string `json:"gaia_id"`
- IsConsentedPrimaryAccount bool `json:"is_consented_primary_account"`
- HasConsentedPrimaryAccount bool `json:"has_consented_primary_account"`
- } `json:"info_cache"`
- } `json:"profile"`
- }
- if !readJSON(path, &state) || len(state.Profile.InfoCache) == 0 {
- return "", "", "", false
- }
-
- entry, ok := state.Profile.InfoCache["Default"]
- if !ok {
- for _, v := range state.Profile.InfoCache {
- entry = v
- break
- }
- }
-
- profileName := entry.Name
- email := entry.UserName
- accountName := entry.GaiaName
- hasAccount := email != "" || entry.GaiaID != "" || entry.IsConsentedPrimaryAccount || entry.HasConsentedPrimaryAccount
- return profileName, email, accountName, hasAccount
-}
-
-func readJSON(path string, out any) bool {
- data, err := os.ReadFile(path)
- if err != nil {
- return false
- }
- if err := json.Unmarshal(data, out); err != nil {
- return false
- }
- return true
-}
-
-func readProfileMeta(profileDir string) ProfileMeta {
- var meta ProfileMeta
- readJSON(filepath.Join(profileDir, "profile.json"), &meta)
- return meta
-}
-
-func writeProfileMeta(profileDir string, meta ProfileMeta) error {
- data, err := json.MarshalIndent(meta, "", " ")
- if err != nil {
- return err
- }
- return os.WriteFile(filepath.Join(profileDir, "profile.json"), data, 0644)
-}
-
-// UpdateMeta updates the profile metadata (useWhen, description)
func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error {
pm.mu.Lock()
defer pm.mu.Unlock()
@@ -393,10 +283,8 @@ func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error
return fmt.Errorf("profile %q not found", name)
}
- // Read existing metadata
existing := readProfileMeta(dir)
- // Update fields if provided
if useWhen, ok := meta["useWhen"]; ok {
existing.UseWhen = useWhen
}
@@ -407,7 +295,6 @@ func (pm *ProfileManager) UpdateMeta(name string, meta map[string]string) error
return writeProfileMeta(dir, existing)
}
-// FindByID returns the profile name matching the given ID, or empty string if not found.
func (pm *ProfileManager) FindByID(id string) (string, error) {
pm.mu.RLock()
defer pm.mu.RUnlock()
diff --git a/profiles_test.go b/internal/profiles/profiles_test.go
similarity index 83%
rename from profiles_test.go
rename to internal/profiles/profiles_test.go
index 9083f7e3..58fb0ee6 100644
--- a/profiles_test.go
+++ b/internal/profiles/profiles_test.go
@@ -1,7 +1,8 @@
-package main
+package profiles
import (
"encoding/json"
+ "fmt"
"net/http"
"net/http/httptest"
"os"
@@ -9,6 +10,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
)
func TestProfileManagerCreateAndList(t *testing.T) {
@@ -194,9 +197,10 @@ func TestProfileManagerDelete(t *testing.T) {
func TestActionTracker(t *testing.T) {
at := NewActionTracker()
+ profName := fmt.Sprintf("prof-%d", time.Now().UnixNano())
for i := 0; i < 5; i++ {
- at.Record("prof1", ActionRecord{
+ at.Record(profName, bridge.ActionRecord{
Timestamp: time.Now().Add(time.Duration(i) * time.Second),
Method: "GET",
Endpoint: "/snapshot",
@@ -206,40 +210,15 @@ func TestActionTracker(t *testing.T) {
})
}
- logs := at.GetLogs("prof1", 3)
+ logs := at.GetLogs(profName, 3)
if len(logs) != 3 {
t.Errorf("expected 3 logs, got %d", len(logs))
}
- report := at.Analyze("prof1")
+ report := at.Analyze(profName)
if report.TotalActions != 5 {
t.Errorf("expected 5 total actions, got %d", report.TotalActions)
}
- if len(report.TopEndpoints) == 0 {
- t.Error("expected at least one top endpoint")
- }
-}
-
-func TestActionTrackerRepeatDetection(t *testing.T) {
- at := NewActionTracker()
-
- for i := 0; i < 10; i++ {
- at.Record("poller", ActionRecord{
- Timestamp: time.Now().Add(time.Duration(i) * 3 * time.Second),
- Endpoint: "/snapshot",
- URL: "https://example.com/page",
- DurationMs: 50,
- Status: 200,
- })
- }
-
- report := at.Analyze("poller")
- if len(report.RepeatPatterns) == 0 {
- t.Error("expected repeat patterns to be detected")
- }
- if len(report.Suggestions) == 0 || report.Suggestions[0] == "No optimization suggestions — usage looks efficient." {
- t.Error("expected optimization suggestions for rapid polling")
- }
}
func TestProfileHandlerList(t *testing.T) {
@@ -258,7 +237,7 @@ func TestProfileHandlerList(t *testing.T) {
t.Fatalf("expected 200, got %d", w.Code)
}
- var profiles []ProfileInfo
+ var profiles []bridge.ProfileInfo
_ = json.NewDecoder(w.Body).Decode(&profiles)
if len(profiles) != 2 {
t.Errorf("expected 2 profiles, got %d", len(profiles))
@@ -271,12 +250,12 @@ func TestProfileHandlerCreate(t *testing.T) {
pm.RegisterHandlers(mux)
body := `{"name": "new-profile"}`
- req := httptest.NewRequest("POST", "/profiles/create", strings.NewReader(body))
+ req := httptest.NewRequest("POST", "/profiles", strings.NewReader(body))
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
- if w.Code != 201 {
- t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
}
@@ -286,7 +265,7 @@ func TestProfileHandlerReset(t *testing.T) {
mux := http.NewServeMux()
pm.RegisterHandlers(mux)
- req := httptest.NewRequest("POST", "/profiles/resettable/reset", nil)
+ req := httptest.NewRequest("POST", "/profiles/reset?name=resettable", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
@@ -301,7 +280,7 @@ func TestProfileHandlerDelete(t *testing.T) {
mux := http.NewServeMux()
pm.RegisterHandlers(mux)
- req := httptest.NewRequest("DELETE", "/profiles/deletable", nil)
+ req := httptest.NewRequest("DELETE", "/profiles?name=deletable", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
@@ -342,8 +321,8 @@ func TestProfileUpdateMeta(t *testing.T) {
_ = pm.Create("updatable")
// Update metadata via PATCH
- body := `{"useWhen":"Updated use case","description":"Updated description"}`
- req := httptest.NewRequest("PATCH", "/profiles/updatable", strings.NewReader(body))
+ body := `{"name":"updatable","useWhen":"Updated use case","description":"Updated description"}`
+ req := httptest.NewRequest("PATCH", "/profiles/meta", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
@@ -351,15 +330,6 @@ func TestProfileUpdateMeta(t *testing.T) {
if w.Code != 200 {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
-
- // Verify response contains updated metadata
- var updatedProfile ProfileInfo
- if err := json.NewDecoder(w.Body).Decode(&updatedProfile); err != nil {
- t.Fatal(err)
- }
- if updatedProfile.UseWhen != "Updated use case" {
- t.Errorf("expected useWhen 'Updated use case', got %q", updatedProfile.UseWhen)
- }
}
func TestProfileCreateWithUseWhen(t *testing.T) {
@@ -369,13 +339,13 @@ func TestProfileCreateWithUseWhen(t *testing.T) {
// Create profile with useWhen
body := `{"name":"test-usewhen","useWhen":"For testing purposes"}`
- req := httptest.NewRequest("POST", "/profiles/create", strings.NewReader(body))
+ req := httptest.NewRequest("POST", "/profiles", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
mux.ServeHTTP(w, req)
- if w.Code != 201 {
- t.Fatalf("expected 201, got %d: %s", w.Code, w.Body.String())
+ if w.Code != 200 {
+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
// Verify profile list includes useWhen
diff --git a/internal/profiles/tracker.go b/internal/profiles/tracker.go
new file mode 100644
index 00000000..2f886a49
--- /dev/null
+++ b/internal/profiles/tracker.go
@@ -0,0 +1,92 @@
+package profiles
+
+import (
+ "encoding/json"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/bridge"
+)
+
+type ActionTracker struct {
+ logs map[string][]bridge.ActionRecord
+ mu sync.RWMutex
+}
+
+func NewActionTracker() *ActionTracker {
+ t := &ActionTracker{
+ logs: make(map[string][]bridge.ActionRecord),
+ }
+ _ = t.load()
+ return t
+}
+
+func (t *ActionTracker) Record(profile string, record bridge.ActionRecord) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.logs[profile] = append(t.logs[profile], record)
+ if len(t.logs[profile]) > 1000 {
+ t.logs[profile] = t.logs[profile][len(t.logs[profile])-1000:]
+ }
+ _ = t.save()
+}
+
+func (t *ActionTracker) GetLogs(profile string, limit int) []bridge.ActionRecord {
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+ logs := t.logs[profile]
+ if limit > 0 && len(logs) > limit {
+ return logs[len(logs)-limit:]
+ }
+ return logs
+}
+
+func (t *ActionTracker) Analyze(profile string) bridge.AnalyticsReport {
+ t.mu.RLock()
+ defer t.mu.RUnlock()
+ logs := t.logs[profile]
+
+ report := bridge.AnalyticsReport{
+ TotalActions: len(logs),
+ CommonHosts: make(map[string]int),
+ }
+
+ last24h := time.Now().Add(-24 * time.Hour)
+ for _, l := range logs {
+ if l.Timestamp.After(last24h) {
+ report.Last24h++
+ }
+ if l.URL != "" {
+ u, err := url.Parse(l.URL)
+ if err == nil && u.Host != "" {
+ report.CommonHosts[u.Host]++
+ }
+ }
+ }
+ return report
+}
+
+func (t *ActionTracker) save() error {
+ h, _ := os.UserHomeDir()
+ path := filepath.Join(h, ".pinchtab", "action_logs.json")
+ _ = os.MkdirAll(filepath.Dir(path), 0755)
+
+ data, err := json.Marshal(t.logs)
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(path, data, 0644)
+}
+
+func (t *ActionTracker) load() error {
+ h, _ := os.UserHomeDir()
+ path := filepath.Join(h, ".pinchtab", "action_logs.json")
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ return json.Unmarshal(data, &t.logs)
+}
diff --git a/internal/web/web.go b/internal/web/web.go
new file mode 100644
index 00000000..b3925b73
--- /dev/null
+++ b/internal/web/web.go
@@ -0,0 +1,54 @@
+package web
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "fmt"
+ "log/slog"
+ "net"
+ "net/http"
+)
+
+func JSON(w http.ResponseWriter, code int, data any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+ if err := json.NewEncoder(w).Encode(data); err != nil {
+ slog.Error("json encode", "err", err)
+ }
+}
+
+func Error(w http.ResponseWriter, code int, err error) {
+ JSON(w, code, map[string]string{"error": err.Error()})
+}
+
+// CancelOnClientDone cancels the given cancel func when the HTTP client disconnects.
+func CancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {
+ <-reqCtx.Done()
+ cancel()
+}
+
+// StatusWriter wraps ResponseWriter to capture the status code.
+// It preserves Hijacker and Flusher interfaces for WebSocket/SSE support.
+type StatusWriter struct {
+ http.ResponseWriter
+ Code int
+}
+
+func (w *StatusWriter) WriteHeader(code int) {
+ w.Code = code
+ w.ResponseWriter.WriteHeader(code)
+}
+
+func (w *StatusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
+ if h, ok := w.ResponseWriter.(http.Hijacker); ok {
+ return h.Hijack()
+ }
+ return nil, nil, fmt.Errorf("underlying ResponseWriter is not a Hijacker")
+}
+
+func (w *StatusWriter) Flush() {
+ if f, ok := w.ResponseWriter.(http.Flusher); ok {
+ f.Flush()
+ }
+}
diff --git a/internal/web/web_test.go b/internal/web/web_test.go
new file mode 100644
index 00000000..eb401320
--- /dev/null
+++ b/internal/web/web_test.go
@@ -0,0 +1,60 @@
+package web
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestStatusWriter(t *testing.T) {
+ w := httptest.NewRecorder()
+ sw := &StatusWriter{ResponseWriter: w, Code: 200}
+
+ sw.WriteHeader(http.StatusNotFound)
+ if sw.Code != http.StatusNotFound {
+ t.Errorf("expected Code 404, got %d", sw.Code)
+ }
+ if w.Code != http.StatusNotFound {
+ t.Errorf("expected recorded code 404, got %d", w.Code)
+ }
+
+ // Test default code
+ w2 := httptest.NewRecorder()
+ sw2 := &StatusWriter{ResponseWriter: w2, Code: 200}
+ _, _ = sw2.Write([]byte("ok"))
+ if sw2.Code != 200 {
+ t.Errorf("expected default code 200, got %d", sw2.Code)
+ }
+}
+
+func TestJSON(t *testing.T) {
+ w := httptest.NewRecorder()
+ data := map[string]string{"foo": "bar"}
+ JSON(w, http.StatusCreated, data)
+
+ if w.Code != http.StatusCreated {
+ t.Errorf("expected status 201, got %d", w.Code)
+ }
+ if ct := w.Header().Get("Content-Type"); ct != "application/json" {
+ t.Errorf("expected content-type application/json, got %q", ct)
+ }
+ expectedBody := `{"foo":"bar"}` + "\n"
+ if w.Body.String() != expectedBody {
+ t.Errorf("expected body %q, got %q", expectedBody, w.Body.String())
+ }
+}
+
+func TestError(t *testing.T) {
+ w := httptest.NewRecorder()
+ err := fmt.Errorf("bad request")
+ Error(w, http.StatusBadRequest, err)
+
+ if w.Code != http.StatusBadRequest {
+ t.Errorf("expected status 400, got %d", w.Code)
+ }
+ expectedBody := `{"error":"bad request"}` + "\n"
+ if w.Body.String() != expectedBody {
+ t.Errorf("expected body %q, got %q", expectedBody, w.Body.String())
+ }
+}
diff --git a/lock.go b/lock.go
deleted file mode 100644
index 8ba0dd00..00000000
--- a/lock.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package main
-
-import (
- "fmt"
- "sync"
- "time"
-)
-
-type TabLock struct {
- Owner string `json:"owner"`
- LockedAt time.Time `json:"lockedAt"`
- ExpiresAt time.Time `json:"expiresAt"`
-}
-
-type lockManager struct {
- locks map[string]*TabLock
- mu sync.Mutex
-}
-
-const (
- defaultLockTimeout = 30 * time.Second
- maxLockTimeout = 5 * time.Minute
-)
-
-func newLockManager() *lockManager {
- return &lockManager{locks: make(map[string]*TabLock)}
-}
-
-func (lm *lockManager) Lock(tabID, owner string, timeout time.Duration) error {
- if owner == "" {
- return fmt.Errorf("owner required")
- }
- if timeout <= 0 {
- timeout = defaultLockTimeout
- }
- if timeout > maxLockTimeout {
- timeout = maxLockTimeout
- }
-
- lm.mu.Lock()
- defer lm.mu.Unlock()
-
- if existing, ok := lm.locks[tabID]; ok {
- if time.Now().Before(existing.ExpiresAt) && existing.Owner != owner {
- return fmt.Errorf("tab locked by %q until %s", existing.Owner, existing.ExpiresAt.Format(time.RFC3339))
- }
- }
-
- lm.locks[tabID] = &TabLock{
- Owner: owner,
- LockedAt: time.Now(),
- ExpiresAt: time.Now().Add(timeout),
- }
- return nil
-}
-
-func (lm *lockManager) Unlock(tabID, owner string) error {
- lm.mu.Lock()
- defer lm.mu.Unlock()
-
- existing, ok := lm.locks[tabID]
- if !ok {
- return nil
- }
-
- if existing.Owner != owner && time.Now().Before(existing.ExpiresAt) {
- return fmt.Errorf("tab locked by %q, cannot unlock", existing.Owner)
- }
-
- delete(lm.locks, tabID)
- return nil
-}
-
-func (lm *lockManager) Get(tabID string) *TabLock {
- lm.mu.Lock()
- defer lm.mu.Unlock()
-
- lock, ok := lm.locks[tabID]
- if !ok {
- return nil
- }
- if time.Now().After(lock.ExpiresAt) {
- delete(lm.locks, tabID)
- return nil
- }
- return lock
-}
-
-func (lm *lockManager) CheckAccess(tabID, owner string) error {
- lock := lm.Get(tabID)
- if lock == nil {
- return nil
- }
- if owner == "" || lock.Owner != owner {
- return fmt.Errorf("tab locked by %q until %s", lock.Owner, lock.ExpiresAt.Format(time.RFC3339))
- }
- return nil
-}
diff --git a/lock_test.go b/lock_test.go
deleted file mode 100644
index a6a622b3..00000000
--- a/lock_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package main
-
-import (
- "testing"
- "time"
-)
-
-func TestLockBasic(t *testing.T) {
- lm := newLockManager()
-
- if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {
- t.Fatal(err)
- }
-
- if err := lm.Lock("tab1", "agent-a", 5*time.Second); err != nil {
- t.Fatal(err)
- }
-
- if err := lm.Lock("tab1", "agent-b", 5*time.Second); err == nil {
- t.Fatal("expected lock conflict")
- }
-
- if err := lm.Unlock("tab1", "agent-a"); err != nil {
- t.Fatal(err)
- }
-
- if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestLockExpiry(t *testing.T) {
- lm := newLockManager()
-
- if err := lm.Lock("tab1", "agent-a", 1*time.Millisecond); err != nil {
- t.Fatal(err)
- }
- time.Sleep(5 * time.Millisecond)
-
- if err := lm.Lock("tab1", "agent-b", 5*time.Second); err != nil {
- t.Fatalf("expected expired lock to allow new owner: %v", err)
- }
-}
-
-func TestLockCheckAccess(t *testing.T) {
- lm := newLockManager()
-
- if err := lm.CheckAccess("tab1", "anyone"); err != nil {
- t.Fatal(err)
- }
-
- _ = lm.Lock("tab1", "agent-a", 5*time.Second)
-
- if err := lm.CheckAccess("tab1", "agent-a"); err != nil {
- t.Fatal(err)
- }
-
- if err := lm.CheckAccess("tab1", "agent-b"); err == nil {
- t.Fatal("expected access denied")
- }
-
- if err := lm.CheckAccess("tab1", ""); err == nil {
- t.Fatal("expected access denied for empty owner")
- }
-}
-
-func TestUnlockIdempotent(t *testing.T) {
- lm := newLockManager()
-
- if err := lm.Unlock("tab1", "anyone"); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestUnlockWrongOwner(t *testing.T) {
- lm := newLockManager()
- _ = lm.Lock("tab1", "agent-a", 5*time.Second)
-
- if err := lm.Unlock("tab1", "agent-b"); err == nil {
- t.Fatal("expected unlock denied for wrong owner")
- }
-}
-
-func TestMaxTimeout(t *testing.T) {
- lm := newLockManager()
- _ = lm.Lock("tab1", "agent-a", 10*time.Minute)
-
- lock := lm.Get("tab1")
- if lock == nil {
- t.Fatal("expected lock")
- }
-
- maxExpiry := time.Now().Add(maxLockTimeout + time.Second)
- if lock.ExpiresAt.After(maxExpiry) {
- t.Fatalf("lock timeout not capped: expires %v", lock.ExpiresAt)
- }
-}
-
-func TestLockRequiresOwner(t *testing.T) {
- lm := newLockManager()
- if err := lm.Lock("tab1", "", 5*time.Second); err == nil {
- t.Fatal("expected error for empty owner")
- }
-}
diff --git a/main.go b/main.go
deleted file mode 100644
index 31bdae38..00000000
--- a/main.go
+++ /dev/null
@@ -1,406 +0,0 @@
-package main
-
-import (
- "context"
- "fmt"
- "log/slog"
- "math/rand"
- "net/http"
- "os"
- "os/signal"
- "path/filepath"
- "strings"
- "sync"
- "syscall"
- "time"
-
- "github.com/chromedp/cdproto/emulation"
- "github.com/chromedp/cdproto/page"
- "github.com/chromedp/chromedp"
-)
-
-// commonWindowSizes are real-world desktop resolutions from StatCounter data.
-var commonWindowSizes = [][2]int{
- {1920, 1080}, {1366, 768}, {1536, 864}, {1440, 900},
- {1280, 720}, {1600, 900}, {2560, 1440}, {1280, 800},
-}
-
-func randomWindowSize() (int, int) {
- s := commonWindowSizes[rand.Intn(len(commonWindowSizes))]
- return s[0], s[1]
-}
-
-// version is set by goreleaser via ldflags
-var version = "dev"
-
-// chromeStartTimeout is the maximum time to wait for Chrome to connect via CDP.
-// If exceeded, Pinchtab clears session data and retries once.
-const chromeStartTimeout = 15 * time.Second
-
-var bridge Bridge
-
-func main() {
-
- loadConfig()
-
- if len(os.Args) > 1 && (os.Args[1] == "--version" || os.Args[1] == "-v") {
- fmt.Printf("pinchtab %s\n", version)
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "config" {
- handleConfigCommand()
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "connect" {
- handleConnectCommand()
- os.Exit(0)
- }
-
- if len(os.Args) > 1 && os.Args[1] == "dashboard" {
- runDashboard()
- return
- }
-
- if err := os.MkdirAll(cfg.StateDir, 0755); err != nil {
- slog.Error("cannot create state dir", "err", err)
- os.Exit(1)
- }
-
- allocCtx, allocCancel, chromeOpts := setupAllocator()
- defer allocCancel()
-
- stealthSeed := rand.Intn(1000000000)
- SetHumanRandSeed(int64(stealthSeed))
- seededScript := fmt.Sprintf("var __pinchtab_seed = %d;\nvar __pinchtab_stealth_level = %q;\n", stealthSeed, cfg.StealthLevel) + stealthScript
- bridge.stealthScript = seededScript
- bridge.allocCtx = allocCtx
-
- browserCtx, browserCancel, err := startChrome(seededScript)
- if err != nil {
- slog.Warn("Chrome startup failed, clearing sessions and retrying once", "err", err)
-
- allocCancel()
- clearChromeSessions()
- markCleanExit()
-
- allocCtx, allocCancel, _ = setupAllocator()
- bridge.allocCtx = allocCtx
- _ = chromeOpts // used implicitly via setupAllocator
-
- browserCtx, browserCancel, err = startChrome(seededScript)
- if err != nil {
- slog.Error("Chrome failed to start after retry",
- "err", err,
- "hint", "try BRIDGE_NO_RESTORE=true or delete your profile directory",
- "profile", cfg.ProfileDir,
- )
- allocCancel()
- os.Exit(1)
- }
- slog.Info("Chrome started on retry")
- }
- defer browserCancel()
-
- applyTimezone(browserCtx)
-
- bridge.browserCtx = browserCtx
- bridge.InitTabManager()
- bridge.initActionRegistry()
- bridge.locks = newLockManager()
-
- profilesDir := filepath.Join(filepath.Dir(cfg.ProfileDir), "profiles")
- profMgr := NewProfileManager(profilesDir)
- dashboard := NewDashboard(nil)
- orchestrator := NewOrchestrator(profilesDir)
- orchestrator.SetProfileManager(profMgr)
- dashboard.SetInstanceLister(orchestrator)
-
- initTargetID := chromedp.FromContext(browserCtx).Target.TargetID
- bridge.RegisterTab(string(initTargetID), browserCtx)
- slog.Info("initial tab", "id", string(initTargetID))
-
- if !cfg.Headless {
- go func() {
- time.Sleep(200 * time.Millisecond)
- _ = chromedp.Run(browserCtx, chromedp.Navigate("http://localhost:"+cfg.Port+"/welcome"))
- }()
- }
-
- if !cfg.NoRestore {
- go bridge.RestoreState()
- }
-
- cleanupCtx, cleanupCancel := context.WithCancel(context.Background())
- defer cleanupCancel()
- go bridge.CleanStaleTabs(cleanupCtx, 30*cfg.ActionTimeout)
-
- mux := http.NewServeMux()
- registerRoutes(mux, &bridge, profMgr, dashboard, orchestrator)
-
- profileObserver := func(evt AgentEvent) {
- if evt.Profile != "" {
- profMgr.RecordAction(evt.Profile, ActionRecord{
- Timestamp: evt.Timestamp,
- Method: strings.SplitN(evt.Action, " ", 2)[0],
- Endpoint: strings.SplitN(evt.Action, " ", 2)[1],
- URL: evt.URL,
- TabID: evt.TabID,
- DurationMs: evt.DurationMs,
- Status: evt.Status,
- })
- }
- }
-
- srv := &http.Server{Addr: cfg.ListenAddr(), Handler: dashboard.TrackingMiddleware(
- []EventObserver{profileObserver},
- loggingMiddleware(corsMiddleware(authMiddleware(mux))),
- )}
-
- shutdownOnce := &sync.Once{}
- doShutdown := func() {
- shutdownOnce.Do(func() {
- slog.Info("shutting down, saving state...")
- orchestrator.Shutdown()
- cleanupCancel()
- bridge.SaveState()
- markCleanExit()
-
- shutdownCtx, shutdownDone := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
- defer shutdownDone()
- if err := srv.Shutdown(shutdownCtx); err != nil {
- slog.Error("shutdown http", "err", err)
- }
-
- browserCancel()
- allocCancel()
- slog.Info("chrome closed")
- })
- }
-
- mux.HandleFunc("POST /shutdown", bridge.handleShutdown(doShutdown))
-
- setupSignalHandler(doShutdown, func() {
- orchestrator.ForceShutdown()
- cleanupCancel()
- browserCancel()
- allocCancel()
- })
-
- slog.Info("🦀 PINCH! PINCH!", "port", cfg.Port, "cdp", cfg.CdpURL, "stealth", cfg.StealthLevel)
- if cfg.Token != "" {
- slog.Info("auth enabled")
- } else {
- slog.Info("auth disabled (set BRIDGE_TOKEN to enable)")
- }
-
- go runStartupHealthCheck()
-
- if err := srv.ListenAndServe(); err != http.ErrServerClosed {
- slog.Error("server", "err", err)
- os.Exit(1)
- }
-}
-
-// setupAllocator creates the Chrome allocator context (remote or local).
-func setupAllocator() (context.Context, context.CancelFunc, []chromedp.ExecAllocatorOption) {
- if cfg.CdpURL != "" {
- slog.Info("connecting to Chrome", "url", cfg.CdpURL)
- ctx, cancel := chromedp.NewRemoteAllocator(context.Background(), cfg.CdpURL)
- return ctx, cancel, nil
- }
-
- if err := os.MkdirAll(cfg.ProfileDir, 0755); err != nil {
- slog.Error("cannot create profile dir", "err", err)
- os.Exit(1)
- }
-
- for _, lockName := range []string{"SingletonLock", "SingletonSocket", "SingletonCookie"} {
- lockPath := fmt.Sprintf("%s/%s", cfg.ProfileDir, lockName)
- if err := os.Remove(lockPath); err == nil {
- slog.Warn("removed stale lock", "file", lockName)
- }
- }
-
- if wasUncleanExit() {
- slog.Warn("previous session exited uncleanly, clearing Chrome session restore data")
- clearChromeSessions()
- }
-
- slog.Info("launching Chrome", "profile", cfg.ProfileDir, "headless", cfg.Headless)
-
- opts := buildChromeOpts()
-
- markCleanExit()
- ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
- return ctx, cancel, opts
-}
-
-// buildChromeOpts assembles the Chrome flags for local execution.
-func buildChromeOpts() []chromedp.ExecAllocatorOption {
- opts := []chromedp.ExecAllocatorOption{
- chromedp.UserDataDir(cfg.ProfileDir),
- chromedp.NoFirstRun,
- chromedp.NoDefaultBrowserCheck,
-
- chromedp.Flag("exclude-switches", "enable-automation"),
- chromedp.Flag("disable-infobars", true),
- chromedp.Flag("disable-dev-shm-usage", true),
- chromedp.Flag("disable-renderer-backgrounding", true),
- chromedp.Flag("disable-background-timer-throttling", true),
- chromedp.Flag("disable-backgrounding-occluded-windows", true),
- chromedp.Flag("disable-client-side-phishing-detection", true),
- chromedp.Flag("disable-default-apps", true),
- chromedp.Flag("disable-hang-monitor", true),
- chromedp.Flag("disable-prompt-on-repost", true),
- chromedp.Flag("disable-sync", true),
- chromedp.Flag("disable-web-security", false),
-
- chromedp.Flag("disable-background-networking", false),
- chromedp.Flag("enable-features", "NetworkService,NetworkServiceInProcess"),
- chromedp.Flag("disable-popup-blocking", true),
- chromedp.Flag("no-first-run", true),
-
- chromedp.Flag("disable-session-crashed-bubble", true),
- chromedp.Flag("hide-crash-restore-bubble", true),
- chromedp.Flag("disable-device-discovery-notifications", true),
-
- chromedp.Flag("js-flags", "--random-seed=1157259157"),
-
- chromedp.WindowSize(randomWindowSize()),
- }
-
- if cfg.ChromeBinary != "" {
- opts = append(opts, chromedp.ExecPath(cfg.ChromeBinary))
- }
- if cfg.ChromeExtraFlags != "" {
- for _, f := range strings.Fields(cfg.ChromeExtraFlags) {
- if k, v, ok := strings.Cut(f, "="); ok {
- opts = append(opts, chromedp.Flag(strings.TrimLeft(k, "-"), v))
- } else {
- opts = append(opts, chromedp.Flag(strings.TrimLeft(f, "-"), true))
- }
- }
- }
-
- if cfg.Headless {
- opts = append(opts, chromedp.Headless)
- } else {
- opts = append(opts, chromedp.Flag("headless", false))
- }
-
- return opts
-}
-
-// startChrome creates a browser context and injects the stealth script.
-func startChrome(seededScript string) (context.Context, context.CancelFunc, error) {
- bCtx, bCancel := chromedp.NewContext(bridge.allocCtx)
-
- startCtx, startDone := context.WithTimeout(context.Background(), chromeStartTimeout)
- defer startDone()
-
- errCh := make(chan error, 1)
- go func() {
- errCh <- chromedp.Run(bCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- _, err := page.AddScriptToEvaluateOnNewDocument(seededScript).Do(ctx)
- return err
- }),
- )
- }()
-
- select {
- case err := <-errCh:
- if err != nil {
- bCancel()
- return nil, nil, err
- }
- return bCtx, bCancel, nil
- case <-startCtx.Done():
- bCancel()
- return nil, nil, fmt.Errorf("timed out after %s", chromeStartTimeout)
- }
-}
-
-// applyTimezone sets the browser timezone override if configured.
-func applyTimezone(browserCtx context.Context) {
- if cfg.Timezone == "" {
- return
- }
- if err := chromedp.Run(browserCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return emulation.SetTimezoneOverride(cfg.Timezone).Do(ctx)
- }),
- ); err != nil {
- slog.Warn("timezone override failed", "tz", cfg.Timezone, "err", err)
- } else {
- slog.Info("timezone override", "tz", cfg.Timezone)
- }
-}
-
-// registerRoutes wires all HTTP handlers to the mux.
-func registerRoutes(mux *http.ServeMux, b *Bridge, profMgr ProfileService, dashboard *Dashboard, orchestrator OrchestratorService) {
- mux.HandleFunc("GET /health", b.handleHealth)
- mux.HandleFunc("GET /tabs", b.handleTabs)
- mux.HandleFunc("GET /snapshot", b.handleSnapshot)
- mux.HandleFunc("GET /screenshot", b.handleScreenshot)
- mux.HandleFunc("GET /text", b.handleText)
- mux.HandleFunc("POST /navigate", b.handleNavigate)
- mux.HandleFunc("POST /action", b.handleAction)
- mux.HandleFunc("POST /actions", b.handleActions)
- mux.HandleFunc("POST /evaluate", b.handleEvaluate)
- mux.HandleFunc("POST /tab", b.handleTab)
- mux.HandleFunc("POST /tab/lock", b.handleTabLock)
- mux.HandleFunc("POST /tab/unlock", b.handleTabUnlock)
- mux.HandleFunc("GET /cookies", b.handleGetCookies)
- mux.HandleFunc("POST /cookies", b.handleSetCookies)
- mux.HandleFunc("GET /stealth/status", b.handleStealthStatus)
- mux.HandleFunc("POST /fingerprint/rotate", b.handleFingerprintRotate)
- mux.HandleFunc("GET /screencast", b.handleScreencast)
- mux.HandleFunc("GET /screencast/tabs", b.handleScreencastAll)
- mux.HandleFunc("GET /welcome", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- _, _ = w.Write([]byte(welcomeHTML))
- })
-
- profMgr.RegisterHandlers(mux)
- dashboard.RegisterHandlers(mux)
- if os.Getenv("BRIDGE_NO_DASHBOARD") == "" {
- orchestrator.RegisterHandlers(mux)
- }
-}
-
-// setupSignalHandler listens for SIGINT/SIGTERM for graceful and force shutdown.
-func setupSignalHandler(shutdownFn func(), forceFn func()) {
- go func() {
- sig := make(chan os.Signal, 2)
- signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
- <-sig
- go shutdownFn()
- <-sig
- slog.Warn("force shutdown requested")
- forceFn()
- os.Exit(130)
- }()
-}
-
-// runStartupHealthCheck verifies the server is responding after launch.
-func runStartupHealthCheck() {
- time.Sleep(500 * time.Millisecond)
- client := &http.Client{Timeout: 5 * time.Second}
- resp, err := client.Get(fmt.Sprintf("http://localhost:%s/health", cfg.Port))
- if err != nil {
- slog.Error("startup health check failed",
- "err", err,
- "hint", "try BRIDGE_NO_RESTORE=true or delete your profile directory",
- )
- return
- }
- _ = resp.Body.Close()
- if resp.StatusCode == http.StatusOK {
- slog.Info("startup health check passed")
- } else {
- slog.Warn("startup health check unexpected status", "status", resp.StatusCode)
- }
-}
diff --git a/middleware.go b/middleware.go
deleted file mode 100644
index 2e14afaa..00000000
--- a/middleware.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package main
-
-import (
- "bufio"
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "net"
- "net/http"
- "time"
-)
-
-// statusWriter wraps ResponseWriter to capture the status code.
-// It preserves Hijacker and Flusher interfaces for WebSocket/SSE support.
-type statusWriter struct {
- http.ResponseWriter
- code int
-}
-
-func (w *statusWriter) WriteHeader(code int) {
- w.code = code
- w.ResponseWriter.WriteHeader(code)
-}
-
-func (w *statusWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
- if h, ok := w.ResponseWriter.(http.Hijacker); ok {
- return h.Hijack()
- }
- return nil, nil, fmt.Errorf("underlying ResponseWriter is not a Hijacker")
-}
-
-func (w *statusWriter) Flush() {
- if f, ok := w.ResponseWriter.(http.Flusher); ok {
- f.Flush()
- }
-}
-
-func loggingMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- start := time.Now()
- sw := &statusWriter{ResponseWriter: w, code: 200}
- next.ServeHTTP(sw, r)
- slog.Info("request",
- "method", r.Method,
- "path", r.URL.Path,
- "status", sw.code,
- "ms", time.Since(start).Milliseconds(),
- )
- })
-}
-
-func authMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if cfg.Token != "" {
- auth := r.Header.Get("Authorization")
- if auth != "Bearer "+cfg.Token {
- jsonErr(w, 401, fmt.Errorf("unauthorized"))
- return
- }
- }
- next.ServeHTTP(w, r)
- })
-}
-
-func corsMiddleware(next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Access-Control-Allow-Origin", "*")
- w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
- w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
- if r.Method == "OPTIONS" {
- w.WriteHeader(204)
- return
- }
- next.ServeHTTP(w, r)
- })
-}
-
-// cancelOnClientDone cancels the given cancel func when the HTTP client disconnects.
-func cancelOnClientDone(reqCtx context.Context, cancel context.CancelFunc) {
- <-reqCtx.Done()
- cancel()
-}
-
-func jsonResp(w http.ResponseWriter, code int, data any) {
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(code)
- if err := json.NewEncoder(w).Encode(data); err != nil {
- slog.Error("json encode", "err", err)
- }
-}
-
-func jsonErr(w http.ResponseWriter, code int, err error) {
- jsonResp(w, code, map[string]string{"error": err.Error()})
-}
diff --git a/orchestrator_handlers.go b/orchestrator_handlers.go
deleted file mode 100644
index 4a4ccc0e..00000000
--- a/orchestrator_handlers.go
+++ /dev/null
@@ -1,252 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "log/slog"
- "net"
- "net/http"
- "strings"
-)
-
-func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {
- mux.HandleFunc("GET /instances", o.handleList)
- mux.HandleFunc("POST /instances/launch", o.handleLaunch)
- mux.HandleFunc("POST /instances/{id}/stop", o.handleStop)
- mux.HandleFunc("GET /profiles/{name}/instance", o.handleProfileInstance)
- mux.HandleFunc("POST /profiles/{name}/stop", o.handleStopProfile)
- mux.HandleFunc("GET /instances/{id}/logs", o.handleLogs)
- mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)
- mux.HandleFunc("GET /instances/{id}/proxy/screencast", o.handleProxyScreencast)
- mux.HandleFunc("POST /start/{id}", o.handleStartByID)
- mux.HandleFunc("POST /stop/{id}", o.handleStopByID)
-}
-
-func (o *Orchestrator) handleList(w http.ResponseWriter, r *http.Request) {
- jsonResp(w, 200, o.List())
-}
-
-func (o *Orchestrator) handleLaunch(w http.ResponseWriter, r *http.Request) {
- var req struct {
- Name string `json:"name"`
- Port string `json:"port"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- jsonErr(w, 400, fmt.Errorf("invalid JSON"))
- return
- }
- if req.Name == "" || req.Port == "" {
- jsonErr(w, 400, fmt.Errorf("name and port required"))
- return
- }
-
- slog.Info("launch request", "profile", req.Name, "port", req.Port, "headed", true)
- inst, err := o.Launch(req.Name, req.Port, false)
- if isStartingConflict(err) {
- slog.Warn("launch blocked by starting instance; stopping and retrying", "profile", req.Name)
- if stopErr := o.StopProfile(req.Name); stopErr != nil {
- slog.Warn("failed to stop starting instance", "profile", req.Name, "err", stopErr)
- jsonErr(w, 409, err)
- return
- }
- inst, err = o.Launch(req.Name, req.Port, false)
- }
- if err != nil {
- slog.Warn("launch rejected", "profile", req.Name, "port", req.Port, "err", err)
- jsonErr(w, 409, err)
- return
- }
- slog.Info("launch accepted", "id", inst.ID, "profile", inst.Name, "port", inst.Port)
- jsonResp(w, 201, inst)
-}
-
-func (o *Orchestrator) handleStop(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- if err := o.Stop(id); err != nil {
- jsonErr(w, 404, err)
- return
- }
- jsonResp(w, 200, map[string]string{"status": "stopped", "id": id})
-}
-
-func (o *Orchestrator) handleProfileInstance(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- if name == "" {
- jsonErr(w, 400, fmt.Errorf("profile name required"))
- return
- }
- inst, ok := findProfileInstance(o.List(), name)
- if !ok {
- jsonResp(w, 200, map[string]any{
- "name": name,
- "running": false,
- "status": "stopped",
- "port": "",
- })
- return
- }
- jsonResp(w, 200, map[string]any{
- "name": name,
- "running": inst.Status == "running",
- "status": inst.Status,
- "port": inst.Port,
- "id": inst.ID,
- "pid": inst.PID,
- "error": inst.Error,
- })
-}
-
-func (o *Orchestrator) handleStopProfile(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- if name == "" {
- jsonErr(w, 400, fmt.Errorf("profile name required"))
- return
- }
- if err := o.StopProfile(name); err != nil {
- jsonErr(w, 404, err)
- return
- }
- jsonResp(w, 200, map[string]string{"status": "stopped", "name": name})
-}
-
-func (o *Orchestrator) handleLogs(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- logs, err := o.Logs(id)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
- w.Header().Set("Content-Type", "text/plain")
- _, _ = w.Write([]byte(logs))
-}
-
-func (o *Orchestrator) handleAllTabs(w http.ResponseWriter, r *http.Request) {
- jsonResp(w, 200, o.AllTabs())
-}
-
-func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- tabID := r.URL.Query().Get("tabId")
-
- o.mu.RLock()
- inst, ok := o.instances[id]
- o.mu.RUnlock()
- if !ok || inst.Status != "running" {
- http.Error(w, "instance not found or not running", 404)
- return
- }
-
- targetURL := fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
- jsonResp(w, 200, map[string]string{"wsUrl": targetURL})
-}
-
-func (o *Orchestrator) handleStartByID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- if o.profiles == nil {
- jsonErr(w, 500, fmt.Errorf("profile manager not configured"))
- return
- }
- name, err := o.profiles.FindByID(id)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- // Optional port from request body; auto-allocate if not provided.
- var req struct {
- Port string `json:"port"`
- Headless bool `json:"headless"`
- }
- _ = json.NewDecoder(r.Body).Decode(&req)
- port := req.Port
- if port == "" {
- p, err := findFreePort()
- if err != nil {
- jsonErr(w, 500, fmt.Errorf("failed to allocate port: %w", err))
- return
- }
- port = p
- }
-
- slog.Info("start-by-id request", "profileId", id, "profile", name, "port", port, "headless", req.Headless)
- inst, err := o.Launch(name, port, req.Headless)
- if isStartingConflict(err) {
- slog.Warn("start-by-id blocked by starting instance; stopping and retrying", "profile", name)
- if stopErr := o.StopProfile(name); stopErr != nil {
- jsonErr(w, 409, err)
- return
- }
- inst, err = o.Launch(name, port, req.Headless)
- }
- if err != nil {
- jsonErr(w, 409, err)
- return
- }
- jsonResp(w, 201, inst)
-}
-
-func (o *Orchestrator) handleStopByID(w http.ResponseWriter, r *http.Request) {
- id := r.PathValue("id")
- if o.profiles == nil {
- jsonErr(w, 500, fmt.Errorf("profile manager not configured"))
- return
- }
- name, err := o.profiles.FindByID(id)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
- if err := o.StopProfile(name); err != nil {
- jsonErr(w, 404, err)
- return
- }
- jsonResp(w, 200, map[string]string{"status": "stopped", "id": id, "name": name})
-}
-
-func findFreePort() (string, error) {
- l, err := net.Listen("tcp", "127.0.0.1:0")
- if err != nil {
- return "", err
- }
- port := l.Addr().(*net.TCPAddr).Port
- _ = l.Close()
- return fmt.Sprintf("%d", port), nil
-}
-
-func isStartingConflict(err error) bool {
- return err != nil && strings.Contains(err.Error(), "already has an active instance (starting)")
-}
-
-func findProfileInstance(instances []Instance, name string) (Instance, bool) {
- bestIdx := -1
- bestScore := -1
- for i := range instances {
- if instances[i].Name != name {
- continue
- }
- score := profileStatusScore(instances[i].Status)
- if bestIdx == -1 || score > bestScore || (score == bestScore && instances[i].StartedAt.After(instances[bestIdx].StartedAt)) {
- bestIdx = i
- bestScore = score
- }
- }
- if bestIdx == -1 {
- return Instance{}, false
- }
- return instances[bestIdx], true
-}
-
-func profileStatusScore(status string) int {
- switch status {
- case "running":
- return 5
- case "starting":
- return 4
- case "stopping":
- return 3
- case "error":
- return 2
- default:
- return 1
- }
-}
diff --git a/orchestrator_runtime.go b/orchestrator_runtime.go
deleted file mode 100644
index d6665e8f..00000000
--- a/orchestrator_runtime.go
+++ /dev/null
@@ -1,538 +0,0 @@
-package main
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log/slog"
- "net"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "sort"
- "strings"
- "sync"
- "time"
-)
-
-const (
- instanceHealthPollInterval = 500 * time.Millisecond
- instanceStartupTimeout = 45 * time.Second
-)
-
-func (o *Orchestrator) Launch(name, port string, headless bool) (*Instance, error) {
- o.mu.Lock()
- defer o.mu.Unlock()
-
- for _, inst := range o.instances {
- if inst.Port == port && instanceIsActive(inst) {
- return nil, fmt.Errorf("port %s already in use by instance %q", port, inst.Name)
- }
- if inst.Name == name && instanceIsActive(inst) {
- return nil, fmt.Errorf("profile %q already has an active instance (%s)", name, inst.Status)
- }
- }
- if !isPortAvailable(port) {
- return nil, fmt.Errorf("port %s is already in use on this machine", port)
- }
-
- id := fmt.Sprintf("%s-%s", name, port)
- if inst, ok := o.instances[id]; ok && inst.Status == "running" {
- return nil, fmt.Errorf("instance %q already running", id)
- }
-
- profilePath := filepath.Join(o.baseDir, name)
- if err := os.MkdirAll(filepath.Join(profilePath, "Default"), 0755); err != nil {
- return nil, fmt.Errorf("create profile dir: %w", err)
- }
- instanceStateDir := filepath.Join(profilePath, ".pinchtab-state")
- if err := os.MkdirAll(instanceStateDir, 0755); err != nil {
- return nil, fmt.Errorf("create state dir: %w", err)
- }
-
- ctx, cancel := context.WithCancel(context.Background())
-
- headlessStr := "true"
- if !headless {
- headlessStr = "false"
- }
-
- cmd := exec.CommandContext(ctx, o.binary)
- cmd.Env = mergeEnvWithOverrides(os.Environ(), map[string]string{
- "BRIDGE_PORT": port,
- "BRIDGE_PROFILE": profilePath,
- "BRIDGE_STATE_DIR": instanceStateDir,
- "BRIDGE_HEADLESS": headlessStr,
- "BRIDGE_NO_RESTORE": "true",
- "BRIDGE_NO_DASHBOARD": "true",
- })
- slog.Info("starting instance process", "id", id, "binary", o.binary, "port", port, "profile", profilePath)
- setProcGroup(cmd)
-
- logBuf := newRingBuffer(64 * 1024)
- cmd.Stdout = logBuf
- cmd.Stderr = logBuf
-
- inst := &Instance{
- ID: id,
- Name: name,
- Profile: profilePath,
- Port: port,
- Headless: headless,
- Status: "starting",
- StartedAt: time.Now(),
- URL: fmt.Sprintf("http://localhost:%s", port),
- cmd: cmd,
- cancel: cancel,
- logBuf: logBuf,
- }
-
- if err := cmd.Start(); err != nil {
- cancel()
- return nil, fmt.Errorf("failed to start: %w", err)
- }
-
- inst.PID = cmd.Process.Pid
- o.instances[id] = inst
-
- go o.monitor(inst)
-
- return inst, nil
-}
-
-func (o *Orchestrator) monitor(inst *Instance) {
- healthy := false
- exitedEarly := false
- lastProbe := "no response"
- resolvedURL := ""
- waitCh := make(chan error, 1)
- go func() {
- waitCh <- inst.cmd.Wait()
- }()
- var waitErr error
- started := time.Now()
- for time.Since(started) < instanceStartupTimeout {
- select {
- case waitErr = <-waitCh:
- exitedEarly = true
- default:
- }
- if exitedEarly {
- break
- }
- time.Sleep(instanceHealthPollInterval)
-
- for _, baseURL := range instanceBaseURLs(inst.Port) {
- resp, err := o.client.Get(baseURL + "/health")
- if err == nil {
- _ = resp.Body.Close()
- lastProbe = fmt.Sprintf("%s -> HTTP %d", baseURL, resp.StatusCode)
- if isInstanceHealthyStatus(resp.StatusCode) {
- healthy = true
- resolvedURL = baseURL
- break
- }
- } else {
- lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())
- }
- }
- if healthy {
- break
- }
- }
-
- o.mu.Lock()
- switch inst.Status {
- case "stopping", "stopped":
- default:
- if healthy {
- inst.Status = "running"
- if resolvedURL != "" {
- inst.URL = resolvedURL
- }
- slog.Info("instance ready", "id", inst.ID, "port", inst.Port)
- } else if exitedEarly {
- inst.Status = "error"
- if waitErr != nil {
- inst.Error = "process exited before health check: " + waitErr.Error()
- } else {
- inst.Error = "process exited before health check succeeded"
- }
- if tail := tailLogLine(inst.logBuf.String()); tail != "" {
- inst.Error += " | " + tail
- }
- slog.Error("instance exited before ready", "id", inst.ID)
- } else {
- inst.Status = "error"
- inst.Error = fmt.Sprintf("health check timeout after %s (%s)", instanceStartupTimeout, lastProbe)
- if tail := tailLogLine(inst.logBuf.String()); tail != "" {
- inst.Error += " | " + tail
- }
- slog.Error("instance failed to start", "id", inst.ID)
- }
- }
- o.mu.Unlock()
-
- if !exitedEarly {
- waitErr = <-waitCh
- }
- o.mu.Lock()
- if inst.Status == "running" || inst.Status == "stopping" {
- inst.Status = "stopped"
- if waitErr != nil {
- inst.Error = waitErr.Error()
- }
- }
- o.mu.Unlock()
- slog.Info("instance exited", "id", inst.ID)
-}
-
-func (o *Orchestrator) Stop(id string) error {
- o.mu.Lock()
- inst, ok := o.instances[id]
- if !ok {
- o.mu.Unlock()
- return fmt.Errorf("instance %q not found", id)
- }
- if inst.Status == "stopped" && !instanceIsActive(inst) {
- o.mu.Unlock()
- return nil
- }
- inst.Status = "stopping"
- o.mu.Unlock()
-
- if inst.cmd == nil || inst.cmd.Process == nil {
- o.markStopped(id)
- return nil
- }
- if inst.PID <= 0 {
- inst.cancel()
- o.markStopped(id)
- return nil
- }
-
- reqCtx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
- defer cancel()
- req, _ := http.NewRequestWithContext(reqCtx, http.MethodPost, inst.URL+"/shutdown", nil)
- resp, err := o.client.Do(req)
- if err == nil {
- _ = resp.Body.Close()
- }
-
- if waitForProcessExit(inst.PID, 5*time.Second) {
- o.markStopped(id)
- return nil
- }
-
- if err := killProcessGroup(inst.PID, sigTERM); err != nil {
- slog.Warn("failed to send SIGTERM to instance", "id", id, "pid", inst.PID, "err", err)
- }
- if waitForProcessExit(inst.PID, 3*time.Second) {
- o.markStopped(id)
- return nil
- }
-
- if err := killProcessGroup(inst.PID, sigKILL); err != nil {
- slog.Warn("failed to send SIGKILL to instance", "id", id, "pid", inst.PID, "err", err)
- }
- inst.cancel()
- if waitForProcessExit(inst.PID, 2*time.Second) {
- o.markStopped(id)
- return nil
- }
-
- o.setStopError(id, fmt.Sprintf("failed to stop process %d; still running", inst.PID))
- return fmt.Errorf("failed to stop instance %q gracefully", id)
-}
-
-func (o *Orchestrator) StopProfile(name string) error {
- o.mu.RLock()
- ids := make([]string, 0, 1)
- for id, inst := range o.instances {
- if inst.Name == name && instanceIsActive(inst) {
- ids = append(ids, id)
- }
- }
- o.mu.RUnlock()
-
- if len(ids) == 0 {
- return fmt.Errorf("no active instance for profile %q", name)
- }
-
- var errs []string
- for _, id := range ids {
- if err := o.Stop(id); err != nil {
- errs = append(errs, err.Error())
- }
- }
- if len(errs) > 0 {
- return fmt.Errorf("failed to stop profile %q: %s", name, strings.Join(errs, "; "))
- }
- return nil
-}
-
-func (o *Orchestrator) markStopped(id string) {
- o.mu.Lock()
- defer o.mu.Unlock()
- if inst, ok := o.instances[id]; ok {
- inst.Status = "stopped"
- }
-}
-
-func (o *Orchestrator) setStopError(id, msg string) {
- o.mu.Lock()
- defer o.mu.Unlock()
- if inst, ok := o.instances[id]; ok {
- inst.Status = "error"
- inst.Error = msg
- }
-}
-
-func instanceIsActive(inst *Instance) bool {
- if inst == nil {
- return false
- }
- if inst.PID > 0 {
- return isProcessAlive(inst.PID)
- }
- return inst.Status == "starting" || inst.Status == "running" || inst.Status == "stopping"
-}
-
-func waitForProcessExit(pid int, timeout time.Duration) bool {
- if pid <= 0 {
- return true
- }
- deadline := time.Now().Add(timeout)
- for time.Now().Before(deadline) {
- if !isProcessAlive(pid) {
- return true
- }
- time.Sleep(150 * time.Millisecond)
- }
- return !isProcessAlive(pid)
-}
-
-func isProcessAlive(pid int) bool {
- return processAlive(pid)
-}
-
-func (o *Orchestrator) List() []Instance {
- o.mu.RLock()
- defer o.mu.RUnlock()
-
- result := make([]Instance, 0, len(o.instances))
- for _, inst := range o.instances {
- copyInst := *inst
- copyInst.cmd = nil
- copyInst.cancel = nil
- copyInst.logBuf = nil
- if instanceIsActive(inst) && copyInst.Status == "stopped" {
- copyInst.Status = "running"
- }
- if !instanceIsActive(inst) &&
- (copyInst.Status == "starting" || copyInst.Status == "running" || copyInst.Status == "stopping") {
- copyInst.Status = "stopped"
- }
-
- result = append(result, copyInst)
- }
- return result
-}
-
-func (o *Orchestrator) Logs(id string) (string, error) {
- o.mu.RLock()
- defer o.mu.RUnlock()
-
- inst, ok := o.instances[id]
- if !ok {
- return "", fmt.Errorf("instance %q not found", id)
- }
- return inst.logBuf.String(), nil
-}
-
-func (o *Orchestrator) FirstRunningURL() string {
- o.mu.RLock()
- defer o.mu.RUnlock()
- for _, inst := range o.instances {
- if inst.Status == "running" && instanceIsActive(inst) {
- return inst.URL
- }
- }
- return ""
-}
-
-func (o *Orchestrator) AllTabs() []instanceTab {
- o.mu.RLock()
- instances := make([]*Instance, 0)
- for _, inst := range o.instances {
- if inst.Status == "running" && instanceIsActive(inst) {
- instances = append(instances, inst)
- }
- }
- o.mu.RUnlock()
-
- var all []instanceTab
- for _, inst := range instances {
- tabs, err := o.fetchTabs(inst.URL)
- if err != nil {
- continue
- }
- for _, tab := range tabs {
- all = append(all, instanceTab{
- InstanceID: inst.ID,
- InstanceName: inst.Name,
- InstancePort: inst.Port,
- TabID: tab.ID,
- URL: tab.URL,
- })
- }
- }
- return all
-}
-
-type instanceTab struct {
- InstanceID string `json:"instanceId"`
- InstanceName string `json:"instanceName"`
- InstancePort string `json:"instancePort"`
- TabID string `json:"tabId"`
- URL string `json:"url"`
-}
-
-type remoteTab struct {
- ID string `json:"id"`
- URL string `json:"url"`
-}
-
-func (o *Orchestrator) fetchTabs(baseURL string) ([]remoteTab, error) {
- resp, err := o.client.Get(baseURL + "/screencast/tabs")
- if err != nil {
- return nil, err
- }
- defer func() { _ = resp.Body.Close() }()
-
- var tabs []remoteTab
- if err := json.NewDecoder(resp.Body).Decode(&tabs); err != nil {
- return nil, err
- }
- return tabs, nil
-}
-
-func (o *Orchestrator) ScreencastURL(instanceID, tabID string) string {
- o.mu.RLock()
- defer o.mu.RUnlock()
- inst, ok := o.instances[instanceID]
- if !ok {
- return ""
- }
- return fmt.Sprintf("ws://localhost:%s/screencast?tabId=%s", inst.Port, tabID)
-}
-
-func (o *Orchestrator) Shutdown() {
- o.mu.RLock()
- ids := make([]string, 0, len(o.instances))
- for id, inst := range o.instances {
- if instanceIsActive(inst) {
- ids = append(ids, id)
- }
- }
- o.mu.RUnlock()
-
- var wg sync.WaitGroup
- for _, id := range ids {
- wg.Add(1)
- go func(instanceID string) {
- defer wg.Done()
- slog.Info("stopping instance", "id", instanceID)
- if err := o.Stop(instanceID); err != nil {
- slog.Warn("stop instance failed", "id", instanceID, "err", err)
- }
- }(id)
- }
- wg.Wait()
-}
-
-func isPortAvailable(port string) bool {
- ln, err := net.Listen("tcp", ":"+port)
- if err != nil {
- return false
- }
- _ = ln.Close()
- return true
-}
-
-func (o *Orchestrator) ForceShutdown() {
- o.mu.RLock()
- instances := make([]*Instance, 0, len(o.instances))
- for _, inst := range o.instances {
- if instanceIsActive(inst) {
- instances = append(instances, inst)
- }
- }
- o.mu.RUnlock()
-
- for _, inst := range instances {
- if inst.PID > 0 {
- _ = killProcessGroup(inst.PID, sigKILL)
- }
- if inst.cancel != nil {
- inst.cancel()
- }
- o.markStopped(inst.ID)
- }
-}
-
-func isInstanceHealthyStatus(code int) bool {
- return code > 0 && code < http.StatusInternalServerError
-}
-
-func instanceBaseURLs(port string) []string {
- return []string{
- fmt.Sprintf("http://127.0.0.1:%s", port),
- fmt.Sprintf("http://[::1]:%s", port),
- fmt.Sprintf("http://localhost:%s", port),
- }
-}
-
-func tailLogLine(logs string) string {
- if logs == "" {
- return ""
- }
- lines := strings.Split(strings.TrimSpace(logs), "\n")
- for i := len(lines) - 1; i >= 0; i-- {
- line := strings.TrimSpace(lines[i])
- if line == "" {
- continue
- }
- const max = 220
- if len(line) > max {
- return line[len(line)-max:]
- }
- return line
- }
- return ""
-}
-
-func mergeEnvWithOverrides(base []string, overrides map[string]string) []string {
- out := make([]string, 0, len(base)+len(overrides))
- for _, kv := range base {
- key, _, ok := strings.Cut(kv, "=")
- if !ok {
- continue
- }
- if _, exists := overrides[key]; exists {
- continue
- }
- out = append(out, kv)
- }
-
- keys := make([]string, 0, len(overrides))
- for k := range overrides {
- keys = append(keys, k)
- }
- sort.Strings(keys)
- for _, k := range keys {
- out = append(out, k+"="+overrides[k])
- }
- return out
-}
diff --git a/orchestrator_runtime_test.go b/orchestrator_runtime_test.go
deleted file mode 100644
index a313fd9b..00000000
--- a/orchestrator_runtime_test.go
+++ /dev/null
@@ -1,183 +0,0 @@
-package main
-
-import (
- "fmt"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time"
-)
-
-func TestInstanceIsActiveStoppedButAlivePID(t *testing.T) {
- inst := &Instance{Status: "stopped", PID: os.Getpid()}
- if !instanceIsActive(inst) {
- t.Fatal("expected instance to be active when pid is alive")
- }
-}
-
-func TestLaunchRejectsStoppedButActiveInstance(t *testing.T) {
- o := &Orchestrator{
- instances: map[string]*Instance{
- "p1-9911": {
- ID: "p1-9911",
- Name: "p1",
- Port: "9911",
- Status: "stopped",
- PID: os.Getpid(),
- },
- },
- baseDir: t.TempDir(),
- binary: "pinchtab",
- client: &http.Client{Timeout: 10 * time.Millisecond},
- }
-
- _, err := o.Launch("p1", "9911", true)
- if err == nil {
- t.Fatal("expected launch to fail for active profile")
- }
- if !strings.Contains(err.Error(), "already has an active instance") && !strings.Contains(err.Error(), "already in use") {
- t.Fatalf("unexpected error: %v", err)
- }
-}
-
-func TestListReconcilesStoppedButAliveToRunning(t *testing.T) {
- o := &Orchestrator{
- instances: map[string]*Instance{
- "p1-9912": {
- ID: "p1-9912",
- Name: "p1",
- Port: "9912",
- Status: "stopped",
- PID: os.Getpid(),
- URL: "http://127.0.0.1:1",
- },
- },
- client: &http.Client{Timeout: 10 * time.Millisecond},
- }
-
- list := o.List()
- if len(list) != 1 {
- t.Fatalf("expected 1 instance, got %d", len(list))
- }
- if list[0].Status != "running" {
- t.Fatalf("expected reconciled status running, got %q", list[0].Status)
- }
-}
-
-func TestMergeEnvWithOverridesReplacesExistingValues(t *testing.T) {
- base := []string{
- "BRIDGE_PORT=9870",
- "BRIDGE_HEADLESS=true",
- "PATH=/usr/bin",
- }
- merged := mergeEnvWithOverrides(base, map[string]string{
- "BRIDGE_PORT": "9868",
- "BRIDGE_HEADLESS": "false",
- "BRIDGE_PROFILE": "/tmp/profile",
- })
- joined := strings.Join(merged, "\n")
-
- if strings.Contains(joined, "BRIDGE_PORT=9870") {
- t.Fatalf("expected old BRIDGE_PORT to be removed, got %v", merged)
- }
- if !strings.Contains(joined, "BRIDGE_PORT=9868") {
- t.Fatalf("expected overridden BRIDGE_PORT, got %v", merged)
- }
- if !strings.Contains(joined, "BRIDGE_HEADLESS=false") {
- t.Fatalf("expected overridden BRIDGE_HEADLESS, got %v", merged)
- }
- if !strings.Contains(joined, "BRIDGE_PROFILE=/tmp/profile") {
- t.Fatalf("expected BRIDGE_PROFILE override, got %v", merged)
- }
-}
-
-func TestIsInstanceHealthyStatus(t *testing.T) {
- tests := []struct {
- code int
- ok bool
- }{
- {code: 200, ok: true},
- {code: 401, ok: true},
- {code: 404, ok: true},
- {code: 500, ok: false},
- {code: 503, ok: false},
- }
- for _, tt := range tests {
- if got := isInstanceHealthyStatus(tt.code); got != tt.ok {
- t.Fatalf("code %d: got %v, want %v", tt.code, got, tt.ok)
- }
- }
-}
-
-func TestIsStartingConflict(t *testing.T) {
- if !isStartingConflict(fmt.Errorf(`profile "x" already has an active instance (starting)`)) {
- t.Fatal("expected starting conflict to match")
- }
- if isStartingConflict(fmt.Errorf(`profile "x" already has an active instance (running)`)) {
- t.Fatal("did not expect running conflict to match")
- }
-}
-
-func TestFindProfileInstancePrefersRunning(t *testing.T) {
- now := time.Now()
- inst, ok := findProfileInstance([]Instance{
- {Name: "alpha", Status: "error", Port: "9868", StartedAt: now.Add(-time.Minute)},
- {Name: "alpha", Status: "running", Port: "9869", StartedAt: now},
- {Name: "beta", Status: "running", Port: "9870", StartedAt: now},
- }, "alpha")
- if !ok {
- t.Fatal("expected instance for alpha")
- }
- if inst.Status != "running" || inst.Port != "9869" {
- t.Fatalf("unexpected selected instance: %+v", inst)
- }
-}
-
-func TestFindProfileInstanceMissing(t *testing.T) {
- _, ok := findProfileInstance([]Instance{{Name: "a", Status: "stopped"}}, "nope")
- if ok {
- t.Fatal("expected no instance")
- }
-}
-
-func TestInstanceBaseURLs(t *testing.T) {
- got := instanceBaseURLs("9869")
- if len(got) != 3 {
- t.Fatalf("expected 3 base URLs, got %d", len(got))
- }
- if got[0] != "http://127.0.0.1:9869" {
- t.Fatalf("unexpected IPv4 URL: %s", got[0])
- }
- if got[1] != "http://[::1]:9869" {
- t.Fatalf("unexpected IPv6 URL: %s", got[1])
- }
- if got[2] != "http://localhost:9869" {
- t.Fatalf("unexpected localhost URL: %s", got[2])
- }
-}
-
-func TestTailLogLine(t *testing.T) {
- got := tailLogLine("\nfirst\n\nsecond\n")
- if got != "second" {
- t.Fatalf("unexpected tail line: %q", got)
- }
-}
-
-func TestNewOrchestratorPrefersCurrentExecutable(t *testing.T) {
- exe, err := os.Executable()
- if err != nil || exe == "" {
- t.Skip("no executable path available")
- }
-
- base := filepath.Join(t.TempDir(), "profiles")
- if err := os.MkdirAll(base, 0755); err != nil {
- t.Fatalf("mkdir base: %v", err)
- }
-
- o := NewOrchestrator(base)
- if o.binary != exe {
- t.Fatalf("expected binary %q, got %q", exe, o.binary)
- }
-}
diff --git a/orchestrator_types.go b/orchestrator_types.go
deleted file mode 100644
index 79c56df6..00000000
--- a/orchestrator_types.go
+++ /dev/null
@@ -1,123 +0,0 @@
-package main
-
-import (
- "context"
- "io"
- "log/slog"
- "net/http"
- "os"
- "os/exec"
- "path/filepath"
- "sync"
- "time"
-)
-
-type Orchestrator struct {
- instances map[string]*Instance
- baseDir string
- binary string
- profiles *ProfileManager
- mu sync.RWMutex
- client *http.Client
-}
-
-type Instance struct {
- ID string `json:"id"`
- Name string `json:"name"`
- Profile string `json:"profile"`
- Port string `json:"port"`
- Headless bool `json:"headless"`
- Status string `json:"status"`
- PID int `json:"pid,omitempty"`
- StartedAt time.Time `json:"startedAt"`
- Error string `json:"error,omitempty"`
- TabCount int `json:"tabCount"`
- URL string `json:"url"`
-
- cmd *exec.Cmd
- cancel context.CancelFunc
- logBuf *ringBuffer
-}
-
-type ringBuffer struct {
- mu sync.Mutex
- data []byte
- max int
-}
-
-func newRingBuffer(max int) *ringBuffer {
- return &ringBuffer{max: max, data: make([]byte, 0, max)}
-}
-
-func (rb *ringBuffer) Write(p []byte) (int, error) {
- rb.mu.Lock()
- defer rb.mu.Unlock()
- rb.data = append(rb.data, p...)
- if len(rb.data) > rb.max {
- rb.data = rb.data[len(rb.data)-rb.max:]
- }
- return len(p), nil
-}
-
-func (rb *ringBuffer) String() string {
- rb.mu.Lock()
- defer rb.mu.Unlock()
- return string(rb.data)
-}
-
-func NewOrchestrator(baseDir string) *Orchestrator {
- binDir := filepath.Join(filepath.Dir(baseDir), "bin")
- stableBin := filepath.Join(binDir, "pinchtab")
- exe, _ := os.Executable()
- binary := exe
- if binary == "" {
- binary = os.Args[0]
- }
-
- if err := os.MkdirAll(binDir, 0755); err != nil {
- slog.Warn("failed to create bin directory", "path", binDir, "err", err)
- }
-
- if exe != "" {
- if err := installStableBinary(exe, stableBin); err != nil {
- slog.Warn("failed to install pinchtab binary", "path", stableBin, "err", err)
- } else {
- slog.Info("installed pinchtab binary", "path", stableBin)
- }
- }
-
- if _, err := os.Stat(binary); err != nil {
- if _, stableErr := os.Stat(stableBin); stableErr == nil {
- binary = stableBin
- }
- }
-
- return &Orchestrator{
- instances: make(map[string]*Instance),
- baseDir: baseDir,
- binary: binary,
- client: &http.Client{Timeout: 3 * time.Second},
- }
-}
-
-// SetProfileManager sets the profile manager for ID-based lookups.
-func (o *Orchestrator) SetProfileManager(pm *ProfileManager) {
- o.profiles = pm
-}
-
-func installStableBinary(src, dst string) error {
- in, err := os.Open(src)
- if err != nil {
- return err
- }
- defer func() { _ = in.Close() }()
-
- out, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
- if err != nil {
- return err
- }
- defer func() { _ = out.Close() }()
-
- _, err = io.Copy(out, in)
- return err
-}
diff --git a/profiles_handlers.go b/profiles_handlers.go
deleted file mode 100644
index a34cacf5..00000000
--- a/profiles_handlers.go
+++ /dev/null
@@ -1,198 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "fmt"
- "net/http"
- "time"
-)
-
-func (pm *ProfileManager) RegisterHandlers(mux *http.ServeMux) {
- mux.HandleFunc("GET /profiles", pm.handleList)
- mux.HandleFunc("POST /profiles/import", pm.handleImport)
- mux.HandleFunc("POST /profiles/create", pm.handleCreate)
- mux.HandleFunc("PATCH /profiles/{name}", pm.handleUpdate)
- mux.HandleFunc("POST /profiles/{name}/reset", pm.handleReset)
- mux.HandleFunc("DELETE /profiles/{name}", pm.handleDelete)
- mux.HandleFunc("GET /profiles/{name}/logs", pm.handleLogs)
- mux.HandleFunc("GET /profiles/{name}/analytics", pm.handleAnalytics)
-}
-
-func (pm *ProfileManager) handleList(w http.ResponseWriter, r *http.Request) {
- profiles, err := pm.List()
- if err != nil {
- jsonErr(w, http.StatusInternalServerError, err)
- return
- }
- jsonResp(w, http.StatusOK, profiles)
-}
-
-func (pm *ProfileManager) handleImport(w http.ResponseWriter, r *http.Request) {
- var req struct {
- Name string `json:"name"`
- Source string `json:"source"`
- UseWhen string `json:"useWhen"`
- Description string `json:"description"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))
- return
- }
- if req.Name == "" || req.Source == "" {
- jsonErr(w, http.StatusBadRequest, fmt.Errorf("name and source required"))
- return
- }
-
- // Import with metadata if provided
- if req.UseWhen != "" || req.Description != "" {
- meta := ProfileMeta{
- UseWhen: req.UseWhen,
- Description: req.Description,
- }
- if err := pm.ImportWithMeta(req.Name, req.Source, meta); err != nil {
- jsonErr(w, http.StatusConflict, err)
- return
- }
- } else {
- if err := pm.Import(req.Name, req.Source); err != nil {
- jsonErr(w, http.StatusConflict, err)
- return
- }
- }
- jsonResp(w, http.StatusCreated, map[string]string{"status": "imported", "name": req.Name})
-}
-
-func (pm *ProfileManager) handleCreate(w http.ResponseWriter, r *http.Request) {
- var req struct {
- Name string `json:"name"`
- UseWhen string `json:"useWhen"`
- Description string `json:"description"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))
- return
- }
- if req.Name == "" {
- jsonErr(w, http.StatusBadRequest, fmt.Errorf("name required"))
- return
- }
-
- // Create with metadata if provided
- if req.UseWhen != "" || req.Description != "" {
- meta := ProfileMeta{
- UseWhen: req.UseWhen,
- Description: req.Description,
- }
- if err := pm.CreateWithMeta(req.Name, meta); err != nil {
- jsonErr(w, http.StatusConflict, err)
- return
- }
- } else {
- if err := pm.Create(req.Name); err != nil {
- jsonErr(w, http.StatusConflict, err)
- return
- }
- }
- jsonResp(w, http.StatusCreated, map[string]string{"status": "created", "name": req.Name})
-}
-
-func (pm *ProfileManager) handleReset(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- if err := pm.Reset(name); err != nil {
- jsonErr(w, http.StatusNotFound, err)
- return
- }
- jsonResp(w, http.StatusOK, map[string]string{"status": "reset", "name": name})
-}
-
-func (pm *ProfileManager) handleDelete(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- if err := pm.Delete(name); err != nil {
- jsonErr(w, http.StatusNotFound, err)
- return
- }
- jsonResp(w, http.StatusOK, map[string]string{"status": "deleted", "name": name})
-}
-
-func (pm *ProfileManager) handleLogs(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- limit := profileQueryInt(r, "limit", 100)
- logs := pm.Logs(name, limit)
- jsonResp(w, http.StatusOK, logs)
-}
-
-func (pm *ProfileManager) handleAnalytics(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- report := pm.Analytics(name)
- jsonResp(w, http.StatusOK, report)
-}
-
-func (pm *ProfileManager) handleUpdate(w http.ResponseWriter, r *http.Request) {
- name := r.PathValue("name")
- var req struct {
- Name string `json:"name"`
- UseWhen string `json:"useWhen"`
- Description string `json:"description"`
- }
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- jsonErr(w, http.StatusBadRequest, fmt.Errorf("invalid JSON"))
- return
- }
-
- meta := map[string]string{
- "useWhen": req.UseWhen,
- "description": req.Description,
- }
- if err := pm.UpdateMeta(name, meta); err != nil {
- jsonErr(w, http.StatusNotFound, err)
- return
- }
-
- if req.Name != "" && req.Name != name {
- if err := pm.Rename(name, req.Name); err != nil {
- jsonErr(w, http.StatusConflict, err)
- return
- }
- name = req.Name
- }
-
- // Return updated profile info
- info, err := pm.profileInfo(name)
- if err != nil {
- jsonErr(w, http.StatusNotFound, err)
- return
- }
- jsonResp(w, http.StatusOK, info)
-}
-
-func (pm *ProfileManager) TrackingMiddleware(profileName string, next http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- start := time.Now()
- sw := &statusWriter{ResponseWriter: w, code: 200}
- next.ServeHTTP(sw, r)
-
- rec := ActionRecord{
- Timestamp: start,
- Method: r.Method,
- Endpoint: r.URL.Path,
- URL: r.URL.Query().Get("url"),
- TabID: r.URL.Query().Get("tabId"),
- DurationMs: time.Since(start).Milliseconds(),
- Status: sw.code,
- }
- pm.tracker.Record(profileName, rec)
- })
-}
-
-func profileQueryInt(r *http.Request, key string, def int) int {
- s := r.URL.Query().Get(key)
- if s == "" {
- return def
- }
- var n int
- _, _ = fmt.Sscanf(s, "%d", &n)
- if n <= 0 {
- return def
- }
- return n
-}
diff --git a/profiles_tracker.go b/profiles_tracker.go
deleted file mode 100644
index a6cbe4a8..00000000
--- a/profiles_tracker.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package main
-
-import (
- "fmt"
- "sort"
- "strings"
- "sync"
- "time"
-)
-
-type ActionTracker struct {
- mu sync.Mutex
- records map[string][]ActionRecord
-}
-
-type ActionRecord struct {
- Timestamp time.Time `json:"timestamp"`
- Method string `json:"method"`
- Endpoint string `json:"endpoint"`
- URL string `json:"url,omitempty"`
- TabID string `json:"tabId,omitempty"`
- DurationMs int64 `json:"durationMs"`
- Status int `json:"status"`
-}
-
-type AnalyticsReport struct {
- TotalActions int `json:"totalActions"`
- Since time.Time `json:"since"`
- TopEndpoints []EndpointCount `json:"topEndpoints"`
- RepeatPatterns []RepeatPattern `json:"repeatPatterns"`
- Suggestions []string `json:"suggestions"`
-}
-
-type EndpointCount struct {
- Endpoint string `json:"endpoint"`
- Count int `json:"count"`
- AvgMs int64 `json:"avgMs"`
-}
-
-type RepeatPattern struct {
- Pattern string `json:"pattern"`
- Count int `json:"count"`
- AvgGapSec float64 `json:"avgGapSec"`
-}
-
-func NewActionTracker() *ActionTracker {
- return &ActionTracker{records: make(map[string][]ActionRecord)}
-}
-
-func (at *ActionTracker) Record(profile string, rec ActionRecord) {
- at.mu.Lock()
- defer at.mu.Unlock()
-
- recs := at.records[profile]
- recs = append(recs, rec)
- if len(recs) > 10000 {
- recs = recs[len(recs)-10000:]
- }
- at.records[profile] = recs
-}
-
-func (at *ActionTracker) GetLogs(profile string, limit int) []ActionRecord {
- at.mu.Lock()
- defer at.mu.Unlock()
-
- recs := at.records[profile]
- if limit <= 0 || limit > len(recs) {
- limit = len(recs)
- }
-
- start := len(recs) - limit
- result := make([]ActionRecord, limit)
- copy(result, recs[start:])
- return result
-}
-
-func (at *ActionTracker) Analyze(profile string) AnalyticsReport {
- at.mu.Lock()
- defer at.mu.Unlock()
-
- recs := at.records[profile]
- if len(recs) == 0 {
- return AnalyticsReport{Suggestions: []string{"No actions recorded yet."}}
- }
-
- report := AnalyticsReport{
- TotalActions: len(recs),
- Since: recs[0].Timestamp,
- }
-
- epCounts := map[string]struct {
- count int
- totalMs int64
- }{}
- for _, rec := range recs {
- entry := epCounts[rec.Endpoint]
- entry.count++
- entry.totalMs += rec.DurationMs
- epCounts[rec.Endpoint] = entry
- }
- for endpoint, entry := range epCounts {
- report.TopEndpoints = append(report.TopEndpoints, EndpointCount{
- Endpoint: endpoint,
- Count: entry.count,
- AvgMs: entry.totalMs / int64(entry.count),
- })
- }
- sort.Slice(report.TopEndpoints, func(i, j int) bool {
- return report.TopEndpoints[i].Count > report.TopEndpoints[j].Count
- })
- if len(report.TopEndpoints) > 10 {
- report.TopEndpoints = report.TopEndpoints[:10]
- }
-
- urlSnapshots := map[string][]time.Time{}
- for _, rec := range recs {
- if rec.Endpoint == "/snapshot" && rec.URL != "" {
- urlSnapshots[rec.URL] = append(urlSnapshots[rec.URL], rec.Timestamp)
- }
- }
- for url, times := range urlSnapshots {
- if len(times) < 3 {
- continue
- }
- var totalGap float64
- for i := 1; i < len(times); i++ {
- totalGap += times[i].Sub(times[i-1]).Seconds()
- }
- avgGap := totalGap / float64(len(times)-1)
- report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{
- Pattern: fmt.Sprintf("snapshot %s", truncURL(url)),
- Count: len(times),
- AvgGapSec: avgGap,
- })
- }
-
- navPattern := map[string]int{}
- for i := 1; i < len(recs); i++ {
- if recs[i-1].Endpoint == "/navigate" && recs[i].Endpoint == "/snapshot" {
- key := truncURL(recs[i-1].URL)
- navPattern[key]++
- }
- }
- for url, count := range navPattern {
- if count >= 3 {
- report.RepeatPatterns = append(report.RepeatPatterns, RepeatPattern{
- Pattern: fmt.Sprintf("navigate→snapshot %s", url),
- Count: count,
- })
- }
- }
-
- for _, pattern := range report.RepeatPatterns {
- if strings.HasPrefix(pattern.Pattern, "snapshot") && pattern.AvgGapSec > 0 && pattern.AvgGapSec < 10 {
- report.Suggestions = append(report.Suggestions,
- fmt.Sprintf("High-frequency polling detected: %s every %.0fs — consider increasing interval or using smart diff", pattern.Pattern, pattern.AvgGapSec))
- }
- if strings.HasPrefix(pattern.Pattern, "navigate→snapshot") && pattern.Count > 5 {
- report.Suggestions = append(report.Suggestions,
- fmt.Sprintf("Repeated navigate→snapshot for same URL %s (%dx) — consider caching or using /text for lighter reads", pattern.Pattern, pattern.Count))
- }
- }
-
- snapCount := 0
- for _, rec := range recs {
- if rec.Endpoint == "/snapshot" {
- snapCount++
- }
- }
- if snapCount > 20 {
- report.Suggestions = append(report.Suggestions,
- fmt.Sprintf("Heavy snapshot usage (%d calls) — use ?selector= or ?maxTokens= to reduce token cost", snapCount))
- }
-
- if len(report.Suggestions) == 0 {
- report.Suggestions = []string{"No optimization suggestions — usage looks efficient."}
- }
-
- return report
-}
-
-func truncURL(u string) string {
- if len(u) > 60 {
- return u[:57] + "..."
- }
- return u
-}
diff --git a/stealth_test.go b/stealth_test.go
deleted file mode 100644
index ab8ff49a..00000000
--- a/stealth_test.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package main
-
-import (
- "encoding/json"
- "net/http/httptest"
- "strings"
- "testing"
-)
-
-func TestStealthJavaScript(t *testing.T) {
-
- content := stealthScript
-
- features := []string{
- "navigator, 'webdriver'",
- "sessionSeed",
- "seededRandom",
- "toDataURL",
- "measureText",
- "hardwareConcurrency",
- "deviceMemory",
- "__pinchtab_timezone",
- }
-
- for _, feature := range features {
- if !strings.Contains(content, feature) {
- t.Errorf("stealth script missing feature: %s", feature)
- }
- }
-
- count := strings.Count(content, "const sessionSeed")
- if count != 1 {
- t.Errorf("expected 1 sessionSeed definition, found %d", count)
- }
-}
-
-func TestGetStealthRecommendations(t *testing.T) {
- allFeatures := map[string]bool{
- "user_agent_override": true,
- "languages_spoofed": true,
- "webrtc_leak_prevented": true,
- "timezone_spoofed": true,
- "canvas_noise": true,
- "font_spoofing": true,
- "audio_noise": true,
- }
-
- tests := []struct {
- name string
- features map[string]bool
- wantRecs int
- }{
- {
- name: "all enabled",
- features: allFeatures,
- wantRecs: 1,
- },
- {
- name: "canvas disabled",
- features: map[string]bool{
- "user_agent_override": true,
- "languages_spoofed": true,
- "webrtc_leak_prevented": true,
- "timezone_spoofed": true,
- "canvas_noise": false,
- "font_spoofing": true,
- "audio_noise": true,
- },
- wantRecs: 1,
- },
- {
- name: "multiple disabled",
- features: map[string]bool{
- "user_agent_override": false,
- "languages_spoofed": false,
- "webrtc_leak_prevented": false,
- "timezone_spoofed": true,
- "canvas_noise": true,
- "font_spoofing": true,
- "audio_noise": true,
- },
- wantRecs: 3,
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- recs := getStealthRecommendations(tt.features)
- if len(recs) != tt.wantRecs {
- t.Errorf("expected %d recommendations, got %d: %v", tt.wantRecs, len(recs), recs)
- }
- })
- }
-}
-
-func TestGenerateFingerprint(t *testing.T) {
- tests := []struct {
- name string
- req fingerprintRequest
- wantUA string
- wantPlat string
- }{
- {
- name: "windows_chrome",
- req: fingerprintRequest{
- OS: "windows",
- Browser: "chrome",
- },
- wantUA: "Chrome/" + cfg.ChromeVersion,
- wantPlat: "Win32",
- },
- {
- name: "mac_chrome",
- req: fingerprintRequest{
- OS: "mac",
- Browser: "chrome",
- },
- wantUA: "Chrome/" + cfg.ChromeVersion,
- wantPlat: "MacIntel",
- },
- {
- name: "random_chrome",
- req: fingerprintRequest{
- OS: "random",
- Browser: "chrome",
- },
- wantUA: "Chrome/" + cfg.ChromeVersion,
- wantPlat: "",
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- fp := generateFingerprint(tt.req)
-
- if tt.wantUA != "" && !strings.Contains(fp.UserAgent, tt.wantUA) {
- t.Errorf("expected UA to contain %s, got %s", tt.wantUA, fp.UserAgent)
- }
-
- if tt.wantPlat != "" && fp.Platform != tt.wantPlat {
- t.Errorf("expected platform %s, got %s", tt.wantPlat, fp.Platform)
- }
-
- if fp.UserAgent == "" {
- t.Error("UserAgent is empty")
- }
- if fp.Platform == "" && tt.req.OS != "random" {
- t.Error("Platform is empty")
- }
- })
- }
-}
-
-func TestHandleStealthStatus(t *testing.T) {
- b := newTestBridgeWithTabs()
-
- req := httptest.NewRequest("GET", "/stealth/status", nil)
- w := httptest.NewRecorder()
-
- b.handleStealthStatus(w, req)
-
- if w.Code != 200 {
- t.Errorf("expected 200, got %d", w.Code)
- }
-
- var resp struct {
- Level string `json:"level"`
- Score int `json:"score"`
- Features map[string]bool `json:"features"`
- ChromeFlags []string `json:"chrome_flags"`
- }
-
- if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
- t.Fatalf("failed to unmarshal response: %v", err)
- }
-
- if resp.Level == "" {
- t.Error("level is empty")
- }
- if resp.Score < 0 || resp.Score > 100 {
- t.Errorf("invalid score: %d", resp.Score)
- }
- if len(resp.Features) == 0 {
- t.Error("features is empty")
- }
- if len(resp.ChromeFlags) == 0 {
- t.Error("chrome_flags is empty")
- }
-
- enabled := 0
- for _, v := range resp.Features {
- if v {
- enabled++
- }
- }
- expectedScore := (enabled * 100) / len(resp.Features)
- if resp.Score != expectedScore {
- t.Errorf("score mismatch: got %d, expected %d", resp.Score, expectedScore)
- }
-}