High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
refactor: remove redundant comments across codebase
Boscha1694669b6f5
diff --git a/cmd/pinchtab/build_test.go b/cmd/pinchtab/build_test.goindex bcb5e70e..f297e03c 100644--- a/cmd/pinchtab/build_test.go+++ b/cmd/pinchtab/build_test.go@@ -18,7 +18,6 @@ type GoReleaserConfig struct {// TestBinaryPermutations verifies all expected binary permutations are configured in goreleaserfunc TestBinaryPermutations(t *testing.T) {- // Find .goreleaser.yml in repo root (2 levels up from cmd/pinchtab/)repoRoot := filepath.Join("..", "..", ".goreleaser.yml")data, err := os.ReadFile(repoRoot)if err != nil {@@ -36,7 +35,6 @@ func TestBinaryPermutations(t *testing.T) {build := cfg.Builds[0]- // Expected OS/arch combinationsexpectedOS := map[string]bool{"linux": true,"darwin": true,@@ -48,7 +46,6 @@ func TestBinaryPermutations(t *testing.T) {"arm64": true,}- // Verify all expected OS are configuredfor os := range expectedOS {found := falsefor _, configOS := range build.GOOS {@@ -62,7 +59,6 @@ func TestBinaryPermutations(t *testing.T) {}}- // Verify all expected architectures are configuredfor arch := range expectedArch {found := falsefor _, configArch := range build.GOARCH {@@ -76,7 +72,6 @@ func TestBinaryPermutations(t *testing.T) {}}- // Calculate expected binary counttotalExpected := len(expectedOS) * len(expectedArch)totalConfigured := len(build.GOOS) * len(build.GOARCH)diff --git a/cmd/pinchtab/cmd_cli_register.go b/cmd/pinchtab/cmd_cli_register.goindex fcacdd23..c9034a99 100644--- a/cmd/pinchtab/cmd_cli_register.go+++ b/cmd/pinchtab/cmd_cli_register.go@@ -406,7 +406,6 @@ func configureBrowserFlags() {cmd.Flags().String("status", "", "Optional resume status note (e.g. completed, failed)")}- // Add --json flag to action commands (default is terse output)addJSONFlag(clickCmd,dblclickCmd,@@ -520,17 +519,6 @@ func addRootCommands(cmds ...*cobra.Command) {rootCmd.AddCommand(cmds...)}-// addTabFlag wires a --tab flag onto the given commands. Anonymous CLI calls-// default its value from the state file written by `nav`, which lets local-// single-agent workflows avoid threading `--tab "$TAB"` through every command:-//-// pinchtab nav http://example.com # writes tab ID to state file-// pinchtab snap -i -c # auto-reads from state file-//-// Explicit --tab still wins (cobra flag precedence). Identified callers-// (PINCHTAB_SESSION, --agent-id, or PINCHTAB_AGENT_ID) leave --tab unset so the-// server-side scoped current-tab store is authoritative. If no state file is-// set, the server picks the active tab as before.// resolveTabArg returns the tab ID from args[0] when present, otherwise it// falls back to the persisted state file written by `nav`.func resolveTabArg(args []string) string {@@ -543,6 +531,17 @@ func resolveTabArg(args []string) string {return readTabStateFile()}+// addTabFlag wires a --tab flag onto the given commands. Anonymous CLI calls+// default its value from the state file written by `nav`, which lets local+// single-agent workflows avoid threading `--tab "$TAB"` through every command:+//+// pinchtab nav http://example.com # writes tab ID to state file+// pinchtab snap -i -c # auto-reads from state file+//+// Explicit --tab still wins (cobra flag precedence). Identified callers+// (PINCHTAB_SESSION, --agent-id, or PINCHTAB_AGENT_ID) leave --tab unset so the+// server-side scoped current-tab store is authoritative. If no state file is+// set, the server picks the active tab as before.func addTabFlag(cmds ...*cobra.Command) {for _, cmd := range cmds {cmd.Flags().String("tab", "", "Tab ID")@@ -583,7 +582,6 @@ func useLocalTabStateFile() bool {return resolveCLIAgentID() == ""}-// tabStateFile returns the path to the tab state file.func tabStateFile() string {if dir := os.Getenv("XDG_STATE_HOME"); dir != "" {return dir + "/pinchtab/current-tab"@@ -594,7 +592,6 @@ func tabStateFile() string {return "/tmp/pinchtab-current-tab"}-// readTabStateFile reads the persisted tab ID from the state file.func readTabStateFile() string {data, err := os.ReadFile(tabStateFile())if err != nil {@@ -657,7 +654,6 @@ func probeTabExists(tabID string) bool {return resp.StatusCode != http.StatusNotFound}-// portIsListening does a fast TCP dial to check if anything is listening.func portIsListening(baseURL string) bool {host := strings.TrimPrefix(baseURL, "http://")host = strings.TrimPrefix(host, "https://")diff --git a/cmd/pinchtab/cmd_cli_runtime_test.go b/cmd/pinchtab/cmd_cli_runtime_test.goindex 93ad0dbc..848fb005 100644--- a/cmd/pinchtab/cmd_cli_runtime_test.go+++ b/cmd/pinchtab/cmd_cli_runtime_test.go@@ -44,7 +44,6 @@ func TestResolveCLIBase(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- // Save and restore global stateoldServerURL := serverURLserverURL = tt.serverFlagdefer func() { serverURL = oldServerURL }()diff --git a/cmd/pinchtab/cmd_cli_state.go b/cmd/pinchtab/cmd_cli_state.goindex 71830b79..f63b458a 100644--- a/cmd/pinchtab/cmd_cli_state.go+++ b/cmd/pinchtab/cmd_cli_state.go@@ -86,24 +86,19 @@ func init() {stateCmd.AddCommand(stateListCmd, stateSaveCmd, stateLoadCmd, stateShowCmd, stateDeleteCmd, stateCleanCmd)addTabFlag(stateCmd)- // save flagsstateSaveCmd.Flags().String("name", "", "Name for the saved state (auto-generated if omitted)")stateSaveCmd.Flags().Bool("encrypt", false, "Encrypt the state file (requires security.stateEncryptionKey in config)")addTabFlag(stateSaveCmd)- // load flagsstateLoadCmd.Flags().String("name", "", "Exact name or prefix of the state file to load")_ = stateLoadCmd.MarkFlagRequired("name")addTabFlag(stateLoadCmd)- // show flagsstateShowCmd.Flags().String("name", "", "Name of the state file to inspect")_ = stateShowCmd.MarkFlagRequired("name")- // delete flagsstateDeleteCmd.Flags().String("name", "", "Name of the state file to delete")_ = stateDeleteCmd.MarkFlagRequired("name")- // clean flagsstateCleanCmd.Flags().Int("older-than", 24, "Remove files older than this many hours")}diff --git a/cmd/pinchtab/cmd_cli_storage.go b/cmd/pinchtab/cmd_cli_storage.goindex de673a72..1ef82e21 100644--- a/cmd/pinchtab/cmd_cli_storage.go+++ b/cmd/pinchtab/cmd_cli_storage.go@@ -59,21 +59,16 @@ var storageClearCmd = &cobra.Command{func init() {storageCmd.AddCommand(storageGetCmd, storageSetCmd, storageDeleteCmd, storageClearCmd)- // Shared tab flagaddTabFlag(storageGetCmd, storageSetCmd, storageDeleteCmd, storageClearCmd)- // get flagsstorageGetCmd.Flags().String("type", "", "Storage type: local, session (default: both)")storageGetCmd.Flags().String("key", "", "Specific key to retrieve")- // set flagsstorageSetCmd.Flags().String("type", "local", "Storage type: local or session")- // delete flagsstorageDeleteCmd.Flags().String("type", "local", "Storage type: local or session")storageDeleteCmd.Flags().String("key", "", "Key to remove (omit to clear entire store)")- // clear flagsstorageClearCmd.Flags().String("type", "local", "Storage type: local or session")storageClearCmd.Flags().Bool("all", false, "Clear both localStorage and sessionStorage")}diff --git a/cmd/pinchtab/cmd_dashboard.go b/cmd/pinchtab/cmd_dashboard.goindex 72594f93..cc479d11 100644--- a/cmd/pinchtab/cmd_dashboard.go+++ b/cmd/pinchtab/cmd_dashboard.go@@ -41,7 +41,6 @@ func runDashboardCommand(cfgPort, cfgBind, cfgToken string, noOpen bool, portOvehost := resolveHost(cfgBind)url := fmt.Sprintf("http://%s:%s", host, port)- // Health checkif !isDashboardReachable(host, port) {fmt.Println(cli.StyleStdout(cli.WarningStyle, " Dashboard doesn't appear to be running."))fmt.Printf(" Start with %s or %s\n\n",@@ -61,7 +60,6 @@ func runDashboardCommand(cfgPort, cfgBind, cfgToken string, noOpen bool, portOve}}- // Open browserif !noOpen {if err := openBrowser(url); err == nil {fmt.Println(cli.StyleStdout(cli.SuccessStyle, " Opened in your browser."))diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.goindex 7c46728a..2332b202 100644--- a/cmd/pinchtab/cmd_server_background_test.go+++ b/cmd/pinchtab/cmd_server_background_test.go@@ -169,7 +169,6 @@ func TestStopViaAPIShutdownEndpoint(t *testing.T) {}))defer srv.Close()- // Extract port from test server URL.port := strings.TrimPrefix(srv.URL, "http://127.0.0.1:")err := server.ShutdownServer(port, "")diff --git a/cmd/pinchtab/cmd_wizard.go b/cmd/pinchtab/cmd_wizard.goindex 6b356099..e30258e6 100644--- a/cmd/pinchtab/cmd_wizard.go+++ b/cmd/pinchtab/cmd_wizard.go@@ -29,7 +29,6 @@ func runSecurityWizard(cfg *config.FileConfig, configPath string, isNew bool) boreturn runUpgradeNotice(cfg, configPath)}-// runNonInteractiveSetup prints a summary and applies defaults silently.func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew bool) bool {if isNew {fmt.Println()@@ -52,7 +51,6 @@ func runNonInteractiveSetup(cfg *config.FileConfig, configPath string, isNew booreturn true}-// runFullWizard runs the interactive first-run wizard.func runFullWizard(cfg *config.FileConfig, configPath string) bool {fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π‘οΈ Know your config"))@@ -62,7 +60,6 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {fmt.Println()printSeparator()- // Guard Upfmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "1. Guard UP (recommended)"))fmt.Println(cli.StyleStdout(cli.MutedStyle, "Only sites running on this machine can be automated."))@@ -76,7 +73,6 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {printSetting("IDPI", cli.StyleStdout(cli.SuccessStyle, "strict"))fmt.Println()- // Guard Downfmt.Println(cli.StyleStdout(cli.HeadingStyle, "2. Guard DOWN (development)"))fmt.Println(cli.StyleStdout(cli.MutedStyle, "All features enabled, any site can be automated. Use for local dev only."))fmt.Println()@@ -106,7 +102,6 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {applyGuardDown(cfg)}- // Dashboard accessprintSeparator()fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Dashboard"))@@ -118,7 +113,6 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {}fmt.Println()- // Savecfg.ConfigVersion = config.CurrentConfigVersionif err := config.SaveFileConfig(cfg, configPath); err != nil {fmt.Fprintln(os.Stderr, cli.StyleStderr(cli.ErrorStyle, fmt.Sprintf("failed to save config: %v", err)))@@ -131,7 +125,6 @@ func runFullWizard(cfg *config.FileConfig, configPath string) bool {return true}-// runUpgradeNotice shows a brief notice for config upgrades.func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "π‘οΈ Config update (v"+config.CurrentConfigVersion+")"))@@ -152,8 +145,6 @@ func runUpgradeNotice(cfg *config.FileConfig, configPath string) bool {return true}-// βββ Guard Presets βββββββββββββββββββββββββββββββββββββββββββββββ-func applyGuardUp(cfg *config.FileConfig) {f := falsecfg.Security.AllowEvaluate = &f@@ -185,8 +176,6 @@ func applyGuardDown(cfg *config.FileConfig) {cfg.Security.AllowedDomains = nil}-// βββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββ-func getAllowedDomains(cfg *config.FileConfig) []string {if len(cfg.Security.AllowedDomains) > 0 {return cfg.Security.AllowedDomains@@ -214,5 +203,3 @@ func orDefault(val, fallback string) string {}return val}--// copyToClipboard is defined in cmd_config.godiff --git a/internal/activity/activity.go b/internal/activity/activity.goindex 58bb1fa2..a5455763 100644--- a/internal/activity/activity.go+++ b/internal/activity/activity.go@@ -166,7 +166,6 @@ func (tr *TailReader) Read(limit int) ([]Event, error) {return nil, err}- // Update offset to current position.newOffset, _ := f.Seek(0, 1)tr.store.tailMu.Lock()tr.store.tailFile = pathdiff --git a/internal/autosolver/autosolver.go b/internal/autosolver/autosolver.goindex 497e2ab5..3a06d086 100644--- a/internal/autosolver/autosolver.go+++ b/internal/autosolver/autosolver.go@@ -56,7 +56,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecu"max_attempts", as.config.MaxAttempts,"llm_fallback", as.config.LLMFallback)- // Detect what kind of page we're dealing with.intent, err := as.detectIntent(ctx, page)if err != nil {slog.Warn("autosolver: intent detection failed, proceeding with unknown",@@ -65,7 +64,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecu}result.Intent = intent.Type- // No challenge - nothing to solve.if intent.Type == IntentNormal {result.Solved = trueresult.TotalDuration = time.Since(start)@@ -82,11 +80,9 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecu"confidence", intent.Confidence,"url", page.URL())- // Run the fallback chain with retry logic.for attempt := 0; attempt < as.config.MaxAttempts; attempt++ {result.Attempts = attempt + 1- // Apply backoff between retries (skip first attempt).if attempt > 0 {delay := as.backoffDelay(attempt)slog.Info("autosolver_retry",@@ -107,7 +103,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecu}}- // Try semantic-first action before any rule-based solver.solved, entry := as.trySemantic(ctx, page, executor, intent)if entry != nil {result.History = append(result.History, *entry)@@ -131,7 +126,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecureturn result, nil}- // Try registered solvers in priority order.solved, entry = as.trySolvers(ctx, page, executor)if entry != nil {result.History = append(result.History, *entry)@@ -155,7 +149,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecureturn result, nil}- // Try LLM fallback if enabled and all solvers failed.if as.config.LLMFallback && as.llm != nil {solved, entry = as.tryLLM(ctx, page, executor, result.History)if entry != nil {@@ -197,8 +190,6 @@ func (as *AutoSolver) Solve(ctx context.Context, page Page, executor ActionExecureturn result, nil}-// detectIntent uses the semantic engine if available, otherwise falls-// back to basic title-based heuristics.func (as *AutoSolver) detectIntent(ctx context.Context, page Page) (*Intent, error) {if as.semantic != nil {return as.semantic.DetectIntent(ctx, page)@@ -206,7 +197,6 @@ func (as *AutoSolver) detectIntent(ctx context.Context, page Page) (*Intent, errreturn detectIntentByTitle(page.Title()), nil}-// trySolvers iterates through matching solvers and returns on first success.func (as *AutoSolver) trySolvers(ctx context.Context, page Page, executor ActionExecutor) (bool, *AttemptEntry) {solvers := as.registry.MatchingSolvers(ctx, page)if len(solvers) == 0 {@@ -719,7 +709,6 @@ func resolveSelectorCenter(ctx context.Context, executor ActionExecutor, selectoreturn coords.X, coords.Y, nil}-// tryLLM builds a trimmed request and asks the LLM for the next action.func (as *AutoSolver) tryLLM(ctx context.Context, page Page, executor ActionExecutor, history []AttemptEntry) (bool, *AttemptEntry) {llmStart := time.Now()entry := &AttemptEntry{Solver: "llm"}@@ -751,7 +740,6 @@ func (as *AutoSolver) tryLLM(ctx context.Context, page Page, executor ActionExecreturn false, entry}- // Execute the LLM's suggested action.if err := executeAction(ctx, executor, resp); err != nil {entry.Status = StatusFailedentry.Error = fmt.Sprintf("execute llm action: %v", err)@@ -764,7 +752,6 @@ func (as *AutoSolver) tryLLM(ctx context.Context, page Page, executor ActionExecreturn true, entry}-// executeAction translates an LLMResponse into an ActionExecutor call.func executeAction(ctx context.Context, executor ActionExecutor, resp *LLMResponse) error {if resp == nil {return fmt.Errorf("nil response")@@ -795,7 +782,6 @@ func executeAction(ctx context.Context, executor ActionExecutor, resp *LLMRespon}}-// backoffDelay calculates exponential backoff with jitter.func (as *AutoSolver) backoffDelay(attempt int) time.Duration {base := as.config.RetryBaseDelayif base <= 0 {diff --git a/internal/autosolver/autosolver_test.go b/internal/autosolver/autosolver_test.goindex d9064a51..d968ff43 100644--- a/internal/autosolver/autosolver_test.go+++ b/internal/autosolver/autosolver_test.go@@ -7,8 +7,6 @@ import ("time")-// --- Mock implementations ----type mockPage struct {url stringtitle string@@ -133,8 +131,6 @@ func (m *mockLLM) SuggestNextAction(_ context.Context, _ LLMRequest) (*LLMResponreturn m.resp, m.err}-// --- Tests ----func TestSolve_NormalPage(t *testing.T) {cfg := DefaultConfig()cfg.MaxAttempts = 3diff --git a/internal/autosolver/external/capsolver.go b/internal/autosolver/external/capsolver.goindex b77d9d71..ebd7ef2a 100644--- a/internal/autosolver/external/capsolver.go+++ b/internal/autosolver/external/capsolver.go@@ -74,7 +74,6 @@ func (c *Capsolver) Solve(ctx context.Context, page autosolver.Page, executor aureturn result, fmt.Errorf("capsolver API key not configured")}- // Step 1: Detect CAPTCHA type from page HTML.html, err := page.HTML()if err != nil {result.Error = fmt.Sprintf("get HTML: %v", err)@@ -87,14 +86,12 @@ func (c *Capsolver) Solve(ctx context.Context, page autosolver.Page, executor aureturn result, fmt.Errorf("no supported CAPTCHA detected on page")}- // Step 2: Extract sitekey from page.sitekey := extractSitekey(html, captchaType)if sitekey == "" {result.Error = "sitekey not found"return result, fmt.Errorf("could not extract sitekey from page")}- // Step 3: Submit task to Capsolver API.// TODO: Implement HTTP client for Capsolver API v1.// POST /createTask with task type + sitekey + page URL._ = sitekey@@ -104,7 +101,6 @@ func (c *Capsolver) Solve(ctx context.Context, page autosolver.Page, executor aureturn result, fmt.Errorf("capsolver: API client not yet implemented β skeleton only")}-// detectCaptchaType identifies the CAPTCHA provider from page HTML.func detectCaptchaType(html string) string {lower := strings.ToLower(html)switch {@@ -119,7 +115,6 @@ func detectCaptchaType(html string) string {}}-// extractSitekey attempts to pull the CAPTCHA sitekey from HTML attributes.func extractSitekey(html, captchaType string) string {var attrNames []stringswitch captchaType {diff --git a/internal/autosolver/heuristics.go b/internal/autosolver/heuristics.goindex b0dcf06a..15d29f56 100644--- a/internal/autosolver/heuristics.go+++ b/internal/autosolver/heuristics.go@@ -11,7 +11,6 @@ func detectIntentByTitle(title string) *Intent {return challenge}- // Cloudflare challenge patternscfPatterns := []string{"just a moment", "attention required", "checking your browser"}for _, p := range cfPatterns {if strings.Contains(lower, p) {@@ -24,7 +23,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Generic CAPTCHA patternscaptchaPatterns := []string{"captcha", "verify you are human", "robot", "bot detection"}for _, p := range captchaPatterns {if strings.Contains(lower, p) {@@ -36,7 +34,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Login patternsloginPatterns := []string{"log in", "login", "sign in", "signin"}for _, p := range loginPatterns {if strings.Contains(lower, p) {@@ -48,7 +45,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Signup patternssignupPatterns := []string{"sign up", "signup", "register", "create account", "join"}for _, p := range signupPatterns {if strings.Contains(lower, p) {@@ -60,7 +56,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Onboarding patternsonboardingPatterns := []string{"getting started", "welcome", "onboarding", "complete your profile", "step 1"}for _, p := range onboardingPatterns {if strings.Contains(lower, p) {@@ -72,7 +67,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Navigation/task-flow patternsnavigationPatterns := []string{"continue", "next step", "choose option", "select plan", "wizard"}for _, p := range navigationPatterns {if strings.Contains(lower, p) {@@ -84,7 +78,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Generic form-filling patternsformPatterns := []string{"application form", "contact form", "checkout", "survey", "questionnaire"}for _, p := range formPatterns {if strings.Contains(lower, p) {@@ -96,7 +89,6 @@ func detectIntentByTitle(title string) *Intent {}}- // Blocked/access-denied patternsblockedPatterns := []string{"access denied", "forbidden", "blocked", "unauthorized"}for _, p := range blockedPatterns {if strings.Contains(lower, p) {diff --git a/internal/autosolver/llm/llm.go b/internal/autosolver/llm/llm.goindex f7f21e00..ce9098b6 100644--- a/internal/autosolver/llm/llm.go+++ b/internal/autosolver/llm/llm.go@@ -52,7 +52,6 @@ func (p *Provider) SuggestNextAction(ctx context.Context, req autosolver.LLMRequreturn nil, fmt.Errorf("llm: API key not configured for provider %q", p.config.Provider)}- // Build the prompt.prompt := buildPrompt(req)// TODO: Implement actual LLM API call based on p.config.Provider.@@ -62,7 +61,6 @@ func (p *Provider) SuggestNextAction(ctx context.Context, req autosolver.LLMRequreturn nil, fmt.Errorf("llm: provider %q not yet implemented β skeleton only", p.config.Provider)}-// buildPrompt creates a structured prompt for the LLM.func buildPrompt(req autosolver.LLMRequest) string {prompt := fmt.Sprintf(`You are a browser automation assistant. Analyze the following page and suggest the next action.diff --git a/internal/autosolver/semantic/adapter.go b/internal/autosolver/semantic/adapter.goindex 5f6714a1..39d22105 100644--- a/internal/autosolver/semantic/adapter.go+++ b/internal/autosolver/semantic/adapter.go@@ -34,7 +34,6 @@ func (a *Adapter) DetectIntent(ctx context.Context, page autosolver.Page) (*autoreturn challenge, nil}- // Cloudflare challenge indicatorscfIndicators := []string{"just a moment", "attention required", "checking your browser"}for _, indicator := range cfIndicators {if strings.Contains(title, indicator) {@@ -47,7 +46,6 @@ func (a *Adapter) DetectIntent(ctx context.Context, page autosolver.Page) (*auto}}- // CAPTCHA indicators (via URL or title patterns)captchaIndicators := []string{"captcha", "challenge", "verify", "recaptcha", "hcaptcha"}for _, indicator := range captchaIndicators {if strings.Contains(title, indicator) || strings.Contains(strings.ToLower(url), indicator) {@@ -59,7 +57,6 @@ func (a *Adapter) DetectIntent(ctx context.Context, page autosolver.Page) (*auto}}- // Login page detection via semantic matching if matcher is available.if a.matcher != nil {intent, err := a.detectViaSemanticMatch(ctx, page)if err == nil && intent != nil {@@ -67,7 +64,6 @@ func (a *Adapter) DetectIntent(ctx context.Context, page autosolver.Page) (*auto}}- // Fallback to title-based heuristics for login/signup.loginPatterns := []string{"log in", "login", "sign in"}for _, p := range loginPatterns {if strings.Contains(title, p) {@@ -145,7 +141,6 @@ func (a *Adapter) FindElement(ctx context.Context, page autosolver.Page, query sreturn nil, err}- // Build minimal element descriptors from interactive element patterns.descs := extractDescriptors(html)if len(descs) == 0 {return nil, nil@@ -212,7 +207,6 @@ func (a *Adapter) SuggestAction(ctx context.Context, page autosolver.Page, inten}}-// suggestCaptchaAction finds the captcha widget and suggests clicking it.func (a *Adapter) suggestCaptchaAction(ctx context.Context, page autosolver.Page, intent *autosolver.Intent) (*autosolver.SuggestedAction, error) {match, err := a.FindElement(ctx, page, "captcha checkbox verify button")if err != nil || match == nil {@@ -231,7 +225,6 @@ func (a *Adapter) suggestCaptchaAction(ctx context.Context, page autosolver.Page}, nil}-// suggestLoginAction finds the first empty input field and suggests focusing it.func (a *Adapter) suggestLoginAction(ctx context.Context, page autosolver.Page) (*autosolver.SuggestedAction, error) {match, err := a.FindElement(ctx, page, "username email input field")if err != nil || match == nil {@@ -248,7 +241,6 @@ func (a *Adapter) suggestLoginAction(ctx context.Context, page autosolver.Page)}, nil}-// suggestSignupAction finds the first registration field.func (a *Adapter) suggestSignupAction(ctx context.Context, page autosolver.Page) (*autosolver.SuggestedAction, error) {match, err := a.FindElement(ctx, page, "name email registration input field")if err != nil || match == nil {@@ -316,7 +308,6 @@ func (a *Adapter) suggestFormAction(ctx context.Context, page autosolver.Page) (// detectViaSemanticMatch uses the semantic matcher to classify page// elements and infer the page intent.func (a *Adapter) detectViaSemanticMatch(ctx context.Context, page autosolver.Page) (*autosolver.Intent, error) {- // Search for login-related elementsmatch, err := a.FindElement(ctx, page, "login submit button")if err == nil && match != nil && match.Score > 0.6 {return &autosolver.Intent{@@ -326,7 +317,6 @@ func (a *Adapter) detectViaSemanticMatch(ctx context.Context, page autosolver.Pa}, nil}- // Search for signup-related elementsmatch, err = a.FindElement(ctx, page, "register create account button")if err == nil && match != nil && match.Score > 0.6 {return &autosolver.Intent{@@ -372,8 +362,6 @@ func (a *Adapter) detectViaSemanticMatch(ctx context.Context, page autosolver.Pafunc extractDescriptors(html string) []semantic.ElementDescriptor {var descs []semantic.ElementDescriptor- // Extract interactive elements by scanning for common patterns.- // A full implementation would use the a11y tree from the bridge.patterns := []struct {searchTag stringselTag string@@ -397,7 +385,6 @@ func extractDescriptors(html string) []semantic.ElementDescriptor {}idx += pos + len(p.searchTag)- // Extract a rough name from surrounding text.end := strings.Index(lower[idx:], ">")if end == -1 {break@@ -461,7 +448,6 @@ func escapeAttrValue(v string) string {return v}-// extractAttr extracts an HTML attribute value from a tag snippet.func extractAttr(snippet, attr string) string {lower := strings.ToLower(snippet)idx := strings.Index(lower, attr+"=")diff --git a/internal/autosolver/solvers/cloudflare.go b/internal/autosolver/solvers/cloudflare.goindex b700076f..9c2220ac 100644--- a/internal/autosolver/solvers/cloudflare.go+++ b/internal/autosolver/solvers/cloudflare.go@@ -36,7 +36,6 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor areturn result, nil}- // Detect challenge type.challengeType, err := detectCFChallengeType(ctx, executor)if err != nil {return result, fmt.Errorf("detect challenge type: %w", err)@@ -47,14 +46,11 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor areturn waitForCFResolve(ctx, page, result, 15*time.Second)}- // Interactive challenge: find and click the Turnstile checkbox.for attempt := 0; attempt < 3; attempt++ {result.Attempts = attempt + 1- // Wait for spinner to complete.waitForSpinner(ctx, executor, 10*time.Second)- // Find the Turnstile iframe bounding box.box, err := findTurnstileBox(ctx, executor)if err != nil {// Challenge may have resolved while we were looking.@@ -75,7 +71,6 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor areturn result, fmt.Errorf("click turnstile: %w", err)}- // Poll for resolution.resolved := pollResolution(ctx, page, 15*time.Second)if resolved {result.Solved = true@@ -84,14 +79,11 @@ func (s *Cloudflare) Solve(ctx context.Context, page autosolver.Page, executor a}}- // Final check after all attempts.result.FinalTitle = page.Title()result.Solved = !isCFChallenge(page.Title())return result, nil}-// --- Internal helpers ----type boundingBox struct {x, y, width, height float64}diff --git a/internal/autosolver/solvers/jschallenge.go b/internal/autosolver/solvers/jschallenge.goindex dda6fbfb..d120a009 100644--- a/internal/autosolver/solvers/jschallenge.go+++ b/internal/autosolver/solvers/jschallenge.go@@ -30,13 +30,12 @@ func (s *JSChallenge) CanHandle(_ context.Context, page autosolver.Page) (bool,func (s *JSChallenge) Solve(ctx context.Context, page autosolver.Page, executor autosolver.ActionExecutor) (*autosolver.Result, error) {result := &autosolver.Result{SolverUsed: s.Name()}- // Step 1: wait briefly for JS anti-bot scripts to execute naturally.+ // Wait briefly for JS anti-bot scripts to execute naturally.if err := executor.WaitFor(ctx, "body", 2*time.Second); err != nil {result.Error = fmt.Sprintf("wait for body: %v", err)return result, err}- // Step 2: click common continue/verify buttons if present.for _, selector := range []string{"button[type='submit']","button[name='verify']",@@ -50,7 +49,6 @@ func (s *JSChallenge) Solve(ctx context.Context, page autosolver.Page, executor_ = clickIfExists(ctx, executor, selector)}- // Step 3: poll for resolution by challenge intent re-check.deadline := time.Now().Add(8 * time.Second)for time.Now().Before(deadline) {html, err := page.HTML()@@ -72,7 +70,6 @@ func (s *JSChallenge) Solve(ctx context.Context, page autosolver.Page, executor}}- // Final state snapshot.result.FinalTitle = page.Title()result.FinalURL = page.URL()html, err := page.HTML()diff --git a/internal/bridge/action_pointer.go b/internal/bridge/action_pointer.goindex 0ab9898d..4fb67a3b 100644--- a/internal/bridge/action_pointer.go+++ b/internal/bridge/action_pointer.go@@ -217,7 +217,6 @@ func (b *Bridge) actionClick(ctx context.Context, req ActionRequest) (result mapclickCtx = ctx}- // Channel to receive click resulttype clickResult struct {err error}diff --git a/internal/bridge/action_resolve.go b/internal/bridge/action_resolve.goindex faf79af1..970f8443 100644--- a/internal/bridge/action_resolve.go+++ b/internal/bridge/action_resolve.go@@ -226,7 +226,6 @@ func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {return fmt.Errorf("get document: %w", err)}- // Perform XPath search.var searchResult json.RawMessageif err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.performSearch", map[string]any{"query": xpath,@@ -245,7 +244,6 @@ func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {return fmt.Errorf("xpath %q: no elements found", xpath)}- // Get the first result.var getResult json.RawMessageif err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.getSearchResults", map[string]any{"searchId": sr.SearchID,@@ -283,7 +281,6 @@ func ResolveXPathToNodeID(ctx context.Context, xpath string) (int64, error) {}backendNodeID = desc.Node.BackendNodeID- // Clean up the search._ = chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.discardSearchResults", map[string]any{"searchId": sr.SearchID,}, nil)diff --git a/internal/bridge/action_text.go b/internal/bridge/action_text.goindex 677a4859..5cb14ef3 100644--- a/internal/bridge/action_text.go+++ b/internal/bridge/action_text.go@@ -109,7 +109,6 @@ func (b *Bridge) actionKeyboardType(ctx context.Context, req ActionRequest) (mapreturn nil, fmt.Errorf("text required for keyboard-type")}- // Promote to the humanized typing path when humanize=true was opted into.if b.effectiveHumanize(req) {return b.actionHumanizedType(ctx, req)}@@ -180,7 +179,6 @@ func (b *Bridge) keyboardTypeBatched(ctx context.Context, text string) (map[strirunes := []rune(text)edgeChars := keyboardTypeBatchedEdgeChars- // If string is short enough, just type the whole thingif len(runes) <= edgeChars*2 {return b.keyboardTypePerChar(ctx, text)}@@ -189,12 +187,10 @@ func (b *Bridge) keyboardTypeBatched(ctx context.Context, text string) (map[strimiddle := string(runes[edgeChars : len(runes)-edgeChars])tail := string(runes[len(runes)-edgeChars:])- // Type first 5 characters with key eventsif _, err := b.keyboardTypePerChar(ctx, head); err != nil {return nil, err}- // Insert middle portionerr := chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {return chromedp.FromContext(ctx).Target.Execute(ctx, "Input.insertText", map[string]any{"text": middle,@@ -204,7 +200,6 @@ func (b *Bridge) keyboardTypeBatched(ctx context.Context, text string) (map[strireturn nil, err}- // Type last 5 characters with key eventsif _, err := b.keyboardTypePerChar(ctx, tail); err != nil {return nil, err}diff --git a/internal/bridge/actions_test.go b/internal/bridge/actions_test.goindex 54cd9209..3c6a45a1 100644--- a/internal/bridge/actions_test.go+++ b/internal/bridge/actions_test.go@@ -827,8 +827,6 @@ func TestUncheckAction_WithSelector_UsesCSSPath(t *testing.T) {}}-// ββ Keyboard action tests ββββββββββββββββββββββββββββββββββββββββββββββ-func TestKeyboardTypeAction_Registered(t *testing.T) {b := New(context.TODO(), nil, &config.RuntimeConfig{})if _, ok := b.Actions[ActionKeyboardType]; !ok {@@ -941,8 +939,6 @@ func TestKeyUpAction_WithCancelledContext(t *testing.T) {}}-// ββ ScrollIntoView action tests ββββββββββββββββββββββββββββββββββββββββ-func TestScrollIntoViewAction_Registered(t *testing.T) {b := New(context.TODO(), nil, &config.RuntimeConfig{})if _, ok := b.Actions[ActionScrollIntoView]; !ok {diff --git a/internal/bridge/api.go b/internal/bridge/api.goindex f6b7386b..f981751f 100644--- a/internal/bridge/api.go+++ b/internal/bridge/api.go@@ -22,9 +22,9 @@ type TabTarget struct {Type string `json:"type"`}-// BridgeAPI abstracts browser tab operations for handler testing.var ErrBrowserDraining = errors.New("browser restart in progress; retry shortly")+// BridgeAPI abstracts browser tab operations for handler testing.type BridgeAPI interface {BrowserContext() context.ContextTabContext(tabID string) (ctx *TabHandle, resolvedID string, err error)@@ -63,15 +63,12 @@ type BridgeAPI interface {RunningBrowser() (string, bool)StealthStatus() *stealth.Status- // Memory metricsGetMemoryMetrics(tabID string) (*MemoryMetrics, error)GetBrowserMemoryMetrics() (*MemoryMetrics, error)GetAggregatedMemoryMetrics() (*MemoryMetrics, error)- // Crash monitoringGetCrashLogs() []string- // Network monitoringNetworkMonitor() *NetworkMonitor// Network request interception (Fetch domain).@@ -79,32 +76,24 @@ type BridgeAPI interface {RemoveRouteRule(tabID, pattern string) (int, error)ListRouteRules(tabID string) ([]RouteRule, error)- // Dialog managementGetDialogManager() *DialogManager- // Console and error logsGetConsoleLogs(tabID string, limit int) []LogEntryClearConsoleLogs(tabID string)GetErrorLogs(tabID string, limit int) []ErrorEntryClearErrorLogs(tabID string)- // NavigationNavigate(ctx context.Context, url string, params NavigateParams) (*NavigateResult, error)- // SnapshotSnapshot(ctx context.Context, tabID string, filter string, params ContentParams) (*SnapshotResult, error)- // TextText(ctx context.Context, tabID string, params ContentParams) (*TextResult, error)- // Cache managementClearCache(ctx context.Context) errorCanClearCache(ctx context.Context) (bool, error)- // Cookie managementClearCookies(ctx context.Context) error- // JavaScript evaluationEvaluate(ctx context.Context, expression string, result any, opts EvalOpts) error// CallFunctionOnNode resolves a backend node ID to a Runtime object,@@ -119,35 +108,27 @@ type BridgeAPI interface {// DescribeNode returns DOM structural info for a backend node ID.DescribeNode(ctx context.Context, backendNodeID int64) (*NodeInfo, error)- // Screenshot captureCaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error)- // Screencast streamingStartScreencast(ctx context.Context, opts ScreencastOpts) (*ScreencastStream, error)- // EmulationSetViewport(ctx context.Context, params ViewportParams) errorSetGeolocation(ctx context.Context, lat, lng, accuracy float64) errorSetEmulatedMedia(ctx context.Context, feature, value string) error- // Network stateSetNetworkConditions(ctx context.Context, params NetworkConditions) errorSetExtraHTTPHeaders(ctx context.Context, headers map[string]string) errorGetCookies(ctx context.Context, urls []string) ([]CookieData, error)SetCookie(ctx context.Context, params SetCookieParams) error- // Navigation infoCurrentURL(ctx context.Context) (string, error)CurrentTitle(ctx context.Context) (string, error)- // PDF generationPrintToPDF(ctx context.Context, params PDFParams) ([]byte, error)- // DOM file inputSetFileInputFiles(ctx context.Context, nodeID int64, paths []string) errorResolveSelectorToNodeID(ctx context.Context, selector string) (int64, error)- // DownloadDownloadURL(ctx context.Context, dlURL string, opts DownloadOpts) (*DownloadResult, error)// HTTP auth credentials (Fetch domain)@@ -157,12 +138,10 @@ type BridgeAPI interface {ContinueWithAuth(ctx context.Context, requestID, username, password string) errorContinueRequest(ctx context.Context, requestID string) error- // Navigation historyGoBack(ctx context.Context) (didNavigate bool, err error)GoForward(ctx context.Context) (didNavigate bool, err error)Reload(ctx context.Context) error- // Navigation wait helpersWaitVisible(ctx context.Context, selector string) error// Navigation policy (network guard)@@ -299,8 +278,6 @@ type OrchestratorService interface {ForceShutdown()}-// Common types used across packages (migrated from main)-type ProfileInfo struct {ID string `json:"id,omitempty"`Name string `json:"name"`@@ -360,15 +337,15 @@ func normalizeInstanceMode(mode string, headless bool) string {}type Instance struct {- ID string `json:"id"` // Hash-based ID: inst_XXXXXXXX- ProfileID string `json:"profileId"` // Hash-based profile ID: prof_XXXXXXXX- ProfileName string `json:"profileName"` // Human-readable profile name (for display only)- Port string `json:"port"` // Internal: instance port- URL string `json:"url,omitempty"` // Canonical base URL for bridge-backed instances- Mode string `json:"mode"` // API mode: "headless" or "headed"- Headless bool `json:"headless"` // Mode: headless vs headed- Status string `json:"status"` // Status: starting/running/stopping/stopped/error- StartTime time.Time `json:"startTime"` // When instance was created+ ID string `json:"id"` // Hash-based ID: inst_XXXXXXXX+ ProfileID string `json:"profileId"` // Hash-based profile ID: prof_XXXXXXXX+ ProfileName string `json:"profileName"` // Human-readable profile name (for display only)+ Port string `json:"port"` // Internal: instance port+ URL string `json:"url,omitempty"` // Canonical base URL for bridge-backed instances+ Mode string `json:"mode"` // API mode: "headless" or "headed"+ Headless bool `json:"headless"` // Mode: headless vs headed+ Status string `json:"status"` // Status: starting/running/stopping/stopped/error+ StartTime time.Time `json:"startTime"`Error string `json:"error,omitempty"` // Error message if status=errorAttached bool `json:"attached"` // True if attached rather than locally launchedAttachType string `json:"attachType,omitempty"` // "cdp" or "bridge" for attached instancesdiff --git a/internal/bridge/bridge_lifecycle.go b/internal/bridge/bridge_lifecycle.goindex 86e1617b..a765fdaa 100644--- a/internal/bridge/bridge_lifecycle.go+++ b/internal/bridge/bridge_lifecycle.go@@ -199,8 +199,6 @@ func (b *Bridge) EnsureBrowser(cfg *config.RuntimeConfig) error {if err := AcquireProfileLock(cfg.ProfileDir); err != nil {if cfg.Headless {- // If we are in headless mode, we are more flexible.- // Instead of failing, we can use a unique temporary profile dir.uniqueDir, tmpErr := os.MkdirTemp("", "pinchtab-profile-*")if tmpErr == nil {slog.Warn("profile in use; using unique temporary profile for headless instance",diff --git a/internal/bridge/capture.go b/internal/bridge/capture.goindex 02440d35..f2fa6b29 100644--- a/internal/bridge/capture.go+++ b/internal/bridge/capture.go@@ -101,7 +101,6 @@ func PairedCapture(ctx context.Context, opts CaptureOpts) (*PairedResult, error)_, _ = WaitForReadyState(ctx, 2*time.Second)}- // Pre-capture frame info β root frame id + loader id.pre, err := FetchFrameTree(ctx)if err != nil {return nil, err@@ -142,7 +141,6 @@ func PairedCapture(ctx context.Context, opts CaptureOpts) (*PairedResult, error)res.Nodes = flatres.Refs = refs- // URL + title for response metadata._ = chromedp.Run(ctx,chromedp.Location(&res.URL),chromedp.Title(&res.Title),diff --git a/internal/bridge/cdpops/pointer.go b/internal/bridge/cdpops/pointer.goindex b5270b01..6932423c 100644--- a/internal/bridge/cdpops/pointer.go+++ b/internal/bridge/cdpops/pointer.go@@ -274,7 +274,6 @@ func ClickByNodeID(ctx context.Context, nodeID int64) error {// href. CDP Input.dispatchMouseEvent doesn't trigger the browser's default// link-navigation behavior, so this ensures anchor clicks actually navigate.func jsClickIfLink(ctx context.Context, nodeID int64) error {- // Resolve backend node to a remote object so we can call functions on it.var resolved json.RawMessageif err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{"backendNodeId": nodeID,diff --git a/internal/bridge/cleanup.go b/internal/bridge/cleanup.goindex 0cc7892d..aaf4346c 100644--- a/internal/bridge/cleanup.go+++ b/internal/bridge/cleanup.go@@ -55,7 +55,6 @@ func CleanupOrphanedChromeProcesses(profileDir string) {// temp profiles (--user-data-dir=.../pinchtab-profile-*).// Called on server shutdown β one ps scan, immediate SIGKILL.func KillAllPinchtabChrome() int {- // Find Chrome processes using either temp or persistent pinchtab profilesvar pids []inttempPids := findPIDsByNeedle("pinchtab-profile")persistPids := findPIDsByNeedle(".pinchtab/profiles")@@ -238,15 +237,12 @@ func killChromeByProfileDir(profileDir string) int {return 0}- // SIGTERM firstfor _, pid := range pids {_ = syscall.Kill(pid, syscall.SIGTERM)}- // Give Chrome 500ms to shut down gracefullytime.Sleep(500 * time.Millisecond)- // SIGKILL any survivorskilled := 0for _, pid := range pids {if err := syscall.Kill(pid, 0); err != nil {diff --git a/internal/bridge/cloudflare.go b/internal/bridge/cloudflare.goindex 1c4cee60..55e85ebe 100644--- a/internal/bridge/cloudflare.go+++ b/internal/bridge/cloudflare.go@@ -110,10 +110,6 @@ func (s *CloudflareSolver) Solve(ctx context.Context, opts solver.Options) (*solreturn result, nil}-// ----------------------------------------------------------------------------// Internal helpers-// ----------------------------------------------------------------------------type cfBoundingBox struct {X float64Y float64diff --git a/internal/bridge/console_logs.go b/internal/bridge/console_logs.goindex 169d9bcf..4a025708 100644--- a/internal/bridge/console_logs.go+++ b/internal/bridge/console_logs.go@@ -119,7 +119,6 @@ func (s *ConsoleLogStore) GetConsoleLogs(tabID string, limit int) []LogEntry {if limit > s.maxLines {limit = s.maxLines}- // Return most recent entriesstart := count - limitresult := make([]LogEntry, limit)copy(result, t.Console[start:])diff --git a/internal/bridge/crash.go b/internal/bridge/crash.goindex 1f70844a..492dea5f 100644--- a/internal/bridge/crash.go+++ b/internal/bridge/crash.go@@ -85,7 +85,6 @@ func (b *Bridge) MonitorCrashes(handler CrashHandler) {return}- // Listen for target crashes on browser contextchromedp.ListenTarget(b.BrowserCtx, func(ev interface{}) {switch e := ev.(type) {case *inspector.EventTargetCrashed:@@ -161,7 +160,6 @@ func (b *Bridge) GetCrashLogs() []string {var logs []string- // Check if last exit was uncleanif WasUncleanExit(b.Config.ProfileDir) {logs = append(logs, "Previous session ended with unclean exit (crash detected)")}diff --git a/internal/bridge/dom.go b/internal/bridge/dom.goindex 3ef8c8ad..07939ab9 100644--- a/internal/bridge/dom.go+++ b/internal/bridge/dom.go@@ -13,7 +13,6 @@ import (// is unmarshaled from the CDP returnByValue response.func (b *Bridge) CallFunctionOnNode(ctx context.Context, backendNodeID int64, functionDecl string, args []map[string]any, result any) error {return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- // Step 1: Resolve backend node ID to a remote object.var resolveResult json.RawMessageif err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{"backendNodeId": backendNodeID,@@ -33,7 +32,6 @@ func (b *Bridge) CallFunctionOnNode(ctx context.Context, backendNodeID int64, fureturn fmt.Errorf("element not found in DOM (backendNodeId=%d)", backendNodeID)}- // Step 2: Call the function on the resolved object.params := map[string]any{"functionDeclaration": functionDecl,"objectId": resolved.Object.ObjectID,@@ -48,7 +46,6 @@ func (b *Bridge) CallFunctionOnNode(ctx context.Context, backendNodeID int64, fureturn fmt.Errorf("call function on node: %w", err)}- // Step 3: Parse the result.var callParsed struct {Result struct {Type string `json:"type"`diff --git a/internal/bridge/input_human.go b/internal/bridge/input_human.goindex 8eb26038..5ce1710e 100644--- a/internal/bridge/input_human.go+++ b/internal/bridge/input_human.go@@ -47,7 +47,6 @@ type Config struct {Rand *rand.Rand}-// getRand returns the configured random source or the global defaultfunc (c *Config) getRand() *rand.Rand {if c != nil && c.Rand != nil {return c.Randdiff --git a/internal/bridge/normalize_selector_test.go b/internal/bridge/normalize_selector_test.goindex 617702d7..d8368d5b 100644--- a/internal/bridge/normalize_selector_test.go+++ b/internal/bridge/normalize_selector_test.go@@ -4,10 +4,6 @@ import ("testing")-// ----------------------------------------------------------------------------// NormalizeSelector β legacy Ref promotion-// ----------------------------------------------------------------------------func TestNormalizeSelector_RefPromotion(t *testing.T) {// When Ref is set and Selector is empty, Ref should promote to Selector.req := ActionRequest{Ref: "e5"}@@ -28,10 +24,6 @@ func TestNormalizeSelector_RefPromotionVariousRefs(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β Selector preserved-// ----------------------------------------------------------------------------func TestNormalizeSelector_SelectorPreserved(t *testing.T) {// When Selector is already set, it should not be overwritten.req := ActionRequest{Selector: "#login"}@@ -59,10 +51,6 @@ func TestNormalizeSelector_SelectorPreservedVariousTypes(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β Ref wins when both set-// ----------------------------------------------------------------------------func TestNormalizeSelector_RefWinsWhenBothSet(t *testing.T) {// When both Ref and Selector are set, Selector is already populated// so NormalizeSelector leaves it as-is (Ref doesn't overwrite).@@ -76,10 +64,6 @@ func TestNormalizeSelector_RefWinsWhenBothSet(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β empty fields-// ----------------------------------------------------------------------------func TestNormalizeSelector_BothEmpty(t *testing.T) {req := ActionRequest{}req.NormalizeSelector()@@ -99,10 +83,6 @@ func TestNormalizeSelector_EmptyRef(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β idempotency-// ----------------------------------------------------------------------------func TestNormalizeSelector_Idempotent(t *testing.T) {// Calling NormalizeSelector multiple times should produce the same result.tests := []ActionRequest{@@ -134,10 +114,6 @@ func TestNormalizeSelector_Idempotent(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β does not modify other fields-// ----------------------------------------------------------------------------func TestNormalizeSelector_OtherFieldsUntouched(t *testing.T) {req := ActionRequest{Ref: "e5",@@ -179,10 +155,6 @@ func TestNormalizeSelector_OtherFieldsUntouched(t *testing.T) {}}-// ----------------------------------------------------------------------------// NormalizeSelector β non-ref values in Ref field (legacy edge case)-// ----------------------------------------------------------------------------func TestNormalizeSelector_NonRefValueInRefField(t *testing.T) {// Some legacy callers might put a CSS selector in the Ref field.// NormalizeSelector should still promote it to Selector.diff --git a/internal/bridge/observe/network.go b/internal/bridge/observe/network.goindex b0b5ec26..53f6f832 100644--- a/internal/bridge/observe/network.go+++ b/internal/bridge/observe/network.go@@ -630,7 +630,6 @@ func (nm *NetworkMonitor) maybeRetainBody(tabCtx context.Context, buf *NetworkBu})}-// GetResponseBody fetches the response body for a specific request via CDP.func (nm *NetworkMonitor) IsTabIdle(tabID string) (bool, bool) {nm.mu.RLock()buf, ok := nm.buffers[tabID]@@ -642,6 +641,7 @@ func (nm *NetworkMonitor) IsTabIdle(tabID string) (bool, bool) {return count == 0, true}+// GetResponseBody fetches the response body for a specific request via CDP.func (nm *NetworkMonitor) GetResponseBody(tabCtx context.Context, requestID string) (string, bool, error) {var body stringvar base64Encoded booldiff --git a/internal/bridge/observe/network_export.go b/internal/bridge/observe/network_export.goindex 963748ff..ab9549ad 100644--- a/internal/bridge/observe/network_export.go+++ b/internal/bridge/observe/network_export.go@@ -8,10 +8,6 @@ import ("sync")-// ----------------------------------------------------------------------------// ExportEncoder β pluggable format interface-// ----------------------------------------------------------------------------// ExportEncoder streams network entries to an io.Writer in a specific format.// Implementations are registered via RegisterFormat and created per-export.// Not concurrent-safe; callers serialize Start β Encode* β Finish.@@ -36,10 +32,6 @@ type ExportEncoder interface {// ExportEncoderFactory creates a new encoder for a single export session.type ExportEncoderFactory func(creatorName, creatorVersion string) ExportEncoder-// ----------------------------------------------------------------------------// Format registry-// ----------------------------------------------------------------------------var (formatsMu sync.RWMutexformats = map[string]ExportEncoderFactory{}@@ -72,10 +64,6 @@ func ListFormats() []string {return names}-// ----------------------------------------------------------------------------// ExportEntry β canonical intermediate for all formats-// ----------------------------------------------------------------------------// ExportEntry is the normalized representation of a network request/response.// All export formats encode from this struct.type ExportEntry struct {@@ -137,10 +125,6 @@ type NameValuePair struct {Value string `json:"value"`}-// ----------------------------------------------------------------------------// Conversion: NetworkEntry β ExportEntry-// ----------------------------------------------------------------------------// NetworkEntryToExport converts a captured NetworkEntry to the canonical ExportEntry.// body and base64Encoded are provided when response bodies are fetched on demand.func NetworkEntryToExport(entry NetworkEntry, body string, base64Encoded bool) ExportEntry {diff --git a/internal/bridge/observe/snapshot.go b/internal/bridge/observe/snapshot.goindex 5ba5750d..c2653629 100644--- a/internal/bridge/observe/snapshot.go+++ b/internal/bridge/observe/snapshot.go@@ -333,7 +333,6 @@ func BuildSnapshot(nodes []RawAXNode, filter string, maxDepth int) ([]A11yNode,hiddenNodes[n.NodeID] = true}}- // Propagate: if a parent is hidden, all descendants inherit hidden status.isHidden := func(nodeID string) bool {cur := nodeIDfor range maxAncestorWalk {diff --git a/internal/bridge/profile_lock.go b/internal/bridge/profile_lock.goindex 8a5ab28f..8ec5d305 100644--- a/internal/bridge/profile_lock.go+++ b/internal/bridge/profile_lock.go@@ -70,8 +70,6 @@ func clearStaleProfileLocks(profileDir, errMsg string) (bool, error) {if err != nil {slog.Warn("failed to probe browser lock pid; falling back to process listing", "profile", profileDir, "pid", pid, "err", err)} else if running {- // If we find the PID from the error message is still running,- // check if it's actually managed by another active PinchTab.if owned, ptPid := isProfileOwnedByRunningPinchtabMock(profileDir); owned {slog.Warn("browser profile lock appears active and owned by another pinchtab; leaving singleton files in place", "profile", profileDir, "pid", pid, "pinchtab_pid", ptPid)return false, nil@@ -98,7 +96,6 @@ func clearStaleProfileLocks(profileDir, errMsg string) (bool, error) {return false, nil}- // If no other PinchTab owns this profile, we can safely kill the stale browser processes.slog.Warn("browser profile lock appears active but no pinchtab owner found; killing stale processes", "profile", profileDir)if err := killChromeProfileProcesses(processes); err != nil {slog.Error("failed to kill stale browser processes", "profile", profileDir, "err", err)diff --git a/internal/bridge/profile_lock_pid_other.go b/internal/bridge/profile_lock_pid_other.goindex af31adcb..7e679f62 100644--- a/internal/bridge/profile_lock_pid_other.go+++ b/internal/bridge/profile_lock_pid_other.go@@ -37,9 +37,8 @@ func killProcesses(processes []chromeProfileProcess) error {if pid <= 0 {continue}- // Try SIGTERM first, then SIGKILL if it doesn't work?- // Given we are in a "stale recovery" path, being aggressive is often better- // to ensure the next startup succeeds.+ // Straight to SIGKILL: in this stale-recovery path, being aggressive+ // is better to ensure the next startup succeeds._ = syscall.Kill(pid, syscall.SIGKILL)}// Give a small amount of time for processes to actually exit@@ -51,8 +50,6 @@ func isPinchTabProcess(pid int) bool {if pid <= 0 {return false}- // On Linux/macOS, we can check the process name or args.- // A simple check is to see if the command contains "pinchtab".cmd := exec.Command("ps", "-p", fmt.Sprintf("%d", pid), "-o", "args=") // #nosec G204 -- pid is an int, not user-controlled stringout, err := cmd.Output()if err != nil {diff --git a/internal/bridge/route.go b/internal/bridge/route.goindex 7956f1cb..0fe1bc52 100644--- a/internal/bridge/route.go+++ b/internal/bridge/route.go@@ -443,8 +443,6 @@ func (rm *RouteManager) Remove(ctx context.Context, tabID string, pattern stringstate := rm.perTab[tabID]if state == nil {rm.mu.Unlock()- // Tab has no rule state at all β distinct from "rules exist but the- // pattern matched nothing." The handler maps ErrTabNotRouted to 404.return 0, ErrTabNotRouted}diff --git a/internal/bridge/route_test.go b/internal/bridge/route_test.goindex 820d63b1..12f75c9e 100644--- a/internal/bridge/route_test.go+++ b/internal/bridge/route_test.go@@ -398,10 +398,6 @@ func TestRouteManager_FulfillForgeryPermittedFor_UnparseableURLDenied(t *testing}}-// Cross-tab dispatch sanity check: rules on tab1 must not match URLs queried-// against tab2. (chromedp's per-target listener dispatch already isolates-// events at the wire level; this asserts the manager-level filter hasn't-// regressed to a global lookup.)// Fulfill rules without an explicit Method should NOT match an OPTIONS// preflight β fulfilling it without ACAO/ACAM/ACAH headers breaks the real// request, and would also let a future custom-headers feature smuggle CORS@@ -499,6 +495,10 @@ func TestNormalizeHTTPMethod(t *testing.T) {}}+// Cross-tab dispatch sanity check: rules on tab1 must not match URLs queried+// against tab2. (chromedp's per-target listener dispatch already isolates+// events at the wire level; this asserts the manager-level filter hasn't+// regressed to a global lookup.)func TestRouteManager_Match_PerTabIsolation(t *testing.T) {rm := NewRouteManager(nil)rm.mu.Lock()diff --git a/internal/bridge/runtime/init_test.go b/internal/bridge/runtime/init_test.goindex c620ea94..d3be6350 100644--- a/internal/bridge/runtime/init_test.go+++ b/internal/bridge/runtime/init_test.go@@ -251,9 +251,7 @@ func TestCloakBrowserFlagArgsNilForNonCloak(t *testing.T) {}}-// ---------------------------------------------------------------------------// Stub browser that does NOT support remote CDP (for guard tests)-// ---------------------------------------------------------------------------type noCDPBrowser struct{}diff --git a/internal/bridge/screencast_test.go b/internal/bridge/screencast_test.goindex c85fe88e..9054e010 100644--- a/internal/bridge/screencast_test.go+++ b/internal/bridge/screencast_test.go@@ -88,7 +88,6 @@ func TestPollingScreencast_FrameDeliveryTiming(t *testing.T) {go func() {defer close(frameCh)- // Simulate initial framecallCount.Add(1)select {case frameCh <- fakeFrame:@@ -114,7 +113,6 @@ func TestPollingScreencast_FrameDeliveryTiming(t *testing.T) {}}()- // Consume frames for 1 secondstart := time.Now()var received inttimeout := time.After(1100 * time.Millisecond)@@ -243,7 +241,6 @@ func TestPollingScreencast_RealLoop_FirstFrameSuccess(t *testing.T) {}defer stream.Close()- // Wait for the first frame.select {case frame, ok := <-stream.Frames:if !ok {@@ -344,7 +341,6 @@ func TestPollingScreencast_RealLoop_MidStreamError(t *testing.T) {}defer stream.Close()- // Drain until channel closes.var received intfor range stream.Frames {received++diff --git a/internal/bridge/screenshot.go b/internal/bridge/screenshot.goindex 988273a7..c0bf2ac5 100644--- a/internal/bridge/screenshot.go+++ b/internal/bridge/screenshot.go@@ -149,15 +149,6 @@ func scaledScreenshotClip(opts ScreenshotOpts, viewportWidth, viewportHeight, do}}-// CaptureScreenshot runs Page.captureScreenshot with the supplied options.-// Quality is applied only for JPEG; clip and beyondViewport are mutually-// exclusive (clip wins) β the same rule the handler enforces on input.-//-// When Scale is non-default (not 0 and not 1), the function ensures a clip is-// passed to CDP β either by reusing the supplied one with Scale multiplied in,-// or by synthesizing a viewport-covering clip from ViewportWidth/Height. CDP's-// top-level capture call has no scale parameter outside of clip, so this is-// the only way to apply a render-time rescale.// captureFromSurface decides the Page.captureScreenshot fromSurface flag.//// fromSurface=false reads the renderer's current view directly instead of@@ -176,6 +167,15 @@ func captureFromSurface(beyondViewport bool, clip *page.Viewport) bool {return clip != nil && clip.Scale != 0 && clip.Scale != 1}+// CaptureScreenshot runs Page.captureScreenshot with the supplied options.+// Quality is applied only for JPEG; clip and beyondViewport are mutually+// exclusive (clip wins) β the same rule the handler enforces on input.+//+// When Scale is non-default (not 0 and not 1), the function ensures a clip is+// passed to CDP β either by reusing the supplied one with Scale multiplied in,+// or by synthesizing a viewport-covering clip from ViewportWidth/Height. CDP's+// top-level capture call has no scale parameter outside of clip, so this is+// the only way to apply a render-time rescale.func CaptureScreenshot(ctx context.Context, opts ScreenshotOpts) ([]byte, error) {clip := opts.Clipif opts.Scale > 0 && opts.Scale != 1 {diff --git a/internal/bridge/tab_executor_integration_test.go b/internal/bridge/tab_executor_integration_test.goindex 088d3ea2..8ce3bad8 100644--- a/internal/bridge/tab_executor_integration_test.go+++ b/internal/bridge/tab_executor_integration_test.go@@ -9,8 +9,6 @@ import ("time")-// --- Integration Tests ----func TestTabExecutor_MultiTabSimulation(t *testing.T) {// Simulate 3 tabs executing independentlyte := NewTabExecutor(4)@@ -93,8 +91,6 @@ func TestTabExecutor_PanicIsolation(t *testing.T) {}}-// --- Stress Tests ----func TestTabExecutor_StressHighConcurrency(t *testing.T) {te := NewTabExecutor(4)var completed int32@@ -164,8 +160,6 @@ func TestTabExecutor_StressSameTabConcurrent(t *testing.T) {}}-// --- TabManager Integration ----func TestTabManager_ExecuteWithoutExecutor(t *testing.T) {tm := &TabManager{tabs: make(map[string]*TabEntry),diff --git a/internal/browsers/all/browser_handle_test.go b/internal/browsers/all/browser_handle_test.goindex 698a3baa..cba78f8c 100644--- a/internal/browsers/all/browser_handle_test.go+++ b/internal/browsers/all/browser_handle_test.go@@ -9,10 +9,6 @@ import (_ "github.com/pinchtab/pinchtab/internal/browsers/all")-// ----------------------------------------------------------------------------// Stub browsers for contract tests-// ----------------------------------------------------------------------------// handleStub always returns DecisionHandle with empty reason.type handleStub struct{}@@ -92,10 +88,6 @@ var (registerFailOnce sync.Once)-// ----------------------------------------------------------------------------// TestHandleContract_DirectHandle-// ----------------------------------------------------------------------------func TestHandleContract_DirectHandle(t *testing.T) {registerHandleOnce.Do(func() { browsers.Register(&handleStub{}) })@@ -120,10 +112,6 @@ func TestHandleContract_DirectHandle(t *testing.T) {}}-// ----------------------------------------------------------------------------// TestHandleContract_SkipToNext-// ----------------------------------------------------------------------------func TestHandleContract_SkipToNext(t *testing.T) {registerSkipOnce.Do(func() { browsers.Register(&skipStub{}) })@@ -146,10 +134,6 @@ func TestHandleContract_SkipToNext(t *testing.T) {}}-// ----------------------------------------------------------------------------// TestHandleContract_HardFailure-// ----------------------------------------------------------------------------func TestHandleContract_HardFailure(t *testing.T) {registerFailOnce.Do(func() { browsers.Register(&failStub{}) })@@ -172,10 +156,6 @@ func TestHandleContract_HardFailure(t *testing.T) {}}-// ----------------------------------------------------------------------------// TestHandleContract_DeterministicReasons-// ----------------------------------------------------------------------------func TestHandleContract_DeterministicReasons(t *testing.T) {b := browsers.MustGet("ghost-chrome")@@ -204,10 +184,6 @@ func TestHandleContract_DeterministicReasons(t *testing.T) {})}-// ----------------------------------------------------------------------------// TestHandleContract_StateChangingSafety-// ----------------------------------------------------------------------------func TestHandleContract_StateChangingSafety(t *testing.T) {tests := []struct {name stringdiff --git a/internal/browsers/browser.go b/internal/browsers/browser.goindex dbcb8b7f..c5f79a3b 100644--- a/internal/browsers/browser.go+++ b/internal/browsers/browser.go@@ -29,10 +29,6 @@ type LaunchFailure struct {BrowserCanceled bool}-// ----------------------------------------------------------------------------// Handle-decision types-// ----------------------------------------------------------------------------// Routing contract://// DecisionHandle β provider accepts the request; proceed with execution.@@ -77,10 +73,6 @@ const (ShapeDownloadUpload = "download-upload")-// ----------------------------------------------------------------------------// Browser interface-// ----------------------------------------------------------------------------// Browser is the extension point for adding new browser providers.type Browser interface {// ID returns a short stable identifier ("chrome", "cloak", β¦).@@ -126,10 +118,6 @@ type Browser interface {NewRuntimeInstance(browserCtx context.Context, headless bool) RuntimeInstance}-// ----------------------------------------------------------------------------// Registry-// ----------------------------------------------------------------------------var (mu sync.Mutexregistry = map[string]Browser{}@@ -193,7 +181,6 @@ func sortedKeysLocked() []string {return out}-// resetForTesting clears the global registry for this package's tests.func resetForTesting() {mu.Lock()defer mu.Unlock()diff --git a/internal/browsers/browser_test.go b/internal/browsers/browser_test.goindex 18c304d3..17cca133 100644--- a/internal/browsers/browser_test.go+++ b/internal/browsers/browser_test.go@@ -35,10 +35,6 @@ func stub(id string) Browser {return &stubBrowser{id: id, displayName: id}}-// ----------------------------------------------------------------------------// Tests-// ----------------------------------------------------------------------------func TestDuplicateRegistrationPanics(t *testing.T) {resetForTesting()diff --git a/internal/browsers/chrome/chrome.go b/internal/browsers/chrome/chrome.goindex 973cedcc..130a4291 100644--- a/internal/browsers/chrome/chrome.go+++ b/internal/browsers/chrome/chrome.go@@ -117,7 +117,6 @@ func (Browser) BuildLaunchArgs(cfg browsers.LaunchConfig) ([]string, []string, e}var args []string- // Debug port (first, before base flags)if cfg.DebugPort > 0 {args = append(args, fmt.Sprintf("--remote-debugging-port=%d", cfg.DebugPort))}diff --git a/internal/browsers/chrome/instance.go b/internal/browsers/chrome/instance.goindex f51ab897..c4d8df86 100644--- a/internal/browsers/chrome/instance.go+++ b/internal/browsers/chrome/instance.go@@ -32,10 +32,6 @@ func NewInstance(browserCtx context.Context, headless bool) *Instance {var _ browsers.RuntimeInstance = (*Instance)(nil)-// ----------------------------------------------------------------------------// Visual capture-// ----------------------------------------------------------------------------// CaptureScreenshot captures a screenshot of the current page.func (i *Instance) CaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error) {var buf []byte@@ -85,13 +81,6 @@ func (i *Instance) CaptureScreenshot(ctx context.Context, format string, qualityreturn buf, nil}-// Screencast streaming (StartScreencast and its event-driven/polling-// strategies) lives in instance_screencast.go.--// ----------------------------------------------------------------------------// JavaScript evaluation-// ----------------------------------------------------------------------------// Evaluate evaluates a JavaScript expression in the page context.func (i *Instance) Evaluate(ctx context.Context, expression string, result any, opts browsers.EvalOpts) error {var chromedpOpts []chromedp.EvaluateOption@@ -154,7 +143,6 @@ func (i *Instance) EvaluateInFrame(ctx context.Context, frameID string, expressi// calls the given JavaScript function on it.func (i *Instance) CallFunctionOnNode(ctx context.Context, backendNodeID int64, functionDecl string, args []map[string]any, result any) error {return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {- // Step 1: Resolve backend node ID to a remote object.var resolveResult json.RawMessageif err := chromedp.FromContext(ctx).Target.Execute(ctx, "DOM.resolveNode", map[string]any{"backendNodeId": backendNodeID,@@ -174,7 +162,6 @@ func (i *Instance) CallFunctionOnNode(ctx context.Context, backendNodeID int64,return fmt.Errorf("element not found in DOM (backendNodeId=%d)", backendNodeID)}- // Step 2: Call the function on the resolved object.params := map[string]any{"functionDeclaration": functionDecl,"objectId": resolved.Object.ObjectID,@@ -189,7 +176,6 @@ func (i *Instance) CallFunctionOnNode(ctx context.Context, backendNodeID int64,return fmt.Errorf("call function on node: %w", err)}- // Step 3: Parse the result.var callParsed struct {Result struct {Type string `json:"type"`@@ -213,10 +199,6 @@ func (i *Instance) CallFunctionOnNode(ctx context.Context, backendNodeID int64,}))}-// ----------------------------------------------------------------------------// DOM-// ----------------------------------------------------------------------------// DescribeNode returns DOM structural info for a backend node ID.func (i *Instance) DescribeNode(ctx context.Context, backendNodeID int64) (*browsers.NodeInfo, error) {var info browsers.NodeInfo@@ -300,10 +282,6 @@ func (i *Instance) SetFileInputFiles(ctx context.Context, nodeID int64, paths []}))}-// ----------------------------------------------------------------------------// Cookies-// ----------------------------------------------------------------------------// GetCookies retrieves cookies for the given URLs via CDP.func (i *Instance) GetCookies(ctx context.Context, urls []string) ([]browsers.CookieData, error) {var cookies []*network.Cookie@@ -369,10 +347,6 @@ func (i *Instance) SetCookie(ctx context.Context, params browsers.SetCookieParam}))}-// ----------------------------------------------------------------------------// Emulation-// ----------------------------------------------------------------------------// SetViewport overrides device metrics for the page.func (i *Instance) SetViewport(ctx context.Context, params browsers.ViewportParams) error {return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {@@ -395,10 +369,6 @@ func (i *Instance) SetEmulatedMedia(ctx context.Context, feature, value string)}))}-// ----------------------------------------------------------------------------// Network state-// ----------------------------------------------------------------------------// SetNetworkConditions emulates network conditions via CDP.func (i *Instance) SetNetworkConditions(ctx context.Context, params browsers.NetworkConditions) error {return chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {@@ -418,10 +388,6 @@ func (i *Instance) SetExtraHTTPHeaders(ctx context.Context, headers map[string]s}))}-// ----------------------------------------------------------------------------// Navigation info-// ----------------------------------------------------------------------------// CurrentURL returns the current page URL.func (i *Instance) CurrentURL(ctx context.Context) (string, error) {var url string@@ -436,10 +402,6 @@ func (i *Instance) CurrentTitle(ctx context.Context) (string, error) {return title, err}-// ----------------------------------------------------------------------------// ----------------------------------------------------------------------------// PrintToPDF generates a PDF of the current page via CDP.func (i *Instance) PrintToPDF(ctx context.Context, params browsers.PDFParams) ([]byte, error) {var buf []byte@@ -476,10 +438,6 @@ func (i *Instance) PrintToPDF(ctx context.Context, params browsers.PDFParams) ([return buf, err}-// ----------------------------------------------------------------------------// Helpers-// ----------------------------------------------------------------------------// frameExecutionContextID returns a Runtime.executionContextId that evaluates// in the given frame's document. Returns (0, nil) when frameID is empty so// callers can fall back to the default top-level context without branching.diff --git a/internal/browsers/chrome/instance_screencast.go b/internal/browsers/chrome/instance_screencast.goindex 25dd22d9..e2fca0a7 100644--- a/internal/browsers/chrome/instance_screencast.go+++ b/internal/browsers/chrome/instance_screencast.go@@ -69,7 +69,6 @@ func (i *Instance) startScreencastEventDriven(ctx context.Context, opts browsers}}()- // Listen for screencast frames with rate limitingvar lastFrame time.Timechromedp.ListenTarget(ctx, func(ev interface{}) {switch e := ev.(type) {diff --git a/internal/browsers/cloak/cloak_test.go b/internal/browsers/cloak/cloak_test.goindex 0846de2c..eee748ef 100644--- a/internal/browsers/cloak/cloak_test.go+++ b/internal/browsers/cloak/cloak_test.go@@ -366,9 +366,7 @@ func TestClassifyLaunchErrorBrowserNotCanceled(t *testing.T) {}}-// ---------------------------------------------------------------------------// Parity tests: verify launch-arg and validation behaviour across configs.-// ---------------------------------------------------------------------------func TestBuildLaunchArgsParityWithRepresentativeConfigs(t *testing.T) {b, ok := browsers.Get("cloak")diff --git a/internal/browsers/cloak/doctor.go b/internal/browsers/cloak/doctor.goindex 1c4f7b35..af79c148 100644--- a/internal/browsers/cloak/doctor.go+++ b/internal/browsers/cloak/doctor.go@@ -141,7 +141,6 @@ func fingerprintFlagsCheck(ctx context.Context, cfg interface{}) browsers.Doctorreturn browsers.DoctorCheckResult{Status: browsers.DoctorSkip, Detail: "skipped β no browser.binary set (see cloakbrowser_present)"}}- // Build fingerprint flags using our own BuildLaunchArgs.launchCfg := browsers.LaunchConfig{Cloak: env.Cloak,}@@ -153,7 +152,6 @@ func fingerprintFlagsCheck(ctx context.Context, cfg interface{}) browsers.DoctorErr: err,}}- // Extract only fingerprint flags.var fpFlags []stringfor _, a := range allArgs {if strings.HasPrefix(a, "--fingerprint") {diff --git a/internal/browsers/config.go b/internal/browsers/config.goindex db2d684b..1b420140 100644--- a/internal/browsers/config.go+++ b/internal/browsers/config.go@@ -2,10 +2,6 @@ package browsersimport "context"-// ----------------------------------------------------------------------------// Provider-neutral config types used by the Browser interface.-// ----------------------------------------------------------------------------// LaunchMode selects how a browser session is launched.type LaunchMode stringdiff --git a/internal/browsers/ghostchrome/bridge_proxy.go b/internal/browsers/ghostchrome/bridge_proxy.goindex 8a58a0b8..778c0c1e 100644--- a/internal/browsers/ghostchrome/bridge_proxy.go+++ b/internal/browsers/ghostchrome/bridge_proxy.go@@ -77,7 +77,6 @@ func (p *BridgeProxy) tabEscalationLock(tabID string) *sync.Mutex {// TabContext resolves a tab ID to a context. For lite tabs it lazily// escalates to Chrome by navigating Chrome to the lite tab's URL.func (p *BridgeProxy) TabContext(tabID string) (context.Context, string, error) {- // Try the Chrome bridge first.ctx, resolved, err := p.chrome.TabContext(tabID)if err == nil {return ctx, resolved, nil@@ -97,18 +96,15 @@ func (p *BridgeProxy) TabContext(tabID string) (context.Context, string, error)if mapErr == nil {return ctx, resolved, nil}- // Cached mapping is stale β clear it.p.tabMap.clear(tabID)slog.Debug("cleared stale liteβchrome mapping", "liteTab", tabID, "chromeTab", chromeID)}- // Look up the URL from the static browser.url, found := p.lite.TabURL(tabID)if !found {return nil, "", err // return original error}- // Escalate: ensure Chrome is running and create a tab.if p.ensureBrowser != nil {if ensureErr := p.ensureBrowser(); ensureErr != nil {return nil, "", ensureErr@@ -243,8 +239,6 @@ func (p *BridgeProxy) TabURL(tabID string) (string, bool) {return p.lite.TabURL(tabID)}-// ---------- tab mapping -----------// tabMapping tracks lite-tabID β Chrome-tabID associations created by// lazy Chrome escalation. Thread-safe.type tabMapping struct {diff --git a/internal/browsers/ghostchrome/bridge_proxy_test.go b/internal/browsers/ghostchrome/bridge_proxy_test.goindex 1c061690..02f64720 100644--- a/internal/browsers/ghostchrome/bridge_proxy_test.go+++ b/internal/browsers/ghostchrome/bridge_proxy_test.go@@ -12,8 +12,6 @@ import ("github.com/pinchtab/pinchtab/internal/browsers/ghostchrome/staticfetch")-// ---------- mock chrome bridge -----------type mockChromeBridge struct {mu sync.Mutextabs map[string]bool // known Chrome tab IDs@@ -71,8 +69,6 @@ func (m *mockChromeBridge) AvailableActions() []string {return []string{ActionClick, ActionType, ActionPress}}-// ---------- ensure browser helper -----------type ensureBrowserTracker struct {calls interr error@@ -85,8 +81,6 @@ func (t *ensureBrowserTracker) fn() func() error {}}-// ---------- tests -----------func TestBridgeProxy_TabContext_ChromeTabPassthrough(t *testing.T) {mb := newMockChromeBridge()ec := &ensureBrowserTracker{}@@ -102,7 +96,6 @@ func TestBridgeProxy_TabContext_ChromeTabPassthrough(t *testing.T) {if resolved != "chrome-tab-1" {t.Fatalf("expected resolved = %q, got %q", "chrome-tab-1", resolved)}- // Should not have called EnsureBrowser or CreateTab.if ec.calls != 0 {t.Fatalf("expected 0 EnsureBrowser calls, got %d", ec.calls)}@@ -134,7 +127,6 @@ func TestBridgeProxy_TabContext_LiteTabEscalates(t *testing.T) {if ctx == nil {t.Fatal("expected non-nil context")}- // Should have escalated: EnsureBrowser + CreateTab.if ec.calls != 1 {t.Fatalf("expected 1 EnsureBrowser call, got %d", ec.calls)}@@ -144,7 +136,6 @@ func TestBridgeProxy_TabContext_LiteTabEscalates(t *testing.T) {if mb.createTabURLs[0] != ts.URL {t.Fatalf("CreateTab URL = %q, want %q", mb.createTabURLs[0], ts.URL)}- // The resolved ID should be the Chrome tab.if resolved != mb.lastCreatedTabID {t.Fatalf("resolved = %q, want %q", resolved, mb.lastCreatedTabID)}@@ -180,7 +171,6 @@ func TestBridgeProxy_TabContext_CachedEscalation(t *testing.T) {if err != nil {t.Fatalf("second call: %v", err)}- // Should NOT have called EnsureBrowser again.if ec.calls != 1 {t.Fatalf("expected still 1 EnsureBrowser call, got %d", ec.calls)}@@ -280,7 +270,6 @@ func TestBridgeProxy_TabContext_ConcurrentEscalation(t *testing.T) {}}- // CreateTab should have been called exactly once.if len(mb.createTabURLs) != 1 {t.Fatalf("expected 1 CreateTab call, got %d", len(mb.createTabURLs))}@@ -305,7 +294,6 @@ func TestBridgeProxy_ExecuteAction_ClickWithRef(t *testing.T) {proxy := NewBridgeProxy(mb, lite, nil)- // Find a button ref from the snapshot.snap, _ := lite.Snapshot(context.Background(), navResult.TabID, "interactive")if len(snap.Nodes) == 0 {t.Skip("no interactive nodes in test page")@@ -322,7 +310,6 @@ func TestBridgeProxy_ExecuteAction_ClickWithRef(t *testing.T) {if result["clicked"] != true {t.Fatalf("expected clicked=true, got %v", result)}- // Should NOT have gone to Chrome bridge.if _, has := result["chrome"]; has {t.Fatal("expected static browser to handle click, but went to Chrome")}@@ -434,8 +421,6 @@ func TestBridgeProxy_AvailableActions_MergesStaticAndChrome(t *testing.T) {}}-// ---------- test HTTP server -----------func startTestHTTPServer(t *testing.T) *httptest.Server {t.Helper()return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.goindex 87510cfb..080162a6 100644--- a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_content.go@@ -21,7 +21,7 @@ func (a *BridgeAdapter) StaticFirstNavigate() bool {return a.StaticBrowser() != nil}-// escalateError builds the typed signal for NoEscalate mode, carrying the+// staticEscalateError builds the typed signal for NoEscalate mode, carrying the// static attempt's route metadata for the caller to merge.func staticEscalateError(quality int, reason string) *bridge.StaticEscalateError {return &bridge.StaticEscalateError{@@ -78,7 +78,6 @@ func (a *BridgeAdapter) Navigate(ctx context.Context, url string, params bridge.ctx = staticfetch.WithNavigateNetworkPolicy(ctx, navigateParamsToPolicy(¶ms))navResult, err := staticBrowser.Navigate(ctx, url)if err == nil {- // Assess content quality by extracting text from the static page.textResult, textErr := staticBrowser.Text(ctx, navResult.TabID)if textErr == nil {gr := ghostchrome.AssessContent(textResult.Text)@@ -127,7 +126,6 @@ func (a *BridgeAdapter) Navigate(ctx context.Context, url string, params bridge.return nil, staticEscalateError(0, "static browser unavailable")}- // Static browser unavailable or failed β go straight to Chrome.chromeResult, chromeErr := a.BridgeAPI.Navigate(ctx, url, params)if chromeErr != nil {return nil, chromeErr@@ -146,13 +144,11 @@ func (a *BridgeAdapter) Snapshot(ctx context.Context, tabID string, filter strinif staticBrowser != nil {snapResult, err := staticBrowser.Snapshot(ctx, tabID, filter)if err == nil && len(snapResult.Nodes) > 0 {- // Convert to ghostchrome.SnapshotNode for quality assessment.assessNodes := make([]ghostchrome.SnapshotNode, len(snapResult.Nodes))for i, n := range snapResult.Nodes {assessNodes[i] = ghostchrome.SnapshotNode{Role: n.Role, Name: n.Name}}if ghostchrome.AssessSnapshot(assessNodes) {- // Convert browserops.SnapshotNode β bridge.A11yNode.flat := make([]bridge.A11yNode, len(snapResult.Nodes))refs := make(map[string]int64, len(snapResult.Nodes))targets := make(map[string]bridge.RefTarget, len(snapResult.Nodes))@@ -171,7 +167,6 @@ func (a *BridgeAdapter) Snapshot(ctx context.Context, tabID string, filter strin}}- // IDPI: scan snapshot node names/values when ContentGuard is set.var idpiWarning stringif params.ContentGuard != nil {var sb strings.Builder@@ -204,12 +199,10 @@ func (a *BridgeAdapter) Snapshot(ctx context.Context, tabID string, filter strinRoute: staticAcceptedRoute(0, "", true),}, nil}- // Quality too low β fall through to Chrome.slog.Debug("ghost-chrome snapshot: quality too low, escalating", "tabID", tabID)}}- // Escalate to Chrome. Resolve the tab ID for escalated tabs.resolvedTabID := tabIDif chromeID, ok := a.proxy.ChromeTabID(tabID); ok {resolvedTabID = chromeID@@ -233,7 +226,6 @@ func (a *BridgeAdapter) Text(ctx context.Context, tabID string, params bridge.Coif err == nil && textResult.Text != "" {gr := ghostchrome.AssessContent(textResult.Text)if gr.ShouldAccept() {- // IDPI: scan extracted text when ContentGuard is set.text := textResult.Textvar idpiWarning stringif params.ContentGuard != nil {@@ -257,13 +249,11 @@ func (a *BridgeAdapter) Text(ctx context.Context, tabID string, params bridge.CoRoute: staticAcceptedRoute(gr.Quality, gr.FormatReason(), true),}, nil}- // Quality too low β fall through to Chrome.slog.Debug("ghost-chrome text: quality too low, escalating","tabID", tabID, "quality", gr.Quality, "reason", gr.FormatReason())}}- // Escalate to Chrome. Resolve the tab ID for escalated tabs.resolvedTabID := tabIDif chromeID, ok := a.proxy.ChromeTabID(tabID); ok {resolvedTabID = chromeID@@ -289,7 +279,6 @@ func navigateParamsToPolicy(p *bridge.NavigateParams) *staticfetch.NavigateNetwoMaxRedirects: p.MaxRedirects,}- // []net.IPNet β []*net.IPNetif len(p.TrustedProxyCIDRs) > 0 {policy.TrustedProxyCIDRs = make([]*net.IPNet, len(p.TrustedProxyCIDRs))for i := range p.TrustedProxyCIDRs {@@ -297,7 +286,6 @@ func navigateParamsToPolicy(p *bridge.NavigateParams) *staticfetch.NavigateNetwo}}- // []net.IP β []netip.Addrif len(p.TrustedResolvedIPs) > 0 {addrs := make([]netip.Addr, 0, len(p.TrustedResolvedIPs))for _, ip := range p.TrustedResolvedIPs {diff --git a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.goindex e48599fa..21b9c99e 100644--- a/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go+++ b/internal/browsers/ghostchrome/bridgekit/bridge_adapter_test.go@@ -20,8 +20,6 @@ import ("github.com/pinchtab/pinchtab/internal/netguard")-// ---------- mock IDPI guard -----------type mockGuard struct {enabled boolblocked bool@@ -49,8 +47,6 @@ func (g *mockGuard) WrapContent(text, pageURL string) string {return text}-// ---------- helpers -----------func newRichTestServer() *httptest.Server {// Produce enough content so the quality gate accepts the static result.body := `<!DOCTYPE html>@@ -83,8 +79,6 @@ func newIDPITestServer(injectedContent string) *httptest.Server {}))}-// ---------- mock chrome bridge for adapter routing tests -----------type mockChromeBridge struct {navigateCalled boolnavigateResult *bridge.NavigateResult@@ -154,8 +148,6 @@ func newTestAdapter(t *testing.T, lite *staticfetch.Browser, mock *mockChromeBri}}-// ---------- routing integration tests -----------func TestAdapterNavigate_StaticAccepted(t *testing.T) {ts := newRichTestServer()defer ts.Close()@@ -809,8 +801,6 @@ func TestStaticSnapshotIDPIWarning(t *testing.T) {}}-// ---------- escalation lifecycle tests -----------// escalatingChromeBridge fails TabContext for unknown IDs, forcing the proxy// down the lite-escalation path; CreateTab registers the new Chrome tab.type escalatingChromeBridge struct {@@ -961,7 +951,7 @@ func TestAdapterCloseTab_UnescalatedLiteTab_NoChromeInvolved(t *testing.T) {}}-// H1b: NoEscalate returns the typed escalation signal instead of internally+// NoEscalate returns the typed escalation signal instead of internally// falling through to Chrome, and releases the rejected static tab.func TestAdapterNavigate_NoEscalateReturnsTypedError(t *testing.T) {ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -995,7 +985,7 @@ func TestAdapterNavigate_NoEscalateReturnsTypedError(t *testing.T) {}}-// H1b: SkipStatic bypasses the static fetch entirely (the handler already+// SkipStatic bypasses the static fetch entirely (the handler already// ran it) and goes straight to Chrome.func TestAdapterNavigate_SkipStaticGoesStraightToChrome(t *testing.T) {ts := newRichTestServer() // would static-accept if the fetch randiff --git a/internal/browsers/ghostchrome/ghostchrome.go b/internal/browsers/ghostchrome/ghostchrome.goindex 880aae58..9ea6ecb9 100644--- a/internal/browsers/ghostchrome/ghostchrome.go+++ b/internal/browsers/ghostchrome/ghostchrome.go@@ -36,9 +36,7 @@ func (b *Browser) DoctorChecks(_ browsers.TargetConfig) []browsers.DoctorCheck {ID: "handle_decisions",Description: "Verify ghost-chrome handle/skip behavior and state-changing safety",Fn: func(ctx context.Context, cfg interface{}) browsers.DoctorCheckResult {- // Static shapes should be handledstaticShapes := []string{browsers.ShapeStaticRead, browsers.ShapeStaticSnapshot}- // Interactive shapes should be skippedskipShapes := []string{browsers.ShapeRenderedRead, browsers.ShapeVisual,browsers.ShapeInteraction, browsers.ShapeSessionState,@@ -61,7 +59,6 @@ func (b *Browser) DoctorChecks(_ browsers.TargetConfig) []browsers.DoctorCheck {}}- // State-changing safety: static-read with StateChanging=true should be skippedd := b.CanHandle(browsers.RequestIntent{Shape: browsers.ShapeStaticRead, StateChanging: true})if d.Decision != browsers.DecisionSkip {issues = append(issues, fmt.Sprintf("state-changing static-read: expected skip, got %s", d.Decision))diff --git a/internal/browsers/ghostchrome/staticfetch/realworld_test.go b/internal/browsers/ghostchrome/staticfetch/realworld_test.goindex b16c1fbc..366782c9 100644--- a/internal/browsers/ghostchrome/staticfetch/realworld_test.go+++ b/internal/browsers/ghostchrome/staticfetch/realworld_test.go@@ -11,11 +11,9 @@ import ("github.com/pinchtab/pinchtab/internal/browserops")-// ----------------------------------------------------------------------------// Realistic page templates simulating common website structures.-// These tests verify the static browser produces correct accessibility snapshots-// comparable to what Chrome's CDP accessibility tree would return.-// ---------------------------------------------------------------------------+// Realistic page templates simulating common website structures. These tests+// verify the static browser produces correct accessibility snapshots comparable+// to what Chrome's CDP accessibility tree would return.const wikipediaStylePage = `<!DOCTYPE html><html lang="en">@@ -347,10 +345,6 @@ const emptyAndMinimalPage = `<!DOCTYPE html><body></body></html>`-// ----------------------------------------------------------------------------// Test runner-// ----------------------------------------------------------------------------type realworldTestCase struct {name stringhtml string@@ -384,10 +378,6 @@ func runRealworldSuite(t *testing.T, tc realworldTestCase) {}}-// ----------------------------------------------------------------------------// Helpers-// ----------------------------------------------------------------------------func snapshotNodes(t *testing.T, lite *Browser, filter string) []browserops.SnapshotNode {t.Helper()result, err := lite.Snapshot(context.Background(), "", filter)@@ -447,10 +437,6 @@ func requireTextNotContains(t *testing.T, text string, subs ...string) {}}-// ----------------------------------------------------------------------------// Test cases-// ----------------------------------------------------------------------------func TestRealworld_WikipediaStyle(t *testing.T) {runRealworldSuite(t, realworldTestCase{name: "Wikipedia-style article",diff --git a/internal/browsers/ghostchrome/staticfetch/staticfetch.go b/internal/browsers/ghostchrome/staticfetch/staticfetch.goindex 27936d01..317539da 100644--- a/internal/browsers/ghostchrome/staticfetch/staticfetch.go+++ b/internal/browsers/ghostchrome/staticfetch/staticfetch.go@@ -303,7 +303,6 @@ func (l *Browser) walkDOM(tab *liteTab, node dom.Node, filter string, depth int)tag := strings.ToLower(el.TagName())- // Skip non-visible and script/style elements.if tag == "script" || tag == "style" || tag == "noscript" || tag == "link" || tag == "meta" {return nodes}@@ -436,7 +435,6 @@ func getRole(el dom.Element) string {return "generic"}-// getAccessibleName resolves an element's accessible name.func getAccessibleName(el dom.Element) string {if label, ok := el.GetAttribute("aria-label"); ok {return label@@ -465,7 +463,6 @@ func getAccessibleName(el dom.Element) string {return ""}-// isInteractive returns true for elements a user can interact with.func isInteractive(el dom.Element) bool {switch strings.ToLower(el.TagName()) {case "a":diff --git a/internal/browsers/runtime.go b/internal/browsers/runtime.goindex 023acad0..89208f26 100644--- a/internal/browsers/runtime.go+++ b/internal/browsers/runtime.go@@ -6,14 +6,10 @@ import ("github.com/pinchtab/pinchtab/internal/cdptk")-// ----------------------------------------------------------------------------// Runtime parameter / result types-//-// These mirror the identically-named types in internal/bridge so that the-// RuntimeInstance interface can be defined without creating an import cycle-// (config β browsers β bridge β config). Bridge implementations convert+// The types below mirror the identically-named types in internal/bridge so+// that the RuntimeInstance interface can be defined without creating an import+// cycle (config β browsers β bridge β config). Bridge implementations convert// between the two sets at the delegation boundary.-// ---------------------------------------------------------------------------// EvalOpts configures JavaScript evaluation behavior.type EvalOpts struct {@@ -156,40 +152,31 @@ type PDFParams struct {// sub-packages (chrome.Instance, cloak.Instance, ghostchrome.Instance);// compile-time assertions can't live here without inverting the imports.type RuntimeInstance interface {- // Visual captureCaptureScreenshot(ctx context.Context, format string, quality int, clip *cdptk.ScreenshotClip) ([]byte, error)StartScreencast(ctx context.Context, opts ScreencastOpts) (*ScreencastStream, error)- // JavaScript evaluationEvaluate(ctx context.Context, expression string, result any, opts EvalOpts) errorEvaluateInFrame(ctx context.Context, frameID string, expression string, result any, opts EvalOpts) errorCallFunctionOnNode(ctx context.Context, backendNodeID int64, functionDecl string, args []map[string]any, result any) error- // DOMDescribeNode(ctx context.Context, backendNodeID int64) (*NodeInfo, error)ResolveSelectorToNodeID(ctx context.Context, selector string) (int64, error)SetFileInputFiles(ctx context.Context, nodeID int64, paths []string) error- // CookiesGetCookies(ctx context.Context, urls []string) ([]CookieData, error)SetCookie(ctx context.Context, params SetCookieParams) error- // EmulationSetViewport(ctx context.Context, params ViewportParams) errorSetGeolocation(ctx context.Context, lat, lng, accuracy float64) errorSetEmulatedMedia(ctx context.Context, feature, value string) error- // Network stateSetNetworkConditions(ctx context.Context, params NetworkConditions) errorSetExtraHTTPHeaders(ctx context.Context, headers map[string]string) error- // Navigation infoCurrentURL(ctx context.Context) (string, error)CurrentTitle(ctx context.Context) (string, error)- // DownloadDownloadURL(ctx context.Context, dlURL string, opts DownloadOpts) (*DownloadResult, error)PrintToPDF(ctx context.Context, params PDFParams) ([]byte, error)}diff --git a/internal/cli/actions/actions_download.go b/internal/cli/actions/actions_download.goindex 6a57206d..5530254b 100644--- a/internal/cli/actions/actions_download.go+++ b/internal/cli/actions/actions_download.go@@ -38,7 +38,6 @@ func Download(client *http.Client, base, token string, args []string, output strprintDownloadResult(result)- // If -o flag set, decode base64 and save to fileif output != "" {savedBytes, err := saveDownloadData(result, output)if err != nil {diff --git a/internal/cli/actions/actions_element.go b/internal/cli/actions/actions_element.goindex ddd1b7ee..709dc6fb 100644--- a/internal/cli/actions/actions_element.go+++ b/internal/cli/actions/actions_element.go@@ -32,10 +32,8 @@ func Action(client *http.Client, base, token, kind, selectorArg string, cmd *cobbody["button"] = button}if css != "" {- // Explicit --css flag: send as plain CSS selectorbody["selector"] = css} else if selectorArg != "" {- // Unified selector: parse and split into ref vs selector for the APIsetSelectorBody(body, selectorArg)} else if !hasXY {cli.Fatal("Usage: pinchtab %s <selector> or pinchtab %s --css <selector> or pinchtab %s --x <num> --y <num>", kind, kind, kind)@@ -99,13 +97,8 @@ func setSelectorBody(body map[string]any, s string) {case selector.KindRef:body["ref"] = sel.Valuecase selector.KindCSS:- // CSS is the default kind β the original string either had a- // `css:` prefix or was auto-detected. Send the value without a- // prefix; the server will re-parse as CSS.body["selector"] = sel.Valuedefault:- // text:, xpath:, semantic:, find: β preserve the original input- // so the server sees the correct kind prefix when it re-parses.body["selector"] = s}}@@ -121,26 +114,22 @@ func postActionWithHeaders(client *http.Client, base, token string, cmd *cobra.Cpath = "/tabs/" + tabID + "/action"}- // Default to terse output; --json flag enables full JSON responsejsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {apiclient.DoPostWithHeaders(client, base, token, path, body, headers)return}- // Quiet mode: print simple success messageresult := apiclient.DoPostQuietWithHeaders(client, base, token, path, body, headers)kind, _ := body["kind"].(string)printActionResult(kind, result)- // If --snap or --snap-diff flag is set, fetch and output snapshotsnap, _ := cmd.Flags().GetBool("snap")snapDiff, _ := cmd.Flags().GetBool("snap-diff")if snap || snapDiff {fetchAndPrintSnapshot(client, base, token, tabID, snapDiff)}- // If --text flag is set, fetch and output text contenttext, _ := cmd.Flags().GetBool("text")if text {fetchAndPrintText(client, base, token, tabID)@@ -175,13 +164,11 @@ func fetchAndPrintText(client *http.Client, base, token, tabID string) {}func printActionResult(kind string, result map[string]any) {- // Check for failureif success, ok := result["success"].(bool); ok && !success {errMsg := "unknown error"if msg, ok := result["error"].(string); ok {errMsg = msg}- // Check for recovery hintsif recovery, ok := result["recovery"].(map[string]any); ok {if failType, ok := recovery["failure_type"].(string); ok {if failType == "stale" || failType == "navigation" {@@ -401,11 +388,9 @@ func ActionSimple(client *http.Client, base, token, kind string, args []string,switch kind {case "type":- // First arg is a unified selectorsetSelectorBody(body, args[0])body["text"] = strings.Join(args[1:], " ")case "fill":- // First arg is a unified selectorsetSelectorBody(body, args[0])body["text"] = strings.Join(args[1:], " ")case "press":diff --git a/internal/cli/actions/actions_element_test.go b/internal/cli/actions/actions_element_test.goindex 90332d32..7ec0c6bb 100644--- a/internal/cli/actions/actions_element_test.go+++ b/internal/cli/actions/actions_element_test.go@@ -619,8 +619,6 @@ func TestSelect(t *testing.T) {}}-// ββ Keyboard command tests βββββββββββββββββββββββββββββββββββββββββββββ-func TestKeyboardType(t *testing.T) {m := newMockServer()defer m.close()@@ -639,7 +637,6 @@ func TestKeyboardType(t *testing.T) {if body["text"] != "hello world" {t.Errorf("expected text='hello world', got %v", body["text"])}- // Should not have selector or refif _, has := body["selector"]; has {t.Error("keyboard-type should not have selector")}diff --git a/internal/cli/actions/actions_evaluate.go b/internal/cli/actions/actions_evaluate.goindex 4269f38d..787e7c8d 100644--- a/internal/cli/actions/actions_evaluate.go+++ b/internal/cli/actions/actions_evaluate.go@@ -38,7 +38,6 @@ func Evaluate(client *http.Client, base, token string, args []string, cmd *cobracase nil:fmt.Println("null")default:- // Object or array: compact JSONif data, err := json.Marshal(v); err == nil {fmt.Println(string(data))} else {diff --git a/internal/cli/actions/actions_find.go b/internal/cli/actions/actions_find.goindex 1c097139..12b2b917 100644--- a/internal/cli/actions/actions_find.go+++ b/internal/cli/actions/actions_find.go@@ -30,7 +30,6 @@ func Find(client *http.Client, base, token string, query string, cmd *cobra.Commpath = "/tabs/" + tabID + "/find"}- // --ref-only: just print the best refif refOnly {result := apiclient.DoPostQuiet(client, base, token, path, body)if ref, ok := result["best_ref"].(string); ok && ref != "" {@@ -40,7 +39,6 @@ func Find(client *http.Client, base, token string, query string, cmd *cobra.Commcli.Fatal("No element found")}- // --json: full JSON outputif jsonOutput {apiclient.DoPost(client, base, token, path, body)returndiff --git a/internal/cli/actions/actions_navigate.go b/internal/cli/actions/actions_navigate.goindex 42bd9a0e..692dd396 100644--- a/internal/cli/actions/actions_navigate.go+++ b/internal/cli/actions/actions_navigate.go@@ -109,7 +109,6 @@ func Reload(client *http.Client, base, token string, cmd *cobra.Command) {func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Command) string {req := buildNavigateRequest(url, cmd)- // JSON output modejsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {result := postNavigate(client, base, token, req, true)@@ -127,7 +126,6 @@ func Navigate(client *http.Client, base, token string, url string, cmd *cobra.Cooutput.Hint("no session set β this tab is shared. Create one with: export PINCHTAB_SESSION=$(pinchtab session create --agent-id <id> --print-token)")}- // If --snap or --snap-diff flag is set, fetch and output snapshotsnap, _ := cmd.Flags().GetBool("snap")snapDiff, _ := cmd.Flags().GetBool("snap-diff")if snap || snapDiff {diff --git a/internal/cli/actions/actions_network.go b/internal/cli/actions/actions_network.goindex 04e09c3a..54d24ae2 100644--- a/internal/cli/actions/actions_network.go+++ b/internal/cli/actions/actions_network.go@@ -21,13 +21,11 @@ func Network(client *http.Client, base, token string, cmd *cobra.Command, args [return}- // Check for --clear flagif v, _ := cmd.Flags().GetBool("clear"); v {NetworkClear(client, base, token, cmd)return}- // Check for --stream flagif v, _ := cmd.Flags().GetBool("stream"); v {NetworkStream(client, base, token, cmd)returndiff --git a/internal/cli/actions/actions_quick.go b/internal/cli/actions/actions_quick.goindex a6d3d187..8978148d 100644--- a/internal/cli/actions/actions_quick.go+++ b/internal/cli/actions/actions_quick.go@@ -16,7 +16,6 @@ func Quick(client *http.Client, base, token string, args []string) {fmt.Println(cli.StyleStdout(cli.HeadingStyle, fmt.Sprintf("Navigating to %s...", args[0])))- // NavigatenavBody := map[string]any{"url": args[0]}navResult := apiclient.DoPost(client, base, token, "/navigate", navBody)@@ -26,13 +25,11 @@ func Quick(client *http.Client, base, token string, args []string) {fmt.Println()fmt.Println(cli.StyleStdout(cli.HeadingStyle, "Page structure"))- // Snapshot with interactive filtersnapParams := url.Values{}snapParams.Set("filter", "interactive")snapParams.Set("compact", "true")apiclient.DoGet(client, base, token, "/snapshot", snapParams)- // Extract info from navigation resultif title, ok := navResult["title"].(string); ok {fmt.Println()fmt.Printf("%s %s\n", cli.StyleStdout(cli.MutedStyle, "Title:"), cli.StyleStdout(cli.ValueStyle, title))diff --git a/internal/cli/actions/actions_state.go b/internal/cli/actions/actions_state.goindex 5dda4976..d471e52d 100644--- a/internal/cli/actions/actions_state.go+++ b/internal/cli/actions/actions_state.go@@ -11,7 +11,7 @@ import ("github.com/spf13/cobra")-// StateList lists all saved state files.+// StateCurrent prints the current browser state.func StateCurrent(client *http.Client, base, token string, cmd *cobra.Command) {tabID, _ := cmd.Flags().GetString("tab")params := url.Values{}diff --git a/internal/cli/actions/actions_system.go b/internal/cli/actions/actions_system.goindex 3639ee37..51c734d0 100644--- a/internal/cli/actions/actions_system.go+++ b/internal/cli/actions/actions_system.go@@ -92,8 +92,6 @@ func Instances(client *http.Client, base, token string, cmd *cobra.Command) {}}-// --- profiles ----func Profiles(client *http.Client, base, token string, cmd *cobra.Command) {jsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {@@ -129,9 +127,6 @@ func decodeProfilesResponse(body []byte) ([]map[string]any, error) {return nil, fmt.Errorf("expected /profiles to return a JSON array")}-// --- internal helpers -----// getInstances fetches the list of running instancesfunc getInstances(client *http.Client, base, token string) []map[string]any {resp, err := http.NewRequest("GET", base+"/instances", nil)if err != nil {diff --git a/internal/cli/actions/actions_text.go b/internal/cli/actions/actions_text.goindex 8369a722..44eae254 100644--- a/internal/cli/actions/actions_text.go+++ b/internal/cli/actions/actions_text.go@@ -34,7 +34,7 @@ func Text(client *http.Client, base, token string, cmd *cobra.Command, args []stparams.Set("frameId", v)}- // Handle element selector - positional arg takes precedence over --selector flag+ // Positional arg takes precedence over --selector flag.selectorStr := ""if len(args) > 0 {selectorStr = args[0]@@ -50,20 +50,17 @@ func Text(client *http.Client, base, token string, cmd *cobra.Command, args []st}}- // Default to terse output (just text); --json for full responsejsonOutput, _ := cmd.Flags().GetBool("json")if jsonOutput {apiclient.DoGet(client, base, token, "/text", params)return}- // Terse mode: print just the text contentbody := apiclient.DoGetRaw(client, base, token, "/text", params)var result struct {Text string `json:"text"`}if err := json.Unmarshal(body, &result); err != nil {- // Not JSON, print rawoutput.Value(string(body))return}diff --git a/internal/cli/actions/actions_wait.go b/internal/cli/actions/actions_wait.goindex 25641d8a..98b6a939 100644--- a/internal/cli/actions/actions_wait.go+++ b/internal/cli/actions/actions_wait.go@@ -35,7 +35,7 @@ func Wait(client *http.Client, base, token string, args []string, cmd *cobra.Comcase fnFlag != "":body["fn"] = fnFlagcase len(args) > 0:- // Check if arg is a number (ms wait) or a selector+ // Bare arg is overloaded: a number means a ms wait, anything else a selector.if ms, err := strconv.Atoi(args[0]); err == nil {body["ms"] = ms} else {diff --git a/internal/cli/apiclient/client.go b/internal/cli/apiclient/client.goindex 95e3d701..1c5836ae 100644--- a/internal/cli/apiclient/client.go+++ b/internal/cli/apiclient/client.go@@ -263,7 +263,6 @@ func setClientHeaders(req *http.Request, token string) {}}-// handleAPIError parses and displays API error responses with hintsfunc handleAPIError(statusCode int, body []byte) {var errResp struct {Error string `json:"error"`@@ -272,19 +271,16 @@ func handleAPIError(statusCode int, body []byte) {}if err := json.Unmarshal(body, &errResp); err != nil {- // Fallback to raw output if not valid JSONfmt.Fprintf(os.Stderr, "Error %d: %s\n", statusCode, string(body))return}- // Print main errorif errResp.Error != "" {fmt.Fprintf(os.Stderr, "Error %d: %s\n", statusCode, errResp.Error)} else {fmt.Fprintf(os.Stderr, "Error %d: %s\n", statusCode, string(body))}- // Print hint and remedy if presentif errResp.Details != nil {if hint, ok := errResp.Details["hint"].(string); ok && hint != "" {fmt.Fprintf(os.Stderr, "\nπ‘ %s\n", hint)diff --git a/internal/cli/apiclient/diagnostics.go b/internal/cli/apiclient/diagnostics.goindex c94ee3a7..ef145068 100644--- a/internal/cli/apiclient/diagnostics.go+++ b/internal/cli/apiclient/diagnostics.go@@ -31,7 +31,6 @@ func CheckServerAndGuide(client *http.Client, base, token string) bool {fmt.Fprintln(os.Stderr, "Learn more: https://github.com/pinchtab/pinchtab#quick-start")return false}- // Other connection errorsfmt.Fprintf(os.Stderr, "Cannot connect to Pinchtab server: %v\n", err)return false}@@ -94,7 +93,6 @@ type refInfo struct {func extractRefs(data map[string]any) []refInfo {var refs []refInfo- // Handle different snapshot formatsif elements, ok := data["elements"].([]any); ok {for _, elem := range elements {if m, ok := elem.(map[string]any); ok {diff --git a/internal/cli/diagnostics_test.go b/internal/cli/diagnostics_test.goindex 9b350b7b..14ec4bdc 100644--- a/internal/cli/diagnostics_test.go+++ b/internal/cli/diagnostics_test.go@@ -8,7 +8,6 @@ import ()func TestCheckServerAndGuide(t *testing.T) {- // Test successful connectionm := newMockServer()m.response = `{"status":"ok"}`defer m.close()@@ -26,7 +25,6 @@ func TestCheckServerAndGuide(t *testing.T) {defer m2.close()client2 := m2.server.Client()- // Capture stderroldStderr := os.Stderrr, w, _ := os.Pipe()os.Stderr = wdiff --git a/internal/cli/styles.go b/internal/cli/styles.goindex db87b5bc..539a0d7b 100644--- a/internal/cli/styles.go+++ b/internal/cli/styles.go@@ -51,7 +51,6 @@ func Fatal(format string, args ...any) {}func SetupUsage(root *cobra.Command) {- // Custom template using the shared ANSI-ready styles.headerStyle := HeadingStyle.RendercmdStyle := CommandStyle.Renderdiff --git a/internal/config/browser_targets_test.go b/internal/config/browser_targets_test.goindex bb696335..5283bb88 100644--- a/internal/config/browser_targets_test.go+++ b/internal/config/browser_targets_test.go@@ -740,8 +740,6 @@ func TestResolveRequestedTarget_InvalidNameErrors(t *testing.T) {}}-// --- TargetsForBrowser ----func TestTargetsForBrowser_SingleMatch(t *testing.T) {cfg := &RuntimeConfig{Targets: BrowserTargetsConfig{@@ -1103,7 +1101,7 @@ func TestApplyTargetOverride_ClonesTargetProxyAndTargetsMap(t *testing.T) {}}-// --- Round-trip preservation of user-authored targets (H3 regression) ---+// Round-trip preservation of user-authored targets (H3 regression).func TestApplyFileConfig_ExplicitDefaultTargetDrivesDefaultBrowser(t *testing.T) {fc := &FileConfig{diff --git a/internal/config/browsers_config_test.go b/internal/config/browsers_config_test.goindex 22b84484..96a0fe67 100644--- a/internal/config/browsers_config_test.go+++ b/internal/config/browsers_config_test.go@@ -12,8 +12,6 @@ import (_ "github.com/pinchtab/pinchtab/internal/browsers/ghostchrome")-// --- Validation tests ----func TestValidateBrowsersBlock_EmptyBlock(t *testing.T) {fc := &FileConfig{}errs := ValidateFileConfig(fc)@@ -175,8 +173,6 @@ func TestValidateBrowsersBlock_EmptyConfigMap(t *testing.T) {}}-// --- Config loading tests ----func TestBrowsersBlock_DefaultsWhenAbsent(t *testing.T) {clearConfigEnvVars(t)dir := t.TempDir()diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 552301ae..f446a65e 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -40,7 +40,6 @@ func EmitDefaultConfigHint() {// Load returns the RuntimeConfig with precedence: env vars > config file > defaults.func Load() *RuntimeConfig {cfg := &RuntimeConfig{- // Server defaultsBind: "127.0.0.1",Port: defaultPort,InstancePortStart: 9868,@@ -49,7 +48,6 @@ func Load() *RuntimeConfig {StateDir: userConfigDir(),CookieSecure: nil,- // Security defaultsAllowEvaluate: false,AllowMacro: false,AllowScreencast: false,@@ -72,7 +70,6 @@ func Load() *RuntimeConfig {UploadMaxTotalBytes: DefaultUploadMaxTotalBytes,MaxRedirects: -1, // Unlimited by default; set to N to limit redirect hops- // Browser / instance defaultsHeadless: true,NoRestore: false,ProfileDir: "",@@ -99,13 +96,11 @@ func Load() *RuntimeConfig {TabCloseDelay: 5 * time.Minute,TabRestore: false,- // Timeout defaultsActionTimeout: 30 * time.Second,NavigateTimeout: 60 * time.Second,ShutdownTimeout: 10 * time.Second,WaitNavDelay: 1 * time.Second,- // Orchestrator defaultsStrategy: "always-on",AllocationPolicy: "fcfs",RestartMaxRestarts: 20,@@ -113,12 +108,10 @@ func Load() *RuntimeConfig {RestartMaxBackoff: 60 * time.Second,RestartStableAfter: 5 * time.Minute,- // Attach defaultsAttachEnabled: false,AttachAllowHosts: []string{"127.0.0.1", "localhost", "::1"},AttachAllowSchemes: []string{"ws", "wss", "http", "https"},- // IDPI defaultsIDPI: IDPIConfig{Enabled: true,StrictMode: true,@@ -127,7 +120,6 @@ func Load() *RuntimeConfig {ScanTimeoutSec: 5,},- // Observability defaultsObservability: ObservabilityConfig{Activity: ActivityConfig{Enabled: true,@@ -137,7 +129,6 @@ func Load() *RuntimeConfig {},},- // Session defaultsSessions: SessionsRuntimeConfig{Agent: AgentSessionRuntimeConfig{Enabled: true,@@ -155,7 +146,6 @@ func Load() *RuntimeConfig {},},- // AutoSolver defaults (disabled by default)AutoSolver: AutoSolverConfig{Enabled: false,AutoTrigger: true,@@ -171,7 +161,6 @@ func Load() *RuntimeConfig {}finalizeProfileConfig(cfg)- // Load config file (supports both legacy flat and new nested format)defaultConfigPath := filepath.Join(userConfigDir(), "config.json")configPath := envOr("PINCHTAB_CONFIG", defaultConfigPath)@@ -209,14 +198,12 @@ func Load() *RuntimeConfig {}}- // Validate file config and log warningsif errs := ValidateFileConfig(fc); len(errs) > 0 {for _, e := range errs {slog.Warn("config validation error", "path", configPath, "error", e)}}- // Apply file config (only if env var NOT set)applyFileConfig(cfg, fc)finalizeProfileConfig(cfg)@@ -287,7 +274,6 @@ func finalizeProfileConfig(cfg *RuntimeConfig) {}func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {- // Serverif fc.Server.Port != "" {cfg.Port = fc.Server.Port}@@ -313,7 +299,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.TrustProxyHeaders = *fc.Server.TrustProxyHeaders}cfg.CookieSecure = fc.Server.CookieSecure- // Securityif fc.Security.AllowEvaluate != nil {cfg.AllowEvaluate = *fc.Security.AllowEvaluate}@@ -431,7 +416,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.Sessions.Dashboard.RequireElevation = *fc.Sessions.Dashboard.RequireElevation}- // Agent sessionsif fc.Sessions.Agent.Enabled != nil {cfg.Sessions.Agent.Enabled = *fc.Sessions.Agent.Enabled}@@ -528,7 +512,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.BrowsersAvailable = []string{"chrome"}}- // Instance defaults β resolve headless bool into mode string.if fc.InstanceDefaults.Headless != nil && fc.InstanceDefaults.Mode == "" {if *fc.InstanceDefaults.Headless {fc.InstanceDefaults.Mode = "headless"@@ -598,7 +581,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.DialogAutoAccept = *fc.InstanceDefaults.DialogAutoAccept}- // Profilesif fc.Profiles.BaseDir != "" {cfg.ProfilesBaseDir = fc.Profiles.BaseDir}@@ -607,7 +589,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {}cfg.ProfileDir = ""- // Multi-instanceif fc.MultiInstance.Strategy != "" {cfg.Strategy = fc.MultiInstance.Strategy}@@ -620,7 +601,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.MultiInstance.InstancePortEnd != nil {cfg.InstancePortEnd = *fc.MultiInstance.InstancePortEnd}- // Restartif fc.MultiInstance.Restart.MaxRestarts != nil {cfg.RestartMaxRestarts = *fc.MultiInstance.Restart.MaxRestarts}@@ -634,7 +614,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.RestartStableAfter = time.Duration(*fc.MultiInstance.Restart.StableAfterSec) * time.Second}- // Attachif fc.Security.Attach.Enabled != nil {cfg.AttachEnabled = *fc.Security.Attach.Enabled}@@ -648,7 +627,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.AttachAllowSchemes = append([]string(nil), fc.Security.Attach.AllowSchemes...)}- // Timeoutsif fc.Timeouts.ActionSec > 0 {cfg.ActionTimeout = time.Duration(fc.Timeouts.ActionSec) * time.Second}@@ -662,7 +640,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.WaitNavDelay = time.Duration(fc.Timeouts.WaitNavMs) * time.Millisecond}- // Schedulerif fc.Scheduler.Enabled != nil {cfg.Scheduler.Enabled = *fc.Scheduler.Enabled}@@ -688,7 +665,6 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {cfg.Scheduler.WorkerCount = *fc.Scheduler.WorkerCount}- // AutoSolverif fc.AutoSolver.Enabled != nil {cfg.AutoSolver.Enabled = *fc.AutoSolver.Enabled}diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 37353127..3120f4bd 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -248,7 +248,6 @@ func TestConfigFileWithNestedValues(t *testing.T) {cfg := Load()- // Config file values should be usedif cfg.Port != "8888" {t.Errorf("config file Port = %v, want 8888", cfg.Port)}@@ -873,12 +872,10 @@ func TestFileConfigFromRuntime_UsesDefaultBrowser(t *testing.T) {fc := FileConfigFromRuntime(cfg)- // Provider should not be set on the output FileConfigif fc.Browser.Provider != "" {t.Errorf("FileConfigFromRuntime should not set browser.provider, got %q", fc.Browser.Provider)}- // browsers.default should be setif fc.Browsers.Default != "chrome" {t.Errorf("FileConfigFromRuntime Browsers.Default = %q, want chrome", fc.Browsers.Default)}diff --git a/internal/config/config_types.go b/internal/config/config_types.goindex 8ad0a18f..817ea21f 100644--- a/internal/config/config_types.go+++ b/internal/config/config_types.go@@ -7,7 +7,6 @@ const defaultPort = "9867"// RuntimeConfig holds all runtime settings used throughout the application.// This is the single source of truth for configuration at runtime.type RuntimeConfig struct {- // Server settingsBind stringPort stringInstancePortStart int // Starting port for instances (default 9868)@@ -19,7 +18,6 @@ type RuntimeConfig struct {VerboseStartup bool // Show full banner and slog output on server startBackgroundMarker string- // Security settingsAllowEvaluate boolAllowMacro boolAllowScreencast bool@@ -45,7 +43,6 @@ type RuntimeConfig struct {TrustedResolveCIDRs []string // CIDRs/IPs allowed when a navigation target resolves to non-public addressesTrustLoopbackProxy bool // when true, navigation responses with a loopback RemoteIPAddress (e.g. system HTTP/SOCKS proxy on 127.0.0.1) are not blocked; default false- // Browser/instance settingsHeadless boolHeadlessSet bool // true when explicitly set via config or flagDisableInProcessGPU bool // runtime-only: kill switch for --in-process-gpu when a user opted in via browser.extraFlags and the browser then crashed@@ -93,7 +90,6 @@ type RuntimeConfig struct {TabCloseDelay time.Duration // applies when TabLifecyclePolicy == "close_idle" (default 5m when enabled)TabRestore bool // restore previously open tabs from sessions.json on startup (default false)- // Timeout settingsActionTimeout time.DurationNavigateTimeout time.DurationShutdownTimeout time.Duration@@ -107,7 +103,6 @@ type RuntimeConfig struct {RestartMaxBackoff time.Duration // Maximum restart backoff cap (0 = strategy default)RestartStableAfter time.Duration // Stable runtime window that resets the restart counter (0 = strategy default)- // Attach settingsAttachEnabled boolAttachAllowHosts []stringAttachAllowSchemes []string@@ -117,13 +112,10 @@ type RuntimeConfig struct {RemoteCDPURL stringRemoteBrowserName string- // IDPI (Indirect Prompt Injection defense) settingsIDPI IDPIConfig- // Dialog settingsDialogAutoAccept bool- // Network monitoringNetworkBufferSize int // Per-tab network buffer size (default 100)RetainNetworkBodies bool // When true, opportunistically retain response bodies in the per-tab network bufferRetainNetworkBodyMaxBytes int // Max retained response-body bytes per entry when RetainNetworkBodies is enabled@@ -131,13 +123,10 @@ type RuntimeConfig struct {// Scheduler settings (dashboard mode only)Scheduler SchedulerConfig- // Observability settingsObservability ObservabilityConfig- // Session settingsSessions SessionsRuntimeConfig- // AutoSolver settingsAutoSolver AutoSolverConfig}diff --git a/internal/config/validate.go b/internal/config/validate.goindex b8e1817c..f83985b9 100644--- a/internal/config/validate.go+++ b/internal/config/validate.go@@ -27,7 +27,6 @@ func (e ValidationError) Error() string {func ValidateFileConfig(fc *FileConfig) []error {var errs []error- // Server validationif fc.Server.Port != "" {if err := validatePort(fc.Server.Port, "server.port"); err != nil {errs = append(errs, err)@@ -108,7 +107,6 @@ func ValidateFileConfig(fc *FileConfig) []error {})}- // Instance defaults validationif fc.InstanceDefaults.Headless != nil && fc.InstanceDefaults.Mode != "" {errs = append(errs, ValidationError{Field: "instanceDefaults.headless",@@ -170,7 +168,6 @@ func ValidateFileConfig(fc *FileConfig) []error {})}- // Multi-instance validationif fc.MultiInstance.Strategy != "" {if !isValidStrategy(fc.MultiInstance.Strategy) {errs = append(errs, ValidationError{@@ -188,7 +185,6 @@ func ValidateFileConfig(fc *FileConfig) []error {}}- // Attach validationfor _, scheme := range fc.Security.Attach.AllowSchemes {if !isValidAttachScheme(scheme) {errs = append(errs, ValidationError{@@ -202,7 +198,6 @@ func ValidateFileConfig(fc *FileConfig) []error {errs = append(errs, validateBrowserExtraFlags(fc.Browser.BrowserExtraFlags)...)}- // IDPI validationerrs = append(errs, validateIDPIConfig(fc.Security.IDPI, effectiveSecurityAllowedDomains(fc.Security))...)errs = append(errs, validateAllowedDomainList("security.downloadAllowedDomains", fc.Security.DownloadAllowedDomains)...)errs = append(errs, validateTrustedCIDRList("security.trustedProxyCIDRs", fc.Security.TrustedProxyCIDRs)...)@@ -220,7 +215,6 @@ func ValidateFileConfig(fc *FileConfig) []error {})}- // Timeouts validationif fc.Timeouts.ActionSec < 0 {errs = append(errs, ValidationError{Field: "timeouts.actionSec",@@ -346,7 +340,6 @@ func validatePort(port string, field string) error {}func validateBind(bind string, field string) error {- // Accept common bind addressesvalidBinds := map[string]bool{"127.0.0.1": true,"0.0.0.0": true,@@ -357,10 +350,7 @@ func validateBind(bind string, field string) error {if validBinds[bind] {return nil}- // Basic IP format check (not exhaustive, just sanity)- // If it contains a dot, assume it's an IPv4 attempt- // If it contains a colon, assume it's an IPv6 attempt- // This is intentionally loose β the OS will reject truly invalid addresses+ // Intentionally loose β the OS will reject truly invalid addresses.return nil}@@ -614,7 +604,6 @@ func ValidAttachSchemes() []string {// validateBrowsersBlock validates the top-level browsers configuration block.func validateBrowsersBlock(fc FileConfig) []error {bc := fc.Browsers- // Skip validation if entire block is empty/zeroif bc.Default == "" && len(bc.Available) == 0 && len(bc.Config) == 0 {return nil}@@ -630,14 +619,12 @@ func validateBrowsersBlock(fc FileConfig) []error {}}- // Validate each entry in availablefor i, name := range bc.Available {if _, ok := browsers.Get(strings.ToLower(strings.TrimSpace(name))); !ok {errs = append(errs, fmt.Errorf("browsers.available[%d]: unknown browser %q (known: %v)", i, name, browsers.IDs()))}}- // Validate default is in available (if available is explicitly set)if bc.Default != "" && len(bc.Available) > 0 {found := falsefor _, name := range bc.Available {diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex 3cf9ee30..8a97f912 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -610,7 +610,6 @@ func TestValidationError_Error(t *testing.T) {}func TestValidEnumValues(t *testing.T) {- // Test that the valid values match the validation functionsfor _, level := range ValidStealthLevels() {if !isValidStealthLevel(level) {t.Errorf("ValidStealthLevels contains %q but isValidStealthLevel returns false", level)@@ -642,8 +641,6 @@ func TestValidEnumValues(t *testing.T) {}}-// --- IDPI validation tests ----// TestValidateIDPIConfig_Disabled verifies that a disabled IDPI config produces// no errors regardless of what fields are set.func TestValidateIDPIConfig_Disabled(t *testing.T) {diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.goindex bee1e4a7..fd4105df 100644--- a/internal/dashboard/config_api_test.go+++ b/internal/dashboard/config_api_test.go@@ -540,7 +540,6 @@ func decodeConfigEnvelope(t *testing.T, w *httptest.ResponseRecorder) configEnve// name) and verifies they are all redacted. This test will fail if a new sensitive// field is added to FileConfig without updating redactToken().func TestRedactTokenCoversAllSensitiveFields(t *testing.T) {- // Populate all known sensitive fields with non-zero valuesfc := config.DefaultFileConfig()fc.Server.Token = "test-token"encKey := "test-encryption-key"@@ -582,7 +581,6 @@ func TestRedactTokenCoversAllSensitiveFields(t *testing.T) {t.Errorf("redactToken mutated source target proxy password")}- // Use reflection to find any sensitive fields that weren't redactedvar unredacted []stringfindSensitiveFields(reflect.ValueOf(redacted), "", &unredacted)@@ -618,7 +616,6 @@ func findSensitiveFields(v reflect.Value, path string, unredacted *[]string) {fieldVal := v.Field(i)- // Check if field name suggests it's sensitivenameLower := strings.ToLower(field.Name)isSensitive := falsefor _, pattern := range sensitivePatterns {@@ -632,7 +629,6 @@ func findSensitiveFields(v reflect.Value, path string, unredacted *[]string) {*unredacted = append(*unredacted, fieldPath)}- // Recurse into nested structsif fieldVal.Kind() == reflect.Struct || (fieldVal.Kind() == reflect.Ptr && fieldVal.Elem().Kind() == reflect.Struct) {findSensitiveFields(fieldVal, fieldPath, unredacted)}diff --git a/internal/dashboard/dashboard_test.go b/internal/dashboard/dashboard_test.goindex bac10733..0100c581 100644--- a/internal/dashboard/dashboard_test.go+++ b/internal/dashboard/dashboard_test.go@@ -104,7 +104,6 @@ func TestDashboardHandleSSE_StreamingDeadlineUnsupportedReturnsProblem(t *testinfunc TestDashboardBroadcastSystemEvent(t *testing.T) {d := NewDashboard(nil)- // Create a test handler and register itmux := http.NewServeMux()d.RegisterHandlers(mux)diff --git a/internal/handlers/action_execution.go b/internal/handlers/action_execution.goindex 64e3f7f4..89aa9daf 100644--- a/internal/handlers/action_execution.go+++ b/internal/handlers/action_execution.go@@ -26,7 +26,6 @@ func (h *Handlers) cacheActionIntent(tabID string, req bridge.ActionRequest) {return}desc := semantic.ElementDescriptor{Ref: req.Ref}- // Try to enrich from the current snapshot cache.if cache := h.Bridge.GetRefCache(tabID); cache != nil {for _, enriched := range semanticDescriptorsFromNodes(cache.Nodes) {if enriched.Ref == req.Ref {diff --git a/internal/handlers/actions.go b/internal/handlers/actions.goindex 245e5463..351f28d0 100644--- a/internal/handlers/actions.go+++ b/internal/handlers/actions.go@@ -171,7 +171,6 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {resolvedBrowser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.effectiveCfg, err := h.resolveEffectiveConfig(resolvedBrowser)if err != nil {var ambErr *config.AmbiguousBrowserError@@ -241,7 +240,6 @@ func (h *Handlers) HandleAction(w http.ResponseWriter, r *http.Request) {h.recordResolvedTab(r, resolvedTabID)w.Header().Set(activity.HeaderPTTabID, resolvedTabID)- // Allow custom timeout via query param (1-60 seconds)actionTimeout := effectiveCfg.ActionTimeoutif r.Method == http.MethodGet {if v := r.URL.Query().Get("timeout"); v != "" {@@ -497,9 +495,7 @@ func (h *Handlers) HandleTabActions(w http.ResponseWriter, r *http.Request) {h.HandleActions(w, wrapped)}-// handleActionsBatch processes a batch of actions (used by both single and batch endpoints)func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, req actionsRequest) {-// Browser resolution: use the first action's browser field as the request// browser, then fall through session > instance > global default > chrome.var requestBrowser string@@ -546,7 +542,6 @@ func (h *Handlers) handleActionsBatch(w http.ResponseWriter, r *http.Request, reresolvedBrowser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.effectiveCfg, err := h.resolveEffectiveConfig(resolvedBrowser)if err != nil {var ambErr *config.AmbiguousBrowserError@@ -848,7 +843,6 @@ func (h *Handlers) HandleMacro(w http.ResponseWriter, r *http.Request) {macroResolvedBrowser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.macroEffectiveCfg, err := h.resolveEffectiveConfig(macroResolvedBrowser)if err != nil {var ambErr *config.AmbiguousBrowserErrordiff --git a/internal/handlers/capture.go b/internal/handlers/capture.goindex a45d4b0e..e1e162ef 100644--- a/internal/handlers/capture.go+++ b/internal/handlers/capture.go@@ -87,7 +87,6 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {browser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.effectiveCfg, err := h.resolveEffectiveConfig(browser)if err != nil {var ambErr *config.AmbiguousBrowserError@@ -258,8 +257,6 @@ func (h *Handlers) HandleCapture(w http.ResponseWriter, r *http.Request) {DomEpoch: result.DomEpoch,})- // Image output: file (default) writes bytes to disk and returns a path;- // inline returns base64; raw returns the bytes as the response body.imageInfo := map[string]any{"format": result.ImageFormat,"bytes": len(result.ImageBytes),diff --git a/internal/handlers/credentials.go b/internal/handlers/credentials.goindex 15751205..affc03a8 100644--- a/internal/handlers/credentials.go+++ b/internal/handlers/credentials.go@@ -137,7 +137,6 @@ func (h *Handlers) setCredentials(w http.ResponseWriter, r *http.Request, req crdefer tCancel()if username == "" {- // Clear credentials: disable fetch domain and remove stored credentials.h.credentialStore.Delete(resolvedTabID)if proxyAuthConfigured(h.Config) {diff --git a/internal/handlers/dialog_test.go b/internal/handlers/dialog_test.goindex 0b996650..ccc252ae 100644--- a/internal/handlers/dialog_test.go+++ b/internal/handlers/dialog_test.go@@ -57,7 +57,6 @@ func TestHandleDialog_NoPendingDialog(t *testing.T) {req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))w := httptest.NewRecorder()h.HandleDialog(w, req)- // Should return 400 because no dialog is pendingif w.Code != 400 {t.Errorf("expected 400 for no pending dialog, got %d: %s", w.Code, w.Body.String())}@@ -68,7 +67,6 @@ func TestHandleDialog_AcceptAction(t *testing.T) {req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept"}`)))w := httptest.NewRecorder()h.HandleDialog(w, req)- // With no pending dialog, should get 400if w.Code != 400 {t.Errorf("expected 400, got %d", w.Code)}@@ -128,7 +126,6 @@ func TestHandleDialog_AcceptWithText(t *testing.T) {req := httptest.NewRequest("POST", "/dialog", bytes.NewReader([]byte(`{"action":"accept","text":"hello"}`)))w := httptest.NewRecorder()h.HandleDialog(w, req)- // No pending dialog, so 400if w.Code != 400 {t.Errorf("expected 400, got %d", w.Code)}@@ -141,7 +138,6 @@ func TestDialogManagerFromMockBridge(t *testing.T) {t.Fatal("expected non-nil DialogManager from mockBridge")}- // Verify it worksdm.SetPending("tab1", &bridge.DialogState{Type: "alert", Message: "test"})got := dm.GetPending("tab1")if got == nil || got.Type != "alert" {diff --git a/internal/handlers/evaluate.go b/internal/handlers/evaluate.goindex afc3fabb..47ff7386 100644--- a/internal/handlers/evaluate.go+++ b/internal/handlers/evaluate.go@@ -68,7 +68,6 @@ func (h *Handlers) HandleEvaluate(w http.ResponseWriter, r *http.Request) {opts := bridge.EvalOpts{AwaitPromise: req.AwaitPromise}if err := h.evalRuntime(tCtx, req.Expression, &result, opts); err != nil {errMsg := err.Error()- // Add helpful hints for common JavaScript errorsif strings.Contains(errMsg, "Cannot read properties of null") ||strings.Contains(errMsg, "Cannot read property") ||strings.Contains(errMsg, "null is not an object") {diff --git a/internal/handlers/find.go b/internal/handlers/find.goindex 4361be93..0dafc8c5 100644--- a/internal/handlers/find.go+++ b/internal/handlers/find.go@@ -95,7 +95,6 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {return}- // Try cached snapshot first; auto-fetch if not available.nodes := h.resolveSnapshotNodes(resolvedTabID)if len(nodes) == 0 {// Auto-refresh: take a fresh snapshot via CDP using the context@@ -110,7 +109,6 @@ func (h *Handlers) HandleFind(w http.ResponseWriter, r *http.Request) {}_ = bridge.EnrichA11yNodesWithDOMMetadata(ctxTab, nodes)- // Build descriptors from A11yNodes.descs := semanticDescriptorsFromNodes(nodes)// IDPI: scan AX-node text corpus and full page body text for injectiondiff --git a/internal/handlers/find_test.go b/internal/handlers/find_test.goindex c63ee649..2a05f3c2 100644--- a/internal/handlers/find_test.go+++ b/internal/handlers/find_test.go@@ -285,7 +285,6 @@ func TestHandleFind_ResponseMetrics(t *testing.T) {t.Fatalf("decode: %v", err)}- // Verify new Phase 2 response fields.if resp.ElementCount != 2 {t.Errorf("expected element_count=2, got %d", resp.ElementCount)}diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.goindex 61673e82..56d78bac 100644--- a/internal/handlers/handlers.go+++ b/internal/handlers/handlers.go@@ -114,9 +114,7 @@ func New(b bridge.BridgeAPI, cfg *config.RuntimeConfig, p bridge.ProfileService,return h.Bridge.Evaluate(ctx, expression, out, opts)}- // Clean up .tmp export files orphaned by a previous crash.go CleanupStaleTmpExports(cfg.StateDir)- // Clean up decoded base64 upload staging dirs left by older runs.go CleanupStaleUploads(cfg.StateDir)return h@@ -377,7 +375,6 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /cache/clear", h.HandleCacheClear)mux.HandleFunc("GET /cache/status", h.HandleCacheStatus)- // Storage (current origin only)mux.HandleFunc("GET /storage", h.HandleStorage)mux.HandleFunc("POST /storage", h.HandleStorage)mux.HandleFunc("DELETE /storage", h.HandleStorage)@@ -385,7 +382,6 @@ func (h *Handlers) RegisterRoutes(mux *http.ServeMux, doShutdown func()) {mux.HandleFunc("POST /tabs/{id}/storage", h.HandleTabStorageSet)mux.HandleFunc("DELETE /tabs/{id}/storage", h.HandleTabStorageDelete)- // State managementmux.HandleFunc("GET /state", h.HandleStateCurrent)mux.HandleFunc("GET /state/list", h.HandleStateList)mux.HandleFunc("GET /state/show", h.HandleStateShow)diff --git a/internal/handlers/handlers_test.go b/internal/handlers/handlers_test.goindex be873d0d..20392523 100644--- a/internal/handlers/handlers_test.go+++ b/internal/handlers/handlers_test.go@@ -457,7 +457,6 @@ func TestHandleNavigate(t *testing.T) {m := &mockBridge{}h := New(m, cfg, nil, nil, nil)- // 1. Valid POST requestbody := `{"url": "https://pinchtab.com"}`req := httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(body)))w := httptest.NewRecorder()@@ -468,7 +467,6 @@ func TestHandleNavigate(t *testing.T) {t.Errorf("unexpected status %d: %s", w.Code, w.Body.String())}- // 2. Valid GET request (ergonomic alias path style)req = httptest.NewRequest("GET", "/nav?url=https%3A%2F%2Fpinchtab.com", nil)w = httptest.NewRecorder()h.HandleNavigate(w, req)@@ -476,7 +474,6 @@ func TestHandleNavigate(t *testing.T) {t.Errorf("unexpected status for GET navigate %d: %s", w.Code, w.Body.String())}- // 3. Missing URLreq = httptest.NewRequest("POST", "/navigate", bytes.NewReader([]byte(`{}`)))w = httptest.NewRecorder()h.HandleNavigate(w, req)@@ -496,7 +493,6 @@ func TestHandleTab(t *testing.T) {m := &mockBridge{}h := New(m, &config.RuntimeConfig{}, nil, nil, nil)- // New Tabbody := `{"action": "new", "url": "about:blank"}`req := httptest.NewRequest("POST", "/tab", bytes.NewReader([]byte(body)))w := httptest.NewRecorder()diff --git a/internal/handlers/health_tabs_test.go b/internal/handlers/health_tabs_test.goindex 7dace0ec..ef2a2285 100644--- a/internal/handlers/health_tabs_test.go+++ b/internal/handlers/health_tabs_test.go@@ -47,7 +47,6 @@ func TestHandleHealth_NilBridge(t *testing.T) {// TestHandleHealth_BridgeListTargetsError verifies health returns 503 when ListTargets failsfunc TestHandleHealth_BridgeListTargetsError(t *testing.T) {- // Create a mock bridge that returns an errormockBridge := &MockBridge{targets: nil,listTargetsErr: "no CDP connection",@@ -83,7 +82,6 @@ func TestHandleHealth_BridgeListTargetsError(t *testing.T) {// TestHandleHealth_Success verifies health returns 200 when everything worksfunc TestHandleHealth_Success(t *testing.T) {- // Create a mock bridge that returns targetsmockBridge := &MockBridge{targets: []bridge.TabTarget{{TargetID: "target1", URL: "https://pinchtab.com", Title: "Example"},@@ -246,12 +244,10 @@ func TestHandleHealth_EnsureBrowserFailure(t *testing.T) {t.Errorf("expected status=error, got %v", status)}- // Verify ensureBrowser was actually calledif !mockBridge.ensureBrowserCalled {t.Error("expected ensureBrowser to be called before ListTargets")}- // Verify error message mentions browser initializationreason, ok := resp["reason"].(string)if !ok || !contains(reason, "browser") {t.Errorf("expected error reason mentioning browser, got %v", reason)@@ -265,7 +261,7 @@ func TestHandleHealth_EnsureBrowserSuccess(t *testing.T) {{TargetID: "target1", URL: "https://pinchtab.com", Title: "Example"},},ensureBrowserCalled: false,- ensureBrowserErr: "", // No error+ ensureBrowserErr: "",}h := &Handlers{@@ -282,7 +278,6 @@ func TestHandleHealth_EnsureBrowserSuccess(t *testing.T) {t.Errorf("expected 200, got %d", w.Code)}- // Verify ensureBrowser was calledif !mockBridge.ensureBrowserCalled {t.Error("expected ensureBrowser to be called before ListTargets")}@@ -297,7 +292,6 @@ func TestHandleHealth_EnsureBrowserSuccess(t *testing.T) {}}-// contains is a simple helper to check if a string contains a substringfunc contains(s, substr string) bool {for i := 0; i <= len(s)-len(substr); i++ {if s[i:i+len(substr)] == substr {diff --git a/internal/handlers/metrics.go b/internal/handlers/metrics.goindex c8a36065..12bdc502 100644--- a/internal/handlers/metrics.go+++ b/internal/handlers/metrics.go@@ -28,7 +28,6 @@ func SnapshotMetrics() map[string]any {bucketHosts := len(rateBuckets)rateMu.Unlock()- // Go runtime metricsvar memStats runtime.MemStatsruntime.ReadMemStats(&memStats)diff --git a/internal/handlers/navigation_browser_test.go b/internal/handlers/navigation_browser_test.goindex 6e5362b2..41c2d29f 100644--- a/internal/handlers/navigation_browser_test.go+++ b/internal/handlers/navigation_browser_test.go@@ -227,8 +227,6 @@ func TestHandleText_BrowserParam_Invalid_Returns400(t *testing.T) {}}-// --- Browser selection precedence tests ----//// These tests verify the handler-level browser resolution chain:// request param > session browser > instance browser > global default > chrome//@@ -545,8 +543,6 @@ func TestHandleNavigate_SameTabResult_NormalPathUnchanged(t *testing.T) {}}-// --- explicit-browser vs running-browser conflict (H6) ----func TestHandleNavigate_ExplicitBrowserConflictsWithRunning_409(t *testing.T) {m := &mockBridge{runningBrowser: config.BrowserChrome}h := New(m, &config.RuntimeConfig{@@ -648,8 +644,6 @@ func TestHandleNavigate_ExplicitBrowserNothingRunning_OK(t *testing.T) {}}-// --- deferred Chrome launch for static-first navigates (H1b) ----// A static-accept on a fresh navigate must never launch Chrome.func TestHandleNavigate_StaticFirstServesWithoutChromeLaunch(t *testing.T) {m := &mockBridge{diff --git a/internal/handlers/network.go b/internal/handlers/network.goindex 6cdbb876..056d2e39 100644--- a/internal/handlers/network.go+++ b/internal/handlers/network.go@@ -181,7 +181,6 @@ func (h *Handlers) HandleNetwork(w http.ResponseWriter, r *http.Request) {bufferSize := parseBufferSize(r)- // Lazily start capture if not already active for this tabbuf := nm.GetBuffer(resolvedTabID)if buf == nil {if err := nm.StartCaptureWithSize(tabCtx, resolvedTabID, bufferSize); err != nil {@@ -276,7 +275,6 @@ func (h *Handlers) HandleNetworkByID(w http.ResponseWriter, r *http.Request) {"tabId": resolvedTabID,}- // Optionally include response bodyif r.URL.Query().Get("body") == "true" && entry.Finished && !entry.Failed {bodyMode := parseNetworkBodyMode(r)if bodyMode == networkBodyModeRetainedPreferred && entry.BodyPending {@@ -395,7 +393,6 @@ func (h *Handlers) HandleNetworkStream(w http.ResponseWriter, r *http.Request) {bufferSize := parseBufferSize(r)- // Ensure capture is activebuf := nm.GetBuffer(resolvedTabID)if buf == nil {if err := nm.StartCaptureWithSize(tabCtx, resolvedTabID, bufferSize); err != nil {@@ -488,7 +485,6 @@ func (h *Handlers) HandleTabNetworkByID(w http.ResponseWriter, r *http.Request)u := *r.URLu.RawQuery = q.Encode()req.URL = &u- // Set the requestId path value by creating a new request with the pathh.HandleNetworkByID(w, req)}diff --git a/internal/handlers/network_export.go b/internal/handlers/network_export.goindex d06ea58a..644fc4f1 100644--- a/internal/handlers/network_export.go+++ b/internal/handlers/network_export.go@@ -143,7 +143,6 @@ func (h *Handlers) HandleNetworkExport(w http.ResponseWriter, r *http.Request) {redactHeaders := r.URL.Query().Get("redact") != "false"output := r.URL.Query().Get("output")- // Timeout + client disconnect for body fetches (#4, #5)fetchCtx, fetchCancel := context.WithTimeout(tabCtx, h.Config.ActionTimeout)defer fetchCancel()go httpx.CancelOnClientDone(r.Context(), fetchCancel)@@ -193,7 +192,6 @@ func (h *Handlers) HandleNetworkExport(w http.ResponseWriter, r *http.Request) {return}- // Stream to responsew.Header().Set("Content-Type", enc.ContentType())if err := enc.Start(w); err != nil {return@@ -219,7 +217,6 @@ func (h *Handlers) writeExportFile(userPath = fmt.Sprintf("network-%s%s", ts, enc.FileExtension())}- // Path safety: use SafeCreatePath + containment check (#1)exportDir := filepath.Join(h.Config.StateDir, "exports")if err := os.MkdirAll(exportDir, 0750); err != nil {return fmt.Errorf("create dir: %w", err)diff --git a/internal/handlers/network_export_stream.go b/internal/handlers/network_export_stream.goindex aeac3062..42fe2401 100644--- a/internal/handlers/network_export_stream.go+++ b/internal/handlers/network_export_stream.go@@ -96,7 +96,6 @@ func (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.RequredactHeaders := r.URL.Query().Get("redact") != "false"filter := parseNetworkFilter(r)- // Path safety (#1)exportDir := filepath.Join(h.Config.StateDir, "exports")if err := os.MkdirAll(exportDir, 0750); err != nil {httpx.Error(w, 500, fmt.Errorf("create dir: %w", err))@@ -116,7 +115,6 @@ func (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.Requreturn}- // Write to temp file, rename on finish (#8)tmpPath := absPath + ".tmp"f, err := os.OpenFile(tmpPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)if err != nil {@@ -132,7 +130,6 @@ func (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.Requreturn}- // Semaphore to throttle concurrent body fetches in streaming mode.streamBodySem := make(chan struct{}, bodyFetchConcurrency)subID, ch := buf.Subscribe()@@ -168,7 +165,6 @@ func (h *Handlers) HandleNetworkExportStream(w http.ResponseWriter, r *http.RequfinalizeOnce.Do(func() {_ = enc.Finish()if err := f.Close(); err == nil {- // Atomic rename on success (#8)if count > 0 {_ = os.Rename(tmpPath, absPath)} else {diff --git a/internal/handlers/network_test.go b/internal/handlers/network_test.goindex 90cbc7a8..81b1d612 100644--- a/internal/handlers/network_test.go+++ b/internal/handlers/network_test.go@@ -526,7 +526,6 @@ func TestHandleNetworkClear_All(t *testing.T) {t.Errorf("expected cleared=true, all=true, got cleared=%v, all=%v", resp.Cleared, resp.All)}- // Verify buffers are emptybuf1 := nm.GetBuffer("tab1")buf2 := nm.GetBuffer("tab2")if buf1 != nil && buf1.Len() != 0 {diff --git a/internal/handlers/openapi.go b/internal/handlers/openapi.goindex da026894..12d3d529 100644--- a/internal/handlers/openapi.go+++ b/internal/handlers/openapi.go@@ -154,7 +154,6 @@ func (h *Handlers) HandleOpenAPI(w http.ResponseWriter, _ *http.Request) {"x-pinchtab-enabled": security["stateExport"].Enabled,},},- // CapStateExport-gated endpoints"/state": map[string]any{"get": map[string]any{"summary": "Read current browser state for a tab","description": security["stateExport"].Message,diff --git a/internal/handlers/pdf.go b/internal/handlers/pdf.goindex 4d0caf9e..c777dab0 100644--- a/internal/handlers/pdf.go+++ b/internal/handlers/pdf.go@@ -81,7 +81,6 @@ func (h *Handlers) HandlePDF(w http.ResponseWriter, r *http.Request) {defer tCancel()go httpx.CancelOnClientDone(r.Context(), tCancel)- // Parse PDF parameters from PrintToPDFParamslandscape := r.URL.Query().Get("landscape") == "true"preferCSSPageSize := r.URL.Query().Get("preferCSSPageSize") == "true"displayHeaderFooter := r.URL.Query().Get("displayHeaderFooter") == "true"diff --git a/internal/handlers/security_parity_test.go b/internal/handlers/security_parity_test.goindex f7b9bb89..48006ee0 100644--- a/internal/handlers/security_parity_test.go+++ b/internal/handlers/security_parity_test.go@@ -45,10 +45,6 @@ func navigateProviders() []providerSetup {}}-// =========================================================================-// Navigation security parity: /navigate endpoint-// =========================================================================-func TestSecurityParity_Navigate_DisallowedDomainBlocked(t *testing.T) {// Domain check fires before DNS resolution and before any Browser call,// so it works identically across all four providers.diff --git a/internal/handlers/snapshot.go b/internal/handlers/snapshot.goindex 7248f0b8..1b4c4318 100644--- a/internal/handlers/snapshot.go+++ b/internal/handlers/snapshot.go@@ -101,7 +101,6 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {browser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.effectiveCfg, err := h.resolveEffectiveConfig(browser)if err != nil {var ambErr *config.AmbiguousBrowserError@@ -225,7 +224,6 @@ func (h *Handlers) HandleSnapshot(w http.ResponseWriter, r *http.Request) {}}- // Check if scoped snapshot returned 0 nodes but element exists in DOMvar scopedEmptyHint stringif len(flat) == 0 && selector != "" && scopeNodeID != 0 {var elemInfo stringdiff --git a/internal/handlers/solver.go b/internal/handlers/solver.goindex 72bc98cb..e012d33a 100644--- a/internal/handlers/solver.go+++ b/internal/handlers/solver.go@@ -59,12 +59,10 @@ func (h *Handlers) HandleSolve(w http.ResponseWriter, r *http.Request) {return}- // If a solver name is provided in the path, use it.if name := r.PathValue("name"); name != "" {req.Solver = name}- // Validate solver name early.if req.Solver != "" {if !h.isAvailableAutoSolver(req.Solver) {httpx.ErrorCode(w, 400, "unknown_solver",diff --git a/internal/handlers/storage.go b/internal/handlers/storage.goindex f1440a17..63c98e27 100644--- a/internal/handlers/storage.go+++ b/internal/handlers/storage.go@@ -103,7 +103,6 @@ type storageSetRequest struct {Type string `json:"type"`}-// handleStorageSet sets a single storage item.func (h *Handlers) handleStorageSet(w http.ResponseWriter, r *http.Request) {if !h.ensureStateExportEnabled(w) {return@@ -208,7 +207,6 @@ func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {}}- // Defaults for empty body/missing typeif req.Type == "" {req.Type = "all"}@@ -217,7 +215,6 @@ func (h *Handlers) handleStorageDelete(w http.ResponseWriter, r *http.Request) {httpx.Error(w, 400, fmt.Errorf("type must be 'local', 'session', or 'all'"))return}- // key is not compatible with type=allif req.Type == "all" && req.Key != "" {httpx.Error(w, 400, fmt.Errorf("key cannot be used with type=all; omit key to clear both storages"))return@@ -316,7 +313,6 @@ func buildStorageGetScript(storageType, key string) string {}}- // No key specified: return all itemsgetAllScript := func(storageObj string) string {return fmt.Sprintf(`(function() {@@ -374,7 +370,6 @@ func buildStorageGetScript(storageType, key string) string {// or clears the entire storage. Supports type local, session, or all.// Returns a JSON string with success/origin fields.func buildStorageDeleteScript(storageType, key string) string {- // type=all: clear both localStorage and sessionStorageif storageType == "all" {return `(function() {diff --git a/internal/handlers/text.go b/internal/handlers/text.goindex 49c8b726..a141af19 100644--- a/internal/handlers/text.go+++ b/internal/handlers/text.go@@ -60,7 +60,6 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {browser = config.BrowserChrome}- // Resolve the effective config with target-specific overrides merged in.effectiveCfg, err := h.resolveEffectiveConfig(browser)if err != nil {var ambErr *config.AmbiguousBrowserError@@ -134,7 +133,6 @@ func (h *Handlers) HandleText(w http.ResponseWriter, r *http.Request) {// partial results when text is called before the page finishes loading.h.waitForReadyState(tCtx)- // Handle element selector - extract text from specific element instead of full pageselectorParam := r.URL.Query().Get("selector")refParam := r.URL.Query().Get("ref")if selectorParam != "" || refParam != "" {@@ -284,7 +282,6 @@ func (h *Handlers) evalTextInFrame(ctx context.Context, script, frameID string)return text, nil}-// extractElementText extracts innerText from a specific element by selector or ref.func (h *Handlers) extractElementText(ctx context.Context, tabID, selector, ref string) (string, error) {var text stringdiff --git a/internal/handlers/upload.go b/internal/handlers/upload.goindex eaaef432..d942938c 100644--- a/internal/handlers/upload.go+++ b/internal/handlers/upload.go@@ -302,7 +302,6 @@ func decodeFileData(input string) ([]byte, string, error) {return nil, "", fmt.Errorf("invalid data URL")}b64 = parts[1]- // Extract mime for extension.meta := strings.TrimPrefix(parts[0], "data:")mime := strings.SplitN(meta, ";", 2)[0]ext = mimeToExt(mime)@@ -312,7 +311,6 @@ func decodeFileData(input string) ([]byte, string, error) {data, err := base64.StdEncoding.DecodeString(b64)if err != nil {- // Try URL-safe encoding.data, err = base64.URLEncoding.DecodeString(b64)if err != nil {return nil, "", fmt.Errorf("base64 decode: %w", err)diff --git a/internal/handlers/wait.go b/internal/handlers/wait.goindex e4f938b6..98e56859 100644--- a/internal/handlers/wait.go+++ b/internal/handlers/wait.go@@ -210,7 +210,6 @@ func (h *Handlers) handleWaitCore(w http.ResponseWriter, r *http.Request, req wareturn}- // All other modes need a browser tab.ctx, resolvedTabID, err := h.tabContext(r, req.TabID)if err != nil {WriteTabContextError(w, err, 404)@@ -379,7 +378,6 @@ func buildSelectorJS(sel, state string) (string, string) {// buildURLMatchJS builds a JS expression that checks if the current URL matches a glob pattern.func buildURLMatchJS(pattern string) string {// Convert glob to regex: ** β .*, * β [^/]*, ? β .- // For simplicity, we use a JS function that does basic glob matching.return fmt.Sprintf(`(function(){var p = %s;var u = window.location.href;@@ -393,7 +391,6 @@ func buildURLMatchJS(pattern string) string {})()`, jsonStr(pattern))}-// jsonStr returns a JSON-encoded string (with quotes).func jsonStr(s string) string {b, _ := json.Marshal(s)return string(b)diff --git a/internal/handlers/wait_test.go b/internal/handlers/wait_test.goindex c4bcc2a6..c4b17131 100644--- a/internal/handlers/wait_test.go+++ b/internal/handlers/wait_test.go@@ -11,8 +11,6 @@ import ("github.com/pinchtab/pinchtab/internal/config")-// ββ Request validation tests βββββββββββββββββββββββββββββββββββββββββββ-func TestHandleWait_InvalidJSON(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`not json`)))@@ -33,8 +31,6 @@ func TestHandleWait_EmptyBody(t *testing.T) {}}-// ββ Fixed duration (ms) tests ββββββββββββββββββββββββββββββββββββββββββ-func TestHandleWait_FixedMs(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"ms": 50}`)))@@ -106,8 +102,6 @@ func TestHandleWait_FixedMsClampedAt30s(t *testing.T) {}}-// ββ Timeout clamping tests βββββββββββββββββββββββββββββββββββββββββββββ-func TestWaitRequest_TimeoutClamping(t *testing.T) {tests := []struct {name string@@ -131,8 +125,6 @@ func TestWaitRequest_TimeoutClamping(t *testing.T) {}}-// ββ Mode detection tests βββββββββββββββββββββββββββββββββββββββββββββββ-func TestWaitRequest_Mode(t *testing.T) {tests := []struct {name string@@ -157,8 +149,6 @@ func TestWaitRequest_Mode(t *testing.T) {}}-// ββ Selector wait (needs browser β tests validation only) ββββββββββββββ-func TestHandleWait_SelectorNoTab(t *testing.T) {h := New(&mockBridge{failTab: true}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/wait", bytes.NewReader([]byte(`{"selector":"#results"}`)))@@ -305,8 +295,6 @@ func TestHandleWait_InvalidLoadState(t *testing.T) {}}-// ββ Tab-scoped wait tests ββββββββββββββββββββββββββββββββββββββββββββββ-func TestHandleTabWait_MissingTabID(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)req := httptest.NewRequest("POST", "/tabs//wait", bytes.NewReader([]byte(`{"ms":50}`)))@@ -346,8 +334,6 @@ func TestHandleTabWait_FixedMs(t *testing.T) {}}-// ββ Response format tests ββββββββββββββββββββββββββββββββββββββββββββββ-func TestWaitResponse_Format(t *testing.T) {resp := waitResponse{Waited: true,@@ -398,8 +384,6 @@ func TestWaitResponse_ErrorFormat(t *testing.T) {}}-// ββ JS builder tests βββββββββββββββββββββββββββββββββββββββββββββββββββ-func TestBuildSelectorJS_CSS(t *testing.T) {js, match := buildSelectorJS("#results", "")if js == "" {@@ -474,8 +458,6 @@ func TestBuildURLMatchJS(t *testing.T) {}}-// ββ Route registration test ββββββββββββββββββββββββββββββββββββββββββββ-func TestWaitRouteRegistered(t *testing.T) {h := New(&mockBridge{}, &config.RuntimeConfig{}, nil, nil, nil)mux := httptest.NewServer(nil).Config.Handler@@ -489,8 +471,6 @@ func TestWaitRouteRegistered(t *testing.T) {}}-// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-func intPtr(v int) *int {return &v}diff --git a/internal/httpx/httpx_test.go b/internal/httpx/httpx_test.goindex 9f0c61fe..a11a06ff 100644--- a/internal/httpx/httpx_test.go+++ b/internal/httpx/httpx_test.go@@ -21,7 +21,6 @@ func TestStatusWriter(t *testing.T) {t.Errorf("expected recorded code 404, got %d", w.Code)}- // Test default codew2 := httptest.NewRecorder()sw2 := &StatusWriter{ResponseWriter: w2, Code: 200}_, _ = sw2.Write([]byte("ok"))diff --git a/internal/httpx/safepath.go b/internal/httpx/safepath.goindex 126cb355..c9418d96 100644--- a/internal/httpx/safepath.go+++ b/internal/httpx/safepath.go@@ -67,7 +67,6 @@ func safeLexicalPath(base, userPath string) (string, string, error) {return "", "", fmt.Errorf("path %q contains invalid components", userPath)}- // Join, clean, resolve to absolute.joined := filepath.Join(absBase, userPath)absPath, err := filepath.Abs(joined)if err != nil {diff --git a/internal/httpx/safepath_test.go b/internal/httpx/safepath_test.goindex 67031b90..e863391a 100644--- a/internal/httpx/safepath_test.go+++ b/internal/httpx/safepath_test.go@@ -38,7 +38,6 @@ func TestSafePath(t *testing.T) {// TestSafePath_TempDir uses real temp directories so paths are valid on every OS// and never rely on hard-coded drive letters or mount points.func TestSafePath_TempDir(t *testing.T) {- // Create a real base directory with a nested child.base := t.TempDir()child := filepath.Join(base, "sub", "dir")if err := os.MkdirAll(child, 0o755); err != nil {diff --git a/internal/idpi/idpi_test.go b/internal/idpi/idpi_test.goindex 940d6a71..569dfee1 100644--- a/internal/idpi/idpi_test.go+++ b/internal/idpi/idpi_test.go@@ -7,8 +7,6 @@ import ("github.com/pinchtab/pinchtab/internal/config")-// βββ helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-func enabledCfg(extra ...func(*config.IDPIConfig)) config.IDPIConfig {cfg := config.IDPIConfig{Enabled: true}for _, fn := range extra {@@ -21,8 +19,6 @@ func allowedDomains(domains ...string) []string {return append([]string(nil), domains...)}-// βββ CheckDomain ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-func TestCheckDomain_DisabledAlwaysPasses(t *testing.T) {cfg := config.IDPIConfig{Enabled: false}if r := CheckDomain("https://evil.com", cfg, allowedDomains("example.com")); r.Threat {@@ -208,9 +204,6 @@ func TestDomainAllowed(t *testing.T) {}}-// βββ ScanContent ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--// --- Guard wiring tests (config flags + WrapContent format) ---// Content scanning correctness is tested in idpishield's own test suite.func newGuard(cfg config.IDPIConfig, allowedDomains ...string) Guard {diff --git a/internal/instance/bridge_client.go b/internal/instance/bridge_client.goindex 4e5eb531..d172d882 100644--- a/internal/instance/bridge_client.go+++ b/internal/instance/bridge_client.go@@ -76,7 +76,6 @@ func (bc *BridgeClient) CreateTab(ctx context.Context, port, url string) (stringreturn "", fmt.Errorf("decode create tab response: %w", err)}- // If URL provided and not about:blank, navigate to itif url != "" && url != "about:blank" {if err := bc.NavigateTab(ctx, port, result.TabID, url); err != nil {return "", fmt.Errorf("navigate after create: %w", err)@@ -149,7 +148,6 @@ func (bc *BridgeClient) SnapshotTab(ctx context.Context, port, tabID string) {// injecting the tabId into the JSON request body so the bridge knows which tab// to operate on. Used for endpoints that don't support /tabs/{id}/... paths.func (bc *BridgeClient) ProxyWithTabID(w http.ResponseWriter, r *http.Request, port, tabID, path string) {- // Read original body and inject tabId.var body map[string]anyif r.Body != nil {if err := json.NewDecoder(r.Body).Decode(&body); err != nil {diff --git a/internal/instance/instance_test.go b/internal/instance/instance_test.goindex 4402c651..2b65cc5b 100644--- a/internal/instance/instance_test.go+++ b/internal/instance/instance_test.go@@ -9,8 +9,6 @@ import ("github.com/pinchtab/pinchtab/internal/instance/allocation")-// --- Test doubles ----type mockLauncher struct {instances map[string]*bridgepkg.InstancenextID int@@ -73,8 +71,6 @@ func (f *mockFetcher) AddTabForURL(instanceURL, tabID, url string) {})}-// --- Repository tests ----func TestRepository_LaunchAndGet(t *testing.T) {launcher := newMockLauncher()repo := instance.NewRepository(launcher)@@ -119,7 +115,6 @@ func TestRepository_Running_FiltersNonRunning(t *testing.T) {inst1, _ := repo.Launch("prof1", "9868", true)_, _ = repo.Launch("prof2", "9869", true)- // Manually mark inst1 as stopped via Add.stopped := *inst1stopped.Status = "stopped"repo.Add(&stopped)@@ -130,8 +125,6 @@ func TestRepository_Running_FiltersNonRunning(t *testing.T) {}}-// --- Locator tests ----func TestLocator_CacheHit(t *testing.T) {launcher := newMockLauncher()fetcher := newMockFetcher()@@ -140,7 +133,6 @@ func TestLocator_CacheHit(t *testing.T) {inst, _ := repo.Launch("default", "9868", true)- // Pre-register in cache.locator.Register("tab_abc", inst.ID)found, err := locator.FindInstanceByTabID("tab_abc")@@ -160,7 +152,6 @@ func TestLocator_CacheMiss_QueriesBridges(t *testing.T) {inst, _ := repo.Launch("default", "9868", true)- // Set up fetcher to return tabs for this instance.fetcher.AddTab("9868", "tab_xyz", "https://pinchtab.com")found, err := locator.FindInstanceByTabID("tab_xyz")@@ -171,7 +162,6 @@ func TestLocator_CacheMiss_QueriesBridges(t *testing.T) {t.Errorf("expected %s, got %s", inst.ID, found.ID)}- // Should now be cached.if locator.CacheSize() != 1 {t.Errorf("expected cache size 1, got %d", locator.CacheSize())}@@ -267,8 +257,6 @@ func TestLocator_StaleCache_InstanceGone(t *testing.T) {}}-// --- Allocator tests ----func TestAllocator_FCFS(t *testing.T) {launcher := newMockLauncher()repo := instance.NewRepository(launcher)@@ -316,32 +304,26 @@ func TestAllocator_NoRunningInstances(t *testing.T) {}}-// --- Manager facade tests ----func TestManager_DelegatesToComponents(t *testing.T) {launcher := newMockLauncher()fetcher := newMockFetcher()mgr := instance.NewManager(launcher, fetcher)- // Launch via manager β delegates to repo.inst, err := mgr.Launch("default", "9868", true)if err != nil {t.Fatal(err)}- // Get via manager β delegates to repo.got, ok := mgr.Get(inst.ID)if !ok || got.ID != inst.ID {t.Error("Get should delegate to repo")}- // List via manager β delegates to repo.list := mgr.List()if len(list) != 1 {t.Errorf("expected 1 instance, got %d", len(list))}- // RegisterTab + FindInstanceByTabID β delegates to locator.mgr.RegisterTab("tab_abc", inst.ID)found, err := mgr.FindInstanceByTabID("tab_abc")if err != nil {@@ -351,7 +333,6 @@ func TestManager_DelegatesToComponents(t *testing.T) {t.Error("FindInstanceByTabID should delegate to locator")}- // Allocate β delegates to allocator.alloc, err := mgr.Allocate()if err != nil {t.Fatal(err)@@ -360,7 +341,6 @@ func TestManager_DelegatesToComponents(t *testing.T) {t.Error("Allocate should delegate to allocator")}- // Stop β delegates to repo + invalidates cache.if err := mgr.Stop(inst.ID); err != nil {t.Fatal(err)}@@ -380,7 +360,6 @@ func TestManager_StopInvalidatesTabCache(t *testing.T) {_ = mgr.Stop(inst.ID)- // Tabs should be invalidated._, err := mgr.FindInstanceByTabID("tab_1")if err == nil {t.Error("expected error: tab cache should be invalidated after stop")diff --git a/internal/instance/locator.go b/internal/instance/locator.goindex f747b12a..a0eca3ee 100644--- a/internal/instance/locator.go+++ b/internal/instance/locator.go@@ -31,7 +31,6 @@ func NewLocator(repo *Repository, fetcher TabFetcher) *Locator {// FindInstanceByTabID returns the instance that owns the given tab.// Fast path: cache hit (O(1)). Slow path: queries all bridges.func (l *Locator) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {- // Fast path: check cache.l.mu.RLock()instID, ok := l.cache[tabID]l.mu.RUnlock()@@ -45,7 +44,6 @@ func (l *Locator) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {l.Invalidate(tabID)}- // Slow path: query all running bridges.running := l.repo.Running()for _, inst := range running {url := inst.URLdiff --git a/internal/instance/manager.go b/internal/instance/manager.goindex 2d87e60b..1de766d1 100644--- a/internal/instance/manager.go+++ b/internal/instance/manager.go@@ -27,8 +27,6 @@ func NewManager(launcher InstanceLauncher, fetcher TabFetcher) *Manager {}}-// --- Lifecycle (delegates to Repository) ----// Launch starts a new instance.func (m *Manager) Launch(name, port string, headless bool) (*bridge.Instance, error) {return m.Repo.Launch(name, port, headless)@@ -55,8 +53,6 @@ func (m *Manager) Running() []bridge.Instance {return m.Repo.Running()}-// --- Discovery (delegates to Locator) ----// FindInstanceByTabID returns the instance that owns a tab.func (m *Manager) FindInstanceByTabID(tabID string) (*bridge.Instance, error) {return m.Locator.FindInstanceByTabID(tabID)@@ -72,8 +68,6 @@ func (m *Manager) InvalidateTab(tabID string) {m.Locator.Invalidate(tabID)}-// --- Allocation (delegates to Allocator) ----// Allocate selects a running instance using the configured policy.func (m *Manager) Allocate() (*bridge.Instance, error) {return m.Allocator.Allocate()diff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.goindex dd697057..0307f649 100644--- a/internal/mcp/client_test.go+++ b/internal/mcp/client_test.go@@ -124,7 +124,7 @@ func TestClientPostNilPayload(t *testing.T) {}func TestClientPostStreamReturnsReadableBody(t *testing.T) {- payload := strings.Repeat("X", 64*1024) // 64 KB β exceeds the 10 MB LimitReader test boundary+ payload := strings.Repeat("X", 64*1024)srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.WriteHeader(200)_, _ = io.WriteString(w, payload)diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.goindex 8ba40e54..a284dba0 100644--- a/internal/mcp/handlers.go+++ b/internal/mcp/handlers.go@@ -9,10 +9,8 @@ import (// maxWaitMS caps wait/timeout durations for safety.const maxWaitMS = 30_000-// handlerMap returns a nameβhandler map for all PinchTab MCP tools.func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {return map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error){- // Navigation"pinchtab_navigate": handleNavigate(c),"pinchtab_snapshot": handleSnapshot(c),"pinchtab_frame": handleFrame(c),@@ -20,7 +18,6 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)"pinchtab_capture": handleCapture(c),"pinchtab_get_text": handleGetText(c),- // Interaction"pinchtab_click": handleAction(c, "click"),"pinchtab_type": handleAction(c, "type"),"pinchtab_press": handleAction(c, "press"),@@ -31,25 +28,21 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)"pinchtab_scroll_into_view": handleAction(c, "scrollintoview"),"pinchtab_fill": handleAction(c, "fill"),- // Keyboard (no selector)"pinchtab_keyboard_type": handleKeyboardText(c, "keyboard-type"),"pinchtab_keyboard_inserttext": handleKeyboardText(c, "keyboard-inserttext"),"pinchtab_keydown": handleKeyboardKey(c, "keydown"),"pinchtab_keyup": handleKeyboardKey(c, "keyup"),- // Content"pinchtab_eval": handleEval(c),"pinchtab_pdf": handlePDF(c),"pinchtab_find": handleFind(c),- // Tab management"pinchtab_list_tabs": handleListTabs(c),"pinchtab_close_tab": handleCloseTab(c),"pinchtab_health": handleHealth(c),"pinchtab_cookies": handleCookies(c),"pinchtab_connect_profile": handleConnectProfile(c),- // Utility"pinchtab_wait": handleWait(),"pinchtab_wait_for_selector": handleWaitForSelector(c),"pinchtab_wait_for_text": handleWaitForText(c),@@ -57,19 +50,16 @@ func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest)"pinchtab_wait_for_load": handleWaitForLoad(c),"pinchtab_wait_for_function": handleWaitForFunction(c),- // Network monitoring"pinchtab_network": handleNetwork(c),"pinchtab_network_detail": handleNetworkDetail(c),"pinchtab_network_clear": handleNetworkClear(c),"pinchtab_network_route": handleNetworkRoute(c),"pinchtab_network_unroute": handleNetworkUnroute(c),- // Recording"pinchtab_record_start": handleRecordStart(c),"pinchtab_record_stop": handleRecordStop(c),"pinchtab_record_status": handleRecordStatus(c),- // Dialog"pinchtab_dialog": handleDialog(c),}}diff --git a/internal/mcp/handlers_interaction.go b/internal/mcp/handlers_interaction.goindex fe3ed49e..ae960739 100644--- a/internal/mcp/handlers_interaction.go+++ b/internal/mcp/handlers_interaction.go@@ -180,7 +180,6 @@ func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequreturn resultFromBytes(body, code)}- // If snap=true, append interactive compact snapshotsnapSupportedKinds := map[string]bool{"click": true, "fill": true, "select": true}if snapSupportedKinds[kind] {if snap, ok := optBool(r, "snap"); ok && snap {diff --git a/internal/mcp/handlers_navigation.go b/internal/mcp/handlers_navigation.goindex 6f88969a..e42feffa 100644--- a/internal/mcp/handlers_navigation.go+++ b/internal/mcp/handlers_navigation.go@@ -37,7 +37,6 @@ func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.return resultFromBytes(body, code)}- // If snap=true, append interactive compact snapshotif snap, ok := optBool(r, "snap"); ok && snap {q := url.Values{}q.Set("filter", "interactive")diff --git a/internal/mcp/handlers_record.go b/internal/mcp/handlers_record.goindex 2a6ab2b2..6bced4b2 100644--- a/internal/mcp/handlers_record.go+++ b/internal/mcp/handlers_record.go@@ -96,7 +96,6 @@ func handleRecordStop(c *Client) func(context.Context, mcp.CallToolRequest) (*mcreturn resultFromBytes(body, code)}- // Poll until encoding finishes, then move the file.serverPath := stopResp.Pathif err := pollRecordingFinished(ctx, c); err != nil {return mcp.NewToolResultError(fmt.Sprintf(@@ -153,7 +152,6 @@ func moveFile(src, dst string) error {if err := os.Rename(src, dst); err == nil {return nil}- // Cross-filesystem: copy with exclusive creation.in, err := os.Open(src)if err != nil {return errdiff --git a/internal/mcp/tools.go b/internal/mcp/tools.goindex 14cb6eb9..e6174d4b 100644--- a/internal/mcp/tools.go+++ b/internal/mcp/tools.go@@ -5,7 +5,6 @@ import "github.com/mark3labs/mcp-go/mcp"// allTools returns every MCP tool exposed by the PinchTab MCP server.func allTools() []mcp.Tool {return []mcp.Tool{- // ββ Navigation ββββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_navigate",mcp.WithDescription("Navigate to a URL in the browser"),mcp.WithString("url", mcp.Required(), mcp.Description("The URL to navigate to")),@@ -74,7 +73,6 @@ func allTools() []mcp.Tool {mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),),- // ββ Interaction βββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_click",mcp.WithDescription("Click an element. Prefer selector from pinchtab_find.best_ref (e.g. 'e5') to avoid extra snapshots."),mcp.WithString("selector", mcp.Description("Unified selector: ref (e.g. 'e5'), CSS, XPath, text, find, role, label, placeholder, alt, title, testid, or first/last/nth. Non-ref selectors resolve in the current frame scope.")),@@ -179,7 +177,6 @@ func allTools() []mcp.Tool {mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),),- // ββ Keyboard (no selector β targets focused element) ββββββββmcp.NewTool("pinchtab_keyboard_type",mcp.WithDescription("Type text at the currently focused element via keystroke events (keyDown + keyUp per character)"),mcp.WithString("text", mcp.Required(), mcp.Description("Text to type")),@@ -209,7 +206,6 @@ func allTools() []mcp.Tool {mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),),- // ββ Content βββββββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_eval",mcp.WithDescription("Execute JavaScript in the browser and return the result. This is not frame-scoped; current pinchtab_frame state does not change evaluation context."),mcp.WithString("expression", mcp.Required(), mcp.Description("JavaScript expression to evaluate")),@@ -228,7 +224,6 @@ func allTools() []mcp.Tool {mcp.WithString("tabId", mcp.Description("Target tab ID")),),- // ββ Tab Management ββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_list_tabs",mcp.WithDescription("List all open browser tabs"),),@@ -248,7 +243,6 @@ func allTools() []mcp.Tool {mcp.WithString("profile", mcp.Required(), mcp.Description("Profile name or profile ID")),),- // ββ Utility βββββββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_wait",mcp.WithDescription("Wait for a specified number of milliseconds"),mcp.WithNumber("ms", mcp.Required(), mcp.Description("Milliseconds to wait (max 30000)")),@@ -291,7 +285,6 @@ func allTools() []mcp.Tool {mcp.Description("Browser to use for this request (e.g. chrome, cloak, ghost-chrome).")),),- // ββ Network Monitoring ββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_network",mcp.WithDescription("List recent network requests captured from the browser. Returns method, status, URL, type, size, and timing for each request."),mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),@@ -329,7 +322,6 @@ func allTools() []mcp.Tool {mcp.WithString("pattern", mcp.Description("Pattern to remove (omit to clear all rules)")),),- // ββ Recording βββββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_record_start",mcp.WithDescription("Start recording browser activity. Requires security.allowScreencast. GIF works without ffmpeg; WebM/MP4 need ffmpeg."),mcp.WithString("file", mcp.Required(), mcp.Description("Output file path (.gif, .webm, or .mp4)")),@@ -346,7 +338,6 @@ func allTools() []mcp.Tool {mcp.WithDescription("Check active recording status (format, fps, duration, frame count)"),),- // ββ Dialog ββββββββββββββββββββββββββββββββββββββββββββββββββmcp.NewTool("pinchtab_dialog",mcp.WithDescription("Handle a JavaScript dialog (alert, confirm, prompt). Accept or dismiss the currently open dialog."),mcp.WithString("action", mcp.Required(), mcp.Description("Action to take: 'accept' or 'dismiss'")),diff --git a/internal/navguard/navguard_test.go b/internal/navguard/navguard_test.goindex df5128ff..03e707de 100644--- a/internal/navguard/navguard_test.go+++ b/internal/navguard/navguard_test.go@@ -19,8 +19,6 @@ func stubHostResolution(t *testing.T, fn func(context.Context, string, string) (})}-// --- URL Validation Tests ----func TestValidateURL_RejectsUnsupportedSchemes(t *testing.T) {for _, rawURL := range []string{"javascript:alert(1)",@@ -60,8 +58,6 @@ func TestValidateURL_RejectsEmpty(t *testing.T) {}}-// --- Target Validation Tests ----func TestValidateTarget_AllowsLocalHosts(t *testing.T) {v := &Validator{}for _, rawURL := range []string{@@ -191,8 +187,6 @@ func TestValidateTarget_RejectsMixedUntrustedWithTrustedResolveCIDR(t *testing.T}}-// --- Remote IP Validation Tests ----func TestValidateRemoteIP_AllowsExactTrustedResolvedIP(t *testing.T) {if err := ValidateRemoteIP("10.1.2.3", nil, []netip.Addr{netip.MustParseAddr("10.1.2.3")}); err != nil {t.Fatalf("expected exact trusted resolved IP to be allowed, got %v", err)@@ -229,8 +223,6 @@ func TestValidateRemoteIP_LoopbackProxyBlockedByDefault(t *testing.T) {}}-// --- CIDR Helper Tests ----func TestBuildTrustedProxyCIDRs_FlagOff(t *testing.T) {got := BuildTrustedProxyCIDRs(false, []string{"10.0.0.0/8"})if len(got) != 1 {@@ -280,8 +272,6 @@ func TestParseCIDRs_TreatsBareIPsAsSingleHosts(t *testing.T) {}}-// --- Domain-allowed + RemoteIP Scenario Tests ----func TestValidateTarget_DomainAllowedCallbackPermitsPrivateIP(t *testing.T) {// Callers compute allowExplicitInternal from the IDPI domain allowlist// (handlers use idpi Guard.DomainAllowed); modeled here as a local callback.@@ -338,8 +328,6 @@ func TestValidateRemoteIP_PrivateIPBlockedWithNoCIDRs(t *testing.T) {}}-// --- Test Helpers ----func cidrsContainIP(cidrs []*net.IPNet, ip net.IP) bool {for _, c := range cidrs {if c.Contains(ip) {diff --git a/internal/orchestrator/handlers.go b/internal/orchestrator/handlers.goindex edc112e7..27611d08 100644--- a/internal/orchestrator/handlers.go+++ b/internal/orchestrator/handlers.go@@ -52,14 +52,12 @@ func (o *Orchestrator) RegisterHandlers(mux *http.ServeMux) {}func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {- // Profile managementif !skipLaunch {mux.HandleFunc("POST /profiles/{id}/start", o.handleStartByID)}mux.HandleFunc("POST /profiles/{id}/stop", o.handleStopByID)mux.HandleFunc("GET /profiles/{id}/instance", o.handleProfileInstance)- // Instance managementmux.HandleFunc("GET /instances", o.handleList)mux.HandleFunc("GET /instances/{id}", o.handleGetInstance)mux.HandleFunc("GET /instances/tabs", o.handleAllTabs)@@ -88,7 +86,6 @@ func (o *Orchestrator) registerHandlers(mux *http.ServeMux, skipLaunch bool) {for _, route := range routes.TabScopedRoutes() {mux.HandleFunc(route, o.proxyTabRequest)}- // Tab-scoped capability-gated routes.for cap, eps := range routes.TabScopedCapabilityRoutes() {var enabled boolvar feature, setting, code stringdiff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.goindex b3262738..ff39a069 100644--- a/internal/orchestrator/handlers_instances.go+++ b/internal/orchestrator/handlers_instances.go@@ -529,7 +529,6 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {return fmt.Errorf("invalid attach URL: %w", err)}- // Validate schemeschemeAllowed := falsefor _, allowed := range o.runtimeCfg.AttachAllowSchemes {if parsed.Scheme == allowed {@@ -554,7 +553,6 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {}}- // Validate hosthost := parsed.Hostname()if !isAllowedAttachHost(host, o.runtimeCfg.AttachAllowHosts) {return fmt.Errorf("host %q not allowed (allowed: %v)", host, o.runtimeCfg.AttachAllowHosts)diff --git a/internal/orchestrator/instance_launch.go b/internal/orchestrator/instance_launch.goindex bc0b9a30..ecd03421 100644--- a/internal/orchestrator/instance_launch.go+++ b/internal/orchestrator/instance_launch.go@@ -164,7 +164,6 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts}env := mergeEnvWithOverrides(filterEnvWithPrefixes(os.Environ(), "PINCHTAB_"), envOverrides)- // Validate the per-instance browser override, if provided.if opts.Browser != "" {var configured []stringif o.runtimeCfg != nil {diff --git a/internal/orchestrator/instance_query.go b/internal/orchestrator/instance_query.goindex 0a49fd9d..2f6c028a 100644--- a/internal/orchestrator/instance_query.go+++ b/internal/orchestrator/instance_query.go@@ -114,7 +114,6 @@ func (o *Orchestrator) FirstRunningURLForRequest(r *http.Request) (string, int,return o.FirstRunningURL(), 0, nil}- // Validate the requested browser before normalization.if _, err := config.ParseBrowser(requested, nil); err != nil {return "", http.StatusBadRequest, fmt.Errorf("unknown browser %q", requested)}@@ -125,7 +124,6 @@ func (o *Orchestrator) FirstRunningURLForRequest(r *http.Request) (string, int,if len(matches) == 0 {return "", http.StatusBadRequest, fmt.Errorf("no browser target configured for browser %q", requested)}- // Valid browser β check if there's a running instance for it.u := o.FirstRunningURLForBrowser(normalized)if u == "" {return "", http.StatusConflict, fmt.Errorf("no running instance for browser %q", requested)diff --git a/internal/orchestrator/launch_target_selection.go b/internal/orchestrator/launch_target_selection.goindex d666580f..821b103c 100644--- a/internal/orchestrator/launch_target_selection.go+++ b/internal/orchestrator/launch_target_selection.go@@ -43,7 +43,6 @@ func (o *Orchestrator) ResolveRequestedBrowser(requested string) (targetName, prreturn resolved.Name, resolved.Provider, nil}case 0:- // No matching target for this browser β treat as unknown.return "", "", &UnknownBrowserError{Target: requested, Err: fmt.Errorf("no browser target configured for browser %q", requested)}default:dt := config.ResolveDefaultTarget(o.runtimeCfg)diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.goindex d31d2064..786bfc8b 100644--- a/internal/orchestrator/orchestrator_test.go+++ b/internal/orchestrator/orchestrator_test.go@@ -167,8 +167,6 @@ func TestOrchestrator_StopProfile(t *testing.T) {}}-// === Security Validation Tests ===-func TestOrchestrator_Launch_RejectsPathTraversal(t *testing.T) {old := processAliveFuncprocessAliveFunc = func(pid int) bool { return pid > 0 }@@ -486,7 +484,6 @@ func TestOrchestrator_Attach(t *testing.T) {t.Errorf("expected ProfileName %q, got %q", "my-external-chrome", inst.ProfileName)}- // Check it appears in listlist := o.List()if len(list) != 1 {t.Fatalf("expected 1 instance in list, got %d", len(list))diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.goindex 11094ad8..cb924fcc 100644--- a/internal/orchestrator/proxy.go+++ b/internal/orchestrator/proxy.go@@ -215,7 +215,6 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requhandlers.SetProxyWSBackendAuthorization(req.Header, "Bearer "+token)}- // Use WebSocket proxy for proper upgradehandlers.ProxyWebSocket(w, req, targetURL.String())}@@ -330,12 +329,12 @@ func (o *Orchestrator) applyInstanceAuth(req *http.Request, inst *InstanceInternfunc classifyLaunchError(err error) int {msg := err.Error()if strings.Contains(msg, "cannot contain") || strings.Contains(msg, "cannot be empty") {- return 400 // Bad Request - validation error+ return 400}if strings.Contains(msg, "already") || strings.Contains(msg, "in use") {- return 409 // Conflict - resource already exists+ return 409}- return 500 // Internal Server Error+ return 500}// enrichActivityFromResponse extracts tabId and url from the bridge JSON@@ -369,8 +368,6 @@ func (o *Orchestrator) handleProxyResponseHeaders(origReq *http.Request, resp *hreturn}- // Tab close β invalidate locator entry. Pre-existing behavior, kept- // here so callers continue to get cache freshness for free.if o.instanceMgr != nil {if tabID := tabClosePathID(origReq); tabID != "" {o.instanceMgr.InvalidateTab(tabID)@@ -441,7 +438,6 @@ func tabsCacheRequestAffectsTabs(req *http.Request, resp *http.Response) bool {}}if strings.HasPrefix(path, "/tabs/") {- // Sub-routes that mutate tab state: /tabs/{id}/{close,navigate,reload,back,forward}switch {case strings.HasSuffix(path, "/close"),strings.HasSuffix(path, "/navigate"),diff --git a/internal/orchestrator/route.go b/internal/orchestrator/route.goindex 6eb5dee9..fb68888d 100644--- a/internal/orchestrator/route.go+++ b/internal/orchestrator/route.go@@ -289,7 +289,6 @@ func (o *Orchestrator) routeToInstanceID(w http.ResponseWriter, r *http.Request,internal, ok := o.instances[instanceID]o.mu.RUnlock()if !ok || internal == nil || internal.Status != "running" || !instanceIsActive(internal) {- // Stale binding: clear and let fallback decide.if o.bindings != nil {o.bindings.ClearInstance(instanceID)}diff --git a/internal/profiles/profiles_test.go b/internal/profiles/profiles_test.goindex e69b9410..17441cae 100644--- a/internal/profiles/profiles_test.go+++ b/internal/profiles/profiles_test.go@@ -598,8 +598,6 @@ func TestProfileListIncludesUseWhen(t *testing.T) {}}-// === Security Validation Tests ===-func TestValidateProfileName(t *testing.T) {tests := []struct {name string@@ -759,7 +757,6 @@ func TestProfileHandlerCreateReturns409OnDuplicate(t *testing.T) {mux := http.NewServeMux()pm.RegisterHandlers(mux)- // Create first profilebody := `{"name":"duplicate-test"}`req := httptest.NewRequest("POST", "/profiles/create", strings.NewReader(body))req.Header.Set("Content-Type", "application/json")@@ -770,7 +767,6 @@ func TestProfileHandlerCreateReturns409OnDuplicate(t *testing.T) {t.Fatalf("first create failed: %d %s", w.Code, w.Body.String())}- // Try to create duplicatereq = httptest.NewRequest("POST", "/profiles/create", strings.NewReader(body))req.Header.Set("Content-Type", "application/json")w = httptest.NewRecorder()@@ -784,7 +780,6 @@ func TestProfileHandlerCreateReturns409OnDuplicate(t *testing.T) {func TestProfileImportRejectsPathTraversal(t *testing.T) {pm := NewProfileManager(t.TempDir())- // Create a valid source directorysrc := filepath.Join(t.TempDir(), "chrome-src")_ = os.MkdirAll(filepath.Join(src, "Default"), 0755)_ = os.WriteFile(filepath.Join(src, "Default", "Preferences"), []byte(`{}`), 0644)diff --git a/internal/routes/routes.go b/internal/routes/routes.goindex eb964147..a1992da5 100644--- a/internal/routes/routes.go+++ b/internal/routes/routes.go@@ -44,15 +44,12 @@ func (e Endpoint) TabRoute() string {return e.Method + " /tabs/{id}" + e.Path}-// coreEndpoints is the canonical list of API endpoints.var coreEndpoints = []Endpoint{- // Navigation{"POST", "/navigate", "Navigate URL or create tab", CapNone, true},{"POST", "/back", "Go back", CapNone, true},{"POST", "/forward", "Go forward", CapNone, true},{"POST", "/reload", "Reload page", CapNone, true},- // Content extraction{"GET", "/snapshot", "Accessibility snapshot", CapNone, true},{"GET", "/frame", "Get current frame scope", CapNone, true},{"POST", "/frame", "Set current frame scope", CapNone, true},@@ -73,33 +70,27 @@ var coreEndpoints = []Endpoint{{"GET", "/pdf", "Export as PDF (GET)", CapNone, true},{"POST", "/pdf", "Export as PDF (POST)", CapNone, true},- // Actions{"POST", "/action", "Single action", CapNone, true},{"POST", "/actions", "Batch actions", CapNone, true},{"POST", "/dialog", "Handle dialog", CapNone, true},{"POST", "/wait", "Wait for condition", CapNone, true},{"POST", "/find", "Find elements", CapNone, true},- // Tab management{"POST", "/tab", "Create or focus tab", CapNone, false},{"POST", "/close", "Close tab", CapNone, true},{"POST", "/lock", "Lock tab", CapNone, true},{"POST", "/unlock", "Unlock tab", CapNone, true},- // Human handoff{"POST", "/handoff", "Pause tab for human handoff", CapNone, true},{"POST", "/resume", "Resume paused tab", CapNone, true},{"GET", "/handoff", "Get handoff status", CapNone, true},- // Cookies{"GET", "/cookies", "Get cookies", CapCookies, true},{"POST", "/cookies", "Set cookies", CapCookies, true},{"DELETE", "/cookies", "Clear all cookies", CapCookies, true},- // Metrics{"GET", "/metrics", "Runtime metrics", CapNone, true},- // Network{"GET", "/network", "Network log", CapNone, true},{"GET", "/network/stream", "Network SSE stream", CapNone, true},{"GET", "/network/export", "Export HAR", CapNone, true},@@ -110,29 +101,24 @@ var coreEndpoints = []Endpoint{{"POST", "/network/route", "Install an interception rule", CapNetworkIntercept, true},{"DELETE", "/network/route", "Remove interception rule(s)", CapNetworkIntercept, true},- // Console & errors{"GET", "/console", "Console logs", CapNone, false},{"POST", "/console/clear", "Clear console logs", CapNone, false},{"GET", "/errors", "Error logs", CapNone, false},{"POST", "/errors/clear", "Clear error logs", CapNone, false},- // Clipboard{"GET", "/clipboard/read", "Read clipboard", CapNone, false},{"POST", "/clipboard/write", "Write clipboard", CapNone, false},{"POST", "/clipboard/copy", "Copy to clipboard", CapNone, false},{"GET", "/clipboard/paste", "Paste from clipboard", CapNone, false},- // Stealth & fingerprint{"GET", "/stealth/status", "Stealth configuration status", CapNone, false},{"POST", "/fingerprint/rotate", "Rotate browser fingerprint", CapNone, false},- // Solvers{"GET", "/solvers", "List available solvers", CapNone, false},{"GET", "/config/autosolver", "Get autosolver runtime config", CapNone, false},{"POST", "/solve", "Run default solver", CapNone, true},{"POST", "/solve/{name}", "Run named solver", CapNone, true},- // Emulation{"POST", "/emulation/viewport", "Set browser viewport dimensions", CapNone, true},{"POST", "/emulation/geolocation", "Set geolocation", CapNone, true},{"POST", "/emulation/offline", "Enable/disable offline mode", CapNone, true},@@ -140,7 +126,6 @@ var coreEndpoints = []Endpoint{{"POST", "/emulation/credentials", "Set HTTP auth credentials", CapNone, true},{"POST", "/emulation/media", "Emulate CSS media features", CapNone, true},- // Cache{"POST", "/cache/clear", "Clear browser cache", CapNone, false},{"GET", "/cache/status", "Cache status", CapNone, false},@@ -148,11 +133,9 @@ var coreEndpoints = []Endpoint{{"POST", "/storage", "Set storage item", CapStateExport, true},{"DELETE", "/storage", "Delete storage items", CapStateExport, true},- // State management{"GET", "/state", "Read current browser state", CapStateExport, false},{"GET", "/state/list", "List saved states", CapStateExport, false},- // Capability-gated{"POST", "/evaluate", "Run JavaScript in page", CapEvaluate, true},{"POST", "/macro", "Macro action pipeline", CapMacro, false},{"GET", "/download", "Download URL via browser session", CapDownload, true},diff --git a/internal/scheduler/queue.go b/internal/scheduler/queue.goindex cdcadf9a..ddbd0d38 100644--- a/internal/scheduler/queue.go+++ b/internal/scheduler/queue.go@@ -232,8 +232,6 @@ type AgentStats struct {Inflight int `json:"inflight"`}-// --- heap implementation ----// taskHeap implements container/heap for priority-then-FIFO ordering.type taskHeap []*Taskdiff --git a/internal/scheduler/results_test.go b/internal/scheduler/results_test.goindex 34eb8c37..f35cbb6d 100644--- a/internal/scheduler/results_test.go+++ b/internal/scheduler/results_test.go@@ -35,25 +35,21 @@ func TestResultStoreList(t *testing.T) {rs.Store(&Task{ID: "t2", AgentID: "a1", State: StateQueued})rs.Store(&Task{ID: "t3", AgentID: "a2", State: StateDone})- // All tasksall := rs.List("", nil)if len(all) != 3 {t.Errorf("expected 3, got %d", len(all))}- // Filter by agenta1Only := rs.List("a1", nil)if len(a1Only) != 2 {t.Errorf("expected 2 for a1, got %d", len(a1Only))}- // Filter by statedoneOnly := rs.List("", []TaskState{StateDone})if len(doneOnly) != 2 {t.Errorf("expected 2 done, got %d", len(doneOnly))}- // Filter by botha1Done := rs.List("a1", []TaskState{StateDone})if len(a1Done) != 1 {t.Errorf("expected 1, got %d", len(a1Done))diff --git a/internal/scheduler/scheduler.go b/internal/scheduler/scheduler.goindex e9955927..aec69516 100644--- a/internal/scheduler/scheduler.go+++ b/internal/scheduler/scheduler.go@@ -67,7 +67,6 @@ type Scheduler struct {// webhookSem bounds the number of concurrent webhook delivery goroutines.webhookSem chan struct{}- // cancellationcancels map[string]context.CancelFunccancelsMu sync.Mutex@@ -446,7 +445,6 @@ func (s *Scheduler) finishTask(t *Task) {delete(s.live, t.ID)s.liveMu.Unlock()- // Fire webhook asynchronously if configured.if t.CallbackURL != "" && t.GetState().IsTerminal() {select {case s.webhookSem <- struct{}{}:diff --git a/internal/scheduler/scheduler_test.go b/internal/scheduler/scheduler_test.goindex 8faf312b..a8d0e06b 100644--- a/internal/scheduler/scheduler_test.go+++ b/internal/scheduler/scheduler_test.go@@ -25,7 +25,6 @@ func (m *mockResolver) ResolveTabInstance(tabID string) (string, error) {func newTestScheduler(t *testing.T) (*Scheduler, *httptest.Server) {t.Helper()- // Mock executor that returns success.executor := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")if err := json.NewEncoder(w).Encode(map[string]bool{"success": true}); err != nil {@@ -33,7 +32,6 @@ func newTestScheduler(t *testing.T) (*Scheduler, *httptest.Server) {}}))- // Extract port from executor URL.parts := strings.Split(executor.URL, ":")port := parts[len(parts)-1]@@ -208,7 +206,6 @@ func TestSchedulerDispatchAndComplete(t *testing.T) {t.Fatalf("submit failed: %v", err)}- // Wait for task to complete.deadline := time.After(5 * time.Second)for {select {diff --git a/internal/scheduler/webhook_test.go b/internal/scheduler/webhook_test.goindex 807be1e7..69141e43 100644--- a/internal/scheduler/webhook_test.go+++ b/internal/scheduler/webhook_test.go@@ -98,7 +98,6 @@ func TestSendWebhookSuccess(t *testing.T) {t.Fatal("webhook was never received")}- // Verify headers.if ct := gotHeaders.Get("Content-Type"); ct != "application/json" {t.Errorf("expected application/json, got %s", ct)}@@ -115,7 +114,6 @@ func TestSendWebhookSuccess(t *testing.T) {t.Fatalf("expected webhook dial to use pinned IP, got %q", dialedAddr.Load().(string))}- // Verify body is a valid task snapshot.var snap Taskif err := json.Unmarshal(gotBody, &snap); err != nil {t.Fatalf("unmarshal body: %v", err)diff --git a/internal/selector/selector.go b/internal/selector/selector.goindex f0a8cb90..8f170810 100644--- a/internal/selector/selector.go+++ b/internal/selector/selector.go@@ -130,7 +130,6 @@ func Parse(s string) Selector {return Selector{}}- // Explicit prefixesif after, ok := cutPrefix(s, "css:"); ok {return Selector{Kind: KindCSS, Value: after}}@@ -177,17 +176,14 @@ func Parse(s string) Selector {return Selector{Kind: KindRef, Value: after}}- // Auto-detect: XPathif strings.HasPrefix(s, "//") || strings.HasPrefix(s, "(//") {return Selector{Kind: KindXPath, Value: s}}- // Auto-detect: Ref (e.g. e5, e123)if IsRef(s) {return Selector{Kind: KindRef, Value: s}}- // Everything else is CSS (backward compatible default)return Selector{Kind: KindCSS, Value: s}}@@ -310,7 +306,6 @@ func splitNthSelectorValue(value string) (int, string, bool) {return index, rawSelector, true}-// cutPrefix is a helper for strings.CutPrefix (available in Go 1.20+).func cutPrefix(s, prefix string) (string, bool) {if strings.HasPrefix(s, prefix) {return s[len(prefix):], truediff --git a/internal/selector/selector_test.go b/internal/selector/selector_test.goindex 5dc257c9..d55f37b5 100644--- a/internal/selector/selector_test.go+++ b/internal/selector/selector_test.go@@ -4,41 +4,32 @@ import ("testing")-// ----------------------------------------------------------------------------// Parse β explicit prefixes-// ----------------------------------------------------------------------------func TestParse_ExplicitPrefixes(t *testing.T) {tests := []struct {input stringkind Kindvalue string}{- // CSS{"css:#login", KindCSS, "#login"},{"css:.btn.primary", KindCSS, ".btn.primary"},{"css:div > span", KindCSS, "div > span"},{"css:input[type=text]", KindCSS, "input[type=text]"},{"css:*", KindCSS, "*"},- // XPath{"xpath://div[@id='main']", KindXPath, "//div[@id='main']"},{"xpath:(//button)[1]", KindXPath, "(//button)[1]"},{"xpath://a[contains(@href,'login')]", KindXPath, "//a[contains(@href,'login')]"},- // Text{"text:Submit", KindText, "Submit"},{"text:Log in", KindText, "Log in"},{"text:", KindText, ""},{"text:with:colon", KindText, "with:colon"},- // Semantic / find{"find:login button", KindSemantic, "login button"},{"semantic:login button", KindSemantic, "login button"},{"find:the search input field", KindSemantic, "the search input field"},{"find:", KindSemantic, ""},- // Locator prefixes{"role:button Save", KindRole, "button Save"},{"label:Email", KindLabel, "Email"},{"placeholder:Search", KindPlaceholder, "Search"},@@ -49,7 +40,6 @@ func TestParse_ExplicitPrefixes(t *testing.T) {{"last:text:Submit", KindLast, "text:Submit"},{"nth:2:role:button Save", KindNth, "2:role:button Save"},- // Ref (explicit prefix){"ref:e5", KindRef, "e5"},{"ref:e0", KindRef, "e0"},{"ref:e99999", KindRef, "e99999"},@@ -67,47 +57,36 @@ func TestParse_ExplicitPrefixes(t *testing.T) {}}-// ----------------------------------------------------------------------------// Parse β auto-detection (no prefix)-// ----------------------------------------------------------------------------func TestParse_AutoDetect(t *testing.T) {tests := []struct {input stringkind Kindvalue string}{- // Refs{"e0", KindRef, "e0"},{"e5", KindRef, "e5"},{"e42", KindRef, "e42"},{"e123", KindRef, "e123"},{"e99999", KindRef, "e99999"},- // CSS auto-detect: # prefix{"#login", KindCSS, "#login"},{"#my-id", KindCSS, "#my-id"},- // CSS auto-detect: . prefix{".btn", KindCSS, ".btn"},{".btn.primary", KindCSS, ".btn.primary"},- // CSS auto-detect: [ prefix{"[type=file]", KindCSS, "[type=file]"},{"[data-testid='foo']", KindCSS, "[data-testid='foo']"},- // CSS auto-detect: compound selectors{"button.submit", KindCSS, "button.submit"},{"div > span", KindCSS, "div > span"},{"input[name='email']", KindCSS, "input[name='email']"},{"ul li:first-child", KindCSS, "ul li:first-child"},{"a:hover", KindCSS, "a:hover"},- // XPath auto-detect: //{"//div[@class='main']", KindXPath, "//div[@class='main']"},{"//a", KindXPath, "//a"},- // XPath auto-detect: (//{"(//button)[1]", KindXPath, "(//button)[1]"},{"(//div[@class='x'])[last()]", KindXPath, "(//div[@class='x'])[last()]"},@@ -132,10 +111,6 @@ func TestParse_AutoDetect(t *testing.T) {}}-// ----------------------------------------------------------------------------// Parse β empty / whitespace-// ----------------------------------------------------------------------------func TestParse_Empty(t *testing.T) {s := Parse("")if !s.IsEmpty() {@@ -156,7 +131,6 @@ func TestParse_WhitespaceOnly(t *testing.T) {}func TestParse_WhitespaceTrimming(t *testing.T) {- // Leading/trailing whitespace should be trimmed before parsingtests := []struct {input stringkind Kind@@ -181,10 +155,6 @@ func TestParse_WhitespaceTrimming(t *testing.T) {}}-// ----------------------------------------------------------------------------// Parse β edge cases-// ----------------------------------------------------------------------------func TestParse_EdgeCases(t *testing.T) {tests := []struct {name string@@ -278,10 +248,6 @@ func TestParse_EdgeCases(t *testing.T) {}}-// ----------------------------------------------------------------------------// IsRef-// ----------------------------------------------------------------------------func TestIsRef(t *testing.T) {refs := []string{"e0", "e5", "e42", "e123", "e9999", "e1234567890"}for _, r := range refs {@@ -302,10 +268,6 @@ func TestIsRef(t *testing.T) {}}-// ----------------------------------------------------------------------------// Selector.String() β canonical representation-// ----------------------------------------------------------------------------func TestSelector_String(t *testing.T) {tests := []struct {sel Selector@@ -340,10 +302,6 @@ func TestSelector_String(t *testing.T) {}}-// ----------------------------------------------------------------------------// Selector.IsEmpty()-// ----------------------------------------------------------------------------func TestSelector_IsEmpty(t *testing.T) {if !(Selector{}).IsEmpty() {t.Error("zero-value Selector should be empty")@@ -356,10 +314,6 @@ func TestSelector_IsEmpty(t *testing.T) {}}-// ----------------------------------------------------------------------------// Selector.Validate()-// ----------------------------------------------------------------------------func TestSelector_Validate(t *testing.T) {valid := []Selector{{KindRef, "e5"},@@ -383,15 +337,12 @@ func TestSelector_Validate(t *testing.T) {}}- // Empty selectorif err := (Selector{}).Validate(); err == nil {t.Error("Validate(empty) should fail")}- // Empty value with kind setif err := (Selector{Kind: KindCSS}).Validate(); err == nil {t.Error("Validate(kind=css, value='') should fail")}- // Unknown kindif err := (Selector{Kind: "bogus", Value: "x"}).Validate(); err == nil {t.Error("Validate(bogus kind) should fail")}@@ -435,12 +386,7 @@ func TestSelector_SemanticQuery(t *testing.T) {}}-// ----------------------------------------------------------------------------// From* constructors-// ----------------------------------------------------------------------------func TestFromConstructors(t *testing.T) {- // Non-empty valuesif s := FromRef("e5"); s.Kind != KindRef || s.Value != "e5" {t.Errorf("FromRef(\"e5\"): %+v", s)}@@ -457,7 +403,6 @@ func TestFromConstructors(t *testing.T) {t.Errorf("FromSemantic(\"btn\"): %+v", s)}- // Empty values β empty selectorempties := []struct {name stringfn func(string) Selector@@ -475,10 +420,6 @@ func TestFromConstructors(t *testing.T) {}}-// ----------------------------------------------------------------------------// Parse roundtrip: Parse β String β Parse should be stable-// ----------------------------------------------------------------------------func TestParse_Roundtrip(t *testing.T) {inputs := []string{"e5",@@ -512,12 +453,7 @@ func TestParse_Roundtrip(t *testing.T) {}}-// ----------------------------------------------------------------------------// Parse β prefix priority (explicit prefix wins over auto-detect)-// ----------------------------------------------------------------------------func TestParse_PrefixPriority(t *testing.T) {- // "css://div" should be CSS, not XPath (explicit prefix wins)s := Parse("css://div")if s.Kind != KindCSS {t.Errorf("Parse(\"css://div\").Kind = %q, want css", s.Kind)@@ -526,7 +462,6 @@ func TestParse_PrefixPriority(t *testing.T) {t.Errorf("Parse(\"css://div\").Value = %q, want \"//div\"", s.Value)}- // "ref:embed" should be ref, not CSSs = Parse("ref:embed")if s.Kind != KindRef {t.Errorf("Parse(\"ref:embed\").Kind = %q, want ref", s.Kind)@@ -535,7 +470,6 @@ func TestParse_PrefixPriority(t *testing.T) {t.Errorf("Parse(\"ref:embed\").Value = %q, want \"embed\"", s.Value)}- // "text:#login" should be text, not CSSs = Parse("text:#login")if s.Kind != KindText {t.Errorf("Parse(\"text:#login\").Kind = %q, want text", s.Kind)@@ -544,7 +478,6 @@ func TestParse_PrefixPriority(t *testing.T) {t.Errorf("Parse(\"text:#login\").Value = %q, want \"#login\"", s.Value)}- // "xpath:e5" should be xpath, not refs = Parse("xpath:e5")if s.Kind != KindXPath {t.Errorf("Parse(\"xpath:e5\").Kind = %q, want xpath", s.Kind)diff --git a/internal/server/server.go b/internal/server/server.goindex 6fc4ae5e..9f4f4b21 100644--- a/internal/server/server.go+++ b/internal/server/server.go@@ -83,7 +83,6 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {sessionAPI = dashboard.NewSessionAPI(sessionStore, cfg.BrowsersAvailable)}- // Wire up instance events to SSE broadcastorch.OnEvent(func(evt orchestrator.InstanceEvent) {dash.BroadcastSystemEvent(dashboard.SystemEvent{Type: evt.Type,diff --git a/internal/solver/solver.go b/internal/solver/solver.goindex 608a733c..5a9a2892 100644--- a/internal/solver/solver.go+++ b/internal/solver/solver.go@@ -44,10 +44,6 @@ type Result struct {Token string `json:"token,omitempty"`}-// ----------------------------------------------------------------------------// Registry-// ----------------------------------------------------------------------------var (registry = make(map[string]Solver)order []string // insertion order for deterministic auto-detect@@ -102,7 +98,6 @@ func Solve(ctx context.Context, name string, opts Options) (*Result, error) {return s.Solve(ctx, opts)}- // Auto-detect: try each registered solver in order.mu.RLock()names := make([]string, len(order))copy(names, order)@@ -120,7 +115,6 @@ func Solve(ctx context.Context, name string, opts Options) (*Result, error) {return s.Solve(ctx, opts)}- // No challenge detected on the current page.var title stringreturn &Result{Solved: true, Title: title}, nil}diff --git a/internal/state/state.go b/internal/state/state.goindex 76a82ee3..6a513ab2 100644--- a/internal/state/state.go+++ b/internal/state/state.go@@ -81,8 +81,6 @@ func EnsureSessionsDir(stateDir string) (string, error) {return dir, nil}-// fileExtension returns the appropriate file extension based on whether the file-// is encrypted. Encrypted files use .json.enc; plaintext files use .json.func fileExtension(encrypted bool) string {if encrypted {return ".json.enc"@@ -156,13 +154,10 @@ func Load(path, encryptionKey string) (*StateFile, error) {return &sf, nil}-// isStateFile reports whether a directory entry is a recognised state file-// (either .json or .json.enc).func isStateFile(name string) bool {return strings.HasSuffix(name, ".json") || strings.HasSuffix(name, ".json.enc")}-// trimStateExt removes the state file extension (.json or .json.enc) from a filename.func trimStateExt(name string) string {if strings.HasSuffix(name, ".json.enc") {return strings.TrimSuffix(name, ".json.enc")@@ -248,7 +243,6 @@ func Delete(stateDir, name string) error {dir := SessionsDir(stateDir)base := sanitizeFilename(name)cleanDir := filepath.Clean(dir) + string(os.PathSeparator)- // Try encrypted extension first.for _, ext := range []string{".json.enc", ".json"} {path := filepath.Clean(filepath.Join(dir, base+ext))if !strings.HasPrefix(path, cleanDir) {@@ -344,7 +338,6 @@ func Decrypt(ciphertext []byte, passphrase string) ([]byte, error) {return nil, fmt.Errorf("encryption key required")}- // Try PBKDF2-based decryption (new format: salt || nonce || ciphertext).if len(ciphertext) > pbkdf2SaltSize {salt := ciphertext[:pbkdf2SaltSize]rest := ciphertext[pbkdf2SaltSize:]@@ -356,7 +349,6 @@ func Decrypt(ciphertext []byte, passphrase string) ([]byte, error) {}}- // Fall back to legacy SHA-256 key derivation.legacyHash := sha256.Sum256([]byte(passphrase))return decryptWithKey(ciphertext, legacyHash[:])}@@ -404,16 +396,13 @@ func sanitizeFilename(name string) string {// Normalize Windows path separators so filepath.Base works on all OSes.name = strings.ReplaceAll(name, "\\", "/")- // Drop any directory components.name = filepath.Base(name)- // Remove leading dot-segments.for strings.HasPrefix(name, "../") {name = strings.TrimPrefix(name, "../")}name = strings.TrimPrefix(name, "./")- // Replace disallowed characters.name = strings.Map(func(r rune) rune {switch r {case '/', '\\', ':', '*', '?', '"', '<', '>', '|':@@ -423,7 +412,6 @@ func sanitizeFilename(name string) string {}}, name)- // Final safety.name = strings.TrimLeft(name, ".")if name == "" || name == "." || name == ".." {return "state"@@ -437,7 +425,6 @@ func sanitizeFilename(name string) string {func ResolvePath(stateDir, name string) string {dir := SessionsDir(stateDir)base := sanitizeFilename(name)- // Try encrypted extension first, then plaintext.for _, ext := range []string{".json.enc", ".json"} {resolved := filepath.Clean(filepath.Join(dir, base+ext))cleanDir := filepath.Clean(dir) + string(os.PathSeparator)diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.goindex f45400fa..fb0c86c5 100644--- a/internal/strategy/autorestart/autorestart_test.go+++ b/internal/strategy/autorestart/autorestart_test.go@@ -648,8 +648,6 @@ func TestStrategy_HandleEvent_SkipsDuplicateDuringRestart(t *testing.T) {}}-// --- Mock runner for orchestrator tests ----type mockRunner struct {portAvail bool}diff --git a/internal/strategy/autorestart/restart.go b/internal/strategy/autorestart/restart.goindex 5552ac2e..1f81a785 100644--- a/internal/strategy/autorestart/restart.go+++ b/internal/strategy/autorestart/restart.go@@ -117,7 +117,6 @@ func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {}slog.Warn(s.logPrefix("instance crashed, scheduling restart"), args...)- // Emit restarting event.if s.orch != nil {s.orch.EmitEvent("instance.restarting", &bridge.Instance{ID: crashedID,@@ -125,7 +124,6 @@ func (s *Strategy) handleCrash(ctx context.Context, crashedID string) {})}- // Wait for backoff period (respecting cancellation).select {case <-time.After(backoff):case <-ctx.Done():diff --git a/internal/urls/urls.go b/internal/urls/urls.goindex 6d324bab..7c3f8160 100644--- a/internal/urls/urls.go+++ b/internal/urls/urls.go@@ -22,7 +22,6 @@ func Sanitize(rawURL string) (string, error) {return "", fmt.Errorf("empty URL")}- // If URL has an explicit scheme, pass it through unchangedif strings.Contains(rawURL, "://") ||strings.HasPrefix(rawURL, "javascript:") ||strings.HasPrefix(rawURL, "vbscript:") ||