Skip to content

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

fix: harden orchestrator target selection and fallback routing

Bosche7577ada9f26
diff --git a/internal/orchestrator/handlers_instances_test.go b/internal/orchestrator/handlers_instances_test.go
index 4652d3df..cff8ad66 100644
--- a/internal/orchestrator/handlers_instances_test.go
+++ b/internal/orchestrator/handlers_instances_test.go
@@ -611,7 +611,7 @@ func TestHandleStartInstance_RequestFallbackTargets_Wins(t *testing.T) {
}
}
-func TestHandleStartInstance_ConfigFallbackOrder_UsedWhenRequestEmpty(t *testing.T) {
+func TestHandleStartInstance_ConfigFallbackOrder_UsedWhenRequestImplicit(t *testing.T) {
fastPolling(t)
o := setupFallbackOrchestrator(t)
fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
@@ -619,7 +619,8 @@ func TestHandleStartInstance_ConfigFallbackOrder_UsedWhenRequestEmpty(t *testing
{target: "cloak-1", succeed: true},
})
- body := `{"browser":"chrome"}`
+ // No browser in the request: operator-configured fallbackOrder applies.
+ body := `{}`
req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(body))
w := httptest.NewRecorder()
@@ -636,6 +637,41 @@ func TestHandleStartInstance_ConfigFallbackOrder_UsedWhenRequestEmpty(t *testing
}
}
+func TestHandleStartInstance_ExplicitBrowser_NeverCrossProviderFallback(t *testing.T) {
+ fastPolling(t)
+ o := setupFallbackOrchestrator(t)
+ fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "cloak-1", succeed: true},
+ })
+
+ // Explicit chrome request: config fallbackOrder (cloak-1) must NOT apply —
+ // the user asked for chrome and must not silently get a cloak instance.
+ // With no fallback chain, the launch takes the direct path: the fallback
+ // planner (and with it any cross-provider attempt) is never engaged.
+ body := `{"browser":"chrome"}`
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if len(fl.calls) != 0 {
+ t.Fatalf("explicit request engaged the fallback planner (%d calls); cfg fallbackOrder must not apply", len(fl.calls))
+ }
+ if w.Code == http.StatusCreated {
+ var inst bridge.Instance
+ if err := json.NewDecoder(w.Body).Decode(&inst); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if inst.Browser != config.BrowserChrome {
+ t.Fatalf("instance Browser = %q, want chrome (never a fallback provider)", inst.Browser)
+ }
+ if inst.FallbackFrom != "" {
+ t.Fatalf("FallbackFrom = %q, want empty for explicit request", inst.FallbackFrom)
+ }
+ }
+}
+
func TestHandleStartInstance_LegacyConfig_NoFallback(t *testing.T) {
old := processAliveFunc
processAliveFunc = func(pid int) bool { return pid > 0 }
@@ -737,7 +773,10 @@ func TestHandleLaunchByName_Exhaustion_502(t *testing.T) {
{target: "cloak-1", failReason: ReasonStartupTimeout},
})
- req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(`{"browser":"chrome"}`))
+ // Implicit request: the operator-configured fallback chain applies and
+ // exhausting it yields the classified 502. (Explicit requests skip the
+ // config chain entirely — see the NeverCrossProviderFallback test.)
+ req := httptest.NewRequest(http.MethodPost, "/instances/launch", strings.NewReader(`{}`))
w := httptest.NewRecorder()
o.handleLaunchByName(w, req)
@@ -749,3 +788,45 @@ func TestHandleLaunchByName_Exhaustion_502(t *testing.T) {
t.Fatalf("body missing browser_target_unavailable code: %s", w.Body.String())
}
}
+
+// M1 regression: an explicit unknown browser on a legacy (no-targets) config
+// must 400 instead of silently launching chrome via NormalizeBrowser coercion.
+func TestHandleStartInstance_UnknownBrowser_LegacyConfig_400(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(`{"browser":"firefox"}`))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400 body=%s", w.Code, w.Body.String())
+ }
+ if !strings.Contains(w.Body.String(), "firefox") {
+ t.Fatalf("error should name the unknown browser: %s", w.Body.String())
+ }
+}
+
+// Known providers (any case) must still resolve on legacy configs.
+func TestHandleStartInstance_KnownBrowser_LegacyConfig_OK(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ defer func() { processAliveFunc = old }()
+ stubPortAvailability(t, func(int) bool { return true })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+
+ req := httptest.NewRequest(http.MethodPost, "/instances/start", strings.NewReader(`{"browser":"chrome"}`))
+ w := httptest.NewRecorder()
+
+ o.handleStartInstance(w, req)
+
+ if w.Code != http.StatusCreated {
+ t.Fatalf("status = %d, want 201 body=%s", w.Code, w.Body.String())
+ }
+}
diff --git a/internal/orchestrator/instance_attach.go b/internal/orchestrator/instance_attach.go
index e7a18d68..e223ae27 100644
--- a/internal/orchestrator/instance_attach.go
+++ b/internal/orchestrator/instance_attach.go
@@ -120,7 +120,28 @@ func (o *Orchestrator) AttachWithOptions(name, cdpURL string, opts AttachOptions
return nil, fmt.Errorf("instance with name %q already exists", name)
}
}
+ // Reserve the name before releasing the lock: the spawn below is slow and
+ // a concurrent same-name attach would otherwise pass the scan above too
+ // and start a second child process against the same external browser.
+ // instanceIsActive treats cmd-less "starting" records as active.
+ o.instances[instanceID] = &InstanceInternal{
+ Instance: bridge.Instance{
+ ID: instanceID,
+ ProfileID: profileID,
+ ProfileName: name,
+ Status: "starting",
+ Attached: true,
+ },
+ }
o.mu.Unlock()
+ reserved := true
+ defer func() {
+ if reserved {
+ o.mu.Lock()
+ delete(o.instances, instanceID)
+ o.mu.Unlock()
+ }
+ }()
// RemoteCDPURL/RemoteBrowserName are passed via CLI flags rather than persisted.
stateDir := filepath.Join(o.baseDir, "attach", instanceID)
@@ -187,6 +208,7 @@ func (o *Orchestrator) AttachWithOptions(name, cdpURL string, opts AttachOptions
o.mu.Lock()
o.instances[instanceID] = internal
o.mu.Unlock()
+ reserved = false
released = true
go o.monitor(internal)
diff --git a/internal/orchestrator/instance_launch.go b/internal/orchestrator/instance_launch.go
index 43dbbd6a..bc0b9a30 100644
--- a/internal/orchestrator/instance_launch.go
+++ b/internal/orchestrator/instance_launch.go
@@ -117,7 +117,19 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
// Browser-aware launch: resolve the browser name to a target for config overrides.
effectiveCfg := o.runtimeCfg
- if browser := strings.TrimSpace(opts.Browser); browser != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
+ targetPromoted := false
+ // A resolved target name is authoritative: re-deriving from the provider
+ // picks the wrong target when several targets share one provider.
+ if targetName := strings.TrimSpace(opts.TargetName); targetName != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
+ resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, targetName)
+ if err == nil {
+ effectiveCfg = resolved.Config
+ targetPromoted = true
+ } else {
+ slog.Warn("launch: resolved target name no longer resolves; falling back to provider-derived config", "target", targetName, "err", err)
+ }
+ }
+ if browser := strings.TrimSpace(opts.Browser); !targetPromoted && browser != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
matches := config.TargetsForBrowser(o.runtimeCfg, browser)
if len(matches) == 1 {
resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, matches[0])
diff --git a/internal/orchestrator/instance_query.go b/internal/orchestrator/instance_query.go
index 50eafc59..0a49fd9d 100644
--- a/internal/orchestrator/instance_query.go
+++ b/internal/orchestrator/instance_query.go
@@ -57,15 +57,11 @@ func (o *Orchestrator) FirstRunningURLForBrowser(browser string) string {
return o.FirstRunningURL()
}
normalized := config.NormalizeBrowser(browser)
- url := o.firstRunningURL(func(inst *InstanceInternal) bool {
- return inst != nil && inst.Browser == normalized
- })
- if url != "" {
- return url
- }
- // Legacy fallback: match instances with empty Browser field.
+ // No legacy empty-Browser fallback here: a request for a SPECIFIC
+ // browser must not be routed to an instance of unknown provenance.
+ // Browserless legacy instances stay reachable via FirstRunningURL.
return o.firstRunningURL(func(inst *InstanceInternal) bool {
- return inst != nil && inst.Browser == ""
+ return inst != nil && inst.Browser == normalized
})
}
diff --git a/internal/orchestrator/instance_stop.go b/internal/orchestrator/instance_stop.go
index bdcc9c11..7ca1da07 100644
--- a/internal/orchestrator/instance_stop.go
+++ b/internal/orchestrator/instance_stop.go
@@ -131,6 +131,7 @@ func (o *Orchestrator) markStopped(id string) {
profileName := inst.ProfileName
browser := inst.browser
+ attached := inst.Attached
delete(o.instances, id)
o.mu.Unlock()
@@ -139,6 +140,14 @@ func (o *Orchestrator) markStopped(id string) {
slog.Info("instance stopped and removed", "id", id, "profile", profileName)
o.cleanupStoppedProfile(profileName, browser)
+ if attached {
+ // Attach children write per-instance state under baseDir/attach/<id>;
+ // without this the dirs accumulate across attach/detach cycles.
+ stateDir := filepath.Join(o.baseDir, "attach", id)
+ if err := os.RemoveAll(stateDir); err != nil {
+ slog.Warn("failed to remove attach state dir", "id", id, "dir", stateDir, "err", err)
+ }
+ }
}
func (o *Orchestrator) releaseInstancePorts(id string, inst *InstanceInternal) {
@@ -168,6 +177,12 @@ func (o *Orchestrator) cleanupStoppedProfile(profileName, browser string) {
if browser == "" && o.runtimeCfg != nil {
browser = config.NormalizeBrowser(o.runtimeCfg.DefaultBrowser)
}
+ if browser == "" {
+ // Every provider's cleanup hook is the same chrome-process sweep;
+ // skipping orphan cleanup entirely (no hook registered under "") is
+ // strictly worse than a chrome-targeted one.
+ browser = config.BrowserChrome
+ }
providerhooks.CleanupProfile(browser, profilePath)
if strings.HasPrefix(profileName, "instance-") {
diff --git a/internal/orchestrator/launch_target_selection.go b/internal/orchestrator/launch_target_selection.go
index 7c9269c0..d666580f 100644
--- a/internal/orchestrator/launch_target_selection.go
+++ b/internal/orchestrator/launch_target_selection.go
@@ -59,7 +59,17 @@ func (o *Orchestrator) ResolveRequestedBrowser(requested string) (targetName, pr
}
}
- return "", "", nil
+ // Legacy (no-targets) fallthrough: an explicit unknown browser must fail
+ // here, not silently launch chrome via NormalizeBrowser coercion later.
+ var available []string
+ if o.runtimeCfg != nil {
+ available = o.runtimeCfg.BrowsersAvailable
+ }
+ parsed, err := config.ParseBrowser(requested, available)
+ if err != nil {
+ return "", "", &UnknownBrowserError{Target: requested, Err: err}
+ }
+ return "", parsed, nil
}
// LaunchWithTargetSelection applies browserTarget/defaultTarget/fallbackOrder
@@ -78,11 +88,16 @@ func (o *Orchestrator) LaunchWithTargetSelection(
opts.RequestedProvider = requestedTarget
opts.Browser = resolvedProvider
+ opts.TargetName = resolvedTarget
+ // Fallback policy: request-supplied fallbackTargets are always honored
+ // verbatim. The config-level fallbackOrder applies only to IMPLICIT
+ // launches — an explicit browser/target request must never silently
+ // change provider via operator-configured fallback.
var fallbacks []string
if len(fallbackTargets) > 0 {
fallbacks = fallbackTargets
- } else if resolvedTarget != "" && o.runtimeCfg != nil {
+ } else if strings.TrimSpace(requestedTarget) == "" && resolvedTarget != "" && o.runtimeCfg != nil {
fallbacks = o.runtimeCfg.FallbackOrder
}
diff --git a/internal/orchestrator/launch_with_fallback.go b/internal/orchestrator/launch_with_fallback.go
index a7d52d9f..b14a67e2 100644
--- a/internal/orchestrator/launch_with_fallback.go
+++ b/internal/orchestrator/launch_with_fallback.go
@@ -141,6 +141,7 @@ func (p LaunchPlanner) LaunchWithFallback(
attemptOpts := opts
attemptOpts.Browser = resolved.Provider
+ attemptOpts.TargetName = resolved.Name
inst, launchErr := p.Launcher.Launch(name, port, headless, attemptOpts)
if launchErr != nil {
@@ -331,13 +332,29 @@ func (o *Orchestrator) waitForLaunchOutcome(instanceID string, timeout time.Dura
}
}
-// tearDownFailedAttempt logs but does not propagate errors so teardown never blocks fallback.
+// failedAttemptExitWait bounds how long fallback waits for a failed attempt's
+// process to exit before launching the next candidate. Var so tests can shrink it.
+var failedAttemptExitWait = 3 * time.Second
+
+// tearDownFailedAttempt logs but does not propagate errors so teardown never
+// blocks fallback indefinitely. It does wait (bounded) for the failed process
+// to exit: the next candidate reuses the same profile name/dir, and a
+// still-dying browser holding Chrome's SingletonLock would poison the retry.
func (o *Orchestrator) tearDownFailedAttempt(instanceID string) {
inst := o.detachFailedAttempt(instanceID)
if inst == nil {
return
}
- go o.stopDetachedFailedAttempt(instanceID, inst)
+ o.detachedStops.Add(1)
+ go func() {
+ defer o.detachedStops.Done()
+ o.stopDetachedFailedAttempt(instanceID, inst)
+ }()
+ if inst.cmd != nil {
+ if pid := inst.cmd.PID(); pid > 0 && !waitForProcessExit(pid, failedAttemptExitWait) {
+ slog.Warn("failed fallback attempt still running; next candidate may hit a locked profile", "id", instanceID, "pid", pid)
+ }
+ }
}
func (o *Orchestrator) detachFailedAttempt(instanceID string) *InstanceInternal {
@@ -361,7 +378,7 @@ func (o *Orchestrator) stopDetachedFailedAttempt(instanceID string, inst *Instan
return
}
defer func() {
- o.cleanupDetachedFailedAttemptProfile(inst.ProfileName)
+ o.cleanupDetachedFailedAttemptProfile(inst.ProfileName, inst.browser)
}()
if inst.cmd == nil {
@@ -410,7 +427,7 @@ func (o *Orchestrator) requestDetachedShutdown(inst *InstanceInternal) {
}
}
-func (o *Orchestrator) cleanupDetachedFailedAttemptProfile(profileName string) {
+func (o *Orchestrator) cleanupDetachedFailedAttemptProfile(profileName, browser string) {
o.mu.RLock()
for _, inst := range o.instances {
if inst != nil && inst.ProfileName == profileName && instanceIsActive(inst) {
@@ -419,7 +436,7 @@ func (o *Orchestrator) cleanupDetachedFailedAttemptProfile(profileName string) {
}
}
o.mu.RUnlock()
- o.cleanupStoppedProfile(profileName, "")
+ o.cleanupStoppedProfile(profileName, browser)
}
// dedupCandidates trims whitespace, drops empty/duplicate entries, preserves order.
diff --git a/internal/orchestrator/launch_with_fallback_test.go b/internal/orchestrator/launch_with_fallback_test.go
index fc10dc15..b499e435 100644
--- a/internal/orchestrator/launch_with_fallback_test.go
+++ b/internal/orchestrator/launch_with_fallback_test.go
@@ -385,6 +385,9 @@ func TestTearDownFailedAttempt_DetachesBeforeAsyncStop(t *testing.T) {
o.instances[activeSameProfile.ID] = activeSameProfile
o.tearDownFailedAttempt(failed.ID)
+ // Join the async stop before assertions/cleanup: its profile-cleanup scan
+ // reads processAliveFunc, which t.Cleanup restores.
+ o.detachedStops.Wait()
o.mu.RLock()
_, failedPresent := o.instances[failed.ID]
@@ -488,3 +491,26 @@ func equalStrings(a, b []string) bool {
}
var _ = errors.New
+
+// Same-provider twins (chrome-local, backup) are distinguishable only by
+// target name; the planner must thread it so LaunchWithOptions promotes the
+// right target's config instead of re-deriving one from the provider.
+func TestLaunchWithFallback_ThreadsTargetNameToEachAttempt(t *testing.T) {
+ fl := fakeLauncherFor([]scriptedOutcome{
+ {target: "chrome-local", failReason: ReasonBinaryMissing},
+ {target: "backup", succeed: true},
+ })
+
+ if _, err := launchWithFallbackForTest(fl, []string{"chrome-local", "backup"}); err != nil {
+ t.Fatalf("LaunchWithFallback: %v", err)
+ }
+ if len(fl.calls) != 2 {
+ t.Fatalf("expected 2 launch calls, got %d", len(fl.calls))
+ }
+ if fl.calls[0].TargetName != "chrome-local" || fl.calls[1].TargetName != "backup" {
+ t.Fatalf("TargetName not threaded per attempt: got %q, %q", fl.calls[0].TargetName, fl.calls[1].TargetName)
+ }
+ if fl.calls[1].Browser != config.BrowserChrome {
+ t.Fatalf("fallback Browser = %q, want chrome (twin shares the provider)", fl.calls[1].Browser)
+ }
+}
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 71d3c45e..5e17cc84 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -40,6 +40,10 @@ type Orchestrator struct {
allowEvaluate bool
internalToken string
bindings *Bindings
+ // detachedStops tracks async failed-attempt teardowns so tests (and
+ // shutdown paths) can wait for them instead of leaking goroutines that
+ // race with stubbed package vars.
+ detachedStops sync.WaitGroup
// strictCrossInstanceTab toggles the cross-instance explicit-tab rule.
// When false (default), a request that targets a tab on a different
@@ -112,6 +116,11 @@ type LaunchOptions struct {
RequestedProvider string
Browser string
+ // TargetName is the resolved browser target name. When set,
+ // LaunchWithOptions uses this exact target's config instead of
+ // re-deriving a target from Browser — with several targets sharing a
+ // provider, re-derivation picks the wrong one.
+ TargetName string
}
type AttachOptions struct {
diff --git a/internal/orchestrator/orchestrator_test.go b/internal/orchestrator/orchestrator_test.go
index 392135ed..d31d2064 100644
--- a/internal/orchestrator/orchestrator_test.go
+++ b/internal/orchestrator/orchestrator_test.go
@@ -2,8 +2,11 @@ package orchestrator
import (
"bytes"
+ "context"
"encoding/json"
+ "errors"
"fmt"
+ "io"
"net/http"
"net/http/httptest"
"net/url"
@@ -11,12 +14,14 @@ import (
"path/filepath"
"strconv"
"strings"
+ "sync/atomic"
"testing"
"time"
_ "github.com/pinchtab/pinchtab/internal/browsers/all"
"github.com/pinchtab/pinchtab/internal/bridge"
+ "github.com/pinchtab/pinchtab/internal/browsers/providerhooks"
"github.com/pinchtab/pinchtab/internal/config"
)
@@ -1209,3 +1214,156 @@ func TestOrchestrator_RegisterHandlers_LocksSensitiveRoutes(t *testing.T) {
}
}
}
+
+// With two targets sharing the chrome provider, an explicit TargetName must
+// promote that exact target's config into the child config — provider-based
+// re-derivation would pick the default target's binary.
+func TestLaunchWithOptions_TargetNamePromotesExactTarget(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+ stubPortAvailability(t, func(int) bool { return true })
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ InstancePortStart: 9900,
+ InstancePortEnd: 9910,
+ DefaultTarget: "chrome-local",
+ Targets: config.BrowserTargetsConfig{
+ "chrome-local": {Provider: config.BrowserChrome, Binary: "/usr/bin/chrome-a"},
+ "backup": {Provider: config.BrowserChrome, Binary: "/usr/bin/chrome-b"},
+ },
+ })
+
+ if _, err := o.LaunchWithOptions("p1", "", true, LaunchOptions{
+ Browser: config.BrowserChrome,
+ TargetName: "backup",
+ }); err != nil {
+ t.Fatalf("LaunchWithOptions: %v", err)
+ }
+
+ cfgPath := envMap(runner.env)["PINCHTAB_CONFIG"]
+ if cfgPath == "" {
+ t.Fatal("PINCHTAB_CONFIG missing from child env")
+ }
+ data, err := os.ReadFile(cfgPath)
+ if err != nil {
+ t.Fatalf("ReadFile(%q): %v", cfgPath, err)
+ }
+ var fc config.FileConfig
+ if err := json.Unmarshal(data, &fc); err != nil {
+ t.Fatalf("unmarshal child config: %v", err)
+ }
+ if fc.Browser.BrowserBinary != "/usr/bin/chrome-b" {
+ t.Fatalf("child binary = %q, want backup's /usr/bin/chrome-b", fc.Browser.BrowserBinary)
+ }
+}
+
+// M9 regression: a failed attach spawn must release the name reservation so
+// a retry with the same name succeeds.
+func TestAttach_FailedSpawnReleasesNameReservation(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &mockRunner{portAvail: true, runErr: errors.New("spawn failed")}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"localhost"})
+ o.attachHealthCheckTimeout = 50 * time.Millisecond
+
+ if _, err := o.Attach("ext", "ws://localhost:9222/devtools/browser/a"); err == nil {
+ t.Fatal("expected attach to fail when the runner errors")
+ }
+ if n := len(o.List()); n != 0 {
+ t.Fatalf("failed attach left %d residual instances (stale reservation)", n)
+ }
+
+ o.runner = &mockRunner{portAvail: true}
+ if _, err := o.Attach("ext", "ws://localhost:9222/devtools/browser/a"); err != nil {
+ t.Fatalf("retry after failed attach should succeed: %v", err)
+ }
+}
+
+// slowAttachRunner widens the spawn window so the duplicate-name race is
+// deterministic: the second attach must fail on the reservation, not spawn.
+type slowAttachRunner struct {
+ mockRunner
+ delay time.Duration
+ runs atomic.Int32
+}
+
+func (r *slowAttachRunner) Run(ctx context.Context, binary string, args []string, env []string, stdout, stderr io.Writer) (Cmd, error) {
+ r.runs.Add(1)
+ time.Sleep(r.delay)
+ return r.mockRunner.Run(ctx, binary, args, env, stdout, stderr)
+}
+
+// M9 regression: concurrent same-name attaches spawn at most one child.
+func TestAttach_ConcurrentDuplicateNameSpawnsOneChild(t *testing.T) {
+ stubAttachBridgeHealthy(t)
+ runner := &slowAttachRunner{mockRunner: mockRunner{portAvail: true}, delay: 50 * time.Millisecond}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ allowAttachForTest(o, []string{"ws"}, []string{"localhost"})
+ o.attachHealthCheckTimeout = 50 * time.Millisecond
+
+ errs := make(chan error, 2)
+ for i := 0; i < 2; i++ {
+ go func() {
+ _, err := o.Attach("shared", "ws://localhost:9222/devtools/browser/a")
+ errs <- err
+ }()
+ }
+ var failures int
+ for i := 0; i < 2; i++ {
+ if err := <-errs; err != nil {
+ failures++
+ if !strings.Contains(err.Error(), "already exists") {
+ t.Fatalf("unexpected attach error: %v", err)
+ }
+ }
+ }
+ if failures != 1 {
+ t.Fatalf("expected exactly one duplicate-name failure, got %d", failures)
+ }
+ if got := runner.runs.Load(); got != 1 {
+ t.Fatalf("expected exactly one child spawn, got %d", got)
+ }
+}
+
+// M9 regression: orphan cleanup must run even with an empty browser and nil
+// runtime config — it defaults to the chrome sweep instead of no-opping.
+func TestCleanupStoppedProfile_EmptyBrowserStillRunsCleanupHook(t *testing.T) {
+ var swept []string
+ providerhooks.Register("chrome", providerhooks.Hooks{CleanupProfile: func(p string) { swept = append(swept, p) }})
+ t.Cleanup(func() {
+ providerhooks.Register("chrome", providerhooks.Hooks{
+ CleanupProfile: bridge.CleanupOrphanedChromeProcesses,
+ Shutdown: func() { bridge.KillAllPinchtabChrome() },
+ })
+ })
+
+ o := &Orchestrator{baseDir: t.TempDir()}
+ o.cleanupStoppedProfile("prof-x", "")
+ if len(swept) != 1 {
+ t.Fatalf("cleanup hook not invoked for empty browser + nil runtimeCfg: %v", swept)
+ }
+}
+
+// L7(h): a browser-specific lookup must not fall back to instances of
+// unknown provenance (empty Browser field).
+func TestFirstRunningURLForBrowser_SkipsBrowserlessInstances(t *testing.T) {
+ old := processAliveFunc
+ processAliveFunc = func(pid int) bool { return pid > 0 }
+ t.Cleanup(func() { processAliveFunc = old })
+
+ o := NewOrchestratorWithRunner(t.TempDir(), &mockRunner{portAvail: true})
+ o.instances["legacy"] = &InstanceInternal{
+ Instance: bridge.Instance{ID: "legacy", Status: "running", Port: "9001"},
+ URL: "http://localhost:9001",
+ }
+
+ if url := o.FirstRunningURLForBrowser("cloak"); url != "" {
+ t.Fatalf("browser-specific lookup matched a browserless instance: %q", url)
+ }
+ if url := o.FirstRunningURLForBrowser(""); url == "" {
+ t.Fatal("non-specific lookup should still reach legacy instances")
+ }
+}
diff --git a/internal/orchestrator/route.go b/internal/orchestrator/route.go
index 6ae8e09a..6eb5dee9 100644
--- a/internal/orchestrator/route.go
+++ b/internal/orchestrator/route.go
@@ -72,14 +72,21 @@ func (o *Orchestrator) launchAndWaitForRequestRoute(profileName, requestedTarget
if launched.URL == "" {
return "", http.StatusServiceUnavailable, fmt.Errorf("auto-launched instance %q has no URL", launched.ID)
}
- url, err := o.waitForRequestRouteReady(launched.URL, routeInstanceReadyWait)
+ o.mu.Lock()
+ inst := o.instances[launched.ID]
+ o.mu.Unlock()
+ if inst == nil {
+ return "", http.StatusServiceUnavailable, fmt.Errorf("auto-launched instance %q disappeared before becoming ready", launched.ID)
+ }
+ url, err := o.waitForRequestRouteReady(inst, routeInstanceReadyWait)
if err != nil {
return "", http.StatusServiceUnavailable, err
}
return url, 0, nil
}
-func (o *Orchestrator) waitForRequestRouteReady(url string, timeout time.Duration) (string, error) {
+func (o *Orchestrator) waitForRequestRouteReady(inst *InstanceInternal, timeout time.Duration) (string, error) {
+ url := inst.URL
healthURL := strings.TrimRight(url, "/") + "/health"
deadline := time.Now().Add(timeout)
client := o.client
@@ -89,6 +96,10 @@ func (o *Orchestrator) waitForRequestRouteReady(url string, timeout time.Duratio
for time.Now().Before(deadline) {
req, _ := http.NewRequest(http.MethodGet, healthURL, nil)
+ // Children inherit Server.Token and /health is auth-gated; an
+ // unauthenticated poll loops on 401 until the timeout and
+ // auto-launch can never succeed.
+ o.applyInstanceAuth(req, inst)
resp, err := client.Do(req)
if err == nil {
_ = resp.Body.Close()
diff --git a/internal/orchestrator/route_test.go b/internal/orchestrator/route_test.go
index 3584543d..7283774b 100644
--- a/internal/orchestrator/route_test.go
+++ b/internal/orchestrator/route_test.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
+ "time"
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
@@ -408,3 +409,45 @@ func TestWrapShorthand_StaleBindingFallsThrough(t *testing.T) {
t.Fatalf("agent binding after stale fallthrough = %q, %v; want inst_a, true", got, ok)
}
}
+
+// M8 regression: the auto-launch readiness poll must authenticate — children
+// inherit Server.Token and an unauthenticated poll loops on 401 until the
+// route times out with 503.
+func TestRouteForRequest_AutoLaunchReadinessPollAuthenticates(t *testing.T) {
+ alwaysAlive(t)
+ stubPortAvailability(t, func(int) bool { return true })
+ oldPoll := routeInstanceReadyPollInterval
+ routeInstanceReadyPollInterval = time.Millisecond
+ t.Cleanup(func() { routeInstanceReadyPollInterval = oldPoll })
+
+ runner := &mockRunner{portAvail: true}
+ o := NewOrchestratorWithRunner(t.TempDir(), runner)
+ o.client = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ status := http.StatusUnauthorized
+ if req.Header.Get("Authorization") == "Bearer child-token" {
+ status = http.StatusOK
+ }
+ return &http.Response{
+ StatusCode: status,
+ Body: io.NopCloser(bytes.NewReader([]byte(`{}`))),
+ Header: make(http.Header),
+ Request: req,
+ }, nil
+ })}
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{
+ Token: "child-token",
+ DefaultTarget: "chrome",
+ Targets: config.BrowserTargetsConfig{
+ "chrome": {Provider: config.BrowserChrome},
+ },
+ })
+
+ req := httptest.NewRequest(http.MethodPost, "/navigate", nil)
+ target, status, err := o.RouteForRequest(req)
+ if err != nil {
+ t.Fatalf("RouteForRequest status=%d err=%v (poll likely unauthenticated)", status, err)
+ }
+ if target == "" {
+ t.Fatal("target URL is empty")
+ }
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 24ceb9c4..6fc4ae5e 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -330,6 +330,10 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
doShutdown := func() {
shutdownOnce.Do(func() {
slog.Info("shutting down dashboard...")
+ // launchd may SIGKILL us shortly after SIGTERM; kill browser
+ // processes first so a mid-teardown SIGKILL can't orphan them.
+ // The hooks are idempotent process sweeps.
+ providerhooks.ShutdownAll()
if err := activeStrategy.Stop(); err != nil {
slog.Warn("strategy stop failed", "err", err)
}
@@ -340,7 +344,6 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
maintenanceCancel()
dash.Shutdown()
gracefulShutdownWithCap(orch, bridgeShutdownTotalCap)
- providerhooks.Shutdown(config.NormalizeBrowser(cfg.DefaultBrowser))
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
@@ -359,6 +362,9 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
sig := make(chan os.Signal, 2)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
<-sig
+ // Synchronous kill before the goroutine hop: the supervisor may not
+ // grant us even the scheduling delay of go doShutdown().
+ providerhooks.ShutdownAll()
go doShutdown()
<-sig
slog.Warn("force shutdown requested")