High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: the config-load debug diagnostics are emitted before the log level is resolved (PIN-106)
Luigi Agosti45f583aefabf
diff --git a/cmd/pinchtab/cmd_bridge.go b/cmd/pinchtab/cmd_bridge.goindex 0b44fc9f..5c5fe542 100644--- a/cmd/pinchtab/cmd_bridge.go+++ b/cmd/pinchtab/cmd_bridge.go@@ -35,7 +35,7 @@ Examples:--browser cloak --remote-browser-name cloak-manager-profile`,RunE: func(cmd *cobra.Command, args []string) error {- cfg := loadConfig()+ cfg, loadDiags := loadConfigDeferringDiagnostics()if v := strings.TrimSpace(bridgeCDPAttach); v != "" {cdpURL, err := validateBridgeCDPURL(v)if err != nil {@@ -60,6 +60,7 @@ Examples:cfg.RemoteBrowserName = v}resolveLogLevel(cfg, bridgeLogLevel, false)+ config.EmitLoadDiagnostics(loadDiags)server.RunBridgeServer(cfg, version)return nildiff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.goindex eefb1c9f..833c70b6 100644--- a/cmd/pinchtab/cmd_server.go+++ b/cmd/pinchtab/cmd_server.go@@ -20,7 +20,7 @@ var serverCmd = &cobra.Command{Run: func(cmd *cobra.Command, args []string) {maybeRunWizard()- cfg := loadConfig()+ cfg, loadDiags := loadConfigDeferringDiagnostics()backgroundMarker, _ := cmd.Flags().GetString("background-child")cfg.BackgroundMarker = backgroundMarker@@ -56,6 +56,7 @@ var serverCmd = &cobra.Command{cfg.VerboseBanner = verboselogLevel, _ := cmd.Flags().GetString("log-level")resolveLogLevel(cfg, logLevel, verbose)+ config.EmitLoadDiagnostics(loadDiags)browserName, _ := cmd.Flags().GetString("browser")if browserName != "" {@@ -101,9 +102,19 @@ func applyServerAddressFlags(cfg *config.RuntimeConfig, bind, port string) {// resolveLogLevel settles a run's threshold from the only inputs that carry it, in// precedence order: --log-level, then server.logLevel from the config file, then-// -v, then the default. Every command that logs calls this rather than assigning-// cfg.LogLevel itself — an unconditional assignment erased server.logLevel on-// every flagless run, which is every daemon-installed and auto-started server.+// -v, then the default. It is the one place that decides that precedence, and no+// caller assigns cfg.LogLevel itself — an unconditional assignment erased+// server.logLevel on every flagless run, which is every daemon-installed and+// auto-started server.+//+// The long-running runtimes call it: `server` and `bridge`. The short-lived+// commands do not, and do not need to. cmd_server_ensure.go and+// cmd_server_background.go log about spawning a server rather than being one, so+// their warnings and errors are recorded at the default level and their two+// slog.Debug lines are deliberately not reachable — a CLI command that+// auto-starts a server has no --log-level of its own to honour, and the server it+// starts resolves its own. Give either of them a level flag and it must route+// through here.func resolveLogLevel(cfg *config.RuntimeConfig, logLevel string, verbose bool) {if v := strings.TrimSpace(logLevel); v != "" {cfg.LogLevel = vdiff --git a/cmd/pinchtab/cmd_server_test.go b/cmd/pinchtab/cmd_server_test.goindex a3a66108..9193f90d 100644--- a/cmd/pinchtab/cmd_server_test.go+++ b/cmd/pinchtab/cmd_server_test.go@@ -1,9 +1,11 @@package mainimport (+ "bytes""encoding/json""log/slog""os"+ "path/filepath""reflect""slices""strings"@@ -217,3 +219,118 @@ func TestServerCommandAssignsTheLogLevelOnlyInsideResolveLogLevel(t *testing.T)t.Error("the server command no longer calls resolveLogLevel with the flag and the verbose flag")}}++// captureRunLog installs the handler a real run installs, at the level a real run+// starts from, so the load-then-resolve sequence below is the production one+// rather than a level set up front.+func captureRunLog(t *testing.T) *bytes.Buffer {+ t.Helper()+ var buf bytes.Buffer+ previous := slog.Default()+ slog.SetDefault(slog.New(safelog.NewDefaultHandler(&buf)))+ safelog.SetLevel(safelog.DefaultLevel)+ t.Cleanup(func() {+ slog.SetDefault(previous)+ safelog.SetLevel(safelog.DefaultLevel)+ })+ return &buf+}++func writeRunConfig(t *testing.T, body string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "config.json")+ if err := os.WriteFile(path, []byte(body), 0600); err != nil {+ t.Fatal(err)+ }+ t.Setenv("PINCHTAB_CONFIG", path)+ t.Setenv("PINCHTAB_TOKEN", "test-token")+ return path+}++// The sequence the defect lived in: the loader describes reading the very file+// that carries server.logLevel, so the diagnostics have to outlive the load and be+// emitted once the level is known.+func loadThenResolve(t *testing.T, flag string, verbose bool) *config.RuntimeConfig {+ t.Helper()+ cfg, diags, err := config.LoadConfig()+ if err != nil {+ t.Fatalf("LoadConfig() error = %v", err)+ }+ resolveLogLevel(cfg, flag, verbose)+ config.EmitLoadDiagnostics(diags)+ return cfg+}++func TestConfigFileDebugLevelRecordsTheConfigLoadDiagnostic(t *testing.T) {+ path := writeRunConfig(t, `{"server":{"port":"9867","logLevel":"debug"}}`)+ buf := captureRunLog(t)++ loadThenResolve(t, "", false)++ out := buf.String()+ if !strings.Contains(out, "loading config file") {+ t.Errorf("server.logLevel=debug did not record the config-load diagnostic:\n%s", out)+ }+ if !strings.Contains(out, path) {+ t.Errorf("the diagnostic does not name the file that was read (%s):\n%s", path, out)+ }+}++// Shape 2 of the card: the flag route works too, so --log-level debug can tell you+// which config file it read even when the file itself says nothing about levels.+func TestLogLevelFlagRecordsTheConfigLoadDiagnostic(t *testing.T) {+ path := writeRunConfig(t, `{"server":{"port":"9867"}}`)+ buf := captureRunLog(t)++ loadThenResolve(t, "debug", false)++ if out := buf.String(); !strings.Contains(out, "loading config file") || !strings.Contains(out, path) {+ t.Errorf("--log-level debug did not record the config-load diagnostic with its path:\n%s", out)+ }+}++// A silently rewritten config is the case a user most needs to see.+func TestLegacyBrowserMigrationNoticeIsReachableAtDebug(t *testing.T) {+ writeRunConfig(t, `{"server":{"port":"9867","logLevel":"debug"},"browser":{"binary":"/tmp/chrome"}}`)+ buf := captureRunLog(t)++ cfg := loadThenResolve(t, "", false)++ if !cfg.TargetsSynthesized {+ t.Fatalf("precondition: the legacy browser config was not migrated, so there is no notice to record")+ }+ if out := buf.String(); !strings.Contains(out, "migrated legacy browser config") {+ t.Errorf("the migration notice is unreachable at debug:\n%s", out)+ }+}++// The fix must not promote the diagnostics: a default run stays quiet about which+// file it read, while a warn-level diagnostic from the same load still lands.+func TestDefaultRunRecordsNoConfigLoadDiagnosticButKeepsWarnings(t *testing.T) {+ writeRunConfig(t, `{"server":{"port":"9867"},"browsers":{"default":"not-a-browser"}}`)+ buf := captureRunLog(t)++ loadThenResolve(t, "", false)++ out := buf.String()+ if strings.Contains(out, "loading config file") {+ t.Errorf("a default run recorded the debug config-load diagnostic:\n%s", out)+ }+ if !strings.Contains(out, "not a known browser") {+ t.Errorf("a warn diagnostic from the same load was dropped:\n%s", out)+ }+}++// internal/config must not grow its own precedence: it collects diagnostics and+// emits them on request, and the level decision stays in resolveLogLevel.+func TestConfigPackageHoldsNoLogLevelPrecedence(t *testing.T) {+ raw, err := os.ReadFile(filepath.Join("..", "..", "internal", "config", "config_load.go"))+ if err != nil {+ t.Fatal(err)+ }+ for _, forbidden := range []string{"safelog.", "SetLevel("} {+ if strings.Contains(string(raw), forbidden) {+ t.Errorf("internal/config/config_load.go references %q — the level decision must stay in resolveLogLevel", forbidden)+ }+ }+}diff --git a/cmd/pinchtab/config_load.go b/cmd/pinchtab/config_load.goindex f35f6733..6ae25cb1 100644--- a/cmd/pinchtab/config_load.go+++ b/cmd/pinchtab/config_load.go@@ -17,6 +17,18 @@ func loadConfig() *config.RuntimeConfig {return cfg}+// loadConfigDeferringDiagnostics is loadConfig for the commands that resolve a log+// level: the returned diagnostics stay unemitted until resolveLogLevel has run,+// so a debug level asked for in the config file can show the load of that file.+// The caller must pass them to config.EmitLoadDiagnostics.+func loadConfigDeferringDiagnostics() (*config.RuntimeConfig, []config.LoadDiagnostic) {+ if err := ensureMandatoryToken(); err != nil {+ fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err)+ os.Exit(1)+ }+ return config.LoadDeferringDiagnostics()+}+func loadLocalConfig() *config.RuntimeConfig {return config.Load()}diff --git a/internal/config/config_load.go b/internal/config/config_load.goindex 6dd452c6..5af5d54c 100644--- a/internal/config/config_load.go+++ b/internal/config/config_load.go@@ -118,7 +118,33 @@ type LoadDiagnostic struct {// defaults. It is a thin wrapper over LoadConfig that emits the load diagnostics// via slog and terminates the process on a fatal config error.func Load() *RuntimeConfig {+ cfg, diags := LoadDeferringDiagnostics()+ EmitLoadDiagnostics(diags)+ return cfg+}++// LoadDeferringDiagnostics loads the config and hands back its diagnostics+// unemitted, for a caller that must resolve the log level before they are+// written. The load diagnostics describe reading the very file that carries+// server.logLevel, so emitting them during the load drops every debug one at any+// setting. A fatal config error still terminates here: it is reported at error+// level, which no level suppresses, and there is nothing to resolve afterwards.+//+// This carries no precedence logic — the caller decides the level and then calls+// EmitLoadDiagnostics.+func LoadDeferringDiagnostics() (*RuntimeConfig, []LoadDiagnostic) {cfg, diags, err := LoadConfig()+ if err != nil {+ EmitLoadDiagnostics(diags)+ slog.Error(err.Error())+ os.Exit(1)+ }+ return cfg, diags+}++// EmitLoadDiagnostics writes collected load diagnostics through slog at the level+// each one declares.+func EmitLoadDiagnostics(diags []LoadDiagnostic) {for _, d := range diags {switch d.Level {case slog.LevelDebug:@@ -129,11 +155,6 @@ func Load() *RuntimeConfig {slog.Warn(d.Message, d.Attrs...)}}- if err != nil {- slog.Error(err.Error())- os.Exit(1)- }- return cfg}// LoadConfig builds the RuntimeConfig (env > file > defaults) with no logging and@@ -293,7 +314,7 @@ func LoadConfig() (*RuntimeConfig, []LoadDiagnostic, error) {diags = append(diags, LoadDiagnostic{slog.LevelWarn, "config validation error", []any{"path", res.Path, "error", e}})}- applyFileConfig(cfg, res.FC)+ diags = append(diags, applyFileConfig(cfg, res.FC)...)finalizeProfileConfig(cfg)if cfg.Port == "" {@@ -343,18 +364,19 @@ func finalizeProfileConfig(cfg *RuntimeConfig) {}}-func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) {+func applyFileConfig(cfg *RuntimeConfig, fc *FileConfig) []LoadDiagnostic {applyServerConfig(cfg, fc.Server)applySecurityConfig(cfg, fc.Security)applyObservabilityConfig(cfg, fc.Observability)applySessionsConfig(cfg, fc.Sessions)- applyBrowserConfig(cfg, &fc.Browser, fc.Browsers)+ diags := applyBrowserConfig(cfg, &fc.Browser, fc.Browsers)applyInstanceDefaultsConfig(cfg, &fc.InstanceDefaults)applyProfilesConfig(cfg, fc.Profiles)applyMultiInstanceConfig(cfg, fc.MultiInstance)applyTimeoutsConfig(cfg, fc.Timeouts)applySchedulerConfig(cfg, fc.Scheduler)applyAutoSolverConfig(cfg, fc.AutoSolver)+ return diags}func applyServerConfig(cfg *RuntimeConfig, s ServerConfig) {@@ -531,12 +553,16 @@ func applySessionsConfig(cfg *RuntimeConfig, s SessionsFileConfig) {}}-func applyBrowserConfig(cfg *RuntimeConfig, browser *BrowserConfig, browsersCfg BrowsersConfig) {+// applyBrowserConfig returns its notices rather than logging them: a debug notice+// emitted during the load is written before any command has resolved the level,+// so logging here made a silently rewritten config unreadable at every setting.+func applyBrowserConfig(cfg *RuntimeConfig, browser *BrowserConfig, browsersCfg BrowsersConfig) []LoadDiagnostic {+ var diags []LoadDiagnosticsynthesized, conflict := migrateLegacyBrowserConfig(browser, browsersCfg.Default)if conflict {- slog.Warn("config has both browser.targets and legacy browser.binary/extraFlags/cloak/proxy set; targets are used as authored (no legacy synthesis), but the legacy fields still seed the base runtime config that target resolution overlays per-field")+ diags = append(diags, LoadDiagnostic{slog.LevelWarn, "config has both browser.targets and legacy browser.binary/extraFlags/cloak/proxy set; targets are used as authored (no legacy synthesis), but the legacy fields still seed the base runtime config that target resolution overlays per-field", nil})} else if synthesized {- slog.Debug("migrated legacy browser config into browser.targets.default")+ diags = append(diags, LoadDiagnostic{slog.LevelDebug, "migrated legacy browser config into browser.targets.default", nil})}cfg.Targets = cloneBrowserTargetsConfig(browser.Targets)cfg.DefaultTarget = browser.DefaultTarget@@ -546,8 +572,8 @@ func applyBrowserConfig(cfg *RuntimeConfig, browser *BrowserConfig, browsersCfgif browsersCfg.Default != "" {cfg.DefaultBrowser = strings.ToLower(strings.TrimSpace(browsersCfg.Default))if _, ok := browsers.Get(strings.ToLower(strings.TrimSpace(browsersCfg.Default))); !ok {- slog.Warn("browsers.default is not a known browser; launches will fall back to chrome",- "configured", browsersCfg.Default, "known", browsers.IDs())+ diags = append(diags, LoadDiagnostic{slog.LevelWarn, "browsers.default is not a known browser; launches will fall back to chrome",+ []any{"configured", browsersCfg.Default, "known", browsers.IDs()}})}} else if name := ResolveDefaultTarget(cfg); name != "" && !cfg.TargetsSynthesized && cfg.Targets[name].Provider != "" {cfg.DefaultBrowser = NormalizeBrowser(cfg.Targets[name].Provider)@@ -594,6 +620,8 @@ func applyBrowserConfig(cfg *RuntimeConfig, browser *BrowserConfig, browsersCfg} else {cfg.BrowsersAvailable = []string{"chrome"}}++ return diags}func applyInstanceDefaultsConfig(cfg *RuntimeConfig, d *InstanceDefaultsConfig) {@@ -809,7 +837,7 @@ func ApplyFileConfigToRuntime(cfg *RuntimeConfig, fc *FileConfig) {return}- applyFileConfig(cfg, fc)+ EmitLoadDiagnostics(applyFileConfig(cfg, fc))finalizeProfileConfig(cfg)}