diff --git a/public/customize-v2.js b/public/customize-v2.js
index 5c8f5c5af..5ff77acfd 100644
--- a/public/customize-v2.js
+++ b/public/customize-v2.js
@@ -3090,7 +3090,7 @@
return '' + label + ' ';
};
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.
' +
+ '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.
' +
'' +
'Short (1-byte) path-hash hops ' +
'' +
diff --git a/public/hop-filter.js b/public/hop-filter.js
index e9511976c..685858c6b 100644
--- a/public/hop-filter.js
+++ b/public/hop-filter.js
@@ -19,8 +19,10 @@
// 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.
- // The default is stored as "no key". The #1633 boolean key migrates once:
- // "true" becomes mode "hide"; anything else is dropped.
+ // "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.
var MODE_KEY = 'meshcore-1byte-hops-mode';
var LEGACY_KEY = 'meshcore-hide-1byte-hops';
var MODES = ['show', 'mark', 'hide'];
@@ -52,8 +54,7 @@
function set1ByteHopsMode(mode) {
if (!isMode(mode)) return;
try {
- if (mode === DEFAULT_MODE) localStorage.removeItem(MODE_KEY);
- else localStorage.setItem(MODE_KEY, mode);
+ localStorage.setItem(MODE_KEY, mode);
localStorage.removeItem(LEGACY_KEY);
} catch (_e) { /* private mode */ }
if (typeof window !== 'undefined' && typeof window.CustomEvent === 'function') {
@@ -63,6 +64,15 @@
}
}
+ // #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; }
+ }
+
// #1633 API, kept for its callers: "hide" is mode hide; turning it off
// restores the pre-#674 unmarked view (show).
function getHide1ByteHops() { return get1ByteHopsMode() === 'hide'; }
@@ -139,6 +149,7 @@
window.MC_setHide1ByteHops = setHide1ByteHops;
window.MC_get1ByteHopsMode = get1ByteHopsMode;
window.MC_set1ByteHopsMode = set1ByteHopsMode;
+ window.MC_getStored1ByteHopsMode = getStored1ByteHopsMode;
window.MC_isVisibleHop = isVisibleHop;
window.MC_filterPathHops = filterPathHops;
window.MC_hopByteLen = hopByteLen;
@@ -151,6 +162,7 @@
setHide1ByteHops: setHide1ByteHops,
get1ByteHopsMode: get1ByteHopsMode,
set1ByteHopsMode: set1ByteHopsMode,
+ getStored1ByteHopsMode: getStored1ByteHopsMode,
isVisibleHop: isVisibleHop,
filterPathHops: filterPathHops,
hopByteLen: hopByteLen,
diff --git a/public/live.js b/public/live.js
index 26accdef1..aff1eb295 100644
--- a/public/live.js
+++ b/public/live.js
@@ -42,6 +42,9 @@
let packetCount = 0;
let activeAnims = 0;
const MAX_CONCURRENT_ANIMS = 20;
+ // #912 M1: an uncertain segment is lighter than a certain one (0.8), as the
+ // route view's redacted edges are (route-render.js: 0.6 against 0.92).
+ const UNCERTAIN_SEGMENT_OPACITY = 0.5;
// Perf caps for the animation overlay (see updateAnimCanvas / renderAnimations).
const ANIM_MAX_DPR = 1.5; // cap backing-store pixels on hi-DPI displays
const ANIM_MIN_FRAME_MS = 15; // don't redraw faster than ~60fps (high-refresh guard)
@@ -4196,6 +4199,9 @@
window._liveFormatLiveTimestampHtml = formatLiveTimestampHtml;
window._liveResolveHopPositions = resolveHopPositions;
window._liveResolveHopEntries = resolveHopEntries;
+ window._liveOneByteHopsMode = oneByteHopsMode;
+ window._liveIsUncertainSegment = isUncertainSegment;
+ window._liveApplyOneByteHopsMode = applyOneByteHopsMode;
window._liveStartFollow = function(hash, opts) { return startFollow(hash, opts); };
window._liveStopFollow = function() { stopFollow(); };
window._liveFollowState = function() { return followState; };
@@ -4665,6 +4671,7 @@
// Prefer path_json (per-observer unique path) over decoded.path.hops (same for all)
var allPaths = [];
var seenPathKeys = new Set();
+ var hopMode = oneByteHopsMode(); // #912 M1: once per packet group
for (var qi = 0; qi < packets.length; qi++) {
var qpkt = packets[qi];
var qd = qpkt.decoded || {};
@@ -4678,7 +4685,7 @@
var pathKey = hops.join(',');
if (seenPathKeys.has(pathKey)) continue;
seenPathKeys.add(pathKey);
- var hopPositions = resolveHopPositions(hops, qp, window.getResolvedPath ? getResolvedPath(qpkt) : null);
+ var hopPositions = resolveHopPositions(hops, qp, window.getResolvedPath ? getResolvedPath(qpkt) : null, hopMode);
if (hopPositions.length >= 2) {
allPaths.push({ hopPositions: hopPositions, raw: qpkt.raw || first.raw });
} else if (hopPositions.length === 1) {
@@ -4689,7 +4696,7 @@
// If no multi-hop paths found, try the decoded path as fallback
if (allPaths.length === 0) {
var fallbackHops = decoded.path?.hops || [];
- var fallbackPositions = resolveHopPositions(fallbackHops, payload);
+ var fallbackPositions = resolveHopPositions(fallbackHops, payload, null, hopMode);
if (fallbackPositions.length >= 2) {
allPaths.push({ hopPositions: fallbackPositions, raw: first.raw });
} else if (fallbackPositions.length === 1) {
@@ -4831,13 +4838,73 @@
});
}
- function resolveHopPositions(hops, payload, resolvedPath) {
+ // #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';
+ function oneByteHopsMode() {
+ const stored = typeof window.MC_getStored1ByteHopsMode === 'function'
+ ? window.MC_getStored1ByteHopsMode() : null;
+ return stored || LIVE_1BYTE_HOPS_FALLBACK;
+ }
+
+ // #912 M1 — applies the mode to a path before it is resolved. Hide leaves
+ // the 1-byte hops out, with resolved_path filtered in step so each server
+ // answer stays with its own hop; Mark keeps them and flags their positions.
+ // Returns the input arrays untouched for Show, or when nothing changes.
+ // O(hops), no lookups: same order as the resolve that follows.
+ function applyOneByteHopsMode(hops, resolvedPath, mode) {
+ const out = { hops: hops, resolvedPath: resolvedPath, oneByte: null, hidden: 0 };
+ const isVisibleHop = window.MC_isVisibleHop;
+ if ((mode !== 'hide' && mode !== 'mark') || !hops || !hops.length ||
+ typeof isVisibleHop !== 'function') return out;
+ const opts = { hide1ByteHops: true };
+ const paired = !!resolvedPath && resolvedPath.length === hops.length;
+ let kept = null, keptRp = null;
+ for (let i = 0; i < hops.length; i++) {
+ if (isVisibleHop(hops[i], opts)) {
+ if (kept) { kept.push(hops[i]); if (keptRp) keptRp.push(resolvedPath[i]); }
+ continue;
+ }
+ if (mode === 'mark') {
+ if (!out.oneByte) out.oneByte = new Array(hops.length).fill(false);
+ out.oneByte[i] = true;
+ continue;
+ }
+ if (!kept) { kept = hops.slice(0, i); keptRp = paired ? resolvedPath.slice(0, i) : null; }
+ out.hidden++;
+ }
+ if (kept) {
+ out.hops = kept;
+ // A resolved_path that did not match the hops is ignored downstream; it
+ // must not start to match the shorter path by accident.
+ out.resolvedPath = keptRp;
+ }
+ return out;
+ }
+
+ // #912 M1 — a segment is drawn dashed and lighter when either end is an
+ // uncertain position (Mark: a 1-byte hop; Hide: any, once hops were dropped).
+ function isUncertainSegment(a, b) {
+ return !!((a && a.uncertain) || (b && b.uncertain));
+ }
+
+ // mode: the 1-byte hop setting (#912 M1); anything but 'hide' / 'mark'
+ // draws every hop unmarked.
+ function resolveHopPositions(hops, payload, resolvedPath, mode) {
// Hoist sender GPS guard once — reject (0,0) as "no GPS"
const hasValidGps = payload.lat != null && payload.lon != null
&& !(payload.lat === 0 && payload.lon === 0);
const senderLat = hasValidGps ? payload.lat : null;
const senderLon = hasValidGps ? payload.lon : null;
- const raw = resolveHopEntries(hops, payload, resolvedPath);
+ const filtered = applyOneByteHopsMode(hops, resolvedPath, mode);
+ const raw = resolveHopEntries(filtered.hops, payload, filtered.resolvedPath);
+ if (filtered.oneByte) {
+ for (let i = 0; i < raw.length; i++) if (filtered.oneByte[i]) raw[i].uncertain = true;
+ }
// Add sender position as anchor if available
if (payload.pubKey && senderLat != null) {
@@ -4846,6 +4913,11 @@
raw.unshift({ key: payload.pubKey, pos: [payload.lat, payload.lon], name: payload.name || payload.pubKey.slice(0, 8), known: true });
}
}
+ // Hide dropped hops: no segment of what is left reads as a direct link
+ // (route-render.js does the same, #1689 r1).
+ if (filtered.hidden > 0) {
+ for (let i = 0; i < raw.length; i++) raw[i].uncertain = true;
+ }
if (!showGhostHops) return raw.filter(h => h.known);
@@ -4931,7 +5003,8 @@
const lineColor = (isGhost || nextGhost) ? '#94a3b8' : color;
const lineOpacity = (isGhost || nextGhost) ? 0.3 : undefined;
const segHash = forceColor ? null : pktMeta?.hash;
- drawAnimatedLine(hp.pos, nextPos, lineColor, () => { hopIndex++; nextHop(); }, lineOpacity, rawHex, segHash);
+ const uncertain = isUncertainSegment(hp, hopPositions[hopIndex + 1]);
+ drawAnimatedLine(hp.pos, nextPos, lineColor, () => { hopIndex++; nextHop(); }, lineOpacity, rawHex, segHash, uncertain);
} else {
if (!isGhost) pulseNode(hp.key, hp.pos, typeName);
hopIndex++; nextHop();
@@ -5506,7 +5579,8 @@
const line = L.polyline([anim.from, anim.to], {
pane: 'animationsPane', // #1514 M2 — fades stack with the moving phase (z=625).
color: anim.lineColor, weight: anim.isDashed ? 1.5 : 2, opacity: anim.opacity,
- lineCap: 'round', dashArray: anim.isDashed ? '4 6' : null
+ lineCap: 'round', dashArray: anim.isDashed ? '4 6' : null,
+ className: anim.uncertain ? 'live-path-uncertain' : ''
}).addTo(pathsLayer);
recentPaths.push({ line, glowLine: contrail, time: Date.now() });
@@ -5529,7 +5603,9 @@
}
}
- function drawAnimatedLine(from, to, color, onComplete, overrideOpacity, rawHex, hash) {
+ // uncertain (#912 M1): a segment at a 1-byte hop (Mark) or of a path whose
+ // 1-byte hops were left out (Hide): dashed and lighter, in its own colour.
+ function drawAnimatedLine(from, to, color, onComplete, overrideOpacity, rawHex, hash, uncertain) {
// GUARD: Prevent stale callbacks from pushing to a destroyed map
if (!map || !animCtx) {
if (onComplete) onComplete();
@@ -5538,14 +5614,15 @@
if (matrixMode) return drawMatrixLine(from, to, color, onComplete, rawHex);
- const mainOpacity = overrideOpacity ?? 0.8;
- const isDashed = overrideOpacity != null;
+ const isGhostLine = overrideOpacity != null;
+ const mainOpacity = overrideOpacity ?? (uncertain ? UNCERTAIN_SEGMENT_OPACITY : 0.8);
+ const isDashed = isGhostLine || !!uncertain;
var hashFill = '#fff';
var hashOutline = color;
var contrailColor = color;
- if (colorByHash && hash && !isDashed && window.HashColor) {
+ if (colorByHash && hash && !isGhostLine && window.HashColor) {
var hsl = HashColor.hashToHsl(hash, _liveTheme());
hashFill = hsl;
hashOutline = HashColor.hashToOutline(hash, _liveTheme());
@@ -5560,7 +5637,8 @@
lastTick: null,
opacity: mainOpacity,
isDashed: isDashed,
- lineColor: (colorByHash && hash && !isDashed && window.HashColor) ? hashFill : color,
+ uncertain: !!uncertain,
+ lineColor: (colorByHash && hash && !isGhostLine && window.HashColor) ? hashFill : color,
contrailColor: contrailColor,
hashFill: hashFill,
hashOutline: hashOutline,
diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json
index 8f96356c4..bd87c0d36 100644
--- a/scripts/e2e-shards.json
+++ b/scripts/e2e-shards.json
@@ -336,6 +336,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-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 65f5f91c6..4c3569b44 100755
--- a/test-all.sh
+++ b/test-all.sh
@@ -312,6 +312,7 @@ run test-issue-1509-detect-preset.js
run test-issue-353-path-hash-warn.js
run test-issue-480-no-scope.js
run test-live.js
+run test-issue-912-live-1byte-hops.js
run test-issue-220-live-filter-readiness.js
run test-coverage-gate.js
run test-node-reach-coverage.js
diff --git a/test-issue-674-1byte-hop-modes-e2e.js b/test-issue-674-1byte-hop-modes-e2e.js
index 414c3d4f2..41d4bd901 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 M1), 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..ee8008ceb 100644
--- a/test-issue-674-1byte-hop-modes.js
+++ b/test-issue-674-1byte-hop-modes.js
@@ -92,7 +92,7 @@ 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', () => {
+test('set1ByteHopsMode stores every explicit choice (mark too, #912 M1), rejects junk', () => {
const store = {};
const w = sandbox(store, ['hop-filter.js']);
w.MC_set1ByteHopsMode('hide');
@@ -100,7 +100,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 (#912 M1): ' + 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-live-1byte-hops-e2e.js b/test-issue-912-live-1byte-hops-e2e.js
new file mode 100644
index 000000000..3910575a2
--- /dev/null
+++ b/test-issue-912-live-1byte-hops-e2e.js
@@ -0,0 +1,282 @@
+/**
+ * E2E (#912 M1): the Live map follows the 1-byte hop setting (Show / Mark /
+ * Hide) of the customizer (public/hop-filter.js, #674).
+ *
+ * Packets are fed through the real WS handler (window._liveWSHandler(), the
+ * function app.js calls per frame). A route is sender A (GPS from its advert)
+ * → B as a 1-byte hop → C as a 2-byte hop, with the server's resolved_path,
+ * between three fixture nodes with distinct positions. Every L.polyline the
+ * Live page creates after the injection is recorded (the fading trail of each
+ * segment and the clickable route), so the checks read what was drawn:
+ *
+ * 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);
+ * - 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
+ * lighter (class live-path-uncertain), since a hop was dropped;
+ * - Hide, pure 1-byte path with decoded.path.hops set: the path_json
+ * route filters down to the sender, so renderPacketTree falls back to
+ * decoded.path.hops; that fallback must apply Hide too (no vertex
+ * other than the sender's);
+ * - 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.
+ *
+ * Usage: BASE_URL=http://localhost:13581 node test-issue-912-live-1byte-hops-e2e.js
+ */
+'use strict';
+const { chromium } = require('playwright');
+
+const BASE = process.env.BASE_URL || 'http://localhost:13581';
+
+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 function open(browser, { phone = false } = {}) {
+ const ctx = await browser.newContext(phone
+ ? { viewport: { width: 375, height: 560 }, isMobile: true, hasTouch: true }
+ : { viewport: { width: 1440, height: 900 } });
+ await ctx.addInitScript(() => {
+ try {
+ if (sessionStorage.getItem('__e2e912_seeded')) return; // a cold start, once per tab
+ sessionStorage.setItem('__e2e912_seeded', '1');
+ localStorage.removeItem('meshcore-1byte-hops-mode');
+ localStorage.removeItem('meshcore-hide-1byte-hops');
+ localStorage.removeItem('live-multibyte-only');
+ localStorage.removeItem('live-matrix-mode');
+ localStorage.removeItem('live-realistic-propagation');
+ } catch (_e) { /* storage unavailable */ }
+ });
+ const page = await ctx.newPage();
+ page.setDefaultTimeout(30000);
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e.message)));
+ return { ctx, page, errors };
+}
+
+// Waits for Live to have its nodes and for the replayed fixture packets to
+// finish animating, then records every polyline created from here on.
+async function readyLive(page) {
+ await page.waitForFunction(() => window._liveNodeData && window._liveWSHandler && window._liveWSHandler() &&
+ window.HopResolver && window.HopResolver.ready() &&
+ Object.values(window._liveNodeData()).filter((n) => n.lat && n.lon).length >= 4, null, { timeout: 30000 });
+ await page.waitForFunction(() => window._liveTestSeams.getAnimCount() === 0 &&
+ document.getElementById('liveAnimCount').textContent === '0', null, { timeout: 30000 });
+ await page.evaluate(() => {
+ if (window.__e2e912Polys) return;
+ window.__e2e912Polys = [];
+ const orig = L.polyline;
+ L.polyline = function (latlngs, options) {
+ const p = orig.apply(this, arguments);
+ window.__e2e912Polys.push({
+ latlngs: (latlngs || []).map((ll) => { const x = L.latLng(ll); return [x.lat, x.lng]; }),
+ className: (options && options.className) || '',
+ dashArray: (options && options.dashArray) || null,
+ opacity: options && options.opacity,
+ weight: options && options.weight,
+ });
+ return p;
+ };
+ });
+}
+
+// Four fixture nodes with GPS and pairwise distinct positions.
+function pickNodes(page) {
+ return page.evaluate(() => {
+ const nd = window._liveNodeData();
+ const out = [];
+ for (const k of Object.keys(nd).sort()) {
+ const n = nd[k];
+ if (!n.lat || !n.lon) continue;
+ if (out.some((o) => Math.abs(o.lat - n.lat) < 0.01 && Math.abs(o.lon - n.lon) < 0.01)) continue;
+ if (out.some((o) => o.key.slice(0, 6) === k.slice(0, 6))) continue;
+ out.push({ key: k, name: n.name, lat: n.lat, lon: n.lon });
+ if (out.length === 4) break;
+ }
+ return out;
+ });
+}
+
+// Sends one ADVERT from `a` over `hops` ([{ node, bytes }]) and waits until
+// every animation is done. Returns the polylines it drew. Headless Chromium
+// without a GPU paints Live at a few frames a second and a segment's progress
+// per frame is capped (tickDt), so a 3-segment route can take ~15 s.
+// With { decodedPath: true } the packet also carries decoded.path.hops, the
+// transmission-level path renderPacketTree falls back to when no observation
+// path yields two positions.
+async function send(page, id, a, hops, { decodedPath = false } = {}) {
+ return page.evaluate(async ({ id, a, hops, decodedPath }) => {
+ window.__e2e912Polys.length = 0;
+ const prefixes = hops.map((h) => h.node.key.slice(0, h.bytes * 2).toUpperCase());
+ window._liveWSHandler()({ type: 'packet', data: {
+ id: 912000000 + id,
+ hash: (0x912000000000 + id).toString(16).padStart(16, '0'),
+ timestamp: new Date().toISOString(),
+ observer_id: 'E2E912', observer_name: 'e2e-912',
+ path_json: JSON.stringify(prefixes),
+ resolved_path: JSON.stringify(hops.map((h) => h.node.key)),
+ decoded: Object.assign({ header: { payloadTypeName: 'ADVERT' },
+ payload: { type: 'ADVERT', pubKey: a.key, name: a.name, lat: a.lat, lon: a.lon } },
+ decodedPath ? { path: { hops: prefixes } } : {}),
+ } });
+ const t0 = Date.now();
+ await new Promise((r) => setTimeout(r, 100));
+ while (window._liveTestSeams.getAnimCount() > 0 || document.getElementById('liveAnimCount').textContent !== '0') {
+ if (Date.now() - t0 > 60000) {
+ throw new Error('animation did not finish: anims=' + window._liveTestSeams.getAnimCount() +
+ ' counter=' + document.getElementById('liveAnimCount').textContent);
+ }
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return window.__e2e912Polys.slice();
+ }, { id, a, hops, decodedPath });
+}
+
+const at = (ll, n) => Math.abs(ll[0] - n.lat) < 1e-9 && Math.abs(ll[1] - n.lon) < 1e-9;
+const hasVertex = (polys, n) => polys.some((p) => p.latlngs.some((ll) => at(ll, n)));
+// Any vertex that is not the sender's: whichever node a heuristic picks for a
+// 1-byte prefix, a drawn hop shows up here.
+const offSender = (polys, a) => polys.filter((p) => p.latlngs.some((ll) => !at(ll, a)));
+// The fading core line of the segment from → to: not its glow (weight 6) and
+// not the invisible clickable route (opacity 0, weight 12).
+const segment = (polys, from, to) => polys.find((p) => p.latlngs.length === 2 && p.opacity > 0 &&
+ p.weight <= 2 && at(p.latlngs[0], from) && at(p.latlngs[1], to));
+const uncertain = (p) => !!p && /\blive-path-uncertain\b/.test(p.className) && p.dashArray === '4 6';
+
+async function pickMode(page, mode, phone) {
+ if (!(await page.$('.cust-overlay:not(.hidden)'))) {
+ if (phone) {
+ await page.tap('[data-bottom-nav-tab="more"]');
+ await page.waitForSelector('[data-mpa-mirror="customizeToggle"]', { state: 'visible', timeout: 5000 });
+ await page.tap('[data-mpa-mirror="customizeToggle"]');
+ } else {
+ // Live hides the top bar after 4 s; a mouse move over the page brings it back.
+ await page.mouse.move(700, 450);
+ await page.mouse.move(720, 460);
+ await page.waitForSelector('#customizeToggle', { state: 'visible', timeout: 5000 });
+ await page.click('#customizeToggle');
+ }
+ await page.waitForSelector('.cust-overlay:not(.hidden)', { timeout: 5000 });
+ }
+ if (phone) await page.tap('.cust-tab[data-tab="display"]'); else await page.click('.cust-tab[data-tab="display"]');
+ await page.waitForSelector('#cv2-hide-1byte-hops', { state: 'visible' });
+ if (phone) await page.tap('#cv2-hide-1byte-hops');
+ await page.selectOption('#cv2-hide-1byte-hops', mode);
+ if (phone) await page.tap('.cust-close'); else await page.click('.cust-close');
+ await page.waitForSelector('.cust-overlay:not(.hidden)', { state: 'detached', timeout: 5000 }).catch(() => {});
+ assert(await page.evaluate(() => window.MC_get1ByteHopsMode()) === mode, 'the select did not set ' + mode);
+}
+
+(async () => {
+ const browser = await chromium.launch({
+ headless: true,
+ executablePath: process.env.CHROMIUM_PATH || undefined,
+ args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'],
+ });
+ try {
+ console.log('\n=== #912 M1 Live 1-byte hop modes E2E against ' + BASE + ' ===');
+
+ {
+ const h = await open(browser);
+ await h.page.goto(BASE + '/#/live', { waitUntil: 'load' });
+ await readyLive(h.page);
+ const [A, B, C, D] = await pickNodes(h.page);
+ assert(D, 'the fixture needs four nodes with distinct GPS positions');
+ const route = [{ node: B, bytes: 1 }, { node: C, bytes: 2 }];
+ 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 () => {
+ const st = await h.page.evaluate(() => ({ stored: localStorage.getItem('meshcore-1byte-hops-mode'),
+ global: window.MC_get1ByteHopsMode() }));
+ 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)));
+ });
+
+ await step('Show (control): the 1-byte hop is drawn, nothing is marked', async () => {
+ await pickMode(h.page, 'show', false);
+ const polys = await send(h.page, ++id, A, route);
+ assert(hasVertex(polys, B), 'Show 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), 'Show marks nothing');
+ // Control for the Hide fallback step below: this packet does draw.
+ const pure = await send(h.page, ++id, A, pureOneByte, { decodedPath: true });
+ assert(offSender(pure, A).length > 0, 'Show must draw the pure 1-byte path: ' + JSON.stringify(pure));
+ });
+
+ await step('Hide: no Live polyline vertex sits on the 1-byte hop, A→C is dashed and lighter', async () => {
+ await pickMode(h.page, 'hide', false);
+ const polys = await send(h.page, ++id, A, route);
+ assert(polys.length > 0, 'the route must still be drawn');
+ assert(!hasVertex(polys, B), 'a vertex sits on the hidden hop B: ' + JSON.stringify(polys));
+ const ac = segment(polys, A, C);
+ assert(ac, 'A→C must be drawn: ' + JSON.stringify(polys));
+ assert(uncertain(ac), 'A→C must carry live-path-uncertain + 4 6 dashes: ' + JSON.stringify(ac));
+ assert(ac.opacity < 0.8, 'A→C must be lighter than a certain segment (0.8): ' + ac.opacity);
+ });
+
+ await step('Hide: a pure 1-byte path with decoded.path.hops set draws no hop (fallback path)', async () => {
+ const polys = await send(h.page, ++id, A, pureOneByte, { decodedPath: true });
+ assert(offSender(polys, A).length === 0,
+ 'the decoded.path fallback drew a hidden 1-byte hop: ' + JSON.stringify(polys));
+ });
+
+ await step('Hide: a route without 1-byte hops is drawn unmarked', async () => {
+ const polys = await send(h.page, ++id, A, [{ node: C, bytes: 2 }, { node: D, bytes: 3 }]);
+ assert(segment(polys, A, C) && segment(polys, C, D), 'A→C and C→D must be drawn');
+ assert(!polys.some(uncertain), 'nothing was dropped, so nothing is marked');
+ });
+
+ await step('Mark: the 1-byte hop stays; A→B and B→C carry the dashed class, C→D not', async () => {
+ await pickMode(h.page, 'mark', false);
+ const polys = await send(h.page, ++id, A, [{ node: B, bytes: 1 }, { node: C, bytes: 2 }, { node: D, bytes: 3 }]);
+ assert(hasVertex(polys, B), 'Mark keeps B');
+ const ab = segment(polys, A, B), bc = segment(polys, B, C), cd = segment(polys, C, D);
+ assert(uncertain(ab), 'A→B must be marked: ' + JSON.stringify(ab));
+ assert(uncertain(bc), 'B→C must be marked: ' + JSON.stringify(bc));
+ 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);
+ });
+
+ await step('no page errors', async () => {
+ assert(h.errors.length === 0, h.errors.join(' | '));
+ });
+ await h.ctx.close();
+ }
+
+ await step('375x560 touch phone, cold start, real taps: Hide leaves no vertex on the 1-byte hop', async () => {
+ const h = await open(browser, { phone: true });
+ await h.page.goto(BASE + '/', { waitUntil: 'load' });
+ await pickMode(h.page, 'hide', true);
+ await h.page.tap('[data-bottom-nav-tab="live"]');
+ await h.page.waitForFunction(() => location.hash.indexOf('#/live') === 0);
+ await readyLive(h.page);
+ const [A, B, C] = await pickNodes(h.page);
+ const polys = await send(h.page, 99, 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));
+ const sw = await h.page.evaluate(() => document.documentElement.scrollWidth);
+ assert(sw <= 375, 'no sideways scroll at 375px: ' + sw);
+ assert(h.errors.length === 0, h.errors.join(' | '));
+ await h.ctx.close();
+ });
+ } finally {
+ await browser.close();
+ }
+ console.log('\n' + passed + ' passed, ' + failed + ' failed');
+ process.exit(failed ? 1 : 0);
+})().catch((e) => { console.error(e); process.exit(1); });
diff --git a/test-issue-912-live-1byte-hops.js b/test-issue-912-live-1byte-hops.js
new file mode 100644
index 000000000..7be37e69e
--- /dev/null
+++ b/test-issue-912-live-1byte-hops.js
@@ -0,0 +1,387 @@
+/**
+ * #912 M1 — the Live map follows the 1-byte hop setting (Show / Mark / Hide).
+ *
+ * The setting lives in public/hop-filter.js (#674) and already applies to the
+ * route view, the Live feed and the node path panel. These tests pin that the
+ * 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);
+ * 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
+ * remaining segment is marked (dashed + lighter, as route-render.js does);
+ * Hide on a path without 1-byte hops changes nothing;
+ * 4. Mark: 1-byte hops stay and the segments that start or end at one are
+ * marked; the sender anchor and multi-byte hops are not;
+ * 5. the input arrays are never mutated;
+ * 6. perf (AGENTS.md rule 0): the filter plus resolveHopPositions on 10k
+ * synthetic paths stays within budget.
+ *
+ * Run: node test-issue-912-live-1byte-hops.js
+ */
+'use strict';
+const fs = require('fs');
+const path = require('path');
+const vm = require('vm');
+const assert = require('assert');
+
+let passed = 0, failed = 0;
+function test(name, fn) {
+ try { fn(); passed++; console.log(' ✅ ' + name); }
+ catch (e) { failed++; console.log(' ❌ ' + name + ': ' + e.message); }
+}
+
+function makeStorage(seed) {
+ const store = Object.assign({}, seed);
+ return {
+ getItem: k => (k in store ? store[k] : null),
+ setItem: (k, v) => { store[k] = String(v); },
+ removeItem: k => { delete store[k]; },
+ };
+}
+
+// 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 = {} } = {}) {
+ const el = () => ({
+ style: {}, dataset: {}, textContent: '', innerHTML: '',
+ classList: { add() {}, remove() {}, contains() { return false; } },
+ setAttribute() {}, getAttribute() { return null; }, addEventListener() {},
+ appendChild() {}, getContext: () => ({}),
+ });
+ const listeners = {};
+ const ctx = {
+ window: {
+ devicePixelRatio: 1,
+ addEventListener(t, fn) { (listeners[t] = listeners[t] || []).push(fn); },
+ removeEventListener() {},
+ dispatchEvent(e) { (listeners[e.type] || []).forEach(fn => fn(e)); },
+ },
+ document: {
+ readyState: 'complete', hidden: false,
+ createElement: el, createElementNS: el,
+ head: { appendChild() {} }, body: { appendChild() {}, removeChild() {}, contains: () => false },
+ documentElement: { getAttribute: () => null, setAttribute() {} },
+ getElementById: () => null, querySelector: () => null, querySelectorAll: () => [],
+ addEventListener() {}, removeEventListener() {},
+ },
+ // hop-resolver.js logs every heuristic pick; keep the run readable.
+ console: { log() {}, debug() {}, info() {}, warn: console.warn, error: console.error },
+ Date, Infinity, Math, Array, Object, String, Number, JSON, RegExp,
+ Error, TypeError, Map, Set, Promise, URLSearchParams,
+ parseInt, parseFloat, isNaN, isFinite, encodeURIComponent, decodeURIComponent,
+ setTimeout: () => 0, clearTimeout() {}, setInterval: () => 0, clearInterval() {},
+ requestAnimationFrame: () => 0, cancelAnimationFrame() {},
+ performance: { now: () => Date.now() },
+ localStorage: makeStorage(storage),
+ location: { hash: '', protocol: 'https:', host: 'localhost' },
+ getComputedStyle: () => ({ getPropertyValue: () => '' }),
+ matchMedia: () => ({ matches: false, addEventListener() {} }),
+ navigator: {}, visualViewport: null,
+ MutationObserver: function () { this.observe = () => {}; this.disconnect = () => {}; },
+ WebSocket: function () { this.close = () => {}; },
+ IATA_COORDS_GEO: {},
+ AreaFilter: { init() {}, onChange() {}, areaQueryString: () => '' },
+ RegionFilter: { init() {}, getSelected: () => null, onRegionChange() {}, nodesRegionQueryString: () => '', packetsRegionQueryString: () => '' },
+ L: { polyline: () => { const p = { addTo() { return p; }, setStyle() {}, remove() {} }; return p; } },
+ registerPage() {}, onWS() {}, offWS() {}, connectWS() {},
+ api: () => Promise.resolve([]), invalidateApiCache() {},
+ favStar: () => '', bindFavStars() {}, getFavorites: () => [], isFavorite: () => false,
+ MeshAudio: null,
+ fetch: () => new Promise(() => {}),
+ };
+ ctx.window.localStorage = ctx.localStorage;
+ ctx.window.CustomEvent = function (type, init) { this.type = type; this.detail = init && init.detail; };
+ ctx.CustomEvent = ctx.window.CustomEvent;
+ vm.createContext(ctx);
+ const files = ['payload-labels.js', 'roles.js', 'live-heard-filter.js', 'packet-helpers.js', 'hop-resolver.js', 'live.js'];
+ if (withHopFilter) files.unshift('hop-filter.js');
+ for (const f of files) {
+ 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];
+ }
+ return ctx;
+}
+
+// Sender A (GPS from its advert), a 1-byte hop to B, a 2-byte hop to C and a
+// 3-byte hop to D. Every hop has a distinct position, so a dropped hop is
+// visible as a missing vertex.
+const A = { public_key: 'a1' + '0'.repeat(62), name: 'SENDER-A', role: 'companion', lat: 55.40, lon: 10.38 };
+const B = { public_key: '18' + '1'.repeat(62), name: 'REPEATER-B', role: 'repeater', lat: 55.70, lon: 9.53 };
+const C = { public_key: 'c2c2' + '2'.repeat(60), name: 'REPEATER-C', role: 'repeater', lat: 56.15, lon: 10.20 };
+const D = { public_key: 'd3d3d3' + '3'.repeat(58), name: 'REPEATER-D', role: 'repeater', lat: 57.05, lon: 9.92 };
+const PAYLOAD = { pubKey: A.public_key, name: A.name, lat: A.lat, lon: A.lon };
+
+function setup(opts) {
+ const ctx = loadLive(opts);
+ const nodes = [A, B, C, D];
+ ctx.HopResolver.init(nodes);
+ ctx.window.HopResolver = ctx.HopResolver;
+ const nodeData = ctx.window._liveNodeData();
+ for (const n of nodes) nodeData[n.public_key] = Object.assign({}, n);
+ return ctx;
+}
+
+const keys = out => out.map(p => p.key);
+const marked = out => out.map(p => !!p.uncertain);
+
+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.
+ 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');
+ assert.strictEqual(ctx.window.MC_get1ByteHopsMode(), 'mark', 'hop-filter.js DEFAULT_MODE is unchanged');
+ assert.strictEqual(ctx.window.MC_getStored1ByteHopsMode(), null);
+ });
+
+ 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());
+ assert.deepStrictEqual(keys(out), [A.public_key, B.public_key, C.public_key]);
+ assert.deepStrictEqual(marked(out), [false, false, false]);
+ });
+
+ for (const stored of ['show', 'mark', 'hide']) {
+ test('a stored "' + stored + '" from an earlier visit applies on Live', () => {
+ const fresh = loadLive({ storage: { 'meshcore-1byte-hops-mode': stored } });
+ assert.strictEqual(fresh.window._liveOneByteHopsMode(), stored);
+ });
+ }
+
+ test('the #1633 "hide" key migrates and applies on Live', () => {
+ const fresh = loadLive({ storage: { 'meshcore-hide-1byte-hops': 'true' } });
+ 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 mode change reaches the next packet at once (MC_set1ByteHopsMode)', () => {
+ let fired = null;
+ ctx.window.addEventListener('mc-hide-1byte-hops-changed', e => { fired = e.detail.mode; });
+ ctx.window.MC_set1ByteHopsMode('hide');
+ assert.strictEqual(fired, 'hide', 'the setter fires mc-hide-1byte-hops-changed');
+ assert.strictEqual(mode(), 'hide');
+ ctx.window.MC_set1ByteHopsMode('show');
+ assert.strictEqual(mode(), 'show');
+ ctx.window.MC_set1ByteHopsMode('mark');
+ assert.strictEqual(mode(), 'mark');
+ });
+
+ test('without hop-filter.js the Live map behaves as Show', () => {
+ const bare = loadLive({ withHopFilter: false });
+ assert.strictEqual(bare.window._liveOneByteHopsMode(), 'show');
+ });
+}
+
+console.log('\n=== #912 M1: which hops reach the animation, and which are marked ===');
+{
+ const ctx = setup();
+ const resolve = ctx.window._liveResolveHopPositions;
+ const hops = ['18', 'C2C2', 'D3D3D3'];
+ const rp = [B.public_key, C.public_key, D.public_key];
+
+ test('Show: every hop reaches the animation, nothing is marked', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'show');
+ assert.deepStrictEqual(keys(out), [A.public_key, B.public_key, C.public_key, D.public_key]);
+ assert.deepStrictEqual(marked(out), [false, false, false, false]);
+ });
+
+ test('no mode argument behaves as Show (existing callers unchanged)', () => {
+ const out = resolve(hops, PAYLOAD, rp);
+ assert.deepStrictEqual(keys(out), [A.public_key, B.public_key, C.public_key, D.public_key]);
+ assert.deepStrictEqual(marked(out), [false, false, false, false]);
+ });
+
+ test('Hide: the 1-byte hop is left out of the animated path', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'hide');
+ assert.deepStrictEqual(keys(out), [A.public_key, C.public_key, D.public_key]);
+ assert.ok(!out.some(p => p.pos[0] === B.lat && p.pos[1] === B.lon), 'no vertex may sit on B');
+ });
+
+ test('Hide: when hops were dropped every remaining segment is marked', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'hide');
+ assert.deepStrictEqual(marked(out), [true, true, true]);
+ for (let i = 0; i < out.length - 1; i++) {
+ assert.strictEqual(ctx.window._liveIsUncertainSegment(out[i], out[i + 1]), true, 'segment ' + i);
+ }
+ });
+
+ test('Hide: resolved_path stays paired with its own hop after the drop', () => {
+ // A 1-byte hop between two multi-byte ones: the server answer for the
+ // last hop must not shift onto the middle one.
+ const out = resolve(['C2C2', '18', 'D3D3D3'], PAYLOAD, [C.public_key, B.public_key, D.public_key], 'hide');
+ assert.deepStrictEqual(keys(out), [A.public_key, C.public_key, D.public_key]);
+ });
+
+ test('Hide: the server answer wins over the heuristic for a shared multi-byte prefix', () => {
+ // C and CX share "c2c2". The heuristic picks C (next to the sender); the
+ // server said CX. After the 1-byte hop is dropped CX must still win, so
+ // resolved_path has to be filtered in step with the hops.
+ const CX = { public_key: 'c2c2' + '9'.repeat(60), name: 'REPEATER-CX', role: 'repeater', lat: 57.70, lon: 11.95 };
+ ctx.HopResolver.init([A, B, C, D, CX]);
+ ctx.window._liveNodeData()[CX.public_key] = Object.assign({}, CX);
+ const heuristic = resolve(['C2C2'], PAYLOAD, null, 'show');
+ const out = resolve(['18', 'C2C2'], PAYLOAD, [B.public_key, CX.public_key], 'hide');
+ ctx.HopResolver.init([A, B, C, D]);
+ delete ctx.window._liveNodeData()[CX.public_key];
+ assert.strictEqual(heuristic[1].key, C.public_key, 'precondition: without the server the heuristic picks C');
+ assert.deepStrictEqual(keys(out), [A.public_key, CX.public_key]);
+ });
+
+ test('Hide: a resolved_path of the wrong length is not realigned by the drop', () => {
+ // resolved_path [C] does not match the 2 hops, so it is ignored. After
+ // the drop only one hop is left; [C] must not become its answer.
+ const E = { public_key: 'e5e5' + '5'.repeat(60), name: 'REPEATER-E', role: 'repeater', lat: 54.90, lon: 9.80 };
+ ctx.HopResolver.init([A, B, C, D, E]);
+ ctx.window._liveNodeData()[E.public_key] = Object.assign({}, E);
+ const out = resolve(['18', 'E5E5'], PAYLOAD, [C.public_key], 'hide');
+ ctx.HopResolver.init([A, B, C, D]);
+ assert.deepStrictEqual(keys(out), [A.public_key, E.public_key], JSON.stringify(keys(out)));
+ });
+
+ test('Hide with no 1-byte hops changes nothing', () => {
+ const mb = ['C2C2', 'D3D3D3'], mbrp = [C.public_key, D.public_key];
+ const show = resolve(mb, PAYLOAD, mbrp, 'show');
+ const hide = resolve(mb, PAYLOAD, mbrp, 'hide');
+ assert.deepStrictEqual(hide, show);
+ assert.deepStrictEqual(marked(hide), [false, false, false]);
+ });
+
+ test('Mark: the 1-byte hop stays, and only its own position is marked', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'mark');
+ assert.deepStrictEqual(keys(out), [A.public_key, B.public_key, C.public_key, D.public_key]);
+ assert.deepStrictEqual(marked(out), [false, true, false, false]);
+ });
+
+ test('Mark: the segments that start or end at a 1-byte hop are marked, the rest not', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'mark');
+ const seg = i => ctx.window._liveIsUncertainSegment(out[i], out[i + 1]);
+ assert.deepStrictEqual([seg(0), seg(1), seg(2)], [true, true, false],
+ 'A→B and B→C touch the 1-byte hop; C→D does not');
+ });
+
+ test('Mark with no 1-byte hops marks nothing', () => {
+ const out = resolve(['C2C2', 'D3D3D3'], PAYLOAD, [C.public_key, D.public_key], 'mark');
+ assert.deepStrictEqual(marked(out), [false, false, false]);
+ });
+
+ test('an unknown mode behaves as Show', () => {
+ const out = resolve(hops, PAYLOAD, rp, 'bogus');
+ assert.deepStrictEqual(keys(out), [A.public_key, B.public_key, C.public_key, D.public_key]);
+ assert.deepStrictEqual(marked(out), [false, false, false, false]);
+ });
+
+ test('the input hops and resolved_path are never mutated', () => {
+ const h = hops.slice(), r = rp.slice();
+ resolve(h, PAYLOAD, r, 'hide');
+ resolve(h, PAYLOAD, r, 'mark');
+ assert.deepStrictEqual(h, hops);
+ assert.deepStrictEqual(r, rp);
+ });
+
+ test('the follow (#880) still sees every hop position in Hide', () => {
+ // resolveHopEntries is the per-position view a follow uses; the setting
+ // only shapes what is animated.
+ ctx.window.MC_set1ByteHopsMode('hide');
+ const out = ctx.window._liveResolveHopEntries(hops, PAYLOAD, rp);
+ ctx.window.MC_set1ByteHopsMode('mark');
+ assert.deepStrictEqual(keys(out), [B.public_key, C.public_key, D.public_key]);
+ });
+}
+
+console.log('\n=== #912 M1: perf — filter + resolveHopPositions on 10k paths ===');
+{
+ // AGENTS.md rule 0: the WS hot path. 2,000 repeaters (the production
+ // scale), 10,000 paths of 1–8 hops mixing 1-, 2- and 3-byte hashes; 80 %
+ // carry a server resolved_path, the rest go through the heuristic.
+ const ctx = loadLive();
+ const nodes = [];
+ let seed = 912;
+ const rnd = () => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff;
+ for (let i = 0; i < 2000; i++) {
+ const pk = (i * 2654435761 >>> 0).toString(16).padStart(8, '0') + i.toString(16).padStart(56, '0');
+ nodes.push({ public_key: pk, name: 'N' + i, role: 'repeater', lat: 54 + rnd() * 3, lon: 8 + rnd() * 4 });
+ }
+ ctx.HopResolver.init(nodes);
+ ctx.window.HopResolver = ctx.HopResolver;
+ const nodeData = ctx.window._liveNodeData();
+ for (const n of nodes) nodeData[n.public_key] = n;
+ const paths = [];
+ for (let i = 0; i < 10000; i++) {
+ const len = 1 + Math.floor(rnd() * 8);
+ const size = 1 + Math.floor(rnd() * 3);
+ const hops = [], rp = [];
+ for (let j = 0; j < len; j++) {
+ const n = nodes[Math.floor(rnd() * nodes.length)];
+ hops.push(n.public_key.slice(0, size * 2).toUpperCase());
+ rp.push(n.public_key);
+ }
+ const s = nodes[Math.floor(rnd() * nodes.length)];
+ paths.push({ hops, rp: rnd() < 0.8 ? rp : null, payload: { pubKey: s.public_key, lat: s.lat, lon: s.lon } });
+ }
+ const resolve = ctx.window._liveResolveHopPositions;
+ const filter = ctx.window._liveApplyOneByteHopsMode;
+ function time(fn) {
+ const t0 = process.hrtime.bigint();
+ fn();
+ return Number(process.hrtime.bigint() - t0) / 1e6;
+ }
+ const full = mode => time(() => { for (const p of paths) resolve(p.hops, p.payload, p.rp, mode); });
+ const filterOnly = mode => time(() => { for (const p of paths) filter(p.hops, p.rp, mode); });
+ // Interleaved, best of 5 after a warm-up, so machine noise hits every mode.
+ const best = { show: Infinity, hide: Infinity, mark: Infinity };
+ const bestFilter = { hide: Infinity, mark: Infinity };
+ for (let r = 0; r < 6; r++) {
+ for (const m of ['show', 'hide', 'mark']) {
+ const ms = full(m);
+ if (r > 0) best[m] = Math.min(best[m], ms);
+ }
+ for (const m of ['hide', 'mark']) {
+ const ms = filterOnly(m);
+ if (r > 0) bestFilter[m] = Math.min(bestFilter[m], ms);
+ }
+ }
+ console.log(` filter+resolve: show ${best.show.toFixed(1)} ms · hide ${best.hide.toFixed(1)} ms · mark ${best.mark.toFixed(1)} ms`);
+ console.log(` filter alone: hide ${bestFilter.hide.toFixed(1)} ms · mark ${bestFilter.mark.toFixed(1)} ms (10k paths, 2k nodes)`);
+
+ test('the filter alone handles 10k paths within 250 ms and 15 % of the resolve', () => {
+ assert.strictEqual(typeof filter, 'function', '_liveApplyOneByteHopsMode must be exposed');
+ for (const m of ['hide', 'mark']) {
+ assert.ok(bestFilter[m] < 250, `${m}: ${bestFilter[m].toFixed(1)} ms over the 250 ms budget`);
+ assert.ok(bestFilter[m] <= best.show * 0.15,
+ `${m}: ${bestFilter[m].toFixed(1)} ms is over 15 % of the ${best.show.toFixed(1)} ms resolve`);
+ }
+ });
+
+ // About 60–125 ms per mode locally and in CI, so the 6 s cap (and the
+ // 250 ms filter cap above) only catch a gross regression such as a hang.
+ // The relative checks are what catch a regression in the filter.
+ test('filter + resolve: 10k paths within 6 s per mode', () => {
+ for (const m of ['show', 'hide', 'mark']) {
+ assert.ok(best[m] < 6000, `${m}: ${best[m].toFixed(1)} ms over the 6000 ms budget`);
+ }
+ });
+
+ test('filter + resolve in Hide / Mark costs at most 50 % + 20 ms over Show', () => {
+ for (const m of ['hide', 'mark']) {
+ assert.ok(best[m] <= best.show * 1.5 + 20, `${m}: ${best[m].toFixed(1)} ms vs show ${best.show.toFixed(1)} ms`);
+ }
+ });
+}
+
+console.log('\n--- ' + passed + ' passed, ' + failed + ' failed ---\n');
+process.exit(failed > 0 ? 1 : 0);