High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: surface actionable instance port conflicts before launch
Luigi Agostid76049d17ad9
diff --git a/.github/workflows/reusable-docker-smoke.yml b/.github/workflows/reusable-docker-smoke.ymlindex 365cd5a9..d7cc523e 100644--- a/.github/workflows/reusable-docker-smoke.yml+++ b/.github/workflows/reusable-docker-smoke.yml@@ -34,5 +34,10 @@ jobs:env:DOCKER_BUILDKIT: 1+ - name: Verify instance port conflict detection+ run: bash scripts/docker-port-conflict-smoke.sh pinchtab-chrome-cft-smoke:${{ github.run_id }}+ env:+ DOCKER_BUILDKIT: 1+- name: Verify MCP stdio in containerrun: bash scripts/docker-mcp-smoke.sh pinchtab-release-smoke:${{ github.run_id }}diff --git a/internal/orchestrator/handlers_instances_test.go b/internal/orchestrator/handlers_instances_test.goindex 4d01df1a..139a2486 100644--- a/internal/orchestrator/handlers_instances_test.go+++ b/internal/orchestrator/handlers_instances_test.go@@ -31,6 +31,7 @@ func TestHandleLaunchByNameAliasesStartSemantics(t *testing.T) {old := processAliveFuncprocessAliveFunc = func(pid int) bool { return pid > 0 }defer func() { processAliveFunc = old }()+ stubPortAvailability(t, func(int) bool { return true })baseDir := t.TempDir()runner := &mockRunner{portAvail: true}diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.goindex c82d1a98..0f5fe02c 100644--- a/internal/orchestrator/orchestrator.go+++ b/internal/orchestrator/orchestrator.go@@ -293,9 +293,12 @@ func (o *Orchestrator) Launch(name, port string, headless bool, extensionPaths [return nil, fmt.Errorf("profile %q already has an active instance (%s)", name, inst.Status)}}- if !o.runner.IsPortAvailable(port) {+ portInspection := o.runner.InspectPort(port)+ if !portInspection.Available {o.mu.Unlock()- return nil, fmt.Errorf("port %s is already in use on this machine", port)+ err := portConflictError(port, portInspection)+ slog.Error("instance launch blocked by port conflict", "profile", name, "port", port, "pid", portInspection.PID, "command", portInspection.Command, "error", err.Error())+ return nil, err}profileID := o.idMgr.ProfileID(name)@@ -382,6 +385,20 @@ func (o *Orchestrator) childInstanceBaseURL(port string) string {return httpBaseURL(host, port)}+func portConflictError(port string, inspection PortInspection) error {+ if inspection.PID > 0 {+ process := fmt.Sprintf("pid %d", inspection.PID)+ if command := strings.TrimSpace(inspection.Command); command != "" {+ process = fmt.Sprintf("%s (%s)", process, command)+ }+ if strings.Contains(strings.ToLower(inspection.Command), "pinchtab") {+ return fmt.Errorf("instance port %s is already in use by %s; stop the stale process and restart PinchTab, for example: kill %d", port, process, inspection.PID)+ }+ return fmt.Errorf("instance port %s is already in use by %s; stop the process and restart PinchTab, for example: kill %d", port, process, inspection.PID)+ }+ return fmt.Errorf("instance port %s is already in use on this machine", port)+}+func (o *Orchestrator) writeChildConfig(port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string) (string, error) {fc := config.FileConfigFromRuntime(o.runtimeCfg)fc.Server.Port = portdiff --git a/internal/orchestrator/port_inspect.go b/internal/orchestrator/port_inspect.gonew file mode 100644index 00000000..40b3ef57--- /dev/null+++ b/internal/orchestrator/port_inspect.go@@ -0,0 +1,184 @@+package orchestrator++import (+ "bufio"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ goruntime "runtime"+ "strconv"+ "strings"+)++func inspectPort(port string) PortInspection {+ portNum, err := parsePortNumber(port)+ if err != nil {+ return PortInspection{}+ }+ if isPortAvailable(port) {+ return PortInspection{Available: true}+ }++ pid, command, ok := findListeningProcess(portNum)+ if !ok {+ return PortInspection{}+ }+ return PortInspection{+ Available: false,+ PID: pid,+ Command: command,+ }+}++func findListeningProcess(port int) (int, string, bool) {+ if goruntime.GOOS == "linux" {+ if pid, command, ok := findListeningProcessLinux(port); ok {+ return pid, command, true+ }+ }+ return findListeningProcessLsof(port)+}++func findListeningProcessLinux(port int) (int, string, bool) {+ inodes := map[string]struct{}{}+ collectListeningSocketInodes(filepath.Join("/proc", "net", "tcp"), port, inodes)+ collectListeningSocketInodes(filepath.Join("/proc", "net", "tcp6"), port, inodes)+ if len(inodes) == 0 {+ return 0, "", false+ }++ entries, err := os.ReadDir("/proc")+ if err != nil {+ return 0, "", false+ }+ for _, entry := range entries {+ if !entry.IsDir() {+ continue+ }+ pid, err := strconv.Atoi(entry.Name())+ if err != nil {+ continue+ }+ fdDir := filepath.Join("/proc", entry.Name(), "fd")+ fds, err := os.ReadDir(fdDir)+ if err != nil {+ continue+ }+ for _, fd := range fds {+ target, err := os.Readlink(filepath.Join(fdDir, fd.Name()))+ if err != nil {+ continue+ }+ inode, ok := socketInodeFromSymlink(target)+ if !ok {+ continue+ }+ if _, exists := inodes[inode]; !exists {+ continue+ }+ return pid, readLinuxProcessCommand(pid), true+ }+ }+ return 0, "", false+}++func collectListeningSocketInodes(path string, port int, inodes map[string]struct{}) {+ file, err := os.Open(path)+ if err != nil {+ return+ }+ defer func() { _ = file.Close() }()++ scanner := bufio.NewScanner(file)+ first := true+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ if first {+ first = false+ continue+ }+ fields := strings.Fields(line)+ if len(fields) < 10 {+ continue+ }+ if fields[3] != "0A" {+ continue+ }+ if !matchesProcNetPort(fields[1], port) {+ continue+ }+ inodes[fields[9]] = struct{}{}+ }+}++func matchesProcNetPort(localAddress string, port int) bool {+ parts := strings.Split(localAddress, ":")+ if len(parts) < 2 {+ return false+ }+ portHex := parts[len(parts)-1]+ value, err := strconv.ParseInt(portHex, 16, 32)+ if err != nil {+ return false+ }+ return int(value) == port+}++func socketInodeFromSymlink(target string) (string, bool) {+ if !strings.HasPrefix(target, "socket:[") || !strings.HasSuffix(target, "]") {+ return "", false+ }+ return strings.TrimSuffix(strings.TrimPrefix(target, "socket:["), "]"), true+}++func readLinuxProcessCommand(pid int) string {+ cmdline, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "cmdline"))+ if err == nil {+ command := strings.TrimSpace(strings.ReplaceAll(string(cmdline), "\x00", " "))+ if command != "" {+ return command+ }+ }+ comm, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "comm"))+ if err == nil {+ return strings.TrimSpace(string(comm))+ }+ return ""+}++func findListeningProcessLsof(port int) (int, string, bool) {+ if _, err := exec.LookPath("lsof"); err != nil {+ return 0, "", false+ }++ cmd := exec.Command("lsof", "-nP", fmt.Sprintf("-iTCP:%d", port), "-sTCP:LISTEN", "-Fpc") // #nosec G204 -- static command, internal numeric port+ out, err := cmd.Output()+ if err != nil {+ return 0, "", false+ }++ var pid int+ var command string+ for _, line := range strings.Split(string(out), "\n") {+ if line == "" {+ continue+ }+ switch line[0] {+ case 'p':+ value, err := strconv.Atoi(strings.TrimSpace(line[1:]))+ if err == nil {+ pid = value+ }+ case 'c':+ command = strings.TrimSpace(line[1:])+ }+ if pid > 0 {+ return pid, command, true+ }+ }+ return 0, "", false+}diff --git a/internal/orchestrator/ports.go b/internal/orchestrator/ports.goindex ec9668b0..23ed4224 100644--- a/internal/orchestrator/ports.go+++ b/internal/orchestrator/ports.go@@ -78,9 +78,6 @@ func (pa *PortAllocator) ReservePort(port int) error {if pa.allocated[port] {return fmt.Errorf("port %d already reserved", port)}- if !portAvailableFunc(port) {- return fmt.Errorf("port %d is already in use", port)- }pa.allocated[port] = trueslog.Debug("reserved port", "port", port)return nildiff --git a/internal/orchestrator/process_test.go b/internal/orchestrator/process_test.goindex 9903da27..ff5defd8 100644--- a/internal/orchestrator/process_test.go+++ b/internal/orchestrator/process_test.go@@ -3,15 +3,18 @@ package orchestratorimport ("context""io"+ "strings""testing""github.com/pinchtab/pinchtab/internal/bridge"+ "github.com/pinchtab/pinchtab/internal/config""github.com/pinchtab/pinchtab/internal/ids")type mockRunner struct {runCalled boolportAvail bool+ portInfo PortInspectionargs []stringenv []stringrunErr error@@ -36,8 +39,11 @@ func (m *mockRunner) Run(ctx context.Context, binary string, args []string, envreturn &mockCmd{pid: 1234, isAlive: true}, nil}-func (m *mockRunner) IsPortAvailable(port string) bool {- return m.portAvail+func (m *mockRunner) InspectPort(port string) PortInspection {+ if m.portInfo != (PortInspection{}) {+ return m.portInfo+ }+ return PortInspection{Available: m.portAvail}}func TestLaunch_Mocked(t *testing.T) {@@ -78,6 +84,35 @@ func TestLaunch_PortConflict(t *testing.T) {}}+func TestLaunch_PortConflictIncludesProcessDetails(t *testing.T) {+ old := portAvailableFunc+ portAvailableFunc = func(int) bool { return true }+ defer func() { portAvailableFunc = old }()++ runner := &mockRunner{portInfo: PortInspection{+ Available: false,+ PID: 4321,+ Command: "pinchtab bridge",+ }}+ o := NewOrchestratorWithRunner(t.TempDir(), runner)+ o.ApplyRuntimeConfig(&config.RuntimeConfig{+ InstancePortStart: 9900,+ InstancePortEnd: 9902,+ })++ _, err := o.Launch("test-prof", "9901", true, nil)+ if err == nil {+ t.Fatal("expected error for unavailable port")+ }+ msg := err.Error()+ if !strings.Contains(msg, "instance port 9901 is already in use by pid 4321 (pinchtab bridge)") {+ t.Fatalf("expected detailed port conflict, got %q", msg)+ }+ if !strings.Contains(msg, "kill 4321") {+ t.Fatalf("expected kill suggestion, got %q", msg)+ }+}+func TestInstanceIsActive(t *testing.T) {tests := []struct {name stringdiff --git a/internal/orchestrator/runner.go b/internal/orchestrator/runner.goindex 6f9c644f..4c863896 100644--- a/internal/orchestrator/runner.go+++ b/internal/orchestrator/runner.go@@ -6,9 +6,15 @@ import ("os/exec")+type PortInspection struct {+ Available bool+ PID int+ Command string+}+type HostRunner interface {Run(ctx context.Context, binary string, args []string, env []string, stdout, stderr io.Writer) (Cmd, error)- IsPortAvailable(port string) bool+ InspectPort(port string) PortInspection}type Cmd interface {@@ -40,8 +46,8 @@ func (r *LocalRunner) Run(ctx context.Context, binary string, args []string, envreturn &localCmd{execCmd: cmd, cancel: cancel}, nil}-func (r *LocalRunner) IsPortAvailable(port string) bool {- return isPortAvailable(port)+func (r *LocalRunner) InspectPort(port string) PortInspection {+ return inspectPort(port)}func (c *localCmd) Wait() error {diff --git a/internal/strategy/autorestart/autorestart_test.go b/internal/strategy/autorestart/autorestart_test.goindex 7791c694..806463ea 100644--- a/internal/strategy/autorestart/autorestart_test.go+++ b/internal/strategy/autorestart/autorestart_test.go@@ -604,6 +604,6 @@ func (r *mockRunner) Run(_ context.Context, _ string, _ []string, _ []string, _,return &mockCmd{}, nil}-func (r *mockRunner) IsPortAvailable(_ string) bool {- return r.portAvail+func (r *mockRunner) InspectPort(_ string) orchestrator.PortInspection {+ return orchestrator.PortInspection{Available: r.portAvail}}diff --git a/internal/strategy/simple/simple_test.go b/internal/strategy/simple/simple_test.goindex b6479c08..12b9b606 100644--- a/internal/strategy/simple/simple_test.go+++ b/internal/strategy/simple/simple_test.go@@ -22,8 +22,8 @@ func (m *mockRunner) Run(context.Context, string, []string, []string, io.Writer,return nil, nil}-func (m *mockRunner) IsPortAvailable(string) bool {- return m.portAvail+func (m *mockRunner) InspectPort(string) orchestrator.PortInspection {+ return orchestrator.PortInspection{Available: m.portAvail}}// fakeBridge creates a test server that mimics a bridge instance.diff --git a/internal/strategy/strategy_test.go b/internal/strategy/strategy_test.goindex 11e4d9c4..36ef027a 100644--- a/internal/strategy/strategy_test.go+++ b/internal/strategy/strategy_test.go@@ -91,7 +91,9 @@ type mockRunner struct{}func (m *mockRunner) Run(_ context.Context, _ string, _ []string, _ []string, _ io.Writer, _ io.Writer) (orchestrator.Cmd, error) {return nil, nil}-func (m *mockRunner) IsPortAvailable(_ string) bool { return true }+func (m *mockRunner) InspectPort(_ string) orchestrator.PortInspection {+ return orchestrator.PortInspection{Available: true}+}func TestCacheRoutes_RegisteredAcrossStrategies(t *testing.T) {strategies := []string{"simple", "explicit", "no-instance", "simple-autorestart"}diff --git a/scripts/docker-port-conflict-smoke.sh b/scripts/docker-port-conflict-smoke.shnew file mode 100644index 00000000..8060bc11--- /dev/null+++ b/scripts/docker-port-conflict-smoke.sh@@ -0,0 +1,99 @@+#!/usr/bin/env bash+set -euo pipefail++IMAGE="${1:-pinchtab-chrome-cft-smoke:${RANDOM}${RANDOM}}"+NAME="pinchtab-port-conflict-smoke-${RANDOM}${RANDOM}"+TOKEN="chrome-cft-smoke-token"+FAILED=0++cleanup() {+ if docker ps -a --format '{{.Names}}' | grep -Fxq "$NAME"; then+ if [ "$FAILED" -ne 0 ]; then+ echo ""+ echo "Container logs:"+ docker logs "$NAME" || true+ fi+ docker rm -f "$NAME" >/dev/null 2>&1 || true+ fi+}+trap cleanup EXIT++echo "Building Ubuntu + Chrome for Testing smoke image..."+docker build \+ --platform linux/amd64 \+ -f tests/docker/chrome-cft-smoke.Dockerfile \+ -t "$IMAGE" \+ .++docker run -d \+ --platform linux/amd64 \+ --name "$NAME" \+ --shm-size=1g \+ -p 127.0.0.1::9867 \+ "$IMAGE" \+ bash -lc "nc -lk 127.0.0.1 9868 >/dev/null 2>&1 & sleep 1; exec pinchtab server" >/dev/null++HOST_PORT="$(docker port "$NAME" 9867/tcp | head -1 | awk -F: '{print $NF}')"+if [ -z "$HOST_PORT" ]; then+ FAILED=1+ echo "failed to determine published host port"+ exit 1+fi++health_check() {+ curl -sS -o /dev/null -H "Authorization: Bearer ${TOKEN}" "http://127.0.0.1:${HOST_PORT}/health"+}++echo "Waiting for dashboard health on port $HOST_PORT..."+for _ in $(seq 1 30); do+ if health_check; then+ break+ fi+ sleep 1+done++if ! health_check; then+ FAILED=1+ echo "dashboard health check did not pass"+ exit 1+fi++NC_PID="$(docker exec "$NAME" sh -lc "ps -eo pid,args | awk '/nc -lk 127.0.0.1 9868/ && !/awk/ {print \$1; exit}'" | tr -d '\r' | xargs)"+if [ -z "$NC_PID" ]; then+ FAILED=1+ echo "failed to locate the synthetic conflicting listener"+ exit 1+fi++RESPONSE_BODY="$(mktemp)"+HTTP_CODE="$(curl -sS -o "$RESPONSE_BODY" -w '%{http_code}' \+ -H "Authorization: Bearer ${TOKEN}" \+ -H "Content-Type: application/json" \+ -X POST \+ -d '{"port":"9868"}' \+ "http://127.0.0.1:${HOST_PORT}/instances/start")"++if [ "$HTTP_CODE" != "409" ]; then+ FAILED=1+ echo "expected HTTP 409 for explicit port conflict, got $HTTP_CODE"+ cat "$RESPONSE_BODY" || true+ exit 1+fi++if ! grep -Fq "instance port 9868 is already in use by pid " "$RESPONSE_BODY"; then+ FAILED=1+ echo "detailed port conflict message missing from response"+ cat "$RESPONSE_BODY" || true+ exit 1+fi++if ! grep -Fq "for example: kill " "$RESPONSE_BODY"; then+ FAILED=1+ echo "kill suggestion missing from response"+ cat "$RESPONSE_BODY" || true+ exit 1+fi++rm -f "$RESPONSE_BODY"++echo "Port conflict smoke test passed."diff --git a/tests/docker/chrome-cft-smoke.Dockerfile b/tests/docker/chrome-cft-smoke.Dockerfileindex 8e15ef8d..c274be89 100644--- a/tests/docker/chrome-cft-smoke.Dockerfile+++ b/tests/docker/chrome-cft-smoke.Dockerfile@@ -54,6 +54,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \libxshmfence1 \libxss1 \libxtst6 \+ netcat-openbsd \procps \unzip \&& rm -rf /var/lib/apt/lists/*