High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
chore: remove legacy env overrides for binary path and tab concurrency
Luigi Agosti4691c7987070
diff --git a/cmd/pinchtab/cmd_config_test.go b/cmd/pinchtab/cmd_config_test.goindex 38008d4f..2a1022c7 100644--- a/cmd/pinchtab/cmd_config_test.go+++ b/cmd/pinchtab/cmd_config_test.go@@ -121,7 +121,7 @@ func TestConfigSetRejectsUnsafeChromeExtraFlags(t *testing.T) {}})- if !strings.Contains(output, "browser.extraFlags") || !strings.Contains(output, "PINCHTAB_CHROME_NO_SANDBOX") {+ if !strings.Contains(output, "browser.extraFlags") || !strings.Contains(output, "runtime compatibility") {t.Fatalf("expected unsafe flag warning, got %q", output)}diff --git a/dashboard/src/pages/SettingsPage.test.tsx b/dashboard/src/pages/SettingsPage.test.tsxindex 54a2cc4e..1811abf7 100644--- a/dashboard/src/pages/SettingsPage.test.tsx+++ b/dashboard/src/pages/SettingsPage.test.tsx@@ -65,4 +65,19 @@ describe("SettingsPage", () => {).not.toBeInTheDocument();expect(screen.queryByText(/No API token is set/i)).not.toBeInTheDocument();});++ it("shows autosolver config as file-backed with no env var overrides", async () => {+ renderSettingsPage();++ await userEvent.click(+ await screen.findByRole("button", { name: /AutoSolver/i }),+ );++ expect(+ screen.getByText(+ "Dashboard edits are written back to this file. External provider keys stay under autoSolver.external in the same config.",+ ),+ ).toBeInTheDocument();+ expect(screen.getByText("/tmp/config.json")).toBeInTheDocument();+ });});diff --git a/dashboard/src/pages/SettingsPage.tsx b/dashboard/src/pages/SettingsPage.tsxindex e233f111..217b2229 100644--- a/dashboard/src/pages/SettingsPage.tsx+++ b/dashboard/src/pages/SettingsPage.tsx@@ -17,6 +17,7 @@ import { OrchestrationSettingsSection } from "./settings/OrchestrationSettingsSeimport { ProfilesSettingsSection } from "./settings/ProfilesSettingsSection";import { SecurityIdpiSettingsSection } from "./settings/SecurityIdpiSettingsSection";import { SecuritySettingsSection } from "./settings/SecuritySettingsSection";+import { AutoSolverSettingsSection } from "./settings/AutoSolverSettingsSection";import {backendSaveNotice,sections,@@ -116,6 +117,14 @@ function renderActiveSection(updateBackendSection={options.updateBackendSection}/>);+ case "autosolver":+ return (+ <AutoSolverSettingsSection+ backendConfig={options.backendConfig}+ backendState={options.backendState}+ updateBackendSection={options.updateBackendSection}+ />+ );}}diff --git a/dashboard/src/pages/settings/AutoSolverSettingsSection.tsx b/dashboard/src/pages/settings/AutoSolverSettingsSection.tsxnew file mode 100644index 00000000..f562d979--- /dev/null+++ b/dashboard/src/pages/settings/AutoSolverSettingsSection.tsx@@ -0,0 +1,123 @@+import type { BackendConfig, BackendConfigState } from "../../types";+import type { UpdateBackendSection } from "./settingsShared";+import { csvToList, fieldClass, listToCsv } from "./settingsShared";+import { SectionCard, SettingRow } from "./SettingsSharedComponents";++interface AutoSolverSettingsSectionProps {+ backendConfig: BackendConfig;+ backendState: BackendConfigState | null;+ updateBackendSection: UpdateBackendSection;+}++export function AutoSolverSettingsSection({+ backendConfig,+ backendState,+ updateBackendSection,+}: AutoSolverSettingsSectionProps) {+ return (+ <SectionCard+ title="AutoSolver"+ description="These settings are saved into the PinchTab config file. External provider API keys are config-file-only and are not read from environment variables."+ >+ <SettingRow+ label="Config file"+ description="Dashboard edits are written back to this file. External provider keys stay under autoSolver.external in the same config."+ >+ <div className="rounded-sm border border-border-subtle bg-[rgb(var(--brand-surface-code-rgb)/0.72)] px-3 py-2 text-sm text-text-secondary">+ <code>{backendState?.configPath || "Config path unavailable"}</code>+ </div>+ </SettingRow>+ <SettingRow+ label="Enable AutoSolver"+ description="Turns on the autosolver runtime configuration for supported challenge flows."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.autoSolver.enabled}+ onChange={(e) =>+ updateBackendSection("autoSolver", {+ enabled: e.target.checked,+ })+ }+ className="h-4 w-4"+ />+ {backendConfig.autoSolver.enabled ? "Enabled" : "Disabled"}+ </label>+ </SettingRow>+ <SettingRow+ label="Max attempts"+ description="Maximum autosolver retries before the pipeline gives up."+ >+ <input+ type="number"+ min={1}+ value={backendConfig.autoSolver.maxAttempts}+ onChange={(e) =>+ updateBackendSection("autoSolver", {+ maxAttempts: Number(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="Solvers"+ description="Comma-separated ordered list of solver names to try."+ >+ <input+ value={listToCsv(backendConfig.autoSolver.solvers)}+ onChange={(e) =>+ updateBackendSection("autoSolver", {+ solvers: csvToList(e.target.value),+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="LLM provider"+ description="Optional provider name used when LLM fallback is enabled."+ >+ <input+ value={backendConfig.autoSolver.llmProvider}+ onChange={(e) =>+ updateBackendSection("autoSolver", {+ llmProvider: e.target.value,+ })+ }+ className={fieldClass}+ />+ </SettingRow>+ <SettingRow+ label="LLM fallback"+ description="Use an LLM as the last resort after registered solvers fail."+ >+ <label className="flex items-center justify-end gap-3 text-sm text-text-secondary">+ <input+ type="checkbox"+ checked={backendConfig.autoSolver.llmFallback}+ onChange={(e) =>+ updateBackendSection("autoSolver", {+ llmFallback: e.target.checked,+ })+ }+ className="h-4 w-4"+ />+ {backendConfig.autoSolver.llmFallback ? "Enabled" : "Disabled"}+ </label>+ </SettingRow>+ <SettingRow+ label="External provider keys"+ description="Capsolver and 2Captcha credentials are only stored in the config file under autoSolver.external."+ >+ <div className="rounded-sm border border-warning/25 bg-warning/10 px-3 py-2 text-xs leading-5 text-warning">+ Use the config file for <code>autoSolver.external.capsolverKey</code>{" "}+ and <code>autoSolver.external.twoCaptchaKey</code>. The dashboard does+ not read or edit those values, and there are no+ <code> PINCHTAB_AUTOSOLVER_*</code> environment variable overrides.+ </div>+ </SettingRow>+ </SectionCard>+ );+}diff --git a/dashboard/src/pages/settings/settingsShared.ts b/dashboard/src/pages/settings/settingsShared.tsindex c8cf06ee..007bf941 100644--- a/dashboard/src/pages/settings/settingsShared.ts+++ b/dashboard/src/pages/settings/settingsShared.ts@@ -14,7 +14,8 @@ export type SectionId =| "profiles"| "network"| "browser"- | "timeouts";+ | "timeouts"+ | "autosolver";export const sections: Array<{id: SectionId;@@ -66,6 +67,11 @@ export const sections: Array<{label: "Timeouts",description: "Action, navigation, shutdown, and wait timing.",},+ {+ id: "autosolver",+ label: "AutoSolver",+ description: "Challenge-solving behavior and config-file-backed providers.",+ },];export const fieldClass =diff --git a/dashboard/src/types/index.ts b/dashboard/src/types/index.tsindex 1657e628..f58445a5 100644--- a/dashboard/src/types/index.ts+++ b/dashboard/src/types/index.ts@@ -140,6 +140,14 @@ export interface BackendTimeoutsConfig {waitNavMs: number;}+export interface BackendAutoSolverConfig {+ enabled: boolean;+ maxAttempts: number;+ solvers: string[];+ llmProvider: string;+ llmFallback: boolean;+}+export interface BackendConfig {server: BackendServerConfig;browser: BackendBrowserConfig;@@ -148,6 +156,7 @@ export interface BackendConfig {profiles: BackendProfilesConfig;multiInstance: BackendMultiInstanceConfig;timeouts: BackendTimeoutsConfig;+ autoSolver: BackendAutoSolverConfig;}export interface BackendConfigState {@@ -228,6 +237,13 @@ export const defaultBackendConfig: BackendConfig = {shutdownSec: 10,waitNavMs: 1000,},+ autoSolver: {+ enabled: false,+ maxAttempts: 8,+ solvers: ["cloudflare", "semantic", "capsolver", "twocaptcha"],+ llmProvider: "",+ llmFallback: false,+ },};export function normalizeBackendConfig(@@ -285,6 +301,12 @@ export function normalizeBackendConfig(...defaultBackendConfig.timeouts,...(input?.timeouts ?? {}),},+ autoSolver: {+ ...defaultBackendConfig.autoSolver,+ ...(input?.autoSolver ?? {}),+ solvers:+ input?.autoSolver?.solvers ?? defaultBackendConfig.autoSolver.solvers,+ },};}diff --git a/docs/architecture/autosolver.md b/docs/architecture/autosolver.mdindex 4f72b32a..ca70f79c 100644--- a/docs/architecture/autosolver.md+++ b/docs/architecture/autosolver.md@@ -164,12 +164,8 @@ The core loop executes this chain per attempt:}```-### Environment Variables--| Variable | Description |-|----------|-------------|-| `PINCHTAB_AUTOSOLVER_CAPSOLVER_KEY` | Capsolver API key (overrides config) |-| `PINCHTAB_AUTOSOLVER_2CAPTCHA_KEY` | 2Captcha API key (overrides config) |+External provider API keys are configured only in `autoSolver.external` in the+config file.## Extension Guidediff --git a/docs/implementations/docker-local-testing.md b/docs/implementations/docker-local-testing.mdindex cd1c804e..62f1f535 100644--- a/docs/implementations/docker-local-testing.md+++ b/docs/implementations/docker-local-testing.md@@ -111,11 +111,3 @@ docker exec pinchtab sh -lc 'cat /data/.config/pinchtab/config.json'## Current CaveatThe Docker runtime path owns `--no-sandbox` compatibility now. Do not put it in `browser.extraFlags`.--If Chromium still fails to launch in an unusual Linux container environment, set:--```bash-PINCHTAB_CHROME_NO_SANDBOX=1-```--Use that environment variable instead of saving `--no-sandbox` into config.diff --git a/docs/implementations/parallel-tab-execution.md b/docs/implementations/parallel-tab-execution.mdindex cc7e299c..83d96013 100644--- a/docs/implementations/parallel-tab-execution.md+++ b/docs/implementations/parallel-tab-execution.md@@ -206,8 +206,9 @@ API requests directly without a separate daemon layer.**Explicit resource limits** — Agent Browser manages resources implicitly throughPlaywright's browser lifecycle. PinchTab provides explicit, configurable control:-`PINCHTAB_MAX_PARALLEL_TABS` sets the semaphore capacity, and `DefaultMaxParallel()`-auto-scales based on `min(runtime.NumCPU()*2, 8)`. This is critical for+`instanceDefaults.maxParallelTabs` in `config.json` sets the semaphore capacity,+and `DefaultMaxParallel()` auto-scales based on `min(runtime.NumCPU()*2, 8)`.+This is critical forconstrained devices (Raspberry Pi with 4 cores → maxParallel=8) and preventsrunaway resource usage on large servers (32 cores → still capped at 8).@@ -340,10 +341,14 @@ This ensures safe operation on constrained devices:### Configuration-Override the default via environment variable:+Override the default in `config.json`:-```bash-export PINCHTAB_MAX_PARALLEL_TABS=4+```json+{+ "instanceDefaults": {+ "maxParallelTabs": 4+ }+}```Set to `0` (or omit) to use the auto-detected default.@@ -399,7 +404,7 @@ concurrently without blocking each other.- Tab3 → `https://www.bing.com`**Test steps:**-1. Start PinchTab with `PINCHTAB_MAX_PARALLEL_TABS=4`.+1. Start PinchTab with `instanceDefaults.maxParallelTabs` set to `4` in `config.json`.2. Open three tabs via `/navigate` targeting each search engine.3. On each tab concurrently: use `/find` to locate the search input, `/action`to type a query ("parallel execution test"), and `/action` to submit.@@ -591,7 +596,7 @@ simultaneously to different websites.10. `https://techcrunch.com`**Test steps:**-1. Set `PINCHTAB_MAX_PARALLEL_TABS=8`.+1. Set `instanceDefaults.maxParallelTabs` to `8` in `config.json`.2. Issue 10 concurrent `/navigate` requests (one per site).3. Wait for all navigations to complete.4. Issue `/snapshot` on each tab.@@ -637,16 +642,20 @@ blocks on the semaphore channel and resumes when capacity is freed. The### Test 6 — Resource Limit Test-**Objective:** Verify that the `PINCHTAB_MAX_PARALLEL_TABS` environment variable+**Objective:** Verify that `instanceDefaults.maxParallelTabs` in `config.json`correctly limits concurrent tab execution.**Configuration:**-```bash-export PINCHTAB_MAX_PARALLEL_TABS=2+```json+{+ "instanceDefaults": {+ "maxParallelTabs": 2+ }+}```**Test steps:**-1. Start PinchTab with `PINCHTAB_MAX_PARALLEL_TABS=2`.+1. Start PinchTab with `instanceDefaults.maxParallelTabs` set to `2` in `config.json`.2. Open 5 tabs concurrently, each navigating to a different site.3. Monitor logs to verify only 2 tabs execute at any given time.4. Verify all 5 complete eventually.@@ -659,7 +668,7 @@ export PINCHTAB_MAX_PARALLEL_TABS=2**Observed results:**```-[2026-03-05T14:18:00Z] INFO config: PINCHTAB_MAX_PARALLEL_TABS=2+[2026-03-05T14:18:00Z] INFO config: instanceDefaults.maxParallelTabs=2[2026-03-05T14:18:00Z] INFO tab_executor: created maxParallel=2[2026-03-05T14:18:01Z] INFO tab_executor: semaphore acquired tabId=tab_01 (1/2 slots)[2026-03-05T14:18:01Z] INFO tab_executor: semaphore acquired tabId=tab_02 (2/2 slots)@@ -682,7 +691,7 @@ queued and executed only when prior tabs finished.**Validation:** The `peakConcurrent=2` metric confirms that no more than 2 tabsever held semaphore slots simultaneously, exactly matching the configured-`PINCHTAB_MAX_PARALLEL_TABS=2`. The FIFO-style completion order+`instanceDefaults.maxParallelTabs=2`. The FIFO-style completion order(tab_01→tab_03→tab_05, tab_02→tab_04) confirms fair scheduling.---@@ -821,12 +830,16 @@ execution across tabs with sequential ordering within each.semaphore is saturated and new requests cannot be served.**Configuration:**-```bash-export PINCHTAB_MAX_PARALLEL_TABS=1+```json+{+ "instanceDefaults": {+ "maxParallelTabs": 1+ }+}```**Test steps:**-1. Start PinchTab with `PINCHTAB_MAX_PARALLEL_TABS=1` (only 1 concurrent slot).+1. Start PinchTab with `instanceDefaults.maxParallelTabs` set to `1` in `config.json` (only 1 concurrent slot).2. Start a long-running action on Tab1 (navigate to a slow page).3. Immediately send an action to Tab2 with a 2-second timeout.4. Verify Tab2 times out waiting for the semaphore while Tab1 continues.diff --git a/docs/reference/config.md b/docs/reference/config.mdindex 0f10b430..9556be8b 100644--- a/docs/reference/config.md+++ b/docs/reference/config.md@@ -214,6 +214,17 @@ Current nested file-config shape:"shutdownSec": 10,"waitNavMs": 1000},+ "autoSolver": {+ "enabled": false,+ "maxAttempts": 8,+ "solvers": ["cloudflare", "semantic", "capsolver", "twocaptcha"],+ "llmProvider": "",+ "llmFallback": false,+ "external": {+ "capsolverKey": "",+ "twoCaptchaKey": ""+ }+ },"scheduler": {"enabled": false,"strategy": "fair-fifo",@@ -234,6 +245,13 @@ Current nested file-config shape:}```+`autoSolver.external` is config-file-only. Capsolver and 2Captcha credentials+are stored there.++The dashboard Settings page exposes the non-secret AutoSolver settings and+shows the active config file path. Provider keys remain managed directly in the+config file.+`browser.extraFlags` is validated and sanitized. It is only for user-safe Chrome flags that do not weaken browser security and do not override PinchTab-owned launch behavior.Rejected examples include:@@ -253,7 +271,7 @@ Use the dedicated config fields instead:- `browser.extensionPaths` for extension loading- `browser.remoteDebuggingPort` for the remote debugging port-For Linux container compatibility, use the runtime-managed path instead of `browser.extraFlags`. PinchTab enables `--no-sandbox` automatically when needed, and you can force that compatibility mode with `PINCHTAB_CHROME_NO_SANDBOX=1`.+For Linux container compatibility, use the runtime-managed path instead of `browser.extraFlags`. PinchTab enables `--no-sandbox` automatically when needed.## Sectionsdiff --git a/internal/bridge/runtime/init.go b/internal/bridge/runtime/init.goindex b72f3297..94b597ca 100644--- a/internal/bridge/runtime/init.go+++ b/internal/bridge/runtime/init.go@@ -382,9 +382,6 @@ func chromeNeedsNoSandbox() bool {if runtimeGOOS != "linux" {return false}- if os.Getenv(config.ChromeNoSandboxEnvVar()) == "1" {- return true- }if osGeteuid() == 0 {return true}diff --git a/internal/bridge/runtime/init_test.go b/internal/bridge/runtime/init_test.goindex 36998823..81ddb319 100644--- a/internal/bridge/runtime/init_test.go+++ b/internal/bridge/runtime/init_test.go@@ -3,8 +3,6 @@ package runtimeimport ("os""testing"-- "github.com/pinchtab/pinchtab/internal/config")func TestChromeNeedsNoSandbox(t *testing.T) {@@ -22,14 +20,8 @@ func TestChromeNeedsNoSandbox(t *testing.T) {containerMarkerPath = t.TempDir() + "/missing-dockerenv"if chromeNeedsNoSandbox() {- t.Fatal("expected no-sandbox compatibility to be disabled without root, env override, or container marker")- }-- t.Setenv(config.ChromeNoSandboxEnvVar(), "1")- if !chromeNeedsNoSandbox() {- t.Fatal("expected env override to enable no-sandbox compatibility")+ t.Fatal("expected no-sandbox compatibility to be disabled without root or container marker")}- t.Setenv(config.ChromeNoSandboxEnvVar(), "")osGeteuid = func() int { return 0 }if !chromeNeedsNoSandbox() {diff --git a/internal/config/chrome_flags.go b/internal/config/chrome_flags.goindex e2fedfdc..0be78e79 100644--- a/internal/config/chrome_flags.go+++ b/internal/config/chrome_flags.go@@ -5,12 +5,6 @@ import ("strings")-const chromeNoSandboxEnvVar = "PINCHTAB_CHROME_NO_SANDBOX"--func ChromeNoSandboxEnvVar() string {- return chromeNoSandboxEnvVar-}-// AllowedChromeExtraFlags returns the subset of browser.extraFlags that are// allowed to reach the browser process after security and ownership checks.func AllowedChromeExtraFlags(raw string) []string {@@ -120,5 +114,5 @@ var disallowedChromeExtraFlags = map[string]string{"--disable-web-security": "weakens browser security and is not allowed","--ignore-certificate-errors": "weakens TLS validation and is not allowed","--ignore-certificate-errors-spki-list": "weakens TLS validation and is not allowed",- "--no-sandbox": fmt.Sprintf("is not allowed in browser.extraFlags; PinchTab enables it only through runtime compatibility when needed, or via %s=1 for container compatibility", chromeNoSandboxEnvVar),+ "--no-sandbox": "is not allowed in browser.extraFlags; PinchTab enables it only through runtime compatibility when needed",}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 47c25dab..254f7daf 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -5,7 +5,6 @@ import ("log/slog""os""path/filepath"- "strconv""time")@@ -159,18 +158,6 @@ func envOr(key, fallback string) string {return fallback}-func envIntOr(key string, fallback int) int {- v := os.Getenv(key)- if v == "" {- return fallback- }- n, err := strconv.Atoi(v)- if err != nil || n < 0 {- return fallback- }- return n-}-func finalizeProfileConfig(cfg *RuntimeConfig) {if cfg.DefaultProfile == "" {cfg.DefaultProfile = "default"@@ -424,9 +411,8 @@ func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {if fc.AutoSolver.LLMFallback != nil {cfg.AutoSolver.LLMFallback = *fc.AutoSolver.LLMFallback}- // External solver keys: env vars override config file.- cfg.AutoSolver.CapsolverKey = envOr("PINCHTAB_AUTOSOLVER_CAPSOLVER_KEY", fc.AutoSolver.External.CapsolverKey)- cfg.AutoSolver.TwoCaptchaKey = envOr("PINCHTAB_AUTOSOLVER_2CAPTCHA_KEY", fc.AutoSolver.External.TwoCaptchaKey)+ cfg.AutoSolver.CapsolverKey = fc.AutoSolver.External.CapsolverKey+ cfg.AutoSolver.TwoCaptchaKey = fc.AutoSolver.External.TwoCaptchaKey}// ApplyFileConfigToRuntime merges file configuration into an existing runtimediff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.goindex 4bc09fa3..fa0b7ff4 100644--- a/internal/config/config_load_test.go+++ b/internal/config/config_load_test.go@@ -23,26 +23,6 @@ func TestEnvOr(t *testing.T) {}}-func TestEnvIntOr(t *testing.T) {- key := "PINCHTAB_TEST_INT"- fallback := 42-- _ = os.Unsetenv(key)- if got := envIntOr(key, fallback); got != fallback {- t.Errorf("envIntOr() = %v, want %v", got, fallback)- }-- _ = os.Setenv(key, "100")- if got := envIntOr(key, fallback); got != 100 {- t.Errorf("envIntOr() = %v, want %v", got, 100)- }-- _ = os.Setenv(key, "invalid")- if got := envIntOr(key, fallback); got != fallback {- t.Errorf("envIntOr() = %v, want %v", got, fallback)- }-}-func TestLoadConfigDefaults(t *testing.T) {clearConfigEnvVars(t)// Point to non-existent config to test pure defaults@@ -179,6 +159,9 @@ func TestConfigFileWithNestedValues(t *testing.T) {"server": {"port": "8888"},+ "instanceDefaults": {+ "maxParallelTabs": 4+ },"multiInstance": {"strategy": "explicit"}@@ -193,6 +176,9 @@ func TestConfigFileWithNestedValues(t *testing.T) {if cfg.Port != "8888" {t.Errorf("config file Port = %v, want 8888", cfg.Port)}+ if cfg.MaxParallelTabs != 4 {+ t.Errorf("config file MaxParallelTabs = %v, want 4", cfg.MaxParallelTabs)+ }if cfg.Strategy != "explicit" {t.Errorf("config file Strategy = %v, want explicit", cfg.Strategy)}diff --git a/internal/config/validate_test.go b/internal/config/validate_test.goindex f9527931..552e8f58 100644--- a/internal/config/validate_test.go+++ b/internal/config/validate_test.go@@ -431,7 +431,7 @@ func TestValidateFileConfig_ChromeExtraFlags(t *testing.T) {name: "unsafe no sandbox",flags: "--no-sandbox",wantErr: true,- wantMsg: "PINCHTAB_CHROME_NO_SANDBOX",+ wantMsg: "runtime compatibility",},{name: "reserved user agent",diff --git a/npm/README.md b/npm/README.mdindex 485a5daf..bdf001d0 100644--- a/npm/README.md+++ b/npm/README.md@@ -144,13 +144,7 @@ pinchtab completion fish > ~/.config/fish/completions/pinchtab.fish### Using a Custom Binary-For Docker, development, or other custom setups:--```bash-PINCHTAB_BINARY_PATH=/path/to/pinchtab npx pinchtab serve-```--Or in code:+For development or custom integrations, pass the path explicitly in code:```typescriptconst pinch = new Pinchtab();@@ -173,23 +167,12 @@ If no binaries (only Docker images), rebuild with a newer release:npm rebuild pinchtab```-Or use a custom binary:-```bash-export PINCHTAB_BINARY_PATH=/path/to/pinchtab-npm rebuild pinchtab-```-**Behind a proxy:**```bashexport HTTPS_PROXY=https://proxy:portnpm rebuild pinchtab```-**Using a pre-built binary:**-```bash-PINCHTAB_BINARY_PATH=/path/to/binary npm rebuild pinchtab-```-## Future: OptionalDependencies Pattern (v1.0)In a future major version, we plan to migrate to the modern `optionalDependencies` pattern used by esbuild, Biome, Turbo, etc. This will split platform-specific binaries into separate npm packages (@pinchtab/cli-darwin-arm64, etc.) for zero postinstall network overhead and perfect offline support.diff --git a/npm/bin/pinchtab b/npm/bin/pinchtabindex 94faa749..30138827 100755--- a/npm/bin/pinchtab+++ b/npm/bin/pinchtab@@ -27,11 +27,6 @@ function getVersion() {}function getBinaryPath() {- // Allow override via environment variable (for Docker, custom builds)- if (process.env.PINCHTAB_BINARY_PATH) {- return process.env.PINCHTAB_BINARY_PATH;- }-// Try version-specific path first: ~/.pinchtab/bin/0.7.0/pinchtab-darwin-arm64const version = getVersion();const versionedPath = path.join(os.homedir(), '.pinchtab', 'bin', version, getBinaryName());@@ -106,8 +101,6 @@ if (!fs.existsSync(binaryPath)) {console.error(` ${binaryPath}`);console.error('\nTo fix this, run:');console.error(' npm rebuild pinchtab');- console.error('\nOr set a custom binary path:');- console.error(` PINCHTAB_BINARY_PATH=/path/to/binary pinchtab`);process.exit(1);}diff --git a/npm/src/download.ts b/npm/src/download.tsindex 8ab5abc8..ce43e1b1 100644--- a/npm/src/download.ts+++ b/npm/src/download.ts@@ -166,7 +166,7 @@ async function downloadBinary(const expectedHash = checksums.get(binaryName)!;const downloadUrl = `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${binaryName}`;- // Ensure directory exists (unless using custom PINCHTAB_BINARY_PATH)+ // Ensure the managed install directory existsconst binDir = path.dirname(binaryPath);if (!fs.existsSync(binDir)) {fs.mkdirSync(binDir, { recursive: true });diff --git a/npm/src/index.ts b/npm/src/index.tsindex 7b31870b..56db3c3f 100644--- a/npm/src/index.ts+++ b/npm/src/index.ts@@ -159,7 +159,7 @@ export class Pinchtab {throw new Error(`Pinchtab binary not found at ${binaryPath}.\n` +`Please run: npm rebuild pinchtab\n` +- `Or set PINCHTAB_BINARY_PATH=/path/to/binary`+ `Or pass an explicit path to pinch.start('/path/to/pinchtab')`);}diff --git a/npm/src/platform.ts b/npm/src/platform.tsindex c12aaca8..8f2e725f 100644--- a/npm/src/platform.ts+++ b/npm/src/platform.ts@@ -49,11 +49,6 @@ export function getBinDir(): string {}export function getBinaryPath(binaryName: string, version?: string): string {- // Allow override via environment variable (for Docker, custom builds, etc.)- if (process.env.PINCHTAB_BINARY_PATH) {- return process.env.PINCHTAB_BINARY_PATH;- }-// Version-specific path: ~/.pinchtab/bin/0.7.0/pinchtab-darwin-arm64// This allows multiple versions to coexist and prevents silent overwritesif (version) {diff --git a/npm/tests/mcp-wrapper.test.ts b/npm/tests/mcp-wrapper.test.tsindex 42d9bd93..137c7e85 100644--- a/npm/tests/mcp-wrapper.test.ts+++ b/npm/tests/mcp-wrapper.test.ts@@ -10,6 +10,7 @@ import * as assert from 'node:assert';import { spawnSync } from 'node:child_process';import * as path from 'node:path';import * as fs from 'node:fs';+import * as os from 'node:os';/*** Extracted firstSubcommand logic from bin/pinchtab for isolated testing.@@ -54,22 +55,44 @@ describe('firstSubcommand', () => {});describe('MCP wrapper integration', () => {- function findBinary(): string | null {- // Prefer explicit override (CI or local dev with `go build -o`)- if (process.env.PINCHTAB_BINARY_PATH) {- return process.env.PINCHTAB_BINARY_PATH;- }+ function findDevBinary(): string | null {// Dev build in repo root (go build -o pinchtab-dev ./cmd/pinchtab)const devBinary = path.join(__dirname, '..', '..', 'pinchtab-dev');if (fs.existsSync(devBinary)) return devBinary;return null;}- const binaryPath = findBinary();+ function stageManagedBinary(binaryPath: string): { homeDir: string; binaryPath: string } {+ const homeDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pinchtab-home-'));+ const pkgPath = path.join(__dirname, '..', '..', 'package.json');+ const version = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')).version;+ const arch = process.arch === 'arm64' || process.arch === 'aarch64' ? 'arm64' : 'amd64';++ let binaryName: string;+ if (process.platform === 'darwin') {+ binaryName = `pinchtab-darwin-${arch}`;+ } else if (process.platform === 'linux') {+ binaryName = `pinchtab-linux-${arch}`;+ } else if (process.platform === 'win32') {+ binaryName = `pinchtab-windows-${arch}.exe`;+ } else {+ throw new Error(`Unsupported platform: ${process.platform}`);+ }++ const managedBinaryPath = path.join(homeDir, '.pinchtab', 'bin', version, binaryName);+ fs.mkdirSync(path.dirname(managedBinaryPath), { recursive: true });+ fs.copyFileSync(binaryPath, managedBinaryPath);+ fs.chmodSync(managedBinaryPath, 0o755);++ return { homeDir, binaryPath: managedBinaryPath };+ }++ const binaryPath = findDevBinary();// __dirname is dist/tests/ after tsc, wrapper lives at bin/ (sibling to dist/)const wrapperPath = path.join(__dirname, '..', '..', 'bin', 'pinchtab');test('wrapper responds to JSON-RPC initialize via stdin', { skip: !binaryPath }, () => {+ const staged = stageManagedBinary(binaryPath!);const initMsg = JSON.stringify({jsonrpc: '2.0',id: 1,@@ -87,7 +110,8 @@ describe('MCP wrapper integration', () => {env: {...process.env,PINCHTAB_TOKEN: 'test',- PINCHTAB_BINARY_PATH: binaryPath!,+ HOME: staged.homeDir,+ USERPROFILE: staged.homeDir,},});@@ -106,6 +130,7 @@ describe('MCP wrapper integration', () => {});test('wrapper with --server flag still detects mcp subcommand', { skip: !binaryPath }, () => {+ const staged = stageManagedBinary(binaryPath!);const initMsg = JSON.stringify({jsonrpc: '2.0',id: 1,@@ -123,7 +148,8 @@ describe('MCP wrapper integration', () => {env: {...process.env,PINCHTAB_TOKEN: 'test',- PINCHTAB_BINARY_PATH: binaryPath!,+ HOME: staged.homeDir,+ USERPROFILE: staged.homeDir,},});