Skip to content

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

fix: the server log level is flag-only, so a daemon-installed or auto-started server cannot set it (PIN-092)

Luigi Agostie024d98aa33c
diff --git a/cmd/pinchtab/cmd_server.go b/cmd/pinchtab/cmd_server.go
index 5067a47b..fd38a8d0 100644
--- a/cmd/pinchtab/cmd_server.go
+++ b/cmd/pinchtab/cmd_server.go
@@ -55,8 +55,7 @@ var serverCmd = &cobra.Command{
verbose, _ := cmd.Flags().GetBool("verbose")
cfg.VerboseBanner = verbose
logLevel, _ := cmd.Flags().GetString("log-level")
- cfg.LogLevel = logLevel
- applyLogLevel(cfg, verbose)
+ resolveLogLevel(cfg, logLevel, verbose)
browserName, _ := cmd.Flags().GetString("browser")
if browserName != "" {
@@ -100,6 +99,19 @@ func applyServerAddressFlags(cfg *config.RuntimeConfig, bind, port string) {
}
}
+// resolveLogLevel settles the run's threshold from the only three inputs that
+// carry it, in precedence order: --log-level, then server.logLevel from the config
+// file, then -v, then the default. It is one function because the command must not
+// be able to apply them in a different order — assigning the flag unconditionally
+// erased server.logLevel on every flagless run, which is every daemon-installed
+// and auto-started server.
+func resolveLogLevel(cfg *config.RuntimeConfig, logLevel string, verbose bool) {
+ if v := strings.TrimSpace(logLevel); v != "" {
+ cfg.LogLevel = v
+ }
+ applyLogLevel(cfg, verbose)
+}
+
func applyLogLevel(cfg *config.RuntimeConfig, verbose bool) {
if strings.TrimSpace(cfg.LogLevel) != "" {
level, err := safelog.ParseLevel(cfg.LogLevel)
diff --git a/cmd/pinchtab/cmd_server_test.go b/cmd/pinchtab/cmd_server_test.go
index e20222cc..a3a66108 100644
--- a/cmd/pinchtab/cmd_server_test.go
+++ b/cmd/pinchtab/cmd_server_test.go
@@ -1,8 +1,12 @@
package main
import (
+ "encoding/json"
"log/slog"
+ "os"
"reflect"
+ "slices"
+ "strings"
"testing"
"github.com/pinchtab/pinchtab/internal/config"
@@ -124,3 +128,92 @@ func TestQuietBannerKeepsDefaultLogging(t *testing.T) {
t.Errorf("level = %v, want the default with a quiet banner", got)
}
}
+
+// The three-way precedence: --log-level beats server.logLevel, server.logLevel
+// beats the default, and -v beats neither. Assigning the flag unconditionally is
+// the bug this pins — it erased the configured level on every flagless run.
+func TestLogLevelPrecedenceFlagBeatsConfigBeatsDefault(t *testing.T) {
+ t.Cleanup(func() { safelog.SetLevel(safelog.DefaultLevel) })
+
+ for _, tc := range []struct {
+ name string
+ configLevel string
+ flag string
+ verbose bool
+ want slog.Level
+ }{
+ {name: "nothing set is the default", want: safelog.DefaultLevel},
+ {name: "config alone is honoured", configLevel: "warn", want: slog.LevelWarn},
+ {name: "flag beats config", configLevel: "warn", flag: "debug", want: slog.LevelDebug},
+ {name: "blank flag leaves config", configLevel: "warn", flag: " ", want: slog.LevelWarn},
+ {name: "verbose loses to config", configLevel: "warn", verbose: true, want: slog.LevelWarn},
+ {name: "verbose loses to the flag", flag: "error", verbose: true, want: slog.LevelError},
+ {name: "verbose applies with neither", verbose: true, want: slog.LevelDebug},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ safelog.SetLevel(slog.LevelInfo)
+ cfg := &config.RuntimeConfig{LogLevel: tc.configLevel}
+ resolveLogLevel(cfg, tc.flag, tc.verbose)
+ if got := safelog.CurrentLevel(); got != tc.want {
+ t.Errorf("level = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// The daemon install and the auto-started server both launch `pinchtab server`
+// with no flags, so the config file is the only way either can ask for a level.
+// This drives the flagless path end to end: file config in, resolved threshold out.
+func TestFlaglessServerResolvesTheConfiguredLogLevel(t *testing.T) {
+ t.Cleanup(func() { safelog.SetLevel(safelog.DefaultLevel) })
+ safelog.SetLevel(slog.LevelInfo)
+
+ var fc config.FileConfig
+ if err := json.Unmarshal([]byte(`{"server":{"logLevel":"warn"}}`), &fc); err != nil {
+ t.Fatal(err)
+ }
+ cfg := &config.RuntimeConfig{}
+ config.ApplyFileConfigToRuntime(cfg, &fc)
+
+ resolveLogLevel(cfg, "", false)
+
+ if got := safelog.CurrentLevel(); got != slog.LevelWarn {
+ t.Fatalf("flagless server resolved %v, want warn from server.logLevel", got)
+ }
+}
+
+// If either launcher ever grew a --log-level argument the test above would stop
+// standing in for it, and a reader would not know which path is authoritative.
+func TestDaemonAndAutoStartLaunchWithoutLogLevelFlags(t *testing.T) {
+ if args := autoStartServerArgs("marker-123"); slices.Contains(args, "--log-level") {
+ t.Errorf("autoStartServerArgs = %v, now passes --log-level; the config path is no longer the only route", args)
+ }
+}
+
+// resolveLogLevel is only load-bearing if the command routes through it. A unit
+// test on the helper cannot see a Run body that assigns cfg.LogLevel itself, and
+// that assignment — `cfg.LogLevel = logLevel`, unconditional — is exactly the bug
+// this card fixed. So the source is the assertion: the flag reaches the runtime
+// config in one place, inside the helper that knows the precedence.
+func TestServerCommandAssignsTheLogLevelOnlyInsideResolveLogLevel(t *testing.T) {
+ raw, err := os.ReadFile("cmd_server.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ src := string(raw)
+
+ const assignment = "cfg.LogLevel = "
+ if got := strings.Count(src, assignment); got != 1 {
+ t.Fatalf("cmd_server.go assigns cfg.LogLevel %d times, want exactly 1 (inside resolveLogLevel)", got)
+ }
+ helper := src[strings.Index(src, "func resolveLogLevel("):]
+ if end := strings.Index(helper, "\nfunc "); end >= 0 {
+ helper = helper[:end]
+ }
+ if !strings.Contains(helper, assignment) {
+ t.Error("the one cfg.LogLevel assignment is outside resolveLogLevel; the flag can bypass the precedence again")
+ }
+ if !strings.Contains(src, "resolveLogLevel(cfg, logLevel, verbose)") {
+ t.Error("the server command no longer calls resolveLogLevel with the flag and the verbose flag")
+ }
+}
diff --git a/docs/commands.md b/docs/commands.md
index 4265a1ae..f65dd7fd 100644
--- a/docs/commands.md
+++ b/docs/commands.md
@@ -26,6 +26,11 @@ transitions, warnings and errors. `-v` adds debug detail and the full startup
banner; `--log-level debug|info|warn|error` sets the threshold explicitly and is
the only thing that can drop request lines or warnings.
+A daemon-installed server and the server a bare `pinchtab nav` auto-starts both
+run `pinchtab server` with no flags, so they take their threshold from
+`server.logLevel` in the config file (`pinchtab config set server.logLevel warn`).
+`--log-level` overrides it for a hand-started run; `-v` does not.
+
## Navigation
```bash
diff --git a/docs/reference/config.md b/docs/reference/config.md
index 6b8c7bc9..a1cd7734 100644
--- a/docs/reference/config.md
+++ b/docs/reference/config.md
@@ -177,6 +177,7 @@ Current nested file-config shape:
"bind": "127.0.0.1",
"token": "your-secret-token",
"stateDir": "/path/to/state",
+ "logLevel": "info",
"networkBufferSize": 100,
"retainNetworkBodies": false,
"retainNetworkBodyMaxBytes": 262144,
@@ -550,6 +551,24 @@ Use `pinchtab config patch` or edit `config.json` directly for fields such as:
}
```
+### Log Level For A Daemon Or Auto-Started Server
+
+`pinchtab server --log-level` only reaches a server you start by hand. A
+daemon-installed server (`pinchtab daemon install`) and the server a bare
+`pinchtab nav` auto-starts both launch `pinchtab server` with no flags, so
+`server.logLevel` is the only way to set their threshold — and it needs no change
+to the unit file.
+
+```bash
+pinchtab config set server.logLevel warn # Warnings and errors only
+pinchtab config set server.logLevel debug # Full debug detail while diagnosing
+pinchtab config get server.logLevel
+```
+
+Accepted values are `debug`, `info` (the default), `warn` and `error`; an
+unparseable value fails when the config loads, naming the accepted values.
+`--log-level` still wins over the configured value, and `-v` wins over neither.
+
### Network Bind With Token
```bash
diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.go
index 1417f9e1..88bb3b5a 100644
--- a/internal/config/config_file_json.go
+++ b/internal/config/config_file_json.go
@@ -22,6 +22,7 @@ type serverConfigJSON struct {
Bind string `json:"bind"`
Token string `json:"token"`
StateDir string `json:"stateDir"`
+ LogLevel string `json:"logLevel,omitempty"`
NetworkBufferSize *int `json:"networkBufferSize,omitempty"`
RetainNetworkBodies *bool `json:"retainNetworkBodies,omitempty"`
RetainNetworkBodyMaxBytes *int `json:"retainNetworkBodyMaxBytes,omitempty"`
diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.go
index ad38de40..c7112771 100644
--- a/internal/config/config_file_marshal.go
+++ b/internal/config/config_file_marshal.go
@@ -169,6 +169,7 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {
Bind: fc.Server.Bind,
Token: fc.Server.Token,
StateDir: fc.Server.StateDir,
+ LogLevel: fc.Server.LogLevel,
NetworkBufferSize: fc.Server.NetworkBufferSize,
RetainNetworkBodies: fc.Server.RetainNetworkBodies,
RetainNetworkBodyMaxBytes: fc.Server.RetainNetworkBodyMaxBytes,
@@ -451,6 +452,7 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {
Bind: cfg.Bind,
Token: cfg.Token,
StateDir: cfg.StateDir,
+ LogLevel: cfg.LogLevel,
NetworkBufferSize: netBufSize,
RetainNetworkBodies: &retainBodies,
RetainNetworkBodyMaxBytes: &retainBodyMaxBytes,
diff --git a/internal/config/config_load.go b/internal/config/config_load.go
index c5f3efab..6dd452c6 100644
--- a/internal/config/config_load.go
+++ b/internal/config/config_load.go
@@ -370,6 +370,9 @@ func applyServerConfig(cfg *RuntimeConfig, s ServerConfig) {
if s.StateDir != "" {
cfg.StateDir = s.StateDir
}
+ if s.LogLevel != "" {
+ cfg.LogLevel = s.LogLevel
+ }
if s.NetworkBufferSize != nil && *s.NetworkBufferSize > 0 {
cfg.NetworkBufferSize = ClampNetworkBufferSize(*s.NetworkBufferSize)
}
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 1c7ebe94..32d78813 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -9,6 +9,8 @@ import (
"strings"
"testing"
"time"
+
+ "github.com/pinchtab/pinchtab/internal/safelog"
)
func TestEnvOr(t *testing.T) {
@@ -1315,3 +1317,136 @@ func TestLoadConfig_MalformedFileWarnsWithoutError(t *testing.T) {
t.Errorf("expected a warn 'failed to parse config' diagnostic, got %+v", diags)
}
}
+
+// The whole point of the key: a flagless server reads its threshold from the
+// config file. Asserting the resolved slog level, not just the string field,
+// is what makes this a behaviour test — the field could round-trip perfectly
+// and still never reach the logger.
+func TestLoadConfig_ServerLogLevelResolvesToAThreshold(t *testing.T) {
+ clearConfigEnvVars(t)
+ writeTestConfig(t, `{"server": {"logLevel": "warn"}}`)
+
+ cfg := Load()
+
+ if cfg.LogLevel != "warn" {
+ t.Fatalf("LogLevel = %q, want warn from the config file", cfg.LogLevel)
+ }
+ level, err := safelog.ParseLevel(cfg.LogLevel)
+ if err != nil {
+ t.Fatalf("ParseLevel(%q): %v", cfg.LogLevel, err)
+ }
+ if level != slog.LevelWarn {
+ t.Fatalf("resolved level = %v, want warn", level)
+ }
+}
+
+// An absent key must leave the runtime empty rather than writing a value, or the
+// flag can no longer tell "unset" from "configured info".
+func TestLoadConfig_AbsentServerLogLevelStaysUnset(t *testing.T) {
+ clearConfigEnvVars(t)
+ writeTestConfig(t, `{"server": {"bind": "127.0.0.1"}}`)
+
+ if cfg := Load(); cfg.LogLevel != "" {
+ t.Fatalf("LogLevel = %q with no key in the file, want empty", cfg.LogLevel)
+ }
+}
+
+// The config path must not be more forgiving than the flag path, and the message
+// an operator reads has to be the same one either way — hence the exact-equality
+// assertion against safelog.ParseLevel rather than a substring check.
+func TestValidateFileConfig_ServerLogLevelRejectsUnknownValues(t *testing.T) {
+ fc := DefaultFileConfig()
+ fc.Server.LogLevel = "verbose"
+
+ errs := ValidateFileConfig(&fc)
+
+ _, parseErr := safelog.ParseLevel("verbose")
+ if parseErr == nil {
+ t.Fatal("safelog.ParseLevel accepts \"verbose\"; this test no longer covers an unparseable value")
+ }
+ var found error
+ for _, err := range errs {
+ if strings.Contains(err.Error(), "server.logLevel") {
+ found = err
+ break
+ }
+ }
+ if found == nil {
+ t.Fatalf("no server.logLevel error for an unparseable value; errors: %v", errs)
+ }
+ if want := "server.logLevel: " + parseErr.Error(); found.Error() != want {
+ t.Fatalf("error = %q, want %q so the config path reads like the flag path", found.Error(), want)
+ }
+ for _, accepted := range []string{"debug", "info", "warn", "error"} {
+ if !strings.Contains(found.Error(), accepted) {
+ t.Errorf("error %q does not name the accepted value %q", found.Error(), accepted)
+ }
+ }
+}
+
+func TestValidateFileConfig_ServerLogLevelAcceptsEveryParseableValue(t *testing.T) {
+ for _, level := range []string{"", "debug", "info", "warn", "warning", "error", "WARN", " warn "} {
+ fc := DefaultFileConfig()
+ fc.Server.LogLevel = level
+ for _, err := range ValidateFileConfig(&fc) {
+ if strings.Contains(err.Error(), "server.logLevel") {
+ t.Errorf("logLevel %q rejected: %v", level, err)
+ }
+ }
+ }
+}
+
+// config get/set plus a save/load round trip, which is the path the CLI takes.
+func TestServerLogLevelSurvivesSetSaveAndLoad(t *testing.T) {
+ fc := DefaultFileConfig()
+ if err := SetConfigValue(&fc, "server.logLevel", "warn"); err != nil {
+ t.Fatalf("set: %v", err)
+ }
+
+ encoded, err := json.Marshal(fc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(encoded), `"logLevel":"warn"`) {
+ t.Fatalf("marshalled config does not carry the key: %s", encoded)
+ }
+
+ var reloaded FileConfig
+ if err := json.Unmarshal(encoded, &reloaded); err != nil {
+ t.Fatal(err)
+ }
+ got, err := GetConfigValue(&reloaded, "server.logLevel")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if got != "warn" {
+ t.Fatalf("get server.logLevel = %q after a round trip, want warn", got)
+ }
+}
+
+// A rejected set must leave the previous value alone, and the message must name
+// the accepted values just like the load path.
+func TestSetServerLogLevelRejectsUnknownValues(t *testing.T) {
+ fc := DefaultFileConfig()
+ fc.Server.LogLevel = "warn"
+
+ err := SetConfigValue(&fc, "server.logLevel", "verbose")
+ if err == nil {
+ t.Fatal("set accepted an unparseable level")
+ }
+ if !strings.Contains(err.Error(), "server.logLevel") || !strings.Contains(err.Error(), "warn") {
+ t.Errorf("error %q does not name the field and the accepted values", err.Error())
+ }
+ if fc.Server.LogLevel != "warn" {
+ t.Errorf("LogLevel = %q after a rejected set, want the previous value", fc.Server.LogLevel)
+ }
+}
+
+// FileConfigFromRuntime is the save side of `config set` on a running config; a
+// missing field there silently drops the operator's setting on the next save.
+func TestFileConfigFromRuntimeCarriesTheLogLevel(t *testing.T) {
+ fc := FileConfigFromRuntime(&RuntimeConfig{LogLevel: "error"})
+ if fc.Server.LogLevel != "error" {
+ t.Fatalf("Server.LogLevel = %q, want error", fc.Server.LogLevel)
+ }
+}
diff --git a/internal/config/config_types.go b/internal/config/config_types.go
index cb1f2ffa..fc2dd14b 100644
--- a/internal/config/config_types.go
+++ b/internal/config/config_types.go
@@ -277,6 +277,7 @@ type ServerConfig struct {
Bind string `json:"bind,omitempty"`
Token string `json:"token,omitempty"`
StateDir string `json:"stateDir,omitempty"`
+ LogLevel string `json:"logLevel,omitempty"`
// Engine is no longer supported. Kept for JSON parsing so old configs get a
// validation error instead of silently ignoring the field.
Engine string `json:"engine,omitempty"`
diff --git a/internal/config/editor_get.go b/internal/config/editor_get.go
index 87cfe264..e8d9348b 100644
--- a/internal/config/editor_get.go
+++ b/internal/config/editor_get.go
@@ -52,6 +52,8 @@ func getServerField(s *ServerConfig, field string) (string, error) {
return s.Token, nil
case "stateDir":
return s.StateDir, nil
+ case "logLevel":
+ return s.LogLevel, nil
case "trustProxyHeaders":
return formatBoolPtr(s.TrustProxyHeaders), nil
case "cookieSecure":
diff --git a/internal/config/editor_set.go b/internal/config/editor_set.go
index f8716d83..17eb6d02 100644
--- a/internal/config/editor_set.go
+++ b/internal/config/editor_set.go
@@ -6,6 +6,7 @@ import (
"strings"
"github.com/pinchtab/pinchtab/internal/browsers"
+ "github.com/pinchtab/pinchtab/internal/safelog"
)
// SetConfigValue sets a dotted path in FileConfig (e.g., "server.port", "instanceDefaults.mode").
@@ -53,6 +54,11 @@ func setServerField(s *ServerConfig, field, value string) error {
s.Token = value
case "stateDir":
s.StateDir = value
+ case "logLevel":
+ if _, err := safelog.ParseLevel(value); err != nil {
+ return fmt.Errorf("server.logLevel: %w", err)
+ }
+ s.LogLevel = strings.ToLower(strings.TrimSpace(value))
case "trustProxyHeaders":
b, err := parseBool(value)
if err != nil {
diff --git a/internal/config/validate.go b/internal/config/validate.go
index 377d3a0a..1fe74d67 100644
--- a/internal/config/validate.go
+++ b/internal/config/validate.go
@@ -13,6 +13,7 @@ import (
"github.com/pinchtab/pinchtab/internal/autosolver/catalog"
"github.com/pinchtab/pinchtab/internal/browsers"
"github.com/pinchtab/pinchtab/internal/config/geo"
+ "github.com/pinchtab/pinchtab/internal/safelog"
)
type ValidationError struct {
@@ -38,6 +39,11 @@ func ValidateFileConfig(fc *FileConfig) []error {
errs = append(errs, err)
}
}
+ if fc.Server.LogLevel != "" {
+ if _, err := safelog.ParseLevel(fc.Server.LogLevel); err != nil {
+ errs = append(errs, ValidationError{Field: "server.logLevel", Message: err.Error()})
+ }
+ }
if fc.Server.NetworkBufferSize != nil {
if *fc.Server.NetworkBufferSize < 1 || *fc.Server.NetworkBufferSize > MaxNetworkBufferSize {
errs = append(errs, ValidationError{
diff --git a/internal/schema/config.json b/internal/schema/config.json
index f4781348..1c98dcf2 100644
--- a/internal/schema/config.json
+++ b/internal/schema/config.json
@@ -169,6 +169,10 @@
"stateDir": {
"type": "string"
},
+ "logLevel": {
+ "type": "string",
+ "description": "Minimum log level for the server: debug, info (default), warn or error. Matching is case-insensitive, so no enum here — safelog.ParseLevel is the single authority and reports the accepted values. A daemon-installed or auto-started server passes no flags, so this key is the only way to set the level there."
+ },
"engine": {
"type": "string",
"enum": [