From e60f62db3b9e154c8b58d3c0aa72d48861a62ffa Mon Sep 17 00:00:00 2001 From: dborup Date: Fri, 27 Nov 2026 10:51:43 +0000 Subject: [PATCH 1/5] test(config): reproduce the missing operator default for the 1-byte hop mode (#912 M2) Go: customizer.oneByteHopsDefault parsing (show/mark/hide, unknown, absent, wrong type, case variants) and its place in the customizer block of /api/config/client. JS: the resolution order (stored choice, operator default, mark), explicit storage, following a later default, the #1633 migration and the customizer's server-default label. E2E: a fresh visitor gets an intercepted hide default, the visitor's own choice wins across a reload, and the setting fits a 375x560 phone in light and dark. The #674 tests now expect an explicit mark to be stored. Co-Authored-By: Claude Opus 5.5 --- .../config_one_byte_hops_default_912_test.go | 141 ++++++++++++ scripts/e2e-shards.json | 1 + test-all.sh | 1 + test-issue-674-1byte-hop-modes-e2e.js | 2 +- test-issue-674-1byte-hop-modes.js | 6 +- ...issue-912-m2-1byte-operator-default-e2e.js | 202 ++++++++++++++++++ test-issue-912-m2-1byte-operator-default.js | 202 ++++++++++++++++++ 7 files changed, 552 insertions(+), 3 deletions(-) create mode 100644 cmd/server/config_one_byte_hops_default_912_test.go create mode 100644 test-issue-912-m2-1byte-operator-default-e2e.js create mode 100644 test-issue-912-m2-1byte-operator-default.js 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..c1043e105 --- /dev/null +++ b/cmd/server/config_one_byte_hops_default_912_test.go @@ -0,0 +1,141 @@ +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, and +// an absent key behaves as before (mark). /api/config/client always serves +// the effective value in its customizer block. + +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", `{}`, "mark", false}, + {"absent key", `{"customizer": {"disabledTabs": ["export"]}}`, "mark", 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 the default stays mark. +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 != "mark" { + t.Fatalf("%s: OneByteHopsDefault() = %q, want mark", 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") + if !ok || f.Type.Kind() != reflect.String || f.Tag.Get("json") != "oneByteHopsDefault" { + t.Fatalf("CustomizerClientConfig.OneByteHopsDefault must be a string tagged oneByteHopsDefault, got %v %q", f.Type, f.Tag) + } +} + +func TestClientConfigOneByteHopsDefaultShape912(t *testing.T) { + for _, c := range []struct { + cfg string + want string + }{ + {`{}`, "mark"}, + {`{"customizer": {"oneByteHopsDefault": "hide"}}`, "hide"}, + {`{"customizer": {"oneByteHopsDefault": "show", "disabledTabs": ["export"]}}`, "show"}, + {`{"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) + } + raw, ok := got.Customizer["oneByteHopsDefault"] + if !ok { + t.Fatalf("cfg %s: customizer.oneByteHopsDefault missing from %s", c.cfg, body) + } + var v string + if err := json.Unmarshal(raw, &v); err != nil || v != c.want { + t.Fatalf("cfg %s: customizer.oneByteHopsDefault = %s, want %q", c.cfg, raw, c.want) + } + if _, ok := got.Customizer["disabledTabs"]; !ok { + t.Fatalf("cfg %s: customizer.disabledTabs must stay in the block", c.cfg) + } + } +} diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 2820cd854..b6ad368fb 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: the served customizer.oneByteHopsDefault, 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, and the customizer setting at 375x560 in light and dark. No CI duration measured yet. 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]}, diff --git a/test-all.sh b/test-all.sh index 722ace113..ad2010010 100755 --- a/test-all.sh +++ b/test-all.sh @@ -405,6 +405,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-674-1byte-hop-modes-e2e.js b/test-issue-674-1byte-hop-modes-e2e.js index 414c3d4f2..23206fa98 100644 --- a/test-issue-674-1byte-hop-modes-e2e.js +++ b/test-issue-674-1byte-hop-modes-e2e.js @@ -140,7 +140,7 @@ function assert(c, m) { if (!c) throw new Error(m || 'assertion failed'); } s = await state(page); assert(s.mode === 'mark' && s.chips === mark.chips, 'back to mark: ' + JSON.stringify(s)); const stored = await page.evaluate(() => localStorage.getItem('meshcore-1byte-hops-mode')); - assert(stored === null, 'the default is stored as no key, got ' + stored); + assert(stored === 'mark', 'an explicit mark is stored (#912 M2), got ' + stored); assert(errors.length === 0, 'page errors: ' + errors.join(' | ')); } finally { await ctx.close(); } }); diff --git a/test-issue-674-1byte-hop-modes.js b/test-issue-674-1byte-hop-modes.js index 7846f4978..66b135368 100644 --- a/test-issue-674-1byte-hop-modes.js +++ b/test-issue-674-1byte-hop-modes.js @@ -92,7 +92,9 @@ test('an invalid stored mode reads as the default and is removed', () => { } }); -test('set1ByteHopsMode stores show/hide, clears the key for the default, rejects junk', () => { +// #912 M2: every explicit choice is stored, mark too, so it survives an +// operator default (see test-issue-912-m2-1byte-operator-default.js). +test('set1ByteHopsMode stores every mode, mark too, and rejects junk', () => { const store = {}; const w = sandbox(store, ['hop-filter.js']); w.MC_set1ByteHopsMode('hide'); @@ -100,7 +102,7 @@ test('set1ByteHopsMode stores show/hide, clears the key for the default, rejects w.MC_set1ByteHopsMode('show'); assert(store[MODE_KEY] === 'show', JSON.stringify(store)); w.MC_set1ByteHopsMode('mark'); - assert(!(MODE_KEY in store), 'default is stored as "no key": ' + JSON.stringify(store)); + assert(store[MODE_KEY] === 'mark', 'an explicit mark is stored: ' + JSON.stringify(store)); w.MC_set1ByteHopsMode('hide'); for (const junk of ['nonsense', 'constructor', '__proto__', 'toString']) { w.MC_set1ByteHopsMode(junk); 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..57e440d8f --- /dev/null +++ b/test-issue-912-m2-1byte-operator-default-e2e.js @@ -0,0 +1,202 @@ +/** + * E2E (#912 M2) — the operator chooses the default 1-byte hop mode. + * + * The server's own /api/config/client carries customizer.oneByteHopsDefault + * (mark when config.json has no key). 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. + * + * 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. + async function open(route, { operatorDefault, viewport, theme } = {}) { + 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 (operatorDefault) { + await ctx.route(url => url.pathname === '/api/config/client', async r => { + 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 }); + }); + } + 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' }); + await page.evaluate(() => window.MeshConfigReady); + return { ctx, page, errors }; + } + + 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), + })); + + console.log(`\n#912 M2 E2E against ${BASE}\n`); + + await step('the server serves customizer.oneByteHopsDefault (mark when config.json has none)', async () => { + const { ctx, page } = await open('#/home'); + try { + const cust = await page.evaluate(async () => (await (await fetch('/api/config/client')).json()).customizer); + assert(cust && ['show', 'mark', 'hide'].includes(cust.oneByteHopsDefault), JSON.stringify(cust)); + assert(Array.isArray(cust.disabledTabs), 'disabledTabs must stay: ' + JSON.stringify(cust)); + } 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(); } + }); + + 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..afc5718e1 --- /dev/null +++ b/test-issue-912-m2-1byte-operator-default.js @@ -0,0 +1,202 @@ +/** + * #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. + */ +'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.__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', () => { + const w = sandbox({}); + assert(w.MC_get1ByteHopsMode() === 'mark', 'got ' + w.MC_get1ByteHopsMode()); + assert(w.MC_get1ByteHopsDefault() === 'mark', '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() === 'mark', 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', () => { + const src = fs.readFileSync(path.join(__dirname, 'public', 'customize-v2.js'), 'utf8'); + const m = src.match(/function _renderHide1ByteHopsToggle\(\) \{[\s\S]*?\n \}\n/); + assert(m, '_renderHide1ByteHopsToggle not found'); + for (const [d, stored] of [['hide', null], ['show', 'mark'], ['mark', null]]) { + const w = sandbox(stored ? { [MODE_KEY]: stored } : {}); + w.MC_set1ByteHopsDefault(d); + const html = vm.runInContext('(' + m[0].trim() + ')()', w); + const opts = [...html.matchAll(/