Publisher.reconnect() called mqtt.js client.reconnect() unconditionally.
mqtt.js connect() replaces this.stream without closing the previous one
(client.js:257), so a press while a CONNECT was still unanswered left the
earlier socket open. When an orphan closed, its 'close' set
client.connected = false over a live session and armed a reconnect that
orphaned that session in turn.
Field log 2026-09-19: connack timeouts on a weak mobile link, then five
presses in four seconds (12:05:54 to 12:05:57), then "connected" followed
by "offline" and "connection closed" in the same second at 12:05:58,
12:06:00, 12:06:02 and 12:06:04.
reconnect() now returns false and does nothing while an attempt is in
flight (no session, no reconnect timer armed); the Push button logs that.
Once the socket has closed it still skips the 4 s wait. Two tests run the
real mqtt.js client over a fake stream; without the guard the first fails.
Not verified: the EMQX log has no lines for this client id, so the
broker-side session takeover between the sockets was not observed.
Version, release notes and the service-worker cache bump ride along, as
AGENTS.md requires.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
holdUntilReply's default was `timers = { setTimeout, clearTimeout }`, so the
native timers were called with that object literal as `this`. Chromium rejects
that with "TypeError: Illegal invocation"; Node does not check, which is why
279 tests passed over it.
The throw lands inside askRepeater's try, after the ask has gone out, so the
20 s hold and the restore of the repeater's original contact path were both
skipped; the restore record waited in localStorage for the next connect. It
fires once per repeater per session, on the ask that applies the override.
Field log 2026-09-18: three of them, 14036f, e3d3f4 and cf7903, each on
"attempt 1 of 4".
Version, release notes and the service-worker cache bump ride along, as
AGENTS.md requires.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A repeater saved as a contact has its stored path forced to zero-hop for the ask and put
back afterwards, and the queue waits for that round. It waited a flat 20s. In the
2026-09-14 commute log 49a98584fce5 and 72d171e63056 both answered 2s after the ask and
the queue then sat blocked 18s more each; cafe314d00e2, heard at 17:47:01, was not asked
until 17:47:14 because of it. Every answer visible across the field logs so far — 11 of
them — arrived 1–2s after its ask.
holdUntilReply resolves on whichever comes first: the matched reply for that target, or
OVERRIDE_HOLD_MS. onRegionsFrame releases the hold right after it files an answer, and a
reply that lands before the hold starts skips it. The no-reply fallback keeps its 20s:
how early a restore is safe while no answer has arrived is a firmware question, and this
only removes time after the answer is in hand.
The restore line now says which way the hold ended, "(reply in, hold ended early)" or
"(no reply in 20s)", so the next field log can confirm it.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012GJuEuyG3JMrSeAGCmJ1GP
noteLinkState's guard was inverted. `state.linkQuiet` holds the INVERSE of
the link being up, so the steady state is `linkQuiet !== linkUp` and an edge
is `linkQuiet === linkUp`. The guard returned on the edge and fell through in
the steady state — the exact opposite of both.
Per-second monitorTick therefore wrote "companion link back" on every tick of
a perfectly healthy link, and swallowed the real transition: linkQuiet never
flipped off its `false` initial value, so "companion link down" could never be
reached at all. A field log from this morning shows 157 of 200 buffered lines
spent on the spam, the whole 200-line ring buffer covering 2m36s, and not one
"link down" line — defeating cc710a3, which added the pair so that a dropped
link would stop reading like an app that had crashed.
The edge decision moves to monitor.js as the pure `linkTransition`, next to
the other per-tick monitor helpers, since app.js cannot be imported under
node --test. Five regression tests cover both steady states, both edges, and a
full drop/return cycle driven tick by tick.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
The 2026-09-13 log ends with two and a half minutes of "discover send failed: GATT
Server is disconnected" — one sweep every 30 seconds, each a write into a characteristic
that no longer exists — an "rf sample incomplete — discarded" for every sampler round,
and region asks failing the same way. None of it could reach a radio.
discoverDecision takes linkUp and reports 'link-down' ahead of every other state; the
monitor tick returns right after rendering it, the RF sampler reschedules without
sampling, and region asks stop with them. The discover clock is not advanced while down,
so the first tick after the link returns sweeps immediately instead of waiting out an
interval.
The link state is read from the browser's own device object through a new
transport.connected(), not mirrored into a flag of ours. A flag would be stale exactly
when it matters, which is the same failure shape as the duplicated default fixed in
v1.17.1 — one source per fact.
Said once in each direction rather than per tick. A log that just goes quiet is
indistinguishable from a crash, an area with nothing to hear, or a feature switched off.
Capture, queueing and uploading are untouched: receptions already in hand are still
queued and published, and the MQTT link keeps its own reconnect.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
Two files held a default for the same limit. src/regionsched.js set DEFAULT_MAX_ASKS = 4
and only the tests read it; src/config.js carried its own 3, and the app reads the
config. So the raise from 3 to 4 shipped in the release notes and not in the app. Nothing
failed and no test could see it — the only evidence was a field log line reading
"attempt 3 of 3 this encounter".
Fixed at the cause rather than by correcting the number: config.js now imports all five
pacing defaults from the scheduler, so there is one number per limit. A test asserts the
config's defaults ARE the scheduler's, which is the assertion that was missing.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
v1.16.0 mirrored simple_repeater's anon_limiter as a rolling client-side ceiling of four
asks per 180s per target. Reading the firmware instead of this repo's notes about it
shows the copy can only do harm.
anon_limiter(4, 180) is real (examples/simple_repeater/MyMesh.cpp:880) and is shared
across every anon request type and every requester, as the notes said. What they did not
say is that RateLimiter::allow uses a FIXED window:
if (now < _start_timestamp + _secs) { _count++; if (_count > _maximum) return false; }
else { _start_timestamp = now; _count = 1; }
The window is anchored to the repeater's clock and starts at the first request it accepts
after an expiry, which a client cannot observe. A rolling copy is therefore wrong in both
directions, and expensively in one: it refuses asks the repeater would have answered
because its window had just reset. The request it refused most reliably was the bonus ask
v1.16.0 was built to send — the one aimed at a strong reception, which by nature does not
wait. The same source shows a denial costs nothing: _count keeps counting but
_start_timestamp does not move, so extra requests neither extend the block nor penalise
the sender.
One repeater's load is bounded by the encounter, unchanged from v1.16.0: four unanswered
asks plus at most one bonus, each at least 30s apart, no new encounter until five minutes
of silence. Five asks over at least two minutes, and on the road far fewer — 180 seconds
is about 3 km, by which time the repeater is out of range and the question does not arise.
That last point is the user's, and the field log agrees with it: every reception the
client-side window would have held off came from a node heard for minutes at a time.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
The 2026-09-12 commute answered the question v1.15's instrumentation was built to ask.
No floor. The ranges came back overlapping — answered snr -5.25 … +12 dB, silent -11 …
-0.75 dB — and two of the three answers came from asks at snr -5.25 / rssi -117 and snr
-1.75 / rssi -113. Any floor worth setting would have blocked them. The earlier reading
that looked like a clean split was drawn from the old scheduler, where silent asks were
timer asks whose signal I took from a reception minutes earlier: the number was standing
in for freshness, not for link quality, and once every ask fired on a live reception the
correlation vanished.
What the same log did show: efef79435050 spent its three asks between 21:06:50 and
21:08:08, all around -115 dBm and all unanswered, and was then heard from 21:09:37 at
-76 to -69 dBm — up to 46 dB stronger, the best receptions of the drive — with nothing
left to spend, because the encounter only ends after five minutes of silence and it kept
coming in loud. So a reception at least 6 dB better in snr than the best one this
encounter already asked on now earns exactly one extra ask, once per encounter.
The per-encounter allowance also goes 3 -> 4, as asked.
Both of those need the firmware's limiter to stop being an approximation: at most 4 asks
to one repeater in any 180s, which is what simple_repeater accepts across every
requester and type. Enforced directly now, ageing on its own clock so an encounter reset
does not clear it, and deliberately not configurable. Note it mostly does not come up on
the road — 180 seconds is about 3 km, by which time the repeater is out of range — and
the field log bears that out: the receptions it would have held off all came from nodes
heard for minutes at a time.
One interaction worth knowing: four asks 30s apart fills the 180s window, so a target
that spends the full allowance cannot take its bonus until the oldest ask ages out,
roughly half a minute. regionMaxAsks: 3 in config.json leaves that slot free instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
The v1.15.1 cleanup deleted a contiguous block of the dead ask path, and that block had
one function in the middle of it that belongs to neither path and is called on every
connect: the replay of a contact-path restore left behind by a session that died between
forcing a contact to zero-hop and putting it back. Restored unchanged.
v1.15.1's check — load the built page in a browser — proved the module initialised,
which was v1.15.0's fault, but it never reached the connect path: that sits behind a Web
Bluetooth pairing a desktop browser with no companion cannot complete. The check that
does catch this compares every top-level definition against the last known-good release
and looks for surviving references to each removed name. Run against v1.14.0 it now
reports none for all eleven definitions dropped since.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
The app painted its shell, opened on Home instead of Settings, and no button or
navigation tab responded.
Removing the old scheduler left one line behind that read a constant no longer
imported: `const OVERRIDE_ROUND_TIMEOUT_MS = PENDING_TIMEOUT_MS` (app.js:359). Being
module-level, evaluating app.js raised a ReferenceError before the view switch and
before a single event listener was attached — the HTML rendered and nothing worked.
Deleted with it, for the same reason it was found: the rest of the old ask path, left in
place and no longer reachable. prepareAndAskRegions, askRegions, finishOverrideRound and
restoreContact all referenced removed imports or the removed pending slot; askRepeater
already does that work inline. disconnectAll also still nulled state.regions.pending; it
now clears the outstanding-tag map and the queue, which is what actually has to happen —
no reply can arrive over a transport that is gone, and a tag from one session must never
match a request from the next.
Why the checks passed: rollup reports a missing export as a warning, not an error; the
suite covers the pure modules and never evaluates app.js; and I did not load the
production bundle in a browser before releasing, though I had loaded every beta build.
This release was verified by serving dist/ and opening it: the version line is painted
by app.js, so seeing it at all is the proof the module initialised.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
The scheduler had three limits and four drives showed each one costing answers rather
than protecting anything. All three are gone; what replaces them is bounded by the
repeater firmware's own limiter instead of by a clock of our own invention.
The shared one-ask-per-60s airtime budget. One ask, from wherever, blocked every
repeater heard in the following minute. The 2026-09-11 80 km log has a2cf63b9fd89 asked
at 18:24:55 on rssi -120 and silent, then heard at 18:25:26 on -102 — 18 dB stronger —
and skipped, because the budget had gone on the weaker reception 31 seconds earlier and
that same ask had put it into backoff.
The 5/15/30-minute per-target backoff, counted per session. A repeater asked once from a
bad spot was locked out for the rest of the drive. It is replaced by an encounter: three
unanswered asks at least 30s apart, then left alone until it has been out of earshot for
five minutes, after which the next reception is a new encounter with a fresh run. Three
asks 30s apart is 3 in any 180s window, inside simple_repeater's 4 anon requests per
180s shared across all requesters — the cap is what keeps us there, not the spacing.
The single in-flight slot. It capped the feature at three asks a minute, and at one per
session whenever a request went unanswered. Several requests can now be outstanding, so
replies are attributed on the 4-byte tag the companion echoes back and an unmatched
reply is dropped rather than guessed at: "something is pending" would file one
repeater's declared regions under another and store it as fact.
Measured, not assumed. A build without the three limits sent 15 asks and got 6 answers;
v1.14.0 on a comparable run sent 5 and got 1. That build is the one merged here (the
beta/regions-sprint commits below), with the pacing tightened from 15s/6 asks to
30s/3 asks so one repeater sees strictly less than the firmware allows one client.
Also here: every ask now carries the snr and rssi of the reception that triggered it,
into the reply or into the timeout. Four drives point at a split — every ask at snr
+1.75 dB or better was answered, every one at -1.25 dB or worse was not — that until now
had to be assembled by hand from pairs of log lines the ring buffer rolls out mid-drive.
No signal floor is applied; this is the measurement that would justify one.
Deleted rather than left behind: selectNextTarget's successors (heardAskDecision,
commitAsk, undoAsk, isTargetDue, dueDelayMs, retryBackoffFor, recordCandidate,
applyRegionsReply, pendingExpired) and monitor's regionDiscoverDue/REGION_INTERVAL_MS.
regionreq.js is framing only now; regionsched.js owns the scheduling.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
Three drives have now pointed at the same split — every region reply came from a
reception at roughly -109 dBm or better, every ask at -111 or worse stayed silent — and
every time it had to be assembled by hand from pairs of log lines, on a sample of ten,
from a ring buffer that rolls those lines out mid-drive. That is not a measurement yet.
An ask now carries the snr and rssi of the reception that triggered it, through the
outstanding map and into whatever comes back. A reply files them under answered; a tag
that times out files them under silent, which is the half that was never recorded at
all. pruneOutstanding returns the dropped records instead of a count for that reason.
The header states both ranges:
beta sig answered asks 7: rssi -109 … -78dBm, snr 1.75 … 12.25dB | silent asks 12: …
They argue for a signal floor only if they do not overlap. If they do overlap, the idea
is dead and one drive says so, which is the same amount of evidence either way.
Per-ask and per-reply lines carry the same two numbers, so a spot check in the visible
part of the buffer does not depend on the header.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
The first field run read "6 of 15 repeaters answered, 15 asks sent". Both 15s are the
same counter — successful enqueues — so the row invited exactly the wrong reading, that
15 distinct repeaters were seen and each was asked once. Neither half was measurable
from it.
Three denominators now stated separately: repeaters SEEN (distinct nodes, from the
per-target map), asks SENT (transmissions), and receptions (how often those nodes were
heard at all). The ratio that decides this experiment is answered over seen; asks over
answered is what it costs.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
Two gaps in the first cut, both raised from the field side.
"Until it answers" never ends. A repeater held in range that does not reply was asked
again on every reception for the rest of the session, which is a poll, not a
measurement. An encounter now gets betaMaxAsks unanswered asks (6) and then stops. What
reopens it is silence: after betaForgetMin (5) without hearing that node, the next
reception is a NEW encounter and the count starts clean, because the same repeater met
40 km later is a different distance and a different antenna aspect, and the failures of
the last meeting say nothing about this one. An answer still ends it permanently, and no
encounter reopens that.
The encounter is ended by silence rather than by elapsed time, so a node heard steadily
for ten minutes stays one meeting instead of being handed a fresh run halfway through.
Second, the 2s queue interval was the wrong knob to state as the rate, and it was
hardcoded. There are two distinct limits and they now live in config.json, editable on
the server between drives with no rebuild:
betaAskGapSec 2 between ANY two transmitted asks; stops rounds overlapping
betaTargetGapSec 15 between two asks to the SAME repeater; this is the rate that
matters for a node parked in range, heard many times a minute
betaMaxAsks 6 unanswered asks per encounter
betaForgetMin 5 silence that starts a new encounter
A value that is missing or unusable (string, negative, NaN) takes the default rather
than disabling the limit it configures: on a transmitting path a typo must not read as
"no limit".
enqueue now returns WHY it said no ('answered' / 'queued' / 'capped' / 'too-soon')
instead of a bare false, the per-ask log line carries "attempt N of M this encounter",
and the header gained a row counting receptions ignored because the repeater had used
its asks. Without that count a capped node and a node that stopped transmitting look
identical in the log.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
An experiment, not a proposed default. Built for rx.on8ar.eu/beta and compiled in only
by `REGION_BETA=1 vite build`; a normal build folds the flag to false and drops every
branch, which the prod bundle confirms (none of the beta strings survive it).
The premise under test, in the requester's words: a moving receiver goes from node to
node, so a repeater is never asked often enough to block its own TX window. So this
path removes all three throttles at once — the shared one-ask-per-60s airtime budget,
the 5/15/30-minute per-target backoff, and the single in-flight slot.
Procedure it implements: a reception of a repeater resolves to a full pubkey (advert
carries one; discover and path-hash prefixes go through the CoreScope resolve endpoint
the app already uses for names), the target is queued, and the queue drains one ask per
2s. A repeater is taken out of rotation only by answering. A target already queued is
not queued twice, so the ask rate is the RECEPTION rate rather than a 2s clock; 2s is a
floor between transmissions, not a generator.
Dropping the single in-flight slot breaks the reply matcher: applyRegionsReply resolves
one pending request, and with several outstanding, "something is pending" would file one
repeater's regions under another. matchOutstanding keys on the 4-byte tag the companion
echoes in its RESP_CODE_SENT ack, an unmatched reply is dropped rather than guessed at,
and tags older than 120s are pruned so the map cannot grow without bound.
Kept deliberately: the contact-path override (a saved contact with a stale out_path is
FLOODed and repeaters ignore flooded requests), and its 20s restore hold. Whether
restoring earlier costs the reply is a firmware question, and this experiment is not
the place to answer it, so a round that needs an override blocks the queue for 20s.
Overrides were needed twice in three field logs.
What the field log will have to show, since the per-ask lines roll out of the 200-line
buffer: two new header rows carry repeaters answered over repeaters seen, asks sent
over replies, and the queue/outstanding/timed-out/unmatched/FLOOD counters.
Not addressed here: simple_repeater rate-limits anon requests to 4 per 180s shared
across all requesters and all types, so a repeater held in range for minutes will start
dropping these. That is part of what the measurement is for.
No service worker in this build: it is served from a subdirectory of the production
origin, and registering '/sw.js' from there would claim the root scope and serve the
experiment to the production URL.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
Twelve minutes of the 2026-09-11 v1.13.0 log: six region requests, one answer. The one
that was answered fired on a live reception and came back in two seconds. The other five
each charged their target an attempt and dropped it into the 5/15/30-minute backoff, so
e3d3f4d7edd0 (heard directly at 12:04:54 and 12:09:32) and 6b8c65b77cf3 (12:03:53,
12:08:02, 12:10:05) could not be asked while they were demonstrably in range.
Two separate causes, both in the ask bookkeeping rather than in the framing or the reply
matcher, and each fixed at its own site.
The 60s timer fallback is removed. selectNextTarget picked from the whole session pool
with no notion of range, which at road speed is a repeater already passed: 12:04:37 to
e470a7fd67fa, last heard 5m45s earlier, and 12:05:38 to 01fa326b4758 are the two clean
examples in the log, neither answered. Since 52b7ff5 those asks also stamp the shared
one-ask-per-60s airtime budget, so a blind ask blocked the heard path for the following
minute as well as backing its target off. maybeAskHeardTarget is now the whole
scheduler, and selectNextTarget, demoted and cursor go with the fallback they served.
A BLE write that throws now costs nothing. commitAndAsk charged attempts, lastAskedAt
and the airtime budget before the write, and askRegions only logged the rejection, so a
request that never reached the radio held the pending slot for its full 20s and then
printed "no reply ... within 20s" — indistinguishable from a repeater that heard us and
stayed silent. Two of the six asks were this: 12:00:00 and 12:02:36, both immediately
after "BLE: reconnecting". commitAsk now returns a receipt and undoAsk restores it,
refusing once the send-ack has captured a tag (that request IS on the air) or once
another target holds the slot. prepareAndAskRegions gained a try/catch for the same
reason: state.transport is nulled on disconnect and askRegions dereferences it, which
rejected unobserved and wedged the slot until it timed out.
Removing the timer removes the only line that narrated the scheduler once a minute, so
heardAskDecision reports why it said no (in flight, budget, answered, backoff, with the
remaining wait) and the heard path logs that at most once a minute. Those four states
were previously indistinguishable from each other and from silence.
Known trade-off, stated in the release notes: the stationary pause stops the discover
sweep, so a parked app now depends on organic traffic to raise a candidate. A repeater
in range that transmits nothing while you are parked next to it is no longer asked.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HSoyBhrLLtSqLgBMEKMiJV
A 'rxlog' attribution only happens on a FLOOD route, where path[last] IS the
node that transmitted to us — one radio hop away, which is exactly the direct
neighbour relation a regions request needs. Those receptions were never
candidates. The stated reason was that the packet carries no pubkey to address,
but that is not the obstacle: the discover path has the same gap and closes it
with a CoreScope lookup, and the app already sends these same prefixes to that
endpoint to resolve names. So forwarders now resolve to a full pubkey and become
candidates like any other repeater.
This fills a real hole rather than adding volume. isOrganicHeard backs the
discover sweep off for 15s after any organic reception, so in busy areas — where
forwarder traffic is densest — the sweep is suppressed and yields the FEWEST
discover-sourced candidates exactly where there is the most to hear.
Node type is unknown for a path hash, which is accepted rather than ignored: a
node appears in a path only because it RETRANSMITTED the packet, and companions
and sensors do not forward, so this population is repeaters and possibly room
servers. A non-answerer costs one ask and is then held off by the existing
5/15/30-minute backoff, the same as a repeater that stays silent. No airtime is
added either way — both paths share the one-ask-per-60s budget.
Whether a 2-byte prefix resolves uniquely often enough to be worth it is a
measurement, not a guess, and the app puts the companion in 2-byte path-hash
mode itself, so this is the least favourable case. The log header now carries
"path keys: N of M path-hash prefixes resolved to a pubkey (K ambiguous or
unknown)". It lives in the header because the 200-line ring buffer rolls
per-prefix lines out long before a drive ends, and it counts DISTINCT prefixes:
resolvePubkey is called on every reception from a forwarder and answers from its
session cache, so counting calls would report the busiest node many times over
and say nothing about how many forwarders could be identified.
Adding a third writer to the candidate map exposed a pre-existing bug worth
naming. The map value is the answered-key isTargetDue compares against, and
advert-sourced candidates carry a real advertTs while discover- and
forwarder-sourced ones carry null. A plain set(pk, null) overwrote a known
timestamp, so answered.get(t) !== advertTs for a repeater that HAD answered: it
read as due and was asked again for nothing. That already applied to the
discover path; a third writer would have tripled it. recordCandidate never
downgrades a known timestamp, and returns the EFFECTIVE key so the call site
cannot hand a stale null to the ask decision — which was the same bug by a
second route. A changed timestamp still overwrites; a re-advert is the
documented signal to ask again.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
state.regions.pending is the single in-flight slot, and it was released in only
three places: a FLOOD send-ack, an accepted reply, and disconnect. None of those
is the ordinary outcome for a moving receiver — a request sent DIRECT to a
repeater we have already driven past is simply never answered, and that left the
slot occupied for the rest of the session.
heardAskEligible gates on that slot, so the first unanswered ask disabled the
event-driven path entirely. What remained was the 60s timer picking a candidate
from the whole session pool — exactly the clock-chosen, minute-late ask the
module header says cannot work at speed. A 23-minute commute log shows ~19
repeaters heard, every ask landing on the timer cadence, not one
"heard ... directly" line, and a single reply.
A pending request now carries sentAt and expires after PENDING_TIMEOUT_MS,
swept by the one-second tick rather than a setTimeout — this app is routinely
backgrounded mid-drive, where a timer fires late or not at all. A pending
without a sentAt counts as expired: a wedged slot costs a whole session, an
early expiry costs one ask that the airtime budget already bounds.
Two invariants the timer path documented but never enforced, unnoticed only
because the wedged slot meant the heard path never ran:
- The shared 60s airtime budget is now stamped in commitAndAsk, the one site
that transmits, so it counts asks from both paths. It was stamped only in
maybeAskHeardTarget, so timer asks spent airtime for free.
- The timer no longer asks over a live request. Doing so overwrote pending.tag
and applyRegionsReply then rejected the real reply as a tag mismatch, so the
fallback path was destroying the answers this feature exists to collect.
OVERRIDE_ROUND_TIMEOUT_MS now derives from the same constant: once the contact
path override is torn down no reply can arrive, so pending must not outlive it.
Also fixes the log line that hid this. "every repeater heard so far has already
answered" was printed whenever the pool came up empty, including when every
candidate was merely waiting out its retry backoff — it read as a finished job
while one repeater of nineteen had answered.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
An Advert's Ed25519 signature is the only cryptographic proof of identity MeshCore
offers. Everything else is plaintext and attacker-chosen: pubkey, name and self-reported
position are whatever the sender wrote, and hop counts, paths and prefixes carry no MAC.
The capture rule in this repo covers provenance, not authenticity, so a 0-hop advert can
be genuinely heard direct and still name a node that does not exist. Adverts captured
here are published to CoreScope, the registry the name resolvers read from, so one
forgery heard by one driver becomes a named node on someone else's screen.
parsePacket now returns advertSig: the pubkey, the signature and the exact message the
firmware signs, which is pubkey(32) || timestamp(4, LE) || app_data with app_data
truncated to MAX_ADVERT_DATA_SIZE (meshcore-firmware src/Mesh.cpp:271-280 verifies what
:404-437 signed, cap at src/MeshCore.h:12). The timestamp goes in as the raw wire bytes,
not the parsed advertTs, so no re-encoding can disagree with what was received. Getting
the 32-byte cap wrong would make every long advert look forged, so the fixture test
covers it, and the real captured advert already in the fixtures verifies against its own
signature, which is what proves the construction rather than asserting it.
src/advertsig.js does the crypto and nothing else. Verification is async: @noble/ed25519
needs a hash and only the async path has one without extra wiring. The capture handler
was already async. A forged advert can carry a pubkey or signature that is not a valid
curve point, which noble rejects by throwing, so that is caught and read as a failed
verification rather than taking the capture path down.
A failed check drops the identity and keeps the reception. The SNR and RSSI measured at
that position are real whoever wrote the advert; only the name attached to them is
worthless, and discarding the row would lose genuine coverage. This is deliberately
narrower than core-hunter, which refuses the whole reception (efiten/core-hunter#356),
because that repo is about identity and this one is about coverage. As a side effect the
node stops being a region-discovery candidate, so the app never sends an anonymous
request to an address somebody invented.
verifyAdverts is off unless config.json says otherwise, and is listed false in
FEATURE_DEFAULTS as well as NO_CONFIG_DEFAULTS. It is the only flag that makes the app
record less than it heard, and inheriting that silently would look like adverts going
missing. The exported log header reports it next to the other three, because "no advert
in the capture" and "advert rejected" are otherwise the same silence.
Not done: no Settings UI for the flag, config.json only, matching the other three. The
gate is not exercised against a forged advert on real hardware, only against fixtures
and a signed synthetic advert.
New dependency: @noble/ed25519 3.2.0. Bundle 435.17 kB -> 442.78 kB (gzip 136.22 ->
139.71).
Tests: 255 pass (+16). SW cache v39 -> v40.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Manrn3qdrTJFz3C4o9PPFL
A v1.11.2 field log shows the app started at 09:45:34 and picked up again at
17:02:25, on a phone that had slept in between. The CONNACK at 17:02:26 and
"CoreScope error: Keepalive timeout" carry the same timestamp, and every reconnect
after it repeated that pair at the 4s reconnectPeriod for three minutes with 20
records left pending. Restarting the app cleared it; the log taken a minute later
is clean.
mqtt.js defaults to timerVariant 'auto', which in a browser runs the keepalive
interval through worker-timers: the page passes performance.timeOrigin +
performance.now() to a Worker that compares it against its own clock
(worker-timers-worker/build/es2019/factories/set-timer.js). That Worker is created
lazily, on the first connect (worker-timers/build/es2019/module.js), so it takes
its time origin from the wall clock at that moment, while the page's
performance.now() does not advance while an Android device sleeps. The Worker was
handed a "now" hours in the past, every tick was already overdue, it fired three
back to back, and KeepaliveManager's counter passed 2 within milliseconds of the
CONNACK (node_modules/mqtt/build/lib/KeepaliveManager.js). mqtt.js arms a fresh
manager on every CONNACK, so each reconnect walked into the same skew, and the
Worker is a module singleton, so retiring the Publisher and building a new client
would not have helped either. Only a page reload, which resets timeOrigin, ended
it, which is what the field report says.
timerVariant 'native' keeps the interval in one clock domain, where that skew
cannot arise. Background throttling of a native timer costs at most one keepalive
timeout, and the ordinary reconnect recovers from that.
The connect options moved into Publisher.connectOptions() so they can be asserted
without opening a socket.
Not verified on a device: the mechanism is read off the field log plus the mqtt.js
5.15.1 and worker-timers sources, not reproduced in a browser.
Tests: 239 pass (+2). SW cache v38 -> v39.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Manrn3qdrTJFz3C4o9PPFL
A clean v1.11.1 field log drained the 59-record backlog four seconds after
connecting - then logged "published 49 record(s)" one second later, for a queue
that had held 59. 59 - 49 = 10 = COMMIT_EVERY, which pins the mechanism exactly.
drain() had no mutual exclusion and four uncoordinated callers: the 5s drainLoop,
the broker 'connect' event, the 'online' event and the "Push pending now" button.
Two overlapping passes each call queue.takeAll(), so both see and both PUBLISH the
rows the other has not committed yet. Here the second pass started just after the
first committed its opening batch of 10, found the other 49 still queued, and
delivered every one of them to the ingestor a second time.
The hole predates the incremental-commit change - the old all-or-nothing drain
could double-publish just as easily - but batching the commits is what made it
visible and measurable in a log.
serialiseDrain() now holds one in-flight pass; a caller arriving mid-pass joins it
rather than starting its own. Joining rather than queueing a follow-up is
deliberate: the second caller wants the outcome, and anything queued after the
running pass took its snapshot is picked up by the next 5s tick. The slot is
released on rejection too, so a failed pass cannot wedge every future drain.
Otherwise that log is healthy and confirms the v1.11.1 fixes: the 59 buffered
records went out in one pass, and the new instrumentation shows publisher #1 alone
with connack rc=0, no retired-publisher events and no keepalive timeouts - the
4-second reconnect loop is gone.
Tests: 237 pass (+3). SW cache v37 -> v38.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A field log showed 59 records buffered and not one published, with ~18
"Keepalive timeout" errors against a single successful CONNACK. Probing the broker
from a fixed line ruled out the obvious causes: publishes to /packets, /rf and
/regions were all PUBACKed in ~85ms with returnCode=0 and no disconnect, and a
deliberate same-clientId takeover makes the victim report a bare 'close', never a
keepalive error. So neither the ACL nor session contention was involved.
What was: two defects that together made a flaky mobile link unrecoverable and
undiagnosable.
1. drain() discarded its own progress. It collected published ids and called
queue.remove ONCE after the loop, so a single rejecting publish threw and every
record the broker had already acknowledged stayed queued to be sent again.
Publishes are sequential, so a 59-record backlog needs ~5s of continuous link at
86ms round-trip and ~18s at 300ms - on a link that stayed up about a second at a
time, the design could never commit anything at all. The loop now lives in
src/drain.js with two invariants under test: a record is removed if and only if
the broker acked it, and one unpublishable record can never block the records
behind it. A link drop is charged to the link, not to the record, so repeated
drops cannot quarantine a good reception.
2. Every Publisher ever created reported into one module-level handler writing one
global brokerState, so an orphaned client's endless 4s reconnect loop overwrote
a healthy connection's state and filled the log with failures nothing could
attribute. Each Publisher now carries an id; events from a retired one are named
once and then ignored. startPublisher no longer ADOPTS a disconnected publisher
(which made connectAll print "CoreScope connected" over a looping client) - it
retires it, which also stops that loop.
Also: keepalive is now set explicitly and quoted in the log next to the CONNACK
return code. mqtt.js arms its keepalive manager only inside _onConnect and only if
one does not already exist (client.js:1101), never re-arming an existing one, so a
surviving manager can report a bogus timeout on a healthy link. That error is now
evidence instead of a red herring.
Tests: 234 pass (+14). SW cache v36 -> v37.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Completes the default-on change. The transmitting feature's default now depends on
WHERE the silence comes from, which is the distinction that makes it safe:
- an absent key in a config.json that EXISTS -> on. That file is a deployment whose
operator owns the repeaters being asked, and this is exactly the case that bit us:
a config predating the key silently reported the feature off.
- no config loaded at all -> off. The app then knows nothing about whose mesh it is
on, and repeaters rate-limit anonymous requests to 4 per 180s shared across every
requester and type, so one client asking once a minute claims most of that budget.
Collecting on an assumption spends our own bandwidth; transmitting on one spends a
stranger's airtime.
FEATURE_DEFAULTS / NO_CONFIG_DEFAULTS make that split explicit, and every
regionDiscovery gate in app.js now goes through featureEnabled() so "which default
applies" has exactly one answer, in config.js. Those gates read
`!cfg || !cfg.regionDiscovery`, which happened to be equivalent for a normalized
config but restated the policy in five places.
Tests: 220 pass.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Goal: never lose a window of coverage data to a config problem. Data that was
never collected is gone for good; data collected and discarded server-side costs
only bandwidth.
Two separate changes, because they cover two different failures:
- normalizeConfig: an ABSENT fullRfLog/rfSampler key now means on. A config.json
written before those keys existed reported both off while the served file said
on - indistinguishable from the features being broken. An explicit `false`
still wins.
- featureEnabled(cfg, name): resolves a flag when there is NO config at all. Every
gate read `!cfg || !cfg.X`, i.e. "we do not know yet" == "off", so a failed
config fetch stopped data collection on top of stopping uploads. The app now
keeps capturing on defaults and the queue publishes once config arrives.
regionDiscovery deliberately still defaults to false. It is the only feature that
transmits, against third-party repeaters that rate-limit anonymous requests to 4
per 180s shared across every requester and type - one client asking once a minute
already claims most of that budget. Spending someone else's airtime on an
assumption is not a default.
The exported log header now names the defaults in force when no config loaded, so
a reader can tell what is in the queued records without guessing.
Documented in the README together with the two standing warnings that make this a
real trade: fullRfLog multiplies upload volume and is discarded unless the
ingestor has clientRxObservations.enabled, and an rfSampler publish denied by the
broker ACL is still PUBACKed, so it looks healthy while the server stores nothing.
config.example.json updated to match the new defaults.
Tests: 220 pass (+3).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two field logs traced to one root cause: config.json is fetched exactly once at
DOMContentLoaded and never retried, so a single transient failure at startup left
getConfig() returning null (or a stale cached copy) for the rest of the session.
Log A: no config at all. connectAll took its else branch, never built a Publisher,
and then reported "All connected - capturing" anyway. An hour of receptions queued
and nothing published. The Push button answered "nothing pending / not connected"
because drain() returns 0 for a null publisher exactly as it does for an empty
queue - and its reconnect branch was guarded on `publisher && !connected()`, which
skipped the one case needing recovery. The only message naming the cause went to
els('status'), which the next connect cleared with log('').
Log B: a config.json cached before rfSampler/regionDiscovery existed. Absent flags
normalize to false, so both features were dead while the served config said on -
publishing worked, everything looked green, and nothing reported it. A stale config
is worse than none: none is detectable, stale is not.
- sw.js: config.json bypasses the cache in both directions, and the
caches.match('/') fallback is limited to navigations. Serving index.html for a
JSON request is what turned an offline start into "invalid JSON: Unexpected
token '<'".
- config.js: loadConfig dedupes concurrent attempts, caches only on success so a
retry actually re-fetches, and names an HTML body instead of leaking a parse error.
- uplink.js (new, pure): uplinkState / uplinkWarning / pushOutcome /
regionInertReason / buildLogHeader.
- app.js: retries the config on every connect, on `online`, and once a minute while
missing; startPublisher() split out so a late config brings uploading up without
reconnecting; a red Home banner while receptions are buffered but not uploaded;
the progress list no longer claims an uplink it does not have; pushNow reports
queue depth independently of link health and picks the matching repair.
- Region discovery names which of its four gates is holding it, once, in the log -
"no regions lines" was consistent with all four and distinguished none. Its
re-entry throttle is now stamped before the gates instead of after.
- Every exported log carries a header with app version, EFFECTIVE config flags,
firmware version, region-discovery status, uplink state and queue depth. Both
field logs arrived unattributable to a version; the header is built at share time
so it cannot roll out of the 200-line ring buffer the way a startup line does.
Tests: 217 pass (+41). sw.js is driven in a node:vm ServiceWorkerGlobalScope so the
shipped file is tested, not a copy of its logic.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two corrections, both in comments, no behaviour change.
The re-ask rule was documented as "advertTs tracks the node's own re-advert clock
so selectNextTarget re-asks after a config edit". That is wrong: Mesh.cpp:418
sets the advert timestamp to getCurrentTime() on every advert, so it moves every
advert interval — 47h in this network — whether or not anything changed. The
repeater owner pointed this out; a comment that misstates a protocol fact is
worse than none, because the next reader builds on it.
What advertTs actually is here is an answered-key, giving "ask each repeater once
per session". That policy stays: it costs roughly 19 requests against the ~180
the discover sweep already sends in the same drive, and it keeps every stored
list demonstrably current rather than assumed.
The real config-change signal is recorded alongside for whoever wants it:
_prefs.discovery_mod_timestamp, set on `regions save` (CommonCLI.cpp:1037) and
filterable through the discover request's optional `since` field
(simple_repeater/MyMesh.cpp:791-798) — the repeater then answers only if it
changed since that time.
Also removes three literal NUL bytes that a shell heredoc left inside a comment
in the previous commit, which made git treat the file as binary. The built bundle
was unaffected (comments are stripped), but the source was not text.
The ANON_REQ reply payload is encrypted with a block cipher
(Utils::encryptThenMAC -> AES), so the plaintext arrives NUL-padded to a 16-byte
boundary, and the firmware's own length is not carried through to us. We stored
the padding verbatim.
Measured in production: 48 of 65 stored rows carry it. The padding lands inside
the LAST region name, so "belml" is stored as "belml\0\0\0..." — which matches no
observed scope and therefore reads as a region the repeater declares but never
forwards. A systematic false finding, on the last entry of nearly every list.
A wildcard-only answer is the worst shape: 0x2A plus seven NULs is exactly one
block, so even `regions_csv = '*'` compares false in SQL, and the audit can miss
the wildcard entirely and report a contradiction that is not there.
Trim before splitting. Padding is also excluded from the truncation measure — it
is not part of the repeater's answer and must not count toward the byte ceiling.
The timer path stamped lastAskAt on every evaluation, including ones that
transmitted nothing. That spent the one-per-60s budget on no-ops and then
blocked the heard-packet path, which is the whole point of the previous commit.
Field log, stationary receiver:
14:29:08 regions: due this round but no candidate to ask yet <- stamped
14:29:27 heard efef7943505052b4 (8B, discover) <- blocked
14:30:09 regions -> asked efef79435050... <- 42s late
14:30:10 regions <- efef79435050... declares: *,eu,bx,be,...
Stationary it only costs 42 seconds. Moving at 50 km/h it is most of a
kilometre, and this request is answered only zero-hop DIRECT.
Split the two clocks: lastEvalAt throttles the timer path's re-entry and its log
line to once a minute; lastAskAt is the airtime budget and is stamped only where
something is actually sent.
Also make the idle message honest — "no candidate to ask yet" read as "nobody
heard" when the real state was usually "everyone heard has already answered".
Region discovery only works zero-hop DIRECT, and the receiver is
moving, so a clock-driven ask (picking from every repeater heard this
session) systematically asked repeaters least likely to still be in
range. Fire the ask when a suitable repeater is heard instead of on a
timer, without increasing airtime: the timer path stays as a fallback
for a candidate heard once and not heard again, and both paths share
state.regions.lastAskAt so the existing one-ask-per-60s ceiling holds
regardless of which fires.
heardAskEligible (src/regionreq.js) is the pure per-target decision
(budget free, no ask pending, target due per isTargetDue — extracted
from selectNextTarget so both paths use the identical due() rule).
Round-robin fairness now emerges from hearing different repeaters at
different moments plus the existing per-target backoff; no second
fairness mechanism was added on top.
Field log showed nine asks to one node in nine minutes. Demotion alone does not
prevent that: it moves a silent target behind the answering ones, but once every
OTHER candidate has answered they are no longer due, selectNextTarget's pool
falls back to "every due candidate", and the silent one is handed straight back
each round.
That is worse than wasted airtime. simple_repeater rate-limits anon requests to
4 per 180s SHARED across all request types and all requesters (MyMesh.cpp:861),
so hammering a node burns the very budget its answer would need — asking more
often makes an answer less likely, not more.
Per-target backoff: 5 min after the first unanswered ask, then 15, then 30 and
held there. It still retries, because silence is ambiguous (out of direct range,
firmware below v13, rate-limited, or simply busy) and dropping a target forever
would lose one that was merely out of range for a stretch.
Region discovery rode the discover clock, and discoverDecision short-circuits on
`paused`, so a parked app never asked a single repeater. That is the wrong
coupling: the pause exists because re-sampling the same spot adds nothing to
coverage or RF data, but a repeater's declared region list is a property of that
repeater, not of where we are standing — and the repeaters that matter most are
often the ones you are parked next to.
Give it its own 60s clock (the same rate the old round-parity scheme produced, so
airtime is unchanged) evaluated independently of dec.fire.
Stamp that clock on every evaluation rather than only on a successful ask: the
tick asks once a second, so an evaluation that finds no candidate would otherwise
re-enter — and re-log "no candidate" — every second instead of every minute.
Field context this came from: the log showed asks stopping dead at "stationary —
capture/upload paused". Separately, a repeater can also stay silent because
simple_repeater rate-limits anon requests to 4 per 180s shared across all types
and all requesters (MyMesh.cpp:861), which is why the busiest node in the mesh
answers least often. Retrying is the only remedy for that, and this change is
what makes retrying possible while parked.
Repeaters only answer ANON_REQ_TYPE_REGIONS over a direct route
(simple_repeater/MyMesh.cpp requires isRouteDirect()), but sendAnonReq
(BaseChatMesh.cpp) sends over whatever out_path is stored for a contact,
which for a repeater already saved as a contact can be a stale multi-hop
path even when node-discover just confirmed it's zero-hop reachable now.
Before asking such a target, read its contact record (CMD_GET_CONTACT_BY_KEY),
override out_path_len to 0 (CMD_ADD_UPDATE_CONTACT), ask, then restore the
original record — all invisible to the user. The original frame is persisted
to localStorage before the override write and replayed on the next connect
to the same companion if the app dies or the BLE link drops mid-dance.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A repeater answers ANON_REQ_TYPE_REGIONS only over a DIRECT route
(simple_repeater/MyMesh.cpp requires isRouteDirect()) and drops a flooded one
without any error. The companion chooses the route, not us: sendAnonReq
(BaseChatMesh.cpp:619) floods whenever the target is a known contact whose
out_path_len is OUT_PATH_UNKNOWN, and only sends direct for a non-contact, where
CMD_SEND_ANON_REQ builds a transient contact with out_path_len = 0.
So asking a repeater already saved as a contact is a guaranteed no-op — which is
what the field log shows: the send succeeds, the ack arrives, and nothing ever
comes back.
The ack already carries the answer and we were discarding it
(companion_radio/MyMesh.cpp:1569: out_frame[1] = SENT_FLOOD ? 1 : 0). Read it,
clear the pending slot instead of waiting out a reply that cannot arrive, and
log it. This does not make the request succeed; it makes a permanent silent
failure legible instead of looking like a repeater that just has not replied yet.
Web Bluetooth allows exactly one GATT operation in flight. Region discovery
rides the discover clock at half rate, so its request was issued in the SAME
tick as the zero-hop discover it follows, and every single region round lost the
race:
[20:49:53] regions request failed: GATT operation already in progress.
[20:49:53] regions → asked efef79435050… for its declared list
[20:49:53] discover → zero-hop node-discover req (all types)
That is deterministic, not flaky — the one answer on record got through only
because it landed on a round where the discover write had already settled.
Serialise in the transport rather than making each call site coordinate: a
promise chain per connection, where each caller still sees its own write's
outcome while the chain itself swallows, so one failure cannot poison every
later send. The covering test issues two sends in one tick and asserts the
characteristic never sees two writes in flight; it fails against the old
unserialised send.
Also log the ask only once the write has gone out — printing "asked" beside
"failed" for the same attempt read as a request that was made and then broke,
rather than one that was never sent.
Firmware, simple_repeater/MyMesh.cpp:562-571: a TRANSPORT_FLOOD is matched
against a named region by code1, while a plain ROUTE_TYPE_FLOOD — a packet
carrying no transport scope at all — is governed solely by the region tree's
root, whose name is '*'. So '*' answers "do I forward unscoped floods?", which
is a different question from any region name.
Shown inside the comma-separated list it read as just another scope. Split it
out into a small "+ unscoped" marker, and base declaresNothing on the scoped
regions alone — a repeater declaring only '*' declares no regions yet does
forward plain floods, and those are two facts, not one.
Adds a new card at the bottom of Home listing the 5 most-recently
answered repeaters from region discovery, most recent first, hidden
until there is at least one answer. Both real answer shapes are shown
distinctly: a repeater that declared regions lists them; one that
declared an empty list says so explicitly ("declares nothing
flood-allowed") rather than rendering blank, since that is a genuine
answer, not an absence of one. A truncated reply is marked, since a
missing region there is not necessarily a real absence.
- src/regionsview.js (new): pure regionsRows(answers) transform —
last 5, most-recent-first, declaresNothing/truncated flags. Name
resolution is a network call and stays out of this module.
- src/app.js: noteRegionsAnswer stores each accepted reply
(onRegionsFrame) and resolves its name once via the existing
names.js session cache (no extra network call per render);
renderRegionsCard does the DOM write.
- index.html: new #regionsCard card following the existing .card +
<label> pattern; .stats font-size 28px->24px and tighter
.statusstrip/.discstatus margins to make room, without touching the
shared .card padding or dropping any of the four top-card figures.
- public/sw.js: CACHE bumped v24 -> v25 (frontend files changed).
Tests: src/regionsview.js covered directly in
test/regionsview.test.mjs (empty input, >5 answers, <5 answers,
declares-regions vs declares-nothing, truncated flag, name pass-
through). app.js has no test harness in this codebase and is not
covered — wiring verified by a clean `vite build` and manual read.
Every repeater on this network has a 47h advert interval, so real
adverts are almost never heard and the region-discovery candidate map
stayed empty — selectNextTarget always returned null and no region
request was ever sent (five discover rounds, zero region requests in
the field log).
Node-discover responses are what actually arrives constantly, but they
carry only an 8-byte pubkey prefix and no advert timestamp/type. Fixes:
- meshpacket.js: parsePacket now also extracts discoverType (low
nibble of the DISCOVER_RESP flags byte, per
simple_repeater/MyMesh.cpp:801) alongside the existing discoverPubkey.
Purely additive — deriveHeardKey is untouched and its pinned tests
stay green unmodified.
- names.js: add resolvePubkey, a sibling of resolveName that resolves
a prefix to the full 32-byte pubkey via the same endpoint and cache
discipline (network errors never cached; a full 64-hex key needs no
request).
- app.js: accept hk.src === 'discover' candidates when discoverType is
ADV_TYPE_REPEATER, resolved to the full pubkey so a repeater never
keys twice under prefix and pubkey. advertTs is stored null;
selectNextTarget's existing due() rule already asks it once per
session and re-asks automatically once a real advert arrives.
- app.js: maybeQueryRegions now logs the half-rate rounds where a
region request was due but no candidate existed yet — this bug was
previously silent.
The 139-byte threshold is derived from the firmware's byte budget, but it was
compared against csv.length, which counts UTF-16 code units. RegionMap's
is_name_char accepts every byte >= 0x80, so accented region names are legal and
cost more bytes than code units — meaning a CSV at or past the boundary could
decode to fewer than 139 units and store truncated: false as fact. That is the
same under-flagging the threshold fix was written to close.
Export TRUNCATION_WARN_BYTES so the tests assert against the constant instead of
a copy; the stale 160 in an existing assertion is what let this drift unnoticed.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- Truncation threshold was 160 bytes, missing any dropped name longer
than 9 chars (be-antwerpen, be-limburg are real names on this
network). Derived the correct floor from RegionMap.cpp/MyMesh.cpp:
the delivered CSV can be as short as 139 bytes while still hiding a
dropped 30-char name, once the trailing-comma trim is accounted for.
- A DEVICE_INFO failure on connect left "Region discovery: on" showing
while state.regions.supported stayed false — now the catch path
writes an honest "off — could not read firmware version" line.
- onRegionsFrame's queue.add() was a fire-and-forget promise in a sync
BLE listener; added the same .catch() pattern used elsewhere.
- maybeQueryRegions committed scheduler state (cursor/demoted/pending)
before building the request frame, so a throw from
buildRegionsRequest would leave the scheduler out of sync with what
was actually sent. Build the frame first.
- Documented regionDiscovery in the README config sample (was only in
config.example.json), matching the fullRfLog/rfSampler warning shape.
- Bumped the sw.js cache version for the frontend changes above.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kind: 'regions' records queued by Task 2 had no route: they fell through
to buildPayload, which reads rx_at/raw/snr/rssi (all undefined on a
regions record), publishing a raw-less PACKET to the coverage topic and
then discarding the record as delivered. Add buildRegionsPayload beside
the existing builders (buildPayload is left untouched — it's the
coverage-topic contract) and extend topicFor/payloadFor with a third
kind: 'regions' branch to meshcore/client/{pubkey}/regions.
No drop-filter: drain() publishes every queued record generically via
topicFor/payloadFor, so this closes the gap by routing, not filtering.
A record with no kind at all (pre-existing queue entries) still hits the
default branch untouched. An empty regions array and truncated: false
both round-trip as-is (JSON.stringify only drops undefined, never [] or
false).
sw.js cache buster: v21 -> v22 (src/publisher.js changed).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
- Guard askRegions' cleanup() against state.transport being null: disconnecting
inside the 4s send-ack window nulls the transport but disconnectAll has no
reference to the pending timer/listener, so the timeout callback threw.
- Reset state.regions.supported = false before each requestDeviceInfo query
(not just after it succeeds): if the query throws, a stale `true` from a
prior connection must not carry over -- an unverified device would otherwise
receive a region request that its (unverified) firmware may silently ignore,
spending this feature's one airtime-costing action for nothing. Also write
the Settings regionsInfo line in both the supported and unsupported branches,
so reconnecting to a v13+ device after a v12 one doesn't leave a stale
"off -- firmware v12" line on screen while the feature is actually live.
- Split the reply-mismatch debug log into two messages: "ack not captured yet"
(pending.tag === null, an expected transient state) versus "actual tag
mismatch" (a stray/late reply from an abandoned round) -- conflating them
hid a real distinction from the field debug log.
public/sw.js CACHE v20 -> v21 (src/app.js changed again).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A stray/late PUSH_CODE_BINARY_RESPONSE (the repeater rate-limits and replies
after a delay; a different repeater is asked every 60s) was being accepted as
an answer for whichever target happened to be pending -- attributing one
repeater's declared regions to a different repeater and storing it as an
authoritative observation. The protocol carries a tag precisely to prevent
this (sendAnonReq generates it, the repeater echoes it, parseRegionsResponse
already parsed it out) but nothing compared it.
- src/regionreq.js: RESP_CODE_SENT (verified companion_radio/MyMesh.cpp:77),
parseSentAck (the [tag] ack for CMD_SEND_ANON_REQ, verified MyMesh.cpp
:1568-1572), and applyRegionsReply -- a pure state-transition that accepts
a reply only when its tag matches the pending request's captured tag, and
otherwise returns accepted:false without mutating `pending` so the real
reply can still arrive and be matched afterward.
- src/app.js: maybeQueryRegions now seeds pending with tag:null; askRegions
sends the request and listens for the RESP_CODE_SENT ack to fill it in
(4s timeout, target-checked against a stale/superseded round); onRegionsFrame
now goes through applyRegionsReply and only clears/records on accepted:true,
logging a mismatch at the 'no' debug level otherwise.
- public/sw.js: CACHE v19 -> v20 (the v19 bump in the prior commit predates
this change to app.js/regionreq.js).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Ask exactly one repeater per region-discovery round (half the 30s discover
cadence, so once a minute) for its declared flood-allowed region list, and
compare it later against what CoreScope observes it actually forward.
- src/regionreq.js: selectNextTarget(state) -> pubkey|null, pure round-robin
selection with demotion for non-answerers (never dropped, since silence is
ambiguous: out of range, rate-limited, old firmware, or busy).
- src/meshpacket.js: parsePacket now also returns advertTs (the node's own
re-advert clock, so a repeater is re-asked only after a config edit) and
advertType (ADV_TYPE_*, so only ADV_TYPE_REPEATER nodes are ever asked --
only simple_repeater firmware implements the reply).
- src/app.js: wiring only. Candidates are 0-hop adverts (full pubkey, direct
RF range) from repeaters; maybeQueryRegions() rides the discover clock at
half rate and sends at most one buildRegionsRequest per round, logged at
the tx (orange) level; onRegionsFrame is a dedicated listener fed the RAW
notification (never parseFrame(...).data, which strips the code byte and
would silently break parseRegionsResponse's bytes[0] check).
- Feature gate: FIRMWARE_VER_CODE >= 13 (CMD_SEND_ANON_REQ's non-contact
allowance), read via the existing requestDeviceInfo() call at connect;
when regionDiscovery is configured on but the firmware is too old, the
feature stays off and Settings shows why.
- config.regionDiscovery defaults to false (config.js, config.example.json).
- index.html: regionsInfo status line in Settings/Diagnostics.
- sw.js: cache buster v18 -> v19 (frontend files changed).
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
frames.js declared its own copy of RESP_CODE_STATS = 24, but nothing
imports it — rfstats.js has the copy parseStats actually uses. Delete
the dead one so there is exactly one definition of this wire constant.
publisher.js's header named only the /packets topic, understating the
module's contract now that it also publishes RF samples on /rf.
README's config.json section never documented rfSampler at all (it
exists in public/config.example.json and config.js). Add it alongside
fullRfLog, and warn that mqtt.js negotiates MQTT 3.1.1 — whose PUBACK
carries no reason code — so a broker ACL denying the /rf subtopic
still lets the app log "published N record(s)" while the server
receives zero rows.
tick() awaits state.queue.add(sample) mid-cycle. If disconnectAll()
runs during that await, stopRfSampler() clears a timer that has
already fired, and the resumed tick then reschedules itself at the
end regardless. If the user reconnects inside that window,
startRfSampler() overwrites state.rfTimer with its new session's
timer, but the stale tick's later reschedule clobbers it again,
leaving a second concurrent tick loop running against its own
closure's orphaned `pending` map.
Each RF sampler session now bumps state.rfGen; a tick only
reschedules itself if the generation it captured at start is still
current, so a superseded tick dies quietly after finishing (and
queuing) whatever sample it was mid-flight on.
No test added: app.js exports nothing and wires DOM/BLE listeners
directly at import time (window.addEventListener('DOMContentLoaded',
...), document.getElementById via els()), with no existing
app.test.mjs or DOM/BLE mocking harness in this repo. Standing up
that infrastructure for this one seam would be a larger change than
the fix itself.
Bump sw.js CACHE per repo convention for any frontend file change.
Publisher.topicFor/payloadFor dispatch on rec.kind so the drain loop
can publish both reception records (no kind, /packets, unchanged
buildPayload) and RF environment samples (kind: 'rf', /rf,
buildRfPayload/type RF_SAMPLE) without dropping either. recv_errors
is only included on the RF payload when present on the record, never
defaulted, so its absence still means "unknown" downstream.
Bumps the sw.js cache version since src/publisher.js changed.