High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: preserve daemon ownership during CLI auto-start
Lukedaf8ee282bc6
diff --git a/cmd/pinchtab/cmd_server_background.go b/cmd/pinchtab/cmd_server_background.goindex 030b3d1a..1a55acea 100644--- a/cmd/pinchtab/cmd_server_background.go+++ b/cmd/pinchtab/cmd_server_background.go@@ -70,6 +70,22 @@ var serverRestartCmd = &cobra.Command{},}+// requireDetachedServerOwnership prevents the detached server launch paths from+// competing with an installed service manager for the same configured port and+// state directory. An installed daemon is the canonical owner; it is also+// KeepAlive-managed, so callers should ask that manager to start it instead of+// creating an orphaned background child.+func requireDetachedServerOwnership(action string) error {+ installed, err := daemonInstallationStatus()+ if err != nil {+ return fmt.Errorf("cannot determine background-service ownership; refusing %s: %w", action, err)+ }+ if installed {+ return fmt.Errorf("background service is installed; use `pinchtab daemon start` so one service manager owns the server")+ }+ return nil+}+func runServerRestart(cfg *config.RuntimeConfig) error {installed, err := daemonInstallationStatus()if err != nil {@@ -138,6 +154,10 @@ func spawnDetachedChild(binary string, args []string, out *os.File) (int, error)}func runServerBackground(cfg *config.RuntimeConfig, opts serverBackgroundOptions) error {+ if err := requireDetachedServerOwnership("background start"); err != nil {+ return err+ }+stateDir := stateDirForConfig(cfg)if info, ok := readServerPID(stateDir); ok {if processAlive(info.PID) {diff --git a/cmd/pinchtab/cmd_server_background_test.go b/cmd/pinchtab/cmd_server_background_test.goindex 47b9270c..2fd20ef5 100644--- a/cmd/pinchtab/cmd_server_background_test.go+++ b/cmd/pinchtab/cmd_server_background_test.go@@ -14,6 +14,44 @@ import ("github.com/pinchtab/pinchtab/internal/server")+func TestDetachedServerStartsRefuseInstalledOrUnknownServiceOwnership(t *testing.T) {+ original := daemonInstallationStatus+ defer func() { daemonInstallationStatus = original }()++ tests := []struct {+ name string+ installed bool+ err error+ start func() error+ want string+ }{+ {+ name: "background installed", installed: true,+ start: func() error { return runServerBackground(&config.RuntimeConfig{}, serverBackgroundOptions{}) },+ want: "pinchtab daemon start",+ },+ {+ name: "automatic installed", installed: true,+ start: autoStartServer,+ want: "pinchtab daemon start",+ },+ {+ name: "automatic unknown", err: errors.New("service path unreadable"),+ start: autoStartServer,+ want: "refusing automatic start",+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ daemonInstallationStatus = func() (bool, error) { return tt.installed, tt.err }+ err := tt.start()+ if err == nil || !strings.Contains(err.Error(), tt.want) {+ t.Fatalf("detached start error = %v, want %q", err, tt.want)+ }+ })+ }+}+func TestServerRestartRefusesInstalledOrUnknownServiceOwnership(t *testing.T) {original := daemonInstallationStatusdefer func() { daemonInstallationStatus = original }()diff --git a/cmd/pinchtab/cmd_server_ensure.go b/cmd/pinchtab/cmd_server_ensure.goindex 4a88aba2..389f5812 100644--- a/cmd/pinchtab/cmd_server_ensure.go+++ b/cmd/pinchtab/cmd_server_ensure.go@@ -19,7 +19,64 @@ type serverHealthFunc func(baseURL, token string) booltype serverProbeFunc func(baseURL, token string) server.HealthProbefunc ensureServerForCLI(cfg *config.RuntimeConfig, baseURL, token, command string) error {- return ensureServerWithAutoStart(baseURL, token, command, canAutoStartServerForCLI(cfg, baseURL), autoStartServer, probeServerHealth, ensureServerTimeout)+ return ensureServerWithDaemonRecovery(+ baseURL, token, command,+ canAutoStartServerForCLI(cfg, baseURL),+ autoStartServer, probeServerHealth,+ daemonInstallationStatus, startInstalledDaemon,+ ensureServerTimeout,+ )+}++// startInstalledDaemon asks the installed service manager to recover the+// daemon. It is intentionally separate from autoStartServer: only the service+// manager may create a server when it owns the lifecycle.+func startInstalledDaemon() (string, error) {+ manager, err := daemonCurrentManager()+ if err != nil {+ return "", fmt.Errorf("access background service manager: %w", err)+ }+ return manager.Start()+}++// ensureServerWithDaemonRecovery preserves CLI cold-start ergonomics without+// allowing a detached child to compete with an installed daemon. A healthy+// daemon needs no action; an unreachable installed daemon is started through+// its manager and given the normal bounded readiness wait. A reachable-but-+// unhealthy listener is never restarted implicitly because it may be a rogue+// child holding the daemon port.+func ensureServerWithDaemonRecovery(baseURL, token, command string, allowAutoStart bool, startDetached serverStartFunc, probe serverProbeFunc, ownership func() (bool, error), startDaemon func() (string, error), timeout time.Duration) error {+ initial := probe(baseURL, token)+ if serverProbeHealthy(initial) {+ return nil+ }+ if !allowAutoStart {+ if initial.Reachable {+ return fmt.Errorf("server at %s is running but unhealthy: %s", baseURL, unhealthyServerDetail(initial))+ }+ return fmt.Errorf("server at %s is not running; auto-start is only supported for the default local server", baseURL)+ }++ installed, err := ownership()+ if err != nil {+ return fmt.Errorf("cannot determine background-service ownership; refusing automatic start: %w", err)+ }+ if installed {+ if initial.Reachable {+ return fmt.Errorf("server at %s is running but unhealthy: %s; an installed PinchTab daemon owns lifecycle, so refusing detached auto-start. Check `pinchtab daemon status` and the port owner", baseURL, unhealthyServerDetail(initial))+ }+ message, err := startDaemon()+ if err != nil {+ return fmt.Errorf("installed PinchTab daemon owns lifecycle, but could not start it: %w; refusing detached auto-start", err)+ }+ ready := func(url, tok string) bool { return serverProbeHealthy(probe(url, tok)) }+ if !waitForServerWith(baseURL, token, timeout, ready) {+ return fmt.Errorf("installed PinchTab daemon was asked to start (%s), but server did not become healthy at %s within %s; a stale or rogue listener may own the port. Run `pinchtab daemon status` and inspect the port owner; refusing detached auto-start", message, baseURL, timeout)+ }+ return nil+ }++ return ensureServerWithAutoStart(baseURL, token, command, true, startDetached, probe, timeout)}func ensureServerWith(baseURL, token, command string, start serverStartFunc, probe serverProbeFunc, timeout time.Duration) error {@@ -83,6 +140,10 @@ func isServerHealthy(baseURL, token string) bool {}func autoStartServer() error {+ if err := requireDetachedServerOwnership("automatic start"); err != nil {+ return err+ }+stateDir := stateDirForConfig(loadConfig())binary, marker, err := prepareServerSpawn()if err != nil {diff --git a/cmd/pinchtab/cmd_server_ensure_test.go b/cmd/pinchtab/cmd_server_ensure_test.goindex 19ce21f5..06fa11a9 100644--- a/cmd/pinchtab/cmd_server_ensure_test.go+++ b/cmd/pinchtab/cmd_server_ensure_test.go@@ -1,6 +1,7 @@package mainimport (+ "errors""net/http""strings""testing"@@ -119,6 +120,96 @@ func TestEnsureServer_UnreachableStillAutoStarts(t *testing.T) {}}+func TestEnsureServerWithDaemonRecoveryOwnsInstalledDaemonLifecycle(t *testing.T) {+ t.Run("installed healthy", func(t *testing.T) {+ ownershipCalled := false+ daemonStarted := false+ detachedStarted := false+ err := ensureServerWithDaemonRecovery(+ "http://127.0.0.1:9867", "", "nav", true,+ func() error { detachedStarted = true; return nil },+ func(string, string) server.HealthProbe {+ return server.HealthProbe{Reachable: true, StatusCode: http.StatusOK}+ },+ func() (bool, error) { ownershipCalled = true; return true, nil },+ func() (string, error) { daemonStarted = true; return "started", nil },+ time.Second,+ )+ if err != nil {+ t.Fatalf("ensureServerWithDaemonRecovery() error = %v", err)+ }+ if ownershipCalled || daemonStarted || detachedStarted {+ t.Fatalf("healthy installed daemon should be left alone: ownership=%t daemon=%t detached=%t", ownershipCalled, daemonStarted, detachedStarted)+ }+ })++ t.Run("installed unloaded starts through manager", func(t *testing.T) {+ daemonStarted := false+ detachedStarted := false+ probes := 0+ err := ensureServerWithDaemonRecovery(+ "http://127.0.0.1:9867", "", "nav", true,+ func() error { detachedStarted = true; return nil },+ func(string, string) server.HealthProbe {+ probes+++ if daemonStarted {+ return server.HealthProbe{Reachable: true, StatusCode: http.StatusOK}+ }+ return server.HealthProbe{}+ },+ func() (bool, error) { return true, nil },+ func() (string, error) { daemonStarted = true; return "Pinchtab daemon started.", nil },+ time.Second,+ )+ if err != nil {+ t.Fatalf("ensureServerWithDaemonRecovery() error = %v", err)+ }+ if !daemonStarted || detachedStarted || probes < 2 {+ t.Fatalf("expected bounded daemon recovery only: daemon=%t detached=%t probes=%d", daemonStarted, detachedStarted, probes)+ }+ })++ t.Run("installed wedged listener refuses detached fallback", func(t *testing.T) {+ daemonStarted := false+ detachedStarted := false+ err := ensureServerWithDaemonRecovery(+ "http://127.0.0.1:9867", "", "nav", true,+ func() error { detachedStarted = true; return nil },+ func(string, string) server.HealthProbe {+ return unhealthyProbe(`{"reason":"browser stuck","status":"error"}`)+ },+ func() (bool, error) { return true, nil },+ func() (string, error) { daemonStarted = true; return "started", nil },+ time.Second,+ )+ if err == nil || !strings.Contains(err.Error(), "installed PinchTab daemon owns lifecycle") || !strings.Contains(err.Error(), "port owner") {+ t.Fatalf("wedged installed daemon error = %v", err)+ }+ if daemonStarted || detachedStarted {+ t.Fatalf("wedged listener must not be restarted or replaced implicitly: daemon=%t detached=%t", daemonStarted, detachedStarted)+ }+ })++ t.Run("unknown ownership refuses detached fallback", func(t *testing.T) {+ daemonStarted := false+ detachedStarted := false+ err := ensureServerWithDaemonRecovery(+ "http://127.0.0.1:9867", "", "nav", true,+ func() error { detachedStarted = true; return nil },+ func(string, string) server.HealthProbe { return server.HealthProbe{} },+ func() (bool, error) { return false, errors.New("service path unreadable") },+ func() (string, error) { daemonStarted = true; return "started", nil },+ time.Second,+ )+ if err == nil || !strings.Contains(err.Error(), "cannot determine background-service ownership") {+ t.Fatalf("unknown ownership error = %v", err)+ }+ if daemonStarted || detachedStarted {+ t.Fatalf("unknown ownership must not start anything: daemon=%t detached=%t", daemonStarted, detachedStarted)+ }+ })+}+func TestEnsureServer_ReadinessWaitTreatsUnhealthyAsNotReadyYet(t *testing.T) {started := falseprobes := 0