diff --git a/cmd/server/config.go b/cmd/server/config.go index ca553f511..c15405ed6 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -449,12 +449,19 @@ type Config struct { } // CustomizerConfig holds operator-side knobs for the in-app customizer modal. -// Today only DisabledTabs is exposed: a list of tab ids the operator wants to -// hide from end users (e.g. ["branding","geofilter","export"]). The frontend +// DisabledTabs is a list of tab ids the operator wants to hide from end users +// (e.g. ["branding","geofilter","export"]). The frontend // (public/customize-v2.js _renderTabs) reads this from /api/config/client and // filters those tabs out before rendering. Issue #1508. type CustomizerConfig struct { DisabledTabs []string `json:"disabledTabs"` + // OneByteHopsDefault (#912 M2) is the 1-byte hop mode (show, mark or + // hide) of a visitor who has not picked one; "" means the operator set + // none, and the browser keeps its built-in (Show on Live, Mark + // elsewhere). Only applyOneByteHopsDefault sets it, from the canonical + // key: the struct decode skips it, so a value of the wrong type warns + // instead of rejecting the whole file. + OneByteHopsDefault string `json:"-"` } // PrivacyConfig is the entire privacy feature's configuration: one opt-in @@ -1214,6 +1221,7 @@ func (c *Config) applyCanonicalKeys(keys *configkey.Doc) error { } } c.applyMaxHopDist(keys, log.Printf) + c.applyOneByteHopsDefault(keys, log.Printf) c.Share.Nodes.Enabled = keys.On("share", "nodes", "enabled") c.Share.Packets.Enabled = keys.On("share", "packets", "enabled") c.AntennaClaims.ApplyGates(keys.On) @@ -1281,6 +1289,39 @@ func (c *Config) applyMaxHopDist(keys *configkey.Doc, logf func(string, ...inter c.MaxHopDist = &v } +// oneByteHopsModes are the 1-byte hop modes of public/hop-filter.js (#674). +var oneByteHopsModes = map[string]bool{"show": true, "mark": true, "hide": true} + +// applyOneByteHopsDefault (#912 M2) takes customizer.oneByteHopsDefault from +// the exact-case key only (#884). An absent key leaves it unset; any other +// value than show, mark or hide logs one warning and gives mark. +func (c *Config) applyOneByteHopsDefault(keys *configkey.Doc, logf func(string, ...interface{})) { + raw := keys.Get("customizer", "oneByteHopsDefault") + if raw == nil { + return + } + if c.Customizer == nil { + c.Customizer = &CustomizerConfig{} + } + var v string + if json.Unmarshal(raw, &v) != nil || !oneByteHopsModes[v] { + logf("[config] customizer.oneByteHopsDefault is not \"show\", \"mark\" or \"hide\"; using \"mark\"") + v = "mark" + } + c.Customizer.OneByteHopsDefault = v +} + +// OneByteHopsDefault is the operator default for the 1-byte hop mode, as +// /api/config/client serves it: "" unless configured. The plan of #912 M2 +// keeps an unconfigured instance as before (CS-VM1 review R2), so the server +// sends no effective default of its own. +func (c *Config) OneByteHopsDefault() string { + if c.Customizer == nil { + return "" + } + return c.Customizer.OneByteHopsDefault +} + // jsonObject is a JSON object as encoding/json decodes it into // interface{}. It is an alias, not a defined type: a decoded object's // dynamic type is the unnamed map type, and a type assertion to a defined diff --git a/cmd/server/config_one_byte_hops_default_912_test.go b/cmd/server/config_one_byte_hops_default_912_test.go new file mode 100644 index 000000000..cc26222ca --- /dev/null +++ b/cmd/server/config_one_byte_hops_default_912_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "bytes" + "encoding/json" + "log" + "os" + "reflect" + "strings" + "testing" +) + +// #912 M2 — customizer.oneByteHopsDefault: the operator's default for the +// 1-byte hop mode (show / mark / hide). It is read from the exact-case key +// only (#884); an unknown value logs one warning and falls back to mark. An +// absent key is served as no default at all, so the browser keeps its +// built-in, Show on Live and Mark elsewhere, as before M2 (the plan's "if the +// key is absent, the behaviour is as today", CS-VM1 review R2). + +func loadOneByteHopsDefault(t *testing.T, cfgJSON string) (*Config, string) { + t.Helper() + dir := t.TempDir() + writeConfigFile(t, dir, "config.json", cfgJSON) + var buf bytes.Buffer + log.SetOutput(&buf) + cfg, err := LoadConfig(dir) + log.SetOutput(os.Stderr) + if err != nil { + t.Fatal(err) + } + return cfg, buf.String() +} + +func TestOneByteHopsDefaultValidation912(t *testing.T) { + cases := []struct { + name string + json string + want string + warn bool + }{ + {"absent block", `{}`, "", false}, + {"absent key", `{"customizer": {"disabledTabs": ["export"]}}`, "", false}, + {"show", `{"customizer": {"oneByteHopsDefault": "show"}}`, "show", false}, + {"mark", `{"customizer": {"oneByteHopsDefault": "mark"}}`, "mark", false}, + {"hide", `{"customizer": {"oneByteHopsDefault": "hide"}}`, "hide", false}, + {"unknown", `{"customizer": {"oneByteHopsDefault": "bogus"}}`, "mark", true}, + {"wrong case", `{"customizer": {"oneByteHopsDefault": "Hide"}}`, "mark", true}, + {"empty", `{"customizer": {"oneByteHopsDefault": ""}}`, "mark", true}, + {"proto-ish", `{"customizer": {"oneByteHopsDefault": "constructor"}}`, "mark", true}, + {"not a string", `{"customizer": {"oneByteHopsDefault": 2}}`, "mark", true}, + {"null", `{"customizer": {"oneByteHopsDefault": null}}`, "mark", true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + cfg, logs := loadOneByteHopsDefault(t, c.json) + if got := cfg.OneByteHopsDefault(); got != c.want { + t.Fatalf("OneByteHopsDefault() = %q, want %q", got, c.want) + } + n := strings.Count(logs, "customizer.oneByteHopsDefault") + if c.warn && n != 1 { + t.Fatalf("want exactly one oneByteHopsDefault warning, got %d:\n%s", n, logs) + } + if !c.warn && n != 0 { + t.Fatalf("unexpected oneByteHopsDefault warning:\n%s", logs) + } + }) + } +} + +// A non-string value must not reject the whole config file: the field is +// read through configkey only, never by the struct decode. +func TestOneByteHopsDefaultBadTypeKeepsTheFile912(t *testing.T) { + cfg, _ := loadOneByteHopsDefault(t, `{"port": 4242, "customizer": {"oneByteHopsDefault": 2, "disabledTabs": ["export"]}}`) + if cfg.Port != 4242 { + t.Fatalf("config file was dropped: port = %d", cfg.Port) + } + if cfg.Customizer == nil || !reflect.DeepEqual(cfg.Customizer.DisabledTabs, []string{"export"}) { + t.Fatalf("disabledTabs lost: %+v", cfg.Customizer) + } +} + +// #884: a case variant is not the canonical key, so it is ignored (with the +// configkey warning) and no default is set. +func TestOneByteHopsDefaultCanonicalKeyOnly912(t *testing.T) { + for _, j := range []string{ + `{"customizer": {"OneByteHopsDefault": "hide"}}`, + `{"customizer": {"onebytehopsdefault": "hide"}}`, + `{"Customizer": {"oneByteHopsDefault": "hide"}}`, + } { + cfg, _ := loadOneByteHopsDefault(t, j) + if got := cfg.OneByteHopsDefault(); got != "" { + t.Fatalf("%s: OneByteHopsDefault() = %q, want none", j, got) + } + } + // The exact key still wins next to a variant. + cfg, _ := loadOneByteHopsDefault(t, `{"customizer": {"oneByteHopsDefault": "show", "OneByteHopsDefault": "hide"}}`) + if got := cfg.OneByteHopsDefault(); got != "show" { + t.Fatalf("exact key next to a variant: got %q, want show", got) + } +} + +func TestOneByteHopsDefaultIsANamedField912(t *testing.T) { + f, ok := reflect.TypeOf(CustomizerConfig{}).FieldByName("OneByteHopsDefault") + if !ok || f.Type.Kind() != reflect.String { + t.Fatalf("CustomizerConfig.OneByteHopsDefault must be a string field, got %v (found=%v)", f.Type, ok) + } + f, ok = reflect.TypeOf(CustomizerClientConfig{}).FieldByName("OneByteHopsDefault") + // omitempty: no configured default, no key on the wire (R2). + if !ok || f.Type.Kind() != reflect.String || f.Tag.Get("json") != "oneByteHopsDefault,omitempty" { + t.Fatalf("CustomizerClientConfig.OneByteHopsDefault must be a string tagged oneByteHopsDefault,omitempty, got %v %q", f.Type, f.Tag) + } +} + +// A configured mode is served; without one the key is left out of the +// customizer block, so Live keeps Show and other pages Mark (R2). Red with a +// server that serves mark when the key is absent. +func TestClientConfigOneByteHopsDefaultShape912(t *testing.T) { + for _, c := range []struct { + cfg string + want string // "" = the key must be absent + }{ + {`{}`, ""}, + {`{"customizer": {"disabledTabs": ["export"]}}`, ""}, + {`{"customizer": {"OneByteHopsDefault": "hide"}}`, ""}, + {`{"customizer": {"oneByteHopsDefault": "hide"}}`, "hide"}, + {`{"customizer": {"oneByteHopsDefault": "show", "disabledTabs": ["export"]}}`, "show"}, + {`{"customizer": {"oneByteHopsDefault": "mark"}}`, "mark"}, + {`{"customizer": {"oneByteHopsDefault": "nope"}}`, "mark"}, + } { + body, _ := clientConfigFor(t, c.cfg) + var got struct { + Customizer map[string]json.RawMessage `json:"customizer"` + } + if err := json.Unmarshal([]byte(body), &got); err != nil { + t.Fatal(err) + } + if got.Customizer == nil { + t.Fatalf("cfg %s: no customizer block in %s", c.cfg, body) + } + raw, ok := got.Customizer["oneByteHopsDefault"] + if c.want == "" { + if ok { + t.Fatalf("cfg %s: no default configured, but customizer.oneByteHopsDefault = %s", c.cfg, raw) + } + } else { + var v string + if !ok || json.Unmarshal(raw, &v) != nil || v != c.want { + t.Fatalf("cfg %s: customizer.oneByteHopsDefault = %s (present %v), want %q", c.cfg, raw, ok, c.want) + } + } + if _, ok := got.Customizer["disabledTabs"]; !ok { + t.Fatalf("cfg %s: customizer.disabledTabs must stay in the block", c.cfg) + } + } +} diff --git a/cmd/server/routes.go b/cmd/server/routes.go index a94b59b92..2bf7d1426 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -696,7 +696,7 @@ func (s *Server) handleConfigClient(w http.ResponseWriter, r *http.Request) { DebugAffinity: s.cfg.DebugAffinity, MapDarkTileProvider: s.cfg.MapDarkTileProvider, Tiles: s.cfg.Tiles, - Customizer: CustomizerClientConfig{DisabledTabs: disabledTabs}, + Customizer: CustomizerClientConfig{DisabledTabs: disabledTabs, OneByteHopsDefault: s.cfg.OneByteHopsDefault()}, ClientRxCoverage: s.cfg.ClientRxCoverageEnabled(), Moments: s.cfg.momentsClientConfig(), Kiosk: s.cfg.kioskClientConfig(), diff --git a/cmd/server/types.go b/cmd/server/types.go index acc9a3b08..71a4048bd 100644 --- a/cmd/server/types.go +++ b/cmd/server/types.go @@ -1721,8 +1721,11 @@ type PrivacyClientConfig struct { // /api/config/client surfaces to the frontend. Issue #1508. The field is // always present (DisabledTabs defaults to an empty slice) so the frontend // can blindly call `.disabledTabs.includes(...)` without an undefined guard. +// OneByteHopsDefault (#912 M2) is the configured mode (show, mark or hide), +// left out when the operator set none: the browser then keeps its built-in. type CustomizerClientConfig struct { - DisabledTabs []string `json:"disabledTabs"` + DisabledTabs []string `json:"disabledTabs"` + OneByteHopsDefault string `json:"oneByteHopsDefault,omitempty"` } // ─── IATA Coords ─────────────────────────────────────────────────────────────── diff --git a/config.example.json b/config.example.json index 4a57e2846..edf899305 100644 --- a/config.example.json +++ b/config.example.json @@ -714,7 +714,8 @@ "_comment_analytics": "Issue #1240 + #1256 + #1265. Each analytics endpoint (topology, rf, distance, channels, hashCollisions, hashSizes, roles, observersClockSkew, nodesClockSkew, advertIntervals) is recomputed in the background on the configured interval and served from an atomic-pointer cache. Reads never block on compute. Default 300s (5 min) per endpoint reflects the operator principle: serving slightly stale data quickly beats real-time data slowly. Lower values = fresher data at higher CPU cost. Only the default query (no region/window) is precomputed; region- and window-filtered requests fall back to the legacy on-request compute + 60s TTL cache.", "customizer": { "disabledTabs": [], - "_comment_disabledTabs": "Issue #1508. List of customizer-modal tab ids to hide from end users. Useful when operators want to expose only daily-use viewer controls and keep one-shot admin chrome out of the way. Recognized ids: branding, theme, nodes, home, display, geofilter, export. Example: [\"branding\", \"geofilter\", \"export\"] hides the admin tabs and leaves theme/colors/home/display visible. Default [] keeps the legacy behavior (all tabs visible). Operators edit this in config.json directly — there is no in-app UI for this list (by design)." + "_comment_disabledTabs": "Issue #1508. List of customizer-modal tab ids to hide from end users. Useful when operators want to expose only daily-use viewer controls and keep one-shot admin chrome out of the way. Recognized ids: branding, theme, nodes, home, display, geofilter, export. Example: [\"branding\", \"geofilter\", \"export\"] hides the admin tabs and leaves theme/colors/home/display visible. Default [] keeps the legacy behavior (all tabs visible). Operators edit this in config.json directly — there is no in-app UI for this list (by design).", + "_comment_oneByteHopsDefault": "#912 M2. Optional key customizer.oneByteHopsDefault, left out here on purpose: the 1-byte path hop mode (Display tab, Path Display) for a visitor who has not picked one. \"show\" draws 1-byte hops without markings; \"mark\" flags them: the map route marks only the uncertain inferred 1-byte hops, while the Live map dashes every segment that touches any 1-byte hop; \"hide\" leaves 1-byte hops out of the route view, the Live map and feed, and the node path panel (nothing stored changes). A configured value applies on every page, Live included. Without the key nothing changes: the Live map shows every hop unmarked and the other pages use mark. A visitor's own pick is stored in their browser and wins; one who never picked follows this value, also when you change it later. Any other value logs one warning and uses mark. The customizer labels the configured value '(server default)'. Example: \"oneByteHopsDefault\": \"hide\"." }, "privacy": { "enabled": false, diff --git a/docs/CUSTOMIZATION.md b/docs/CUSTOMIZATION.md index 81c3479f0..61a957292 100644 --- a/docs/CUSTOMIZATION.md +++ b/docs/CUSTOMIZATION.md @@ -182,7 +182,7 @@ User themes take priority over admin themes. Users can reset their personal them ### Operator display defaults (`config.json`) -Two Display settings take a default for every browser from `config.json`, served on `/api/config/client`: +Three Display settings take a default for every browser from `config.json`, served on `/api/config/client`: - **Timestamps:** the `timestamps` block. @@ -198,6 +198,15 @@ Two Display settings take a default for every browser from `config.json`, served `defaultMode` is `ago` or `absolute`, `timezone` is `local` or `utc`, and `formatPreset` is `iso`, `iso-seconds` or `locale`. An invalid value logs a warning and takes the built-in (`ago`, `local`, `iso`). `allowCustomFormat: true` offers the **Custom Format** field in the Display tab; `customFormat` is then its default, with the tokens `YYYY`, `MM`, `DD`, `HH`, `mm`, `ss`, `SSS` and `Z`. - **Live Moments:** `moments.display`, while `moments.enabled` is on. See [moments.md](moments.md#display-defaults-for-your-viewers). +- **Short (1-byte) path-hash hops** (Path Display, #912): `customizer.oneByteHopsDefault`. + + ```json + "customizer": { + "oneByteHopsDefault": "hide" + } + ``` + + `show` draws 1-byte hops without markings. `mark` flags them: the map route view marks only the uncertain inferred 1-byte hops, while the Live map dashes every segment that touches any 1-byte hop. `hide` leaves 1-byte hops out of the route view, the Live map and feed, and the node path panel. Nothing stored changes. A configured value applies on every page, Live included. Without the key nothing changes from before: the Live map shows every hop unmarked and the other pages use `mark`, and the server sends no `oneByteHopsDefault` on `/api/config/client`. Any other value logs one warning and takes `mark`. The customizer labels the operator's mode "(server default)"; without one it labels Mark "(default)", as before. A viewer's pick is always stored in their browser, so it keeps winning when the operator later changes the default. While a pick is stored, **↺ Use server default** (**↺ Use default** when no default is configured) under the setting removes it (Reset All removes it too), and the open page follows the default at once; a viewer who never picked follows the current default. Before #912, choosing Mark stored nothing, so a viewer who explicitly picked Mark then cannot be told apart from one who never picked: they now follow your default. A viewer's own value in the customizer wins over the operator's, and the operator's wins over the built-in. For Moments on/off, a `?moments=` link and the viewer's Live checkbox win over both. Keys are case-sensitive: a different spelling (`AllowCustomFormat`) is ignored with a warning in the server log. diff --git a/docs/api-spec.md b/docs/api-spec.md index 4dfb1332e..0f83be4bd 100644 --- a/docs/api-spec.md +++ b/docs/api-spec.md @@ -3063,7 +3063,11 @@ Client-side configuration values. "cacheInvalidateMs": number | null, "externalUrls": object | null, "propagationBufferMs": number, // default: 5000 - "estimatedPositions": { "enabled": boolean } // default: true; operator policy + "estimatedPositions": { "enabled": boolean }, // default: true; operator policy + "customizer": { + "disabledTabs": string[], // default: [] + "oneByteHopsDefault": "show" | "mark" | "hide" // optional; only when configured, #912 M2 + } } ``` diff --git a/public/customize-v2.js b/public/customize-v2.js index 37e0f1499..4bc628483 100644 --- a/public/customize-v2.js +++ b/public/customize-v2.js @@ -3282,26 +3282,70 @@ // ── #1633 / #674 1-byte path hops: Show / Mark / Hide ── // Reads and writes through hop-filter.js (MC_get1ByteHopsMode / - // MC_set1ByteHopsMode), which owns the storage key, the default (mark) and - // the migration of the #1633 boolean key. Every change fires + // MC_set1ByteHopsMode), which owns the storage key, the default (the + // operator's customizer.oneByteHopsDefault, else mark, #912 M2) and the + // migration of the #1633 boolean key. Without an operator default the + // field reads as before M2: Mark is the "(default)" and the hint says Live + // shows every hop (CS-VM1 review R2). Every change fires // `mc-hide-1byte-hops-changed`; map.js (which redraws the route view) and // packets.js subscribe and re-render in place (PR #1689 r1 adv #4, #673). // Analytics rebuilds on its next tab activation. + // "Use server default" (MC_clear1ByteHopsMode; "Use default" without one) + // is offered while the visitor has a stored choice, so they can follow the + // operator again (PR #1001 review F1); _syncHide1ByteHopsField keeps an + // open panel in step. + var HOP_MODE_LABELS = { show: 'Show', mark: 'Mark uncertain hops', hide: 'Hide' }; + function _hopModeState() { + return { + mode: typeof window.MC_get1ByteHopsMode === 'function' ? window.MC_get1ByteHopsMode() : 'mark', + dflt: typeof window.MC_get1ByteHopsDefault === 'function' ? window.MC_get1ByteHopsDefault() : null, + choice: typeof window.MC_getStored1ByteHopsMode === 'function' ? window.MC_getStored1ByteHopsMode() : null + }; + } + function _hopModeLabel(value, dflt) { + if (dflt) return HOP_MODE_LABELS[value] + (dflt === value ? ' (server default)' : ''); + return HOP_MODE_LABELS[value] + (value === 'mark' ? ' (default)' : ''); + } + function _hopResetLabel(dflt) { return dflt ? '↺ Use server default' : '↺ Use default'; } function _renderHide1ByteHopsToggle() { - var mode = typeof window.MC_get1ByteHopsMode === 'function' ? window.MC_get1ByteHopsMode() : 'mark'; - var opt = function (value, label) { - return ''; + var st = _hopModeState(); + var opt = function (value) { + return ''; }; return '

Path Display

' + - '

1-byte path-hash prefixes (firmware default) collide often: several nodes share each one, so a 1-byte hop on a route is a best guess. Mark flags the uncertain hops on the map route; Hide leaves 1-byte hops out everywhere without changing what\'s stored. Until you pick a mode here, the Live map shows every hop unmarked.

' + + '

1-byte path-hash prefixes (firmware default) collide often: several nodes share each one, so a 1-byte hop on a route is a best guess. Mark flags the uncertain hops on the map route; Hide leaves 1-byte hops out everywhere without changing what\'s stored. Until you pick a mode here, the Live map shows every hop unmarked.

' + '
' + '' + '' + + '' + '
'; } + // Updates the open select in place, not by re-rendering it: a pick fires + // the change event while the select has the focus. + function _syncHide1ByteHopsField() { + var sel = document.getElementById('cv2-hide-1byte-hops'); + if (!sel) return; + var st = _hopModeState(); + for (var i = 0; i < sel.options.length; i++) { + sel.options[i].textContent = _hopModeLabel(sel.options[i].value, st.dflt); + } + sel.value = st.mode; + var reset = document.getElementById('cv2-hide-1byte-hops-reset'); + if (reset) { + reset.hidden = !st.choice; + reset.textContent = _hopResetLabel(st.dflt); + } + var note = document.getElementById('cv2-hide-1byte-hops-live-note'); + if (note) note.hidden = !!st.dflt; + } + try { + window.addEventListener('mc-hide-1byte-hops-changed', _syncHide1ByteHopsField); + window.addEventListener('mc-1byte-hops-default-changed', _syncHide1ByteHopsField); + } catch (_e) { /* no window events (tests) */ } + // ── #1454 Show-encrypted-channels toggle ── // Writes localStorage["channels-show-encrypted"]. Default OFF: key is // removed (not set to "false") so the read-gate in channels.js cleanly @@ -4232,6 +4276,14 @@ if (typeof window.MC_set1ByteHopsMode === 'function') window.MC_set1ByteHopsMode(sel.value); }); }); + container.querySelectorAll('[data-cv2-hide-1byte-hops-reset]').forEach(function (btn) { + btn.addEventListener('click', function () { + if (typeof window.MC_clear1ByteHopsMode === 'function') window.MC_clear1ByteHopsMode(); + // The button hides itself; keep the focus on the setting. + var sel = document.getElementById('cv2-hide-1byte-hops'); + if (sel) sel.focus(); + }); + }); // Preset buttons container.querySelectorAll('.cust-preset-btn').forEach(function (btn) { @@ -4856,7 +4908,13 @@ } catch (_e) { /* ignore */ } }); - // 6. Encrypted-channel toggle — removing the LS key (step 1) fixes + // 6. 1-byte path hops — step 1 removed the choice; tell the open page, + // which now follows the operator default (PR #1001 review F2). + try { + if (typeof window !== 'undefined' && typeof window.MC_clear1ByteHopsMode === 'function') window.MC_clear1ByteHopsMode(); + } catch (_e) { /* ignore */ } + + // 7. Encrypted-channel toggle — removing the LS key (step 1) fixes // persistence, but channels.js subscribes to // mc-channels-show-encrypted-changed for live re-render. Fire it // explicitly with on:false so the channels list reverts to "hide diff --git a/public/hop-filter.js b/public/hop-filter.js index 685858c6b..bbe58bb23 100644 --- a/public/hop-filter.js +++ b/public/hop-filter.js @@ -19,10 +19,15 @@ // show — as before #674, no markings; // mark — (default) visible, uncertain hops marked in the map route view; // hide — the #1633 behaviour: 1-byte hops left out everywhere. - // "No key" means the visitor never chose; an explicit choice, Mark - // included, is always stored (#912 M1: Live tells the two apart). The #1633 - // boolean key migrates once: "true" becomes mode "hide"; anything else is - // dropped. + // #912 M2 — the mode is the visitor's stored choice, else the operator's + // default (customizer.oneByteHopsDefault on /api/config/client), else the + // caller's built-in: mark, Show on Live. The server sends a default only + // when the operator configured one (CS-VM1 review R2). + // Every explicit choice is stored, so a pick equal to today's default still + // wins when the operator changes it; a visitor who never chose has no key + // and follows the operator; clear1ByteHopsMode() takes a visitor back to + // that (PR #1001 review). The #1633 boolean key migrates once: "true" + // becomes mode "hide"; anything else is dropped. var MODE_KEY = 'meshcore-1byte-hops-mode'; var LEGACY_KEY = 'meshcore-hide-1byte-hops'; var MODES = ['show', 'mark', 'hide']; @@ -32,7 +37,20 @@ // pass as a mode (#677 review). function isMode(m) { return MODES.indexOf(m) !== -1; } - function get1ByteHopsMode() { + // The operator default, or null when none is configured. roles.js hands it + // over once the client config arrives; a config that arrived before this + // file ran is read here. + var operatorDefault = null; + if (typeof window !== 'undefined' && window.MC_CUSTOMIZER_CFG && isMode(window.MC_CUSTOMIZER_CFG.oneByteHopsDefault)) { + operatorDefault = window.MC_CUSTOMIZER_CFG.oneByteHopsDefault; + } + + function get1ByteHopsDefault() { return operatorDefault; } + + // The visitor's stored choice, or null when they never chose or went back + // to the default (#912 M1/M2). Junk is dropped and the #1633 key migrates + // here, so every reader sees the same choice. + function getStored1ByteHopsMode() { try { var stored = localStorage.getItem(MODE_KEY); if (isMode(stored)) return stored; @@ -48,7 +66,21 @@ } } } catch (_e) { /* storage unavailable */ } - return DEFAULT_MODE; + return null; + } + + // The mode in force: the stored choice, else the operator default, else + // `fallback` when it is a mode, else mark. Live passes "show" (#912). + function get1ByteHopsMode(fallback) { + return getStored1ByteHopsMode() || operatorDefault || (isMode(fallback) ? fallback : DEFAULT_MODE); + } + + function fireChanged(mode) { + if (typeof window !== 'undefined' && typeof window.CustomEvent === 'function') { + window.dispatchEvent(new window.CustomEvent('mc-hide-1byte-hops-changed', { + detail: { mode: mode, value: mode === 'hide' } + })); + } } function set1ByteHopsMode(mode) { @@ -57,20 +89,31 @@ localStorage.setItem(MODE_KEY, mode); localStorage.removeItem(LEGACY_KEY); } catch (_e) { /* private mode */ } - if (typeof window !== 'undefined' && typeof window.CustomEvent === 'function') { - window.dispatchEvent(new window.CustomEvent('mc-hide-1byte-hops-changed', { - detail: { mode: mode, value: mode === 'hide' } - })); - } + fireChanged(mode); } - // #912 M1 — the visitor's own choice, or null when they never made one. - // Runs get1ByteHopsMode() first so junk is dropped and the #1633 key - // migrates exactly as for every other reader. - function getStored1ByteHopsMode() { - var mode = get1ByteHopsMode(); - try { return localStorage.getItem(MODE_KEY) != null ? mode : null; } - catch (_e) { return null; } + // Forget the choice: the visitor follows the operator default again. + function clear1ByteHopsMode() { + try { + localStorage.removeItem(MODE_KEY); + localStorage.removeItem(LEGACY_KEY); + } catch (_e) { /* private mode */ } + fireChanged(get1ByteHopsMode()); + } + + // #912 M2 — set the operator default (anything but a mode clears it). A + // visitor who follows the default is told when their mode changes; the + // customizer, which labels the default, is told when the default changes. + function set1ByteHopsDefault(mode) { + var before = get1ByteHopsMode(); + var beforeDefault = get1ByteHopsDefault(); + operatorDefault = isMode(mode) ? mode : null; + var after = get1ByteHopsMode(); + if (after !== before) fireChanged(after); + var dflt = get1ByteHopsDefault(); + if (dflt !== beforeDefault && typeof window !== 'undefined' && typeof window.CustomEvent === 'function') { + window.dispatchEvent(new window.CustomEvent('mc-1byte-hops-default-changed', { detail: { default: dflt } })); + } } // #1633 API, kept for its callers: "hide" is mode hide; turning it off @@ -150,6 +193,9 @@ window.MC_get1ByteHopsMode = get1ByteHopsMode; window.MC_set1ByteHopsMode = set1ByteHopsMode; window.MC_getStored1ByteHopsMode = getStored1ByteHopsMode; + window.MC_clear1ByteHopsMode = clear1ByteHopsMode; + window.MC_get1ByteHopsDefault = get1ByteHopsDefault; + window.MC_set1ByteHopsDefault = set1ByteHopsDefault; window.MC_isVisibleHop = isVisibleHop; window.MC_filterPathHops = filterPathHops; window.MC_hopByteLen = hopByteLen; @@ -163,6 +209,9 @@ get1ByteHopsMode: get1ByteHopsMode, set1ByteHopsMode: set1ByteHopsMode, getStored1ByteHopsMode: getStored1ByteHopsMode, + clear1ByteHopsMode: clear1ByteHopsMode, + get1ByteHopsDefault: get1ByteHopsDefault, + set1ByteHopsDefault: set1ByteHopsDefault, isVisibleHop: isVisibleHop, filterPathHops: filterPathHops, hopByteLen: hopByteLen, diff --git a/public/live.js b/public/live.js index 6f3130b57..ad29595e4 100644 --- a/public/live.js +++ b/public/live.js @@ -4864,14 +4864,12 @@ // #912 M1 — the 1-byte hop setting of hop-filter.js (#674), read per // packet so a change (MC_set1ByteHopsMode fires mc-hide-1byte-hops-changed) // reaches the next packet at once; animations in flight just finish. - // A visitor who never chose (or no hop-filter.js) gets Show on Live: owner - // decision on #912 (2026-11-27) until M2's operator default replaces this - // fallback. Other pages keep hop-filter.js's own default. - const LIVE_1BYTE_HOPS_FALLBACK = 'show'; + // The visitor's choice, else the operator default (#912 M2), else Show: + // with no default from /api/config/client (or no hop-filter.js) Live draws + // as before #912, owner decision on #912 (2026-11-27). function oneByteHopsMode() { - const stored = typeof window.MC_getStored1ByteHopsMode === 'function' - ? window.MC_getStored1ByteHopsMode() : null; - return stored || LIVE_1BYTE_HOPS_FALLBACK; + return typeof window.MC_get1ByteHopsMode === 'function' + ? window.MC_get1ByteHopsMode('show') : 'show'; } // #912 M1 — applies the mode to a path before it is resolved. Hide leaves diff --git a/public/roles.js b/public/roles.js index 306b2afca..9d2e39be9 100644 --- a/public/roles.js +++ b/public/roles.js @@ -966,9 +966,15 @@ // #1508 — expose operator-side customizer knobs to customize-v2.js. // Default to an empty disabledTabs list so the .indexOf() guard in // _renderTabs is a no-op when the field is absent. + // #912 M2 — oneByteHopsDefault is the operator's 1-byte hop mode for + // visitors who never picked one; hop-filter.js validates it. window.MC_CUSTOMIZER_CFG = (cfg.customizer && typeof cfg.customizer === 'object') - ? { disabledTabs: Array.isArray(cfg.customizer.disabledTabs) ? cfg.customizer.disabledTabs : [] } + ? { + disabledTabs: Array.isArray(cfg.customizer.disabledTabs) ? cfg.customizer.disabledTabs : [], + oneByteHopsDefault: cfg.customizer.oneByteHopsDefault + } : { disabledTabs: [] }; + if (typeof window.MC_set1ByteHopsDefault === 'function') window.MC_set1ByteHopsDefault(window.MC_CUSTOMIZER_CFG.oneByteHopsDefault); // #1574 — operator-configurable cap on /live map node count. if (cfg.liveMapMaxNodes != null) window.LIVE_MAP_MAX_NODES = cfg.liveMapMaxNodes; // Configured geo_filter box/polygon (#730), for classifying domestic diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 2ff2662f5..5ea3e9a80 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -61,6 +61,7 @@ {"file":"test-issue-723-heritage-info-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":47.317,"measurementNote":"New suite; #723 M2 click-for-info on the protected ancient monuments overlay on Map and Live with an intercepted heritage client-config block, a stubbed and recorded GET /api/terrain/heritage and the agency's WMS answered by a 1x1 PNG (neither the WMS nor the WFS is contacted): no lookup with the overlay off or at zoom 11, one lat/lon-only lookup and the monument popup at zoom 13, the overlay going off closing it, dataset HTML shown as text and never run, a node marker click and Path profile picking winning over the lookup, a 44x44 close button at 360x740 touch on both pages, a popup closed while its lookup is pending staying closed (the lookup aborted) on both pages, and the popup's theme variables in light and dark. About 85s locally; no CI duration measured yet. Assigned to shard 1 next to the #723 M1 suite.","secondsByExecution":[44.621,45.271,45.618,45.822,53.546,49.026]}, {"file":"test-issue-723-profile-warning-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":36.6,"measurementNote":"New suite; #723 M3 protected ancient monument warning in the Map Path profile with intercepted dhm and heritage client-config blocks, a stubbed /api/terrain/profile and a stubbed, recorded GET /api/terrain/heritage (the agency's WMS/WFS, DHM and every other outside host are stubbed or refused): no lookup without the heritage block; A inside a zone, B 42 m from one and both at once each show the warn chip in the title row and the note under the detail line with the neutral wording, type, distance and credit, one lat/lon-only lookup per end, and the verdict chip exactly as without the block; a height edit adds no lookup and Close takes the note away; nothing near, 502 and 429 stay silent with no all-clear text; hostile dataset text is inert; at 740x360, 568x320 and 844x390 touch the note does not move the chart, which stays hit-testable on screen; the chip and note border use --warning in light and dark. About 16s locally; no CI duration measured yet. Assigned to shard 1 next to the #723 M1/M2 suites.","secondsByExecution":[32.093,33.121,33.526,35.722,46.882,38.256]}, {"file":"test-issue-674-1byte-hop-modes-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":8.871,"measurementNote":"New suite; #674 1-byte hop Show/Mark/Hide: Mark default (badge, uncertain summary, chips, dashed markers) on the 22-hop 1-byte fixture route, live mode changes through the customizer select, #1633 key migration, 2-byte control, light/dark notice theming and a 375px no-overflow check. About 20s locally; no CI duration measured yet. Assigned to shard 1 next to #673.","secondsByExecution":[7.198,7.711,7.902,8.547,12.554,9.315]}, + {"file":"test-issue-912-m2-1byte-operator-default-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","measurementNote":"New suite; #912 M2 operator default for the 1-byte hop mode: no customizer.oneByteHopsDefault served without the key and the customizer labels as before M2, a fresh visitor under an intercepted hide default (no 1-byte relays on the 22-hop fixture route, nothing stored, customizer labels the server default), the visitor's own Show and an explicit Mark winning over it across a reload, the customizer setting at 375x560 in light and dark, and (PR #1001 review) Use server default, Reset All and a late client config. No CI duration measured yet; about 180 s locally with 11 steps, under load. Assigned to shard 1 next to #674."}, {"file":"test-issue-673-map-hide-inferred-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":3.792,"measurementNote":"New suite; #673 map packet route honours the hide-1-byte-hops toggle for inferred hops: live toggle off/on/off on a 22-hop 1-byte route with one observer and with a synthetic second observer (drawPacketRouteMulti), plus a 14-hop 2-byte control route. About 3s locally; no CI duration measured yet. Assigned to shard 1, which runs the fewest suites.","secondsByExecution":[3.129,3.294,3.33,3.648,5.273,4.08]}, {"file":"test-issue-598-hop-path-inference-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":9.687,"measurementNote":"New suite; #598 whole-path hop inference on fixture packet 57224a4a01c9c682 observation 147 (22 one-byte hops) at 1280 and 390 px, including the map route view. About 20s locally; no CI duration measured yet. Assigned to shard 1 (fewest suites).","secondsByExecution":[9.235,9.318,9.356,9.646,10.754,9.811]}, {"file":"test-issue-262-mymesh-observer-e2e.js","shard":1,"env":{"CHROMIUM_REQUIRE":"1"},"output":"e2e","meanSeconds":1.841,"measurementNote":"New suite; #262 My Mesh observer identity, status, traffic, navigation and unavailable state at 1280 px and 390 px. Fully stubbed (no BASE_URL server). About 6s locally; no CI duration measured yet. Assigned to shard 1, the shard with the fewest suites.","secondsByExecution":[1.645,1.686,1.725,1.759,2.361,1.872]}, @@ -337,7 +338,7 @@ {"file":"test-issue-978-view-path-recovery-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":3.5,"measurementNote":"New suite; #978 items 2 and 3 on a 375x560 touch phone from a cold start in the light and dark theme: a View Path whose /api/packets//path request is aborted once shows a 44x44+ Try again that refetches and draws the map; a shared #/packets/?viewPath=1 link with packet-path-map.js blocked shows a notice, keeps ?viewPath=1, reports a second blocked retry, then loads the script and opens the modal; Close on the notice drops ?viewPath=1; Escape closes it, a second open replaces it, and leaving the page removes it. 3.5s locally (mean of 5 runs, 3.4 to 3.6s); no CI duration measured yet. Assigned to shard 3, the lightest by meanSeconds.","secondsByExecution":[]}, {"file":"test-984-live-affinity-poller-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":22,"measurementNote":"New suite; #984 the Live neighbor-graph (hop affinity) poller on Playwright's clock, with the app socket replaced by page.routeWebSocket and every /api/analytics/neighbor-graph request intercepted (held, or answered with the real server body), counted and tracked while open: a 375x560 touch phone from a cold start whose connection stalls for 5 ticks makes one request per tick, each aborted by the timeout before the next, never two open; while one is held extra ticks and a re-armed poller add none, and the next tick's answer reaches HopResolver.setAffinity; a hidden tab (document.hidden overridden, the real visibilitychange listener) polls nothing for 5 min and refreshes exactly once on return with stale data, not with fresh; #/live?kiosk=1 at 1920x1080 still refreshes every 60 s; leaving Live aborts the open request and nothing polls afterwards, and an in-place remount polls on one interval. About 22s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-990-packets-live-area-e2e.js","shard":2,"env":{"CHROMIUM_REQUIRE":"1"},"output":"e2e","meanSeconds":7,"measurementNote":"New suite; #990 live WebSocket packets on the Packets page follow the Area filter. Fully stubbed (page.route and routeWebSocket), no server needed. Local runs about 7 s; assigned to the lightest shard."}, - {"file":"test-issue-912-live-1byte-hops-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":10.5,"measurementNote":"#912 M1 the Live map follows the 1-byte hop setting: with no stored mode Live uses Show (owner decision, until M2); ADVERT routes between fixture nodes through the real WS handler with every L.polyline recorded; at 1440x900 with the mode switched through the customizer select and no reload, Show draws the 1-byte hop unmarked (control), Hide leaves no polyline vertex on it and draws A to C dashed and lighter (live-path-uncertain), a pure 1-byte path with decoded.path.hops set draws no hop through the renderPacketTree fallback, a multi-byte route stays unmarked, Mark keeps the hop and marks only the segments that touch it; a 375x560 touch phone from a cold start picks Hide by real taps (More, Customize, Display) and Live draws no vertex on the hop. About 10s in CI shard 1 (run 46044676327) and 10.5s locally with the #912 fix-round steps. Assigned to shard 1, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, + {"file":"test-issue-912-live-1byte-hops-e2e.js","shard":1,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":10.5,"measurementNote":"#912 M1 the Live map follows the 1-byte hop setting: with no stored mode on a server without the key no default is served and Live draws Show while other pages keep Mark (#912 M2, CS-VM1 review R2), with an intercepted hide default Hide and without a default Show (owner decision); ADVERT routes between fixture nodes through the real WS handler with every L.polyline recorded; at 1440x900 with the mode switched through the customizer select and no reload, Show draws the 1-byte hop unmarked (control), Hide leaves no polyline vertex on it and draws A to C dashed and lighter (live-path-uncertain), a pure 1-byte path with decoded.path.hops set draws no hop through the renderPacketTree fallback, a multi-byte route stays unmarked, Mark keeps the hop and marks only the segments that touch it; a 375x560 touch phone from a cold start picks Hide by real taps (More, Customize, Display) and Live draws no vertex on the hop. About 10s in CI shard 1 (run 46044676327) and 10.5s locally with the #912 fix-round steps; the two #912 M2 steps add two cold Live loads, no CI duration measured for them yet. Assigned to shard 1, the lightest by the sum of meanSeconds.","secondsByExecution":[]}, {"file":"test-issue-740-m3a-dagi-filter-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":10,"measurementNote":"New suite; #740 M3a the Danish areas (DAGI) filter on the Nodes page against the real GET /api/config/dagi: at 375x560 touch in light and dark from a cold #/nodes with real taps only, the trigger opens a bottom sheet inside the viewport (no sideways scroll, 44 px rows, no autofocus in the search), aar finds Aarhus and the postcodes, a tap puts kommune=0751 in the URL and the request (that one /api/nodes answer is fulfilled from a real fixture node, as the fixture has no Danish node), labels the trigger and shows the hidden-count notice, and the clear button takes it all away again; unmocked: kommune=0860 shows the server count and an empty list, an unknown code is never sent and leaves the URL, the most specific of several params wins; at 1440x900 keyboard pick, Escape and a search or tab change keeping the param; first open and a search timed at 4x CPU throttling; the saved pick across a reload and a street postcode link. About 9s locally; no CI duration measured yet. Assigned to shard 3, the lightest by the sum of meanSeconds."}, {"file":"test-issue-740-m3b-packets-live-dagi-e2e.js","shard":1,"env":{"CHROMIUM_REQUIRE":"1"},"output":"e2e","meanSeconds":8,"measurementNote":"New suite; #740 M3b live WebSocket packets on the Packets page follow the DAGI filter by the server's rule (the ADVERT sender is in the member set; a known area nobody is in matches nothing; an unknown or unchecked code is never sent), with one member-set request per selection change, picked with the real dagi-filter.js control. Fully stubbed (page.route and routeWebSocket), no server needed. About 8 s locally; no CI duration measured yet. Assigned to shard 1, the lightest by the sum of meanSeconds."}, {"file":"test-issue-740-m3b-dagi-packets-map-e2e.js","shard":2,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":85,"measurementNote":"New suite; #740 M3b against the real server: Packets and Map at 375x560 touch in light and dark from a cold start with real taps (a bottom sheet nothing covers, kommune=0751 on /api/packets with one member-set request and the ADVERT note; the Map outline from one polygon request, fitted on the pick, a zoom asks for nothing, the clear removes it and its credit; the #740 M3b follow-up adds the Map case at 360x640 and checks that the pick closes the controls panel so nothing covers the fitted outline), 1440x900 light and dark (a cold link with its own view draws without a fit, a keyboard pick in the unclipped popover replaces the outline and fits, pan and zoom ask for nothing), a leave/re-enter leak check, and the Packets REST and URL-writer cases. About 60 s locally; no CI duration measured yet. Assigned to shard 2, the lightest by the sum of meanSeconds after the stubbed suite."}, diff --git a/test-all.sh b/test-all.sh index 9c506642c..ed05da391 100755 --- a/test-all.sh +++ b/test-all.sh @@ -411,6 +411,7 @@ run test-drag-manager.js run test-fluid-scaffolding.js run test-hop-resolver-affinity.js run test-issue-912-max-hop-dist.js +run test-issue-912-m2-1byte-operator-default.js run test-issue-598-hop-path-inference.js run test-issue-598-hop-path-detail.js run test-issue-1470-card-bg-contrast.js diff --git a/test-issue-912-live-1byte-hops-e2e.js b/test-issue-912-live-1byte-hops-e2e.js index 3910575a2..b3b69653b 100644 --- a/test-issue-912-live-1byte-hops-e2e.js +++ b/test-issue-912-live-1byte-hops-e2e.js @@ -11,8 +11,10 @@ * * 1. 1440x900, the mode switched through the customizer's own select and no * reload between modes (mc-hide-1byte-hops-changed): - * - no stored mode (cold start): Live uses Show, so B is drawn unmarked - * (owner decision on #912, 2026-11-27, until M2); + * - no stored mode (cold start) on a server without + * customizer.oneByteHopsDefault: the server serves no default, and + * Live draws Show while other pages keep Mark, as before #912 M2 + * (CS-VM1 review R2; red where the server serves mark for no key); * - Show: a vertex sits on B and no segment is marked (control); a pure * 1-byte path is drawn; * - Hide: no polyline vertex sits on B, and A→C is drawn dashed and @@ -24,7 +26,11 @@ * - Mark: B stays, A→B and B→C carry the dashed class, and a route * with only multi-byte hops carries none; the choice is stored; * 2. a 375x560 touch phone from a cold start: More → Customize → Display by - * real taps, Hide picked, Live by a real tap; no vertex on B. + * real taps, Hide picked, Live by a real tap; no vertex on B; + * 3. #912 M2, a fresh profile with /api/config/client answering + * oneByteHopsDefault "hide": Hide on Live (no vertex on B), nothing + * stored; with no default in the client config (an older server), Live + * draws as before #912: Show (owner decision on #912, 2026-11-27). * * Usage: BASE_URL=http://localhost:13581 node test-issue-912-live-1byte-hops-e2e.js */ @@ -40,10 +46,22 @@ async function step(name, fn) { } function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } -async function open(browser, { phone = false } = {}) { +// With `hopsDefault`, /api/config/client is answered with that +// customizer.oneByteHopsDefault; null removes the key. +async function open(browser, { phone = false, hopsDefault } = {}) { const ctx = await browser.newContext(phone ? { viewport: { width: 375, height: 560 }, isMobile: true, hasTouch: true } : { viewport: { width: 1440, height: 900 } }); + if (hopsDefault !== undefined) { + await ctx.route('**/api/config/client*', async (route) => { + const res = await route.fetch(); + const cfg = await res.json(); + cfg.customizer = cfg.customizer || {}; + if (hopsDefault === null) delete cfg.customizer.oneByteHopsDefault; + else cfg.customizer.oneByteHopsDefault = hopsDefault; + await route.fulfill({ response: res, json: cfg }); + }); + } await ctx.addInitScript(() => { try { if (sessionStorage.getItem('__e2e912_seeded')) return; // a cold start, once per tab @@ -194,15 +212,22 @@ async function pickMode(page, mode, phone) { const pureOneByte = [{ node: B, bytes: 1 }]; let id = 0; - await step('no stored mode (cold start): Live uses Show, the 1-byte hop is drawn unmarked', async () => { + // This suite runs against a server with no customizer.oneByteHopsDefault + // in its config (CI: no config.json). + await step('no stored mode (cold start), no operator default: no default served, Show on Live, Mark elsewhere', async () => { + const cust = (await (await h.page.request.get(BASE + '/api/config/client')).json()).customizer; const st = await h.page.evaluate(() => ({ stored: localStorage.getItem('meshcore-1byte-hops-mode'), - global: window.MC_get1ByteHopsMode() })); + global: window.MC_get1ByteHopsMode(), live: window._liveOneByteHopsMode(), dflt: window.MC_get1ByteHopsDefault() })); assert(st.stored === null, 'precondition: no stored mode, got ' + st.stored); - assert(st.global === 'mark', 'other pages keep hop-filter.js\'s default (mark), got ' + st.global); const polys = await send(h.page, ++id, A, route); - assert(hasVertex(polys, B), 'Live must draw a vertex on B: ' + JSON.stringify(polys)); - assert(segment(polys, A, B) && segment(polys, B, C), 'A→B and B→C must be drawn'); - assert(!polys.some(uncertain), 'no stored mode marks nothing on Live: ' + JSON.stringify(polys.filter(uncertain))); + const got = { + served: cust && 'oneByteHopsDefault' in cust ? cust.oneByteHopsDefault : null, + live: st.live, global: st.global, dflt: st.dflt, + vertexOnB: hasVertex(polys, B), abDrawn: !!segment(polys, A, B), anyDashed: polys.some(uncertain), + }; + const want = { served: null, live: 'show', global: 'mark', dflt: null, vertexOnB: true, abDrawn: true, anyDashed: false }; + assert(JSON.stringify(got) === JSON.stringify(want), + 'as before M2 (R2): got ' + JSON.stringify(got) + ', want ' + JSON.stringify(want)); }); await step('Show (control): the 1-byte hop is drawn, nothing is marked', async () => { @@ -249,7 +274,7 @@ async function pickMode(page, mode, phone) { assert(cd && !uncertain(cd), 'C→D is certain: ' + JSON.stringify(cd)); assert(ab.opacity < cd.opacity, 'a marked segment is lighter: ' + ab.opacity + ' vs ' + cd.opacity); const stored = await h.page.evaluate(() => localStorage.getItem('meshcore-1byte-hops-mode')); - assert(stored === 'mark', 'an explicit Mark must be stored, or Live falls back to Show: ' + stored); + assert(stored === 'mark', 'an explicit Mark must be stored, or Live follows the default: ' + stored); }); await step('no page errors', async () => { @@ -274,6 +299,38 @@ async function pickMode(page, mode, phone) { assert(h.errors.length === 0, h.errors.join(' | ')); await h.ctx.close(); }); + + // #912 M2: red with M1's `stored || 'show'` fallback, which drew B. + await step('M2: oneByteHopsDefault "hide" and a fresh profile: Hide on Live, nothing stored', async () => { + const h = await open(browser, { hopsDefault: 'hide' }); + await h.page.goto(BASE + '/#/live', { waitUntil: 'load' }); + await readyLive(h.page); + await h.page.waitForFunction(() => window.MC_get1ByteHopsDefault() === 'hide', null, { timeout: 10000 }); + const [A, B, C] = await pickNodes(h.page); + const st = await h.page.evaluate(() => ({ stored: localStorage.getItem('meshcore-1byte-hops-mode'), + live: window._liveOneByteHopsMode() })); + assert(st.stored === null && st.live === 'hide', JSON.stringify(st)); + const polys = await send(h.page, 98, A, [{ node: B, bytes: 1 }, { node: C, bytes: 2 }]); + assert(polys.length > 0 && !hasVertex(polys, B), 'a vertex sits on the hidden hop B: ' + JSON.stringify(polys)); + assert(uncertain(segment(polys, A, C)), 'A→C must be dashed: ' + JSON.stringify(polys)); + assert(h.errors.length === 0, h.errors.join(' | ')); + await h.ctx.close(); + }); + + await step('M2: no default in the client config and a fresh profile: Show on Live', async () => { + const h = await open(browser, { hopsDefault: null }); + await h.page.goto(BASE + '/#/live', { waitUntil: 'load' }); + await readyLive(h.page); + await h.page.waitForFunction(() => window.MC_CUSTOMIZER_CFG && window.MC_CUSTOMIZER_CFG.oneByteHopsDefault === undefined, + null, { timeout: 10000 }); + const [A, B, C] = await pickNodes(h.page); + const st = await h.page.evaluate(() => ({ live: window._liveOneByteHopsMode(), global: window.MC_get1ByteHopsMode() })); + assert(st.live === 'show' && st.global === 'mark', JSON.stringify(st)); + const polys = await send(h.page, 97, A, [{ node: B, bytes: 1 }, { node: C, bytes: 2 }]); + assert(hasVertex(polys, B) && !polys.some(uncertain), 'Show draws B unmarked: ' + JSON.stringify(polys)); + assert(h.errors.length === 0, h.errors.join(' | ')); + await h.ctx.close(); + }); } finally { await browser.close(); } diff --git a/test-issue-912-live-1byte-hops.js b/test-issue-912-live-1byte-hops.js index 7be37e69e..ccf952f48 100644 --- a/test-issue-912-live-1byte-hops.js +++ b/test-issue-912-live-1byte-hops.js @@ -6,11 +6,11 @@ * Live map animation follows it too, against the real public/live.js, * public/hop-filter.js and public/hop-resolver.js in a vm sandbox: * - * 1. the mode is read per packet from the visitor's stored choice - * (MC_getStored1ByteHopsMode), so a change (MC_set1ByteHopsMode fires - * mc-hide-1byte-hops-changed) reaches the next packet at once; with no - * stored choice, or without hop-filter.js, Live uses Show (owner - * decision on #912, 2026-11-27, until M2); + * 1. the mode is read per packet: the visitor's stored choice, else the + * operator default (#912 M2, customizer.oneByteHopsDefault), else Show + * when no default has arrived or hop-filter.js is missing (owner + * decision on #912, 2026-11-27); a change (MC_set1ByteHopsMode fires + * mc-hide-1byte-hops-changed) reaches the next packet at once; * 2. Show: every hop reaches the animation, no segment is marked; * 3. Hide: 1-byte hops are left out, the server's resolved_path stays * paired with the hop it belongs to, and when hops were dropped every @@ -48,7 +48,9 @@ function makeStorage(seed) { // A browser-like sandbox with just enough DOM for live.js to load. Leaflet, // the app shell and the WS channel are stubs; hop filtering and resolution // are the real files. -function loadLive({ withHopFilter = true, storage = {} } = {}) { +// operatorDefault is handed over as roles.js does once /api/config/client +// arrives (MC_set1ByteHopsDefault); omitted, no client config has arrived. +function loadLive({ withHopFilter = true, storage = {}, operatorDefault } = {}) { const el = () => ({ style: {}, dataset: {}, textContent: '', innerHTML: '', classList: { add() {}, remove() {}, contains() { return false; } }, @@ -106,6 +108,7 @@ function loadLive({ withHopFilter = true, storage = {} } = {}) { vm.runInContext(fs.readFileSync(path.join(__dirname, 'public', f), 'utf8'), ctx, { filename: f }); for (const k of Object.keys(ctx.window)) ctx[k] = ctx.window[k]; } + if (operatorDefault !== undefined) ctx.window.MC_set1ByteHopsDefault(operatorDefault); return ctx; } @@ -136,8 +139,9 @@ console.log('\n=== #912 M1: the mode Live reads ==='); const ctx = setup(); const mode = ctx.window._liveOneByteHopsMode; - test('no stored mode: the Live map uses Show; other pages keep hop-filter.js\'s default', () => { - // Owner decision on #912 (2026-11-27): Live defaults to Show until M2. + test('no stored mode and no operator default yet: the Live map uses Show; other pages keep hop-filter.js\'s default', () => { + // Owner decision on #912 (2026-11-27): without an operator default, Live + // draws as before #912. assert.strictEqual(typeof mode, 'function', '_liveOneByteHopsMode must be exposed'); assert.strictEqual(ctx.localStorage.getItem('meshcore-1byte-hops-mode'), null, 'precondition: no choice'); assert.strictEqual(mode(), 'show'); @@ -145,6 +149,40 @@ console.log('\n=== #912 M1: the mode Live reads ==='); assert.strictEqual(ctx.window.MC_getStored1ByteHopsMode(), null); }); + // #912 M2: once M2 lands the operator default decides the starting mode + // (owner decision, 2026-11-27). Red with M1's `stored || 'show'` fallback. + test('oneByteHopsDefault "hide" and a fresh profile: Hide on Live', () => { + const fresh = loadLive({ operatorDefault: 'hide' }); + assert.strictEqual(fresh.localStorage.getItem('meshcore-1byte-hops-mode'), null, 'precondition: no choice'); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'hide'); + }); + + for (const dflt of ['show', 'mark']) { + test('no stored mode: the operator default "' + dflt + '" applies on Live', () => { + assert.strictEqual(loadLive({ operatorDefault: dflt }).window._liveOneByteHopsMode(), dflt); + }); + } + + test('a stored choice beats the operator default on Live, Mark too', () => { + const fresh = loadLive({ storage: { 'meshcore-1byte-hops-mode': 'mark' }, operatorDefault: 'hide' }); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'mark'); + }); + + test('a default that arrives late reaches the next packet; Use server default returns to it', () => { + const fresh = loadLive(); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'show', 'before the client config'); + fresh.window.MC_set1ByteHopsDefault('hide'); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'hide', 'after the client config'); + fresh.window.MC_set1ByteHopsMode('show'); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'show', 'a pick'); + fresh.window.MC_clear1ByteHopsMode(); + assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'hide', 'back to the operator default'); + }); + + test('an invalid operator default counts as none: Show on Live', () => { + assert.strictEqual(loadLive({ operatorDefault: 'constructor' }).window._liveOneByteHopsMode(), 'show'); + }); + test('no stored mode: a 1-byte route is drawn unmarked on Live', () => { const out = ctx.window._liveResolveHopPositions(['18', 'C2C2'], PAYLOAD, [B.public_key, C.public_key], mode()); @@ -164,9 +202,11 @@ console.log('\n=== #912 M1: the mode Live reads ==='); assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'hide'); }); - test('a junk stored mode counts as no choice: Show on Live', () => { - const fresh = loadLive({ storage: { 'meshcore-1byte-hops-mode': 'constructor' } }); - assert.strictEqual(fresh.window._liveOneByteHopsMode(), 'show'); + test('a junk stored mode counts as no choice: the operator default on Live, else Show', () => { + const withDefault = loadLive({ storage: { 'meshcore-1byte-hops-mode': 'constructor' }, operatorDefault: 'hide' }); + assert.strictEqual(withDefault.window._liveOneByteHopsMode(), 'hide'); + const without = loadLive({ storage: { 'meshcore-1byte-hops-mode': 'constructor' } }); + assert.strictEqual(without.window._liveOneByteHopsMode(), 'show'); }); test('a mode change reaches the next packet at once (MC_set1ByteHopsMode)', () => { diff --git a/test-issue-912-m2-1byte-operator-default-e2e.js b/test-issue-912-m2-1byte-operator-default-e2e.js new file mode 100644 index 000000000..1745796b6 --- /dev/null +++ b/test-issue-912-m2-1byte-operator-default-e2e.js @@ -0,0 +1,313 @@ +/** + * E2E (#912 M2) — the operator chooses the default 1-byte hop mode. + * + * The server's own /api/config/client carries customizer.oneByteHopsDefault + * only when config.json sets it; this suite runs against a server without + * the key, which serves none (CS-VM1 review R2). The other steps answer that request + * with the server's real body plus oneByteHopsDefault "hide", and check on + * the 22-hop 1-byte fixture route (packet 57224a4a01c9c682, observation 147, + * as #674's suite uses) that: + * - a fresh visitor gets Hide: no 1-byte relays on the route, nothing + * stored, and the customizer selects Hide and labels it the server default; + * - a visitor's own choice (Show, picked in the customizer) wins over the + * default and survives a reload; + * - an explicit Mark survives the Hide default across a reload. + * Also: the customizer's 1-byte hop setting on a 375x560 phone, light and + * dark, does not scroll sideways and fits the screen. + * PR #1001 review: + * - F1 "Use server default" takes a visitor who picked Show back to the + * Hide default, on the open route, and they keep following it; + * - F2 Reset All does the same without a reload; + * - F3 a customizer opened before /api/config/client lands shows the + * operator default once it does. + * + * Usage: BASE_URL=http://localhost:13581 node test-issue-912-m2-1byte-operator-default-e2e.js + * Set E2E_SHOTS= to keep the phone screenshots. + */ +'use strict'; +const path = require('path'); +const { chromium } = require('playwright'); + +const BASE = process.env.BASE_URL || 'http://localhost:13581'; +const ONE_BYTE = '#/map?packet=57224a4a01c9c682&obs=147'; +const RELAYS = 22; +const MODE_KEY = 'meshcore-1byte-hops-mode'; + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + ': ' + e.message); } +} +function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } + +(async () => { + const browser = await chromium.launch({ + headless: true, + executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'], + }); + + // A fresh browser profile per call. operatorDefault, when set, replaces + // customizer.oneByteHopsDefault in the server's real client config. + // storage is put into localStorage before the first page load only. + // holdConfig keeps the client config back until the returned + // releaseConfig() is called. + async function open(route, { operatorDefault, viewport, theme, storage, holdConfig } = {}) { + const ctx = await browser.newContext(viewport + ? { viewport, isMobile: true, hasTouch: true } + : { viewport: { width: 1280, height: 900 } }); + if (theme) { + await ctx.addInitScript((t) => { try { localStorage.setItem('meshcore-theme', t); } catch (_e) { /* storage unavailable */ } }, theme); + } + if (storage) { + await ctx.addInitScript((items) => { + try { + if (sessionStorage.getItem('e2e-912-seeded')) return; + sessionStorage.setItem('e2e-912-seeded', '1'); + for (const k of Object.keys(items)) localStorage.setItem(k, items[k]); + } catch (_e) { /* storage unavailable */ } + }, storage); + } + let releaseConfig = () => {}; + const held = holdConfig ? new Promise(r => { releaseConfig = r; }) : null; + if (operatorDefault) { + await ctx.route(url => url.pathname === '/api/config/client', async r => { + if (held) await held; + try { + const res = await r.fetch(); + const body = await res.json(); + body.customizer = Object.assign({}, body.customizer, { oneByteHopsDefault: operatorDefault }); + await r.fulfill({ response: res, json: body }); + } catch (e) { + // A held request released as its step's context closes. + if (!/closed/.test(String(e && e.message))) throw e; + } + }); + } + const page = await ctx.newPage(); + page.setDefaultTimeout(30000); + const errors = []; + page.on('pageerror', e => errors.push(String(e.message))); + await page.goto(BASE + '/' + route, { waitUntil: 'load' }); + if (!held) await page.evaluate(() => window.MeshConfigReady); + return { ctx, page, errors, releaseConfig }; + } + + const relays = (page) => page.evaluate(() => + [...document.querySelectorAll('.mc-rt-sidebar .mc-rt-row')].filter(r => !/from payload/.test(r.textContent)).length); + const waitRelays = (page, n) => page.waitForFunction((n) => + [...document.querySelectorAll('.mc-rt-sidebar .mc-rt-row')].filter(r => !/from payload/.test(r.textContent)).length === n, n); + const waitRouteDrawn = (page) => page.waitForFunction(() => !!window.__mc_lastRouteDraw); + const stored = (page) => page.evaluate((k) => localStorage.getItem(k), MODE_KEY); + const mode = (page) => page.evaluate(() => window.MC_get1ByteHopsMode()); + + // A phone reaches the customizer by taps, through the bottom nav's More. + async function openCustomizerDisplay(page, { touch = false } = {}) { + if (touch) { + await page.tap('[data-bottom-nav-tab="more"]'); + await page.waitForSelector('[data-mpa-mirror="customizeToggle"]', { state: 'visible' }); + await page.tap('[data-mpa-mirror="customizeToggle"]'); + } else await page.click('#customizeToggle'); + await page.waitForSelector('.cust-overlay:not(.hidden)'); + if (touch) await page.tap('.cust-tab[data-tab="display"]'); else await page.click('.cust-tab[data-tab="display"]'); + await page.waitForSelector('#cv2-hide-1byte-hops'); + } + const selectState = (page) => page.$eval('#cv2-hide-1byte-hops', sel => ({ + value: sel.value, + defaults: [...sel.options].filter(o => /\(server default\)/.test(o.textContent)).map(o => o.value), + reset: !!document.querySelector('#cv2-hide-1byte-hops-reset:not([hidden])'), + })); + const waitSelectState = (page, want) => page.waitForFunction((want) => { + const sel = document.getElementById('cv2-hide-1byte-hops'); + if (!sel) return false; + const got = { + value: sel.value, + defaults: [...sel.options].filter(o => /\(server default\)/.test(o.textContent)).map(o => o.value), + reset: !!document.querySelector('#cv2-hide-1byte-hops-reset:not([hidden])'), + }; + return JSON.stringify(got) === JSON.stringify(want); + }, want, { timeout: 10000 }).catch(async () => { + throw new Error('select state ' + JSON.stringify(await selectState(page)) + ', want ' + JSON.stringify(want)); + }); + + console.log(`\n#912 M2 E2E against ${BASE}\n`); + + await step('without the key in config.json the server serves no default; the customizer reads as before M2', async () => { + const { ctx, page, errors } = await open('#/home'); + try { + const cust = await page.evaluate(async () => (await (await fetch('/api/config/client')).json()).customizer); + assert(cust && !('oneByteHopsDefault' in cust), 'no default configured, none served: ' + JSON.stringify(cust)); + assert(Array.isArray(cust.disabledTabs), 'disabledTabs must stay: ' + JSON.stringify(cust)); + await openCustomizerDisplay(page); + const f = await page.evaluate(() => ({ + dflt: window.MC_get1ByteHopsDefault(), + labels: [...document.getElementById('cv2-hide-1byte-hops').options].map(o => o.textContent), + note: !document.getElementById('cv2-hide-1byte-hops-live-note').hidden, + })); + assert(f.dflt === null, 'no operator default: ' + f.dflt); + assert(JSON.stringify(f.labels) === '["Show","Mark uncertain hops (default)","Hide"]', 'labels ' + JSON.stringify(f.labels)); + assert(f.note, 'the hint must say Live shows every hop until a pick'); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + + await step('a fresh visitor gets the operator default (Hide): no 1-byte relays, nothing stored, customizer says so', async () => { + const { ctx, page, errors } = await open(ONE_BYTE, { operatorDefault: 'hide' }); + try { + await waitRouteDrawn(page); + await page.waitForFunction(() => window.MC_get1ByteHopsMode() === 'hide'); + await page.waitForFunction(() => [...document.querySelectorAll('.mc-rt-sidebar .mc-rt-row')] + .filter(r => !/from payload/.test(r.textContent)).length === 0); + assert(await stored(page) === null, 'following the default must store nothing'); + await openCustomizerDisplay(page); + const s = await selectState(page); + assert(s.value === 'hide' && JSON.stringify(s.defaults) === '["hide"]', JSON.stringify(s)); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + + await step('control: without an operator default the same visitor gets Mark (all 22 relays)', async () => { + const { ctx, page } = await open(ONE_BYTE); + try { + await waitRelays(page, RELAYS); + assert(await mode(page) === 'mark', 'mode ' + await mode(page)); + } finally { await ctx.close(); } + }); + + await step('the visitor\'s own choice (Show) wins over the Hide default and survives a reload', async () => { + const { ctx, page, errors } = await open(ONE_BYTE, { operatorDefault: 'hide' }); + try { + await waitRouteDrawn(page); + await page.waitForFunction(() => window.MC_get1ByteHopsMode() === 'hide'); + await openCustomizerDisplay(page); + await page.selectOption('#cv2-hide-1byte-hops', 'show'); + await page.click('#customizeToggle'); + await waitRelays(page, RELAYS); + assert(await stored(page) === 'show', 'stored ' + await stored(page)); + await page.reload({ waitUntil: 'load' }); + await page.evaluate(() => window.MeshConfigReady); + await waitRelays(page, RELAYS); + assert(await mode(page) === 'show', 'after reload: ' + await mode(page)); + await openCustomizerDisplay(page); + const s = await selectState(page); + assert(s.value === 'show' && JSON.stringify(s.defaults) === '["hide"]', JSON.stringify(s)); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + + await step('an explicit Mark is stored and survives the Hide default across a reload', async () => { + const { ctx, page } = await open(ONE_BYTE, { operatorDefault: 'hide' }); + try { + await waitRouteDrawn(page); + await openCustomizerDisplay(page); + await page.selectOption('#cv2-hide-1byte-hops', 'mark'); + await page.click('#customizeToggle'); + await waitRelays(page, RELAYS); + assert(await stored(page) === 'mark', 'stored ' + await stored(page)); + await page.reload({ waitUntil: 'load' }); + await page.evaluate(() => window.MeshConfigReady); + await waitRelays(page, RELAYS); + assert(await mode(page) === 'mark', 'after reload: ' + await mode(page) + ', relays ' + await relays(page)); + } finally { await ctx.close(); } + }); + + await step('F1 "Use server default" takes a Show pick back to the Hide default, on the open route', async () => { + const { ctx, page, errors } = await open(ONE_BYTE, { operatorDefault: 'hide' }); + try { + await waitRouteDrawn(page); + await openCustomizerDisplay(page); + await waitSelectState(page, { value: 'hide', defaults: ['hide'], reset: false }); + await page.selectOption('#cv2-hide-1byte-hops', 'show'); + await waitRelays(page, RELAYS); + await waitSelectState(page, { value: 'show', defaults: ['hide'], reset: true }); + const h = await page.$eval('#cv2-hide-1byte-hops-reset', el => el.getBoundingClientRect().height); + assert(h >= 24, 'the reset button is too small to tap: ' + h); + await page.click('#cv2-hide-1byte-hops-reset'); + await waitRelays(page, 0); + await waitSelectState(page, { value: 'hide', defaults: ['hide'], reset: false }); + assert(await stored(page) === null, 'stored ' + await stored(page)); + assert(await page.evaluate(() => document.activeElement && document.activeElement.id) === 'cv2-hide-1byte-hops', 'the focus must stay on the setting'); + await page.reload({ waitUntil: 'load' }); + await page.evaluate(() => window.MeshConfigReady); + await waitRouteDrawn(page); + await waitRelays(page, 0); + assert(await mode(page) === 'hide' && await stored(page) === null, 'after reload: ' + await mode(page)); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + + await step('F2 Reset All takes a stored Show back to the Hide default without a reload', async () => { + const { ctx, page, errors } = await open(ONE_BYTE, { + operatorDefault: 'hide', + // A theme override as well, so the Export tab offers Reset All. + storage: { [MODE_KEY]: 'show', 'cs-theme-overrides': JSON.stringify({ theme: { accent: '#3366cc' } }) }, + }); + try { + await waitRouteDrawn(page); + await waitRelays(page, RELAYS); + await openCustomizerDisplay(page); + await page.click('.cust-tab[data-tab="export"]'); + page.once('dialog', d => d.accept()); + await page.click('#cv2ResetAll'); + await waitRelays(page, 0); + assert(await stored(page) === null && await mode(page) === 'hide', 'mode ' + await mode(page) + ', stored ' + await stored(page)); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + + for (const pick of [null, 'show']) { + await step(`F3 a customizer opened before the client config lands shows the Hide default once it does (${pick ? 'stored ' + pick : 'no pick'})`, async () => { + const { ctx, page, errors, releaseConfig } = await open('#/home', { + operatorDefault: 'hide', holdConfig: true, storage: pick ? { [MODE_KEY]: pick } : undefined, + }); + try { + await openCustomizerDisplay(page); + assert(await page.evaluate(() => window.MC_get1ByteHopsDefault()) === null, 'the config must still be held'); + await waitSelectState(page, { value: pick || 'mark', defaults: [], reset: !!pick }); + releaseConfig(); + await page.evaluate(() => window.MeshConfigReady); + await waitSelectState(page, { value: pick || 'hide', defaults: ['hide'], reset: !!pick }); + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { releaseConfig(); await ctx.close(); } + }); + } + + for (const theme of ['light', 'dark']) { + await step(`375x560 phone, ${theme}: the 1-byte hop setting fits and the page does not scroll sideways`, async () => { + const { ctx, page, errors } = await open('#/home', { operatorDefault: 'hide', viewport: { width: 375, height: 560 }, theme }); + try { + await openCustomizerDisplay(page, { touch: true }); + await page.$eval('#cv2-hide-1byte-hops', el => el.scrollIntoView({ block: 'center' })); + const g = await page.evaluate(() => { + const sel = document.getElementById('cv2-hide-1byte-hops'); + const r = sel.getBoundingClientRect(); + const label = document.querySelector('label[for="cv2-hide-1byte-hops"]').getBoundingClientRect(); + const cs = getComputedStyle(sel); + return { + theme: document.documentElement.getAttribute('data-theme'), + left: r.left, right: r.right, top: r.top, bottom: r.bottom, h: r.height, + labelRight: label.right, vw: window.innerWidth, vh: window.innerHeight, + scroll: document.documentElement.scrollWidth, client: document.documentElement.clientWidth, + bg: cs.backgroundColor, fg: cs.color, + text: sel.options[sel.selectedIndex].textContent, + }; + }); + assert(g.theme === theme, 'theme ' + g.theme); + assert(g.scroll <= g.client + 1, 'horizontal overflow: ' + JSON.stringify(g)); + assert(g.left >= 0 && g.right <= g.vw && g.labelRight <= g.vw, 'select or label leaves the screen: ' + JSON.stringify(g)); + assert(g.top >= 0 && g.bottom <= g.vh, 'select not reachable on screen: ' + JSON.stringify(g)); + assert(g.h >= 24, 'select too small to tap: ' + g.h); + assert(g.bg !== g.fg, 'select text has no contrast: ' + JSON.stringify(g)); + assert(/Hide \(server default\)/.test(g.text), 'selected option text: ' + g.text); + if (process.env.E2E_SHOTS) { + await page.screenshot({ path: path.join(process.env.E2E_SHOTS, `912-m2-phone-${theme}.png`) }); + } + assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); + } finally { await ctx.close(); } + }); + } + + await browser.close(); + console.log(`\n#912 M2 E2E: ${passed} passed, ${failed} failed`); + process.exit(failed ? 1 : 0); +})().catch(e => { console.error(' ✗ #912 M2 E2E:', e.stack || e); process.exit(1); }); diff --git a/test-issue-912-m2-1byte-operator-default.js b/test-issue-912-m2-1byte-operator-default.js new file mode 100644 index 000000000..72e83e328 --- /dev/null +++ b/test-issue-912-m2-1byte-operator-default.js @@ -0,0 +1,428 @@ +/** + * #912 M2 — the operator chooses the default 1-byte hop mode. + * + * Runs the real hop-filter.js, roles.js' client-config hand-off and + * customize-v2.js' select in vm sandboxes: + * - resolution order: the visitor's stored choice, then the operator default + * (customizer.oneByteHopsDefault), then mark; + * - an explicit choice is always stored, so an explicit "mark" survives a + * "hide" default; + * - a visitor who never chose follows the operator default, also when it + * changes later, and is told so through mc-hide-1byte-hops-changed; + * - the #1633 boolean key still migrates; + * - the customizer marks the server default. + * PR #1001 review: + * - F1 a visitor with a stored choice can go back to following the + * default ("Use server default", MC_clear1ByteHopsMode); + * - F2 that, and Reset All, fire mc-hide-1byte-hops-changed; + * - F3 an open customizer follows a client config that lands later + * (mc-1byte-hops-default-changed); + * - F5 a junk early MC_CUSTOMIZER_CFG, and the #1633 key under a + * load-time default. + * CS-VM1 review: N1 the way back for a pick equal to the default, N2 clear + * without an operator default, and the caller's fallback (Live: Show). + * CS-VM1 review round 3, R2: with no operator default MC_get1ByteHopsDefault() + * is null and the customizer reads as before M2 (Mark "(default)", the Live + * hint, "Use default"). + */ +'use strict'; +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +let passed = 0, failed = 0; +function test(name, fn) { + try { fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.log(' ✗ ' + name + ': ' + e.message); } +} +function assert(cond, msg) { if (!cond) throw new Error(msg); } + +const MODE_KEY = 'meshcore-1byte-hops-mode'; +const LEGACY_KEY = 'meshcore-hide-1byte-hops'; +const SRC = fs.readFileSync(path.join(__dirname, 'public', 'hop-filter.js'), 'utf8'); + +function sandbox(store, pre) { + const events = []; + const ctx = { + console, + localStorage: { + getItem: (k) => (Object.prototype.hasOwnProperty.call(store, k) ? store[k] : null), + setItem: (k, v) => { store[k] = String(v); }, + removeItem: (k) => { delete store[k]; }, + }, + CustomEvent: function (type, init) { this.type = type; this.detail = init && init.detail; }, + dispatchEvent: (e) => { events.push(e); return true; }, + }; + ctx.window = ctx; + if (pre) pre(ctx); + vm.createContext(ctx); + vm.runInContext(SRC, ctx, { filename: 'hop-filter.js' }); + ctx.__events = events; + ctx.__changes = () => events.filter(e => e.type === 'mc-hide-1byte-hops-changed').map(e => e.detail.mode); + return ctx; +} + +console.log('\n=== #912 M2 operator default for the 1-byte hop mode ==='); + +// ── Resolution order ──────────────────────────────────────────────────── +test('no stored choice, no operator default: mark, and no default to report', () => { + const w = sandbox({}); + assert(w.MC_get1ByteHopsMode() === 'mark', 'got ' + w.MC_get1ByteHopsMode()); + assert(w.MC_get1ByteHopsDefault() === null, 'default ' + w.MC_get1ByteHopsDefault()); +}); + +test('no stored choice: the operator default applies', () => { + for (const d of ['show', 'mark', 'hide']) { + const w = sandbox({}); + w.MC_set1ByteHopsDefault(d); + assert(w.MC_get1ByteHopsMode() === d, d + ': got ' + w.MC_get1ByteHopsMode()); + assert(w.MC_get1ByteHopsDefault() === d, d + ': default ' + w.MC_get1ByteHopsDefault()); + } + const w = sandbox({}); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_getHide1ByteHops() === true && w.MC_isVisibleHop('AB') === false, 'a hide default must hide'); +}); + +test('the stored choice wins over the operator default', () => { + for (const [stored, d] of [['show', 'hide'], ['mark', 'hide'], ['hide', 'show'], ['mark', 'show']]) { + const w = sandbox({ [MODE_KEY]: stored }); + w.MC_set1ByteHopsDefault(d); + assert(w.MC_get1ByteHopsMode() === stored, `stored ${stored}, default ${d}: got ${w.MC_get1ByteHopsMode()}`); + } +}); + +test('an invalid operator default is ignored: mark', () => { + for (const junk of ['bogus', 'constructor', '__proto__', 'toString', '', null, undefined, 3, 'Hide']) { + const w = sandbox({}); + w.MC_set1ByteHopsDefault(junk); + assert(w.MC_get1ByteHopsMode() === 'mark', JSON.stringify(junk) + ' read as ' + w.MC_get1ByteHopsMode()); + assert(w.MC_get1ByteHopsDefault() === null, JSON.stringify(junk) + ' default ' + w.MC_get1ByteHopsDefault()); + } +}); + +test('a client config that arrived before hop-filter.js loaded is picked up', () => { + const w = sandbox({}, (c) => { c.MC_CUSTOMIZER_CFG = { disabledTabs: [], oneByteHopsDefault: 'hide' }; }); + assert(w.MC_get1ByteHopsMode() === 'hide', 'got ' + w.MC_get1ByteHopsMode()); +}); + +// ── Explicit storage ──────────────────────────────────────────────────── +test('every explicit choice is stored, the default one too', () => { + const store = {}; + const w = sandbox(store); + for (const m of ['hide', 'show', 'mark']) { + w.MC_set1ByteHopsMode(m); + assert(store[MODE_KEY] === m, m + ' stored as ' + JSON.stringify(store)); + } +}); + +test('an explicit "mark" survives a "hide" operator default', () => { + const store = {}; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('hide'); + w.MC_set1ByteHopsMode('mark'); + assert(w.MC_get1ByteHopsMode() === 'mark', 'same page: ' + w.MC_get1ByteHopsMode()); + // Next visit: a fresh page, the server still says hide. + const next = sandbox(store); + next.MC_set1ByteHopsDefault('hide'); + assert(next.MC_get1ByteHopsMode() === 'mark', 'after reload: ' + next.MC_get1ByteHopsMode()); +}); + +test('junk is still rejected and stores nothing', () => { + const store = {}; + const w = sandbox(store); + for (const junk of ['nonsense', 'constructor', '__proto__', '']) w.MC_set1ByteHopsMode(junk); + assert(!(MODE_KEY in store), JSON.stringify(store)); +}); + +// ── Following the operator default ────────────────────────────────────── +test('a visitor who never chose follows a later change of the default, and is told', () => { + const store = {}; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_get1ByteHopsMode() === 'hide', 'first default'); + w.MC_set1ByteHopsDefault('show'); + assert(w.MC_get1ByteHopsMode() === 'show', 'changed default'); + assert(!(MODE_KEY in store), 'following the default stores nothing: ' + JSON.stringify(store)); + assert(JSON.stringify(w.__changes()) === '["hide","show"]', 'events ' + JSON.stringify(w.__changes())); +}); + +test('a default equal to the current mode fires no event; a stored choice hides the change', () => { + const w = sandbox({}); + w.MC_set1ByteHopsDefault('mark'); + assert(w.__changes().length === 0, 'mark → mark fired ' + JSON.stringify(w.__changes())); + const s = sandbox({ [MODE_KEY]: 'show' }); + s.MC_set1ByteHopsDefault('hide'); + assert(s.__changes().length === 0, 'a stored choice is unaffected, no event: ' + JSON.stringify(s.__changes())); +}); + +// ── Legacy migration ──────────────────────────────────────────────────── +test('the #1633 "true" key still migrates to a stored hide, even under a show default', () => { + const store = { [LEGACY_KEY]: 'true' }; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('show'); + assert(w.MC_get1ByteHopsMode() === 'hide', 'got ' + w.MC_get1ByteHopsMode()); + assert(store[MODE_KEY] === 'hide' && !(LEGACY_KEY in store), JSON.stringify(store)); +}); + +test('another legacy value is dropped and the operator default applies', () => { + const store = { [LEGACY_KEY]: 'false' }; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_get1ByteHopsMode() === 'hide' && !(LEGACY_KEY in store) && !(MODE_KEY in store), JSON.stringify(store)); +}); + +test('a junk stored mode is dropped and the operator default applies', () => { + const store = { [MODE_KEY]: 'bogus' }; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('show'); + assert(w.MC_get1ByteHopsMode() === 'show' && !(MODE_KEY in store), JSON.stringify(store)); +}); + +// ── roles.js hands the server value to hop-filter.js ─────────────────── +test('roles.js passes customizer.oneByteHopsDefault from /api/config/client to hop-filter.js', () => { + const roles = fs.readFileSync(path.join(__dirname, 'public', 'roles.js'), 'utf8'); + const start = roles.indexOf('window.MC_CUSTOMIZER_CFG ='); + assert(start !== -1, 'MC_CUSTOMIZER_CFG assignment not found'); + const end = roles.indexOf(';', roles.indexOf('MC_set1ByteHopsDefault', start)); + assert(end > start, 'roles.js does not call MC_set1ByteHopsDefault after MC_CUSTOMIZER_CFG'); + const snippet = roles.slice(start, end + 1); + for (const [cust, want] of [[{ oneByteHopsDefault: 'hide', disabledTabs: ['x'] }, 'hide'], [undefined, 'mark'], [{ oneByteHopsDefault: 7 }, 'mark']]) { + const w = sandbox({}); + vm.runInContext('(function (cfg) {' + snippet + '})(' + JSON.stringify({ customizer: cust }) + ')', w); + assert(w.MC_get1ByteHopsMode() === want, JSON.stringify(cust) + ' → ' + w.MC_get1ByteHopsMode()); + assert(Array.isArray(w.MC_CUSTOMIZER_CFG.disabledTabs), 'disabledTabs must stay an array'); + } +}); + +// ── The customizer marks the server default ───────────────────────────── +test('the customizer select labels the server default and selects the effective mode', () => { + for (const [d, stored] of [['hide', null], ['show', 'mark'], ['mark', null]]) { + const p = customizerPage(stored ? { [MODE_KEY]: stored } : {}); + p.ctx.window.MC_set1ByteHopsDefault(d); + const { html, sel } = p.mount(); + assert(sel.options.length === 3, 'options: ' + html); + const s = p.shown(); + assert(JSON.stringify(s.defaults) === JSON.stringify([d]), `default ${d}: marked ${JSON.stringify(s.defaults)}`); + assert(s.value === (stored || d), `default ${d}, stored ${stored}: selected ${s.value}`); + } +}); + +test('R2 without an operator default the customizer reads as before M2', () => { + // Master: "Mark uncertain hops (default)" and the hint that Live shows + // every hop until a pick; no "(server default)" anywhere. + for (const stored of [null, 'hide']) { + const p = customizerPage(stored ? { [MODE_KEY]: stored } : {}); + const { html, sel, note } = p.mount(); + const labels = sel.options.map(o => o.textContent); + assert(JSON.stringify(labels) === '["Show","Mark uncertain hops (default)","Hide"]', 'labels ' + JSON.stringify(labels)); + assert(!/server default\)/.test(html), 'no server default to label: ' + JSON.stringify(labels)); + assert(sel.value === (stored || 'mark'), 'selected ' + sel.value); + assert(note && !note.hidden && /Until you pick a mode here, the Live map shows every hop unmarked\./.test(html), 'the Live hint must be shown'); + if (stored) assert(p.resetText() === '↺ Use default', 'reset text ' + p.resetText()); + } + // With a configured default the Live hint goes: Live follows it. + const c = customizerPage({}); + c.ctx.window.MC_set1ByteHopsDefault('mark'); + const m = c.mount(); + assert(m.note && m.note.hidden, 'a configured default hides the Live hint'); + assert(JSON.stringify(m.sel.options.map(o => o.textContent)) === '["Show","Mark uncertain hops (server default)","Hide"]', + 'labels ' + JSON.stringify(m.sel.options.map(o => o.textContent))); +}); + +// ── Review of PR #1001 (F1–F3, F5) ───────────────────────────────────── +// F1: a visitor who picked a mode has a way back to following the operator +// default. F2: that way back (and Reset All) tells the open page. F3: an open +// customizer follows a client config that lands after it rendered. +const defaultChanges = (w) => w.__events.filter(e => e.type === 'mc-1byte-hops-default-changed').map(e => e.detail.default); + +test('F1 MC_getStored1ByteHopsMode: the stored pick, or null when the visitor follows the default', () => { + const w = sandbox({}); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_getStored1ByteHopsMode() === null, 'no pick: ' + w.MC_getStored1ByteHopsMode()); + w.MC_set1ByteHopsMode('hide'); + assert(w.MC_getStored1ByteHopsMode() === 'hide', 'a pick equal to the default is still a pick: ' + w.MC_getStored1ByteHopsMode()); + assert(sandbox({ [MODE_KEY]: 'bogus' }).MC_getStored1ByteHopsMode() === null, 'junk is no pick'); + const store = { [LEGACY_KEY]: 'true' }; + assert(sandbox(store).MC_getStored1ByteHopsMode() === 'hide' && store[MODE_KEY] === 'hide', 'the #1633 key migrates: ' + JSON.stringify(store)); +}); + +test('F1 MC_clear1ByteHopsMode: the pick goes, the visitor follows the default again, later changes too', () => { + const store = { [MODE_KEY]: 'show', [LEGACY_KEY]: 'true' }; + const w = sandbox(store); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_get1ByteHopsMode() === 'show', 'before: ' + w.MC_get1ByteHopsMode()); + w.MC_clear1ByteHopsMode(); + assert(!(MODE_KEY in store) && !(LEGACY_KEY in store), 'keys left: ' + JSON.stringify(store)); + assert(w.MC_get1ByteHopsMode() === 'hide' && w.MC_getStored1ByteHopsMode() === null, 'after: ' + w.MC_get1ByteHopsMode()); + w.MC_set1ByteHopsDefault('show'); + assert(w.MC_get1ByteHopsMode() === 'show', 'a later default is followed: ' + w.MC_get1ByteHopsMode()); +}); + +test('F2 MC_clear1ByteHopsMode fires mc-hide-1byte-hops-changed with the mode now in force', () => { + const w = sandbox({ [MODE_KEY]: 'show' }); + w.MC_set1ByteHopsDefault('hide'); + w.MC_clear1ByteHopsMode(); + assert(JSON.stringify(w.__changes()) === '["hide"]', 'events ' + JSON.stringify(w.__changes())); + const e = w.__events.filter(x => x.type === 'mc-hide-1byte-hops-changed').pop(); + assert(e.detail.value === true, 'detail.value must say hide: ' + JSON.stringify(e.detail)); +}); + +test('F2 MC_clear1ByteHopsMode without an operator default fires mark, the mode now in force', () => { + // CS-VM1 review N2: the event carries the effective mode, not the raw + // (absent) operator default. + const store = { [MODE_KEY]: 'hide' }; + const w = sandbox(store); + w.MC_clear1ByteHopsMode(); + assert(!(MODE_KEY in store), 'key left: ' + JSON.stringify(store)); + assert(JSON.stringify(w.__changes()) === '["mark"]', 'events ' + JSON.stringify(w.__changes())); + assert(w.MC_get1ByteHopsMode() === 'mark', 'mode ' + w.MC_get1ByteHopsMode()); +}); + +test('MC_get1ByteHopsMode(fallback): the caller\'s fallback only when there is no pick and no operator default', () => { + // Live passes "show" (#912 M1/M2); every other caller keeps mark. + const w = sandbox({}); + assert(w.MC_get1ByteHopsMode('show') === 'show', 'no pick, no default: ' + w.MC_get1ByteHopsMode('show')); + assert(w.MC_get1ByteHopsMode() === 'mark', 'no fallback: ' + w.MC_get1ByteHopsMode()); + assert(w.MC_get1ByteHopsMode('constructor') === 'mark', 'a junk fallback is mark'); + w.MC_set1ByteHopsDefault('mark'); + assert(w.MC_get1ByteHopsMode('show') === 'mark', 'an operator mark beats the fallback: ' + w.MC_get1ByteHopsMode('show')); + w.MC_set1ByteHopsDefault('hide'); + assert(w.MC_get1ByteHopsMode('show') === 'hide', 'the operator default: ' + w.MC_get1ByteHopsMode('show')); + w.MC_set1ByteHopsMode('show'); + w.MC_set1ByteHopsDefault('mark'); + assert(w.MC_get1ByteHopsMode('hide') === 'show', 'the pick wins: ' + w.MC_get1ByteHopsMode('hide')); +}); + +test('F3 a changed operator default fires mc-1byte-hops-default-changed, also behind a stored pick', () => { + const w = sandbox({ [MODE_KEY]: 'show' }); + w.MC_set1ByteHopsDefault('hide'); + w.MC_set1ByteHopsDefault('hide'); + w.MC_set1ByteHopsDefault('junk'); + assert(JSON.stringify(defaultChanges(w)) === '["hide",null]', 'default events ' + JSON.stringify(defaultChanges(w))); + assert(w.__changes().length === 0, 'the stored pick hides the mode change: ' + JSON.stringify(w.__changes())); + const m = sandbox({}); + m.MC_set1ByteHopsDefault(undefined); + assert(defaultChanges(m).length === 0, 'none → none fired ' + JSON.stringify(defaultChanges(m))); + m.MC_set1ByteHopsDefault('mark'); + assert(JSON.stringify(defaultChanges(m)) === '["mark"]', 'none → mark is a change: ' + JSON.stringify(defaultChanges(m))); +}); + +test('F5 an early MC_CUSTOMIZER_CFG with a junk default is ignored: mark', () => { + for (const junk of ['bogus', 'constructor', '__proto__', 'Hide', 3]) { + const w = sandbox({}, (c) => { c.MC_CUSTOMIZER_CFG = { disabledTabs: [], oneByteHopsDefault: junk }; }); + assert(w.MC_get1ByteHopsDefault() === null, JSON.stringify(junk) + ': default ' + w.MC_get1ByteHopsDefault()); + assert(w.MC_get1ByteHopsMode() === 'mark', JSON.stringify(junk) + ': mode ' + w.MC_get1ByteHopsMode()); + } +}); + +test('F5 a legacy "true" migrates on the first read under a load-time default (no earlier get)', () => { + const store = { [LEGACY_KEY]: 'true' }; + const w = sandbox(store, (c) => { c.MC_CUSTOMIZER_CFG = { disabledTabs: [], oneByteHopsDefault: 'show' }; }); + assert(w.MC_get1ByteHopsMode() === 'hide', 'got ' + w.MC_get1ByteHopsMode()); + assert(store[MODE_KEY] === 'hide' && !(LEGACY_KEY in store), JSON.stringify(store)); +}); + +// The customizer, run in tests/customizer-sandbox.js with the real +// hop-filter.js over the same window and localStorage, as on the page. +function customizerPage(stored) { + const { loadCustomizer } = require('./tests/customizer-sandbox'); + const listeners = {}; + const fired = []; + const els = {}; + const p = loadCustomizer({ + setup(ctx) { + Object.assign(ctx.localStorage._data, stored || {}); + ctx.window.addEventListener = (t, fn) => { (listeners[t] = listeners[t] || []).push(fn); }; + ctx.window.dispatchEvent = (ev) => { fired.push(ev); (listeners[ev.type] || []).forEach(fn => fn(ev)); return true; }; + ctx.document.getElementById = (id) => els[id] || null; + }, + }); + vm.runInContext(SRC, p.ctx, { filename: 'hop-filter.js' }); + p.fired = fired; + // A select and reset button built from the rendered markup, standing in + // for the open panel's DOM. + p.mount = () => { + const html = p.api.renderDisplay(); + const m = html.match(/