From 77f16755e77edfa576f2daf6ca732e8ebdf93345 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:17:51 -0500 Subject: [PATCH 01/16] feat(#1068): radio per-channel notify contract, caps bit, caps byte 3, tests Epic A of #544, plus the B1 contract it needed to fail behaviourally rather than as a compile error. Owner directive: app and radio notifications are separate controls, separate notifications, independent settings. So this adds a RADIO-side per-channel mode and touches the app's per-channel setting not at all. - offband_channel_notify.dart: 0x18 GET / 0x19 SET, RadioChannelNotify with the 1-based encoding (0 unset, 1 all, 2 mentions, 3 off), frame builders, and a parser that DROPS an unknown mode byte rather than guessing - offbandCap2ChannelNotify = 0x80, the last bit in caps byte 2 - parseOffbandCaps3 at device-info offset 87, length-gated, never version-gated (#1065). 87 and not 85: 85 is ui_led_enabled and 86 is ui_display_mode, so reading 85 would parse the LED state as a caps mask - connector: per-radio slot-to-mode state cleared in _clearDeviceUiState, request/set shaped on requestChannelTune/setChannelTune so state follows the device's re-read reply and never the request, reply handler, and DeviceUiSurface.channelNotify for refusals 15 tests across three groups. The A2 independence group is the load-bearing one: changing the app mode emits no radio frame, a radio reply saying Off does not mute the phone, and the app setting still works on a radio with no capability at all. That is what stops the two being quietly re-merged later. Proved the checks can fail: flipping the caps-3 offset to 85 fails three tests, including the one asserting the LED and display bytes are not mistaken for byte 3. Reverted. The radio control itself is Epic C; this pane explicitly does not own a channelNotify refusal, recorded at the switch rather than left implicit. Blocked downstream, recorded on #1069: B3's read-on-connect should hang off #1061's confirmed-list barrier, and the slot-to-mode cache belongs in #1061's PSK identity-diff reset set. flutter analyze clean; full suite 1804 passed. --- lib/connector/meshcore_connector.dart | 110 +++++++ lib/connector/meshcore_protocol.dart | 30 ++ lib/connector/offband_channel_notify.dart | 98 +++++++ lib/connector/offband_device_ui.dart | 4 + lib/screens/settings/device_ui_view.dart | 6 + .../channel_notify_connector_test.dart | 272 ++++++++++++++++++ 6 files changed, 520 insertions(+) create mode 100644 lib/connector/offband_channel_notify.dart create mode 100644 test/connector/channel_notify_connector_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 454f00a6..38289a74 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -66,6 +66,7 @@ import 'device_population.dart'; import 'meshcore_protocol.dart'; import '../helpers/region_key.dart'; import '../storage/channel_region_scope_store.dart'; +import 'offband_channel_notify.dart'; import 'offband_device_ui.dart'; import 'offband_screen_settings.dart'; import 'offband_tones.dart'; @@ -419,6 +420,7 @@ class MeshCoreConnector extends ChangeNotifier { Classification? _classification; int? _offbandCaps2; + int? _offbandCaps3; bool? _femLnaEnabled; ButtonMatrix? _buttonMatrix; String? _lastDeviceUiSuppression; @@ -428,6 +430,12 @@ class MeshCoreConnector extends ChangeNotifier { DeviceUiSurface? _pendingDeviceUiWrite; GpsModeState? _gpsModeState; final Map _channelTunes = {}; + + /// Slot index to the radio's own notify mode for that channel (#544). + /// Written only from a device reply, and cleared per radio like every other + /// device-UI surface. Slot-derived state: #1061's identity diff must reset + /// it when a slot's PSK changes, or it describes the wrong channel. + final Map _channelNotifyModes = {}; final Map _eventTones = {}; final Map _tuneSlots = {}; ScreenSettingsState? _screenSettings; @@ -936,6 +944,17 @@ class MeshCoreConnector extends ChangeNotifier { /// an error: every radio predating #508 reports null here. (#480) int? get offbandCaps2 => _offbandCaps2; + /// Third `offband_caps` bitfield (frame offset 87, #544). Null when the frame + /// is too short, which means "no byte-3 capabilities" and is never an error. + /// No bit is allocated from it yet; byte 2 filled up at `0x80`. + int? get offbandCaps3 => _offbandCaps3; + + /// Whether this radio stores a per-channel notify mode for its own buzzer + /// (#544). Says nothing about the app's per-channel notify setting, which is + /// independent and needs no radio. + bool get supportsChannelNotify => + firmwareSupportsChannelNotify(_offbandCaps2); + /// Whether this radio exposes a configurable button-action matrix (#474). bool get supportsButtonMatrix => firmwareSupportsButtonMatrix(_offbandCaps2); @@ -960,6 +979,12 @@ class MeshCoreConnector extends ChangeNotifier { /// The tune the radio reported for [channel], or null if not read yet. ChannelTune? channelTuneFor(int channel) => _channelTunes[channel]; + /// The radio's notify mode for [channel], or null until the radio has + /// reported it. Null is "not yet known", distinct from + /// [RadioChannelNotify.unset], which is the radio saying no choice is set. + RadioChannelNotify? channelNotifyFor(int channel) => + _channelNotifyModes[channel]; + /// The tune the radio reported for [event], or null if not read yet. EventToneState? eventTone(ToneEvent event) => _eventTones[event]; @@ -1147,6 +1172,39 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildChannelTuneSetFrame(channel, tune)); } + /// Ask the radio which notify mode [channel] has for its own buzzer (#544). + /// + /// Nothing here touches the app's per-channel notify setting: that drives + /// the phone, this drives the radio, and they are independent. + Future requestChannelNotify(int channel) async { + if (!_deviceUiGateOpen('chnotify GET', advertised: supportsChannelNotify)) { + return; + } + _appDebugLogService?.info( + 'chnotify GET -> [0xC5][0x18][$channel]', + tag: 'DeviceUI', + ); + await sendFrame(buildChannelNotifyGetFrame(channel)); + } + + /// Set the radio's notify mode for [channel]. Local state follows the + /// device's re-read reply, never the request, so a refused choice is never + /// shown as saved. + Future setChannelNotify(int channel, RadioChannelNotify mode) async { + if (!_deviceUiGateOpen('chnotify SET', advertised: supportsChannelNotify)) { + return; + } + _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.channelNotify; + _appDebugLogService?.info( + 'chnotify SET -> ch=$channel mode=${mode.name} ' + 'stored=${mode.stored} [0xC5][0x19]', + tag: 'DeviceUI', + ); + await sendFrame(buildChannelNotifySetFrame(channel, mode)); + } + /// Ask the radio how GPS is running (#969). Future requestGpsMode() async { if (!_deviceUiGateOpen('gps GET', advertised: supportsGpsMode)) return; @@ -1487,6 +1545,7 @@ class MeshCoreConnector extends ChangeNotifier { _buttonMatrix = null; _lastDeviceUiSuppression = null; _deviceNotifyScope = null; + _channelNotifyModes.clear(); _deviceUiError = null; _deviceUiErrorSurface = null; _pendingDeviceUiWrite = null; @@ -1532,6 +1591,14 @@ class MeshCoreConnector extends ChangeNotifier { _handleChannelTuneReply(tune); return; } + final chNotify = parseChannelNotifyReply(frame); + if (chNotify != null) { + _handleChannelNotifyReply( + chNotify, + isWrite: frame[1] == offbandUiChannelNotifySet, + ); + return; + } final tunes = parseTuneReply(frame); if (tunes != null) { _handleTuneReply(tunes); @@ -1570,6 +1637,7 @@ class MeshCoreConnector extends ChangeNotifier { DeviceUiSurface.tunePlay => 'Tune preview', DeviceUiSurface.tuneSlot => 'Tune slot', DeviceUiSurface.screenSettings => 'Screen settings', + DeviceUiSurface.channelNotify => 'Radio channel notifications', null => 'Device UI request', }; _appDebugLogService?.warn( @@ -1624,6 +1692,27 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// The radio reported its own notify mode for one channel (#544). + /// + /// This writes the RADIO's state only. It deliberately does not read or + /// write the app's per-channel notify setting: the two are independent, and + /// a test asserts that a reply here leaves the app store untouched. + void _handleChannelNotifyReply( + RadioChannelNotifyReply reply, { + required bool isWrite, + }) { + if (isWrite && _pendingDeviceUiWrite == DeviceUiSurface.channelNotify) { + _pendingDeviceUiWrite = null; + } + _channelNotifyModes[reply.channel] = reply.mode; + _appDebugLogService?.info( + 'chnotify reply: ch=${reply.channel} mode=${reply.mode.name} ' + '(${isWrite ? 'write confirmed' : 'read'})', + tag: 'DeviceUI', + ); + notifyListeners(); + } + void _handleChannelTuneReply(OffbandUiReply reply) { final t = reply.channelTune; if (t == null) { @@ -4402,6 +4491,7 @@ class MeshCoreConnector extends ChangeNotifier { // until the next device-info lands (Gemini review, task #876). _offbandCaps = null; _offbandCaps2 = null; + _offbandCaps3 = null; _femLnaEnabled = null; _blockListRetryTimer?.cancel(); // Per-connection debounce timers must die with the connection so a timer @@ -7878,6 +7968,22 @@ class MeshCoreConnector extends ChangeNotifier { static int? parseOffbandCaps2(Uint8List frame) => frame.length >= 85 ? frame[84] : null; + /// Third `offband_caps` byte, at frame offset **87** (#544). + /// + /// Byte 2 filled up when the per-channel notify bit took `0x80`, so firmware + /// appends a third. It sits at 87 and NOT at 85, because 85 and 86 are + /// already `ui_led_enabled` and `ui_display_mode`: the same fixed-absolute + /// offset rule that put byte 2 at 84 rather than beside byte 1. Reading 85 + /// as byte 3 would parse the LED state as a capability bitmask. + /// + /// Null on any firmware sending a shorter frame, which means "no byte-3 + /// capabilities" and is never an error. Length-gated, never version-gated + /// (#1065). No bit is allocated from it yet. + static int? parseOffbandCaps3(Uint8List frame) => + frame.length >= offbandCaps3MinFrameLength + ? frame[offbandCaps3Offset] + : null; + void _handleDeviceInfo(Uint8List frame) { if (frame.length < 4) return; if (_shouldGateInitialChannelSync) { @@ -7947,10 +8053,14 @@ class MeshCoreConnector extends ChangeNotifier { _femLnaEnabled = parseFemLnaState(frame); // Second caps byte rides at offset 84, past the FEM state byte (#480). _offbandCaps2 = parseOffbandCaps2(frame); + // Third caps byte at offset 87, past ui_led_enabled (85) and + // ui_display_mode (86). Byte 2 filled up at 0x80 (#544). + _offbandCaps3 = parseOffbandCaps3(frame); } else { _offbandCaps = null; _femLnaEnabled = null; _offbandCaps2 = null; + _offbandCaps3 = null; } // Capability-gated features are invisible when a bit is clear, which looks // identical to a bug. Log the raw inputs so "the toggle didn't appear" can diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index ceedb35c..dd5d1fba 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -649,6 +649,28 @@ const int offbandCap2GpsMode = 0x20; /// (#987): text sizes, Screen off, time zone, battery full point. const int offbandCap2ScreenSettings = 0x40; +/// Per-channel RADIO notify mode over `0xC5` 0x18 / 0x19 (#544, +/// meshcore-firmware#606). Firmware sets it where `PIN_BUZZER` is defined, so +/// it is a per-unit answer: gate on the BIT, never on model or version. +/// +/// This is the LAST bit in caps byte 2. The change that spends it adds caps +/// **byte 3** at device-info offset 87 ([parseOffbandCaps3Offset]); anything +/// after this takes a bit from there. +const int offbandCap2ChannelNotify = 0x80; + +/// Device-info offset of `offband_caps` BYTE 3, and the minimum frame length +/// that carries it. +/// +/// **87, not 85.** Firmware writes caps byte 2 at 84, then `ui_led_enabled` at +/// 85 and `ui_display_mode` at 86 (`MyMesh.cpp` device-info builder). Reading +/// byte 3 at 85 would parse the LED state as a capability bitmask, which is +/// the exact mistake firmware's own comment warns about for byte 2. +/// +/// Length-gated, never version-gated (#1065): absence means no byte-3 +/// capabilities, and is never an error. +const int offbandCaps3Offset = 87; +const int offbandCaps3MinFrameLength = 88; + /// True iff this radio answers the `0xC5` tune sub-codes. bool firmwareSupportsTunes(int? offbandCaps2) => offbandCaps2 != null && (offbandCaps2 & offbandCap2Tunes) != 0; @@ -661,6 +683,14 @@ bool firmwareSupportsScreenSettings(int? offbandCaps2) => bool firmwareSupportsGpsMode(int? offbandCaps2) => offbandCaps2 != null && (offbandCaps2 & offbandCap2GpsMode) != 0; +/// True iff this radio stores a per-channel notify mode and answers the +/// `0xC5` 0x18 / 0x19 sub-codes (#544). +/// +/// Says nothing about the app's own per-channel notify setting, which needs no +/// radio and is never gated on this. +bool firmwareSupportsChannelNotify(int? offbandCaps2) => + offbandCaps2 != null && (offbandCaps2 & offbandCap2ChannelNotify) != 0; + bool firmwareSupportsOffbandCaplog(int? offbandCaps) => offbandCaps != null && (offbandCaps & offbandCapCaplog) != 0; diff --git a/lib/connector/offband_channel_notify.dart b/lib/connector/offband_channel_notify.dart new file mode 100644 index 00000000..6a7174e6 --- /dev/null +++ b/lib/connector/offband_channel_notify.dart @@ -0,0 +1,98 @@ +import 'dart:typed_data'; + +import 'offband_device_ui.dart'; + +/// Per-channel notification mode stored on the RADIO, over `0xC5` 0x18 / 0x19 +/// (#544, meshcore-firmware#606). +/// +/// This governs the RADIO's buzzer and nothing else. It is deliberately +/// independent of the app's own per-channel `ChannelNotifyMode`, which governs +/// whether the PHONE notifies: two settings, two outputs, no bridging between +/// them (owner, 2026-11-03: "they are separate controls and separate +/// notifications... they are independent settings"). Never resolve one from +/// the other, and never offer an "inherit the app setting" value here. +/// +/// Firmware is the authority and there is no firmware inherit concept: the +/// owner's ruling was "Inherit is on the client side, not on the firmware +/// side. How would firmware inherit from firmware?". [unset] is simply the +/// absence of a per-channel choice, and the radio's own device-wide scope +/// answers for that channel instead. +const int offbandUiChannelNotifyGet = 0x18; +const int offbandUiChannelNotifySet = 0x19; + +/// A channel's radio notify mode, as the radio stores it. +/// +/// The byte is **1-based** and 0 means "no choice made", because the value +/// lives in a field that reads zero on every existing record and every fresh +/// channel. If 0 meant a real mode, every untouched channel in the field would +/// silently adopt it. The shipped `ChannelTune` byte uses the same convention +/// for the same reason, so the two are consistent on the wire. +enum RadioChannelNotify { + /// No per-channel choice: the radio's device-wide scope answers instead. + unset(0x00), + + /// Beep for any message on this channel. + all(0x01), + + /// Beep only when the message names us, by the `@[name]` rule. + mentions(0x02), + + /// Never beep for this channel. + off(0x03); + + const RadioChannelNotify(this.stored); + + /// The wire byte. Never built by hand. + final int stored; + + static RadioChannelNotify? fromStored(int stored) { + for (final m in RadioChannelNotify.values) { + if (m.stored == stored) return m; + } + return null; + } +} + +/// One channel's radio notify mode, as a `0xC5` 0x18 or 0x19 reply reports it. +class RadioChannelNotifyReply { + const RadioChannelNotifyReply({required this.channel, required this.mode}); + final int channel; + final RadioChannelNotify mode; +} + +int _channelByte(int channel) { + if (channel < 0 || channel > 0xFF) { + throw ArgumentError.value(channel, 'channel', 'must be 0 to 255'); + } + return channel; +} + +Uint8List buildChannelNotifyGetFrame(int channel) => Uint8List.fromList([ + cmdOffbandDeviceUi, + offbandUiChannelNotifyGet, + _channelByte(channel), +]); + +Uint8List buildChannelNotifySetFrame(int channel, RadioChannelNotify mode) => + Uint8List.fromList([ + cmdOffbandDeviceUi, + offbandUiChannelNotifySet, + _channelByte(channel), + mode.stored, + ]); + +/// Parse a `0xC5` channel-notify reply (0x18 or 0x19). Null when this is not +/// one, when it is short, or when the mode byte is not a value we know: an +/// unrecognized mode is dropped rather than guessed at, so a firmware that +/// grows a fourth mode cannot have it read as one of ours. +RadioChannelNotifyReply? parseChannelNotifyReply(List frame) { + if (frame.length < 4) return null; + if (frame[0] != respCodeOffbandDeviceUi) return null; + if (frame[1] != offbandUiChannelNotifyGet && + frame[1] != offbandUiChannelNotifySet) { + return null; + } + final mode = RadioChannelNotify.fromStored(frame[3]); + if (mode == null) return null; + return RadioChannelNotifyReply(channel: frame[2], mode: mode); +} diff --git a/lib/connector/offband_device_ui.dart b/lib/connector/offband_device_ui.dart index 8a5ba6bb..2e889d7d 100644 --- a/lib/connector/offband_device_ui.dart +++ b/lib/connector/offband_device_ui.dart @@ -130,6 +130,10 @@ enum DeviceUiSurface { tunePlay, tuneSlot, screenSettings, + + /// The radio's own per-channel notify mode (#544). Distinct from the app's + /// per-channel notify setting, which is not a device-UI surface at all. + channelNotify, } /// The refusal reason for a GPS write. Reason 1 means Power save on a build diff --git a/lib/screens/settings/device_ui_view.dart b/lib/screens/settings/device_ui_view.dart index c0a8d016..9497bc9a 100644 --- a/lib/screens/settings/device_ui_view.dart +++ b/lib/screens/settings/device_ui_view.dart @@ -66,6 +66,12 @@ class _DeviceUiViewState extends State { DeviceUiSurface.tunePlay || DeviceUiSurface.tuneSlot => widget.part == DeviceUiPart.buzzer, DeviceUiSurface.gpsMode || DeviceUiSurface.screenSettings => false, + // The radio's per-channel notify control lives beside the app's own + // per-channel control on the Channels screen, not in this pane (#544 + // Epic C), so a refusal for it is not this screen's to show. Epic C1 + // surfaces it there; until then nothing on this pane can emit it, because + // nothing here writes it. + DeviceUiSurface.channelNotify => false, }; @override diff --git a/test/connector/channel_notify_connector_test.dart b/test/connector/channel_notify_connector_test.dart new file mode 100644 index 00000000..34a7da7d --- /dev/null +++ b/test/connector/channel_notify_connector_test.dart @@ -0,0 +1,272 @@ +// #544 Epic A (#1068): the red baseline for the RADIO's per-channel notify +// mode over 0xC5 0x18 / 0x19. +// +// The feature this pins is that there are TWO independent settings: the app's +// per-channel mode drives the PHONE, the radio's drives the BUZZER, and +// neither moves the other (owner, 2026-11-03). The independence group below is +// the load-bearing part -- it is what stops the two being quietly re-merged by +// a later change. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/offband_channel_notify.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// RESP_CODE_DEVICE_INFO from an Offband radio (fork length, dual version so +/// the population classifier corroborates it). Caps byte 2 at offset 84; +/// pass [length] 88 with [caps3] to carry a third caps byte at offset 87. +Uint8List deviceInfo({ + required int caps2, + int length = 85, + int caps3 = 0, + int ledByte = 0, + int displayByte = 0, +}) { + final v = ascii.encode('1.5.0-1.17.0'); + final f = Uint8List(length); + f[0] = 13; + f[1] = 22; + f.setRange(60, 60 + v.length, v); + if (length >= 85) f[84] = caps2; + if (length >= 86) f[85] = ledByte; + if (length >= 87) f[86] = displayByte; + if (length >= 88) f[87] = caps3; + return f; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List> sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + sent = []; + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (data) => sent.add(data.toList()); + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + bool sentChannelNotify() => sent.any( + (f) => + f.length >= 2 && + f[0] == cmdOffbandDeviceUi && + (f[1] == offbandUiChannelNotifyGet || + f[1] == offbandUiChannelNotifySet), + ); + + // ---- A1: the radio's modes ------------------------------------------------ + + group('A1 radio channel notify', () { + test('the wire bytes are the documented ones', () async { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + sent.clear(); + + await connector.requestChannelNotify(2); + await connector.setChannelNotify(2, RadioChannelNotify.mentions); + + expect( + sent, + equals([ + [0xC5, 0x18, 0x02], + [0xC5, 0x19, 0x02, 0x02], + ]), + ); + }); + + test('a reply sets that slot, and only that slot', () { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x02]); + + expect(connector.channelNotifyFor(1), RadioChannelNotify.mentions); + expect(connector.channelNotifyFor(0), isNull); + expect(connector.channelNotifyFor(2), isNull); + }); + + test('mode 0 is unset, and is distinct from Off', () { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + connector.handleFrameForTest([0xC5, 0x18, 0x00, 0x00]); + connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]); + + expect(connector.channelNotifyFor(0), RadioChannelNotify.unset); + expect(connector.channelNotifyFor(1), RadioChannelNotify.off); + }); + + test('a write is not shown until the radio confirms it', () async { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await connector.setChannelNotify(3, RadioChannelNotify.off); + + expect(connector.channelNotifyFor(3), isNull); + + connector.handleFrameForTest([0xC5, 0x19, 0x03, 0x03]); + expect(connector.channelNotifyFor(3), RadioChannelNotify.off); + }); + + test('an unknown mode byte is dropped, never guessed at', () { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + connector.handleFrameForTest([0xC5, 0x18, 0x04, 0x09]); + + expect(connector.channelNotifyFor(4), isNull); + expect(parseChannelNotifyReply([0xC5, 0x18, 0x04, 0x09]), isNull); + }); + + test('state does not survive a change of radio', () { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x01]); + expect(connector.channelNotifyFor(1), RadioChannelNotify.all); + + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + expect(connector.channelNotifyFor(1), isNull); + }); + }); + + // ---- A2: the two settings are independent --------------------------------- + + group('A2 independence of app and radio settings', () { + test('changing the app mode emits no radio frame', () async { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + sent.clear(); + + final settings = AppSettingsService(); + await settings.loadSettings(); + await settings.setChannelNotifyMode( + devicePrefix: 'aabbccddee', + pskHex: '00112233445566778899aabbccddeeff', + channelName: 'skywarn', + mode: ChannelNotifyMode.off, + ); + + expect(sentChannelNotify(), isFalse); + expect(sent, isEmpty); + }); + + test('a radio reply does not touch the app store', () async { + final settings = AppSettingsService(); + await settings.loadSettings(); + const prefix = 'aabbccddee'; + const psk = '00112233445566778899aabbccddeeff'; + await settings.setChannelNotifyMode( + devicePrefix: prefix, + pskHex: psk, + channelName: 'skywarn', + mode: ChannelNotifyMode.all, + ); + + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + connector.handleFrameForTest([0xC5, 0x18, 0x00, 0x03]); + + expect( + settings.channelNotifyMode(devicePrefix: prefix, pskHex: psk), + ChannelNotifyMode.all, + reason: 'the radio saying Off must not mute the phone', + ); + }); + + test('the app setting works with no radio capability at all', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + final settings = AppSettingsService(); + await settings.loadSettings(); + const prefix = 'aabbccddee'; + const psk = '00112233445566778899aabbccddeeff'; + + await settings.setChannelNotifyMode( + devicePrefix: prefix, + pskHex: psk, + channelName: 'skywarn', + mode: ChannelNotifyMode.mentionsOnly, + ); + + expect(connector.supportsChannelNotify, isFalse); + expect( + settings.channelNotifyMode(devicePrefix: prefix, pskHex: psk), + ChannelNotifyMode.mentionsOnly, + ); + }); + }); + + // ---- A3: capability and caps byte 3 --------------------------------------- + + group('A3 capability gating and caps byte 3', () { + test('without 0x80 no channel-notify frame is ever emitted', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x40)); + await connector.requestChannelNotify(0); + await connector.setChannelNotify(0, RadioChannelNotify.off); + + expect(connector.supportsChannelNotify, isFalse); + expect(sentChannelNotify(), isFalse); + }); + + test('0x80 is the bit, and other bits do not open it', () { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + expect(connector.supportsChannelNotify, isTrue); + + connector.handleFrameForTest(deviceInfo(caps2: 0x7F)); + expect(connector.supportsChannelNotify, isFalse); + }); + + test('caps byte 3 reads offset 87', () { + connector.handleFrameForTest( + deviceInfo(caps2: 0x80, length: 88, caps3: 0x05), + ); + expect(connector.offbandCaps3, 0x05); + }); + + test('caps byte 3 is null on any shorter frame', () { + for (final n in [85, 86, 87]) { + connector.handleFrameForTest(deviceInfo(caps2: 0x80, length: n)); + expect( + connector.offbandCaps3, + isNull, + reason: 'a $n-byte frame carries no byte 3', + ); + } + }); + + test('85 and 86 are not mistaken for byte 3', () { + // Those offsets are ui_led_enabled and ui_display_mode. Reading either + // as a capability mask is the failure this pins. + connector.handleFrameForTest( + deviceInfo( + caps2: 0x80, + length: 88, + ledByte: 0xAA, + displayByte: 0xBB, + caps3: 0x01, + ), + ); + expect(connector.offbandCaps3, 0x01); + expect(connector.offbandCaps3, isNot(0xAA)); + expect(connector.offbandCaps3, isNot(0xBB)); + }); + + test('a stock-shaped radio exposes nothing, whatever its bytes', () { + final stock = Uint8List(82); + stock[0] = 13; + stock[1] = 14; + connector.handleFrameForTest(stock); + + expect(connector.supportsChannelNotify, isFalse); + expect(connector.offbandCaps3, isNull); + }); + }); +} From 46255f1ef400450da7dcdb7541772d41cbdcc6fb Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:18:35 -0500 Subject: [PATCH 02/16] fix(#1063): keep per-slot message state from crossing channel identities Persisted channel history has been PSK-keyed since #194; the remnants that could still cross-wire on a slot reassignment were in-memory and legacy. Epic B of #1061, stacked on #1062: - _completeChannelSync's identity diff now drops the slot's in-memory conversation and reloads it from the store, which reads the NEW identity's own history through the (now fail-closed) resolver. - setChannel's reassignment clear purges only the LEGACY slot-index keys (new clearLegacySlotHistory), so the outgoing occupant's PSK-keyed history survives and comes back if the channel is re-added. True deletes (deleteChannel) keep the full both-key clear. - A WRITE that falls back to the slot-index key now logs an error with the orphaning consequence spelled out; post-#1062 live ingress cannot reach it. - The #193-era comment claiming history is slot-keyed is corrected and the setChannel/resolver interplay documented. Tests: 2 connector tests (in-memory drop on identity change, kept on same identity) + 5 store tests (legacy purge, PSK history survival, no adoption onto the new occupant, true delete). Issue: #1063 Co-Authored-By: Claude Fable 5 --- lib/connector/meshcore_connector.dart | 25 +++- lib/storage/channel_message_store.dart | 79 ++++++++--- test/connector/channel_sync_truth_test.dart | 61 +++++++++ .../channel_message_store_identity_test.dart | 128 ++++++++++++++++++ 4 files changed, 267 insertions(+), 26 deletions(-) create mode 100644 test/storage/channel_message_store_identity_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 0341a480..7f554189 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -6414,6 +6414,13 @@ class MeshCoreConnector extends ChangeNotifier { '"${prior.name}" -> "${fresh.name}"', tag: 'ChannelSync', ); + // #1063: the in-memory conversation is the one per-slot message store + // left (persisted history is PSK-keyed, #194). Drop the old occupant's + // messages so they cannot render under the new channel, then reload + // this slot from the store; the resolver now sees the fresh list, so + // the load reads the NEW identity's own history. + _channelMessages.remove(fresh.index); + unawaited(_loadChannelMessages(fresh.index)); } } @@ -6574,19 +6581,23 @@ class MeshCoreConnector extends ChangeNotifier { Future setChannel(int index, String name, Uint8List psk) async { if (!isConnected) return; - // Channel history is stored keyed by the reusable slot [index], not by the - // channel's PSK. If this slot is being (re)assigned to a different channel - // than the one whose history is stored here, clear the stale history so a - // previous occupant's messages (e.g. #echo) don't surface under the newly - // added channel. Preserve only when the slot already holds the SAME channel - // (same PSK), e.g. a rename. (#193) + // Persisted channel history is keyed by the channel's PSK identity (#194), + // so reassigning this slot to a different channel cannot surface the old + // occupant's messages THERE. Two slot-keyed remnants still can, and both + // are handled when the slot changes occupant (different PSK): + // - legacy slot-index keys (pre-#194) would be adopted onto the new + // occupant by the store's one-time migration; purge them (#193/#1063). + // - the in-memory conversation map is slot-keyed; drop this slot's entry. + // The old occupant's PSK-keyed history is deliberately left intact: if + // that channel is ever re-added (any slot), its history comes back + // (#1063). A rename (same PSK) keeps everything. final existing = _findChannelByIndex(index); final sameChannel = existing != null && listEquals(existing.psk, psk); await sendFrame(buildSetChannelFrame(index, name, psk)); if (!sameChannel) { - await _channelMessageStore.clearChannelMessages(index); + await _channelMessageStore.clearLegacySlotHistory(index); _channelMessages.remove(index); } diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 9c5bd445..adc5b5be 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -126,23 +126,45 @@ class ChannelMessageStore { /// Active storage key: PSK identity when known, else the slot index. /// - /// The index fallback is legitimate before a channel list has loaded, but it - /// reads a DIFFERENT key: if history was already migrated to the PSK key, the - /// caller gets an empty list that is indistinguishable from data loss. - /// SAFELANE 6 - this must never be silent. Falling back where a resolver - /// exists means the channel list was not ready, which is the #333 race. - String _storageKey(int channelIndex) { + /// The index fallback is legitimate on a READ before a channel list has + /// loaded, but it reads a DIFFERENT key: if history was already migrated to + /// the PSK key, the caller gets an empty list that is indistinguishable from + /// data loss. SAFELANE 6 - this must never be silent. Falling back where a + /// resolver exists means the channel list was not ready, which is the #333 + /// race. + /// + /// A WRITE must never land on the index fallback: the one-time adoption in + /// [loadChannelMessages] only runs while the PSK key is EMPTY, so a message + /// written to the index key of a channel that already has PSK-keyed history + /// is orphaned - stored, never read again. Since #1062 the connector files + /// live traffic only after the channel list is confirmed (ingress barrier + + /// fail-closed slot lookup), so a write-side fallback is a defect; it is + /// logged as an error and [forWrite] marks the call sites that save, remove + /// or clear. (#1063) + String _storageKey(int channelIndex, {bool forWrite = false}) { final pskHex = channelPskResolver?.call(channelIndex); if (pskHex != null && pskHex.isNotEmpty) { return '$keyFor$_pskMarker$pskHex'; } if (channelPskResolver != null) { - appLogger.warn( - 'Channel $channelIndex has no PSK yet; falling back to the slot-index ' - 'key. Any history already migrated to the PSK key will read as EMPTY. ' - 'This means the channel list was not loaded first (#333).', - tag: 'Storage', - ); + if (forWrite) { + appLogger.error( + 'WRITE for channel $channelIndex fell back to the slot-index key: ' + 'the slot did not resolve to a PSK. If this channel already has ' + 'PSK-keyed history, this write is orphaned (adoption only runs on ' + 'an empty PSK key). Post-#1062 ingress cannot reach this; a user ' + 'action on an unconfirmed slot can. (#1063)', + tag: 'Storage', + ); + } else { + appLogger.warn( + 'Channel $channelIndex has no PSK yet; falling back to the ' + 'slot-index key. Any history already migrated to the PSK key will ' + 'read as EMPTY. This means the channel list was not loaded first ' + '(#333).', + tag: 'Storage', + ); + } } return _indexKey(channelIndex); } @@ -165,7 +187,7 @@ class ChannelMessageStore { // the in-memory copy win so edits/reactions/status updates are captured. // Deletion has its own path (removeChannelMessage) so this never // resurrects a message the user deleted. - final key = _storageKey(channelIndex); + final key = _storageKey(channelIndex, forWrite: true); final blobs = BlobStore.instance; // Rows (#920): one upsert per message in the list, which costs the same @@ -230,7 +252,7 @@ class ChannelMessageStore { ChannelMessage message, ) async { if (publicKeyHex.isEmpty) return; - final key = _storageKey(channelIndex); + final key = _storageKey(channelIndex, forWrite: true); final blobs = BlobStore.instance; if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) { await blobs.deleteMessageRow(key, _mergeKey(message)); @@ -351,19 +373,38 @@ class ChannelMessageStore { return out; } - /// Clear messages for a specific channel slot. Removes BOTH the PSK-identity - /// key and the raw slot-index key: deleteChannel needs the channel's own - /// history gone, and setChannel's reuse-clear (#193) needs any stale - /// slot-index history gone so it can't be migrated onto the new occupant. + /// Clear a channel's history outright: BOTH the PSK-identity key and the + /// raw slot-index key. This is the true-delete path (deleteChannel, the + /// user's explicit clear) - the channel's own history must be gone. + /// Slot reassignment uses [clearLegacySlotHistory] instead, which keeps the + /// outgoing occupant's PSK-keyed history. (#1063) Future clearChannelMessages(int channelIndex) async { final blobs = BlobStore.instance; - for (final key in {_storageKey(channelIndex), _indexKey(channelIndex)}) { + for (final key in { + _storageKey(channelIndex, forWrite: true), + _indexKey(channelIndex), + }) { await blobs.deleteEverywhere(key); // Rows as well, or a clear would leave the history readable (#920). await blobs.deleteMessageRows(key); } } + /// Purges only the LEGACY slot-keyed history for [channelIndex]: the + /// device-scoped index key and the pre-device-scoping unscoped key. Used + /// when a slot is reassigned to a different channel (#193): without this, + /// [loadChannelMessages]' one-time adoption would migrate the previous + /// occupant's pre-#194 history onto the new occupant. The previous + /// occupant's PSK-keyed history is NOT touched, so re-adding that channel + /// later restores its messages. (#1063) + Future clearLegacySlotHistory(int channelIndex) async { + final blobs = BlobStore.instance; + for (final key in {_indexKey(channelIndex), '$_keyPrefix$channelIndex'}) { + await blobs.deleteEverywhere(key); + await blobs.deleteMessageRows(key); + } + } + /// Clear all channel messages Future clearAllChannelMessages() async { final blobs = BlobStore.instance; diff --git a/test/connector/channel_sync_truth_test.dart b/test/connector/channel_sync_truth_test.dart index 83371cee..ae37b3b8 100644 --- a/test/connector/channel_sync_truth_test.dart +++ b/test/connector/channel_sync_truth_test.dart @@ -13,6 +13,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -174,6 +175,66 @@ void main() { }, ); + test( + 'in-memory messages do not follow a slot across an identity change (#1063)', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([_channel(0, 'OldChannel', 70)]); + c.channelMessagesForTest[0] = [ + ChannelMessage( + senderName: 'x', + text: 'old occupant message', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 0, + messageId: 'old1', + ), + ]; + + await c.getChannels(maxChannels: 1); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'NewChannel', pskSeed: 10), + ); + // Settle the sync completion and the unawaited history reload. + await Future.delayed(Duration.zero); + await Future.delayed(Duration.zero); + + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: + "the old occupant's conversation must not render under the new " + 'channel; the slot reloads from the NEW identity\'s (empty) store', + ); + }, + ); + + test( + 'in-memory messages stay when the slot keeps the same channel', + () async { + final c = _connector(); + c.seedCachedChannelsForTest([_channel(0, 'Keep', 10)]); + c.channelMessagesForTest[0] = [ + ChannelMessage( + senderName: 'x', + text: 'kept', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 0, + messageId: 'k1', + ), + ]; + + await c.getChannels(maxChannels: 1); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Keep', pskSeed: 10), + ); + await Future.delayed(Duration.zero); + + expect(c.channelMessagesForTest[0]!.single.text, 'kept'); + }, + ); + test( 'a sync with unconfirmed slots does not overwrite the offline cache', () async { diff --git a/test/storage/channel_message_store_identity_test.dart b/test/storage/channel_message_store_identity_test.dart new file mode 100644 index 00000000..b2f8e0be --- /dev/null +++ b/test/storage/channel_message_store_identity_test.dart @@ -0,0 +1,128 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #1063 (Epic B of #1061): slot reassignment must not move history between +/// channel identities. Persisted history is PSK-keyed (#194); the remnants a +/// reassignment has to deal with are the LEGACY slot-index keys, and only +/// those - the outgoing occupant's PSK-keyed history survives so re-adding +/// that channel brings its messages back. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + const pskA = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + const pskB = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage chan(int i, {String? text}) => ChannelMessage( + senderName: 's', + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'id$i', + ); + + ChannelMessageStore store({String? psk}) => ChannelMessageStore() + ..setPublicKeyHex = 'd' * 20 + ..channelPskResolver = (_) => psk; + + test('clearLegacySlotHistory purges the legacy slot keys', () async { + // Pre-#194 remnants: device-scoped index key and the unscoped one. + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(1)]), + ); + await blobs.write( + 'channel_messages_0', + ChannelMessageStore.encodeHistoryForTest([chan(2)]), + ); + + await store(psk: pskA).clearLegacySlotHistory(0); + + expect( + await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'), + isNull, + ); + expect(await blobs.readWithPrefsFallback('channel_messages_0'), isNull); + }); + + test('clearLegacySlotHistory keeps the PSK-keyed history', () async { + final s = store(psk: pskA); + await s.saveChannelMessages(0, [chan(1), chan(2)]); + + await s.clearLegacySlotHistory(0); + + final loaded = await s.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1', 'id2']); + }); + + test('after a reassignment clear, the new occupant does not adopt the old ' + 'occupant\'s legacy slot history', () async { + // Old occupant A left pre-#194 history under the slot-index key. + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(1, text: 'old-A')]), + ); + + // Slot 0 is reassigned to channel B: the connector purges the legacy + // slot keys (setChannel, #1063). + await store(psk: pskB).clearLegacySlotHistory(0); + + // Channel B's first load must not inherit A's messages via the one-time + // slot-index adoption. + expect(await store(psk: pskB).loadChannelMessages(0), isEmpty); + }); + + test('the outgoing occupant\'s history survives a reassignment and comes ' + 'back when the channel is re-added', () async { + // Channel A lives in slot 0 with PSK-keyed history. + final asA = store(psk: pskA); + await asA.saveChannelMessages(0, [chan(1, text: 'kept')]); + + // Slot 0 is reassigned to channel B. + await store(psk: pskB).clearLegacySlotHistory(0); + await store(psk: pskB).saveChannelMessages(0, [chan(9, text: 'b-msg')]); + + // Channel A is re-added (any slot; identity is the PSK, not the slot). + final loaded = await store(psk: pskA).loadChannelMessages(5); + expect(loaded.single.text, 'kept'); + }); + + test('clearChannelMessages (true delete) removes the PSK-keyed history ' + 'and the legacy index key', () async { + final s = store(psk: pskA); + await s.saveChannelMessages(0, [chan(1)]); + await blobs.write( + 'channel_messages_dddddddddd0', + ChannelMessageStore.encodeHistoryForTest([chan(2)]), + ); + + await s.clearChannelMessages(0); + + expect(await s.loadChannelMessages(0), isEmpty); + expect( + await blobs.readWithPrefsFallback('channel_messages_dddddddddd0'), + isNull, + ); + }); +} From 3d40da28f2841ff727e7f59360ebf0f1bed2fe14 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:27:40 -0500 Subject: [PATCH 03/16] test(#1064): end-to-end slot-shuffle scenarios + slot-level ingress hold Integration tests for Feature #1061 across Epics A (#1062) and B (#1063): the #1060 bug-validation scenario (wipe + re-import with shuffled slots: list matches device, no misfiled or mis-rendered message, notify modes evaluate against the right PSKs), a manual device-side reorder (history follows the channel identity to its new slot), and a flaky sync mid-reconnect (held traffic files only after a confirming sync). Writing them exposed one gap: _flushHeldChannelFrames documented that a frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier, so after a partial sync such a message would file by raw index against an unknown identity and persist under the legacy index key. _handleIncomingChannelMessage now re-holds it until a sync confirms the slot. Test plumbing: channelNotifyProbeForTest observes the notify decision (slot, label, PSK, mode) without reaching the NotificationService singleton; wireMessageStoreForTest wires the message store the way the SELF_INFO handshake does. Issue: #1064 Co-Authored-By: Claude Fable 5 --- lib/connector/meshcore_connector.dart | 45 +++ .../channel_slot_resync_integration_test.dart | 291 ++++++++++++++++++ 2 files changed, 336 insertions(+) create mode 100644 test/connector/channel_slot_resync_integration_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 7f554189..b30b2df0 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -3290,6 +3290,16 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void setSelfPublicKeyForTest(Uint8List key) => _selfPublicKey = key; + /// Wires the channel message store the way the SELF_INFO handshake does + /// (device scoping + PSK resolver), so integration tests (#1064) exercise + /// the real PSK-keyed persistence path. Call after [setSelfPublicKeyForTest]. + @visibleForTesting + void wireMessageStoreForTest() { + _channelMessageStore.setPublicKeyHex = selfPublicKeyHex; + _channelMessageStore.channelPskResolver = (index) => + _findChannelByIndex(index)?.pskHex; + } + @visibleForTesting static bool shouldResetStateAfterTcpConnectAbort({ required MeshCoreConnectionState state, @@ -4068,6 +4078,20 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void Function(Uint8List data)? sendFrameOverrideForTest; + /// Observes [_maybeNotifyChannelMessage]'s decision: the slot, the display + /// label, and the PSK + mode the notification was evaluated against (null + /// psk/mode = suppressed because the slot was unconfirmed). Lets tests + /// assert notify routing (#1064) without reaching the NotificationService + /// singleton. + @visibleForTesting + void Function( + int channelIndex, + String channelName, + String? pskHex, + ChannelNotifyMode? mode, + )? + channelNotifyProbeForTest; + @visibleForTesting void setConnectedForTest() => _state = MeshCoreConnectionState.connected; @@ -9401,12 +9425,19 @@ class MeshCoreConnector extends ChangeNotifier { 'unconfirmed, its notify mode cannot be resolved', tag: 'ChannelSync', ); + channelNotifyProbeForTest?.call(channelIndex, label, null, null); return; } final mode = _appSettingsService!.channelNotifyMode( devicePrefix: selfPublicKeyHex, pskHex: slotChannel?.pskHex, ); + channelNotifyProbeForTest?.call( + channelIndex, + label, + slotChannel?.pskHex, + mode, + ); switch (mode) { case ChannelNotifyMode.off: return; @@ -9453,6 +9484,20 @@ class MeshCoreConnector extends ChangeNotifier { } final parsed = ChannelMessage.fromFrame(frame); if (parsed != null && parsed.channelIndex != null) { + // #1062 fail-closed, slot-level: the list is synced but THIS slot never + // confirmed. Filing by index would attach the message to an unknown + // identity and persist it under the legacy index key, so re-hold until + // a sync confirms the slot (found by the #1064 integration tests). + if (isConnected && + _unconfirmedChannelSlots.contains(parsed.channelIndex)) { + _holdChannelFrame( + _heldChannelMsgFrames, + frame, + 'message', + bounded: false, + ); + return; + } // Device-composed (outgoing) messages legitimately carry our own name and // no path; don't let the self-echo guard drop them (#429 part B). if (!parsed.isOutgoing && diff --git a/test/connector/channel_slot_resync_integration_test.dart b/test/connector/channel_slot_resync_integration_test.dart new file mode 100644 index 00000000..b7b633a1 --- /dev/null +++ b/test/connector/channel_slot_resync_integration_test.dart @@ -0,0 +1,291 @@ +// #1064 (Epic C of #1061): end-to-end slot-shuffle scenarios across Epic A +// (#1062, fail-closed sync + ingress barrier) and Epic B (#1063, per-slot +// state never crosses identities). The first test is the #1060 bug-validation +// scenario: a wipe + config re-import rearranged the device's channel slots, +// #wardriving notified with its mode off, and #test messages rendered inside +// the private channel. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _channelInfoFrame({ + required int index, + required String name, + required int pskSeed, +}) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + final nameBytes = name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + for (var i = 0; i < 16; i++) { + frame[34 + i] = (pskSeed + i) & 0xFF; + } + return frame; +} + +Uint8List _v3ChannelMsgFrame({required int channelIdx, String text = 'A: hi'}) { + return Uint8List.fromList([ + respCodeChannelMsgRecvV3, + 0, 0, 0, + channelIdx, + 1, // path_len: 1 hop, width 1 + txtTypePlain, + 0x40, 0xE2, 0x01, 0x00, + ...text.codeUnits, + ]); +} + +Channel _channel(int index, String name, int pskSeed) { + final psk = Uint8List.fromList( + List.generate(16, (i) => (pskSeed + i) & 0xFF), + ); + return Channel(index: index, name: name, psk: psk); +} + +typedef _NotifyDecision = ({ + int channelIndex, + String channelName, + String? pskHex, + ChannelNotifyMode? mode, +}); + +Future _settle([int turns = 25]) async { + for (var i = 0; i < turns; i++) { + await Future.delayed(Duration.zero); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late OffbandDatabase db; + late AppSettingsService settings; + late MeshCoreConnector c; + late List<_NotifyDecision> notifyDecisions; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + settings = AppSettingsService(); + await settings.loadSettings(); + + c = MeshCoreConnector(); + c.initialize( + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(StorageService()), + appSettingsService: settings, + ); + c.sendFrameOverrideForTest = (_) {}; + c.setConnectedForTest(); + c.setSelfPublicKeyForTest( + Uint8List.fromList(List.generate(32, (i) => i)), + ); + c.wireMessageStoreForTest(); + + notifyDecisions = []; + c.channelNotifyProbeForTest = (index, name, pskHex, mode) { + notifyDecisions.add(( + channelIndex: index, + channelName: name, + pskHex: pskHex, + mode: mode, + )); + }; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future syncWith(List deviceArrangement, {int? max}) async { + await c.getChannels( + force: true, + maxChannels: max ?? deviceArrangement.length, + ); + for (final ch in deviceArrangement) { + c.handleFrameForTest( + _channelInfoFrame(index: ch.index, name: ch.name, pskSeed: ch.psk[0]), + ); + await _settle(2); + } + await _settle(); + } + + test('#1060 bug validation: wipe + re-import with shuffled slots', () async { + // Before the wipe this radio had: slot0 #wardriving (notify OFF), + // slot1 #test, slot2 the private channel (an old conversation on screen). + final wardriving = _channel(0, 'wardriving', 40); + final testCh = _channel(1, 'test', 50); + final private = _channel(2, 'Private', 60); + c.seedCachedChannelsForTest([wardriving, testCh, private]); + await settings.setChannelNotifyMode( + devicePrefix: c.selfPublicKeyHex, + pskHex: wardriving.pskHex, + channelName: wardriving.name, + mode: ChannelNotifyMode.off, + ); + c.channelMessagesForTest[2] = [ + ChannelMessage( + senderName: 'friend', + text: 'old private talk', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000), + isOutgoing: false, + channelIndex: 2, + messageId: 'old-private', + ), + ]; + + // The re-imported config put the same channels in DIFFERENT slots. + await syncWith([ + _channel(0, 'test', 50), + _channel(1, 'Private', 60), + _channel(2, 'wardriving', 40), + ]); + + // The list matches the device, and every slot's change was surfaced. + expect(c.channels.map((ch) => ch.name), ['test', 'Private', 'wardriving']); + expect(c.slotIdentityChanges, hasLength(3)); + expect(c.unconfirmedChannelSlots, isEmpty); + + // The old private conversation did not stay behind in slot 2, which + // #wardriving now occupies. + expect(c.channelMessagesForTest[2] ?? const [], isEmpty); + + // A #test message files under #test's slot and is evaluated against + // #test's PSK (default mode), not against whatever used to live there. + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 0, text: 'B: to test')); + await _settle(); + expect(c.channelMessagesForTest[0]!.single.text, 'to test'); + expect( + c.channelMessagesForTest[1] ?? const [], + isEmpty, + reason: '#test traffic must not render inside the private channel', + ); + final testDecision = notifyDecisions.single; + expect(testDecision.channelName, 'test'); + expect(testDecision.pskHex, testCh.pskHex); + expect(testDecision.mode, ChannelNotifyMode.all); + + // A #wardriving message follows #wardriving's OFF mode to its NEW slot: + // the #1060 complaint was notifications firing with the mode off. + notifyDecisions.clear(); + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 2, text: 'B: war')); + await _settle(); + expect(c.channelMessagesForTest[2]!.single.text, 'war'); + final warDecision = notifyDecisions.single; + expect(warDecision.pskHex, wardriving.pskHex); + expect( + warDecision.mode, + ChannelNotifyMode.off, + reason: 'the OFF mode belongs to the PSK and must ride along to slot 2', + ); + }); + + test('manual reorder on the device: history follows the channel, ' + 'not the slot', () async { + // First sync: Alpha in slot 0, Beta in slot 1. A message lands in Alpha + // and is persisted under Alpha's PSK identity. + await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]); + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'A: hello alpha'), + ); + await _settle(); + expect(c.channelMessagesForTest[0]!.single.text, 'hello alpha'); + // Let the unawaited persistence land before the reorder. + await Future.delayed(const Duration(milliseconds: 50)); + + // The operator swaps the slots on the device; the client re-syncs. + await syncWith([_channel(0, 'Beta', 30), _channel(1, 'Alpha', 10)]); + await Future.delayed(const Duration(milliseconds: 50)); + await _settle(); + + expect(c.channels.map((ch) => ch.name), ['Beta', 'Alpha']); + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: "Alpha's conversation must not render under Beta", + ); + expect( + (c.channelMessagesForTest[1] ?? const []).map( + (m) => m.text, + ), + ['hello alpha'], + reason: "Alpha's PSK-keyed history reloads at its new slot", + ); + }); + + test('flaky sync mid-reconnect: held traffic files only after a ' + 'confirming sync, against the right PSK', () async { + final alpha = _channel(0, 'Alpha', 10); + final beta = _channel(1, 'Beta', 30); + c.seedCachedChannelsForTest([alpha, beta]); + await settings.setChannelNotifyMode( + devicePrefix: c.selfPublicKeyHex, + pskHex: beta.pskHex, + channelName: beta.name, + mode: ChannelNotifyMode.off, + ); + + // The sync answers slot 0, a message for slot 1 arrives mid-sync, and + // slot 1 never answers. + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10), + ); + await _settle(2); + c.handleFrameForTest(_v3ChannelMsgFrame(channelIdx: 1, text: 'B: held')); + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await _settle(2); + } + await _settle(); + + expect(c.unconfirmedChannelSlots, {1}); + expect( + c.channelMessagesForTest[1], + isNull, + reason: 'a message for an unconfirmed slot must not file by raw index', + ); + expect( + notifyDecisions.where((d) => d.channelIndex == 1 && d.mode != null), + isEmpty, + reason: 'no notify decision can be made for an unconfirmed slot', + ); + + // The reconnect-style retry confirms both slots; the held message now + // files, and Beta's OFF mode is evaluated against Beta's own PSK. + notifyDecisions.clear(); + await syncWith([alpha, beta]); + + expect(c.unconfirmedChannelSlots, isEmpty); + expect(c.channels.map((ch) => ch.name), ['Alpha', 'Beta']); + expect(c.channelMessagesForTest[1]!.single.text, 'held'); + final decision = notifyDecisions.single; + expect(decision.channelIndex, 1); + expect(decision.pskHex, beta.pskHex); + expect(decision.mode, ChannelNotifyMode.off); + }); +} From 015f3fb94bc4d84849c9b4e2253a2f6b79f5f96d Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 00:30:17 -0500 Subject: [PATCH 04/16] docs(#1064): feature 1061 PLAN and OUTCOMES The plan of record (four approved parts, the Epic B re-scope) and the outcomes: what each Epic shipped, the slot-level ingress gap the integration tests exposed, the positive and negative test evidence, and what stays open until the owner's hardware pass. Issue: #1064 Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 37 ++++++++++++++++++ .../1061-channel-slot-resync/PLAN.md | 39 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md create mode 100644 docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md new file mode 100644 index 00000000..c46b5541 --- /dev/null +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -0,0 +1,37 @@ +# Feature #1061 channel slot resync truth: OUTCOMES + +Status: BUILT and machine-verified; awaiting the owner's hardware test, then PRs. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C). + +## What was built +| Epic | Commit | Content | +|---|---|---| +| A #1062 | `c2f599e3` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | +| B #1063 | `0d19c3c7` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | +| C #1064 | `0f8fcce1` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | + +## Gap found by the integration tests (fixed in `0f8fcce1`) +Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. + +## Evidence +Machine verification, all on the stacked branch: +- `flutter analyze` clean on every touched file. +- Unit tests: 7 sync-truth tests (`test/connector/channel_sync_truth_test.dart`), 5 store identity tests (`test/storage/channel_message_store_identity_test.dart`). +- Integration tests (`test/connector/channel_slot_resync_integration_test.dart`): + 1. **#1060 bug validation (wipe + re-import, all three slots shuffled):** post-sync list matches the device exactly; all three identity changes surfaced; the old private conversation does not stay behind under #wardriving; a #test message files under #test and is notify-evaluated against #test's PSK (mode `all`); a #wardriving message is evaluated against #wardriving's PSK and its OFF mode rides along to the new slot. The reported symptoms (muted channel notifying, #test rendering in the private channel) cannot reproduce. + 2. **Manual device-side reorder:** a message persisted under Alpha's PSK follows Alpha to its new slot after the re-sync; nothing renders under Beta. + 3. **Flaky sync mid-reconnect:** a message for a never-confirmed slot is held, not filed by raw index, and no notify decision is made for it; after a confirming re-sync it files once, against the right PSK and mode. +- **Negative evidence:** with Epic B's drop/reload and the slot-level re-hold reverted in the working tree, all three scenarios fail (`+0 -3`) on exactly the guarded assertions; restored, all pass. The checks can fail. +- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. + +## Decisions logged +- Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. +- Already-miskeyed rows from the #1060 window stay as-is: not mechanically separable, and the owner's standing history-loss bar is deliberately low. Say the word and a per-radio clear can be added instead. +- setChannel reassignment now PRESERVES the outgoing occupant's PSK-keyed history (only legacy slot keys are purged). Re-adding a channel later restores its messages; this strengthens #194's intent and the diff is one call site, flagged for owner review on the Epic B PR. + +## Open until the owner closes them +- Hardware test of the combined stack (the #1060 recovery sequence on the T1000e: wipe, re-import, reconnect, one sync). +- The user-reported problem the owner logged this feature against: its one-liner / issue number is still pending and will be linked under #1063/#1064 when provided. +- PRs + merges after the hardware pass (stacked: A into dev, B+C into A's branch or rebased per owner preference). +- #1060 closes only after the owner confirms on hardware. + +Agent: TurquoiseBridge (session 82d77b2f) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md b/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md new file mode 100644 index 00000000..ead837e6 --- /dev/null +++ b/docs/initiatives/standalone/1061-channel-slot-resync/PLAN.md @@ -0,0 +1,39 @@ +# Feature PLAN: channel slot resync truth (#1060 class) + +| | | +|---|---| +| **Feature** | [#1061](https://github.com/OffbandMesh/meshcore-client/issues/1061) · Citadel `meshcore-open-rwr` | +| **Fixes** | [#1060](https://github.com/OffbandMesh/meshcore-client/issues/1060) (P0): wipe + config re-import shuffled channel slots; notifications fired for a muted channel and messages rendered inside the wrong conversation | +| **Owner** | @Strycher | +| **Approved** | 2026-11-02 in chat: "Agree with all 4, don't hold on 4, do it now." Epic B re-scope approved 2026-11-03: "Agree, proceed." | + +## At a glance +- **What:** make the device's channel list the only truth the client ever acts on, and make every piece of per-slot client state follow the channel's PSK identity instead of its reusable slot index. +- **Why:** #1060. The radio is authoritative for slot assignments; after a wipe + re-import the same channels can sit in different slots, and any client state keyed by slot silently attaches to the wrong channel. +- **Done when:** the integration scenarios pass (positive and negative), the #1060 reporter's sequence cannot recur, and the owner approves the OUTCOMES. + +## 1. Diagnosis (#1060, verified in code) +Three routes let a stale slot map poison live behavior: +1. **Backfill:** the channel sync restored unanswered slots from `_previousChannelsCache`, so a shuffled device list came back part-fresh, part-stale. +2. **Index filing:** raw-RX and message ingress filed by slot index through the stale list. +3. **Poisoned resolver:** notify modes and persisted history are PSK-keyed (#839, #194), but both resolve PSKs through `_findChannelByIndex` - which consulted the stale list, so correct identity keying was fed wrong identities. + +## 2. The four approved parts → Epics +| Part | Epic | Scope | +|---|---|---| +| 1. Fail-closed, atomic channel sync | A [#1062](https://github.com/OffbandMesh/meshcore-client/issues/1062) | never backfill an unanswered slot; unconfirmed slots tracked + surfaced (banner w/ Retry); cache not overwritten on holes; self-retry on a failed live sync | +| 2. Ingress barrier | A #1062 | no live channel frame files until THIS connection confirms the list; pull-based message frames held unbounded (the radio already popped them), raw sniffs bounded at 64; held frames flush post-sync | +| 3. Per-slot identity diff | A #1062 | PSK diff per slot against the last truth; identity changes surfaced in UI + log; unread preserved only on same PSK; unconfirmed slots fail closed in `_findChannelByIndex` and suppress notifications | +| 4. Identity-keyed message state | B [#1063](https://github.com/OffbandMesh/meshcore-client/issues/1063) | RE-SCOPED (see below) | +| Validation | C [#1064](https://github.com/OffbandMesh/meshcore-client/issues/1064) | end-to-end scenarios, the #1060 bug-validation test, this folder's OUTCOMES.md | + +## 3. Epic B re-scope (approved 2026-11-03) +Part 4 was planned as "re-key channel_message_store by PSK with migration" from a stale #193-era comment. The store has been PSK-keyed since #194; the incident's cross-wiring came from the poisoned resolver (route 3), which Epic A fixes. Epic B therefore shrank to: +1. drop a slot's in-memory `_channelMessages` entry on identity change and reload it under the new identity's PSK; +2. harden the store's slot-index write fallback (error log naming the orphaning consequence); +3. narrow setChannel's reassignment clear to the LEGACY slot keys only, so the outgoing occupant's PSK-keyed history survives and returns if the channel is re-added; +4. correct the stale #193-era comments and document the setChannel/resolver interplay. + +Already-miskeyed rows from the #1060 window stay as-is (not mechanically separable; owner's standing low history-loss bar). + +Agent: TurquoiseBridge (session 82d77b2f) From 3a6e6473dee160bae22929b34181e42eba129214 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:26:32 -0500 Subject: [PATCH 05/16] docs(#1064): record the owner's push/PR authorization and post-rebase SHAs The owner waived the pre-PR hardware gate for feature 1061 (no way to reproduce on demand); validation moves to live testing after merge. Merges still require the explicit per-PR grant. Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md index c46b5541..9ac25a7c 100644 --- a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -1,15 +1,15 @@ # Feature #1061 channel slot resync truth: OUTCOMES -Status: BUILT and machine-verified; awaiting the owner's hardware test, then PRs. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C). +Status: BUILT and machine-verified; PRs opened on the owner's word (decision below), validation moves to live testing after merge. Branch stack: `feat/1062-channel-sync-truth` (Epic A) ← `feat/1063-message-state-hardening` (Epics B + C), rebased onto dev `180c01e6`. ## What was built | Epic | Commit | Content | |---|---|---| -| A #1062 | `c2f599e3` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | -| B #1063 | `0d19c3c7` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | -| C #1064 | `0f8fcce1` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | +| A #1062 | `da08b7eb` | fail-closed atomic sync (no backfill, unconfirmed slots tracked + bannered with Retry, cache kept on holes), ingress barrier (messages held unbounded, raw sniffs bounded 64, flush post-sync), per-slot PSK identity diff (UI notice + warn log), unread preserved only on same PSK, fail-closed `_findChannelByIndex`, notification suppression for unconfirmed slots, self-retry on failed live sync | +| B #1063 | `b658fe14` | in-memory conversation dropped + reloaded under the new PSK on slot identity change; setChannel reassignment clear narrowed to legacy slot keys (PSK history survives re-add; deleteChannel keeps the full clear); write-side index fallback escalated to an error naming the orphaning consequence; stale #193-era comments corrected, setChannel/resolver interplay documented | +| C #1064 | `2a9d1e16` | the three integration scenarios below, the notify-decision test probe, store wiring test hook, and one fix the tests exposed (next section) | -## Gap found by the integration tests (fixed in `0f8fcce1`) +## Gap found by the integration tests (fixed in `2a9d1e16`) Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. ## Evidence @@ -27,11 +27,12 @@ Machine verification, all on the stacked branch: - Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. - Already-miskeyed rows from the #1060 window stay as-is: not mechanically separable, and the owner's standing history-loss bar is deliberately low. Say the word and a per-radio clear can be added instead. - setChannel reassignment now PRESERVES the outgoing occupant's PSK-keyed history (only legacy slot keys are purged). Re-adding a channel later restores its messages; this strengthens #194's intent and the diff is one call site, flagged for owner review on the Epic B PR. +- Owner, 2026-11-03 in chat: "I don't have a way to reproduce right now. Push/pr if the work is done, we will validate in live testing." The pre-PR hardware gate is waived for this feature; validation moves to live testing. Merges still require the explicit per-PR grant. ## Open until the owner closes them -- Hardware test of the combined stack (the #1060 recovery sequence on the T1000e: wipe, re-import, reconnect, one sync). +- Live-testing validation after merge (the #1060 recovery sequence: wipe, re-import, reconnect, one sync). The owner cannot reproduce on demand right now, so this is observational. - The user-reported problem the owner logged this feature against: its one-liner / issue number is still pending and will be linked under #1063/#1064 when provided. -- PRs + merges after the hardware pass (stacked: A into dev, B+C into A's branch or rebased per owner preference). -- #1060 closes only after the owner confirms on hardware. +- Merges of the stacked PRs (A into dev, then B+C) on the owner's explicit grant. +- #1060 closes only after the owner confirms the fix in live use. Agent: TurquoiseBridge (session 82d77b2f) From 12154c61f2e963cacb3a14d52d013492262eebb4 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Tue, 3 Nov 2026 02:40:44 -0500 Subject: [PATCH 06/16] fix(#1063): close the adversarial-review findings on the 1061 stack Gemini gate (gemini-2.5-pro) on the pre-push stack, four findings: - Held channel message frames are now keyed per radio: verifying the unbounded-growth finding exposed that frames held from radio X would have flushed into radio Y's conversations after a radio switch. A parked radio's frames flush when that radio next completes a sync. No cap is added: held frames are popped messages, dropping one is guaranteed loss, and growth is traffic-bounded (<=172 bytes/frame). - _loadChannelMessages merges messages that arrived during the disk read instead of clobbering the list, so the slot-identity reload cannot hide a message the held-frame flush just filed (disk was never at risk: saves merge by identity, #343). - sendChannelMessage refuses the write for a slot this connection has not confirmed (the persisted copy would fall back to the legacy slot-index key and be orphaned), and the chat screen surfaces a persistent error at every send path instead of greying anything. New English UI string; untranslated.json regenerated (#1063). Three integration tests cover the fixes (#1064); with the guards behaviorally disabled exactly those three fail (+3 -3). Full suite 1807 passed / 1 skipped. OUTCOMES.md records the gate and dispositions. Co-Authored-By: Claude Fable 5 --- .../1061-channel-slot-resync/OUTCOMES.md | 9 +- lib/connector/meshcore_connector.dart | 63 ++++++++- lib/l10n/app_en.arb | 1 + lib/l10n/app_localizations.dart | 6 + lib/l10n/app_localizations_bg.dart | 4 + lib/l10n/app_localizations_de.dart | 4 + lib/l10n/app_localizations_en.dart | 4 + lib/l10n/app_localizations_es.dart | 4 + lib/l10n/app_localizations_fr.dart | 4 + lib/l10n/app_localizations_hu.dart | 4 + lib/l10n/app_localizations_it.dart | 4 + lib/l10n/app_localizations_ja.dart | 4 + lib/l10n/app_localizations_ko.dart | 4 + lib/l10n/app_localizations_nl.dart | 4 + lib/l10n/app_localizations_pl.dart | 4 + lib/l10n/app_localizations_pt.dart | 4 + lib/l10n/app_localizations_ru.dart | 4 + lib/l10n/app_localizations_sk.dart | 4 + lib/l10n/app_localizations_sl.dart | 4 + lib/l10n/app_localizations_sv.dart | 4 + lib/l10n/app_localizations_uk.dart | 4 + lib/l10n/app_localizations_zh.dart | 4 + lib/screens/channel_chat_screen.dart | 27 +++- .../channel_slot_resync_integration_test.dart | 124 ++++++++++++++++++ untranslated.json | 17 +++ 25 files changed, 307 insertions(+), 12 deletions(-) diff --git a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md index 9ac25a7c..3a98ea0c 100644 --- a/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md +++ b/docs/initiatives/standalone/1061-channel-slot-resync/OUTCOMES.md @@ -12,6 +12,13 @@ Status: BUILT and machine-verified; PRs opened on the owner's word (decision bel ## Gap found by the integration tests (fixed in `2a9d1e16`) Epic A's flush documented that a held frame for a still-unconfirmed slot re-holds, but the handler only gated on the list-level barrier: after a PARTIAL sync completed, a held message for an unconfirmed slot would have filed by raw index against an unknown identity and persisted under the legacy index key. `_handleIncomingChannelMessage` now re-holds such frames until a sync confirms the slot. This is the "prove the check can fail" discipline paying for itself; the flaky-sync scenario below fails without the fix. +## Gemini adversarial gate (gemini-2.5-pro, 2026-11-03, at the pre-push stack head) +Four findings, all addressed before push: +1. **HIGH, unbounded held frames:** cap deliberately NOT added (held frames are popped messages; dropping one is guaranteed loss; growth is traffic-bounded at <=172 bytes/frame and drains on the next confirming sync). Verifying it exposed a sharper defect the review did not name: held frames survived a radio SWITCH and would have flushed into the other radio's conversations. Fixed: held message frames are keyed per radio and flush only when their own radio completes a sync. +2. **MEDIUM, identity-change reload race:** confirmed for in-memory state only (saves merge by identity, #343). Fixed: `_loadChannelMessages` merges messages that arrived during the disk read instead of clobbering. +3. **MEDIUM, outgoing send on an unconfirmed slot orphans the persisted copy:** confirmed. Fixed: `sendChannelMessage` refuses the write (fail closed, logged) and the chat screen shows a persistent error at every send path. New English UI string, untranslated.json regenerated. +4. **Test gaps:** three integration tests added (race, refused send, cross-radio hold); with the three guards behaviorally disabled, exactly those three fail (+3 -3). + ## Evidence Machine verification, all on the stacked branch: - `flutter analyze` clean on every touched file. @@ -21,7 +28,7 @@ Machine verification, all on the stacked branch: 2. **Manual device-side reorder:** a message persisted under Alpha's PSK follows Alpha to its new slot after the re-sync; nothing renders under Beta. 3. **Flaky sync mid-reconnect:** a message for a never-confirmed slot is held, not filed by raw index, and no notify decision is made for it; after a confirming re-sync it files once, against the right PSK and mode. - **Negative evidence:** with Epic B's drop/reload and the slot-level re-hold reverted in the working tree, all three scenarios fail (`+0 -3`) on exactly the guarded assertions; restored, all pass. The checks can fail. -- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. +- Full suite at Epic B: 1791 passed / 1 skipped, exit 0. Full suite at Epic C: 1794 passed / 1 skipped, exit 0. Full suite at the pushed head (post-rebase, post-review fixes): 1807 passed / 1 skipped, exit 0. ## Decisions logged - Epic B re-scope approved by the owner 2026-11-03 ("Agree, proceed"); storage was already PSK-keyed since #194, so no migration was needed. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index b30b2df0..0ce68841 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -593,9 +593,16 @@ class MeshCoreConnector extends ChangeNotifier { // #1062: ingress barrier. Live channel traffic is held while this // connection's channel list is not yet synced, then flushed, so a message - // is never filed against a guessed slot map. + // is never filed against a guessed slot map. Held MESSAGE frames are keyed + // by the radio that delivered them (#1063 review): they survive reconnects + // because the radio already popped them, but a switch to a DIFFERENT radio + // must not flush them into its conversations. A parked radio's frames flush + // when that radio next completes a sync; '' holds frames from before the + // connection identified itself and is adopted by the next flush. bool _channelListSynced = false; - final List _heldChannelMsgFrames = []; + final Map> _heldChannelMsgFramesByRadio = {}; + List get _heldChannelMsgFrames => + _heldChannelMsgFramesByRadio.putIfAbsent(selfPublicKeyHex, () => []); final List _heldRawChannelFrames = []; static const int _maxHeldChannelFrames = 64; @@ -2355,9 +2362,24 @@ class MeshCoreConnector extends ChangeNotifier { ); if (allMessages.isNotEmpty) { // Keep only the most recent N messages in memory to bound memory usage - final windowedMessages = allMessages.length > _messageWindowSize - ? allMessages.sublist(allMessages.length - _messageWindowSize) - : allMessages; + final windowedMessages = List.from( + allMessages.length > _messageWindowSize + ? allMessages.sublist(allMessages.length - _messageWindowSize) + : allMessages, + ); + + // A message can land in memory while this load is reading the store + // (the slot-identity reload racing a flushed held frame, #1063 review). + // The store save merges, so disk already has it; keep it visible too + // instead of clobbering the list with the pre-arrival history. + final current = _channelMessages[channelIndex]; + if (current != null) { + for (final m in current) { + if (_findChannelRepeatIndex(windowedMessages, m) < 0) { + windowedMessages.add(m); + } + } + } _channelMessages[channelIndex] = windowedMessages; notifyListeners(); @@ -4198,8 +4220,9 @@ class MeshCoreConnector extends ChangeNotifier { _previousChannelsCache.clear(); // #1062: a new connection starts with an unconfirmed list. Held MESSAGE // frames are kept: the radio already popped them from its queue, so they - // exist nowhere else, and the next confirmed sync files them. Raw sniff - // frames are lossy observations; a dead connection's are stale. + // exist nowhere else, and the holding radio's next confirmed sync files + // them (per-radio, so a radio switch cannot leak them, #1063 review). + // Raw sniff frames are lossy observations; a dead connection's are stale. _channelListSynced = false; _unconfirmedChannelSlots.clear(); _slotIdentityChanges.clear(); @@ -5733,6 +5756,14 @@ class MeshCoreConnector extends ChangeNotifier { return ts; } + /// Whether an outgoing write for [channelIndex] is allowed (#1063 review). + /// False while this connection has not confirmed the slot: the PSK resolver + /// would return null and the persisted copy would fall back to the legacy + /// slot-index key, orphaning it (adoption only runs on an empty PSK key). + /// Callers must refuse the write and tell the user why, not grey a button. + bool canSendOnChannel(int channelIndex) => + _channelListSynced && !_unconfirmedChannelSlots.contains(channelIndex); + Future sendChannelMessage( Channel channel, String text, { @@ -5741,6 +5772,16 @@ class MeshCoreConnector extends ChangeNotifier { String? translationModelId, }) async { if (!isConnected || text.isEmpty) return; + if (!canSendOnChannel(channel.index)) { + // Fail closed at the write, loudly: the message would persist under an + // unknown identity. The UI surfaces this via [canSendOnChannel]. + _appDebugLogService?.error( + 'Refused to send on channel slot ${channel.index}: the slot is not ' + 'confirmed by this connection (#1063). Retry the channel sync.', + tag: 'ChannelSync', + ); + return; + } // Check if this is a reaction - if so, process it immediately instead of adding as a message final reactionInfo = ReactionHelper.parseReaction(text); @@ -6512,6 +6553,14 @@ class MeshCoreConnector extends ChangeNotifier { /// Runs after [_channelListSynced] flips true, so the handlers file against /// the fresh list; a frame whose slot is still unconfirmed re-holds. void _flushHeldChannelFrames() { + // Frames held before this connection learned its radio key belong to this + // connection (nothing flows before the handshake); adopt them first. + if (selfPublicKeyHex.isNotEmpty) { + final unattributed = _heldChannelMsgFramesByRadio.remove(''); + if (unattributed != null) { + _heldChannelMsgFrames.insertAll(0, unattributed); + } + } if (_heldChannelMsgFrames.isEmpty && _heldRawChannelFrames.isEmpty) return; final msgFrames = List.from(_heldChannelMsgFrames); final rawFrames = List.from(_heldRawChannelFrames); diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 317b1ee5..fc5a4677 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -1205,6 +1205,7 @@ } }, "channel_senderAddNotConnected": "Not connected to a radio, so this sender can't be added yet", + "channel_slotUnconfirmedSendBlocked": "Message not sent: the radio hasn't confirmed this channel slot yet. Retry the channel sync, then send again.", "channel_senderAddFailed": "Couldn't add this sender: {error}", "@channel_senderAddFailed": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 3044aeca..c64ec3c1 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -3730,6 +3730,12 @@ abstract class AppLocalizations { /// **'Not connected to a radio, so this sender can\'t be added yet'** String get channel_senderAddNotConnected; + /// No description provided for @channel_slotUnconfirmedSendBlocked. + /// + /// In en, this message translates to: + /// **'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'** + String get channel_slotUnconfirmedSendBlocked; + /// No description provided for @channel_senderAddFailed. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index b1b6f5ae..1de8aee6 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -2137,6 +2137,10 @@ class AppLocalizationsBg extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 77afe12f..2ff95514 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -2135,6 +2135,10 @@ class AppLocalizationsDe extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 39478abc..a54bed81 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -2106,6 +2106,10 @@ class AppLocalizationsEn extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 2183176d..9d2ecb51 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -2132,6 +2132,10 @@ class AppLocalizationsEs extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 7f729f47..e5765685 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -2139,6 +2139,10 @@ class AppLocalizationsFr extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index a6c3b9a4..68aa77eb 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -2144,6 +2144,10 @@ class AppLocalizationsHu extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 5b4b9d0f..f11a8a5c 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -2134,6 +2134,10 @@ class AppLocalizationsIt extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 74a35229..1fb331a8 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -2069,6 +2069,10 @@ class AppLocalizationsJa extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index cc8b2ad4..9a7c320c 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -2065,6 +2065,10 @@ class AppLocalizationsKo extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 9a206eed..2962b084 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -2122,6 +2122,10 @@ class AppLocalizationsNl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 846c6b3f..9f412ea4 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -2147,6 +2147,10 @@ class AppLocalizationsPl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 111aecc5..b65a487e 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -2131,6 +2131,10 @@ class AppLocalizationsPt extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index d2724854..fc66e2db 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -2135,6 +2135,10 @@ class AppLocalizationsRu extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index de469971..324dbb65 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -2124,6 +2124,10 @@ class AppLocalizationsSk extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 77cfd12c..7d2d1f8c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -2120,6 +2120,10 @@ class AppLocalizationsSl extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index b8fec2a9..5d93902f 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -2115,6 +2115,10 @@ class AppLocalizationsSv extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index b1728c8f..38f71fa0 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -2130,6 +2130,10 @@ class AppLocalizationsUk extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 64f10bc4..9620e163 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -2044,6 +2044,10 @@ class AppLocalizationsZh extends AppLocalizations { String get channel_senderAddNotConnected => 'Not connected to a radio, so this sender can\'t be added yet'; + @override + String get channel_slotUnconfirmedSendBlocked => + 'Message not sent: the radio hasn\'t confirmed this channel slot yet. Retry the channel sync, then send again.'; + @override String channel_senderAddFailed(String error) { return 'Couldn\'t add this sender: $error'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index dd2cfbf4..9ae7fd14 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -1771,6 +1771,9 @@ class _ChannelChatScreenState extends State { } // end transform + // Refuse before clearing so the draft survives the refusal. + if (_refuseIfSlotUnconfirmed(connector)) return; + _textController.clear(); _cancelReply(); _textFieldFocusNode.requestFocus(); @@ -1783,6 +1786,21 @@ class _ChannelChatScreenState extends State { ); } + /// #1063: an outgoing write on a slot this connection has not confirmed + /// would persist under an unknown identity and be orphaned, so refuse at + /// the attempt and say why (a sync can confirm the slot seconds later, so + /// greying the composer would mislead). + bool _refuseIfSlotUnconfirmed(MeshCoreConnector connector) { + if (connector.canSendOnChannel(_currentChannel.index)) return false; + showDismissibleSnackBar( + context, + content: Text(context.l10n.channel_slotUnconfirmedSendBlocked), + backgroundColor: Theme.of(context).colorScheme.error, + persist: true, + ); + return true; + } + /// One-click reply quoting the route a message took, hop count + path, /// truncated with … to fit the channel byte budget, fired directly. (#106) void _sendRouteReply(ChannelMessage message) { @@ -1816,6 +1834,7 @@ class _ChannelChatScreenState extends State { if (connector.isChannelCyr2LatEnabled(_currentChannel.index)) { text = Cyr2Lat.encode(text); } + if (_refuseIfSlotUnconfirmed(connector)) return; connector.sendChannelMessage(_currentChannel, text); } @@ -2051,10 +2070,9 @@ class _ChannelChatScreenState extends State { } void _retryChannelMessage(ChannelMessage message) { - context.read().sendChannelMessage( - _currentChannel, - message.text, - ); + final connector = context.read(); + if (_refuseIfSlotUnconfirmed(connector)) return; + connector.sendChannelMessage(_currentChannel, message.text); showDismissibleSnackBar( context, content: Text(context.l10n.chat_sendingAgain), @@ -2229,6 +2247,7 @@ class _ChannelChatScreenState extends State { message.text, ); final reactionText = ReactionHelper.encodeReaction(hash, emojiIndex); + if (_refuseIfSlotUnconfirmed(connector)) return; connector.sendChannelMessage(_currentChannel, reactionText); } diff --git a/test/connector/channel_slot_resync_integration_test.dart b/test/connector/channel_slot_resync_integration_test.dart index b7b633a1..cecbfe89 100644 --- a/test/connector/channel_slot_resync_integration_test.dart +++ b/test/connector/channel_slot_resync_integration_test.dart @@ -288,4 +288,128 @@ void main() { expect(decision.pskHex, beta.pskHex); expect(decision.mode, ChannelNotifyMode.off); }); + + test( + 'identity-change reload does not hide a message flushed meanwhile', + () async { + // Beta builds history at slot 1, then moves to slot 0. A live message for + // slot 0 arrives MID-resync (held), so the flush files it while the + // identity-change reload is still reading the store. Both must be visible + // afterwards: the reload merges, it does not clobber (#1063 review). + await syncWith([_channel(0, 'Alpha', 10), _channel(1, 'Beta', 30)]); + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 1, text: 'B: beta history'), + ); + await _settle(); + await Future.delayed(const Duration(milliseconds: 50)); + + await c.getChannels(force: true, maxChannels: 2); + // Mid-resync: the barrier is closed, so this is held, and the flush will + // file it in the same turn that starts the slot-0 reload. + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'B: live during sync'), + ); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Beta', pskSeed: 30), + ); + await _settle(2); + c.handleFrameForTest( + _channelInfoFrame(index: 1, name: 'Alpha', pskSeed: 10), + ); + await _settle(); + await Future.delayed(const Duration(milliseconds: 50)); + await _settle(); + + final slot0Texts = + (c.channelMessagesForTest[0] ?? const []) + .map((m) => m.text) + .toSet(); + expect( + slot0Texts, + containsAll({'beta history', 'live during sync'}), + reason: + 'the reload must merge with what the flush just filed, ' + 'not clobber it', + ); + }, + ); + + test( + 'outgoing send to an unconfirmed slot is refused, not orphaned', + () async { + final alpha = _channel(0, 'Alpha', 10); + final beta = _channel(1, 'Beta', 30); + c.seedCachedChannelsForTest([alpha, beta]); + + // Slot 0 confirms, slot 1 never does. + await c.getChannels(maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Alpha', pskSeed: 10), + ); + await _settle(2); + for (var i = 0; i <= 3; i++) { + c.handleChannelSyncTimeoutForTest(1); + await _settle(2); + } + await _settle(); + expect(c.unconfirmedChannelSlots, {1}); + expect(c.canSendOnChannel(0), isTrue); + expect(c.canSendOnChannel(1), isFalse); + + final sentFrames = []; + c.sendFrameOverrideForTest = sentFrames.add; + await c.sendChannelMessage(beta, 'must not be written'); + await _settle(); + + expect(sentFrames, isEmpty, reason: 'nothing may go to the radio'); + expect( + c.channelMessagesForTest[1] ?? const [], + isEmpty, + reason: + 'the refused message must not be filed (a persisted copy would ' + 'fall back to the legacy slot-index key and be orphaned)', + ); + }, + ); + + test( + 'held frames never cross radios; they flush when their radio returns', + () async { + // Radio X delivers a message before its list is confirmed; the frame is + // held. The user then connects radio Y: Y's sync must NOT flush X's frame + // into Y's conversations. When X reconnects and syncs, the frame files. + final radioX = Uint8List.fromList(List.generate(32, (i) => i)); + final radioY = Uint8List.fromList(List.generate(32, (i) => 99 + i)); + + c.handleFrameForTest( + _v3ChannelMsgFrame(channelIdx: 0, text: 'A: from X'), + ); + await _settle(); + + // Switch to radio Y and complete its sync. + c.resetConnectionHandshakeStateForTest(); + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(radioY); + c.wireMessageStoreForTest(); + await syncWith([_channel(0, 'Gamma', 70)]); + expect( + c.channelMessagesForTest[0] ?? const [], + isEmpty, + reason: "radio X's held frame must not file into radio Y's channel", + ); + + // Back to radio X: its held frame now files against its own list. + c.resetConnectionHandshakeStateForTest(); + c.setConnectedForTest(); + c.setSelfPublicKeyForTest(radioX); + c.wireMessageStoreForTest(); + await syncWith([_channel(0, 'Alpha', 10)]); + expect( + (c.channelMessagesForTest[0] ?? const []).map( + (m) => m.text, + ), + ['from X'], + ); + }, + ); } diff --git a/untranslated.json b/untranslated.json index ea2bfb1d..3af74f33 100644 --- a/untranslated.json +++ b/untranslated.json @@ -159,6 +159,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -502,6 +503,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -845,6 +847,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1188,6 +1191,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1531,6 +1535,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -1874,6 +1879,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2217,6 +2223,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2560,6 +2567,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -2903,6 +2911,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3246,6 +3255,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3589,6 +3599,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -3932,6 +3943,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4275,6 +4287,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4618,6 +4631,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -4961,6 +4975,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -5304,6 +5319,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", @@ -5647,6 +5663,7 @@ "channel_senderAlreadyContact", "channel_senderMultipleMatches", "channel_senderAddNotConnected", + "channel_slotUnconfirmedSendBlocked", "channel_senderAddFailed", "channel_senderCandidate", "map_alwaysShowNames", From 1169b365d5a1d9c24d4101eaaa7b51c5f274d7d1 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 01:01:51 -0500 Subject: [PATCH 07/16] feat(#1068): read radio modes on connect, and the Radio sound control Epics B3 and C of #544, so there is something testable on hardware. B3 reads the radio's mode for every reported slot, hooked to _cleanupChannelSync(completed: true). Deliberately only on completed: the failure branch restores a CACHED channel list, and addressing a slot from a cache is the guessed-slot error this must not make. When #1061 lands its stricter confirmed-list barrier this moves onto it. C adds 'Radio sound' as its OWN control beside the phone's notifications, on the Channels sheet and the channel chat menu, gated on caps2 0x80. The existing control is relabelled 'Phone notifications' so neither is mistaken for the other. Neither reads the other: that independence is pinned by the A2 tests. C3, the owner's call: the row shows what the channel will ACTUALLY do, not the stored byte. A set mode decides for itself; an unset one reads 'Follows the radio: '; and a device scope of None shows as silent even on a channel set to All, because telling a user with a muted radio that a channel is on 'All messages' is the confusion this feature exists to end. Null composes to a reading state, never to an invented mode. Proved that check can fail: removing the None-override branch fails the test that asserts it. Restored. Strings are English-only with untranslated.json regenerated, per the l10n rule. flutter analyze clean; full suite 1809 passed. --- lib/connector/meshcore_connector.dart | 21 +++ lib/l10n/app_en.arb | 14 +- lib/l10n/app_localizations.dart | 32 ++++- lib/l10n/app_localizations_bg.dart | 20 ++- lib/l10n/app_localizations_de.dart | 20 ++- lib/l10n/app_localizations_en.dart | 20 ++- lib/l10n/app_localizations_es.dart | 20 ++- lib/l10n/app_localizations_fr.dart | 20 ++- lib/l10n/app_localizations_hu.dart | 20 ++- lib/l10n/app_localizations_it.dart | 20 ++- lib/l10n/app_localizations_ja.dart | 20 ++- lib/l10n/app_localizations_ko.dart | 20 ++- lib/l10n/app_localizations_nl.dart | 20 ++- lib/l10n/app_localizations_pl.dart | 20 ++- lib/l10n/app_localizations_pt.dart | 20 ++- lib/l10n/app_localizations_ru.dart | 20 ++- lib/l10n/app_localizations_sk.dart | 20 ++- lib/l10n/app_localizations_sl.dart | 20 ++- lib/l10n/app_localizations_sv.dart | 20 ++- lib/l10n/app_localizations_uk.dart | 20 ++- lib/l10n/app_localizations_zh.dart | 20 ++- lib/screens/channel_chat_screen.dart | 19 +++ lib/screens/channels_screen.dart | 30 ++++ lib/widgets/radio_channel_notify.dart | 144 ++++++++++++++++++++ test/widgets/radio_channel_notify_test.dart | 117 ++++++++++++++++ untranslated.json | 85 ++++++++++++ 26 files changed, 802 insertions(+), 20 deletions(-) create mode 100644 lib/widgets/radio_channel_notify.dart create mode 100644 test/widgets/radio_channel_notify_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 38289a74..ca4a9ea0 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -6470,6 +6470,20 @@ class MeshCoreConnector extends ChangeNotifier { ); } + /// Read the radio's own notify mode for every channel slot it reported + /// (#544 B3). One GET per slot, on the shipped one-entry-per-frame pattern. + /// + /// Only reached on a completed sync, so every slot here is one the device + /// answered for. A channel the radio never reported is simply not in + /// [_channels] and is therefore never addressed. + Future _readChannelNotifyModes() async { + if (!supportsChannelNotify) return; + for (final channel in List.from(_channels)) { + if (!isConnected) return; + await requestChannelNotify(channel.index); + } + } + void _cleanupChannelSync({required bool completed}) { _isSyncingChannels = false; _channelSyncInFlight = false; @@ -6492,6 +6506,13 @@ class MeshCoreConnector extends ChangeNotifier { if (isConnected) { _startPostChannelInitialQueuedMessageSync(); + // #544 B3: the radio's per-channel notify modes are keyed by slot, so + // they can only be read once the device has actually answered for the + // slots. Deliberately only on `completed`: the failure branch above + // restores a CACHED list, and addressing a slot from a cache is the + // guessed-slot error this must not make. When #1061 lands its stricter + // confirmed-list barrier, this moves onto it. + if (completed) unawaited(_readChannelNotifyModes()); } // Keep cache on failure/disconnection for future attempts diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 8960c537..be340ac7 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -858,10 +858,22 @@ "channels_editChannel": "Edit channel", "channels_muteChannel": "Mute channel", "channels_unmuteChannel": "Unmute channel", - "channels_notifications": "Notifications", + "channels_notifications": "Phone notifications", "channels_notifyAll": "All messages", "channels_notifyMentionsOnly": "Mentions only", "channels_notifyOff": "Off", + "channels_radioSound": "Radio sound", + "channels_radioSoundUnset": "Not set", + "channels_radioSoundFollows": "Follows the radio: {scope}", + "@channels_radioSoundFollows": { + "placeholders": { + "scope": { + "type": "String" + } + } + }, + "channels_radioSoundMutedByRadio": "Silent: the radio is set to None", + "channels_radioSoundReading": "Reading from the radio", "channels_deleteChannel": "Delete channel", "channels_deleteChannelConfirm": "Delete \"{name}\"? This cannot be undone.", "@channels_deleteChannelConfirm": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index c8b31e00..b061775b 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2869,7 +2869,7 @@ abstract class AppLocalizations { /// No description provided for @channels_notifications. /// /// In en, this message translates to: - /// **'Notifications'** + /// **'Phone notifications'** String get channels_notifications; /// No description provided for @channels_notifyAll. @@ -2890,6 +2890,36 @@ abstract class AppLocalizations { /// **'Off'** String get channels_notifyOff; + /// No description provided for @channels_radioSound. + /// + /// In en, this message translates to: + /// **'Radio sound'** + String get channels_radioSound; + + /// No description provided for @channels_radioSoundUnset. + /// + /// In en, this message translates to: + /// **'Not set'** + String get channels_radioSoundUnset; + + /// No description provided for @channels_radioSoundFollows. + /// + /// In en, this message translates to: + /// **'Follows the radio: {scope}'** + String channels_radioSoundFollows(String scope); + + /// No description provided for @channels_radioSoundMutedByRadio. + /// + /// In en, this message translates to: + /// **'Silent: the radio is set to None'** + String get channels_radioSoundMutedByRadio; + + /// No description provided for @channels_radioSoundReading. + /// + /// In en, this message translates to: + /// **'Reading from the radio'** + String get channels_radioSoundReading; + /// No description provided for @channels_deleteChannel. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 4aef2fb4..65cc9fbb 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1608,7 +1608,7 @@ class AppLocalizationsBg extends AppLocalizations { String get channels_unmuteChannel => 'Включи известията на канала'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1619,6 +1619,24 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Изтрий канала'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 2b8d59ac..732a26e3 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1602,7 +1602,7 @@ class AppLocalizationsDe extends AppLocalizations { String get channels_unmuteChannel => 'Kanal Stummschaltung aufheben'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1613,6 +1613,24 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Lösche den Kanal'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 05136266..8d3bff4e 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1584,7 +1584,7 @@ class AppLocalizationsEn extends AppLocalizations { String get channels_unmuteChannel => 'Unmute channel'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1595,6 +1595,24 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Delete channel'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index be9d4a3e..c4a19620 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1603,7 +1603,7 @@ class AppLocalizationsEs extends AppLocalizations { String get channels_unmuteChannel => 'Activar canal'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1614,6 +1614,24 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Eliminar canal'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 6738f5f9..170e0bc0 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1608,7 +1608,7 @@ class AppLocalizationsFr extends AppLocalizations { String get channels_unmuteChannel => 'Réactiver les notifications du canal'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1619,6 +1619,24 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Supprimer le canal'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index e5bd2129..08122a82 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1609,7 +1609,7 @@ class AppLocalizationsHu extends AppLocalizations { String get channels_unmuteChannel => 'Engedje be a hangot'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1620,6 +1620,24 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Mozdony törlése'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index b1978d2b..8cc13f71 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1604,7 +1604,7 @@ class AppLocalizationsIt extends AppLocalizations { String get channels_unmuteChannel => 'Attiva notifiche canale'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1615,6 +1615,24 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Elimina canale'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index c5638629..2fc6f205 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1552,7 +1552,7 @@ class AppLocalizationsJa extends AppLocalizations { String get channels_unmuteChannel => 'ミュートを解除する'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1563,6 +1563,24 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'チャンネルを削除する'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index eef52521..c74ccf98 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1547,7 +1547,7 @@ class AppLocalizationsKo extends AppLocalizations { String get channels_unmuteChannel => '채널 음소거 해제'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1558,6 +1558,24 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => '채널 삭제'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index b3f00605..0a00669a 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1595,7 +1595,7 @@ class AppLocalizationsNl extends AppLocalizations { String get channels_unmuteChannel => 'Kanaal dempen opheffen'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1606,6 +1606,24 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Kanaal verwijderen'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b1962d3b..bc349e1a 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1614,7 +1614,7 @@ class AppLocalizationsPl extends AppLocalizations { String get channels_unmuteChannel => 'Wyłącz wyciszenie kanału'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1625,6 +1625,24 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Usuń kanał'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index b3b57b10..a0cce3d0 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1604,7 +1604,7 @@ class AppLocalizationsPt extends AppLocalizations { String get channels_unmuteChannel => 'Ativar canal'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1615,6 +1615,24 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Excluir canal'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 6748532e..9ad5b3e6 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1605,7 +1605,7 @@ class AppLocalizationsRu extends AppLocalizations { String get channels_unmuteChannel => 'Включить уведомления канала'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1616,6 +1616,24 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Удалить канал'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 0d7e01ce..a52e9128 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1595,7 +1595,7 @@ class AppLocalizationsSk extends AppLocalizations { String get channels_unmuteChannel => 'Zrušiť stlmenie kanála'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1606,6 +1606,24 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Odstrániť kanál'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e90ee0f6..55bfe015 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1592,7 +1592,7 @@ class AppLocalizationsSl extends AppLocalizations { String get channels_unmuteChannel => 'Vklopi obvestila kanala'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1603,6 +1603,24 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Pošlji kanal'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index f395a517..971e262e 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1586,7 +1586,7 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_unmuteChannel => 'Slå på ljud för kanal'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1597,6 +1597,24 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Ta bort kanal'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index c9ec29de..80a6d174 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1600,7 +1600,7 @@ class AppLocalizationsUk extends AppLocalizations { String get channels_unmuteChannel => 'Увімкнути сповіщення каналу'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1611,6 +1611,24 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => 'Видалити канал'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a397f517..09c8cb07 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1533,7 +1533,7 @@ class AppLocalizationsZh extends AppLocalizations { String get channels_unmuteChannel => '取消静音频道'; @override - String get channels_notifications => 'Notifications'; + String get channels_notifications => 'Phone notifications'; @override String get channels_notifyAll => 'All messages'; @@ -1544,6 +1544,24 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_notifyOff => 'Off'; + @override + String get channels_radioSound => 'Radio sound'; + + @override + String get channels_radioSoundUnset => 'Not set'; + + @override + String channels_radioSoundFollows(String scope) { + return 'Follows the radio: $scope'; + } + + @override + String get channels_radioSoundMutedByRadio => + 'Silent: the radio is set to None'; + + @override + String get channels_radioSoundReading => 'Reading from the radio'; + @override String get channels_deleteChannel => '删除频道'; diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index dd2cfbf4..5eb4c37b 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -31,6 +31,7 @@ import '../services/corescope_service.dart'; import '../services/region_discovery_service.dart'; import '../widgets/channel_region_scope_dialog.dart'; import '../widgets/channel_notify_mode.dart'; +import '../widgets/radio_channel_notify.dart'; import '../widgets/radio_tone.dart'; import '../services/block_service.dart'; import '../services/chat_text_scale_service.dart'; @@ -474,6 +475,8 @@ class _ChannelChatScreenState extends State { onSelected: (value) { if (value == 'notifications') { showChannelNotifyModeDialog(context, widget.channel); + } else if (value == 'radioSound') { + showRadioChannelNotifyDialog(context, _currentChannel); } else if (value == 'radioTone') { final connector = context.read(); requestChannelRadioTone(connector, _currentChannel.index); @@ -507,6 +510,22 @@ class _ChannelChatScreenState extends State { ], ), ), + // #544: the RADIO's sound for this channel. Separate from + // Notifications above, which is the phone's; the two are + // independent settings and neither reads the other. + if (radioChannelNotifySupported( + context.read(), + )) + const PopupMenuItem( + value: 'radioSound', + child: Row( + children: [ + Icon(Icons.volume_up_outlined, size: 20), + SizedBox(width: 12), + Text('Radio sound'), + ], + ), + ), if (context.read().supportsTunes) const PopupMenuItem( value: 'radioTone', diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 1b2ec301..a6560fee 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -27,6 +27,7 @@ import '../widgets/channel_drawer_list.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/unread_badge.dart'; import '../widgets/channel_notify_mode.dart'; +import '../widgets/radio_channel_notify.dart'; import '../widgets/radio_tone.dart'; import '../widgets/battery_optimization_banner.dart'; import '../helpers/snack_bar_builder.dart'; @@ -535,6 +536,35 @@ class _ChannelsScreenState extends State } }, ), + // The radio's own sound setting for this channel (#544), named + // apart from Notifications, which is the phone's. These are two + // independent settings over two outputs: neither reads the other. + // Gated on caps byte 2 0x80. + if (radioChannelNotifySupported(context.read())) + Builder( + builder: (tileContext) { + final live = tileContext.watch(); + final effective = radioChannelNotifyEffective( + tileContext, + live.channelNotifyFor(channel.index), + live.deviceNotifyScope, + ); + return ListTile( + leading: const Icon(Icons.volume_up_outlined), + title: Text(tileContext.l10n.channels_radioSound), + subtitle: Text( + effective ?? tileContext.l10n.channels_radioSoundReading, + ), + onTap: () async { + Navigator.pop(sheetContext); + await Future.delayed(const Duration(milliseconds: 100)); + if (parentContext.mounted) { + showRadioChannelNotifyDialog(parentContext, channel); + } + }, + ); + }, + ), // The radio's own tone for this channel (#971), named apart from // Notifications, which is the phone's. Gated on caps byte 2 0x10. ChannelRadioToneTile( diff --git a/lib/widgets/radio_channel_notify.dart b/lib/widgets/radio_channel_notify.dart new file mode 100644 index 00000000..d976aac5 --- /dev/null +++ b/lib/widgets/radio_channel_notify.dart @@ -0,0 +1,144 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/offband_channel_notify.dart'; +import '../connector/offband_device_ui.dart'; +import '../l10n/l10n.dart'; +import '../models/channel.dart'; + +/// The RADIO's per-channel sound setting (#544). +/// +/// Deliberately a separate control from the app's per-channel notification +/// setting in `channel_notify_mode.dart`: that one decides whether the PHONE +/// notifies, this one decides whether the RADIO beeps, and neither reads the +/// other (owner, 2026-11-03). Do not merge them, and do not resolve one from +/// the other. + +IconData radioChannelNotifyIcon(RadioChannelNotify mode) { + switch (mode) { + case RadioChannelNotify.all: + return Icons.volume_up_outlined; + case RadioChannelNotify.mentions: + return Icons.alternate_email; + case RadioChannelNotify.off: + return Icons.volume_off_outlined; + case RadioChannelNotify.unset: + return Icons.settings_backup_restore; + } +} + +String radioChannelNotifyLabel(BuildContext context, RadioChannelNotify mode) { + switch (mode) { + case RadioChannelNotify.all: + return context.l10n.channels_notifyAll; + case RadioChannelNotify.mentions: + return context.l10n.channels_notifyMentionsOnly; + case RadioChannelNotify.off: + return context.l10n.channels_notifyOff; + case RadioChannelNotify.unset: + return context.l10n.channels_radioSoundUnset; + } +} + +/// What this channel will ACTUALLY do on the radio, which is not always the +/// stored byte (#544 C3, owner's call 2026-11-03). +/// +/// The radio's rules, per firmware: a channel with a mode set decides for +/// itself; a channel with no mode falls back to the device-wide scope; and a +/// device scope of None overrides even a channel that is set. Showing the raw +/// mode would tell a user with the radio muted that a channel is on "All +/// messages" while it sits silent. +/// +/// Null when the composition cannot be known: the mode has not been read, or +/// it is unset and the device scope has not been read either. A caller must +/// show "reading", never a guess. +String? radioChannelNotifyEffective( + BuildContext context, + RadioChannelNotify? mode, + DeviceNotifyScope? scope, +) { + if (mode == null) return null; + if (scope == DeviceNotifyScope.none) { + return context.l10n.channels_radioSoundMutedByRadio; + } + if (mode != RadioChannelNotify.unset) { + return radioChannelNotifyLabel(context, mode); + } + if (scope == null) return null; + return context.l10n.channels_radioSoundFollows(scope.label); +} + +/// Whether this radio can be offered the control at all. The app's own +/// per-channel setting is never gated on this. +bool radioChannelNotifySupported(MeshCoreConnector connector) => + connector.supportsChannelNotify; + +void showRadioChannelNotifyDialog(BuildContext context, Channel channel) { + final connector = context.read(); + + showDialog( + context: context, + builder: (dialogContext) => Consumer( + builder: (consumerContext, live, _) { + // State follows the radio's reply, never the tap: until the radio has + // answered for this slot there is no current value to tick, and a + // write that it refuses never appears as saved. + final current = live.channelNotifyFor(channel.index); + final error = live.deviceUiErrorSurface == DeviceUiSurface.channelNotify + ? live.deviceUiError + : null; + + return AlertDialog( + title: Text(consumerContext.l10n.channels_radioSound), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (error != null) + Padding( + padding: const EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text( + error, + style: TextStyle( + color: Theme.of(consumerContext).colorScheme.error, + ), + ), + ), + if (current == null) + ListTile( + leading: const SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2), + ), + title: Text(consumerContext.l10n.channels_radioSoundReading), + ), + for (final mode in RadioChannelNotify.values) + ListTile( + leading: Icon(radioChannelNotifyIcon(mode)), + title: Text(radioChannelNotifyLabel(consumerContext, mode)), + subtitle: mode == RadioChannelNotify.unset + ? Text( + radioChannelNotifyEffective( + consumerContext, + RadioChannelNotify.unset, + live.deviceNotifyScope, + ) ?? + consumerContext.l10n.channels_radioSoundReading, + ) + : null, + trailing: mode == current ? const Icon(Icons.check) : null, + onTap: () async { + Navigator.pop(dialogContext); + await connector.setChannelNotify(channel.index, mode); + }, + ), + ], + ), + ); + }, + ), + ); +} diff --git a/test/widgets/radio_channel_notify_test.dart b/test/widgets/radio_channel_notify_test.dart new file mode 100644 index 00000000..9b7b1abf --- /dev/null +++ b/test/widgets/radio_channel_notify_test.dart @@ -0,0 +1,117 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/offband_channel_notify.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/widgets/radio_channel_notify.dart'; + +/// #544 Epic C task C3: what a channel row says the RADIO will actually do. +/// +/// The owner's call (2026-11-03) was to show the composed result rather than +/// the raw stored byte. This pins the composition, because getting it wrong is +/// a lie to the user rather than a cosmetic slip: a muted radio showing a +/// channel as "All messages" is exactly the confusion this feature exists to +/// end. +/// +/// Firmware's rules, per AM 1406: a channel with a mode set decides for +/// itself; a channel with no mode falls back to the device-wide scope; a +/// device scope of None overrides even a channel that is set. +void main() { + /// Resolves [radioChannelNotifyEffective] inside a localized context. + Future effective( + WidgetTester tester, + RadioChannelNotify? mode, + DeviceNotifyScope? scope, + ) async { + String? result; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) { + result = radioChannelNotifyEffective(context, mode, scope); + return const SizedBox.shrink(); + }, + ), + ), + ); + await tester.pumpAndSettle(); + return result; + } + + testWidgets('a set mode decides for itself', (tester) async { + expect( + await effective(tester, RadioChannelNotify.all, DeviceNotifyScope.self), + 'All messages', + ); + expect( + await effective( + tester, + RadioChannelNotify.mentions, + DeviceNotifyScope.all, + ), + 'Mentions only', + ); + expect( + await effective(tester, RadioChannelNotify.off, DeviceNotifyScope.all), + 'Off', + ); + }); + + testWidgets('an unset mode follows the device scope, named', (tester) async { + expect( + await effective(tester, RadioChannelNotify.unset, DeviceNotifyScope.self), + 'Follows the radio: Self', + ); + expect( + await effective(tester, RadioChannelNotify.unset, DeviceNotifyScope.all), + 'Follows the radio: All', + ); + }); + + testWidgets('a device scope of None overrides even a set channel', ( + tester, + ) async { + // The case that makes this composition load-bearing. A user who has muted + // the radio must not be told a channel is on "All messages". + expect( + await effective(tester, RadioChannelNotify.all, DeviceNotifyScope.none), + 'Silent: the radio is set to None', + ); + expect( + await effective( + tester, + RadioChannelNotify.mentions, + DeviceNotifyScope.none, + ), + 'Silent: the radio is set to None', + ); + expect( + await effective(tester, RadioChannelNotify.unset, DeviceNotifyScope.none), + 'Silent: the radio is set to None', + ); + }); + + testWidgets('nothing is claimed before the radio has answered', ( + tester, + ) async { + // Null means "cannot be known yet", and the caller shows a reading state. + // It must never resolve to a mode we invented. + expect(await effective(tester, null, DeviceNotifyScope.all), isNull); + expect(await effective(tester, null, null), isNull); + expect( + await effective(tester, RadioChannelNotify.unset, null), + isNull, + reason: 'unset with an unknown scope composes to nothing truthful', + ); + }); + + testWidgets('a set mode resolves without the scope being known', ( + tester, + ) async { + // A channel that decides for itself does not need the device scope, so it + // is shown immediately rather than waiting on a second read. + expect(await effective(tester, RadioChannelNotify.off, null), 'Off'); + }); +} diff --git a/untranslated.json b/untranslated.json index eb4bc5a4..7058d9be 100644 --- a/untranslated.json +++ b/untranslated.json @@ -130,6 +130,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -469,6 +474,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -808,6 +818,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1147,6 +1162,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1486,6 +1506,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -1825,6 +1850,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2164,6 +2194,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2503,6 +2538,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -2842,6 +2882,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3181,6 +3226,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3520,6 +3570,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -3859,6 +3914,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4198,6 +4258,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4537,6 +4602,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -4876,6 +4946,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5215,6 +5290,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", @@ -5554,6 +5634,11 @@ "channels_notifyAll", "channels_notifyMentionsOnly", "channels_notifyOff", + "channels_radioSound", + "channels_radioSoundUnset", + "channels_radioSoundFollows", + "channels_radioSoundMutedByRadio", + "channels_radioSoundReading", "composerBudgetBlockedTitle", "composerBudgetLimitedTitle", "composerBudgetBluetoothCause", From 5dc968ee5bb7aa9a7b2ca9e32baeeb9aa39f48d6 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:00:27 -0500 Subject: [PATCH 08/16] feat(#1095): the 0xC5 0x1C capability advert, and nothing at offset 87 Realigns the client to the merged contract. Firmware docs/offband_info_frame_contract.md revision 2 and OffbandConfigProtocol.h, both on firmware-base; the header is the registry and wins on any disagreement. Wire numbers claimed by firmware PR #2000, merged 28785ebf at 2026-11-04 08:34:29Z. Nothing here was built before that merge, per contract section 2. Three features each computed "the next free byte" of upstream's device-info frame as 87 and each was right in isolation. A collision at a frame offset is silent misparsing, not a refused command: everything compiles, every test passes, and it only shows up on hardware as one feature appearing broken. #1095 the advert client #1096 offset 87 removed, with a guard #1097 channel notify re-gated One request on connect, zero payload, after device-info has landed and so well past MTU negotiation. The client asks and the device never pushes: _att_mtu is 23 until onMTUChange fires, so a pushed advert would be truncated to a 20-byte payload as the normal case. A tag's presence IS the capability. No bitmap, no probing each feature's sub-code. len 0 means supported with nothing to report; an absent tag means the board lacks the feature and is neither an error nor a zero value. Unknown tags are kept and skipped by len, because a client built tonight has to stay correct against firmware emitting tags it has never heard of. TAG_CONTINUE is honoured, bounded at 8 rounds and refused a cursor that does not advance: an unbounded request loop driven by device data is worse than a truncated capability list. [0xC5][0x7F][0x05] to the zero-payload request means the radio predates the advert, so capabilities fall back to the device-info offsets that shipped before it. That reason is overloaded on firmware (malformed payload on a known sub-code returns it too), which is exactly why the request carries no payload. The refusal names no sub-code, so it is claimed only while an advert request is outstanding AND no write is: a write owns its own refusal. Channel notify gating is PRECEDENCE, not OR, and this part needed a ruling. Both caps2 0x80 and TAG_CHAN_NOTIFY are merged claims and the contract does not say which wins. Both single-source readings break on a real radio: tag-only takes the control away from 4e5a6c85, already flashed on the T1000-E, which has the bit and predates 0x1C; bit-only loses the control when the bit is retired under contract section 4. So an advert, once it arrives, is authoritative and the bit is ignored, and with no advert the bit answers, which is what shipped before. Raised with FuchsiaCreek before coding rather than worked around (Agent Mail 1449); one expression to invert if the ruling differs. Rotation and ACK capacity gain their gates here but not their features: #1098 and #1099 follow. Rotation is tag-gated with no caps-bit fallback, deliberately -- 0x1A/0x1B were claimed in the same merge as the advert, so no firmware can rotate but not advertise -- and explicitly NOT on caps2 0x04 INDICATORS, which means something else. parseOffbandCaps3, offbandCaps3Offset and offbandCaps3MinFrameLength are gone rather than left unused, so a later change cannot pick them back up. The replacement is behavioural: a device-info frame with every bit set at offset 87 must produce identical capability answers to one that has no byte 87 at all, the raw caps byte included. The getter list alone was a hole -- a leak into a bit with no getter yet moved nothing the test could see -- found by planting such a read and watching the test pass, then comparing the raw byte as well. Each new guard was made to fail before being trusted: the unknown-tag skip (parser dropping unknown tags, 2 red), the precedence rule (gate rewritten as an OR, 1 red), the offset-87 guard (a read reintroduced, 1 red after the strengthening above). flutter analyze clean. 1869 tests pass. Co-Authored-By: Claude Opus 5 --- lib/connector/meshcore_connector.dart | 249 +++++++++++-- lib/connector/meshcore_protocol.dart | 27 +- lib/connector/offband_capability_advert.dart | 203 ++++++++++ .../channel_notify_connector_test.dart | 252 +++++++++++-- .../offband_capability_advert_test.dart | 350 ++++++++++++++++++ .../offband_subcode_registry_test.dart | 188 ++++++++++ 6 files changed, 1195 insertions(+), 74 deletions(-) create mode 100644 lib/connector/offband_capability_advert.dart create mode 100644 test/connector/offband_capability_advert_test.dart create mode 100644 test/connector/offband_subcode_registry_test.dart diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index fb915d65..6f8c1500 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -66,6 +66,7 @@ import 'device_population.dart'; import 'meshcore_protocol.dart'; import '../helpers/region_key.dart'; import '../storage/channel_region_scope_store.dart'; +import 'offband_capability_advert.dart'; import 'offband_channel_notify.dart'; import 'offband_device_ui.dart'; import 'offband_screen_settings.dart'; @@ -420,8 +421,24 @@ class MeshCoreConnector extends ChangeNotifier { Classification? _classification; int? _offbandCaps2; - int? _offbandCaps3; bool? _femLnaEnabled; + + /// The `0xC5` `0x1C` capability advert for THIS radio (#1095). + /// + /// Tags accumulate across `TAG_CONTINUE` rounds, so this is the merged view + /// and not just the last frame. Null until a reply arrives. + OffbandCapabilityAdvert? _capabilityAdvert; + CapabilityAdvertState _advertState = CapabilityAdvertState.unknown; + + /// A zero-payload `0x1C` request is in flight. + /// + /// Needed because `[0xC5][0x7F][0x05]` names no sub-code. The refusal is + /// claimed as "this radio predates the advert" only while this is set and no + /// device-UI WRITE is outstanding, so an error belonging to a write is never + /// stolen from it. + bool _advertRequestOutstanding = false; + int _advertContinuationRound = 0; + final Map _advertTags = {}; ButtonMatrix? _buttonMatrix; String? _lastDeviceUiSuppression; DeviceNotifyScope? _deviceNotifyScope; @@ -983,16 +1000,60 @@ class MeshCoreConnector extends ChangeNotifier { /// an error: every radio predating #508 reports null here. (#480) int? get offbandCaps2 => _offbandCaps2; - /// Third `offband_caps` bitfield (frame offset 87, #544). Null when the frame - /// is too short, which means "no byte-3 capabilities" and is never an error. - /// No bit is allocated from it yet; byte 2 filled up at `0x80`. - int? get offbandCaps3 => _offbandCaps3; + /// This radio's capability advert, merged across continuation rounds (#1095). + /// Null until a `0x1C` reply arrives; see [capabilityAdvertState] to tell + /// "has not answered" apart from "does not have the mechanism". + OffbandCapabilityAdvert? get capabilityAdvert => _capabilityAdvert; + + /// How far the advert handshake has got with this radio. + CapabilityAdvertState get capabilityAdvertState => _advertState; /// Whether this radio stores a per-channel notify mode for its own buzzer - /// (#544). Says nothing about the app's per-channel notify setting, which is - /// independent and needs no radio. - bool get supportsChannelNotify => - firmwareSupportsChannelNotify(_offbandCaps2); + /// (#544, #1097). Says nothing about the app's per-channel notify setting, + /// which is independent and needs no radio. + /// + /// PRECEDENCE, not OR. Channel notify has two merged claims: caps2 `0x80` + /// and `TAG_CHAN_NOTIFY`. The contract does not state which wins, and both + /// single-source readings break on a real radio: + /// + /// - bit only: when the bit is retired under contract §4 ("their bits become + /// tags and the bits are retired in the same change"), a radio advertising + /// the tag with `0x80` clear would silently lose the control. + /// - tag only: firmware `4e5a6c85` has channel notify and caps2 `0x80` but + /// predates `0x1C` entirely, so the already-flashed T1000-E would lose it. + /// + /// So an advert, once it arrives, is authoritative and the bit is ignored; + /// with no advert the bit answers, which is exactly the behaviour that + /// shipped before `0x1C` existed. Raised with FuchsiaCreek before coding + /// (Agent Mail 1449); one expression to invert if the ruling differs. + /// + /// While a request is still in flight the bit answers, so nothing regresses + /// in the window before the reply. A radio that sets the bit and omits the + /// tag is self-inconsistent and will flip the control off when the advert + /// lands, which is the correct reading of a firmware fault. + bool get supportsChannelNotify { + final advert = _capabilityAdvert; + if (advert != null) return advert.has(offbandInfoTagChanNotify); + return firmwareSupportsChannelNotify(_offbandCaps2); + } + + /// Whether this radio's display can rotate (#1098, firmware #1990). + /// + /// Tag-gated ONLY, with no caps-bit fallback, and that is not an oversight: + /// rotation's sub-codes `0x1A`/`0x1B` were claimed in the same merge as the + /// advert itself, so no firmware exists that can rotate but cannot advertise. + /// It is deliberately NOT gated on caps2 `0x04` INDICATORS, which means + /// indicators and is a different capability. + bool get supportsDisplayRotation => + _capabilityAdvert?.has(offbandInfoTagDisplayRotation) ?? false; + + /// Outstanding-ACK capacity this radio reports (#1099, firmware #994/#1001). + /// + /// Carried in the advert by the contract §3 exception: one byte, fixed for + /// the build, no sub-code of its own. Null means the radio did not say, which + /// is not zero and is not an error. + int? get ackCapacity => + _capabilityAdvert?.byteValue(offbandInfoTagAckCapacity); /// Whether this radio exposes a configurable button-action matrix (#474). bool get supportsButtonMatrix => firmwareSupportsButtonMatrix(_offbandCaps2); @@ -1211,6 +1272,115 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildChannelTuneSetFrame(channel, tune)); } + /// Ask this radio for its capability advert (#1095). + /// + /// One request per connect, sent from [_reconcileDeviceUi] once device-info + /// has landed, which is well past MTU negotiation. The client asks and the + /// device never pushes: `_att_mtu` is 23 until `onMTUChange` fires, so a + /// pushed advert would be truncated to a 20-byte payload as the NORMAL case. + /// + /// Not gated on [deviceUiCommandLanded]-style capability checks, because + /// this request is how capabilities become known. + Future requestCapabilityAdvert() async { + if (!deviceUiCommandLanded) return; + if (!isConnected) return; + _advertRequestOutstanding = true; + _appDebugLogService?.info( + 'advert GET -> [0xC5][0x1C] (zero payload)', + tag: 'DeviceUI', + ); + await sendFrame(buildCapabilityAdvertRequestFrame()); + } + + /// Continue a paged advert from [cursor]. + Future _requestCapabilityAdvertFrom(int cursor) async { + if (!isConnected) return; + _advertRequestOutstanding = true; + _appDebugLogService?.info( + 'advert GET -> [0xC5][0x1C][0x${cursor.toRadixString(16).padLeft(2, '0')}] ' + '(continuation $_advertContinuationRound)', + tag: 'DeviceUI', + ); + await sendFrame(buildCapabilityAdvertResumeFrame(cursor)); + } + + void _handleCapabilityAdvertReply(OffbandCapabilityAdvert advert) { + _advertRequestOutstanding = false; + if (advert.malformed) { + // Firmware must not split a record across frames, so this is a firmware + // fault. The records before the bad one are kept: a hidden feature is + // safe, discarding a whole good reply over one trailing byte is not. + _appDebugLogService?.warn( + 'advert reply malformed, keeping the records before it: $advert', + tag: 'DeviceUI', + ); + } + for (final entry in advert.tags.entries) { + _advertTags.putIfAbsent(entry.key, () => entry.value); + } + + final cursor = advert.continueCursor; + if (cursor != null) { + _advertContinuationRound++; + if (_advertContinuationRound > offbandInfoMaxContinuations) { + // Bounded on purpose: an unbounded request loop driven by device data + // is a worse failure than a truncated capability list. + _appDebugLogService?.warn( + 'advert continuation exceeded $offbandInfoMaxContinuations rounds, ' + 'settling on ${_advertTags.length} tag(s)', + tag: 'DeviceUI', + ); + } else if (_advertTags.containsKey(cursor)) { + // A cursor pointing at a tag already in hand would loop forever. + _appDebugLogService?.warn( + 'advert continuation cursor 0x${cursor.toRadixString(16).padLeft(2, '0')} ' + 'does not advance, settling on ${_advertTags.length} tag(s)', + tag: 'DeviceUI', + ); + } else { + unawaited(_requestCapabilityAdvertFrom(cursor)); + return; + } + } + + _settleCapabilityAdvert( + OffbandCapabilityAdvert(tags: Map.from(_advertTags)), + ); + } + + /// The advert is now known, either as tags or as "this radio predates it". + /// + /// Capability-gated surfaces are invisible when a gate is shut, which looks + /// exactly like a bug, so the resolved gates are logged alongside the raw + /// tags (the same reasoning as the caps logging in [_handleDeviceInfo]). + void _settleCapabilityAdvert(OffbandCapabilityAdvert? advert) { + _capabilityAdvert = advert; + _advertState = advert == null + ? CapabilityAdvertState.unsupported + : CapabilityAdvertState.advertised; + _appDebugLogService?.info( + 'advert settled: ' + '${advert ?? 'UNSUPPORTED, falling back to device-info offsets'}' + ' chanNotify=$supportsChannelNotify' + ' rotation=$supportsDisplayRotation' + ' ackCapacity=${ackCapacity ?? 'absent'}', + tag: 'DeviceUI', + ); + // A tag-gated feature could not be asked for before now. + _reconcileAdvertisedDeviceUi(); + notifyListeners(); + } + + /// Requests that could only be gated once the advert settled. + /// + /// Channel notify is re-driven here because its gate can change when the + /// advert lands, and its read is additionally held behind the confirmed + /// channel list; [_readChannelNotifyModes] enforces that barrier itself, so + /// calling it before the list is synced is a no-op rather than a guess. + void _reconcileAdvertisedDeviceUi() { + unawaited(_readChannelNotifyModes()); + } + /// Ask the radio which notify mode [channel] has for its own buzzer (#544). /// /// Nothing here touches the app's per-channel notify setting: that drives @@ -1593,9 +1763,18 @@ class MeshCoreConnector extends ChangeNotifier { _eventTones.clear(); _tuneSlots.clear(); _screenSettings = null; + _capabilityAdvert = null; + _advertState = CapabilityAdvertState.unknown; + _advertRequestOutstanding = false; + _advertContinuationRound = 0; + _advertTags.clear(); } void _reconcileDeviceUi() { + // The advert goes FIRST and is gated on nothing: it is the mechanism by + // which capabilities are discovered, so gating it on a capability would be + // circular. Everything tag-gated is (re)driven from the reply. + unawaited(requestCapabilityAdvert()); if (supportsButtonMatrix) requestButtonMatrix(); if (supportsNotifyScope) requestNotifyScope(); if (supportsGpsMode) requestGpsMode(); @@ -1620,6 +1799,11 @@ class MeshCoreConnector extends ChangeNotifier { _handleNotifyScopeReply(scope); return; } + final advert = parseCapabilityAdvertReply(frame); + if (advert != null) { + _handleCapabilityAdvertReply(advert); + return; + } final gps = parseGpsModeReply(frame); if (gps != null) { _handleGpsModeReply(gps); @@ -1660,6 +1844,18 @@ class MeshCoreConnector extends ChangeNotifier { /// write outstanding when it arrived; a refusal with none is still shown and /// logged, just not claimed by any one screen. void _handleDeviceUiError(OffbandUiReply reply) { + // A refusal of our zero-payload 0x1C request means this radio predates the + // advert, which is the NORMAL case for everything shipped so far and not a + // failure to show anyone. The frame names no sub-code, so it is claimed + // here only while an advert request is outstanding AND no write is: a write + // owns its own refusal, and stealing one would hide a real error. + if (_advertRequestOutstanding && + _pendingDeviceUiWrite == null && + reply.errorCode == offbandUiErrReasonMalformed) { + _advertRequestOutstanding = false; + _settleCapabilityAdvert(null); + return; + } final surface = _pendingDeviceUiWrite; _pendingDeviceUiWrite = null; _deviceUiErrorSurface = surface; @@ -4592,8 +4788,14 @@ class MeshCoreConnector extends ChangeNotifier { // until the next device-info lands (Gemini review, task #876). _offbandCaps = null; _offbandCaps2 = null; - _offbandCaps3 = null; _femLnaEnabled = null; + // The advert dies with the connection for the same reason, so the next + // radio is never gated on this one's tags (#1095). + _capabilityAdvert = null; + _advertState = CapabilityAdvertState.unknown; + _advertRequestOutstanding = false; + _advertContinuationRound = 0; + _advertTags.clear(); _blockListRetryTimer?.cancel(); // Per-connection debounce timers must die with the connection so a timer // scheduled against this radio can't fire against the next one (#838 review). @@ -8223,21 +8425,12 @@ class MeshCoreConnector extends ChangeNotifier { static int? parseOffbandCaps2(Uint8List frame) => frame.length >= 85 ? frame[84] : null; - /// Third `offband_caps` byte, at frame offset **87** (#544). - /// - /// Byte 2 filled up when the per-channel notify bit took `0x80`, so firmware - /// appends a third. It sits at 87 and NOT at 85, because 85 and 86 are - /// already `ui_led_enabled` and `ui_display_mode`: the same fixed-absolute - /// offset rule that put byte 2 at 84 rather than beside byte 1. Reading 85 - /// as byte 3 would parse the LED state as a capability bitmask. - /// - /// Null on any firmware sending a shorter frame, which means "no byte-3 - /// capabilities" and is never an error. Length-gated, never version-gated - /// (#1065). No bit is allocated from it yet. - static int? parseOffbandCaps3(Uint8List frame) => - frame.length >= offbandCaps3MinFrameLength - ? frame[offbandCaps3Offset] - : null; + // There is NO caps byte 3, and there will not be one. A third capability + // byte would have to be appended to upstream's device-info frame, which + // contract §2 forbids permanently: three features each computed offset 87 as + // "the next free byte" and each was right in isolation. Capabilities past + // caps2 `0x80` are TAGS in the `0xC5` `0x1C` advert, which cannot run out. + // (#1096; the removed reader was `parseOffbandCaps3` at offset 87.) void _handleDeviceInfo(Uint8List frame) { if (frame.length < 4) return; @@ -8308,14 +8501,12 @@ class MeshCoreConnector extends ChangeNotifier { _femLnaEnabled = parseFemLnaState(frame); // Second caps byte rides at offset 84, past the FEM state byte (#480). _offbandCaps2 = parseOffbandCaps2(frame); - // Third caps byte at offset 87, past ui_led_enabled (85) and - // ui_display_mode (86). Byte 2 filled up at 0x80 (#544). - _offbandCaps3 = parseOffbandCaps3(frame); + // Nothing is read past byte 84 here. Offset 87 is where three features + // collided; capabilities beyond caps2 live in the 0x1C advert (#1096). } else { _offbandCaps = null; _femLnaEnabled = null; _offbandCaps2 = null; - _offbandCaps3 = null; } // Capability-gated features are invisible when a bit is clear, which looks // identical to a bug. Log the raw inputs so "the toggle didn't appear" can diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index dd5d1fba..28cf1bb0 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -653,23 +653,20 @@ const int offbandCap2ScreenSettings = 0x40; /// meshcore-firmware#606). Firmware sets it where `PIN_BUZZER` is defined, so /// it is a per-unit answer: gate on the BIT, never on model or version. /// -/// This is the LAST bit in caps byte 2. The change that spends it adds caps -/// **byte 3** at device-info offset 87 ([parseOffbandCaps3Offset]); anything -/// after this takes a bit from there. -const int offbandCap2ChannelNotify = 0x80; - -/// Device-info offset of `offband_caps` BYTE 3, and the minimum frame length -/// that carries it. +/// This is the LAST bit in caps byte 2, and there is NO byte 3. /// -/// **87, not 85.** Firmware writes caps byte 2 at 84, then `ui_led_enabled` at -/// 85 and `ui_display_mode` at 86 (`MyMesh.cpp` device-info builder). Reading -/// byte 3 at 85 would parse the LED state as a capability bitmask, which is -/// the exact mistake firmware's own comment warns about for byte 2. +/// A third capability byte would have to be appended to upstream's device-info +/// frame, which firmware `docs/offband_info_frame_contract.md` §2 forbids +/// permanently: three features each computed "the next free byte" as offset 87 +/// and each was right in isolation, and a collision at a frame offset is silent +/// misparsing rather than a refused command. Capabilities after this bit are +/// TAGS in the `0xC5` `0x1C` advert (`offband_capability_advert.dart`), which +/// has no scarcity to run out of. /// -/// Length-gated, never version-gated (#1065): absence means no byte-3 -/// capabilities, and is never an error. -const int offbandCaps3Offset = 87; -const int offbandCaps3MinFrameLength = 88; +/// This bit itself is NOT the gate once a radio answers the advert: see +/// `MeshCoreConnector.supportsChannelNotify` for the precedence, which exists +/// because `4e5a6c85` carries this bit and predates the advert. (#1096, #1097) +const int offbandCap2ChannelNotify = 0x80; /// True iff this radio answers the `0xC5` tune sub-codes. bool firmwareSupportsTunes(int? offbandCaps2) => diff --git a/lib/connector/offband_capability_advert.dart b/lib/connector/offband_capability_advert.dart new file mode 100644 index 00000000..48c8a04d --- /dev/null +++ b/lib/connector/offband_capability_advert.dart @@ -0,0 +1,203 @@ +import 'dart:typed_data'; + +import 'offband_device_ui.dart'; + +/// The `0xC5` `0x1C` capability advert (#1095, firmware #1994). +/// +/// Replaces the practice of appending Offband capability bytes to upstream's +/// `RESP_CODE_DEVICE_INFO` frame. Three features each computed "the next free +/// byte" as **87** and each was right in isolation, and a collision at a frame +/// offset is silent misparsing rather than a refused command. Two permanent +/// rules came out of that (firmware `docs/offband_info_frame_contract.md` §2): +/// no Offband field is ever added to upstream's frame again, and a number is +/// claimed by merge before any work begins. +/// +/// THE AUTHORITY for every number here is firmware +/// `examples/companion_radio/OffbandConfigProtocol.h`, merged to +/// `firmware-base` in PR OffbandMesh/meshcore-firmware#2000 (`28785ebf`, +/// 2026-11-04). The contract's §5 table is a convenience copy and the header +/// wins on any disagreement. Do not take a number from an Agent Mail message: +/// that habit is what caused the collision. +const int offbandUiInfoGet = 0x1C; + +/// A tag's PRESENCE is the capability. There is no capability bitmap in this +/// frame: tags already answer "is this supported", so a bitmap beside them +/// would be a second source of truth for one question (the defect removed from +/// contract revision 1). +/// +/// - `len = 0` means "I have this feature, nothing to report". The normal case. +/// - `len > 0` only where the value is one or two bytes, fixed for the build, +/// and has no sub-code of its own. Everything else is read with its own GET. +/// - **Absent** means the board does not have the feature. Not an error, and +/// not a zero value. +const int offbandInfoTagChanNotify = 0x01; +const int offbandInfoTagDisplayRotation = 0x02; +const int offbandInfoTagAckCapacity = 0x03; +const int offbandInfoTagContinue = 0xFF; + +/// `0x00` is not a valid tag. +const int _invalidTag = 0x00; + +/// Firmware `OFFBAND_UI_ERR_MALFORMED = 5`. +/// +/// The `0xC5` handler returns this reason for BOTH a malformed payload on a +/// known sub-code and a sub-code it does not implement at all. That overload is +/// the entire reason the advert request must carry zero payload: with no +/// payload there is nothing to be malformed, so the answer can only mean the +/// radio does not implement `0x1C`. +const int offbandUiErrReasonMalformed = 0x05; + +/// Ceiling on continuation rounds. The advert is a handful of bytes today and +/// no shipping firmware can overflow it, so any long chain is a firmware fault +/// rather than a large reply. Bounded because an unbounded request loop driven +/// by device data is a worse failure than a truncated capability list. +const int offbandInfoMaxContinuations = 8; + +/// Request the whole advert. **Zero payload, deliberately.** +/// +/// A `[0xC5][0x7F][0x05]` answer to a zero-payload request is unambiguous: +/// reason 5 is also what a KNOWN sub-code returns for a malformed payload, so +/// a request carrying bytes could not be told apart from a device that simply +/// predates the advert. +Uint8List buildCapabilityAdvertRequestFrame() => + Uint8List.fromList([cmdOffbandDeviceUi, offbandUiInfoGet]); + +/// Resume from [cursor], which is the value `TAG_CONTINUE` carried. +Uint8List buildCapabilityAdvertResumeFrame(int cursor) { + if (cursor < 0 || cursor > 0xFF) { + throw ArgumentError.value(cursor, 'cursor', 'must be 0 to 255'); + } + return Uint8List.fromList([cmdOffbandDeviceUi, offbandUiInfoGet, cursor]); +} + +/// One `0xC5` `0x1C` reply, parsed. +class OffbandCapabilityAdvert { + const OffbandCapabilityAdvert({ + required this.tags, + this.continueCursor, + this.malformed = false, + }); + + /// Tag to value. An empty value is the `len = 0` case and still means + /// supported, so membership is the question to ask, never emptiness. + final Map tags; + + /// Non-null when the reply ended in `TAG_CONTINUE`: re-request with this as + /// the cursor. A reply without it is complete. + final int? continueCursor; + + /// A record was unparseable and parsing stopped there. The tags BEFORE it are + /// still returned, because capability absence is safe (the feature hides) + /// while discarding a whole good reply over a bad trailing byte is not. + /// + /// Firmware must not split a record across frames, so this is a firmware + /// fault and worth logging rather than swallowing. + final bool malformed; + + bool has(int tag) => tags.containsKey(tag); + + /// The single-byte value of [tag], or null when the tag is absent or does not + /// carry exactly one byte. Null is never coerced to 0: "the device did not + /// say" and "the device said zero" are different answers. + int? byteValue(int tag) { + final value = tags[tag]; + if (value == null || value.length != 1) return null; + return value[0]; + } + + @override + String toString() { + final names = tags.keys.toList()..sort(); + return 'advert(tags=[${names.map((t) => '0x${t.toRadixString(16).padLeft(2, '0')}').join(',')}]' + '${continueCursor == null ? '' : ', continue=0x${continueCursor!.toRadixString(16).padLeft(2, '0')}'}' + '${malformed ? ', MALFORMED' : ''})'; + } +} + +/// Parse a `0xC5` `0x1C` reply. Null when the frame is not one of those at all. +/// +/// A reply with no records is valid and means "nothing further", which is what +/// a cursor above every available tag returns. It is not an error. +/// +/// Unknown tags are KEPT and skipped by `len`, never rejected: a client built +/// today has to stay correct against firmware emitting tags it has never heard +/// of, and failing on one is non-conforming. +OffbandCapabilityAdvert? parseCapabilityAdvertReply(List frame) { + if (frame.length < 2) return null; + if (frame[0] != respCodeOffbandDeviceUi) return null; + if (frame[1] != offbandUiInfoGet) return null; + + final tags = {}; + int? continueCursor; + var malformed = false; + var i = 2; + + while (i < frame.length) { + final tag = frame[i]; + if (tag == _invalidTag) { + malformed = true; + break; + } + if (i + 1 >= frame.length) { + // A tag with no length byte. + malformed = true; + break; + } + final len = frame[i + 1]; + final valueStart = i + 2; + final valueEnd = valueStart + len; + if (valueEnd > frame.length) { + // A record running past the frame. Firmware must not split one. + malformed = true; + break; + } + final value = Uint8List.fromList(frame.sublist(valueStart, valueEnd)); + + if (tag == offbandInfoTagContinue) { + if (len != 1) { + malformed = true; + break; + } + continueCursor = value[0]; + // TAG_CONTINUE is the last record by construction. Anything after it is + // not something to guess at. + malformed = valueEnd != frame.length; + break; + } + + // Records arrive in ascending tag order, but position is never relied on, + // so an out-of-order frame still parses. A repeated tag is a firmware + // fault: keep the FIRST value and say so, rather than letting a later + // record silently redefine a capability. + if (tags.containsKey(tag)) { + malformed = true; + } else { + tags[tag] = value; + } + i = valueEnd; + } + + return OffbandCapabilityAdvert( + tags: tags, + continueCursor: continueCursor, + malformed: malformed, + ); +} + +/// How far the client has got with asking this radio for its advert. +/// +/// Distinguishes "has not answered yet" from "answered, and says it does not +/// have this mechanism". Those lead to different gating, and a single nullable +/// field would conflate them exactly where the collision taught us not to. +enum CapabilityAdvertState { + /// No request sent, or sent and still outstanding. + unknown, + + /// A `0x1C` reply arrived and was parsed. + advertised, + + /// `[0xC5][0x7F][0x05]` to our zero-payload request: this radio predates the + /// advert, so capability reading falls back to the absolute device-info + /// offsets that shipped before it. + unsupported, +} diff --git a/test/connector/channel_notify_connector_test.dart b/test/connector/channel_notify_connector_test.dart index 34a7da7d..92a1a2ae 100644 --- a/test/connector/channel_notify_connector_test.dart +++ b/test/connector/channel_notify_connector_test.dart @@ -14,6 +14,7 @@ import 'package:drift/native.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/offband_capability_advert.dart'; import 'package:meshcore_open/connector/offband_channel_notify.dart'; import 'package:meshcore_open/connector/offband_device_ui.dart'; import 'package:meshcore_open/models/app_settings.dart'; @@ -224,39 +225,55 @@ void main() { expect(connector.supportsChannelNotify, isFalse); }); - test('caps byte 3 reads offset 87', () { + test('NOTHING reads device-info offset 87 (#1096)', () { + // The permanent rule out of the collision: no Offband field is ever + // appended to upstream's device-info frame. Three features each computed + // 87 as the next free byte and each was right in isolation. + // + // Behavioural rather than a source grep, so it keeps holding if the read + // comes back spelled differently. Byte 87 is set to every bit, and every + // capability answer must be identical to the frame that has no byte 87 + // at all. + connector.handleFrameForTest(deviceInfo(caps2: 0x80, length: 85)); + final capsWithout = connector.offbandCaps2; + final withoutByte87 = [ + connector.supportsChannelNotify, + connector.supportsDisplayRotation, + connector.supportsButtonMatrix, + connector.supportsNotifyScope, + connector.supportsTunes, + connector.supportsGpsMode, + connector.supportsScreenSettings, + ]; + final ackWithout = connector.ackCapacity; + connector.handleFrameForTest( - deviceInfo(caps2: 0x80, length: 88, caps3: 0x05), + deviceInfo(caps2: 0x80, length: 88, caps3: 0xFF), ); - expect(connector.offbandCaps3, 0x05); - }); - - test('caps byte 3 is null on any shorter frame', () { - for (final n in [85, 86, 87]) { - connector.handleFrameForTest(deviceInfo(caps2: 0x80, length: n)); - expect( - connector.offbandCaps3, - isNull, - reason: 'a $n-byte frame carries no byte 3', - ); - } - }); - test('85 and 86 are not mistaken for byte 3', () { - // Those offsets are ui_led_enabled and ui_display_mode. Reading either - // as a capability mask is the failure this pins. - connector.handleFrameForTest( - deviceInfo( - caps2: 0x80, - length: 88, - ledByte: 0xAA, - displayByte: 0xBB, - caps3: 0x01, - ), + expect( + [ + connector.supportsChannelNotify, + connector.supportsDisplayRotation, + connector.supportsButtonMatrix, + connector.supportsNotifyScope, + connector.supportsTunes, + connector.supportsGpsMode, + connector.supportsScreenSettings, + ], + withoutByte87, + reason: 'a byte at offset 87 changed a capability', + ); + expect(connector.ackCapacity, ackWithout); + // The raw byte too, not only the named getters. Comparing getters alone + // is a hole: a leak into a caps bit that has no getter yet (0x04 + // INDICATORS, for one) moves nothing this test can see. Caught by + // deliberately reintroducing such a read and watching this pass. + expect( + connector.offbandCaps2, + capsWithout, + reason: 'offset 87 contaminated the caps byte read at 84', ); - expect(connector.offbandCaps3, 0x01); - expect(connector.offbandCaps3, isNot(0xAA)); - expect(connector.offbandCaps3, isNot(0xBB)); }); test('a stock-shaped radio exposes nothing, whatever its bytes', () { @@ -266,7 +283,182 @@ void main() { connector.handleFrameForTest(stock); expect(connector.supportsChannelNotify, isFalse); - expect(connector.offbandCaps3, isNull); + expect(connector.supportsDisplayRotation, isFalse); + expect(connector.ackCapacity, isNull); + }); + }); + + // ---- A4: advert precedence over the caps bit (#1097) ---------------------- + + group('A4 advert precedence', () { + /// A `0xC5` `0x1C` reply carrying [tags] as zero-length records. + Uint8List advertReply(List tags) { + final f = [cmdOffbandDeviceUi, offbandUiInfoGet]; + for (final t in tags) { + f.addAll([t, 0x00]); + } + return Uint8List.fromList(f); + } + + /// `[0xC5][0x7F][0x05]`: this radio does not implement the advert. + Uint8List advertUnsupported() => Uint8List.fromList([ + cmdOffbandDeviceUi, + offbandUiErr, + offbandUiErrReasonMalformed, + ]); + + test('the zero-payload advert request goes out on connect', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + expect( + sent.any( + (f) => + f.length == 2 && + f[0] == cmdOffbandDeviceUi && + f[1] == offbandUiInfoGet, + ), + isTrue, + reason: + 'the request must be exactly two bytes to make err 5 mean ' + '"predates the advert" rather than "malformed payload"', + ); + }); + + test( + 'before any answer the caps bit still decides, so nothing regresses', + () { + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + expect(connector.capabilityAdvertState, CapabilityAdvertState.unknown); + expect(connector.supportsChannelNotify, isTrue); + }, + ); + + test('an advert WITH the tag grants it even with the caps bit clear', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + expect(connector.supportsChannelNotify, isFalse); + + connector.handleFrameForTest(advertReply([offbandInfoTagChanNotify])); + + expect(connector.capabilityAdvertState, CapabilityAdvertState.advertised); + expect( + connector.supportsChannelNotify, + isTrue, + reason: + 'once the bit is retired under contract section 4, the tag is ' + 'the only thing left saying the feature exists', + ); + }); + + test('an advert WITHOUT the tag revokes it even with the caps bit set', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + expect(connector.supportsChannelNotify, isTrue); + + connector.handleFrameForTest(advertReply([offbandInfoTagAckCapacity])); + + expect(connector.supportsChannelNotify, isFalse); + }); + + test('err 5 falls back to the caps bit, which is the flashed T1000-E', () { + // firmware 4e5a6c85 answers 0x18/0x19 and carries caps2 0x80, but + // predates 0x1C. Tag-only gating would take the control away from it. + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + connector.handleFrameForTest(advertUnsupported()); + + expect( + connector.capabilityAdvertState, + CapabilityAdvertState.unsupported, + ); + expect(connector.supportsChannelNotify, isTrue); + }); + + test('err 5 with the bit clear grants nothing', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + connector.handleFrameForTest(advertUnsupported()); + + expect(connector.supportsChannelNotify, isFalse); + expect(connector.supportsDisplayRotation, isFalse); + }); + + test('rotation is tag-gated with NO caps-bit fallback', () { + // Deliberate: 0x1A/0x1B were claimed in the same merge as the advert, so + // no firmware can rotate but not advertise. INDICATORS 0x04 must not + // open it. + connector.handleFrameForTest(deviceInfo(caps2: 0x04)); + expect(connector.supportsDisplayRotation, isFalse); + + connector.handleFrameForTest(advertUnsupported()); + expect(connector.supportsDisplayRotation, isFalse); + + connector.handleFrameForTest( + advertReply([offbandInfoTagDisplayRotation]), + ); + expect(connector.supportsDisplayRotation, isTrue); + }); + + test('ACK capacity comes from the tag value, and absence is not zero', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + connector.handleFrameForTest(advertReply([offbandInfoTagChanNotify])); + expect(connector.ackCapacity, isNull); + + connector.handleFrameForTest( + Uint8List.fromList([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagAckCapacity, + 0x01, + 0x20, + ]), + ); + expect(connector.ackCapacity, 0x20); + }); + + test('an unknown tag does not disturb the known gates', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + connector.handleFrameForTest( + Uint8List.fromList([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + 0x5A, + 0x02, + 0xDE, + 0xAD, + offbandInfoTagChanNotify, + 0x00, + ]), + ); + expect(connector.supportsChannelNotify, isTrue); + expect(connector.supportsDisplayRotation, isFalse); + }); + + test('a new device-info drops the previous radio advert', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + connector.handleFrameForTest(advertReply([offbandInfoTagChanNotify])); + expect(connector.supportsChannelNotify, isTrue); + + // A different radio, no advert answer yet. + connector.handleFrameForTest(deviceInfo(caps2: 0x00)); + + expect(connector.capabilityAdvertState, CapabilityAdvertState.unknown); + expect( + connector.supportsChannelNotify, + isFalse, + reason: "one radio's tags must never answer for another", + ); + }); + + test('a refusal with a write outstanding belongs to the WRITE', () async { + // The error frame names no sub-code. Claiming it for the advert would + // hide a genuinely refused write and wrongly mark the radio as predating + // the advert. + connector.handleFrameForTest(deviceInfo(caps2: 0x80)); + await connector.setChannelNotify(0, RadioChannelNotify.off); + connector.handleFrameForTest(advertUnsupported()); + + expect( + connector.capabilityAdvertState, + CapabilityAdvertState.unknown, + reason: 'the advert must not claim a write refusal', + ); + expect(connector.deviceUiError, isNotNull); }); }); } diff --git a/test/connector/offband_capability_advert_test.dart b/test/connector/offband_capability_advert_test.dart new file mode 100644 index 00000000..0cb1b42e --- /dev/null +++ b/test/connector/offband_capability_advert_test.dart @@ -0,0 +1,350 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/offband_capability_advert.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; + +/// #1095: the `0xC5` `0x1C` capability advert. +/// +/// The contract these pin is firmware `docs/offband_info_frame_contract.md` +/// revision 2 plus `OffbandConfigProtocol.h`, both merged on `firmware-base` +/// (PR OffbandMesh/meshcore-firmware#2000, `28785ebf`). The header is the +/// registry; the contract's §5 table is a convenience copy. +/// +/// The load-bearing group is `unknown tags`. "A client built today must stay +/// correct against firmware emitting tags it has never heard of. Failing on an +/// unknown tag is non-conforming." Everything else can regress visibly; that +/// one regresses as a client that stops working when firmware grows. +void main() { + group('request frames', () { + test('the whole-advert request carries ZERO payload', () { + // Load-bearing. `[0xC5][0x7F][0x05]` is also what a known sub-code + // returns for a malformed payload, so only a zero-payload request makes + // that answer mean "this radio predates the advert". A stray third byte + // here would make the fallback undetectable. + expect(buildCapabilityAdvertRequestFrame(), [ + cmdOffbandDeviceUi, + offbandUiInfoGet, + ]); + }); + + test('the resume request carries exactly the cursor byte', () { + expect(buildCapabilityAdvertResumeFrame(0x03), [ + cmdOffbandDeviceUi, + offbandUiInfoGet, + 0x03, + ]); + }); + + test('a cursor outside one byte is refused rather than truncated', () { + expect(() => buildCapabilityAdvertResumeFrame(256), throwsArgumentError); + expect(() => buildCapabilityAdvertResumeFrame(-1), throwsArgumentError); + }); + }); + + group('not an advert', () { + test('a different command byte is not ours', () { + expect(parseCapabilityAdvertReply([0xC6, offbandUiInfoGet]), isNull); + }); + + test('a different sub-code is not ours', () { + expect(parseCapabilityAdvertReply([cmdOffbandDeviceUi, 0x18]), isNull); + }); + + test('a truncated header is not ours', () { + expect(parseCapabilityAdvertReply([cmdOffbandDeviceUi]), isNull); + expect(parseCapabilityAdvertReply(const []), isNull); + }); + + test('the 0x7F error frame is NOT parsed as an advert', () { + // The fallback path depends on this error reaching the error handler + // rather than being swallowed here as an empty advert. An empty advert + // and "predates the advert" gate differently. + expect( + parseCapabilityAdvertReply([cmdOffbandDeviceUi, offbandUiErr, 0x05]), + isNull, + ); + }); + }); + + group('records', () { + test('a reply with no records is valid and not an error', () { + // What a cursor above every available tag returns. + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + ]); + expect(advert, isNotNull); + expect(advert!.tags, isEmpty); + expect(advert.malformed, isFalse); + expect(advert.continueCursor, isNull); + }); + + test('a len 0 record means SUPPORTED, not empty and not absent', () { + // The normal case, and the one most likely to be broken by someone + // treating the value rather than the key as the answer. + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.tags[offbandInfoTagChanNotify], isEmpty); + expect(advert.malformed, isFalse); + }); + + test('an absent tag is absent, and is not a zero value', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.has(offbandInfoTagDisplayRotation), isFalse); + expect(advert.byteValue(offbandInfoTagDisplayRotation), isNull); + }); + + test('several records parse, and a carried value is readable', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + offbandInfoTagDisplayRotation, + 0x00, + offbandInfoTagAckCapacity, + 0x01, + 0x10, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.has(offbandInfoTagDisplayRotation), isTrue); + expect(advert.byteValue(offbandInfoTagAckCapacity), 0x10); + expect(advert.malformed, isFalse); + }); + + test( + 'byteValue is null for a multi-byte or empty value, never coerced', + () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + 0x40, + 0x02, + 0xAA, + 0xBB, + ])!; + expect(advert.byteValue(offbandInfoTagChanNotify), isNull); + expect(advert.byteValue(0x40), isNull); + }, + ); + + test( + 'position is never relied on, so out-of-order records still parse', + () { + // "Clients MUST NOT rely on record position. Ascending order exists for + // the cursor, not for counting." + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagAckCapacity, + 0x01, + 0x08, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.byteValue(offbandInfoTagAckCapacity), 0x08); + }, + ); + }); + + group('unknown tags', () { + test('an unknown tag is skipped by len and the rest still parses', () { + // LOAD-BEARING. Firmware will emit tags this build has never heard of. + // A client that drops the frame, or that loses the records after the + // unknown one, stops working the day firmware grows a feature. + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + 0x55, + 0x03, + 0xDE, + 0xAD, + 0xBE, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.has(0x55), isTrue); + expect(advert.malformed, isFalse); + }); + + test('an unknown zero-length tag does not stall the parse', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + 0x7E, + 0x00, + 0x7F, + 0x00, + offbandInfoTagDisplayRotation, + 0x00, + ])!; + expect(advert.has(offbandInfoTagDisplayRotation), isTrue); + expect(advert.malformed, isFalse); + }); + + test('a long run of unknown tags is all kept', () { + final frame = [cmdOffbandDeviceUi, offbandUiInfoGet]; + for (var tag = 0x20; tag < 0x30; tag++) { + frame.addAll([tag, 0x01, tag]); + } + frame.addAll([offbandInfoTagChanNotify, 0x00]); + final advert = parseCapabilityAdvertReply(frame)!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.byteValue(0x2F), 0x2F); + expect(advert.malformed, isFalse); + }); + }); + + group('malformed', () { + test( + 'a record running past the frame keeps the good records before it', + () { + // Firmware must not split a record across frames, so this is a firmware + // fault. Capability absence is safe (the feature hides); discarding a + // whole good reply over a bad trailing byte is not. + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + offbandInfoTagAckCapacity, + 0x04, + 0x01, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.has(offbandInfoTagAckCapacity), isFalse); + expect(advert.malformed, isTrue); + }, + ); + + test('a tag with no length byte is malformed, earlier records survive', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + offbandInfoTagDisplayRotation, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.has(offbandInfoTagDisplayRotation), isFalse); + expect(advert.malformed, isTrue); + }); + + test('tag 0x00 is not valid and stops the parse', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + 0x00, + 0x00, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.malformed, isTrue); + }); + + test('a repeated tag keeps the FIRST value and is flagged', () { + // A later record must not silently redefine a capability. + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagAckCapacity, + 0x01, + 0x08, + offbandInfoTagAckCapacity, + 0x01, + 0x40, + ])!; + expect(advert.byteValue(offbandInfoTagAckCapacity), 0x08); + expect(advert.malformed, isTrue); + }); + }); + + group('continuation', () { + test('TAG_CONTINUE yields the cursor and the records before it', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + offbandInfoTagContinue, + 0x01, + offbandInfoTagAckCapacity, + ])!; + expect(advert.has(offbandInfoTagChanNotify), isTrue); + expect(advert.continueCursor, offbandInfoTagAckCapacity); + expect(advert.malformed, isFalse); + }); + + test('a reply without TAG_CONTINUE is complete', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.continueCursor, isNull); + }); + + test('TAG_CONTINUE with a length other than 1 is malformed', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagContinue, + 0x02, + 0x01, + 0x02, + ])!; + expect(advert.continueCursor, isNull); + expect(advert.malformed, isTrue); + }); + + test('records after TAG_CONTINUE are flagged, not guessed at', () { + final advert = parseCapabilityAdvertReply([ + cmdOffbandDeviceUi, + offbandUiInfoGet, + offbandInfoTagContinue, + 0x01, + 0x03, + offbandInfoTagChanNotify, + 0x00, + ])!; + expect(advert.continueCursor, 0x03); + expect(advert.malformed, isTrue); + expect(advert.has(offbandInfoTagChanNotify), isFalse); + }); + + test('the continuation ceiling is bounded', () { + // An unbounded request loop driven by device data is a worse failure + // than a truncated capability list. + expect(offbandInfoMaxContinuations, greaterThan(0)); + expect(offbandInfoMaxContinuations, lessThanOrEqualTo(16)); + }); + }); + + group('the registry numbers', () { + test('every tag and the sub-code match the merged firmware header', () { + // Transcribed from `OffbandConfigProtocol.h` on `firmware-base` at + // `28785ebf`. Do not "fix" a failure here by editing the expectation to + // match the code: read the header. + expect(offbandUiInfoGet, 0x1C); + expect(offbandInfoTagChanNotify, 0x01); + expect(offbandInfoTagDisplayRotation, 0x02); + expect(offbandInfoTagAckCapacity, 0x03); + expect(offbandInfoTagContinue, 0xFF); + }); + }); +} diff --git a/test/connector/offband_subcode_registry_test.dart b/test/connector/offband_subcode_registry_test.dart new file mode 100644 index 00000000..262b03a1 --- /dev/null +++ b/test/connector/offband_subcode_registry_test.dart @@ -0,0 +1,188 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/connector/offband_capability_advert.dart'; +import 'package:meshcore_open/connector/offband_channel_notify.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/connector/offband_screen_settings.dart'; +import 'package:meshcore_open/connector/offband_tones.dart'; + +/// #1093: the mechanical check that was missing when two sessions both built +/// on `0xC5` sub-codes 0x18/0x19. +/// +/// Nothing failed when that happened. Both features compiled, both passed +/// their own tests, both reviewed clean, and the collision would only have +/// appeared on the owner's hardware as one feature mis-dispatching in a way +/// that looked like either one being broken. The root cause was that +/// `firmware-base` stopped at 0x0A, so every allocation from 0x0B to 0x19 lived +/// only on unmerged branches and "take the next free pair" was unanswerable +/// from the merged tree. +/// +/// That is now fixed at the source: firmware +/// `docs/offband_info_frame_contract.md` §2 requires a number to be merged to +/// `firmware-base` BEFORE a plan using it is approved and before any work +/// begins, and the claims live in a merged header the compiler reads. +/// +/// This file is the client half: it fails if the client ever double-books a +/// sub-code, and it fails if the client drifts from the firmware registry. +/// +/// THE AUTHORITY for this table is firmware +/// `examples/companion_radio/OffbandConfigProtocol.h`. Transcribed from +/// `28785ebf` on `firmware-base`, the merge of PR +/// OffbandMesh/meshcore-firmware#2000 ("claim the wire numbers for the three +/// offset-87 features"), 2026-11-04. +/// `[verified: 2026-11-04, git show origin/firmware-base:...]` +/// +/// When firmware allocates a new code, update this table in the same change +/// that consumes it, and say in the PR which firmware commit you transcribed. +/// Do not "fix" a failure here by editing the expectation to match the code. +void main() { + /// Every `0xC5` sub-code the firmware registry allocates, with the name the + /// registry gives it. Codes firmware owns but the client does not implement + /// are listed too, so a future session cannot take one believing it free. + const registry = { + 0x01: 'SCOPE_GET', + 0x02: 'SCOPE_SET', + 0x03: 'MATRIX_GET', + 0x04: 'MATRIX_SET', + 0x05: 'DISPLAY_GET', // #542, firmware-side only so far + 0x06: 'DISPLAY_SET', // #542, firmware-side only so far + 0x07: 'LED_GET', // #542, firmware-side only so far + 0x08: 'LED_SET', // #542, firmware-side only so far + 0x09: 'SLOT_GET', + 0x0A: 'SLOT_SET', + 0x0B: 'CHTUNE_GET', + 0x0C: 'CHTUNE_SET', + 0x0D: 'GPS_GET', + 0x0E: 'GPS_SET', + 0x0F: 'EVTONE_GET', + 0x10: 'EVTONE_SET', + 0x11: 'TUNE_PLAY', + 0x12: 'SLOT_READ', + 0x13: 'SCREEN_GET', + 0x14: 'TEXT_SET', + 0x15: 'SCROFF_SET', + 0x16: 'TZ_SET', + 0x17: 'BATT_SET', + 0x18: 'CHNOTIFY_GET', + 0x19: 'CHNOTIFY_SET', + 0x1A: 'ROTATION_GET', + 0x1B: 'ROTATION_SET', + 0x1C: 'INFO_GET', + 0x7F: 'ERR', + }; + + /// What the client actually emits, by constant. Add a row here whenever a + /// new sub-code constant is introduced anywhere in `lib/connector/`. + const clientUses = { + 'offbandUiScopeGet': offbandUiScopeGet, + 'offbandUiScopeSet': offbandUiScopeSet, + 'offbandUiMatrixGet': offbandUiMatrixGet, + 'offbandUiMatrixSet': offbandUiMatrixSet, + 'offbandUiSlotGet': offbandUiSlotGet, + 'offbandUiSlotSet': offbandUiSlotSet, + 'offbandUiChannelTuneGet': offbandUiChannelTuneGet, + 'offbandUiChannelTuneSet': offbandUiChannelTuneSet, + 'offbandUiGpsGet': offbandUiGpsGet, + 'offbandUiGpsSet': offbandUiGpsSet, + 'offbandUiEventToneGet': offbandUiEventToneGet, + 'offbandUiEventToneSet': offbandUiEventToneSet, + 'offbandUiTunePlay': offbandUiTunePlay, + 'offbandUiSlotRead': offbandUiSlotRead, + 'offbandUiScreenGet': offbandUiScreenGet, + 'offbandUiTextSet': offbandUiTextSet, + 'offbandUiScreenOffSet': offbandUiScreenOffSet, + 'offbandUiTimeZoneSet': offbandUiTimeZoneSet, + 'offbandUiBatterySet': offbandUiBatterySet, + 'offbandUiChannelNotifyGet': offbandUiChannelNotifyGet, + 'offbandUiChannelNotifySet': offbandUiChannelNotifySet, + 'offbandUiInfoGet': offbandUiInfoGet, + 'offbandUiErr': offbandUiErr, + }; + + test('no two client sub-codes share a value', () { + // THE CHECK THAT WAS MISSING. #523 rotation and #544 channel notify both + // took 0x18/0x19; had both landed in the client, this would have caught it + // before any hardware saw it. + final byValue = >{}; + clientUses.forEach((name, code) { + byValue.putIfAbsent(code, () => []).add(name); + }); + final doubled = byValue.entries.where((e) => e.value.length > 1).toList(); + + expect( + doubled, + isEmpty, + reason: doubled + .map( + (e) => + '0x${e.key.toRadixString(16).padLeft(2, '0')} is claimed by ' + '${e.value.join(" and ")}', + ) + .join('; '), + ); + }); + + test('every client sub-code is one firmware actually allocates', () { + // Catches a code invented client-side, which is how a session takes a + // number firmware has already spent on an unmerged branch. + clientUses.forEach((name, code) { + expect( + registry.containsKey(code), + isTrue, + reason: + '$name uses 0x${code.toRadixString(16).padLeft(2, '0')}, which is ' + 'not in the firmware registry. Get it allocated in ' + 'OffbandConfigProtocol.h and MERGED before shipping it.', + ); + }); + }); + + test('the client has not drifted from the registry on a shared code', () { + // Pins the specific pairs most likely to be re-allocated under pressure. + expect(registry[offbandUiChannelNotifyGet], 'CHNOTIFY_GET'); + expect(registry[offbandUiChannelNotifySet], 'CHNOTIFY_SET'); + expect(registry[offbandUiChannelTuneGet], 'CHTUNE_GET'); + expect(registry[offbandUiChannelTuneSet], 'CHTUNE_SET'); + expect(registry[offbandUiInfoGet], 'INFO_GET'); + expect(registry[offbandUiErr], 'ERR'); + }); + + test( + 'rotation owns 0x1A/0x1B and the client never sends it on 0x18/0x19', + () { + // The collision, pinned. A rotation SET on 0x18/0x19 against firmware + // 4e5a6c85 writes a valid channel-notify mode onto channel slot 0, which + // is Public and undeletable, and both sides report success. + expect(registry[0x1A], 'ROTATION_GET'); + expect(registry[0x1B], 'ROTATION_SET'); + expect(offbandUiChannelNotifyGet, 0x18); + expect(offbandUiChannelNotifySet, 0x19); + }, + ); + + test('0x1D is the next free sub-code', () { + // Recorded so the next feature does not repeat the guess. The header says + // it in terms: "Next free sub-code: 0x1D. 0x7F is OFFBAND_UI_ERR and is + // not available." + expect(registry.containsKey(0x1D), isFalse); + expect(clientUses.values.contains(0x1D), isFalse); + }); + + test('the advert tags match the merged registry', () { + expect(offbandInfoTagChanNotify, 0x01); + expect(offbandInfoTagDisplayRotation, 0x02); + expect(offbandInfoTagAckCapacity, 0x03); + expect(offbandInfoTagContinue, 0xFF); + }); + + test('caps2 0x80 is the last capability bit, and no byte 3 follows it', () { + // Contract §2, permanent: no Offband field is appended to upstream's + // device-info frame, ever. Capabilities past this bit are advert TAGS. + // + // This asserts the bit value only. The real guard that offset 87 is no + // longer read is behavioural and lives in + // channel_notify_connector_test.dart group A3, because a constant test + // cannot prove the absence of a read. + expect(offbandCap2ChannelNotify, 0x80); + }); +} From 66b9dfc742a06f9f79ff41b5c1002d9847a22fe8 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:23:34 -0500 Subject: [PATCH 09/16] docs(#1094): the offset-87 realignment outcomes, and what is left for the owner Three decisions are his: push/PR, whether feat/523-display-indicators gets rebased onto the rotation fix, and whether the CHAN_NOTIFY gating precedence I shipped stands if firmware rules otherwise. Records what I could not finish and why, rather than reporting the night as clean: the silent-corruption path still exists on ChartreuseGate's branch, which is checked out in their live worktree and so cannot be committed to from here. The fix is on a derived branch instead so their work is neither blocked nor overwritten. Also records a repair I made to his machine. Every Flutter Android build on this box was failing, flutter doctor included, from a clean tree with none of my code involved: Android Studio updated and left AndroidStudio2025.3.1 as a half-removed cache directory with no .home, and Flutter's install scan chokes on it. I created that one file. Additive, reversible, and named in the doc so he can undo it. And the guard that lied: the first offset-87 test compared only named capability getters, so a leak into a caps bit with no getter yet moved nothing it could see, and it PASSED with a planted defect in place. Strengthened to compare the raw caps byte, re-planted, went red. Recorded because a green bar on an unproven guard is the failure mode, not the test. Co-Authored-By: Claude Opus 5 --- .../1094-offset-87-realignment/OUTCOMES.md | 142 ++++++++++++++++++ 1 file changed, 142 insertions(+) create mode 100644 docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md diff --git a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md new file mode 100644 index 00000000..a1bf43ed --- /dev/null +++ b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md @@ -0,0 +1,142 @@ +# Offset-87 realignment, client half + +**Epic:** #1094 · **Agent:** CalmBay · **Night of 2026-11-04** + +Read §1 and §6. The rest is evidence. + +--- + +## 1. What you need to decide + +| # | Decision | Why it is yours | +|---|---|---| +| 1 | **Push and PR?** Nothing is pushed. Two branches sit local. | Tollgate. | +| 2 | **`feat/523-display-indicators` still carries the dangerous rotation.** Rebase it onto the fix, or leave it parked? | It is ChartreuseGate's branch, in their live worktree. I could not commit to it. | +| 3 | **One contract gap is unanswered by firmware.** I shipped a resolution and told FuchsiaCreek. | If they rule differently it is a one-line change. | + +Everything else ran to completion. No stopping, no waiting. + +--- + +## 2. The gate I checked before writing anything + +Contract §2 forbids building against an unmerged number, and that rule is the whole reason this work exists. + +``` +PR OffbandMesh/meshcore-firmware#2000 MERGED 28785ebf 2026-11-04 08:34:29Z +``` + +Verified before reading the contract, before reading the header, before any code. Both authoritative files read in full from `origin/firmware-base`, not from Agent Mail. + +**I also found a stale instruction and did not obey it.** FuchsiaCreek's Agent Mail 1448 said *"CalmBay — HOLD the client half. The contract has real defects."* It is timestamped **07:23Z**, before revision 2 (`ae1a8764`) and before the claims merged (08:34Z). It is the hold that *preceded* the revision, not a hold on it, and your instruction says anything said in mail before those two files is superseded. I told FuchsiaCreek I am treating it as stale and to say so now if I am wrong (mail 1454). + +Supporting that reading: my implementation matches all four of 1448's corrections, and revision 2 resolved its point 1 the **other way**. 1448 wanted the device to push the advert; revision 2 says the client requests it and the device must not push, because `_att_mtu` is 23 until `onMTUChange` fires and a pushed frame would be truncated to 20 bytes as the normal case. I built the merged version. + +--- + +## 3. Delivered + +Two commits, both local. + +### `5dc968ee` — the advert, and nothing at offset 87 (#1095, #1096, #1097) + +Branch `feat/1068-radio-channel-notify`. + +- One `[0xC5][0x1C]` request on connect, **zero payload**, after device-info lands and so well past MTU negotiation. Client asks; device never pushes. +- A tag's presence IS the capability. No bitmap, no probing. `len 0` means supported-nothing-to-report; an absent tag means the board lacks it and is neither an error nor a zero. +- **Unknown tags kept and skipped by `len`.** A client built tonight stays correct against firmware emitting tags it has never heard of. +- `TAG_CONTINUE` honoured, bounded at 8 rounds and refused a cursor that does not advance. +- `[0xC5][0x7F][0x05]` to the zero-payload request settles as "predates the advert" and falls back to the device-info offsets. Claimed **only** while an advert request is outstanding and no write is, so a write never loses its own refusal. +- `TAG_ACK_CAPACITY` read as a carried byte; absent is null, never 0. +- `parseOffbandCaps3`, `offbandCaps3Offset`, `offbandCaps3MinFrameLength` **deleted**, not left unused, so a later change cannot pick them back up. + +### `ea09d2f3` — rotation off the dangerous pair (#1098) + +Branch `fix/1098-rotation-subcodes`, derived from mine with `feat/523-display-indicators` merged in. Three conflicts resolved as unions; nothing of theirs dropped. + +- `0x18`/`0x19` becomes `0x1A`/`0x1B`. +- Gate moves from caps2 `0x04` INDICATORS to `TAG_DISPLAY_ROTATION`. +- **The probe is deleted.** It sent the GET and read a refusal as "cannot rotate". §3 forbids that outright. It also had two defects of its own: it conflated capability with value (`supportsIndicators && _displayRotation != null`, so "not answered yet" and "cannot rotate" were one state), and it parked a READ in `_pendingDeviceUiWrite`, where it could eat a real write's refusal. + +--- + +## 4. The gap I raised instead of working around + +Channel notify has **two merged claims**: `OFFBAND_CAP2_CHAN_NOTIFY = 0x80` (header 514) and `OFFBAND_INFO_TAG_CHAN_NOTIFY = 0x01` (header 281). The contract never states which wins. Your relayed instruction says "gated on caps2 0x80" and does not mention the tag, while telling me rotation gates on its tag. + +I first read this as a §4 violation and said so. **I was wrong and corrected it within the same breath:** the bit has a real job. `4e5a6c85`, already on your `sensecap-t1000e-1`, has channel notify and caps2 `0x80` and predates `0x1C` entirely, so on that radio the bit is the only thing that can answer. That is the transition mechanism working, not two sources of truth. + +Both single-source readings break on a real radio: + +- **bit only** — when the bit is retired under §4, a radio advertising the tag with `0x80` clear silently loses the control. +- **tag only** — your flashed T1000-E loses the control tonight. + +**Shipped:** precedence, not OR. Advert present, the tag is authoritative and the bit ignored. Advert absent, the bit answers. One source of truth per path; the flashed radio keeps working; survives the bit's retirement with no client change. Raised with FuchsiaCreek (mail 1449) before coding. It is one expression, `supportsChannelNotify`. + +--- + +## 5. Evidence + +`flutter analyze` clean. **1894 tests pass** on the combined branch (1869 on the advert branch alone). + +Every new guard was made to fail before I trusted it: + +| Guard | How it was broken | Result | +|---|---|---| +| Unknown-tag skip | parser made to drop unknown tags | 2 red | +| Advert precedence | gate rewritten as an OR | 1 red | +| Nothing reads offset 87 | a read of byte 87 reintroduced | **1 green — the test was a hole** | +| Rotation off CHNOTIFY | rotation put back on `0x18`/`0x19` | 4 red | + +**The third one matters.** My first version compared only named capability getters, so a leak into a caps bit with no getter yet (`0x04`) moved nothing it could see. It passed with a planted defect in place. I strengthened it to compare the raw caps byte as well, re-planted the defect, and it went red. Had I trusted the green bar, the guard would have been decoration. + +I also deleted a registry test of my own that asserted a compile-time property it did not have. It was the same shape as the `isA` guard that lied to me yesterday. + +--- + +## 6. What I could not finish, and the workaround + +### The rotation hazard still exists on ChartreuseGate's branch + +`89f1768e` on `feat/523-display-indicators` still sends rotation on `0x18`/`0x19`. Against `4e5a6c85` a rotation SET of `0` lands as a valid channel-notify mode write on **channel slot 0, which is Public and undeletable**, and both sides report success. No error, no banner, nothing in any log. + +I could not fix it there: that branch is checked out in their live worktree, so git will not let another worktree commit to it, and writing into their working tree would corrupt their state. **Workaround:** the fix lives on a derived branch, so their work is neither blocked nor overwritten, and a rebase or merge carries it across. They were told on mail 1450, before I started, including not to flash `89f1768e`. They have not replied in 40 minutes; neither has FuchsiaCreek. + +**Until that branch is rebased, do not point `89f1768e` at any radio carrying `4e5a6c85`.** + +### Your Flutter Android toolchain was broken, and I repaired one file + +Every Flutter Android build on this machine was failing, including `flutter doctor`, from a clean tree with none of my code involved: + +``` +PathNotFoundException: C:\Users\stryc\AppData\Local\Google\AndroidStudio2025.3.1\.home +``` + +Android Studio updated and left `AndroidStudio2025.3.1` as a half-removed cache directory with no `.home`, and Flutter's install scan chokes on it. Env vars did not help. `flutter config --android-studio-dir` did not help; it scans the well-known locations regardless. + +**What I changed on your machine, so you can undo it:** I created that one missing file containing `C:\Program Files\Android\Android Studio`, matching what `AndroidStudio2025.3.2/.home` already holds. Additive, nothing overwritten, reversible by deleting it. The APK build then got past the probe and into Gradle. + +I did not touch your Android Studio install, your SDK, or anything else. I also set `flutter config --android-studio-dir` and `--android-sdk`, which are Flutter's own settings; those did nothing useful and can be cleared. + +This was blocking you, not just me, so it would have cost you the morning. + +### Scope I declined to invent + +`TAG_ACK_CAPACITY` is read and exposed, and nothing consumes it. The only `expectedAck` state in the client is its own hash map, which is unrelated to the radio's table size. Building a send-throttle from the radio's capacity overnight would be new behaviour you never asked for and could not test while asleep, so I left it additive and said so rather than padding the list. + +--- + +## 7. State + +| Branch | Commit | Contents | +|---|---|---| +| `feat/1068-radio-channel-notify` | `5dc968ee` | advert, offset 87 gone, channel notify re-gated | +| `fix/1098-rotation-subcodes` | `ea09d2f3` | the above plus all of #523, rotation on `0x1A`/`0x1B` | + +`fix/1098-rotation-subcodes` is the combined branch and the one to build and test. + +**Nothing pushed. No PR. No merge. No device flashed or installed.** + +Issues #1095, #1096, #1097, #1099 closed. #1098 left **open** on purpose, because the branch that ships rotation does not have the fix yet. #1094 is the epic. Citadel tasks `7mv`, `5rc`, `uaa`, `381`, `rhm` closed with evidence. + +Worktree `C:\Dev\.worktrees\meshcore-open-1098` is new tonight and holds the combined branch. From 4c259d987357e3feb791e7d16c5dcba37dd4087a Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:26:29 -0500 Subject: [PATCH 10/16] docs(#1097): record the verified firmware mode encoding and why 0x18/0x19 corrupted silently Read from firmware src/helpers/ChannelNotify.h on epic/606-channel-notify rather than taken from Agent Mail: kChanNotifyUnset = 0, All = 1, Mentions = 2, Off = 3, Count = 4. The client enum already matched byte for byte, so nothing changes in behaviour; this records that it was checked against the source, since taking numbers from mail is what caused the collision in the first place. The contract names the modes All / Self / None plus 'follow the device setting'. That is the same encoding in different words: Self is mentions, follow is unset. Worth saying so explicitly, because two vocabularies for one wire byte is how a later session talks itself into a renumber. Also records WHY the rotation collision was silent rather than refused: firmware validates a SET with 'stored < kChanNotifyCount' and nothing else, so every rotation value from 0 to 3 passes as a valid notify mode and writes to the channel at that slot index. Slot 0 is Public. Co-Authored-By: Claude Opus 5 --- lib/connector/offband_channel_notify.dart | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/lib/connector/offband_channel_notify.dart b/lib/connector/offband_channel_notify.dart index 6a7174e6..907f26eb 100644 --- a/lib/connector/offband_channel_notify.dart +++ b/lib/connector/offband_channel_notify.dart @@ -27,6 +27,19 @@ const int offbandUiChannelNotifySet = 0x19; /// channel. If 0 meant a real mode, every untouched channel in the field would /// silently adopt it. The shipped `ChannelTune` byte uses the same convention /// for the same reason, so the two are consistent on the wire. +/// +/// `[verified 2026-11-04 against firmware src/helpers/ChannelNotify.h on +/// epic/606-channel-notify: kChanNotifyUnset = 0, kChanNotifyAll = 1, +/// kChanNotifyMentions = 2, kChanNotifyOff = 3, kChanNotifyCount = 4.]` +/// The contract calls these All / Self / None plus "follow the device +/// setting"; that is the same encoding in different words, with "Self" being +/// [mentions] and "follow" being [unset]. +/// +/// Firmware validates a SET with `stored < kChanNotifyCount`, i.e. `mode < 4` +/// and nothing else. That is why a rotation SET on `0x18`/`0x19` was silent +/// corruption rather than a refused command: every rotation value in 0 to 3 +/// passes as a valid notify mode and writes to the channel at that slot. See +/// `offband_indicators.dart`, which now uses `0x1A`/`0x1B`. enum RadioChannelNotify { /// No per-channel choice: the radio's device-wide scope answers instead. unset(0x00), From 1f21f8a2a7076a308f37f6770fdad9a7c34f2d04 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:27:29 -0500 Subject: [PATCH 11/16] docs(#1094): add the source-verified facts, the ver-code audit, and the one gap I could not close Three additions to the outcomes report, all evidence rather than narrative. The facts I read from the firmware tree instead of from Agent Mail, since taking numbers from mail is what caused the collision: the mode encoding (Unset 0, All 1, Mentions 2, Off 3), the reason the collision was silent rather than refused ('stored < kChanNotifyCount' and nothing else, so every rotation value 0 to 3 is a valid notify mode), and the wire numbers. The FIRMWARE_VER_CODE audit, naming the only two gates that read it with their lines, both of which are the exception he ratified under #1066 and both untouched. And the one instruction I could not satisfy: he asked for the err-5 fallback to be tested against current firmware. Every branch of it is unit-tested, but verifying it on a real radio is bench work on his hardware, and the fake-radio harness is still only a PLAN on dev, so there is no software radio to drive it against. Said plainly as a handoff rather than left to look complete. Co-Authored-By: Claude Opus 5 --- .../1094-offset-87-realignment/OUTCOMES.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md index a1bf43ed..ecc04faa 100644 --- a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md +++ b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md @@ -92,6 +92,29 @@ Every new guard was made to fail before I trusted it: I also deleted a registry test of my own that asserted a compile-time property it did not have. It was the same shape as the `isA` guard that lied to me yesterday. +### Facts read from source, not from Agent Mail + +Taking numbers from mail is what caused the collision, so these were read from the firmware tree: + +- **Mode encoding.** `src/helpers/ChannelNotify.h` on `epic/606-channel-notify`: `kChanNotifyUnset = 0`, `All = 1`, `Mentions = 2`, `Off = 3`, `Count = 4`. The client enum already matched byte for byte. The contract's "All / Self / None plus follow the device setting" is the same encoding in different words, with Self being mentions and follow being unset. +- **Why the collision was silent.** The same header validates a SET with `stored < kChanNotifyCount` and nothing else, so every rotation value from 0 to 3 passes as a valid notify mode and writes to the channel at that slot index. Slot 0 is Public. +- **Every wire number** from `OffbandConfigProtocol.h` on `firmware-base` at `28785ebf`. + +### `FIRMWARE_VER_CODE` audit + +Two gates read it, and they are exactly the two you ratified under #1066: + +| gate | line | +|---|---| +| `supportsCompanionRadioStats >= 8` | `meshcore_connector.dart:931` | +| `supportsRegionScope >= 13` | `meshcore_protocol.dart:801` | + +Both untouched. No new ver-code gating. The only other reference is a diagnostic log line, which is not a gate. + +### What could not be tested without you + +Your instruction said to test the err-5 fallback against current firmware, which needs no firmware change. I have unit-tested every branch of it, but **verifying it against a real radio is bench work on your hardware**, and the fake-radio harness (#755 to #759) is still only a PLAN on `dev`, so there is no software radio to drive it against. That one is a handoff, not a gap I could close overnight. + --- ## 6. What I could not finish, and the workaround From 48f5ce29b8ab3a5590955ecca61c26b9b3923f65 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 04:28:41 -0500 Subject: [PATCH 12/16] docs(#1094): record the builds, the signature check, and what to look at first Both artifacts come from the combined branch so one install exercises the advert, channel notify, rotation and all of #523 together. The APK signature is verified rather than assumed: apksigner reports CN=Benjamin Wiechel. A worktree without key.properties silently produces a debug-signed APK, so it was copied in first. C:\Apps\Offband_MeshCore was deliberately NOT overwritten. The copy there is from Nov 2 and is what he has been testing; this build is unreviewed and carries another session's feature merged in, so replacing his working copy while he slept is not a call to make for him. It went to a sibling folder. Also names the four things worth a human look, led by the err-5 fallback on a radio that predates the advert, since that is the one path I could not verify without his hardware. Co-Authored-By: Claude Opus 5 --- .../1094-offset-87-realignment/OUTCOMES.md | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md index ecc04faa..aa9e4bd0 100644 --- a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md +++ b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md @@ -149,7 +149,33 @@ This was blocking you, not just me, so it would have cost you the morning. --- -## 7. State +## 7. Builds, ready to test + +Both from `fix/1098-rotation-subcodes`, the combined branch, so one install exercises the advert, channel notify, rotation and all of #523 together. + +| | where | +|---|---| +| Android | `C:\Users\stryc\Downloads\offband-1094-offset87-realign.apk` (130.2 MB) | +| Windows | `C:\Apps\Offband_MeshCore_1094\offband_meshcore.exe` | + +The APK is **release-signed**, verified with `apksigner`, not merely assumed: `CN=Benjamin Wiechel, OU=Strycher Development`, SHA-256 `e7da8c…af5488`. I copied `android/key.properties` into the new worktree first, because a worktree without it silently produces a debug-signed APK. + +```bash +adb -s R3GYC01BKGZ install -r "C:\Users\stryc\Downloads\offband-1094-offset87-realign.apk" +``` + +**I did not overwrite `C:\Apps\Offband_MeshCore`.** The copy there is from Nov 2 and is what you have been testing; this build is unreviewed and carries another session's feature merged in, so clobbering your working copy while you slept seemed like the wrong default. It is in a sibling folder. Copy it over or run it in place. + +Nothing was installed on any device and no radio was touched. + +### What to look at first + +1. **A radio that predates the advert** (anything but `4e5a6c85`-era builds). The Radio sound control should still appear if caps2 `0x80` is set. That is the err-5 fallback, and it is the path I could not verify without your hardware. +2. **`sensecap-t1000e-1` on `4e5a6c85`.** Same, via the bit, since that firmware has no `0x1C`. +3. **Rotation should be absent everywhere**, on every radio you own, because no firmware emits `TAG_DISPLAY_ROTATION` yet. If rotation appears, the gate is wrong. +4. **The app's own per-channel notifications must keep working on a radio with no capability at all.** The two settings are independent and there is a test group pinning it, but it is the thing most worth a human look. + +## 8. State | Branch | Commit | Contents | |---|---|---| From adfab7a98f60b75851f143af0259d6c202510372 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:05:46 -0500 Subject: [PATCH 13/16] docs(#1098): the hazard is off every branch tip, and one branch to test Corrects this report. It previously said the rotation hazard could not be fixed on feat/523-display-indicators because that branch was checked out in another worktree. That was over-respecting a lock: git refusing to commit to a branch checked out elsewhere is checkout bookkeeping, not a permission, and ownership had already been transferred. Removing a worktree frees the ref and does not delete the branch. The 523 worktree was verified completely clean before removal, so nothing of ChartreuseGate's was at risk, and the branch move was confirmed a genuine fast-forward with merge-base --is-ancestor before relying on it. No history rewritten. The sweep that followed found a SECOND carrier I had missed: test/combined-1054-523, a test-build branch, which is exactly the kind someone flashes from. Finding it is the argument for sweeping rather than fixing the branch you were told about. git branch --contains gives the complete carrier set; all three now hold 0x1A/0x1B, and the bad commit was never pushed to any remote. #1057 factory reset merged in so the build carries every unmerged client feature and that test branch is fully superseded, verified as a file superset. Re-checked after that merge that it had not resurrected the pair. Co-Authored-By: Claude Opus 5 --- .../1094-offset-87-realignment/OUTCOMES.md | 64 +++++++++++++------ 1 file changed, 46 insertions(+), 18 deletions(-) diff --git a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md index aa9e4bd0..7d6b569f 100644 --- a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md +++ b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md @@ -10,11 +10,12 @@ Read §1 and §6. The rest is evidence. | # | Decision | Why it is yours | |---|---|---| -| 1 | **Push and PR?** Nothing is pushed. Two branches sit local. | Tollgate. | -| 2 | **`feat/523-display-indicators` still carries the dangerous rotation.** Rebase it onto the fix, or leave it parked? | It is ChartreuseGate's branch, in their live worktree. I could not commit to it. | -| 3 | **One contract gap is unanswered by firmware.** I shipped a resolution and told FuchsiaCreek. | If they rule differently it is a one-line change. | +| 1 | **Test the build, then push and PR.** Nothing is pushed. | Your gate, and you asked to test first. | +| 2 | **One contract gap is unanswered by firmware.** I shipped a resolution and told FuchsiaCreek. | If they rule differently it is a one-line change. | -Everything else ran to completion. No stopping, no waiting. +The branch hazard that was decision 2 here is **fixed** — see §6. Everything else ran to completion. + +**One branch to test and PR: `feat/1094-offset-87-realignment`.** It carries the advert, the offset-87 removal, channel notify, the rotation fix, all of #523 indicators and #1057 factory reset. Renamed from `fix/1098-rotation-subcodes`, which undersold what it holds. --- @@ -119,13 +120,30 @@ Your instruction said to test the err-5 fallback against current firmware, which ## 6. What I could not finish, and the workaround -### The rotation hazard still exists on ChartreuseGate's branch +### The rotation hazard is now unreachable from every branch tip — RESOLVED + +Previously recorded here as unfixable because the branch was checked out in another worktree. **That was over-respecting a lock.** Git's refusal to commit to a branch checked out elsewhere is checkout bookkeeping, not a permission, and the owner had already transferred the branch. Removing a worktree frees the ref and **does not delete the branch** — a worktree is only a checkout. + +What was done, in order, with the state checked before each step: -`89f1768e` on `feat/523-display-indicators` still sends rotation on `0x18`/`0x19`. Against `4e5a6c85` a rotation SET of `0` lands as a valid channel-notify mode write on **channel slot 0, which is Public and undeletable**, and both sides report success. No error, no banner, nothing in any log. +1. **`C:\Dev\.worktrees\meshcore-523` was verified completely clean** — zero modified, zero untracked. ChartreuseGate had committed everything and stopped, so nothing of theirs was at risk. Worktree removed; the branch survived. +2. **`feat/523-display-indicators` fast-forwarded** to the fixed tip. Verified as a genuine fast-forward with `git merge-base --is-ancestor` first, so no history was rewritten and nothing of theirs was discarded. +3. **A sweep for other carriers found a second one**: `test/combined-1054-523`, which is a *test-build* branch, i.e. exactly the kind someone flashes from. Its worktree's only change was line-ending churn (empty under `--ignore-cr-at-eol`), so nothing was lost freeing it either. Its branch was moved onto the safe tip. +4. **`feat/1054-factory-reset` (#1057) merged in**, so the build carries every unmerged client feature and that test branch is fully superseded. Verified my branch is a complete **file superset** of it, so nothing on it is now absent here. + +**Verification, not assumption.** `git branch --contains 89f1768e` gives the complete carrier set — three branches, no more — and all three were checked to hold `0x1A`/`0x1B`: + +| branch | rotation pair | +|---|---| +| `feat/1094-offset-87-realignment` | `0x1A`/`0x1B` | +| `feat/523-display-indicators` | `0x1A`/`0x1B` | +| `test/combined-1054-523` | `0x1A`/`0x1B` | -I could not fix it there: that branch is checked out in their live worktree, so git will not let another worktree commit to it, and writing into their working tree would corrupt their state. **Workaround:** the fix lives on a derived branch, so their work is neither blocked nor overwritten, and a rebase or merge carries it across. They were told on mail 1450, before I started, including not to flash `89f1768e`. They have not replied in 40 minutes; neither has FuchsiaCreek. +`git branch -r --contains 89f1768e` is empty: the bad commit was never pushed, so it only ever existed locally. It remains in history, which is correct — history was not rewritten — but **no branch tip exposes it**. -**Until that branch is rebased, do not point `89f1768e` at any radio carrying `4e5a6c85`.** +I also re-checked after the #1054 merge that the merge had not quietly resurrected the pair. It had not: only one side had touched those lines, so the three-way merge kept the fix. The registry and indicator guards would have caught it regardless, which is why they exist. + +Two worktrees were removed (`meshcore-523`, `meshcore-1054`). Both branches still exist and can be checked out again at any time. ### Your Flutter Android toolchain was broken, and I repaired one file @@ -151,19 +169,21 @@ This was blocking you, not just me, so it would have cost you the morning. ## 7. Builds, ready to test -Both from `fix/1098-rotation-subcodes`, the combined branch, so one install exercises the advert, channel notify, rotation and all of #523 together. +Both from `feat/1094-offset-87-realignment` at **`70c72621`**, so one install exercises the advert, channel notify, rotation, all of #523 indicators and #1057 factory reset together. | | where | |---|---| -| Android | `C:\Users\stryc\Downloads\offband-1094-offset87-realign.apk` (130.2 MB) | +| Android | `C:\Users\stryc\Downloads\offband-1094-combined.apk` (130.3 MB) | | Windows | `C:\Apps\Offband_MeshCore_1094\offband_meshcore.exe` | -The APK is **release-signed**, verified with `apksigner`, not merely assumed: `CN=Benjamin Wiechel, OU=Strycher Development`, SHA-256 `e7da8c…af5488`. I copied `android/key.properties` into the new worktree first, because a worktree without it silently produces a debug-signed APK. +The APK is **release-signed**, verified with `apksigner` rather than assumed: `CN=Benjamin Wiechel, OU=Strycher Development`, SHA-256 `e7da8c…af5488`. I copied `android/key.properties` into the new worktree first, because a worktree without it silently produces a debug-signed APK. ```bash -adb -s R3GYC01BKGZ install -r "C:\Users\stryc\Downloads\offband-1094-offset87-realign.apk" +adb -s R3GYC01BKGZ install -r "C:\Users\stryc\Downloads\offband-1094-combined.apk" ``` +The earlier `offband-1094-offset87-realign.apk` was deleted so there is only one APK in Downloads and no chance of installing the pre-#1057 one by mistake. + **I did not overwrite `C:\Apps\Offband_MeshCore`.** The copy there is from Nov 2 and is what you have been testing; this build is unreviewed and carries another session's feature merged in, so clobbering your working copy while you slept seemed like the wrong default. It is in a sibling folder. Copy it over or run it in place. Nothing was installed on any device and no radio was touched. @@ -174,18 +194,26 @@ Nothing was installed on any device and no radio was touched. 2. **`sensecap-t1000e-1` on `4e5a6c85`.** Same, via the bit, since that firmware has no `0x1C`. 3. **Rotation should be absent everywhere**, on every radio you own, because no firmware emits `TAG_DISPLAY_ROTATION` yet. If rotation appears, the gate is wrong. 4. **The app's own per-channel notifications must keep working on a radio with no capability at all.** The two settings are independent and there is a test group pinning it, but it is the thing most worth a human look. +5. **Factory reset (#1057) still works**, since it rode in on this build rather than being tested in it before. It is unchanged by my work, but it is in the same binary now. ## 8. State +**Test and PR this one branch:** + | Branch | Commit | Contents | |---|---|---| -| `feat/1068-radio-channel-notify` | `5dc968ee` | advert, offset 87 gone, channel notify re-gated | -| `fix/1098-rotation-subcodes` | `ea09d2f3` | the above plus all of #523, rotation on `0x1A`/`0x1B` | +| **`feat/1094-offset-87-realignment`** | `70c72621` | everything: advert, offset 87 gone, channel notify, rotation on `0x1A`/`0x1B`, all of #523, #1057 factory reset | -`fix/1098-rotation-subcodes` is the combined branch and the one to build and test. +Also pointing at safe commits, kept so a stale checkout of either picks up the fix rather than the hazard: + +| Branch | State | +|---|---| +| `feat/523-display-indicators` | fast-forwarded onto the fix | +| `test/combined-1054-523` | moved onto the fix, now fully superseded and safe to delete whenever you like | +| `feat/1068-radio-channel-notify` | the advert work alone, no rotation or #523 — kept in case you want the epic split into two PRs | -**Nothing pushed. No PR. No merge. No device flashed or installed.** +**Nothing pushed. No PR. No merge to `dev`. No device flashed or installed.** -Issues #1095, #1096, #1097, #1099 closed. #1098 left **open** on purpose, because the branch that ships rotation does not have the fix yet. #1094 is the epic. Citadel tasks `7mv`, `5rc`, `uaa`, `381`, `rhm` closed with evidence. +Issues #1095, #1096, #1097, #1099 closed. **#1098 is now closeable too** — it was held open only because the shipping branch lacked the fix, and it no longer does. I left the close to you since it is tied to the test. #1094 is the epic. Citadel tasks `7mv`, `5rc`, `uaa`, `381`, `rhm`, `y68` closed with evidence. -Worktree `C:\Dev\.worktrees\meshcore-open-1098` is new tonight and holds the combined branch. +Worktree `C:\Dev\.worktrees\meshcore-open-1098` holds the combined branch. `meshcore-523` and `meshcore-1054` were removed; both their branches still exist. From 061451c48efd41635d8a01172a92ae8a887dc71b Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 4 Nov 2026 05:06:54 -0500 Subject: [PATCH 14/16] docs(#1095): record the checked MTU ordering, and the final artifacts The advert is requested from the device-info handler. On Android that is genuinely after MTU negotiation, because requestMtu(185) is awaited before service discovery and before device-info is asked for; elsewhere the platform reports the negotiated value through the MTU stream, so the request could in principle precede Dart observing it. It does not matter in practice, since the link-layer negotiation has already happened, today's advert fits inside even the 20-byte floor, and TAG_CONTINUE covers overflow. Flagged rather than left to be discovered, and checked in the connect path rather than asserted from the contract. Also notes that the Windows .exe is only the runner shell, so its timestamp does not move when Dart changes. The payload is data/app.so, which is what was verified and re-delivered. Co-Authored-By: Claude Opus 5 --- .../standalone/1094-offset-87-realignment/OUTCOMES.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md index 7d6b569f..a6a9b76f 100644 --- a/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md +++ b/docs/initiatives/standalone/1094-offset-87-realignment/OUTCOMES.md @@ -188,6 +188,8 @@ The earlier `offband-1094-offset87-realign.apk` was deleted so there is only one Nothing was installed on any device and no radio was touched. +**One ordering nuance, checked rather than assumed.** The advert is requested from the device-info handler, so on Android it is genuinely after MTU negotiation: `requestMtu(185)` is `await`ed before service discovery and before device-info is asked for. On other platforms the platform reports the negotiated value on its own through the MTU stream, so in principle the request could go out before Dart has observed the larger value. It does not matter in practice: the link-layer negotiation has already happened by then, today's advert is a handful of bytes and fits inside even the 20-byte floor, and `TAG_CONTINUE` covers overflow by design. Recording it because it is the sort of thing better flagged than discovered. + ### What to look at first 1. **A radio that predates the advert** (anything but `4e5a6c85`-era builds). The Radio sound control should still appear if caps2 `0x80` is set. That is the err-5 fallback, and it is the path I could not verify without your hardware. From 383ed5f9ee131ff3df2e2037a6e60964c1c661a3 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Thu, 5 Nov 2026 22:46:56 -0500 Subject: [PATCH 15/16] fix(#1060): erased slots never overwrite the channel list, and radio notify follows the channel Two findings from the owner's field report: a Channels screen full of replacement characters, and a channel he had silenced chirping again. An erased record is not an empty one. Erased flash reads back 0xFF and Channel.isEmpty tests for 0x00, so a slot the radio had LOST was adopted as a channel, rendered with U+FFFD, and then persisted over the client's own good cached list. One missing validation gate, two symptoms. - Channel.isErased / isUnusable: an all-0xFF record, or a name that did not decode, is never adopted. - A sync that sees an erased slot KEEPS the cached list, reusing the fail-closed branch #1062 already had for unconfirmed holes. - restoreChannelsToRadio() writes the cache back to the original slots with their PSKs, behind a confirmed banner action. Radio notify was keyed by slot, not identity. #544 landed after #1061 and keyed its in-memory map by slot index; the slot-identity handler cleared the slot's messages but not its notify mode, so a channel that moved slots handed its mode to the new occupant and lost its own. - _channelNotifyModes is keyed by PSK hex, matching channelNotifyModesByRadio (#848) and the PSK-keyed history (#194). - A reply whose slot does not resolve to a confirmed channel is dropped. - setChannelNotify takes a Channel and resolves its CURRENT slot at send time, so a stale handle cannot address the wrong one; unresolvable is a visible refusal, not a silent write. Both guards proved against planted defects: forcing isErased false turns 5 tests red including the cache overwrite, and restoring the slot-keyed map yields Expected: null, Actual: RadioChannelNotify.off. flutter analyze clean, 1885 tests pass. New strings English-only with untranslated.json regenerated. Task: meshcore-open-75d Agent: CalmBay Co-Authored-By: Claude Opus 5 --- .../OUTCOMES.md | 95 +++++++ lib/connector/meshcore_connector.dart | 182 ++++++++++++- lib/l10n/app_en.arb | 29 ++ lib/l10n/app_localizations.dart | 30 +++ lib/l10n/app_localizations_bg.dart | 22 ++ lib/l10n/app_localizations_de.dart | 22 ++ lib/l10n/app_localizations_en.dart | 22 ++ lib/l10n/app_localizations_es.dart | 22 ++ lib/l10n/app_localizations_fr.dart | 22 ++ lib/l10n/app_localizations_hu.dart | 22 ++ lib/l10n/app_localizations_it.dart | 22 ++ lib/l10n/app_localizations_ja.dart | 22 ++ lib/l10n/app_localizations_ko.dart | 22 ++ lib/l10n/app_localizations_nl.dart | 22 ++ lib/l10n/app_localizations_pl.dart | 22 ++ lib/l10n/app_localizations_pt.dart | 22 ++ lib/l10n/app_localizations_ru.dart | 22 ++ lib/l10n/app_localizations_sk.dart | 22 ++ lib/l10n/app_localizations_sl.dart | 22 ++ lib/l10n/app_localizations_sv.dart | 22 ++ lib/l10n/app_localizations_uk.dart | 22 ++ lib/l10n/app_localizations_zh.dart | 22 ++ lib/models/channel.dart | 17 ++ lib/screens/channels_screen.dart | 72 ++++- lib/widgets/radio_channel_notify.dart | 4 +- test/connector/channel_erased_slot_test.dart | 248 ++++++++++++++++++ .../channel_notify_connector_test.dart | 246 +++++++++++++++-- untranslated.json | 85 ++++++ 28 files changed, 1369 insertions(+), 35 deletions(-) create mode 100644 docs/initiatives/standalone/1060-channel-identity-alignment/OUTCOMES.md create mode 100644 test/connector/channel_erased_slot_test.dart diff --git a/docs/initiatives/standalone/1060-channel-identity-alignment/OUTCOMES.md b/docs/initiatives/standalone/1060-channel-identity-alignment/OUTCOMES.md new file mode 100644 index 00000000..1e855e92 --- /dev/null +++ b/docs/initiatives/standalone/1060-channel-identity-alignment/OUTCOMES.md @@ -0,0 +1,95 @@ +# Channel identity alignment: erased slots and slot-keyed notify (#1060) + +Agent: CalmBay. Branch `feat/1068-radio-channel-notify`. No push, no PR. + +## 1. Who owns the "key by identity, not slot" work + +**Feature #1061, agent TurquoiseBridge (session 82d77b2f).** The identity key is +the channel's **PSK hex**, not a pubkey; channels have no pubkey, and the PSK is +what both history and settings already hang off. + +| Issue | What | State | +|---|---|---| +| #1060 | the bug: slot map diverges after wipe + re-import, wrong-channel notifications | open | +| #1061 | feature: channel state follows channel identity | open | +| #1062 | fail-closed sync, ingress barrier, slot identity diff | landed | +| #1063 | message history keyed by channel identity | landed | +| #1064 | integration testing + #1060 bug validation | **open** | + +The pattern itself is older than #1061: `feat(#260)` (2026-07-17) introduced +PSK-keyed notify storage, `fix(#848)` scoped it per radio and killed the index +fallback, and `#194` keyed message history the same way. + +`test/connector/channel_slot_resync_integration_test.dart` already encodes the +exact field case, down to `#wardriving` set to OFF. + +## 2. What was still slot-keyed + +#544 (epics #1068-#1071, this branch) added the RADIO-side per-channel notify +after #1061 landed, and keyed it by **slot index**: + +```dart +final Map _channelNotifyModes = {}; +``` + +That re-opened the exact class of defect #1061 was built to close, on the one +surface where the user notices it fastest: the buzzer. The slot-identity-change +handler cleared `_channelMessages[slot]` but not `_channelNotifyModes[slot]`, +so after a slot shift the new occupant inherited the old one's mode. + +Reproduced by planting the slot-keyed map back and running the new A5 test: + +``` +Expected: null + Actual: RadioChannelNotify: +``` + +A channel silenced on the radio handing its Off to whatever took its slot, and +losing its own. That is the chirping. + +### Fixed + +- `_channelNotifyModes` is keyed by **PSK hex**. The wire stays slot-addressed; + the slot is resolved to an identity at the wire edge and nowhere else. +- A reply whose slot does not resolve to a confirmed channel is **dropped**, + not stored against a slot number. +- `setChannelNotify` takes a `Channel` and resolves its **current** slot at + send time, so a `Channel` a widget captured before a re-sync cannot address a + stale slot. Unresolvable means a visible refusal, no frame. + +## 3. The erased-slot defect + +Erased flash reads back as `0xFF`. `Channel.isEmpty` tests for `0x00`, so an +erased record is not empty: it was adopted as a channel, rendered with U+FFFD +replacement characters, and then **saved over the client's own good list**. + +That is one missing validation gate, not two defects. The rendering and the +overwrite are the same hole seen twice. + +### Fixed + +- `Channel.isErased` / `isUnusable`: an all-`0xFF` record, or a name that did + not decode, is never adopted. +- A sync that sees an erased slot **keeps the cached list** instead of + overwriting it, reusing the fail-closed branch #1062 already had for holes. +- `restoreChannelsToRadio()` writes the cached channels back to their own + slots, with their PSKs, so history and settings line up again. Surfaced as an + undismissable banner with a confirmed **Restore to radio** action. + +Probe: forcing `isErased => false` turns 5 of the new tests red, including the +cache overwrite. + +## 4. Recovery for the list already lost + +Not built, flagged for a decision. Message history keys are +`channel_messages_psk_`, so **the PSKs of the lost +channels still exist in the message store** even though the channel list was +overwritten. A recovery pass could enumerate those keys and rebuild the list. +Names would need retyping; the PSK is the part that matters. + +## 5. State + +`flutter analyze` clean. **1885 tests pass, 1 skipped.** New strings are +English-only with `untranslated.json` regenerated. + +Not pushed, no PR: the owner's gate is a hardware test first. diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 6f8c1500..594ea6a2 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -452,7 +452,14 @@ class MeshCoreConnector extends ChangeNotifier { /// Written only from a device reply, and cleared per radio like every other /// device-UI surface. Slot-derived state: #1061's identity diff must reset /// it when a slot's PSK changes, or it describes the wrong channel. - final Map _channelNotifyModes = {}; + // #1060/#544: keyed by channel PSK hex, NOT by slot index. The wire is + // slot-addressed, but a slot is not an identity: when a channel moves slots + // (wipe + re-import, manual reorder) a slot-keyed mode follows the SLOT and + // lands on whatever channel now sits there. That is how a channel set to + // None started chirping again. The slot is resolved at the wire edge only, + // and everything the client holds or shows is keyed by PSK, matching the + // app's own `channelNotifyModesByRadio` (#848) and PSK-keyed history (#194). + final Map _channelNotifyModes = {}; final Map _eventTones = {}; final Map _tuneSlots = {}; ScreenSettingsState? _screenSettings; @@ -616,6 +623,25 @@ class MeshCoreConnector extends ChangeNotifier { Set get unconfirmedChannelSlots => Set.unmodifiable(_unconfirmedChannelSlots); + // #1060: slots the device answered for with an ERASED record (all-0xFF). + // The device answering is not the same as the device having a channel: a + // reflash or a wipe leaves readable garbage, not silence. These are refused + // rather than adopted, and their presence blocks the cached-list overwrite + // below, because a cached list the user can still see is better data than + // erased flash. + final Set _erasedChannelSlots = {}; + + /// Device slots that answered with an erased record on the latest sync. + /// Non-empty means the radio lost channel storage and the client is holding + /// its own cached list instead (#1060). + Set get erasedChannelSlots => Set.unmodifiable(_erasedChannelSlots); + + /// True when the radio reported erased slots and the client therefore kept a + /// cached channel list the radio no longer has. The UI offers a restore. + bool get canRestoreChannelsToRadio => + _erasedChannelSlots.isNotEmpty && + _cachedChannels.any((c) => !c.isUnusable); + // #1062: ingress barrier. Live channel traffic is held while this // connection's channel list is not yet synced, then flushed, so a message // is never filed against a guessed slot map. Held MESSAGE frames are keyed @@ -1082,8 +1108,11 @@ class MeshCoreConnector extends ChangeNotifier { /// The radio's notify mode for [channel], or null until the radio has /// reported it. Null is "not yet known", distinct from /// [RadioChannelNotify.unset], which is the radio saying no choice is set. - RadioChannelNotify? channelNotifyFor(int channel) => - _channelNotifyModes[channel]; + /// + /// Looked up by the channel's PSK identity, so a mode read for one channel + /// can never be shown against another that later occupies its slot (#1060). + RadioChannelNotify? channelNotifyFor(Channel channel) => + _channelNotifyModes[channel.pskHex]; /// The tune the radio reported for [event], or null if not read yet. EventToneState? eventTone(ToneEvent event) => _eventTones[event]; @@ -1399,19 +1428,53 @@ class MeshCoreConnector extends ChangeNotifier { /// Set the radio's notify mode for [channel]. Local state follows the /// device's re-read reply, never the request, so a refused choice is never /// shown as saved. - Future setChannelNotify(int channel, RadioChannelNotify mode) async { + /// The slot [channel] currently occupies on the radio, by PSK identity, or + /// null when the synced list does not hold it. The caller's own + /// [Channel.index] is deliberately not trusted: it may have been captured + /// before a re-sync moved the channel, and writing to a stale slot is how a + /// setting lands on the wrong channel (#1060). + int? _liveSlotFor(Channel channel) { + if (!_channelListSynced) return null; + for (final c in _channels) { + if (c.pskHex == channel.pskHex && !c.isUnusable) return c.index; + } + return null; + } + + Future setChannelNotify( + Channel channel, + RadioChannelNotify mode, + ) async { if (!_deviceUiGateOpen('chnotify SET', advertised: supportsChannelNotify)) { return; } + final slot = _liveSlotFor(channel); + if (slot == null) { + // Fail closed and visibly, per #1021's rule: refuse the write and say + // why, rather than addressing a slot whose occupant is unconfirmed. + _deviceUiError = + 'This channel is not confirmed on the radio right now, so its ' + 'sound setting was not written. Refresh the channel list and try ' + 'again.'; + _deviceUiErrorSurface = DeviceUiSurface.channelNotify; + _pendingDeviceUiWrite = null; + _appDebugLogService?.error( + 'chnotify SET refused: "${channel.name}" (psk ${channel.pskHex}) ' + 'does not resolve to a confirmed slot; no frame sent', + tag: 'DeviceUI', + ); + notifyListeners(); + return; + } _deviceUiError = null; _deviceUiErrorSurface = null; _pendingDeviceUiWrite = DeviceUiSurface.channelNotify; _appDebugLogService?.info( - 'chnotify SET -> ch=$channel mode=${mode.name} ' + 'chnotify SET -> ch=$slot "${channel.name}" mode=${mode.name} ' 'stored=${mode.stored} [0xC5][0x19]', tag: 'DeviceUI', ); - await sendFrame(buildChannelNotifySetFrame(channel, mode)); + await sendFrame(buildChannelNotifySetFrame(slot, mode)); } /// Ask the radio how GPS is running (#969). @@ -1939,10 +2002,27 @@ class MeshCoreConnector extends ChangeNotifier { if (isWrite && _pendingDeviceUiWrite == DeviceUiSurface.channelNotify) { _pendingDeviceUiWrite = null; } - _channelNotifyModes[reply.channel] = reply.mode; + // #1060: the wire gives a slot; the client stores an identity. Resolve the + // slot against the synced list and drop the reply if it cannot be + // resolved, rather than filing a mode under a slot number that may mean a + // different channel by the time anything reads it. + final channel = _findChannelByIndex(reply.channel); + if (channel == null || channel.isUnusable) { + _appDebugLogService?.warn( + 'chnotify reply for slot ${reply.channel} ' + '(mode=${reply.mode.name}) does not resolve to a known channel; ' + 'dropped rather than stored against a slot number', + tag: 'DeviceUI', + ); + // A pending write was still cleared above, so the UI must be released + // from "saving" even though nothing was stored. + notifyListeners(); + return; + } + _channelNotifyModes[channel.pskHex] = reply.mode; _appDebugLogService?.info( - 'chnotify reply: ch=${reply.channel} mode=${reply.mode.name} ' - '(${isWrite ? 'write confirmed' : 'read'})', + 'chnotify reply: ch=${reply.channel} "${channel.name}" ' + 'mode=${reply.mode.name} (${isWrite ? 'write confirmed' : 'read'})', tag: 'DeviceUI', ); notifyListeners(); @@ -4413,6 +4493,11 @@ class MeshCoreConnector extends ChangeNotifier { _cachedChannels = List.from(channels); } + /// The last fully-confirmed channel list this client persisted. Survives a + /// sync that found erased slots, which is what makes a restore possible + /// (#1060). + List get cachedChannels => List.unmodifiable(_cachedChannels); + @visibleForTesting Channel? findChannelByIndexForTest(int index) => _findChannelByIndex(index); @@ -4510,6 +4595,7 @@ class MeshCoreConnector extends ChangeNotifier { // Raw sniff frames are lossy observations; a dead connection's are stale. _channelListSynced = false; _unconfirmedChannelSlots.clear(); + _erasedChannelSlots.clear(); _slotIdentityChanges.clear(); _heldRawChannelFrames.clear(); } @@ -6649,6 +6735,7 @@ class MeshCoreConnector extends ChangeNotifier { // against a stale one (#1062). _channelListSynced = false; _unconfirmedChannelSlots.clear(); + _erasedChannelSlots.clear(); _previousChannelsCache = List.from(_channels); _channels.clear(); _nextChannelIndexToRequest = 0; @@ -6781,7 +6868,19 @@ class MeshCoreConnector extends ChangeNotifier { } } - if (_unconfirmedChannelSlots.isEmpty) { + if (_erasedChannelSlots.isNotEmpty) { + // #1060: the radio answered, but for erased slots. "Device is truth" + // assumes the device HAS the truth; erased flash is the device having + // lost it. Writing this over the cache would turn one-sided loss on the + // radio into total loss, so the cached list stands and the UI offers to + // push it back. + _appDebugLogService?.error( + 'Channel sync found ERASED slots $_erasedChannelSlots. The radio has ' + 'lost those channels. Cached list NOT overwritten (${_cachedChannels.where((c) => !c.isUnusable).length} ' + 'channel(s) retained); use Restore to write them back to the radio.', + tag: 'ChannelSync', + ); + } else if (_unconfirmedChannelSlots.isEmpty) { // Full confirmation: the fresh list is the truth, replace the cache. _cachedChannels = List.from(_channels); unawaited( @@ -6990,6 +7089,44 @@ class MeshCoreConnector extends ChangeNotifier { await getChannels(force: true); } + /// Writes the client's cached channel list back onto the radio (#1060). + /// + /// For a radio that lost channel storage (reflash, wipe) the client's cache + /// is the only surviving copy. Each cached channel goes back to the slot it + /// came from, so PSK-keyed history and per-channel settings line up again. + /// + /// Frames are sent directly rather than through [setChannel] because that + /// re-syncs after every write; this re-syncs once at the end. Nothing here + /// clears history: the identities being restored are the ones that own it. + /// + /// Returns the number of channels written, or -1 when there was nothing to + /// restore or the link is down. + Future restoreChannelsToRadio() async { + if (!isConnected) return -1; + final toRestore = _cachedChannels.where((c) => !c.isUnusable).toList(); + if (toRestore.isEmpty) return -1; + + _appDebugLogService?.info( + 'Restoring ${toRestore.length} cached channel(s) to the radio: ' + '${toRestore.map((c) => 'slot ${c.index} "${c.name}"').join(', ')}', + tag: 'ChannelSync', + ); + + var written = 0; + for (final channel in toRestore) { + if (!isConnected) break; + await sendFrame( + buildSetChannelFrame(channel.index, channel.name, channel.psk), + ); + written++; + } + + // The radio now holds these again, so a fresh sync should confirm them and + // the erased-slot block clears itself on the next pass. + await getChannels(force: true); + return written; + } + Future deleteChannel(int index) async { if (!isConnected) return; @@ -10250,6 +10387,22 @@ class MeshCoreConnector extends ChangeNotifier { '[ChannelSync] Received channel ${channel.index}: ${channel.isEmpty ? "empty" : channel.name}', ); + // #1060: an erased record is the radio having LOST this slot, not the + // radio reporting a channel. Adopting it would render replacement + // characters as a channel name, and persisting it would destroy the + // client's own good copy. Refuse it here, loudly, and let the sync + // completion keep the cached list. + if (channel.isErased) { + if (_erasedChannelSlots.add(channel.index)) { + _appDebugLogService?.error( + 'Channel slot ${channel.index} came back ERASED (all-0xFF name/PSK). ' + 'The radio has lost this channel. Refusing to adopt it, and the ' + 'cached channel list will NOT be overwritten.', + tag: 'ChannelSync', + ); + } + } + // Preserve unread count from the cached channel, but only when the slot // still holds the SAME channel. An unread count following the slot across // an identity change is another channel's count (#1062). @@ -10269,8 +10422,9 @@ class MeshCoreConnector extends ChangeNotifier { _channelSyncInFlight = false; _channelSyncRetries = 0; // Reset retry counter on success - // Only add non-empty channels - if (!channel.isEmpty) { + // Only add slots that carry a usable channel. An erased slot is + // skipped exactly like an empty one (#1060). + if (!channel.isUnusable) { _channels.add(channel); } @@ -10286,7 +10440,7 @@ class MeshCoreConnector extends ChangeNotifier { '[ChannelSync] Received unexpected channel ${channel.index}, expected $_nextChannelIndexToRequest', ); // Add it anyway but don't advance sync - if (!channel.isEmpty && + if (!channel.isUnusable && !_channels.any((c) => c.index == channel.index)) { _channels.add(channel); } @@ -10295,7 +10449,7 @@ class MeshCoreConnector extends ChangeNotifier { } // Not syncing, or received unsolicited update - handle normally - if (!channel.isEmpty) { + if (!channel.isUnusable) { // Update or add channel final existingIndex = _channels.indexWhere( (c) => c.index == channel.index, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index afb24841..ef6edf19 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -845,6 +845,35 @@ } }, "channels_retrySync": "Retry sync", + "channels_erasedSlots": "The radio has lost the channels in slot(s) {slots}; it reported them as erased. Your channel list here has been kept and was not overwritten.", + "@channels_erasedSlots": { + "placeholders": { + "slots": { + "type": "String" + } + } + }, + "channels_restoreToRadio": "Restore to radio", + "channels_restoreToRadioConfirm": "Write {count} channel(s) back to the radio: {names}. This replaces whatever those slots hold now.", + "@channels_restoreToRadioConfirm": { + "placeholders": { + "count": { + "type": "int" + }, + "names": { + "type": "String" + } + } + }, + "channels_restoreToRadioDone": "Restored {count} channel(s) to the radio.", + "@channels_restoreToRadioDone": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "channels_restoreToRadioFailed": "Could not restore the channel list: nothing cached to restore, or the radio is not connected.", "channels_slotIdentityChanged": "Channel layout changed on the radio: {changes}", "@channels_slotIdentityChanged": { "placeholders": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 2543f3c7..47341f0e 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2830,6 +2830,36 @@ abstract class AppLocalizations { /// **'Retry sync'** String get channels_retrySync; + /// No description provided for @channels_erasedSlots. + /// + /// In en, this message translates to: + /// **'The radio has lost the channels in slot(s) {slots}; it reported them as erased. Your channel list here has been kept and was not overwritten.'** + String channels_erasedSlots(String slots); + + /// No description provided for @channels_restoreToRadio. + /// + /// In en, this message translates to: + /// **'Restore to radio'** + String get channels_restoreToRadio; + + /// No description provided for @channels_restoreToRadioConfirm. + /// + /// In en, this message translates to: + /// **'Write {count} channel(s) back to the radio: {names}. This replaces whatever those slots hold now.'** + String channels_restoreToRadioConfirm(int count, String names); + + /// No description provided for @channels_restoreToRadioDone. + /// + /// In en, this message translates to: + /// **'Restored {count} channel(s) to the radio.'** + String channels_restoreToRadioDone(int count); + + /// No description provided for @channels_restoreToRadioFailed. + /// + /// In en, this message translates to: + /// **'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'** + String get channels_restoreToRadioFailed; + /// No description provided for @channels_slotIdentityChanged. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index d6f41aef..15633656 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1587,6 +1587,28 @@ class AppLocalizationsBg extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 3fdb8e6d..cb80f11f 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1581,6 +1581,28 @@ class AppLocalizationsDe extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index bad9c5af..caa4dbe6 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1563,6 +1563,28 @@ class AppLocalizationsEn extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 9221fc2d..714ee1a9 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1582,6 +1582,28 @@ class AppLocalizationsEs extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 659f7080..72288df6 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1587,6 +1587,28 @@ class AppLocalizationsFr extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index 4cce9131..f7a5b079 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1588,6 +1588,28 @@ class AppLocalizationsHu extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index 1d159ebf..01f8db8e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1583,6 +1583,28 @@ class AppLocalizationsIt extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index c9a7da4b..936ae484 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1531,6 +1531,28 @@ class AppLocalizationsJa extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 64612a97..fb2c7b42 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1526,6 +1526,28 @@ class AppLocalizationsKo extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 08891ac8..931bf061 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1574,6 +1574,28 @@ class AppLocalizationsNl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index b28421a5..35fd6381 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1593,6 +1593,28 @@ class AppLocalizationsPl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 27958e40..d37c11ad 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1583,6 +1583,28 @@ class AppLocalizationsPt extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index fc6c41e0..d307a8ab 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1584,6 +1584,28 @@ class AppLocalizationsRu extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index 4c4a1d17..45f345ee 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1574,6 +1574,28 @@ class AppLocalizationsSk extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index 9d17168b..f387d76a 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1571,6 +1571,28 @@ class AppLocalizationsSl extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index c872f74a..0cba958d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1565,6 +1565,28 @@ class AppLocalizationsSv extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 70fb4af9..8a3b9dc5 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1579,6 +1579,28 @@ class AppLocalizationsUk extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index a78eac9f..6cb94e49 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1512,6 +1512,28 @@ class AppLocalizationsZh extends AppLocalizations { @override String get channels_retrySync => 'Retry sync'; + @override + String channels_erasedSlots(String slots) { + return 'The radio has lost the channels in slot(s) $slots; it reported them as erased. Your channel list here has been kept and was not overwritten.'; + } + + @override + String get channels_restoreToRadio => 'Restore to radio'; + + @override + String channels_restoreToRadioConfirm(int count, String names) { + return 'Write $count channel(s) back to the radio: $names. This replaces whatever those slots hold now.'; + } + + @override + String channels_restoreToRadioDone(int count) { + return 'Restored $count channel(s) to the radio.'; + } + + @override + String get channels_restoreToRadioFailed => + 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/models/channel.dart b/lib/models/channel.dart index 10135cf7..f39943c0 100644 --- a/lib/models/channel.dart +++ b/lib/models/channel.dart @@ -25,6 +25,23 @@ class Channel { bool get isEmpty => name.isEmpty && psk.every((b) => b == 0); + /// A slot the radio answered for that holds no usable channel. + /// + /// Erased flash reads back as 0xFF, not 0x00, so such a record is NOT + /// [isEmpty]: the name decodes through `allowMalformed` into U+FFFD + /// replacement characters and the PSK is all-ones. Both halves are checked + /// because either one being unreadable makes the record unusable as a + /// channel identity, and the PSK is what every per-channel setting is keyed + /// by (#1060). + /// + /// The client must never adopt one of these as a channel, and must never + /// persist a list containing one over a known-good cached list. + bool get isErased => + name.contains('�') || (psk.isNotEmpty && psk.every((b) => b == 0xFF)); + + /// A slot that carries no channel the client should hold, for either reason. + bool get isUnusable => isEmpty || isErased; + bool get isPublicChannel => pskHex == publicChannelPsk; static Channel? fromFrame(Uint8List frame) { diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 453f24c5..74b82e3c 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -209,6 +209,30 @@ class _ChannelsScreenState extends State ), ], ), + // #1060: the radio answered for these slots with erased + // records. Undismissable: the radio has lost channels the + // client still holds, and the only way out is to write them + // back or accept the loss deliberately. + if (connector.erasedChannelSlots.isNotEmpty) + MaterialBanner( + backgroundColor: Theme.of( + context, + ).colorScheme.errorContainer, + content: Text( + context.l10n.channels_erasedSlots( + connector.erasedChannelSlots.toList().join(', '), + ), + ), + actions: [ + if (connector.canRestoreChannelsToRadio) + TextButton( + onPressed: () => unawaited( + _confirmRestoreChannels(context, connector), + ), + child: Text(context.l10n.channels_restoreToRadio), + ), + ], + ), if (connector.slotIdentityChanges.isNotEmpty) MaterialBanner( content: Text( @@ -581,7 +605,7 @@ class _ChannelsScreenState extends State final live = tileContext.watch(); final effective = radioChannelNotifyEffective( tileContext, - live.channelNotifyFor(channel.index), + live.channelNotifyFor(channel), live.deviceNotifyScope, ); return ListTile( @@ -1616,6 +1640,52 @@ class _ChannelsScreenState extends State ); } + /// Writes the client's cached channels back onto a radio that lost them + /// (#1060). Confirmed first: it overwrites whatever those slots hold now. + Future _confirmRestoreChannels( + BuildContext context, + MeshCoreConnector connector, + ) async { + final toRestore = connector.cachedChannels + .where((c) => !c.isUnusable) + .toList(); + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => AlertDialog( + title: Text(dialogContext.l10n.channels_restoreToRadio), + content: Text( + dialogContext.l10n.channels_restoreToRadioConfirm( + toRestore.length, + toRestore.map((c) => c.name).join(', '), + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(dialogContext.l10n.common_cancel), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(dialogContext.l10n.channels_restoreToRadio), + ), + ], + ), + ); + if (confirmed != true) return; + + final written = await connector.restoreChannelsToRadio(); + if (!context.mounted) return; + showDismissibleSnackBar( + context, + content: Text( + written < 0 + ? context.l10n.channels_restoreToRadioFailed + : context.l10n.channels_restoreToRadioDone(written), + ), + persist: written < 0, + ); + } + void _confirmDeleteChannel( BuildContext context, MeshCoreConnector connector, diff --git a/lib/widgets/radio_channel_notify.dart b/lib/widgets/radio_channel_notify.dart index d976aac5..570de17b 100644 --- a/lib/widgets/radio_channel_notify.dart +++ b/lib/widgets/radio_channel_notify.dart @@ -84,7 +84,7 @@ void showRadioChannelNotifyDialog(BuildContext context, Channel channel) { // State follows the radio's reply, never the tap: until the radio has // answered for this slot there is no current value to tick, and a // write that it refuses never appears as saved. - final current = live.channelNotifyFor(channel.index); + final current = live.channelNotifyFor(channel); final error = live.deviceUiErrorSurface == DeviceUiSurface.channelNotify ? live.deviceUiError : null; @@ -132,7 +132,7 @@ void showRadioChannelNotifyDialog(BuildContext context, Channel channel) { trailing: mode == current ? const Icon(Icons.check) : null, onTap: () async { Navigator.pop(dialogContext); - await connector.setChannelNotify(channel.index, mode); + await connector.setChannelNotify(channel, mode); }, ), ], diff --git a/test/connector/channel_erased_slot_test.dart b/test/connector/channel_erased_slot_test.dart new file mode 100644 index 00000000..a5cd1e9e --- /dev/null +++ b/test/connector/channel_erased_slot_test.dart @@ -0,0 +1,248 @@ +// #1060: a radio that has LOST its channel storage still answers for every +// slot. Erased flash reads back as 0xFF, so the reply is a well-formed +// CHANNEL_INFO frame carrying garbage, not silence and not an error. +// +// The field case: a reflash between two sessions left slot 0 ("Public") +// intact and slots 1+ entirely 0xFF. The client adopted those records as +// channels, rendered their names as replacement characters, and then +// persisted them over the user's own good cached list, turning one-sided loss +// on the radio into loss on both sides. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _channelInfoFrame({ + required int index, + required String name, + required int pskSeed, +}) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + final nameBytes = name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + for (var i = 0; i < 16; i++) { + frame[34 + i] = (pskSeed + i) & 0xFF; + } + return frame; +} + +/// Everything after the slot index reads back as erased flash. +Uint8List _erasedFrame(int index) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + for (var i = 2; i < 50; i++) { + frame[i] = 0xFF; + } + return frame; +} + +Channel _channel(int index, String name, int pskSeed) => Channel( + index: index, + name: name, + psk: Uint8List.fromList(List.generate(16, (i) => (pskSeed + i) & 0xFF)), +); + +Future _settle([int turns = 25]) async { + for (var i = 0; i < turns; i++) { + await Future.delayed(Duration.zero); + } +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector c; + late List> sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + sent = []; + c = MeshCoreConnector(); + c.sendFrameOverrideForTest = (data) => sent.add(data.toList()); + c.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + group('the erased record itself', () { + test('an all-0xFF record is erased, and is NOT caught by isEmpty', () { + final erased = Channel.fromFrame(_erasedFrame(1))!; + + expect(erased.isErased, isTrue); + expect(erased.isUnusable, isTrue); + // This is the exact gap that let the garbage through: isEmpty tests for + // 0x00, and erased flash is 0xFF. + expect( + erased.isEmpty, + isFalse, + reason: 'if this ever passes, isEmpty alone would have been enough', + ); + }); + + test('the erased name is replacement characters, which is what showed', () { + final erased = Channel.fromFrame(_erasedFrame(1))!; + expect(erased.name, contains('�')); + }); + + test('a real channel is neither empty nor erased', () { + final real = Channel.fromFrame( + _channelInfoFrame(index: 0, name: 'Public', pskSeed: 10), + )!; + + expect(real.isErased, isFalse); + expect(real.isEmpty, isFalse); + expect(real.isUnusable, isFalse); + expect(real.name, 'Public'); + }); + + test('a genuinely empty slot is still empty, not erased', () { + final empty = Channel.fromFrame( + Uint8List(50)..[0] = respCodeChannelInfo, + )!; + + expect(empty.isEmpty, isTrue); + expect(empty.isErased, isFalse); + expect(empty.isUnusable, isTrue); + }); + }); + + group('sync against a radio that lost its channels', () { + /// The field case: slot 0 survived, slots 1 and 2 came back erased. + Future syncWithErasedTail() async { + await c.getChannels(force: true, maxChannels: 3); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Public', pskSeed: 10), + ); + await _settle(2); + c.handleFrameForTest(_erasedFrame(1)); + await _settle(2); + c.handleFrameForTest(_erasedFrame(2)); + await _settle(); + } + + test('erased slots are not adopted as channels', () async { + await syncWithErasedTail(); + + expect(c.channels.map((ch) => ch.index), [0]); + expect(c.channels.single.name, 'Public'); + expect( + c.channels.any((ch) => ch.name.contains('�')), + isFalse, + reason: 'no channel may be named with replacement characters', + ); + }); + + test( + 'erased slots are reported, so the UI can say what happened', + () async { + await syncWithErasedTail(); + + expect(c.erasedChannelSlots, {1, 2}); + }, + ); + + test('the good cached list is NOT overwritten', () async { + c.seedCachedChannelsForTest([ + _channel(0, 'Public', 10), + _channel(1, 'wardriving', 40), + _channel(2, 'test', 50), + ]); + + await syncWithErasedTail(); + + // The data-loss fix: the client keeps its own copy of the channels the + // radio has lost, rather than saving erased records over them. + expect(c.cachedChannels.map((ch) => ch.name), [ + 'Public', + 'wardriving', + 'test', + ]); + expect(c.canRestoreChannelsToRadio, isTrue); + }); + + test('a clean sync still replaces the cache', () async { + c.seedCachedChannelsForTest([_channel(0, 'stale', 99)]); + + await c.getChannels(force: true, maxChannels: 2); + c.handleFrameForTest( + _channelInfoFrame(index: 0, name: 'Public', pskSeed: 10), + ); + await _settle(2); + c.handleFrameForTest( + _channelInfoFrame(index: 1, name: 'wardriving', pskSeed: 40), + ); + await _settle(); + + expect( + c.cachedChannels.map((ch) => ch.name), + ['Public', 'wardriving'], + reason: 'the guard must not block a healthy sync', + ); + expect(c.erasedChannelSlots, isEmpty); + expect(c.canRestoreChannelsToRadio, isFalse); + }); + }); + + group('restoring the list to the radio', () { + test('every cached channel is written back to its own slot', () async { + c.seedCachedChannelsForTest([ + _channel(0, 'Public', 10), + _channel(1, 'wardriving', 40), + ]); + sent.clear(); + + final written = await c.restoreChannelsToRadio(); + + expect(written, 2); + final setFrames = sent.where((f) => f[0] == cmdSetChannel).toList(); + expect(setFrames.length, 2); + expect(setFrames[0][1], 0); + expect(setFrames[1][1], 1); + // The PSK travels with it, so the restored channel keeps the identity + // its history and settings are keyed by. + expect(setFrames[1].sublist(34, 50), _channel(1, 'wardriving', 40).psk); + }); + + test('an erased cached entry is never written back', () async { + c.seedCachedChannelsForTest([ + _channel(0, 'Public', 10), + Channel.fromFrame(_erasedFrame(1))!, + ]); + sent.clear(); + + final written = await c.restoreChannelsToRadio(); + + expect(written, 1); + expect(sent.where((f) => f[0] == cmdSetChannel).length, 1); + }); + + test( + 'restoring with nothing cached is refused, not a silent no-op', + () async { + c.seedCachedChannelsForTest([]); + + expect(await c.restoreChannelsToRadio(), -1); + expect(sent.where((f) => f[0] == cmdSetChannel), isEmpty); + }, + ); + }); +} diff --git a/test/connector/channel_notify_connector_test.dart b/test/connector/channel_notify_connector_test.dart index 92a1a2ae..b398e613 100644 --- a/test/connector/channel_notify_connector_test.dart +++ b/test/connector/channel_notify_connector_test.dart @@ -18,6 +18,7 @@ import 'package:meshcore_open/connector/offband_capability_advert.dart'; import 'package:meshcore_open/connector/offband_channel_notify.dart'; import 'package:meshcore_open/connector/offband_device_ui.dart'; import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/models/channel.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/storage/drift/blob_store.dart'; import 'package:meshcore_open/storage/drift/offband_database.dart'; @@ -46,6 +47,55 @@ Uint8List deviceInfo({ return f; } +/// A RESP_CODE_CHANNEL_INFO frame. [pskSeed] makes each channel's PSK, and so +/// its identity, distinct. +Uint8List channelInfoFrame({ + required int index, + required String name, + required int pskSeed, +}) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + final nameBytes = name.codeUnits; + for (var i = 0; i < nameBytes.length && i < 31; i++) { + frame[2 + i] = nameBytes[i]; + } + for (var i = 0; i < 16; i++) { + frame[34 + i] = (pskSeed + i) & 0xFF; + } + return frame; +} + +/// A slot whose stored record was erased: flash reads back as 0xFF, so the +/// name decodes to replacement characters and the PSK is all-ones (#1060). +Uint8List erasedChannelInfoFrame(int index) { + final frame = Uint8List(50); + frame[0] = respCodeChannelInfo; + frame[1] = index; + for (var i = 2; i < 50; i++) { + frame[i] = 0xFF; + } + return frame; +} + +/// A standalone Channel for tests that never sync a list, e.g. the capability +/// gate, which must refuse before it ever looks a slot up. +Channel testChannel(int index, {String name = 'ch', int pskSeed = 10}) => + Channel( + index: index, + name: name, + psk: Uint8List.fromList( + List.generate(16, (i) => (pskSeed + i) & 0xFF), + ), + ); + +Future settle([int turns = 25]) async { + for (var i = 0; i < turns; i++) { + await Future.delayed(Duration.zero); + } +} + void main() { late OffbandDatabase db; late MeshCoreConnector connector; @@ -68,6 +118,26 @@ void main() { await db.close(); }); + /// Drives a full channel sync so slot indices are confirmed. The radio's + /// notify modes are only meaningful past that barrier (#1062), and since + /// #1060 the client resolves every slot to a channel identity, so a test + /// that never syncs has no identities to resolve against. + Future syncChannels( + List<({int index, String name, int seed})> arrangement, + ) async { + await connector.getChannels(force: true, maxChannels: arrangement.length); + for (final ch in arrangement) { + connector.handleFrameForTest( + channelInfoFrame(index: ch.index, name: ch.name, pskSeed: ch.seed), + ); + await settle(2); + } + await settle(); + } + + Channel slot(int index) => + connector.channels.firstWhere((c) => c.index == index); + bool sentChannelNotify() => sent.any( (f) => f.length >= 2 && @@ -81,10 +151,15 @@ void main() { group('A1 radio channel notify', () { test('the wire bytes are the documented ones', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + (index: 2, name: 'wardriving', seed: 40), + ]); sent.clear(); await connector.requestChannelNotify(2); - await connector.setChannelNotify(2, RadioChannelNotify.mentions); + await connector.setChannelNotify(slot(2), RadioChannelNotify.mentions); expect( sent, @@ -95,49 +170,179 @@ void main() { ); }); - test('a reply sets that slot, and only that slot', () { + test('a reply sets that channel, and only that channel', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + (index: 2, name: 'wardriving', seed: 40), + ]); connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x02]); - expect(connector.channelNotifyFor(1), RadioChannelNotify.mentions); - expect(connector.channelNotifyFor(0), isNull); - expect(connector.channelNotifyFor(2), isNull); + expect(connector.channelNotifyFor(slot(1)), RadioChannelNotify.mentions); + expect(connector.channelNotifyFor(slot(0)), isNull); + expect(connector.channelNotifyFor(slot(2)), isNull); }); - test('mode 0 is unset, and is distinct from Off', () { + test('mode 0 is unset, and is distinct from Off', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + ]); connector.handleFrameForTest([0xC5, 0x18, 0x00, 0x00]); connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]); - expect(connector.channelNotifyFor(0), RadioChannelNotify.unset); - expect(connector.channelNotifyFor(1), RadioChannelNotify.off); + expect(connector.channelNotifyFor(slot(0)), RadioChannelNotify.unset); + expect(connector.channelNotifyFor(slot(1)), RadioChannelNotify.off); }); test('a write is not shown until the radio confirms it', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); - await connector.setChannelNotify(3, RadioChannelNotify.off); + await syncChannels([(index: 3, name: 'wardriving', seed: 40)]); + await connector.setChannelNotify(slot(3), RadioChannelNotify.off); - expect(connector.channelNotifyFor(3), isNull); + expect(connector.channelNotifyFor(slot(3)), isNull); connector.handleFrameForTest([0xC5, 0x19, 0x03, 0x03]); - expect(connector.channelNotifyFor(3), RadioChannelNotify.off); + expect(connector.channelNotifyFor(slot(3)), RadioChannelNotify.off); }); - test('an unknown mode byte is dropped, never guessed at', () { + test('an unknown mode byte is dropped, never guessed at', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([(index: 4, name: 'wardriving', seed: 40)]); connector.handleFrameForTest([0xC5, 0x18, 0x04, 0x09]); - expect(connector.channelNotifyFor(4), isNull); + expect(connector.channelNotifyFor(slot(4)), isNull); expect(parseChannelNotifyReply([0xC5, 0x18, 0x04, 0x09]), isNull); }); - test('state does not survive a change of radio', () { + test('state does not survive a change of radio', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([(index: 1, name: 'wardriving', seed: 40)]); + final wardriving = slot(1); connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x01]); - expect(connector.channelNotifyFor(1), RadioChannelNotify.all); + expect(connector.channelNotifyFor(wardriving), RadioChannelNotify.all); + + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + expect(connector.channelNotifyFor(wardriving), isNull); + }); + + test( + 'a reply for a slot with no confirmed channel is dropped, not stored', + () async { + connector.handleFrameForTest( + deviceInfo(caps2: offbandCap2ChannelNotify), + ); + await syncChannels([(index: 0, name: 'Public', seed: 10)]); + + // Slot 7 was never confirmed. Storing this against slot 7 is what let + // a later occupant of that slot inherit the mode (#1060). + connector.handleFrameForTest([0xC5, 0x18, 0x07, 0x03]); + + expect(connector.channels.any((c) => c.index == 7), isFalse); + expect(connector.channelNotifyFor(slot(0)), isNull); + }, + ); + }); + + // ---- A5: the mode follows the channel, not the slot (#1060) -------------- + + group('A5 radio notify is keyed by channel identity', () { + test('a mode read for one channel does not appear on the channel that ' + 'later takes its slot', () async { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + // #wardriving sits in slot 1 and the radio reports it as Off. + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'wardriving', seed: 40), + ]); + final wardriving = slot(1); + connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]); + expect(connector.channelNotifyFor(wardriving), RadioChannelNotify.off); + + // A wipe and re-import puts a DIFFERENT channel in slot 1. + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + ]); + final testCh = slot(1); + + // The new occupant must not inherit #wardriving's Off. Before this + // fix the slot-keyed map handed it straight over, which is how a + // channel the owner had silenced started chirping again. + expect(testCh.pskHex, isNot(wardriving.pskHex)); + expect(connector.channelNotifyFor(testCh), isNull); + }); + test('a mode survives the channel moving to a different slot', () async { connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); - expect(connector.channelNotifyFor(1), isNull); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'wardriving', seed: 40), + ]); + connector.handleFrameForTest([0xC5, 0x18, 0x01, 0x03]); + + // Same channel, new slot. + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + (index: 2, name: 'wardriving', seed: 40), + ]); + + expect(connector.channelNotifyFor(slot(2)), RadioChannelNotify.off); + expect(connector.channelNotifyFor(slot(1)), isNull); + }); + + test( + 'a write addresses the channel current slot, not a stale one', + () async { + connector.handleFrameForTest( + deviceInfo(caps2: offbandCap2ChannelNotify), + ); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'wardriving', seed: 40), + ]); + // A Channel captured while it was in slot 1, as a UI widget holds one. + final staleHandle = slot(1); + + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'test', seed: 50), + (index: 2, name: 'wardriving', seed: 40), + ]); + sent.clear(); + + await connector.setChannelNotify(staleHandle, RadioChannelNotify.off); + + // Addressed to slot 2, where #wardriving actually is now. + expect( + sent, + equals([ + [0xC5, 0x19, 0x02, 0x03], + ]), + ); + }, + ); + + test('a write for a channel the radio does not hold is refused', () async { + connector.handleFrameForTest(deviceInfo(caps2: offbandCap2ChannelNotify)); + await syncChannels([ + (index: 0, name: 'Public', seed: 10), + (index: 1, name: 'wardriving', seed: 40), + ]); + final gone = slot(1); + + // The channel is deleted on the radio. + await syncChannels([(index: 0, name: 'Public', seed: 10)]); + sent.clear(); + + await connector.setChannelNotify(gone, RadioChannelNotify.off); + + expect(sent, isEmpty); + expect(connector.deviceUiError, isNotNull); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.channelNotify); }); }); @@ -211,7 +416,7 @@ void main() { test('without 0x80 no channel-notify frame is ever emitted', () async { connector.handleFrameForTest(deviceInfo(caps2: 0x40)); await connector.requestChannelNotify(0); - await connector.setChannelNotify(0, RadioChannelNotify.off); + await connector.setChannelNotify(testChannel(0), RadioChannelNotify.off); expect(connector.supportsChannelNotify, isFalse); expect(sentChannelNotify(), isFalse); @@ -450,7 +655,12 @@ void main() { // hide a genuinely refused write and wrongly mark the radio as predating // the advert. connector.handleFrameForTest(deviceInfo(caps2: 0x80)); - await connector.setChannelNotify(0, RadioChannelNotify.off); + // The channel must really exist, so the write really goes out: a write + // refused for an unresolvable slot would also set deviceUiError and + // pass this test for the wrong reason. + await syncChannels([(index: 0, name: 'Public', seed: 10)]); + await connector.setChannelNotify(slot(0), RadioChannelNotify.off); + expect(sentChannelNotify(), isTrue); connector.handleFrameForTest(advertUnsupported()); expect( diff --git a/untranslated.json b/untranslated.json index 054ed262..5b143e3e 100644 --- a/untranslated.json +++ b/untranslated.json @@ -128,6 +128,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -477,6 +482,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -826,6 +836,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1175,6 +1190,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1524,6 +1544,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1873,6 +1898,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -2222,6 +2252,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -2571,6 +2606,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -2920,6 +2960,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3269,6 +3314,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3618,6 +3668,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3967,6 +4022,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -4316,6 +4376,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -4665,6 +4730,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5014,6 +5084,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5363,6 +5438,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5712,6 +5792,11 @@ "contact_cliConsole", "channels_unconfirmedSlots", "channels_retrySync", + "channels_erasedSlots", + "channels_restoreToRadio", + "channels_restoreToRadioConfirm", + "channels_restoreToRadioDone", + "channels_restoreToRadioFailed", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", From bd0744e472ced9d05db6942d754c97dd0bb095a6 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Fri, 6 Nov 2026 01:28:56 -0500 Subject: [PATCH 16/16] fix(#1060): drop erased records on load, and pace the restore writes Adversarial review (gemini-2.5-pro) on the push candidate raised five findings. Two were real and are fixed here; the other three are justified in the PR body. Storage is an untrusted source too. The guards already on this branch stop an erased (all-0xFF) record being adopted from the WIRE, but a build from before they existed could have persisted one, and loadCachedChannels applied no filter. _cachedChannels is a fallback identity source for _findChannelByIndex and is re-saved by the unread paths, so such a record comes back as the channel for live traffic and outlives every radio. It is dropped at the load boundary, which protects every consumer at once. It carries nothing recoverable: the name is U+FFFD and the PSK is all-ones. restoreChannelsToRadio sent its writes in an unpaced loop. On BLE sendFrame prefers write-without-response, so its await returns when the frame reaches the OS and not when the radio has taken it: a multi-channel restore could overrun the radio and lose channels with no error raised anywhere. The USB branch of sendFrame already spaces its own frames for exactly this reason. Same 10ms gap between consecutive channel writes. The restore result is documented as written and NOT confirmed. Counting confirmations after the re-sync was tried and reverted: getChannels returns once the first request is away rather than once the sync has finished, so it would have read a list the radio had not answered for and reported zero every time. The erased-slot banner is re-derived on every sync and stays up if writes did not land, so it remains the authoritative signal. Both new guards proved against planted defects rather than assumed: removing the load filter turns 2 tests red, and removing the pacing yields "Expected: a value greater than or equal to <20>, Actual: <0>". flutter analyze clean, 1896 tests pass, 1 skipped. Co-Authored-By: Claude Opus 5 --- lib/connector/meshcore_connector.dart | 54 ++++++++++-- lib/l10n/app_en.arb | 2 +- lib/l10n/app_localizations.dart | 6 ++ lib/l10n/app_localizations_bg.dart | 5 ++ lib/l10n/app_localizations_de.dart | 5 ++ lib/l10n/app_localizations_en.dart | 5 ++ lib/l10n/app_localizations_es.dart | 5 ++ lib/l10n/app_localizations_fr.dart | 5 ++ lib/l10n/app_localizations_hu.dart | 5 ++ lib/l10n/app_localizations_it.dart | 5 ++ lib/l10n/app_localizations_ja.dart | 5 ++ lib/l10n/app_localizations_ko.dart | 5 ++ lib/l10n/app_localizations_nl.dart | 5 ++ lib/l10n/app_localizations_pl.dart | 5 ++ lib/l10n/app_localizations_pt.dart | 5 ++ lib/l10n/app_localizations_ru.dart | 5 ++ lib/l10n/app_localizations_sk.dart | 5 ++ lib/l10n/app_localizations_sl.dart | 5 ++ lib/l10n/app_localizations_sv.dart | 5 ++ lib/l10n/app_localizations_uk.dart | 5 ++ lib/l10n/app_localizations_zh.dart | 5 ++ test/connector/channel_erased_slot_test.dart | 90 ++++++++++++++++++++ untranslated.json | 17 ++++ 23 files changed, 253 insertions(+), 6 deletions(-) diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index b8a40270..48427c75 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -619,6 +619,11 @@ class MeshCoreConnector extends ChangeNotifier { List _previousChannelsCache = []; static const int _maxChannelSyncRetries = 3; + /// Gap between consecutive channel writes in [restoreChannelsToRadio], so a + /// multi-channel restore cannot outrun the radio. Matches the spacing the USB + /// branch of [sendFrame] already applies per frame (#1060). + static const Duration _channelRestoreFrameGap = Duration(milliseconds: 10); + // #1062: fail-closed channel sync. A slot the device never answered for is // UNKNOWN: tracked here, surfaced to the UI, and never backfilled from a // previous list (that backfill is how a stale slot map misrouted @@ -2542,7 +2547,24 @@ class MeshCoreConnector extends ChangeNotifier { } Future loadCachedChannels() async { - _cachedChannels = await _channelStore.loadChannels(); + // #1060: a build from before `isErased` existed could persist an erased + // (all-0xFF) record over the good list, so storage itself may hold records + // that are not channel identities. Drop them at the boundary rather than + // at each use: [_cachedChannels] is a fallback identity source for + // [_findChannelByIndex] and is re-saved by the unread paths, so one that + // slips in here comes back as the channel for live traffic and outlives + // every radio. They carry nothing recoverable (name is U+FFFD, PSK is + // all-ones), so dropping them loses no information. + final loaded = await _channelStore.loadChannels(); + final usable = loaded.where((c) => !c.isUnusable).toList(); + if (usable.length != loaded.length) { + _appDebugLogService?.warn( + 'Dropped ${loaded.length - usable.length} unusable channel record(s) ' + 'from storage on load; a pre-#1060 build had persisted erased slots', + tag: 'ChannelSync', + ); + } + _cachedChannels = usable; _recalculateCachedChannelsUnreadTotal(); } @@ -4465,6 +4487,12 @@ class MeshCoreConnector extends ChangeNotifier { void setContactSettingsKeyForTest(String radioKeyHex) => _contactSettingsStore.setPublicKeyHex = radioKeyHex; + /// Scopes the channel store without a connect handshake, so the persisted + /// load path can be exercised directly. (#1060) + @visibleForTesting + void setChannelStoreKeyForTest(String radioKeyHex) => + _channelStore.setPublicKeyHex = radioKeyHex; + /// Feeds a device frame through the normal dispatch, so parse paths can be /// exercised without a radio. (#578) @visibleForTesting @@ -7124,7 +7152,8 @@ class MeshCoreConnector extends ChangeNotifier { /// clears history: the identities being restored are the ones that own it. /// /// Returns the number of channels written, or -1 when there was nothing to - /// restore or the link is down. + /// restore or the link is down. Written is not the same as confirmed: the + /// erased-slot banner is what tells the user the radio took them. Future restoreChannelsToRadio() async { if (!isConnected) return -1; final toRestore = _cachedChannels.where((c) => !c.isUnusable).toList(); @@ -7136,19 +7165,34 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'ChannelSync', ); - var written = 0; + var sent = 0; for (final channel in toRestore) { if (!isConnected) break; await sendFrame( buildSetChannelFrame(channel.index, channel.name, channel.psk), ); - written++; + sent++; + // Space the writes. On BLE [sendFrame] prefers write-without-response, + // which returns once the frame reaches the OS and not once the radio has + // taken it, so an unpaced loop can overrun the radio and lose channels + // with no error anywhere. The USB branch of [sendFrame] already spaces + // its own frames for exactly this reason; BLE has no such pause. + if (sent < toRestore.length) { + await Future.delayed(_channelRestoreFrameGap); + } } // The radio now holds these again, so a fresh sync should confirm them and // the erased-slot block clears itself on the next pass. + // + // This deliberately does NOT report how many the radio confirmed: + // [getChannels] returns once the first request is away, not once the sync + // has finished, so counting confirmations here would read a list the radio + // has not answered for yet and report 0 every time. The authoritative + // feedback is the erased-slot banner, which is re-derived on every sync and + // therefore stays up if some writes did not land. await getChannels(force: true); - return written; + return sent; } Future deleteChannel(int index) async { diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 726644ff..67a35e60 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -887,7 +887,7 @@ } } }, - "channels_restoreToRadioDone": "Restored {count} channel(s) to the radio.", + "channels_restoreToRadioDone": "Wrote {count} channel(s) back to the radio. If the warning above stays, some did not take.", "@channels_restoreToRadioDone": { "placeholders": { "count": { diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 7627cf2d..e9143266 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -2908,6 +2908,12 @@ abstract class AppLocalizations { /// **'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'** String get channels_restoreToRadioFailed; + /// No description provided for @channels_restoreToRadioPartial. + /// + /// In en, this message translates to: + /// **'Only {written} of {total} channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'** + String channels_restoreToRadioPartial(int written, int total); + /// No description provided for @channels_slotIdentityChanged. /// /// In en, this message translates to: diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 6e271fb5..71cc4b54 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -1640,6 +1640,11 @@ class AppLocalizationsBg extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 00745c5d..2e3c621b 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -1634,6 +1634,11 @@ class AppLocalizationsDe extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 82f9c71c..61292838 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -1616,6 +1616,11 @@ class AppLocalizationsEn extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 92e7cbb2..aae1876e 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -1635,6 +1635,11 @@ class AppLocalizationsEs extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index 2f480d41..35548842 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -1640,6 +1640,11 @@ class AppLocalizationsFr extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index e7773d74..a7620c80 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -1641,6 +1641,11 @@ class AppLocalizationsHu extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index ed6648b9..e8cd3199 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -1636,6 +1636,11 @@ class AppLocalizationsIt extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index 4839f452..3e872186 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -1584,6 +1584,11 @@ class AppLocalizationsJa extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 005ecd2d..504d09a1 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -1579,6 +1579,11 @@ class AppLocalizationsKo extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index 211699bf..65e4a765 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -1627,6 +1627,11 @@ class AppLocalizationsNl extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index 00f50105..db61d00d 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -1646,6 +1646,11 @@ class AppLocalizationsPl extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index 952b743c..2805a9fb 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -1636,6 +1636,11 @@ class AppLocalizationsPt extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 9e83146f..ea40f812 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -1637,6 +1637,11 @@ class AppLocalizationsRu extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index a252ae03..2f0c9a09 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -1627,6 +1627,11 @@ class AppLocalizationsSk extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index a5a886ac..cabae35c 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -1624,6 +1624,11 @@ class AppLocalizationsSl extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index a81ab444..716dbdf2 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -1618,6 +1618,11 @@ class AppLocalizationsSv extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index 8f6b18fc..d3f3f227 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -1632,6 +1632,11 @@ class AppLocalizationsUk extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index d063a542..a40445dc 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -1565,6 +1565,11 @@ class AppLocalizationsZh extends AppLocalizations { String get channels_restoreToRadioFailed => 'Could not restore the channel list: nothing cached to restore, or the radio is not connected.'; + @override + String channels_restoreToRadioPartial(int written, int total) { + return 'Only $written of $total channel(s) came back after the restore. The radio did not take the rest. Try the restore again.'; + } + @override String channels_slotIdentityChanged(String changes) { return 'Channel layout changed on the radio: $changes'; diff --git a/test/connector/channel_erased_slot_test.dart b/test/connector/channel_erased_slot_test.dart index a5cd1e9e..7d5a1cd1 100644 --- a/test/connector/channel_erased_slot_test.dart +++ b/test/connector/channel_erased_slot_test.dart @@ -15,6 +15,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; import 'package:meshcore_open/storage/drift/blob_store.dart'; import 'package:meshcore_open/storage/drift/offband_database.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; @@ -244,5 +245,94 @@ void main() { expect(sent.where((f) => f[0] == cmdSetChannel), isEmpty); }, ); + + // Adversarial review finding: on BLE sendFrame prefers write-without- + // response, so its await returns when the frame reaches the OS and not + // when the radio has taken it. An unpaced loop can therefore overrun the + // radio and drop channels with no error raised anywhere. The USB branch + // of sendFrame already spaces its frames; this loop must too. + test( + 'consecutive channel writes are spaced, not fired in a tight loop', + () async { + c.seedCachedChannelsForTest([ + _channel(0, 'Public', 10), + _channel(1, 'wardriving', 40), + _channel(2, 'test', 70), + ]); + sent.clear(); + + final sw = Stopwatch()..start(); + final written = await c.restoreChannelsToRadio(); + sw.stop(); + + expect(written, 3); + // Two gaps between three writes. A lower bound, so this asserts the + // pacing exists without pinning the exact duration. + expect( + sw.elapsedMilliseconds, + greaterThanOrEqualTo(20), + reason: 'three writes with no spacing would return almost instantly', + ); + }, + ); + }); + + // Adversarial review finding: the guards added here stop an erased record + // being adopted from the WIRE, but a build from before they existed could + // already have persisted one. Storage is therefore an untrusted source too, + // and _cachedChannels is a fallback identity source for _findChannelByIndex + // as well as being re-saved by the unread paths, so one that slips in comes + // back as the channel for live traffic and outlives every radio. + group('erased records already sitting in storage', () { + const radioKey = 'aabbccddee'; + + test('are dropped on load, not adopted from the cache', () async { + final store = ChannelStore()..setPublicKeyHex = radioKey; + await store.saveChannels([ + _channel(0, 'Public', 10), + Channel.fromFrame(_erasedFrame(1))!, + _channel(2, 'wardriving', 40), + ]); + // The store itself is faithful: it persisted exactly what it was given, + // which is how the bad record got there in the first place. + expect((await store.loadChannels()).length, 3); + + c.setChannelStoreKeyForTest(radioKey); + await c.loadCachedChannels(); + + expect(c.cachedChannels.map((ch) => ch.name), ['Public', 'wardriving']); + expect(c.cachedChannels.any((ch) => ch.isUnusable), isFalse); + }); + + test('a clean stored list is loaded untouched', () async { + final store = ChannelStore()..setPublicKeyHex = radioKey; + await store.saveChannels([ + _channel(0, 'Public', 10), + _channel(1, 'wardriving', 40), + ]); + + c.setChannelStoreKeyForTest(radioKey); + await c.loadCachedChannels(); + + expect(c.cachedChannels.length, 2); + expect(c.cachedChannels.map((ch) => ch.name), ['Public', 'wardriving']); + }); + + test('an all-erased stored list leaves nothing to restore', () async { + final store = ChannelStore()..setPublicKeyHex = radioKey; + await store.saveChannels([ + Channel.fromFrame(_erasedFrame(0))!, + Channel.fromFrame(_erasedFrame(1))!, + ]); + + c.setChannelStoreKeyForTest(radioKey); + await c.loadCachedChannels(); + + expect(c.cachedChannels, isEmpty); + // Nothing usable cached means the restore is refused rather than + // writing erased records back onto the radio. + expect(await c.restoreChannelsToRadio(), -1); + expect(sent.where((f) => f[0] == cmdSetChannel), isEmpty); + }); }); } diff --git a/untranslated.json b/untranslated.json index b34f1b93..50f1f65d 100644 --- a/untranslated.json +++ b/untranslated.json @@ -141,6 +141,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -503,6 +504,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -865,6 +867,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1227,6 +1230,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1589,6 +1593,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -1951,6 +1956,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -2313,6 +2319,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -2675,6 +2682,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3037,6 +3045,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3399,6 +3408,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -3761,6 +3771,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -4123,6 +4134,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -4485,6 +4497,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -4847,6 +4860,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5209,6 +5223,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5571,6 +5586,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications", @@ -5933,6 +5949,7 @@ "channels_restoreToRadioConfirm", "channels_restoreToRadioDone", "channels_restoreToRadioFailed", + "channels_restoreToRadioPartial", "channels_slotIdentityChanged", "common_dismiss", "channels_notifications",