High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
fix: carry sessions.agent through the wire twin and make it addressable from config get/set (PIN-184)
Luigi Agostib7a61fd62673
diff --git a/internal/config/config_apply_census_test.go b/internal/config/config_apply_census_test.goindex a8d7a675..75fd9c3c 100644--- a/internal/config/config_apply_census_test.go+++ b/internal/config/config_apply_census_test.go@@ -68,6 +68,15 @@ var censusCandidates = []string{"census-value", "17", "false", "true", "/tmp/cen// behaviour: a key `config set` accepts and writes to the file, and that the value in// effect never reflects, changes nothing and says so nowhere. Adding such a key fails here// until the value arrives or the product refuses it with a reason.+//+// ITS SCOPE IS THE ADDRESSABLE SET, which is narrower than the declared one. It walks the+// keys `config set` can address, so a section the editor cannot address at all is invisible+// to it — no candidate is ever tried, and nothing reds. sessions.agent was exactly that: the+// schema declared it, the loader honoured it, `config patch` accepted and discarded it, and+// this census could not see any of that because `config set sessions.agent.enabled` answered+// "unknown field". The class of defect this cannot detect is therefore an UNADDRESSABLE key,+// and the guard for that one is TestTheWireTwinCarriesEveryDeclaredField, which walks the+// declared types instead. The two are complements; neither subsumes the other.func TestEverySettableConfigKeyReachesTheRuntime(t *testing.T) {paths := addressableConfigPaths(t)if len(paths) < 100 {diff --git a/internal/config/config_file_json.go b/internal/config/config_file_json.goindex 27f45997..bfec7168 100644--- a/internal/config/config_file_json.go+++ b/internal/config/config_file_json.go@@ -184,6 +184,19 @@ type activityEventsConfigJSON struct {type sessionsFileConfigJSON struct {Dashboard dashboardSessionConfigJSON `json:"dashboard"`+ Agent agentSessionConfigJSON `json:"agent,omitempty"`+}++// agentSessionConfigJSON mirrors AgentSessionFileConfig. Its absence is why+// `config patch {"sessions":{"agent":{"enabled":true}}}` answered success and wrote+// nothing: the update path patches the existing file object with the marshalled map, so+// a key in neither could not appear. TestTheWireTwinCarriesEveryDeclaredField is what+// keeps this hand-maintained twin from falling behind again.+type agentSessionConfigJSON struct {+ Enabled *bool `json:"enabled,omitempty"`+ Mode string `json:"mode,omitempty"`+ IdleTimeoutSec *int `json:"idleTimeoutSec,omitempty"`+ MaxLifetimeSec *int `json:"maxLifetimeSec,omitempty"`}type dashboardSessionConfigJSON struct {diff --git a/internal/config/config_file_json_parity_test.go b/internal/config/config_file_json_parity_test.gonew file mode 100644index 00000000..a9d77a7a--- /dev/null+++ b/internal/config/config_file_json_parity_test.go@@ -0,0 +1,148 @@+package config++import (+ "reflect"+ "sort"+ "strings"+ "testing"+)++// declaredJSONPathFloor is the vacuity floor: the walk found this many leaf paths on+// FileConfig when it was written, so a rename that makes the walk stop descending fails+// here rather than reporting a clean parity between two empty sets.+const declaredJSONPathFloor = 150++// wireTwinExemptions are FileConfig paths that deliberately do NOT reach the wire type,+// with the reason each is excluded. Checked in BOTH directions: an exempt path that+// starts being marshalled must fail too, or the reason outlives the omission.+var wireTwinExemptions = map[string]string{+ "server.engine": "declared only so a config carrying the retired key gets a validation error instead of being silently ignored. Writing it back would re-create the key it exists to reject, so its absence from the wire type is the point rather than an oversight",++ "instanceDefaults.headless": "superseded by instanceDefaults.mode, which is the spelling the writer renders. ValidateFileConfig reports an error when both are set (mode takes precedence), so writing headless back would manufacture the conflict it warns about. Read from an old config, never written to a new one",+}++// FileConfig.MarshalJSON renders through fileConfigJSON, a hand-maintained twin. A field+// declared on FileConfig but missing from the twin is not a rendering nicety: the update+// path patches the existing file object with the marshalled map, so a key in neither the+// map nor the file cannot appear — `config patch` reports success and writes nothing.+// That is how sessions.agent went missing while the schema declared it and the loader+// honoured it.+//+// This walks both types rather than naming the fields, because the omission happened+// precisely because a human maintained the second copy by hand, and a hand-written list+// of what to check fails the same way.+func TestTheWireTwinCarriesEveryDeclaredField(t *testing.T) {+ declared := jsonLeafPaths(reflect.TypeOf(FileConfig{}))+ onWire := jsonLeafPaths(reflect.TypeOf(fileConfigJSON{}))++ if len(declared) < declaredJSONPathFloor {+ t.Fatalf("walked %d leaf paths on FileConfig, want at least %d; the walk stopped descending and this parity check would pass vacuously", len(declared), declaredJSONPathFloor)+ }+ if len(onWire) == 0 {+ t.Fatalf("walked no leaf paths on fileConfigJSON; the twin was renamed and this check compares nothing")+ }++ var missing []string+ for _, path := range declared {+ if onWire.has(path) {+ continue+ }+ if _, exempt := wireTwinExemptions[path]; exempt {+ continue+ }+ missing = append(missing, path)+ }+ sort.Strings(missing)+ if len(missing) > 0 {+ t.Errorf("FileConfig declares %v but fileConfigJSON does not carry them, so MarshalJSON drops them and `config patch` reports success while writing nothing; add them to the twin, or exempt each in wireTwinExemptions with the reason it must not be written back", missing)+ }++ // The other direction on the exemption table.+ for path, reason := range wireTwinExemptions {+ if !declared.has(path) {+ t.Errorf("%s is exempted (%s) but FileConfig no longer declares it; drop the entry rather than leaving a reason with nothing to excuse", path, reason)+ }+ if onWire.has(path) {+ t.Errorf("%s is exempted from the wire type (%s) but fileConfigJSON now carries it; either it stopped being exempt, in which case delete the entry, or the field was added by mistake", path, reason)+ }+ }+}++// The specific member this card exists for, asserted by name beside the derived walk+// above. The derived check proves the CLASS is closed; this proves the instance, so a+// walk that silently stopped covering sessions cannot leave it green.+func TestTheAgentSessionBlockReachesTheWire(t *testing.T) {+ declared := jsonLeafPaths(reflect.TypeOf(FileConfig{}))+ onWire := jsonLeafPaths(reflect.TypeOf(fileConfigJSON{}))++ for _, path := range []string{+ "sessions.agent.enabled",+ "sessions.agent.mode",+ "sessions.agent.idleTimeoutSec",+ "sessions.agent.maxLifetimeSec",+ } {+ if !declared.has(path) {+ t.Fatalf("%s is no longer declared on FileConfig; this test is measuring nothing", path)+ }+ if !onWire.has(path) {+ t.Errorf("%s is declared but not on the wire type, so a config patch setting it reports success and writes nothing", path)+ }+ }+}++type jsonPathSet []string++func (s jsonPathSet) has(path string) bool {+ for _, p := range s {+ if p == path {+ return true+ }+ }+ return false+}++// jsonLeafPaths walks a config struct's json tags into dotted leaf paths. Nested structs+// (and pointers to them) are descended; slices and maps are leaves, since their element+// shape is not what this parity check is about.+func jsonLeafPaths(t reflect.Type) jsonPathSet {+ var paths jsonPathSet+ var walk func(t reflect.Type, prefix string, depth int)+ walk = func(t reflect.Type, prefix string, depth int) {+ if depth > 8 {+ return+ }+ for t.Kind() == reflect.Ptr {+ t = t.Elem()+ }+ if t.Kind() != reflect.Struct {+ return+ }+ for i := 0; i < t.NumField(); i++ {+ field := t.Field(i)+ if !field.IsExported() {+ continue+ }+ name, _, _ := strings.Cut(field.Tag.Get("json"), ",")+ if name == "" || name == "-" {+ continue+ }+ path := name+ if prefix != "" {+ path = prefix + "." + name+ }++ fieldType := field.Type+ for fieldType.Kind() == reflect.Ptr {+ fieldType = fieldType.Elem()+ }+ if fieldType.Kind() == reflect.Struct && fieldType.PkgPath() != "time" {+ walk(fieldType, path, depth+1)+ continue+ }+ paths = append(paths, path)+ }+ }+ walk(t, "", 0)+ sort.Strings(paths)+ return paths+}diff --git a/internal/config/config_file_marshal.go b/internal/config/config_file_marshal.goindex 067e2879..7f27a950 100644--- a/internal/config/config_file_marshal.go+++ b/internal/config/config_file_marshal.go@@ -309,6 +309,12 @@ func (fc FileConfig) MarshalJSON() ([]byte, error) {PersistElevationAcrossRestart: fc.Sessions.Dashboard.PersistElevationAcrossRestart,RequireElevation: fc.Sessions.Dashboard.RequireElevation,},+ Agent: agentSessionConfigJSON{+ Enabled: fc.Sessions.Agent.Enabled,+ Mode: fc.Sessions.Agent.Mode,+ IdleTimeoutSec: fc.Sessions.Agent.IdleTimeoutSec,+ MaxLifetimeSec: fc.Sessions.Agent.MaxLifetimeSec,+ },},AutoSolver: autoSolverFileConfigJSON{Enabled: fc.AutoSolver.Enabled,@@ -414,6 +420,9 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {dashboardSessionElevationWindowSec := int(cfg.Sessions.Dashboard.ElevationWindow / time.Second)dashboardSessionPersistElevationAcrossRestart := cfg.Sessions.Dashboard.PersistElevationAcrossRestartdashboardSessionRequireElevation := cfg.Sessions.Dashboard.RequireElevation+ agentSessionEnabled := cfg.Sessions.Agent.Enabled+ agentSessionIdleSec := int(cfg.Sessions.Agent.IdleTimeout / time.Second)+ agentSessionMaxLifetimeSec := int(cfg.Sessions.Agent.MaxLifetime / time.Second)autoSolverEnabled := cfg.AutoSolver.EnabledautoSolverAutoTrigger := cfg.AutoSolver.AutoTriggerautoSolverTriggerOnNavigate := cfg.AutoSolver.TriggerOnNavigate@@ -577,6 +586,12 @@ func FileConfigFromRuntime(cfg *RuntimeConfig) FileConfig {PersistElevationAcrossRestart: &dashboardSessionPersistElevationAcrossRestart,RequireElevation: &dashboardSessionRequireElevation,},+ Agent: AgentSessionFileConfig{+ Enabled: &agentSessionEnabled,+ Mode: cfg.Sessions.Agent.Mode,+ IdleTimeoutSec: &agentSessionIdleSec,+ MaxLifetimeSec: &agentSessionMaxLifetimeSec,+ },},AutoSolver: AutoSolverFileConfig{Enabled: &autoSolverEnabled,diff --git a/internal/config/editor_get.go b/internal/config/editor_get.goindex be280d5e..110495ee 100644--- a/internal/config/editor_get.go+++ b/internal/config/editor_get.go@@ -223,9 +223,36 @@ func getSessionsField(s *SessionsFileConfig, field string) (string, error) {if strings.HasPrefix(field, "dashboard.") {return getDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."))}+ if strings.HasPrefix(field, "agent.") {+ return getAgentSessionField(&s.Agent, strings.TrimPrefix(field, "agent."))+ }return "", fmt.Errorf("unknown field sessions.%s", field)}+// getAgentSessionField addresses the switch behind the whole agent-session flow. It was+// unreachable here while the schema declared it and the loader honoured it, so the only+// way to turn agent sessions on was to hand-edit JSON — and the editor answered "unknown+// field", which claims the key is wrong rather than that it is not settable here.+//+// The cases mirror AgentSessionFileConfig's declared fields, and+// TestTheSessionsEditorAddressesEveryDeclaredField walks that struct rather than this+// list: a hand-listed switch is how a field goes missing from a section that otherwise+// looks complete.+func getAgentSessionField(s *AgentSessionFileConfig, field string) (string, error) {+ switch field {+ case "enabled":+ return formatBoolPtr(s.Enabled), nil+ case "mode":+ return s.Mode, nil+ case "idleTimeoutSec":+ return formatIntPtr(s.IdleTimeoutSec), nil+ case "maxLifetimeSec":+ return formatIntPtr(s.MaxLifetimeSec), nil+ default:+ return "", fmt.Errorf("unknown field sessions.agent.%s", field)+ }+}+func getDashboardSessionField(s *DashboardSessionFileConfig, field string) (string, error) {switch field {case "persist":diff --git a/internal/config/editor_sections_test.go b/internal/config/editor_sections_test.goindex f3de5fa7..b0e102be 100644--- a/internal/config/editor_sections_test.go+++ b/internal/config/editor_sections_test.go@@ -163,11 +163,6 @@ var unreachableConfigLeaves = map[string]string{"server.engine": "removed setting, parsed only so an old config gets a validation error; making it settable would offer an operator a value nothing honours","instanceDefaults.headless": "superseded by instanceDefaults.mode, which is the spelling the file writer renders; setting both is a validation error, and a settable headless would be dropped by MarshalJSON and read as accepted-then-discarded",-- "sessions.agent.enabled": "owned by the agent-session editor card, which also has to teach MarshalJSON the agent block — the editor half alone would report success and write nothing",- "sessions.agent.mode": "owned by the agent-session editor card (see sessions.agent.enabled)",- "sessions.agent.idleTimeoutSec": "owned by the agent-session editor card (see sessions.agent.enabled)",- "sessions.agent.maxLifetimeSec": "owned by the agent-session editor card (see sessions.agent.enabled)",}// unreachableConfigSubtrees are whole blocks excluded by one reason, so the table does notdiff --git a/internal/config/editor_sessions_test.go b/internal/config/editor_sessions_test.gonew file mode 100644index 00000000..21e19f93--- /dev/null+++ b/internal/config/editor_sessions_test.go@@ -0,0 +1,192 @@+package config++import (+ "encoding/json"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"+)++func saveAndReload(t *testing.T, fc *FileConfig, path string) map[string]any {+ t.Helper()++ if err := SaveFileConfig(fc, path); err != nil {+ t.Fatalf("SaveFileConfig: %v", err)+ }+ raw, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read back: %v", err)+ }+ var onDisk map[string]any+ if err := json.Unmarshal(raw, &onDisk); err != nil {+ t.Fatalf("config on disk is not JSON (%v): %s", err, raw)+ }+ return onDisk+}++func agentBlockOnDisk(t *testing.T, onDisk map[string]any) map[string]any {+ t.Helper()++ sessions, ok := onDisk["sessions"].(map[string]any)+ if !ok {+ t.Fatalf("no sessions block on disk: %v", onDisk)+ }+ agent, ok := sessions["agent"].(map[string]any)+ if !ok {+ t.Fatalf("no sessions.agent block on disk; the value was accepted and discarded: %v", sessions)+ }+ return agent+}++// The live defect, and the first thing to assert: `config patch` answered "Config patched+// successfully" and left the file byte-identical. The update path patches the existing+// file object with the marshalled map, so a key the wire type never carried could not+// appear however it was set.+//+// Driven through the real save against an EXISTING file, because that is the only path+// where the defect lives — a test that only marshals the struct would pass while the+// shipped command still wrote nothing.+func TestPatchingAnAgentSessionKeyPersistsIt(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"18899"}}`), 0600); err != nil {+ t.Fatal(err)+ }++ fc := &FileConfig{}+ if err := PatchConfigJSON(fc, `{"sessions":{"agent":{"enabled":true,"mode":"header"}}}`); err != nil {+ t.Fatalf("PatchConfigJSON: %v", err)+ }++ agent := agentBlockOnDisk(t, saveAndReload(t, fc, path))+ if agent["enabled"] != true {+ t.Errorf("sessions.agent.enabled on disk = %v, want true", agent["enabled"])+ }+ if agent["mode"] != "header" {+ t.Errorf("sessions.agent.mode on disk = %v, want %q", agent["mode"], "header")+ }+}++// The card's original finding: the editor answered "unknown field sessions.agent.enabled",+// which claims the key is wrong rather than that it is not settable here — for the one+// switch that turns on the whole agent-session flow.+func TestTheEditorAddressesAgentSessionKeysAndTheySurviveASave(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "config.json")+ if err := os.WriteFile(path, []byte(`{"server":{"port":"18899"}}`), 0600); err != nil {+ t.Fatal(err)+ }++ fc := &FileConfig{}+ for _, tc := range []struct{ key, value, want string }{+ {"sessions.agent.enabled", "true", "true"},+ {"sessions.agent.mode", "header", "header"},+ {"sessions.agent.idleTimeoutSec", "900", "900"},+ {"sessions.agent.maxLifetimeSec", "7200", "7200"},+ } {+ if err := SetConfigValue(fc, tc.key, tc.value); err != nil {+ t.Fatalf("config set %s: %v", tc.key, err)+ }+ got, err := GetConfigValue(fc, tc.key)+ if err != nil {+ t.Fatalf("config get %s: %v", tc.key, err)+ }+ if got != tc.want {+ t.Errorf("config get %s = %q, want %q", tc.key, got, tc.want)+ }+ }++ agent := agentBlockOnDisk(t, saveAndReload(t, fc, path))+ if agent["enabled"] != true || agent["mode"] != "header" {+ t.Errorf("agent block on disk = %v, want the values just set", agent)+ }+ if agent["idleTimeoutSec"] != float64(900) || agent["maxLifetimeSec"] != float64(7200) {+ t.Errorf("agent timeouts on disk = %v, want 900 and 7200", agent)+ }+}++// The fix changes the marshal path that preservation depends on, so the thing most worth+// re-asserting is that it did not start destroying what it used to keep: a hand-written+// agent block is how every operator enabled this before the fix, and it must survive an+// unrelated set.+func TestAHandWrittenAgentBlockSurvivesAnUnrelatedSet(t *testing.T) {+ dir := t.TempDir()+ path := filepath.Join(dir, "config.json")+ original := `{"server":{"port":"18899"},"sessions":{"agent":{"enabled":true,"mode":"header","idleTimeoutSec":1234}}}`+ if err := os.WriteFile(path, []byte(original), 0600); err != nil {+ t.Fatal(err)+ }++ fc := &FileConfig{}+ if err := json.Unmarshal([]byte(original), fc); err != nil {+ t.Fatalf("load the hand-written config: %v", err)+ }+ if err := SetConfigValue(fc, "server.port", "19000"); err != nil {+ t.Fatal(err)+ }++ onDisk := saveAndReload(t, fc, path)+ agent := agentBlockOnDisk(t, onDisk)+ if agent["enabled"] != true {+ t.Errorf("sessions.agent.enabled = %v after an unrelated set, want the hand-written true preserved", agent["enabled"])+ }+ if agent["mode"] != "header" {+ t.Errorf("sessions.agent.mode = %v, want the hand-written value preserved", agent["mode"])+ }+ if agent["idleTimeoutSec"] != float64(1234) {+ t.Errorf("sessions.agent.idleTimeoutSec = %v, want the hand-written 1234 preserved", agent["idleTimeoutSec"])+ }+ server, _ := onDisk["server"].(map[string]any)+ if server["port"] != "19000" {+ t.Errorf("server.port = %v, want the set value 19000", server["port"])+ }+}++// The sessions vocabulary is checked against the DECLARED fields rather than against the+// names missing today. A hand-listed switch is exactly how `enabled` fell out of a section+// that otherwise looked complete, so listing the fix would reproduce the defect's cause.+func TestTheSessionsEditorAddressesEveryDeclaredField(t *testing.T) {+ for _, section := range []struct {+ prefix string+ typ reflect.Type+ }{+ {"sessions.agent.", reflect.TypeOf(AgentSessionFileConfig{})},+ {"sessions.dashboard.", reflect.TypeOf(DashboardSessionFileConfig{})},+ } {+ if section.typ.NumField() == 0 {+ t.Fatalf("%s declares no fields; this census is reading the wrong type", section.prefix)+ }+ for i := 0; i < section.typ.NumField(); i++ {+ name, _, _ := strings.Cut(section.typ.Field(i).Tag.Get("json"), ",")+ if name == "" || name == "-" {+ continue+ }+ key := section.prefix + name++ fc := &FileConfig{}+ if _, err := GetConfigValue(fc, key); err != nil {+ t.Errorf("config get %s: %v — the field is declared and the loader honours it, so refusing it as unknown tells the user the key is wrong", key, err)+ }+ }+ }+}++// The other direction: the editor must not invent keys the section does not declare.+// sessions.dashboard.enabled is the case that prompted this — it is refused today and the+// refusal is CORRECT, because no such field exists on the type, in the schema, or in the+// loader. Adding it would create exactly the accepted-and-discarded shape this card removes.+func TestTheSessionsEditorRefusesAKeyTheSectionDoesNotDeclare(t *testing.T) {+ fc := &FileConfig{}++ if _, ok := reflect.TypeOf(DashboardSessionFileConfig{}).FieldByName("Enabled"); ok {+ t.Fatal("DashboardSessionFileConfig now declares Enabled; this test pins its ABSENCE, so either the field is real and the editor should address it, or it was added by mistake")+ }+ if _, err := GetConfigValue(fc, "sessions.dashboard.enabled"); err == nil {+ t.Error("config get sessions.dashboard.enabled was accepted, but nothing declares or honours it — a settable key nothing reads is the accepted-and-discarded shape this card exists to remove")+ }+ if _, err := GetConfigValue(fc, "sessions.agent.nonesuch"); err == nil {+ t.Error("config get sessions.agent.nonesuch was accepted; the agent branch must still refuse an undeclared field")+ }+}diff --git a/internal/config/editor_set.go b/internal/config/editor_set.goindex 16fa7433..50129193 100644--- a/internal/config/editor_set.go+++ b/internal/config/editor_set.go@@ -304,9 +304,43 @@ func setSessionsField(s *SessionsFileConfig, field, value string) error {if strings.HasPrefix(field, "dashboard.") {return setDashboardSessionField(&s.Dashboard, strings.TrimPrefix(field, "dashboard."), value)}+ if strings.HasPrefix(field, "agent.") {+ return setAgentSessionField(&s.Agent, strings.TrimPrefix(field, "agent."), value)+ }return fmt.Errorf("unknown field sessions.%s", field)}+// setAgentSessionField is the write half of getAgentSessionField. mode is stored as given+// and left to ValidateFileConfig, which is where every other enumerated string in this+// editor is checked — a second vocabulary here would be a copy of the validator's.+func setAgentSessionField(s *AgentSessionFileConfig, field, value string) error {+ switch field {+ case "enabled":+ b, err := parseBool(value)+ if err != nil {+ return fmt.Errorf("sessions.agent.enabled: %w", err)+ }+ s.Enabled = &b+ case "mode":+ s.Mode = value+ case "idleTimeoutSec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("sessions.agent.idleTimeoutSec must be a number: %w", err)+ }+ s.IdleTimeoutSec = &n+ case "maxLifetimeSec":+ n, err := strconv.Atoi(value)+ if err != nil {+ return fmt.Errorf("sessions.agent.maxLifetimeSec must be a number: %w", err)+ }+ s.MaxLifetimeSec = &n+ default:+ return fmt.Errorf("unknown field sessions.agent.%s", field)+ }+ return nil+}+func setDashboardSessionField(s *DashboardSessionFileConfig, field, value string) error {switch field {case "persist":