High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: deferring the config-load diagnostics means a flag error before the emit discards them entirely (PIN-115)
Luigi Agosti2015f03d9ff9
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.goindex 5c5fe542..09f87379 100644--- a/cmd/pinchtab/cmd_bridge.go+++ b/cmd/pinchtab/cmd_bridge.go@@ -36,6 +36,9 @@ Examples:`,RunE: func(cmd *cobra.Command, args []string) error {cfg, loadDiags := loadConfigDeferringDiagnostics()+ resolveLogLevel(cfg, bridgeLogLevel, false)+ config.EmitLoadDiagnostics(loadDiags)+if v := strings.TrimSpace(bridgeCDPAttach); v != "" {cdpURL, err := validateBridgeCDPURL(v)if err != nil {@@ -59,8 +62,6 @@ Examples:if v := strings.TrimSpace(bridgeRemoteBrowserName); v != "" {cfg.RemoteBrowserName = v}- resolveLogLevel(cfg, bridgeLogLevel, false)- config.EmitLoadDiagnostics(loadDiags)server.RunBridgeServer(cfg, version)return nildiff --git a/cmd/pinchtab/cmd_bridge_test.go b/cmd/pinchtab/cmd_bridge_test.goindex ee3cdc3e..5a8e0166 100644--- a/cmd/pinchtab/cmd_bridge_test.go+++ b/cmd/pinchtab/cmd_bridge_test.go@@ -242,3 +242,27 @@ func TestBridgeResolvesTheLevelFromAWrittenChildConfig(t *testing.T) {t.Fatalf("bridge started from a written child config resolved %v, want warn", got)}}++// The window this card closed: the prologue validated flags between the load and+// the emit, so a bad --cdp-attach returned before the loader's warnings were ever+// written. Driving the real RunE is what makes that visible — the warning has to+// reach the log alongside the flag error, not instead of it.+func TestBridgeFlagErrorStillEmitsLoaderWarnings(t *testing.T) {+ writeRunConfig(t, `{"server":{"port":"9867"},"browsers":{"default":"not-a-browser"}}`)+ buf := captureRunLog(t)++ previous := bridgeCDPAttach+ bridgeCDPAttach = "garbage"+ t.Cleanup(func() { bridgeCDPAttach = previous })++ err := bridgeCmd.RunE(bridgeCmd, nil)+ if err == nil {+ t.Fatal("bridge --cdp-attach garbage returned no error, so this test is not exercising the early-return path")+ }+ if !strings.Contains(err.Error(), "--cdp-attach") {+ t.Fatalf("error = %v, want the --cdp-attach validation failure", err)+ }+ if out := buf.String(); !strings.Contains(out, "not a known browser") {+ t.Errorf("the flag error discarded the loader warning:\n%s", out)+ }+}diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.goindex 833c70b6..21cd1697 100644--- a/cmd/pinchtab/cmd_server.go+++ b/cmd/pinchtab/cmd_server.go@@ -21,6 +21,12 @@ var serverCmd = &cobra.Command{maybeRunWizard()cfg, loadDiags := loadConfigDeferringDiagnostics()+ verbose, _ := cmd.Flags().GetBool("verbose")+ cfg.VerboseBanner = verbose+ logLevel, _ := cmd.Flags().GetString("log-level")+ resolveLogLevel(cfg, logLevel, verbose)+ config.EmitLoadDiagnostics(loadDiags)+backgroundMarker, _ := cmd.Flags().GetString("background-child")cfg.BackgroundMarker = backgroundMarker@@ -52,11 +58,6 @@ var serverCmd = &cobra.Command{if len(exts) > 0 {cfg.ExtensionPaths = append(cfg.ExtensionPaths, exts...)}- verbose, _ := cmd.Flags().GetBool("verbose")- cfg.VerboseBanner = verbose- logLevel, _ := cmd.Flags().GetString("log-level")- resolveLogLevel(cfg, logLevel, verbose)- config.EmitLoadDiagnostics(loadDiags)browserName, _ := cmd.Flags().GetString("browser")if browserName != "" {diff --git a/cmd/pinchtab/cmd_server_test.go b/cmd/pinchtab/cmd_server_test.goindex 86eb46e0..19dbc8c4 100644--- a/cmd/pinchtab/cmd_server_test.go+++ b/cmd/pinchtab/cmd_server_test.go@@ -3,8 +3,11 @@ package mainimport ("bytes""encoding/json"+ "errors"+ "fmt""log/slog""os"+ "os/exec""path/filepath""reflect""slices"@@ -372,3 +375,106 @@ func TestConfigPackageHoldsNoLogLevelPrecedence(t *testing.T) {}}}++// yoloChildEnv marks the re-executed child that drives serverCmd.Run for real.+const yoloChildEnv = "PINCHTAB_TEST_YOLO_EXIT_CHILD"++// The --yolo branch reports its failures with os.Exit, which no defer and no+// in-process test can observe, so this re-executes the test binary and reads the+// child's own output. Two things have to survive that exit: the loader's warning,+// and the debug line the config asked for — the second one only lands if the level+// is resolved above the --yolo branch rather than merely before the work.+func TestServerYoloExitStillEmitsLoaderDiagnostics(t *testing.T) {+ if os.Getenv(yoloChildEnv) == "1" {+ runYoloExitChild()+ return+ }++ path := filepath.Join(t.TempDir(), "config.json")+ body := `{"configVersion":"` + config.CurrentConfigVersion + `","server":{"token":"test-token","logLevel":"debug"},` ++ `"browser":{"binary":"/tmp/chrome"},"browsers":{"default":"not-a-browser"}}`+ if err := os.WriteFile(path, []byte(body), 0600); err != nil {+ t.Fatal(err)+ }++ child := exec.Command(os.Args[0], "-test.run=TestServerYoloExitStillEmitsLoaderDiagnostics", "-test.timeout=60s") // #nosec G204 -- re-executes this test binary.+ child.Env = append(os.Environ(),+ yoloChildEnv+"=1",+ "PINCHTAB_CONFIG="+path,+ "PINCHTAB_TOKEN=test-token",+ )+ raw, err := child.CombinedOutput()+ out := string(raw)++ var exitErr *exec.ExitError+ if !errors.As(err, &exitErr) {+ t.Fatalf("child exited with %v, want the --yolo os.Exit(1); output:\n%s", err, out)+ }+ if code := exitErr.ExitCode(); code != 1 {+ t.Fatalf("child exit code = %d, want 1; output:\n%s", code, out)+ }+ if !strings.Contains(out, "--yolo:") {+ t.Fatalf("child did not reach the --yolo failure, so the exit path is unproven:\n%s", out)+ }+ if !strings.Contains(out, "not a known browser") {+ t.Errorf("the --yolo exit discarded the loader warning:\n%s", out)+ }+ if !strings.Contains(out, "loading config file") {+ t.Errorf("server.logLevel=debug was not resolved before the --yolo exit, so its diagnostics stayed hidden:\n%s", out)+ }+ if !strings.Contains(out, "migrated legacy browser config") {+ t.Errorf("the legacy-browser migration notice was lost on the --yolo exit path:\n%s", out)+ }+}++// runYoloExitChild is the child half: production logging, the real Run body, the+// real os.Exit.+func runYoloExitChild() {+ safelog.InstallDefault()+ if err := serverCmd.Flags().Set("yolo", "true"); err != nil {+ fmt.Fprintln(os.Stderr, "child could not set --yolo:", err)+ os.Exit(9)+ }+ serverCmd.Run(serverCmd, nil)+}++// The fix is an ordering, and an ordering is only kept by something that checks+// it: the next flag validation added to either prologue would reopen the window+// silently. Every command that defers its diagnostics must emit them before it can+// leave the prologue, so no exit may sit between the load and the emit.+func TestDeferredDiagnosticsAreEmittedBeforeAnyExit(t *testing.T) {+ const (+ load = "= loadConfigDeferringDiagnostics()"+ emit = "config.EmitLoadDiagnostics("+ )++ deferring := 0+ for _, path := range commandSourceFiles(t) {+ raw, err := os.ReadFile(path) // #nosec G304 -- files listed from this package's own directory.+ if err != nil {+ t.Fatal(err)+ }+ src := string(raw)+ start := strings.Index(src, load)+ if start < 0 {+ continue+ }+ deferring++++ emitAt := strings.Index(src[start:], emit)+ if emitAt < 0 {+ t.Errorf("%s defers its load diagnostics and never emits them", filepath.Base(path))+ continue+ }+ window := src[start : start+emitAt]+ for _, escape := range []string{"return", "os.Exit("} {+ if strings.Contains(window, escape) {+ t.Errorf("%s can %s between the load and %s, which discards the loader's diagnostics; move the emit above it:\n%s",+ filepath.Base(path), escape, emit, window)+ }+ }+ }+ if deferring < 2 {+ t.Fatalf("found %d commands calling %s; the census matched almost nothing and would pass vacuously", deferring, load)+ }+}