Merge pull request #1008 from OffbandMesh/dev

release: promote 1.7.0+68 to main
main
Strycher 1 month ago committed by GitHub
commit 7734d681e8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -8,19 +8,83 @@ on:
pull_request:
jobs:
# #904: decides whether this change touches only documentation. Plain git,
# no third-party actions - the merge gate must not grow a supply-chain
# dependency. Every build job below still RUNS (so all required check names
# report), but short-circuits its steps to an honest success when the diff
# is docs-only. A wrong classification must only ever waste a build, never
# skip one, so every ambiguous case classifies as code.
classify:
runs-on: ubuntu-latest
outputs:
docs_only: ${{ steps.diff.outputs.docs_only }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Classify changed files
id: diff
run: |
set -eu
# No override, by design (#927). The #904 spike added an env flag
# that forced docs_only=true, it reached dev, and for every PR after
# it the build and test jobs reported pass in a few seconds having
# built nothing. A switch that turns every merge gate in the repo
# into a no-op, silently, is not worth the convenience of testing
# this job against itself.
if [ "${{ github.event_name }}" = "pull_request" ]; then
# checkout hands us the PR merge commit; parent 1 is the current
# base tip, so this is exactly the PR's effective diff.
git diff --name-only HEAD^1 HEAD > changed.txt
else
before="${{ github.event.before }}"
if [ "$before" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$before" 2>/dev/null; then
echo "no usable before-SHA; classifying as code"
echo "docs_only=false" >> "$GITHUB_OUTPUT"
exit 0
fi
git diff --name-only "$before" "${{ github.sha }}" > changed.txt
fi
echo "changed files:"
cat changed.txt
if [ ! -s changed.txt ]; then
echo "empty diff; classifying as code"
echo "docs_only=false" >> "$GITHUB_OUTPUT"
exit 0
fi
docs_only=true
while IFS= read -r f; do
case "$f" in
*.md) ;;
docs/*) ;;
LICENSE) ;;
.github/ISSUE_TEMPLATE/*) ;;
*) docs_only=false; echo "not docs: $f"; break ;;
esac
done < changed.txt
echo "docs_only=$docs_only" >> "$GITHUB_OUTPUT"
android:
runs-on: ubuntu-latest
needs: classify
steps:
- name: "Docs-only change: android build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: actions/setup-java@v4
if: needs.classify.outputs.docs_only != 'true'
with:
distribution: "temurin"
java-version: "17"
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- name: Cache Gradle
if: needs.classify.outputs.docs_only != 'true'
uses: actions/cache@v4
with:
path: |
@ -30,13 +94,18 @@ jobs:
restore-keys: |
${{ runner.os }}-gradle-
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
- name: Write dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
env:
GIPHY_API_KEY: ${{ secrets.GIPHY_API_KEY }}
run: jq -n --arg k "$GIPHY_API_KEY" '{GIPHY_API_KEY:$k}' > dart_defines.json
- run: flutter build apk --release --no-pub --dart-define-from-file=dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
- name: Upload APK
if: needs.classify.outputs.docs_only != 'true'
uses: actions/upload-artifact@v4
with:
name: offband-android-r${{ github.run_number }}-${{ github.event.pull_request.head.sha || github.sha }}
@ -46,36 +115,67 @@ jobs:
ios:
runs-on: macos-latest
needs: classify
steps:
- name: "Docs-only change: ios build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
- run: flutter build ios --release --no-codesign --no-pub
if: needs.classify.outputs.docs_only != 'true'
linux:
runs-on: ubuntu-latest
# PINNED, not ubuntu-latest (#929). GitHub moved ubuntu-latest from 24.04
# to 26.04 on 2026-10-19, and 26.04's glibc headers clash with the vendored
# native sources: "typedef redefinition with different types ('__once_flag'
# vs 'int')" plus "conflicting types for 'pthread_once'", two seconds into
# the native compile. The same commit built on 24.04 that morning.
#
# This buys time, it does not fix anything: 24.04 images get retired, and
# the header conflict has to be resolved before that. #929 carries the real
# fix. The other ubuntu jobs pass on 26.04 and stay on ubuntu-latest.
runs-on: ubuntu-24.04
needs: classify
steps:
- name: "Docs-only change: linux build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- name: Install Linux build deps
if: needs.classify.outputs.docs_only != 'true'
run: sudo apt-get update && sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
- name: Write dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
env:
GIPHY_API_KEY: ${{ secrets.GIPHY_API_KEY }}
run: jq -n --arg k "$GIPHY_API_KEY" '{GIPHY_API_KEY:$k}' > dart_defines.json
- name: Enable native assets (bundles sqlite3 + llamadart libs, #445)
if: needs.classify.outputs.docs_only != 'true'
run: flutter config --enable-native-assets
- run: flutter build linux --release --no-pub --dart-define-from-file=dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
- name: Upload Linux bundle
if: needs.classify.outputs.docs_only != 'true'
uses: actions/upload-artifact@v4
with:
name: offband-linux-r${{ github.run_number }}-${{ github.event.pull_request.head.sha || github.sha }}
@ -85,34 +185,55 @@ jobs:
macos:
runs-on: macos-latest
needs: classify
steps:
- name: "Docs-only change: macos build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
- name: Enable native assets (bundles sqlite3 + llamadart libs, #445)
if: needs.classify.outputs.docs_only != 'true'
run: flutter config --enable-native-assets
- run: flutter build macos --release --no-pub
if: needs.classify.outputs.docs_only != 'true'
web:
runs-on: ubuntu-latest
needs: classify
steps:
- name: "Docs-only change: web build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
- name: Write dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
env:
GIPHY_API_KEY: ${{ secrets.GIPHY_API_KEY }}
run: jq -n --arg k "$GIPHY_API_KEY" '{GIPHY_API_KEY:$k}' > dart_defines.json
- run: flutter build web --release --no-pub --dart-define-from-file=dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
- name: Upload web build
if: needs.classify.outputs.docs_only != 'true'
uses: actions/upload-artifact@v4
with:
name: offband-web-r${{ github.run_number }}-${{ github.event.pull_request.head.sha || github.sha }}
@ -122,26 +243,38 @@ jobs:
windows:
runs-on: windows-latest
needs: classify
steps:
- name: "Docs-only change: windows build short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to build"
- uses: actions/checkout@v4
if: needs.classify.outputs.docs_only != 'true'
- uses: subosito/flutter-action@v2
if: needs.classify.outputs.docs_only != 'true'
with:
flutter-version: "3.44.1"
cache: true
- run: flutter pub get
if: needs.classify.outputs.docs_only != 'true'
- run: dart run build_runner build --delete-conflicting-outputs
if: needs.classify.outputs.docs_only != 'true'
# Windows runner defaults to PowerShell; jq is not guaranteed there,
# so build the JSON with ConvertTo-Json, which escapes correctly.
- name: Write dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
env:
GIPHY_API_KEY: ${{ secrets.GIPHY_API_KEY }}
run: |
@{ GIPHY_API_KEY = $env:GIPHY_API_KEY } | ConvertTo-Json -Compress |
Set-Content -Path dart_defines.json -Encoding utf8 -NoNewline
- name: Enable native assets (bundles sqlite3 + llamadart libs, #445)
if: needs.classify.outputs.docs_only != 'true'
run: flutter config --enable-native-assets
- run: flutter build windows --release --no-pub --dart-define-from-file=dart_defines.json
if: needs.classify.outputs.docs_only != 'true'
- name: Upload Windows build
if: needs.classify.outputs.docs_only != 'true'
uses: actions/upload-artifact@v4
with:
name: offband-windows-r${{ github.run_number }}-${{ github.event.pull_request.head.sha || github.sha }}

@ -8,31 +8,97 @@ on:
- dev
jobs:
# #904: same classifier as build.yml (workflows cannot share jobs without a
# reusable-workflow indirection; the duplication is the cheaper evil and the
# two copies are kept textually identical). Plain git, no third-party
# actions. Ambiguity always classifies as code.
classify:
runs-on: ubuntu-latest
outputs:
docs_only: ${{ steps.diff.outputs.docs_only }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Classify changed files
id: diff
run: |
set -eu
# No override, by design (#927). The #904 spike added an env flag
# that forced docs_only=true, it reached dev, and for every PR after
# it the build and test jobs reported pass in a few seconds having
# built nothing. A switch that turns every merge gate in the repo
# into a no-op, silently, is not worth the convenience of testing
# this job against itself.
if [ "${{ github.event_name }}" = "pull_request" ]; then
# checkout hands us the PR merge commit; parent 1 is the current
# base tip, so this is exactly the PR's effective diff.
git diff --name-only HEAD^1 HEAD > changed.txt
else
before="${{ github.event.before }}"
if [ "$before" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$before" 2>/dev/null; then
echo "no usable before-SHA; classifying as code"
echo "docs_only=false" >> "$GITHUB_OUTPUT"
exit 0
fi
git diff --name-only "$before" "${{ github.sha }}" > changed.txt
fi
echo "changed files:"
cat changed.txt
if [ ! -s changed.txt ]; then
echo "empty diff; classifying as code"
echo "docs_only=false" >> "$GITHUB_OUTPUT"
exit 0
fi
docs_only=true
while IFS= read -r f; do
case "$f" in
*.md) ;;
docs/*) ;;
LICENSE) ;;
.github/ISSUE_TEMPLATE/*) ;;
*) docs_only=false; echo "not docs: $f"; break ;;
esac
done < changed.txt
echo "docs_only=$docs_only" >> "$GITHUB_OUTPUT"
analyze:
runs-on: ubuntu-latest
needs: classify
steps:
- name: "Docs-only change: analyze short-circuited (#904)"
if: needs.classify.outputs.docs_only == 'true'
run: echo "docs-only diff; nothing to analyze"
- name: Checkout
if: needs.classify.outputs.docs_only != 'true'
uses: actions/checkout@v4
- name: Guard against em-dash characters (#464)
if: needs.classify.outputs.docs_only != 'true'
run: python3 .github/scripts/check_no_emdash.py
- name: Set up Flutter
if: needs.classify.outputs.docs_only != 'true'
uses: subosito/flutter-action@v2
with:
flutter-version: "3.44.1"
- name: Install dependencies
if: needs.classify.outputs.docs_only != 'true'
run: flutter pub get
- name: Generate code (drift / build_runner)
if: needs.classify.outputs.docs_only != 'true'
run: dart run build_runner build --delete-conflicting-outputs
- name: Analyze code
if: needs.classify.outputs.docs_only != 'true'
run: flutter analyze --fatal-infos --fatal-warnings
- name: Verify formatting
if: needs.classify.outputs.docs_only != 'true'
run: dart format --output=none --set-exit-if-changed .
- name: Run tests
if: needs.classify.outputs.docs_only != 'true'
run: flutter test -r github

@ -2,6 +2,93 @@
All notable changes to Offband Meshcore. Pre-releases are tagged `-beta.N` / `-rc.N`.
## [1.7.0] - 2026-10-26
Production successor to 1.6.0. A foundations release: per-message storage with a
one-way schema upgrade, radio-profile isolation, sync-is-truth contacts, custom contact
names, region scoping, a Settings restructure, and CLI for stock 1.18 companions.
### Storage (one-way upgrade, schema 1 to 2)
- History stored **one drift row per message** with a verified blob-to-rows
migration; save cost no longer grows with history (#917, #920).
- Blob read-modify-write, DM save merges, and both delete paths moved **off the UI
isolate** (#919).
- A newer schema is **refused loudly** instead of rewriting the version; the migration
gate asserts a superset, so keys with extra rows no longer stay stuck (#943, #952).
- **Stale blob reclamation**: per-key migration timestamps, an automatic sweep after
30 days, a durable audit of what it deleted, and **Clear Stale History Now** in App
Settings > Storage that reports refusals (#962, #965, #966).
- Earlier versions cannot open a schema-2 database; disclosed in the release texts
(#953).
### Radio-profile isolation (#853)
- Scoping inventory with a verdict gate, and repros of the remaining bleeds (#936).
- Path history and delivery observations per radio; dead `pending_messages` API
removed (#937).
- Discovered contacts per radio (#754); a blank radio is no longer pre-blocked from
another radio's list (#471); Blocked pane says "No radio connected" (#938).
- Storage scope keys cleared on an unexpected disconnect, closing the stale-read window
(#939); full isolation matrix across a radio switch and a restart (#940).
- Channel notify modes scoped per radio, index fallback removed, set-and-back resets
(#839, #848).
### Contacts
- **Sync is truth**: live adverts (0x8A, 0x88) feed discovery only; the persisted list
comes from the radio's contact sync, with a debounced incremental reconcile when an
advert matches the radio's auto-add policy (#838, #842, #850).
- **Custom Name**: `customName` over `receivedName`, kept off the wire and out of
exports and contact shares, scoped per radio (#750).
### Region scoping (#812)
- Region model and name-derived transport key; flood-scope frames and anon-regions
discovery, gated on `FIRMWARE_VER_CODE >= 13` (#813, #820, #821, #822).
- Discover Regions service and screen (#814, #825, #826); per-channel region-scope
store, Set Region Scope action, and per-send scoping (#815, #829, #830, #831).
- Hardware fixes: searchable, path-aware repeater picker; corrected discovery request
format, multi-hop reply path, firmware-estimate timeout, one auto-retry (#830, #836).
### Settings and badge parity (#975)
- Location is a top-level category and the only home for GPS (#977); Button actions in
Node Settings, Buzzer and tones in Message Settings (#978).
- Over 0xC5, capability-gated: GPS mode and power-save interval (#969), event tones
(#986), custom tunes with RTTTL order check and Fix order (#970), screen settings
(#971, #987), channel tune codec (#981). Requires Offband firmware not yet released.
- Config import/export, GPX exports, and "Sync queued messages now" moved to Actions;
Debug reordered (#902).
### CLI (stock 1.18 companions)
- Population classifier and capability-gate rework (#866, #875, #876, #877, #878,
#880); stock 1.18.0 classified by frame shape, not version suffix (#946).
- Companion CLI codec (frame 66/29), local CLI service, and Device CLI console
(#868, #881, #882, #883, #884).
- Remote CLI to companions: contact permission flag 0x10, role-based TXT type, command
service generalized to companions, inbound type 3, CLI kept out of chat, console
offered only on a 1.18 radio (#870, #887, #888, #889, #890, #891, #999).
### Bluetooth and stability
- Bounded, interruptible auto-reconnect: 5 attempts or 3 minutes, Stop ends it, a user
connect wins; a connect waits for a disconnect still in progress (#996, #997).
- Windows: use-after-free crash on app close fixed (#989).
- ANR and exit-record capture via ApplicationExitInfo, shipped with the exported log
(Android 11+) (#906, #910, #931).
### Fixes
- Channel hop counts decoded from the packed path-len byte, so 2- and 3-byte path
hashes render the right hop count (#985).
### CI
- CI no longer reports a pass without running; Linux pinned to ubuntu-24.04 (#927,
#929); docs-only changes short-circuit the required checks (#904, #905).
## [1.6.0] - 2026-10-05
First stable release of the 1.5.0 line and the production successor to 1.4.0. A large

@ -0,0 +1,267 @@
package com.meshcore.meshcore_open
import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
/**
* Reads the system's record of why this app's processes died, so an ANR that
* killed the process can be reported on the next launch (#906).
*
* `ActivityManager.getHistoricalProcessExitReasons` is API 30; `minSdk` here is
* 24, so everything below reports itself unsupported rather than failing. The
* query and the trace reads run on a background executor: #334 is the leading
* hypothesis for these ANRs, so a collector that blocked the main thread would
* be adding to the problem it exists to measure.
*/
class AppExitInfoFunctions(
private val activity: FlutterActivity,
) {
private companion object {
/** Bound on the query. The system keeps a ring buffer of unspecified size. */
const val maxRecords = 15
/** Per-trace read cap, so one pathological trace can't be unbounded. */
const val maxTraceBytes = 256 * 1024
}
private val channelName = "meshcore_open/app_exit_info"
private val activityManager by lazy {
activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
}
private val mainHandler = Handler(Looper.getMainLooper())
private val ioExecutor: ExecutorService = Executors.newSingleThreadExecutor()
@Volatile private var disposed = false
fun configureFlutterEngine(flutterEngine: FlutterEngine) {
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, channelName)
.setMethodCallHandler { call, result ->
when (call.method) {
"getExitRecords" -> handleGetExitRecords(result)
"forceMainThreadBlock" -> handleForceMainThreadBlock(call, result)
else -> result.notImplemented()
}
}
}
fun dispose() {
disposed = true
// shutdown(), NOT shutdownNow(): an in-flight read is holding a
// MethodChannel.Result, and interrupting it would leave that Result
// neither succeeded nor errored, so the Dart future would never
// complete. Letting the task finish is cheap; a hung future is not.
ioExecutor.shutdown()
}
private fun handleGetExitRecords(result: MethodChannel.Result) {
if (disposed) {
result.error("exit_info_disposed", "activity is being destroyed", null)
return
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
result.success(
mapOf(
"supported" to false,
"unsupportedReason" to "api_below_30",
"sdkInt" to Build.VERSION.SDK_INT,
"records" to emptyList<Map<String, Any?>>(),
),
)
return
}
try {
ioExecutor.execute {
try {
val records = collectExitRecords()
mainHandler.post {
result.success(
mapOf(
"supported" to true,
"sdkInt" to Build.VERSION.SDK_INT,
"records" to records,
),
)
}
} catch (error: Exception) {
// Surfaced, never swallowed: Dart logs this and leaves the
// watermark untouched so the next launch retries.
mainHandler.post {
result.error(
"exit_info_query_failed",
error.message ?: error.javaClass.simpleName,
error.stackTraceToString().take(2000),
)
}
}
}
} catch (error: RejectedExecutionException) {
// The executor shut down between the disposed check and here. Reply
// rather than returning silently, so the Dart future completes.
result.error("exit_info_rejected", error.message ?: "executor shut down", null)
}
}
/**
* API 30+ only, isolated in its own method so the verifier never has to
* resolve [ApplicationExitInfo] on a device that cannot run this path.
*/
private fun collectExitRecords(): List<Map<String, Any?>> {
// null package name means this app's own records, which needs no permission.
val infos = activityManager.getHistoricalProcessExitReasons(null, 0, maxRecords)
return infos.map { info -> describe(info) }
}
private fun describe(info: ApplicationExitInfo): Map<String, Any?> {
val record = mutableMapOf<String, Any?>(
"reason" to info.reason,
"reasonName" to reasonName(info.reason),
"description" to info.description,
"timestampMs" to info.timestamp,
"pid" to info.pid,
"processName" to info.processName,
"importance" to info.importance,
// Documented as kB, and 0 when the system never sampled the process.
"pssKb" to info.pss,
"rssKb" to info.rss,
"status" to info.status,
)
readTrace(info, record)
return record
}
/**
* A text ANR trace is printable ASCII; a native tombstone protobuf is not.
*
* Content, not reason code, decides whether the bytes are usable. Gating on
* [ApplicationExitInfo.REASON_CRASH_NATIVE] instead would lose a real text
* trace, because AOSP says a trace from an earlier ANR stays attached to the
* record even when the process later died for a different reason.
*/
private fun looksLikeText(bytes: ByteArray): Boolean {
val sample = minOf(bytes.size, 256)
if (sample == 0) return false
var printable = 0
for (i in 0 until sample) {
val b = bytes[i].toInt() and 0xFF
if (b == 0x09 || b == 0x0A || b == 0x0D || (b in 0x20..0x7E)) printable++
}
return printable * 10 >= sample * 9
}
/**
* A trace is NOT guaranteed, even for [ApplicationExitInfo.REASON_ANR]: the
* system keeps traces in a circular buffer shared across all applications,
* so another app's crash can evict ours. A trace can also ride on a record
* whose reason is something else, when the process survived an ANR and died
* later for another reason. So this attempts the read on every record and
* treats absence as an ordinary outcome, not an error.
*
* `getTraceInputStream()` is declared `throws IOException`, so the call
* itself is inside the try, not only the reads on the stream it returns.
*/
private fun readTrace(info: ApplicationExitInfo, record: MutableMap<String, Any?>) {
try {
val stream = info.traceInputStream
if (stream == null) {
record["traceUnavailable"] = "evicted_or_absent"
return
}
stream.use { open ->
// Read loop rather than readNBytes: that one is API 33, and this
// path has to work from API 30 up.
val sink = ByteArrayOutputStream()
val chunk = ByteArray(8192)
while (sink.size() < maxTraceBytes) {
val read = open.read(chunk, 0, minOf(chunk.size, maxTraceBytes - sink.size()))
if (read <= 0) break
sink.write(chunk, 0, read)
}
if (sink.size() == 0) {
record["traceUnavailable"] = "empty_stream"
return
}
val bytes = sink.toByteArray()
if (!looksLikeText(bytes)) {
// Almost certainly a native tombstone protobuf (API 31+).
// Recorded rather than written, because concatenating binary
// into a text log would corrupt it (#906).
record["traceUnavailable"] = "binary_tombstone_not_text"
return
}
record["traceBytes"] = bytes
if (bytes.size >= maxTraceBytes) {
record["traceTruncated"] = true
}
}
} catch (error: IOException) {
record["traceUnavailable"] = "io_error: ${error.message ?: "IOException"}"
}
}
private fun reasonName(reason: Int): String = when (reason) {
ApplicationExitInfo.REASON_ANR -> "ANR"
ApplicationExitInfo.REASON_CRASH -> "CRASH"
ApplicationExitInfo.REASON_CRASH_NATIVE -> "CRASH_NATIVE"
ApplicationExitInfo.REASON_DEPENDENCY_DIED -> "DEPENDENCY_DIED"
ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE -> "EXCESSIVE_RESOURCE_USAGE"
ApplicationExitInfo.REASON_EXIT_SELF -> "EXIT_SELF"
ApplicationExitInfo.REASON_FREEZER -> "FREEZER"
ApplicationExitInfo.REASON_INITIALIZATION_FAILURE -> "INITIALIZATION_FAILURE"
ApplicationExitInfo.REASON_LOW_MEMORY -> "LOW_MEMORY"
ApplicationExitInfo.REASON_OTHER -> "OTHER"
ApplicationExitInfo.REASON_PACKAGE_STATE_CHANGE -> "PACKAGE_STATE_CHANGE"
ApplicationExitInfo.REASON_PACKAGE_UPDATED -> "PACKAGE_UPDATED"
ApplicationExitInfo.REASON_PERMISSION_CHANGE -> "PERMISSION_CHANGE"
ApplicationExitInfo.REASON_SIGNALED -> "SIGNALED"
ApplicationExitInfo.REASON_USER_REQUESTED -> "USER_REQUESTED"
ApplicationExitInfo.REASON_USER_STOPPED -> "USER_STOPPED"
else -> "UNKNOWN"
}
/**
* Test-only: hangs the main thread so the system raises a real ANR, which is
* the only way to produce an [ApplicationExitInfo.REASON_ANR] record. No adb
* command induces one. Unreachable in a shipped build, because the only
* caller is compiled out unless `OFFBAND_ANR_TEST` is defined (#911).
*
* Replies before blocking so the Dart call completes; the block then runs on
* the next turn of the main looper.
*/
private fun handleForceMainThreadBlock(call: MethodCall, result: MethodChannel.Result) {
val millis = (call.argument<Int>("millis") ?: 20000).coerceIn(1000, 120000)
result.success(millis)
mainHandler.post {
// Sleeps to a deadline and swallows interrupts rather than a single
// Thread.sleep. An interrupt cutting the block short would mean no
// ANR, no record, and a wasted trip to the hardware. Looping on
// short sleeps keeps the duration guaranteed without the CPU burn
// (and thermal throttling) of a busy-wait.
val deadline = System.nanoTime() + millis * 1_000_000L
while (true) {
val remainingMs = (deadline - System.nanoTime()) / 1_000_000L
if (remainingMs <= 0) break
try {
Thread.sleep(minOf(remainingMs, 250L))
} catch (_: InterruptedException) {
// Deliberately ignored; the deadline is what ends this.
}
}
}
}
}

@ -6,12 +6,14 @@ import io.flutter.plugin.common.MethodChannel
class MainActivity : FlutterActivity() {
private val usbFunctions by lazy { MeshcoreUsbFunctions(this) }
private val appExitInfoFunctions by lazy { AppExitInfoFunctions(this) }
private val appLifecycleChannelName = "meshcore_open/app_lifecycle"
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
usbFunctions.configureFlutterEngine(flutterEngine)
appExitInfoFunctions.configureFlutterEngine(flutterEngine)
MethodChannel(
flutterEngine.dartExecutor.binaryMessenger,
@ -32,6 +34,7 @@ class MainActivity : FlutterActivity() {
override fun onDestroy() {
usbFunctions.dispose()
appExitInfoFunctions.dispose()
super.onDestroy()
}
}

@ -0,0 +1,25 @@
🚀 **Offband Meshcore 1.7.0 is out.** A foundations release: faster storage, every radio keeps its own data, and a contact list that matches your radio. Over 100 changes since 1.6.0.
⚠️ **Read this before updating: it's a one-way upgrade.** On first launch, 1.7.0 converts your message history to a new database format. After that, **older versions of the app can't open it**, so there's no going back to 1.6.0. Your messages carry over. The old copy is kept 30 days and then cleared automatically, so the database is bigger for a while. Want the space back now? **App Settings > Storage > Clear Stale History Now** (it asks first and never touches your messages).
💾 **Storage that keeps up.** One row per message instead of one giant blob per conversation, so a new message costs the same at 50,000 messages of history as at 50, and the heavy lifting is off the UI thread.
📻 **Every radio keeps its own data.** Discovered nodes, blocked contacts, channel notification modes, path history, and delivery records all belong to the radio they came from. A brand-new radio no longer shows up pre-blocked, and switching radios no longer flashes the last radio's history.
👥 **Contacts that match your radio.** No more phantom contacts piling up from adverts your radio rejected; a contact your radio actually stores still shows up on its own. And **custom names**: rename any contact, keep seeing what the node calls itself underneath, and your label never goes over the air or into exports.
🗺️ **Region scoping.** Discover a repeater's regions and scope a channel to one, so its messages flood only there. Needs MeshCore companion 1.16+ or current Offband firmware.
⚙️ **Settings, reorganized.** Location gets its own category (and is the one home for GPS), Buzzer and tones moves to Message Settings, and import/export plus GPX live under Actions. Badge tones, custom tunes, screen settings, and GPS power save are built in and will appear once the matching Offband firmware ships.
🖥️ **CLI for stock 1.18 companions.** A Device CLI console for your radio, remote CLI to another companion from the chat menu, and a per-contact Remote CLI permission toggle. CLI stays out of your chat.
📶 **Steadier Bluetooth.** Auto-reconnect now gives up after 5 tries or 3 minutes, **Stop** ends it right away, and a connect you start always wins. Plus a fix for a race that could leave the composer unusable, and a Windows crash on close.
🔧 **Fixes.** Messages with 2- or 3-byte path hashes show the right hop count (no more 13 hops reading as 39).
**📥 Get it on Google Play:** search **Offband MeshCore**, or https://play.google.com/store/apps/details?id=app.offband.meshcore (rolling out in stages, so it may take a few days to reach you)
💻 **Desktop (Windows / Linux) and Android APK:** https://github.com/OffbandMesh/meshcore-client/releases/tag/v1.7.0
🌐 **Or run it in your browser:** https://offband.app
💚 Thanks as always to the **OKIMesh community** (https://okimesh.org/). Offband is open source and always will be; if you'd like to help keep it going: https://offband.org/donate

@ -0,0 +1,52 @@
# Feature #812 region scoping: OUTCOMES
Status: shipped and verified on hardware (D1 PASSED, 2026-10-15). Client-only, no firmware change.
## What shipped
A client capability at parity with stock MeshCore, built on current stock-parity firmware:
- **Discover Regions** (Epic #814): from a reachable repeater, ask which flood regions it carries and present the list.
- **Channel Set Region Scope** (Epic #815): a per-channel region selection that makes a channel's outgoing messages ride that region's flood scope, orchestrated per send (set the flood-scope key before each channel send, clear after).
- **Protocol + transport** (Epic #813): the v8 companion frames and the region transport-key derivation that both of the above rely on.
### Epics / PRs
| Epic | Scope | PR |
|---|---|---|
| #813 | protocol + transport (anon-request discovery, flood-scope CMD 54/63/64, name-derived keys, version gate) | #824 |
| #814 | Discover Regions service + UI | #828 |
| #815 | channel Set Region Scope (store + picker + per-send scoping) | #833 |
| #816 | integration testing + this OUTCOMES.md | (this PR) |
## Wire contract (verified in firmware source)
- Region transport key = first 16 bytes of `SHA256("#"+name)` (`RegionMap.getTransportKeysFor` / `TransportKeyStore`). On-air code = `HMAC(key, type+payload)[:2]` little-endian, reserving `0x0000`/`0xFFFF`.
- Flood-scope: `CMD_SET_FLOOD_SCOPE_KEY` 54 (sub-0 set 16B key / sub-0 no-key clear / sub-1 unscoped), `CMD_SET_DEFAULT_FLOOD_SCOPE` 63, `CMD_GET_DEFAULT_FLOOD_SCOPE` 64, `RESP_CODE_DEFAULT_FLOOD_SCOPE` 28.
- Discovery is an ANON request: `CMD_SEND_ANON_REQ` 57 with payload `[ANON_REQ_TYPE_REGIONS 0x01][reply_path_len][reply_path]`. The firmware's `sendAnonReq` prepends its own 4-byte tag and returns it in `RESP_CODE_SENT`; the repeater echoes it in the `PUSH_CODE_BINARY_RESPONSE` 0x8C reply `[0x8C][0][tag:4][clock:4][CSV names]`. The reply routes back along the client-supplied `reply_path`, used as-is (`Mesh.cpp:176-177`).
- Version gate: `firmwareSupportsRegionScope` is `FIRMWARE_VER_CODE >= 13`.
## D1 hardware session (PASSED)
On a real radio (region-capable firmware, direct repeater), end to end:
1. Discover Regions returned the repeater's flood-allowed region list.
2. Set Region Scope persisted the chosen region on a channel.
3. A send on that channel rode the chosen region's flood scope.
4. The feature is hidden below the firmware gate.
## Issues found in D1 and fixed (all on epic/815-channel-scope)
D1 did its job; several defects only surfaced on real hardware.
- **Repeater picker unusable** (#830): the picker was an unsorted, unsearchable dropdown. Now alpha-sorted and searchable.
- **Path-aware picker** (#830, owner Option 1): the picker lists only repeaters with a usable route, with a note explaining that; a search surfaces path-less matches greyed out and non-selectable, labeled "No stored path".
- **Direct repeaters wrongly excluded** (#830): `hasPath` required a non-empty path, but a direct (0-hop) repeater has `pathLength 0` and an empty path. Direct is reachable (best case); fixed to `pathLength >= 0`.
- **Discovery returned no reply** (#836): two wire-format bugs. The client double-counted the anon-request tag (the firmware prepends its own), so the repeater read the request as a login and never answered; and the reply was correlated on a client-invented tag instead of the firmware tag the 0x8C echoes. Fixed to match the real contract.
- **Zero-hop reply cap** (#836): the reply was pinned to zero-hop, so only an adjacent repeater could answer. Now the request carries the repeater contact's stored path as the reply path (multi-hop), and the discovery timeout uses the firmware's own `est_timeout` estimate rather than a fixed value.
- **First-attempt LoRa drop** (#836, owner Option A): a single anon-request round-trip can drop over LoRa. Discovery now makes one automatic retry before reporting no response.
## Region model finding (firmware/repeater, not client)
A community discussion raised that `region def` on a repeater stores and displays regions as a hierarchy, and a region can only have one parent, which breaks tri-state-border configs (e.g. putting `oki` under both `us-midwest` and `us-southeast`). Verified in firmware: `RegionMap::findMatch` iterates regions as a **flat whitelist** at forward time (flood allow/deny flag plus a transport-code match) and never consults `parent_id`. So the hierarchy is cosmetic; the re-parenting on `region def` is a repeater-side config/doc UX flaw, not a routing behavior. Our client scopes a channel by the flat tag name and discovers the flat list of flood-allowed names, so it is already aligned with how the firmware routes and is unaffected by the hierarchy issue.
## Known limits / follow-ups
- The multi-hop reply uses the repeater contact's **stored** path. Stored paths go stale when the companion moves, so a repeater can occasionally not answer until the path refreshes; this surfaces as a plain timeout (plus the one auto-retry), never a silent drop. The repeater list is deliberately not filtered by hop count for the same reason.
- `$`-prefixed private regions are not name-derivable (keystore-only) and are out of scope.
- A true per-channel firmware scope (firmware TODO) would remove the client-orchestrated per-send dance; sequenced separately by the owner.
- Android was not built for D1 (release signing needs the keystore in the worktree); the owner tested on Windows, and the same client code runs on both.
Agent: EmeraldFalcon (session 6966cd3a)

@ -0,0 +1,132 @@
# Feature PLAN: region scoping (client): Discover Regions + channel Set Region Scope
| | |
|---|---|
| **Feature** | [#812](https://github.com/OffbandMesh/meshcore-client/issues/812) · Citadel `meshcore-open-e0l` |
| **Serves** | No parent Initiative; a standalone Feature. Pulls "Set Region Scope" out of the #651 channel-menu parity bundle. |
| **Status** | Draft. Approved when this PR merges. |
| **Owner** | @Strycher |
| **Last updated** | 2026-10-07 |
## At a glance
- **What:** a **Discover Regions** action that asks a reachable repeater which regions it floods, and a per-channel **Set Region Scope** action (stock channel-menu parity) that makes that channel's outgoing messages ride the chosen region's flood scope.
- **Why:** stock MeshCore has both; Offband has neither. Owner-directed 2026-10-06.
- **How:** entirely client-side against current stock-parity firmware. No firmware change. Four Epics in order: A protocol/transport, B Discover Regions, C channel Set Region Scope, D hardware integration test.
- **Done when:** the owner can discover regions from his repeater, set a channel's region, send on that channel scoped to the region, and confirm on hardware; the feature is hidden on firmware that doesn't support it.
## 1. Diagnosis
Verified against firmware `C:\Dev\meshcore-firmware` and client `dev`, 2026-10-06/07. Full cited contract on #817.
| # | Finding | Evidence |
|---|---|---|
| 1 | Client has no region capability; only raw repeater-CLI passthrough | `repeater_cli_screen.dart` region commands; no region model/UI in `lib/` |
| 2 | **Discover Regions = an ANON request**, not control-data | `ANON_REQ_TYPE_REGIONS 0x01` via `CMD_SEND_ANON_REQ 57`; repeater `handleAnonRegionsReq` replies region names; reply to app as `PUSH_CODE_BINARY_RESPONSE 0x8C` `[0x8C,0,tag4,clock4,CSV names]` `[simple_repeater MyMesh.cpp:58,150-166,599; companion MyMesh.cpp:3114-3141,1201-1211; RegionMap.cpp:318-346]` |
| 3 | Region names are public; key is derivable | transport key = first 16B of `SHA256("#"+name)`; `$`-prefixed private regions are not name-derivable `[RegionMap.cpp:173-188; TransportKeyStore.cpp:44-47; TransportKeyStore.h:8]` |
| 4 | Scope-set is exposed over the companion | `CMD_SET_FLOOD_SCOPE_KEY 54` (sub-0 set 16B key / sub-1 unscoped), `CMD_SET_DEFAULT_FLOOD_SCOPE 63`, `CMD_GET_DEFAULT_FLOOD_SCOPE 64`, `RESP 28` `[companion MyMesh.cpp:3512-3547]` |
| 5 | No per-channel scope in firmware | `companion MyMesh.cpp:896 "// TODO: have per-channel send_scope"`; send applies one `send_scope` override or the node default |
| 6 | Client implements none of it; v8+ | highest client command 61; `appProtocolVersion 4`; client already gates by `firmwareVerCode` (`firmwareSupportsPktHash` >= 22) `[meshcore_protocol.dart]` |
## 2. Scope
**In:**
- Protocol: anon regions request + 0x8C reply parse; flood-scope cmd 54/63/64 + RESP 28; name->key (SHA256) + on-air code (HMAC); firmware-version gate.
- Discover Regions: query a chosen repeater, parse the CSV region names, present a list.
- Channel scope: per-channel region stored client-side; channel-menu "Set Region Scope"; and the **client-orchestrated per-send** apply (set `send_scope` via cmd 54 sub-0 with the channel's SHA256 key immediately before each channel send, reset after).
- Optional node default scope via cmd 63/64.
**Out:**
- Firmware changes of any kind (per-channel firmware scope, finding 5, is a firmware TODO the owner sequences separately).
- `$`-prefixed private regions (keys not name-derivable).
- RF/IATA region settings (#503) and geofencing: different concern.
- Administering a repeater's region map (that is the existing repeater CLI).
## 3. Epics
Each Epic ends with a verification task and gets one PR. The first task reproduces the diagnosis as a failing test.
### Epic A: protocol + transport layer (#813)
| Task | Pts |
|---|---|
| **A1 · Region model + key derivation:** NEW `lib/models/region.dart`, NEW `lib/helpers/region_key.dart` (transportKeyForName = first 16B of SHA256("#"+name); on-air code HMAC). Unit tests incl. a known vector and wildcard. | 2 |
| **A2 · Frames + version gate:** `lib/connector/meshcore_protocol.dart` constants (cmd 54/63/64, resp 28, push 0x8C), builders (anon regions req type 0x01, set-scope-key, default-scope set/get), parsers (resp 28, 0x8C CSV), `firmwareSupportsRegionScope(verCode)`. Unit tests. | 3 |
| **A3 · Connector wiring:** `lib/connector/meshcore_connector.dart`: `discoverRegions()`, set/clear channel send scope, set/get default scope, 0x8C + resp 28 handling (tag-matched), exposed via stream/callback. | 3 |
| **A4 · Epic verification:** protocol unit tests pass; frames round-trip against a real radio on benign paths. | 1 |
### Epic B: Discover Regions (#814)
| Task | Pts |
|---|---|
| **B1 · Discovery service:** NEW `lib/services/region_discovery_service.dart`: target a repeater, send, collect/parse/dedupe 0x8C replies; timeout, empty, parse-error all surfaced. Unit tests with a fake connector. | 3 |
| **B2 · Discover Regions UI:** list screen/dialog (source node, SNR), entry point, l10n. | 3 |
| **B3 · Epic verification:** discover against rpt-01 returns its regions; empty/timeout surfaces. | 1 |
### Epic C: channel Set Region Scope (#815)
| Task | Pts |
|---|---|
| **C1 · Per-channel scope store:** NEW `lib/storage/channel_region_scope_store.dart` (device-key scoped, channel->region) + model + tests. | 3 |
| **C2 · Channel-menu action + picker:** `lib/screens/channel_chat_screen.dart` overflow item "Set Region Scope" + picker (sourced from B), writes the store, l10n. | 3 |
| **C3 · Send-path scoping:** `lib/connector/meshcore_connector.dart` channel send: apply send_scope (cmd 54 sub-0, SHA256) before send, reset after; optional node default (cmd 63). | 3 |
| **C4 · Epic verification:** a scoped channel send applies the right key on the wire. | 1 |
### Epic D: integration testing (#816)
| Task | Pts |
|---|---|
| **D1 · Owner hardware session:** discover from rpt-01 -> set a channel's region -> send -> confirm flood-scoped; verify the feature is hidden on non-supporting firmware. | 2 |
| **D2 · OUTCOMES.md** | 1 |
## 4. Order and dependencies
- A, B, C, D in order; each Epic's verification blocks the next (wired in Citadel).
- **File overlap:** only `lib/connector/meshcore_connector.dart` is shared (A3 and C3) -> Epic C depends on Epic A. No other cross-task file collisions.
- Merges held to the end of the Feature, stacked, so each Epic branch is on the one before.
- Fail-closed branches (standards#677): firmware ver < gate -> feature hidden, never send region frames; discovery empty/malformed -> surface, never show empty as success; discovery timeout -> surface + retry, never hang; channel scoped but firmware unsupported -> block the send with a clear error, never send unscoped; cmd 54 ERR before a send -> abort + surface. No fail-open branches.
## 5. Grants and authorization
| Term | Proposed | Why |
|---|---|---|
| **What merging this plan authorizes** | Running Epics A to D in order without stopping between them: code, tests, builds, one PR per Epic, stacked. | Canon: once the plan grant is minted, run the whole chain. |
| **Merges** | Held to the end of the Feature, in order A, B, C, D, after the owner's D1 hardware session. | Canon. |
| **Epic verification** | Command mode: the merge hook runs `flutter test` on each PR's exact commit; the owner's D1 hardware session is the Feature-level gate before the end merges. | Minimizes owner per-PR steps; the real on-air proof is D1. |
| **Owner steps during the run** | None until D1 (the hardware session, one sitting). | Canon: owner steps are one message, at the end. |
| **Stops** | A new decision; a firmware reply I can't cite; a fault I can't fix. | |
| **Flash** | None (client-only; owner tests via a build, the session flashes nothing). | |
```grant-terms
{
"epic_chain": [813, 814, 815, 816],
"chain": true,
"verification": { "mode": "command", "command": "flutter test" },
"merge": { "budget": 4, "basis": "One PR per Epic: #813 protocol, #814 Discover Regions, #815 channel Set Region Scope, #816 integration test + OUTCOMES.md." },
"flash": null,
"reset": null,
"expires_after_hours": 168
}
```
`expires_after_hours` basis: ~32 points across four Epics at interactive pace around the owner's day job; 168h is the maximum.
## 6. Verification
- **Named commands** on every Epic PR: `flutter analyze --fatal-infos --fatal-warnings`, `dart format --set-exit-if-changed`, the em-dash guard, `flutter test`.
- **Acceptance:** key derivation matches a firmware vector; discovery parses a real repeater's region CSV; a scoped channel send puts the right transport key on the wire; the feature is hidden on firmware below the gate; every surfaced error is tested present-on-failure and absent-when-ideal (#748).
- **D1 hardware session** proves discover -> scope -> send end to end; the owner signs off.
## 7. Done when
- Discover Regions lists the owner's repeater's regions over BLE/USB.
- A channel can be scoped to a discovered region; its sends ride that region's flood scope, confirmed on hardware.
- The feature is hidden/disabled on firmware that doesn't support it.
- `OUTCOMES.md` is approved.
## 8. Your choices
| # | Question | Option A | Option B | Rec. | Your choice |
|---|---|---|---|---|---|
| 1 | Epic verification mode | Command (`flutter test` per PR; D1 is the on-air gate) | Owner `dw-approve verify` per Epic PR | A (fewer steps for you; D1 is the real proof) | |
| 2 | Node default scope (cmd 63) | Include as an option in C | Channels only, skip default | A (cheap, matches firmware) | |
## Decisions
| Date | Decision |
|---|---|
| 2026-10-06 | Build region scoping client-side; stock parity: Discover Regions + channel Set Region Scope. |
| 2026-10-07 | Diagnosis (#817) accepted: discovery = anon request; scope via flood-scope commands; key = SHA256("#"+name). |
| 2026-10-07 | Channel scope is client-orchestrated per-send (cmd 54 before each channel send): the only path at parity with stock firmware until stock exposes per-channel scope. |
## Alternatives considered but not chosen
- **Control-data (PAYLOAD_TYPE_CONTROL) for discovery:** that is node discovery (`CTL_TYPE_NODE_DISCOVER 0x80/0x90`), not regions; regions use the anon-request path.
- **Per-channel firmware scope:** firmware TODO (finding 5); would be firmware work the owner sequences, not this client Feature.
- **Reading the stock client (Liam's) source for the discovery format:** unavailable; the firmware is the authoritative contract and fully specifies it.
When this plan merges, each Task gets a GitHub issue and a Citadel task, per canon.

@ -0,0 +1,193 @@
# Feature PLAN: radio-profile isolation
| | |
|---|---|
| **Feature** | [#853](https://github.com/OffbandMesh/meshcore-client/issues/853) · Citadel task minted on merge |
| **Serves** | No parent Initiative; a standalone Feature. |
| **Status** | Draft. Approved when this PR merges. |
| **Owner** | @Strycher |
| **Last updated** | 2026-10-20 |
## At a glance
- **What:** every piece of client state that belongs to a specific radio is scoped to that radio, and every surface that stays global is global **on the record** rather than by accident.
- **Why now:** the owner runs twelve radios through one client. Eleven stores already scope correctly, so what is left are leftovers, and leftovers rot: #754 and #471 sat written-but-unmerged for four days because this Feature had no plan, so no chain could run them.
- **How:** a harness that makes the verdict mechanical, then one consolidated migration for the three remaining global surfaces, then the two smaller jobs, then integration testing.
- **Done when:** a test fails if any persistence surface lacks a declared scoping verdict, and on hardware radio A's data never appears while radio B is connected, across a switch and a restart.
## 1. Diagnosis
Verified against `dev` at `b59bc728`, which is after tonight's #917 storage rewrite and after #754 and #471 landed. The audit in #853's body was taken at `a69cb998` and parts of it have moved since; the rows below supersede it.
| # | Finding | Evidence | Effect |
|---|---|---|---|
| 1 | Twelve stores already scope by the connected radio's key prefix and are correct | `channel_message_store`, `message_store`, `channel_store`, `channel_order_store`, `channel_region_scope_store`, `channel_settings_store`, `contact_store`, `contact_settings_store`, `contact_group_store`, `community_store`, `unread_store`, `block_store` all read `publicKeyHex` | The mechanism works. This Feature closes leftovers, it does not redesign |
| 2 | `contact_discovery_store` was the last store-level hole and is now fixed | #754, merged `a331075a` | One hole closed, and the pattern it used (orphan the untagged legacy blob, let it self-heal) is the precedent for choice 1 below |
| 3 | `path_history_<contactPubKey>` is keyed by contact only, so a learned mesh route bleeds between any two radios that share a contact | `storage_service.dart:51`, `path_history_service.dart:360,411,472` | #854. A route learned by a 1 W handheld gets applied to a repeater, and the reverse |
| 4 | `path_history_` is also unbounded in SharedPreferences: **2,041 keys, 3,652,667 bytes, 86% of a 4.23 MB prefs file**, while `PathHistoryService` caches only 50 | measured on the owner's live prefs, 2026-10-19 | #924. And since every prefs write re-encodes the whole file (#923, 49.4 ms on Windows), this one store makes every unrelated settings write about seven times slower |
| 5 | `delivery_observations` is one global list feeding the ACK-timeout ML model, so one radio's RF timing trains another radio's predictions | `storage_service.dart:166`, `timeout_prediction_service.dart:46,92`; 3,091 bytes, 14 entries on the owner's install | #856. Silent accuracy loss rather than a visible failure, which is why nobody reported it |
| 6 | `pending_messages` is **dead code**: `loadPendingMessages`, `savePendingMessages` and `clearPendingMessages` have no callers anywhere in `lib/` or `test/`, and the key is absent from the owner's live prefs | `grep -rn "PendingMessages\|pending_messages" lib/ test/` returns only the three definitions; the `_pendingMessages` field at `message_retry_service.dart:547` is an unrelated in-memory list | #855 does not need scoping. It needs deleting |
| 7 | The scope key is set from the SELF_INFO handshake, so a read issued before it lands uses the **previous** radio's prefix | #158, confirmed in source at `meshcore_connector.dart` and `channels_screen.dart`; desktop-only, does not reproduce on Android | A different defect class from rows 3 to 6: these stores are scoped correctly and still bleed, through timing |
| 8 | #190's named root cause is already addressed, yet #190 is still open as an in-progress epic | #190 blames slot-index keying with no PSK binding; `channel_message_store._storageKey()` now resolves PSK first and logs loudly on the index fallback (#194), and #472 closed the cross-radio case | Needs a **verdict**, not an assumption. Either it no longer reproduces, or what remains is narrower than its body says |
| 9 | Three surfaces are global **on purpose** and must not be "fixed" | `client_id_store` (`client_install_id`, the app install identity); `repeater_passwords` and `repeater_auto_clock_sync_after_login` (keyed per repeater **node**, not per connecting radio); theme, language, units, map prefs | Without a recorded verdict a future audit re-opens these as holes, which is exactly how time gets wasted |
| 10 | Nothing makes any of this checkable | #853's acceptance says the Feature closes when "every store has a verified scoping verdict", and the only way to check that today is to re-read the audit by hand | A new global key can land tomorrow and nothing notices. Same lesson as #927: a prose guard does not gate |
**Root cause of the *pattern*, as distinct from the individual bugs:** there is no mechanical statement of what each surface's scoping is meant to be, so correctness lives in an issue body and decays.
## 2. Scope
**In:**
- A machine-checkable scoping verdict for every persistence surface, which is #853's acceptance bar made executable.
- #854 path history per radio, and out of SharedPreferences, which also resolves #924.
- #855 dead `pending_messages` API removed.
- #856 delivery observations per radio.
- #507 Settings to Blocked per-radio view, plus its T1000e hardware validation.
- #158 the stale-scope read window, and a verdict on #190.
- Recorded global-on-purpose verdicts for the surfaces in diagnosis row 9.
**Out:**
- **#923**, the 49 ms cost of a single SharedPreferences write on Windows. Epic B shrinks its blast radius considerably by removing 86% of the prefs file, but the mechanism is untouched and #923 stays open. Fixing it properly means moving the remaining keys or batching writes, which is its own work.
- Refactoring the twelve already-correct stores onto a shared scoping helper. The pattern is duplicated and the rule of three would justify a helper, but rewriting working per-radio storage carries real data risk for no user-visible benefit.
- #660 and #280. #853's own body excludes them as "related but not isolation, not parented here", and that is still right: #660 is radio-side contact loss, #280 is message ordering.
- Any firmware or wire-format change. This Feature is entirely client-side.
## 3. Epics
Tasks are 3 to 4 points. Each Epic ends with a verification task and gets one PR. Epic A reproduces the diagnosis as failing tests before anything is built.
### Epic A: [#936](https://github.com/OffbandMesh/meshcore-client/issues/936) scoping-verdict harness and failing repros
| Task | Pts |
|---|---|
| **A1 · Surface inventory with declared verdicts:** a test that enumerates every persistence surface (drift key prefixes and prefs keys) against a declared table of `perRadio` or `globalOnPurpose(reason)`. It fails on an unclassified surface and on a new global key. Proven by adding a fake global key in the test and watching it go red | 4 |
| **A2 · Reproduce rows 3 and 5 as failing tests:** radio A's path history visible to radio B, and radio A's delivery observations feeding radio B's model. Both red before Epic B touches anything | 3 |
| **A3 · Epic verification:** the harness fails for the right reasons and passes for the current declared set, with A2's two repros red | 1 |
### Epic B: [#937](https://github.com/OffbandMesh/meshcore-client/issues/937) the three global `storage_service` surfaces, as one migration
| Task | Pts |
|---|---|
| **B1 · Delete the dead `pending_messages` API** (#855): three methods and the key, with the harness updated so the surface leaves the inventory rather than being reclassified | 3 |
| **B2 · Path history per radio, in drift** (#854 and #924): scope by radio prefix, move the store from SharedPreferences to `BlobStore`, bound what persists to what `PathHistoryService` actually caches, and **delete the 2,041 legacy untagged keys once the readback gate passes** (decision 1) | 4 |
| **B3 · Delivery observations per radio** (#856): scope by radio prefix so the model trains per radio, and **delete the legacy global list** (decision 1) | 3 |
| **B4 · Epic verification:** A2's repros now pass, the inventory shows no unclassified surface, and the owner's real prefs file is measurably smaller with route history intact | 1 |
### Epic C: [#938](https://github.com/OffbandMesh/meshcore-client/issues/938) Blocked per-radio view
| Task | Pts |
|---|---|
| **C1 · The view** (#507): Settings to Blocked lists the connected radio's blocks, with an explicit disconnected state and an explicit empty state that read differently from each other | 3 |
| **C2 · Isolation and clear tests:** a block on radio A is absent on radio B, and a clear sticks across a restart | 3 |
| **C3 · Epic verification:** hardware on the T1000e, confirming the re-clear behind #471 does not recur | 1 |
### Epic D: [#939](https://github.com/OffbandMesh/meshcore-client/issues/939) scope-key lifecycle, the stale-read window
| Task | Pts |
|---|---|
| **D1 · Verdict on #190** (diagnosis, no code): does its reproduction still reproduce after #194 and #472? Close it, or re-scope it to what actually remains, with evidence either way | 3 |
| **D2 · Close the stale-read window** (#158): no per-radio read resolves against a stale or unset prefix. Fail closed, returning nothing rather than the previous radio's data | 4 |
| **D3 · Epic verification:** a switch between two radios with no window in which a read can see the wrong prefix, proven by test and on desktop where #158 was seen | 1 |
### Epic E: [#940](https://github.com/OffbandMesh/meshcore-client/issues/940) Integration Testing
| Task | Pts |
|---|---|
| **E1 · The full matrix:** for every surface in the inventory, radio A's datum isolated and not inherited by radio B, across a radio switch **and** an app restart, which is #853's stated acceptance bar | 4 |
| **E2 · Hardware validation:** two real radios on the owner's own install, including the twelve-radio database already on his machine | 3 |
| **E3 · Epic verification and Feature closure:** the inventory is complete, every verdict recorded, no hole left | 1 |
## 4. Order and dependencies
**A, then B, then C and D in either order, then E.**
- **A is first** because it is the base diagnostic: without it, B's fixes cannot be shown to have fixed anything, and it is the only task that prevents recurrence.
- **B is second** because it is the largest hole and the only one with a cost a user feels today, both the route bleed and the prefs-file tax on every other settings write.
- **C and D are independent** of each other and of B. C touches `lib/screens/`, D touches the connector and the scope-key plumbing, neither touches `storage_service.dart`.
- **E is last** by canon: a Feature's final Epic is Integration Testing of the whole integrated environment.
**File overlap:** only B touches `lib/services/storage_service.dart`, and it touches it three times inside one Epic instead of across three PRs, which is the whole reason these were consolidated. D touches `lib/connector/meshcore_connector.dart`, the most contended file in the repo, so D should not run alongside other connector work.
## 5. Grants and authorization
What merging this plan authorizes, in words:
| Term | Proposed | Why |
|---|---|---|
| **What merging this plan authorizes** | Building all five Epics end to end with no further approval, opening one PR per Epic | The chain model that worked for #917: one approval, unattended run, merges held |
| **Merges** | 5, one per Epic | Tasks are commits on the Epic branch, so there is no per-task PR. Five Epics, five PRs |
| **Epic verification** | `owner` | Three of the five end in a judgement only the owner can make: hardware on the T1000e (C), a real two-radio switch (D and E), and whether route history survived the move (B). A command here would be a check that cannot fail |
| **Owner steps during the run** | Two, both late: the T1000e check for C and the two-radio switch for E, one message each | Everything else, including the migration rehearsal against a copy of his real database, runs without him |
| **Stops** | A refused migration readback, a harness failure this plan did not predict, or any sign of lost route history | Each is a data-integrity signal, and each stops rather than proceeding |
| **Flash** | `null` | Nothing here touches firmware. The T1000e check uses whatever is already on it |
```grant-terms
{
"epic_chain": [936, 937, 938, 939, 940],
"chain": true,
"verification": { "mode": "owner" },
"merge": { "budget": 5, "basis": "one merge per Epic in the chain (936, 937, 938, 939, 940); Tasks are commits on the Epic branch, so there is no per-task PR" },
"flash": null,
"reset": null,
"expires_after_hours": 168
}
```
**Basis for the expiry.** 168 hours, the maximum, because Epics C, D and E each end in an owner hardware step and the owner has a day job. #917's 72 hours was enough only because its single owner step came at the very end; a grant that expired between Epic C's hardware check and Epic D's would break the chain and need a re-mint for no reason.
## 6. Can't-tell branches
| Where | Can't tell what | Does |
|---|---|---|
| Legacy untagged `path_history_<contact>` key | which radio learned this route | **stop** — never assign it to a radio. Per decision 1 it is deleted, not guessed at, and only after the per-radio readback gate passes |
| Legacy untagged `delivery_observations` | which radio produced these observations | **stop** — same. Deleted per decision 1; mixed-radio data is worse than no data for the model |
| Per-radio read with an empty or unset scope prefix (#158) | which radio is connected | **stop** — return nothing, never fall back to the last known prefix. This is the #754 precedent: an unset key loads nothing and never writes |
| A surface in the inventory with no declared verdict | whether it should be per-radio | **stop** — the harness fails the build. That is the point of A1 |
| Path-history migration readback mismatch | whether every route survived the move into drift | **stop** — keep the prefs copy, delete nothing, surface loudly. Same gate as #920, which caught a lossy converter precisely because the count was measured independently of the converter |
| `repeater_passwords`, keyed by repeater node | nothing: this one is **decidable**, and the verdict is global-on-purpose | proceeds, by recorded verdict rather than by silence. Not a fail-open branch |
No fail-open branches. Nothing in this plan needs a fail-open grant.
## 7. Verification
- **Named command:** `flutter test test/storage/ test/services/ test/connector/` plus `flutter analyze`, with the scoping-inventory test named explicitly in each Epic's PR body.
- **Acceptance bar:** the inventory test fails when a surface is unclassified or a new global key appears, proven by making it fail on purpose; Epic A's two repros go red to green across Epic B; and on hardware, radio A's data never appears while radio B is connected, across a switch and a restart.
## 8. Done when
- Every persistence surface has a declared verdict, `perRadio` or `globalOnPurpose` with a reason, and a test fails if one does not.
- #854, #855, #856, #507 and #158 are closed, and #190 has a recorded verdict.
- #924 is closed as a side effect of B2.
- On the owner's own twelve-radio install, a radio switch and a restart show no data belonging to any other radio.
## 9. Decisions
Settled by the owner, 2026-10-20. No open choices remain in this plan.
| # | Decision | What it means for the build |
|---|---|---|
| 1 | **Delete the legacy untagged data.** The 2,041 `path_history_<contact>` keys and the global `delivery_observations` are removed, not orphaned | B2 and B3 each delete their legacy key **only after** the per-radio readback gate passes. Both surfaces are regenerable: routes relearn in normal use and the ML model retrains. This is also what reclaims 86% of the prefs file |
| 2 | **Path history moves into drift**, not just a radio prefix in place | B2 is a store move plus a scoping change in one migration, following #335's precedent for messages and contacts. Resolves #924, and cuts most of #923's per-write cost as a side effect by shrinking the file every other write re-encodes |
| 3 | **#158 and #190 stay in this Feature**, as Epic D | The Feature cannot claim isolation while a read can still resolve against a stale prefix. A user cannot tell "wrong store" from "right store, wrong moment" |
Decision 1 differs from #754's choice to orphan, deliberately: that blob was small, whereas here the orphaned data *is* the performance problem.
## 10. Carried-in work
| Item | Goes to |
|---|---|
| #854 path history per radio | Epic B, task B2 |
| #855 pending messages | Epic B, task B1, **as a deletion** rather than a scoping fix |
| #856 delivery observations | Epic B, task B3 |
| #924 `path_history_` unbounded (filed 2026-10-19) | Epic B, task B2, the same change as #854 |
| #507 Blocked per-radio view | Epic C |
| #158 history bleed after a radio switch | Epic D, task D2 |
| #190 history bleed into a new channel | Epic D, task D1, as a verdict |
| #923 prefs write cost | **Out of scope.** B2 shrinks its blast radius; the mechanism is untouched and the issue stays open |
## Alternatives considered but not chosen
- **One shared scoping helper across all twelve stores.** The rule of three would justify it, but rewriting working per-radio storage risks data for no user-visible gain.
- **Three separate PRs for #854, #855 and #856.** How they were filed, and the reason this plan exists. They share a file, a defect and a migration decision, and splitting them triples the review and test rounds while hiding that one of the three is dead code.
- **A commit hook blocking any new global prefs key.** Mechanical, but it would fire on every legitimate global setting. A1's inventory test achieves the same thing where the knowledge belongs, in a declared table beside the code.
When this plan merges, each Epic's Tasks get a GitHub issue and a Citadel task, per canon.

@ -0,0 +1,175 @@
# Feature PLAN: storage save path: remove O(history) work per message
| | |
|---|---|
| **Feature** | [#917](https://github.com/OffbandMesh/meshcore-client/issues/917) · Citadel `meshcore-open-1hf` |
| **Serves** | No parent Initiative; a standalone Feature. Resolves the cause behind [#334](https://github.com/OffbandMesh/meshcore-client/issues/334), the originating Epic, which stays open until this Feature's integration test proves the ANRs are gone. |
| **Status** | Draft. Approved when this PR merges. |
| **Owner** | @Strycher |
| **Last updated** | 2026-10-19 |
## At a glance
- **What:** stop re-encoding a channel's entire message history every time one message arrives. First move the work off the UI isolate (Epic A), then delete the work by storing one row per message (Epic B).
- **Why:** 25 ANR clusters on Play since September, all `Input dispatching timed out`. The cost grows linearly with history, so it worsens for exactly the users who use the app most. ANR rate is also the Android vitals signal Google uses to suppress an app in Play search, and Offband is currently absent from search for "meshcore" while ranking first for "offband".
- **How:** entirely client-side. No firmware change. Three Epics in order: A isolate offload, B normalise to rows with a migration, C hardware integration test.
- **Done when:** receiving a message costs the same at 50,000 messages of history as at 50, no message is lost in the migration, and the owner confirms on hardware on Android and Windows.
## 1. Diagnosis
All figures measured 2026-10-19 against the owner's live database and the real Dart VM. Full evidence: [#334 comment](https://github.com/OffbandMesh/meshcore-client/issues/334#issuecomment-6262727767).
| # | Finding | Evidence |
|---|---|---|
| 1 | `StoredBlobs` is `key TEXT PRIMARY KEY, value TEXT`: one JSON blob per store key | `lib/storage/drift/offband_database.dart:347` |
| 2 | Live DB is 41.03 MB: 151 rows, 39.21 MB of JSON. Largest row is 5.38 MB holding **9,230 messages** in one channel | `select key, length(value) from stored_blobs` on a copy of the live DB |
| 3 | Saving one message decodes the whole blob, rebuilds every record, re-encodes the whole blob | `channel_message_store.dart:80-104`, `message_store.dart:33-57` |
| 4 | That costs **134 ms** on a desktop CPU: decode 50, rebuild 38, encode 51 | Dart benchmark, real 5.39 MB payload, median of 5 |
| 5 | Cost scales linearly: ~14 ms per 1,000 records of history, per message | 500 recs 4 ms, 1k 12 ms, 2.5k 26 ms, 5k 83 ms, 9,230 130 ms |
| 6 | Appending one record instead costs **0.002 ms**, so the current path does **67,000x** more work per message | Same benchmark, single-record encode, median of 200 |
| 7 | Bursts serialize: `BlobStore.synchronized` chains futures per key, so N messages each pay full cost | `blob_store.dart:58-62` |
| 8 | 5 messages on a 10x slower device is **6.7 s**, past the 5 s ANR watchdog | Arithmetic on finding 4. **Not reproduced on a device**; see Risks |
| 9 | Each cycle allocates ~11 MB of strings plus 9,230 maps, which is why traces are dominated by GC frames | `ScavengerVisitor`, `MarkingVisitor`, `FreeList::TryAllocate`, `String::ConcatAllRange` in 25 clusters |
| 10 | **#335 did not fix this.** It moved the bytes into SQLite; the JSON stayed. ANRs span version codes 65, 66 and 67, all post-drift | Play Reporting API clusters by `lastAppVersion` |
| 11 | **SQLite was never on the UI isolate.** `drift_flutter` 0.3.1 hosts connections in a background isolate; web uses `drift_worker.js` | `drift_flutter-0.3.1/lib/src/connect.dart` |
| 12 | Only 9 distinct users affected, 1 per cluster, consistent with cost scaling by history | `distinctUsers` on every cluster |
**Root cause:** O(entire history) work per message, serialized across a burst, with GC pressure compounding it.
## 2. Decisions
| Decision | Choice | Why |
|---|---|---|
| Fix the isolate first or normalise first | Isolate first | Stops the ANRs and the Play penalty with zero data risk, and buys time to do the migration carefully |
| Is the isolate offload sufficient | No | It relocates ~11 MB of allocation per message rather than removing it. Total work unchanged |
| Isolate granularity | One `Isolate.run` around the **whole** read-modify-write | Only two strings cross the boundary. Wrapping encode and decode separately would ship the object graph across twice |
| Where the helper lives | `BlobStore` | One place, so stores change call shape instead of each growing its own isolate wrapper |
| Migration safety | Additive. Blob retained until per-key readback matches | #355 cost 574 messages after the last storage migration shipped in a day |
| Retype #334 | No | #917 is the Feature and carries this plan. #334 stays as the originating Epic and closes on the integration test. Less board churn |
## 3. Epic chain
### Epic A: blob read-modify-write off the UI isolate
One helper in `lib/storage/drift/blob_store.dart` that runs the entire read, decode, merge, encode, write inside a single `Isolate.run`, taking the raw JSON string in and returning the merged string out. Then call-shape changes in `channel_message_store.dart`, `message_store.dart` and `lib/services/storage_service.dart` (11 JSON call sites). Smaller stores follow only if measurement says they matter.
**Epic verification:** the benchmark harness shows main-isolate block time at or near zero against the real 5.39 MB payload, and the owner confirms a burst no longer freezes the UI.
#### Epic A outcome, 2026-10-19
Built as A1 (`BlobStore.mergeOffThread`), A2 (DM save), A3 (both explicit delete paths), A5 (verification). Measured against the owner's real largest channel, 5,650,194 chars / 9,230 messages, on a desktop:
| | UI blocked | wall | heartbeats |
|---|---|---|---|
| 1 save, inline (pre-#919) | 381 ms | 381 ms | 1 |
| 1 save, off-thread | 44 ms | 297 ms | 174 |
| 5 saves, inline | 1,385 ms | 1,385 ms | 1 |
| 5 saves, off-thread | 66 ms | 1,496 ms | 964 |
Wall time barely moves, as predicted. Inline, the blocked time equals the whole operation. The burst case is now measured rather than arithmetic, though still on desktop hardware; the device check remains the owner's.
**A4 (`storage_service.dart`) was measured and declined**, which is this section's "smaller stores follow only if measurement says they matter" resolving to no. The largest value that file touches is 20,907 bytes (`path_history`, from the owner's live prefs); it costs 0.22 ms inline and 0.48 ms through `Isolate.run`, so converting those 11 call sites would add 2.2x the work. Full numbers: [#919 comment](https://github.com/OffbandMesh/meshcore-client/issues/919#issuecomment-6269611306).
That measurement turned up two things outside this Feature's shape, filed rather than absorbed:
- [#923](https://github.com/OffbandMesh/meshcore-client/issues/923): on Windows, one `SharedPreferences` write costs **49.4 ms on the UI isolate**, because `shared_preferences_windows` is pure Dart and re-encodes plus rewrites the whole file per key. Measured against the owner's live 4.23 MB prefs.
- [#924](https://github.com/OffbandMesh/meshcore-client/issues/924): `path_history_` is unbounded on disk, 2,041 keys and 86% of that prefs file, which makes every write in #923 worse over time.
Both are children of #334 and neither is fixed by this Feature.
### Epic B: normalise messages into rows
A real drift table beside `StoredBlobs`, one row per message. A save becomes an INSERT; reads page. Both message stores' read and write paths rewritten. An additive migration that never deletes a blob until readback proves the per-key count matches.
**Epic verification:** per-key message counts identical before and after on a copy of the real 41 MB database, and the benchmark shows per-message cost flat across history length.
#### Epic B outcome, 2026-10-19
Built as B1 (`message_records` at schema 2 plus a row API), B2 (both stores on rows), B3 (the per-key migration and its gate), B4 (verification). Run against a copy of the live 41.17 MiB database:
| | |
|---|---|
| keys migrated | **138 of 138** |
| records in blobs | 64,883 |
| rows stored | **64,883** |
| elapsed | 4,382 ms |
Exact parity, no refusals, and every blob byte-identical afterwards (length and content hash per key).
Per-message save cost against history length, median of 20:
| history | one more save |
|---|---|
| 500 | 0.124 ms |
| 5,000 | 0.126 ms |
| 50,000 | 0.133 ms |
A hundred times the history for 1.07x the cost, against 381 ms of UI block at 9,230 messages on the blob path. The Feature's "done when" is met.
One-time migration of the worst key (5.38 MiB, 9,230 messages), measured with a production-shaped background-isolate connection: **UI blocked 64 ms, wall 447 ms**. So the first open of the biggest channel after this ships costs one 64 ms hitch on a desktop.
**Two deliberate departures from this plan, both stricter or narrower, never looser:**
1. **The blob is never deleted**, not even on a verified match. This plan said "retained until per-key readback matches"; the implementation keeps it after the match too. Rows become the read and write path and the blob is left untouched, so the database temporarily holds both copies. Reclaiming that space is a separate owner-gated step, because the moment that delete runs is the moment a mistake stops being recoverable.
> **Correction, 2026-10-21 (#943), revised 2026-10-22.** This section originally added that a downgrade to an older build "still finds its history where it looks for it". That is true of the **data** and false in **practice**, and the owner hit it: a pre-#917 build cannot open a migrated database at all, so it never gets as far as the blobs it would have read.
>
> The first version of this correction gave the wrong reason, namely that drift refuses a newer `user_version`. It does not; there is no such check. drift compares the stored version against `schemaVersion` for *inequality* and routes a downgrade into `onUpgrade` just like an upgrade. The pre-#917 build declared schema 1 and **no `migration` getter**, so it got drift's default `onUpgrade`, which throws. The conclusion stands and is in fact firmer: every already-shipped build lacks that strategy, so no change made now can let one open a schema-2 file.
>
> The consequence is a release one, not a desktop one: **once a user launches a schema-2 build they cannot go back to an earlier release.** A Play rollback or a halted staged rollout does not help anyone who already launched it, and the real fallback is an older build *plus* a pre-migration database copy, which loses everything received since. #943 carries the decisions (release-note wording, whether to tolerate a newer schema, whether the app should take its own pre-migration copy), with measurements and a recommendation per decision in its comments. Behaviour is pinned by `test/storage/schema_downgrade_test.dart`.
2. **One row per message with the per-message JSON in a `payload` column**, rather than a column per field. The migration is then a pure re-key with no field mapping that can silently drop or coerce a value, and the stores reuse their existing encoders verbatim. The trade, stated on the issue before building: message fields are not SQL-queryable. Columns can be added beside the payload later without another data migration.
### Epic C: Integration Testing
A and B together on real hardware, Android and Windows. Carries the test that validates #334 is dead, which gates closing it.
## 4. Interfaces
No protocol, wire-format or firmware change. No new dependency: `Isolate.run` is `dart:isolate`, and drift is already present. Storage schema change is internal and additive.
## 5. Secrets
None. This Feature touches no credential, key or external service.
## 6. Cannot-tell branches (standards#677)
| Branch | Behaviour |
|---|---|
| `Isolate.run` throws | **Stop.** Surface the error, leave the blob untouched. Never fall back to a silent main-thread encode |
| Blob is corrupt or not a JSON list | **Stop.** Do not overwrite. Log the key and byte length, keep the original |
| Migration readback count mismatch for a key | **Stop.** Keep the blob, delete nothing, surface loudly |
| Row insert fails mid-migration | **Stop** inside a transaction, roll back, keep the blob |
| Payload too large to send across the isolate | **Ask the owner.** Needs a measured threshold first; no guessed limit |
No fail-open paths. No branch proceeds on a condition it cannot confirm.
## 7. Risks
| Risk | Mitigation |
|---|---|
| Migration loses messages | Additive, blob retained, per-key readback gate, test against a copy of the real 41 MB DB |
| The burst multiplier is arithmetic, not observed | Epic A's verification includes an owner device check. If a burst does not reproduce, the ANR cause is re-opened rather than assumed fixed |
| Isolate transfer cost exceeds the saving on small blobs | Measure before converting the smaller stores. Epic A converts the three big ones first |
| Play traces stay unresolvable | Out of scope here. Release builds strip Dart symbols, so no frame from this codebase appears in any trace. Retaining native debug symbols is a separate pipeline issue |
## 8. Owner steps
One, at the end of Epic A, and one at the end of Epic C: run the build on hardware and confirm the UI no longer freezes under a burst. Everything else, including the migration test, runs without him.
## grant-terms
The Epic chain is [#919](https://github.com/OffbandMesh/meshcore-client/issues/919) (A, isolate offload), [#920](https://github.com/OffbandMesh/meshcore-client/issues/920) (B, normalise to rows), [#921](https://github.com/OffbandMesh/meshcore-client/issues/921) (C, integration testing), merged in that order.
```grant-terms
{ "epic_chain": [919, 920, 921],
"chain": true,
"verification": {"mode": "owner"},
"merge": {"budget": 3,
"basis": "one merge per Epic in the chain (919, 920, 921); Tasks are commits on the Epic branch, so there is no per-task PR"},
"expires_after_hours": 72 }
```
**Basis for the expiry.** 72 hours because Epic B carries a migration test against a copy of the real 41 MB database, and a grant that outlasts a careful run beats one expiring mid-chain and needing a re-mint.
**No flash or reset budget.** Nothing in this Feature touches a radio, so both keys are omitted and default to null.
**Verification is `owner` rather than a command** because two of the three Epics end in a judgement only the owner can make: that the UI no longer freezes under a burst on his device, and that nothing is missing after the migration. A command here would be a check that cannot fail, which the tool flags and which would verify nothing.

@ -0,0 +1,175 @@
# Feature PLAN: reclaim the stale post-migration message blob
| | |
|---|---|
| **Feature** | [#962](https://github.com/OffbandMesh/meshcore-client/issues/962) · Citadel `meshcore-open-8xj` |
| **Serves** | Follows the #917 storage rewrite. #917's plan deferred this as "a separate owner-gated step, because the moment that delete runs is the moment a mistake stops being recoverable." The owner opened that gate on 2026-10-22. |
| **Status** | Draft. Approved when this PR merges. |
| **Owner** | @Strycher |
| **Last updated** | 2026-10-22 |
## At a glance
- **What:** each migrated message key gets a timestamp; **30 days** later its stale blob is deleted, with a Settings action to do it immediately.
- **Why now:** schema 2 has not shipped. Every install that takes it will hold its message history twice, and the fix can be in place before anyone receives it.
- **How:** Epic A writes the timestamps and the sweep, Epic B the manual action, Epic C the owner's hardware check.
- **Done when:** a key migrated more than 30 days ago has no blob, the file has actually shrunk, and a key whose re-verify fails still has its blob.
## 1. Diagnosis
| # | Finding | Evidence | Effect |
|---|---|---|---|
| 1 | The migrated blob goes **stale**: nothing writes it after a key is marked. | Every blob write is in the fallback branch behind an early `return` in the migrated branch: `channel_message_store.dart:175,235`, `message_store.dart:111,152`. | The blob is a frozen snapshot at the migration moment, not a mirror. Deleting it costs the pre-migration snapshot and nothing else. |
| 2 | Nothing ever deletes it. | No caller removes a migrated history blob. `ensureMessageRowsMigrated` documents "**The blob is never deleted**, not even on a verified match." | The database holds the history twice, permanently. |
| 3 | `DELETE` frees **no disk space**. | Measured on a copy of the owner's database: 74,350,592 bytes before, **74,350,592 after** deleting all 40 migrated blobs. | A sweep without `VACUUM` reclaims nothing the user can see. |
| 4 | `VACUUM` reclaims it, cheaply. | Same copy: 54,919,168 bytes after, **-18.5 MiB in 0.6 s**, `integrity_check ok`, all 28,386 rows intact. | One `VACUUM` after a sweep is the whole win. |
| 5 | Migration is **lazy and per key**. | The owner's install had 40 keys migrated (16.2 MB of blob) and **98 not** (23.8 MB), because those radios had not been reconnected. | An install-wide clock would delete nothing for a long time, then a lot at once. The marker must be per key. |
| 6 | The marker holds no timestamps. | `__msgrows_migrated` is `jsonEncode(keys.toList())`, a flat array (`blob_store.dart:281`). | There is nothing to age a key against today. |
| 7 | Some blobs are **not** reclaimable and must not be touched. | `contacts*`, `discovered_contacts*`, `path_history_*` have no row equivalent; the blob IS their storage. 2.0 MB on his install. | The sweep must be restricted to migrated message-history keys. |
| 8 | Clearing history already removes both copies. | `clearChannelMessages` calls `deleteEverywhere` **and** `deleteMessageRows` (`channel_message_store.dart:361,372`). | No stale-history-after-delete hole to fix. Checked because it would be worse than wasted space. |
| 9 | Losing the marker after deletion is survivable. | `blob_store.dart:340`: an empty or absent blob re-marks the key and reads rows. | Deletion does not create a new single point of failure beyond the rows themselves. |
| 10 | It affects users, not just this install. | ~175 active Android installs (173 on 2026-10-17, Play installs overview) plus desktop. Schema 2 is on `dev` at `4d4d44a6` and absent from v1.6.0. | Shippable before anyone is exposed. |
| 11 | `VACUUM` removes nothing. It reclaims only pages the deletes already freed. | Measured on a copy: 40 migrated blobs deleted, 291 keys kept **including all 98 unmigrated history blobs**, each hashed before and after. 0 missing, 0 byte-changed, 0 unexpected; rows 28,389 to 28,389; file 74,350,592 to 54,927,360; `integrity_check ok`. | **All the risk is in the DELETE selection, none in `VACUUM`.** The safety budget belongs on the per-key re-verify and the key-pattern restriction, which is where this plan puts it. |
**What the snapshot does and does not protect**, so this is not mistaken for removing a backup: it protects the *pre-migration* history against a migration or read-path bug found later; it protects **nothing** that arrived since, which is single-copy from the instant it lands either way; and its coverage decays as new messages accumulate.
## 2. Scope
**In:**
- A per-key migration timestamp, including a backfill for keys already migrated when this ships.
- An automatic sweep, **once per launch**, that deletes a stale blob once its key is older than 30 days, re-verifying the key immediately before each delete rather than trusting the marker.
- One `VACUUM`, only after a sweep that actually deleted something.
- A Settings action, "Clear Stale History Now", reporting bytes before and after.
**Out:**
- The retention limit (discarding history the user has only one copy of): #963, deliberately later.
- Blobs for keys that have **not** migrated. Those are authoritative.
- `contacts*`, `discovered_contacts*`, `path_history_*`. The blob is their storage.
- Any backup or export story for rows. Raised and not asked for.
- Reclaiming the SharedPreferences legacy copies. #853 already purged those.
## 3. Epics
### Epic A: the timestamp and the sweep
| Task | Pts |
|---|---|
| **A1 · Reproduce the diagnosis as failing tests:** a key migrated long ago still has its blob; the marker carries no timestamp; `DELETE` without `VACUUM` leaves the file size unchanged. Red before anything is built. | 3 |
| **A2 · Per-key timestamps:** a `__msgrows_migrated_at` blob mapping key to epoch ms, written when a key is marked. Pre-existing migrated keys are **stamped on first sight**, not treated as eligible, so no blob is deleted the moment a user updates. | 3 |
| **A3 · The sweep:** for each migrated message-history key older than the 30-day constant, re-run the superset check (every blob record present as a row) and delete the blob **only** on a pass. Restricted to `channel_messages_*` and `messages_*`. Wired to run **once per launch**, after startup settles, never mid-session. | 4 |
| **A4 · One `VACUUM`,** only if the sweep deleted something, with the reclaimed byte count logged. | 3 |
| **A5 · Epic verification:** the named command, plus the sweep run against a copy of a real database. | 1 |
### Epic B: "Clear Stale History Now"
| Task | Pts |
|---|---|
| **B0 · Mock-ups FIRST, owner-approved before any of it is built.** Every state of every new surface, as a committed HTML file beside this plan, in the format the firmware initiative uses: numbered variants, real chrome and tokens, example values from the owner's own install, and the behaviour to build as bullets under each. **Added 2026-10-23, after this Epic's UI was built and installed on both his machines without him ever seeing the design.** The plan had no such step, which is why that happened. | 2 |
| **B1 · The action** in Settings, showing database size before and after and how many keys were cleared, with the same re-verify and refusal path as the sweep. Per decision 4 it **reports keys it refused** in the result, not just the log: "cleared 12, kept 1 that failed verification". | 3 |
| **B1a · A confirmation stating the scope** before anything is deleted: how many copies, roughly how much space, how many messages are *not* affected, and that it cannot be undone. Needs a **preview pass** in the sweep, verifying every eligible key and totalling it without deleting, so the numbers are real rather than estimated. Verification then runs twice for a confirmed clear, once to preview and once under the key lock. That is the price of saying what will go before it goes. Owner-required 2026-10-23. | 3 |
| **B2 · Widget tests:** the action with nothing eligible, with eligible keys, and with a key whose re-verify fails (which must report a refusal rather than silence). Plus the confirmation: it states the scope, Cancel deletes nothing and leaves the action usable, a forecast refusal is shown before the press, and nothing eligible opens no dialog at all. | 3 |
| **B3 · Epic verification** | 1 |
### Epic C: Integration Testing
| Task | Pts |
|---|---|
| **C1 · Owner hardware run,** Windows and Android: the action reports a real reduction, history still reads correctly afterwards, and an unmigrated radio's history is untouched when that radio is next connected. | 3 |
| **C2 · Post-run read-back** of the live database: no migrated key retains a blob, unmigrated keys all do, row count unchanged. | 1 |
## 4. Order and dependencies
A before B: the action is a manual trigger for the sweep A builds, so building B first would mean writing the engine twice. C last, per canon, and it is the only Epic needing the owner.
A and B both touch `blob_store.dart`; B also touches the Settings screen and ARB files. No overlap with #963, which should follow this rather than lead it (see its fourth open question: a row trim makes the blob a superset of the rows, which is this sweep's refusal condition, so the two must agree on authority or a trim permanently blocks reclamation the way #952 did).
## 5. Grants and authorization
| Term | Proposed | Why |
|---|---|---|
| **What merging this plan authorizes** | Building Epics A, B and C, and merging one PR per Epic. | Three Epics, three PRs. |
| **Merges** | 3 | One per Epic. Tasks are commits on the Epic branch, so there is no per-task PR. |
| **Epic verification** | Owner approves each Epic's PR. | A destructive data operation. Each Epic's PR should be looked at, not auto-verified by a command. |
| **Owner steps during the run** | Epic C only. | A and B are test-provable; only the real-hardware reduction needs him. |
| **Stops** | Any key whose re-verify fails. The sweep keeps that blob, logs loudly, and never retries into a loop. | The #952 lesson: a refusal that silently repeats forever is worse than a loud one. |
| **Flash** | None. | No firmware. |
```grant-terms
{
"epic_chain": [965, 966, 967],
"chain": true,
"verification": { "mode": "owner" },
"merge": { "budget": 3, "basis": "one merge per Epic (A the timestamp and sweep, B the manual action, C Integration Testing); Tasks are commits on the Epic branch, so there is no per-task PR" },
"flash": null,
"reset": null,
"expires_after_hours": 168
}
```
**`epic_chain` filled 2026-10-23:** [#965](https://github.com/OffbandMesh/meshcore-client/issues/965) (Epic A, the timestamp and sweep), [#966](https://github.com/OffbandMesh/meshcore-client/issues/966) (Epic B, the manual action), [#967](https://github.com/OffbandMesh/meshcore-client/issues/967) (Epic C, Integration Testing). All three are sub-issues of #962, with Citadel tasks `meshcore-open-5vt`, `-gan` and `-2jd` chained A to B to C.
It was left empty when this plan first merged, which was a sequencing mistake: `grant.py` requires a non-empty chain, so the plan as merged could not have minted a grant and this follow-up was needed. The Epic issues should exist before a plan PR merges.
**Basis for the expiry.** 168 hours, the maximum. Epic C ends in an owner hardware step on two platforms and he has a day job; a grant expiring between Epic B's merge and Epic C's run would need a re-mint for no reason.
## 6. Can't-tell branches
| Where | Can't tell what | Does |
|---|---|---|
| Sweep: a key's re-verify finds a blob record with no row | whether the rows really hold this key's history | **stop** — keep the blob, log which records are missing, never delete, do not retry in a loop |
| Sweep: the blob will not decode during re-verify | what the blob contains | **stop** — keep it, log it |
| Sweep: a migrated key has no timestamp | when it migrated | **stop** deleting — stamp it now and let it age the full 30 days |
| Sweep: the key is not `channel_messages_*` or `messages_*` | whether a row equivalent exists | **stop** — out of scope, never considered |
| `VACUUM` fails, e.g. no temporary space | whether the file can be compacted | **proceeds**, logging the failure. Not fail-open on data: the deletes already happened and are correct, and `VACUUM` only affects file size. The next sweep retries it. |
No fail-open branch touches data. The one branch that proceeds affects file size only, and the deletes it follows are each individually verified.
## 7. Verification
- **Named command:** `flutter test test/storage/ test/screens/` plus `flutter analyze`
- **Acceptance bar:**
- A key stamped older than 30 days, whose rows hold every blob record, loses its blob; the file shrinks after `VACUUM`.
- A key stamped older than 30 days with **one** blob record missing from rows **keeps** its blob, and the refusal names the missing records. This gate must be proved able to fail.
- A key stamped inside 30 days keeps its blob, including at 29 days, so the boundary is tested and not just the middle of each range.
- A migrated key with no timestamp is stamped, not deleted.
- `contacts`, `discovered_contacts` and `path_history_` keys are never considered, asserted by name.
- An unmigrated history key keeps its blob.
- **Every kept blob is byte-identical after `VACUUM`**, compared by hash before and after, with the unmigrated history keys asserted present by name. Row count unchanged. This is the owner's question answered as a test rather than a paragraph: the sweep must be shown to delete only what it selected, and `VACUUM` to add nothing to that set.
- Run against a copy of a real database, reporting bytes reclaimed, and skipping loudly rather than passing when no database is supplied.
## 8. Done when
- No key migrated more than 30 days ago retains a message-history blob.
- The database file is measurably smaller, verified by reading the live file, not by trusting a log line.
- Row count is unchanged across the whole sweep.
- A key whose re-verify fails still has its blob, and said so.
- The Settings action reports a real before and after on the owner's install, on both platforms.
## 9. Decisions
Owner, 2026-10-22: *"X = 30, sweep once per launch, timestamps in separate blob, button reports refusals, agreed."* All four as recommended.
| # | Question | Decision | Why |
|---|---|---|---|
| 1 | How long is X? | **30 days** | One full month of real use, and it matches the monthly granularity of the Play installs and crash reports the owner reads, so a migration problem gets a reporting cycle to surface in before the snapshot goes. 14 would have halved the double-storage window and also halved the time to notice. |
| 2 | When does the automatic sweep run? | **Once per launch**, after startup settles | Predictable, at most one `VACUUM` per launch, and it cannot fire mid-session while the app is in use. |
| 3 | Where do the timestamps live? | **A separate `__msgrows_migrated_at` blob** | `__msgrows_migrated` is read on every save and load through a cached hot path; reshaping it would risk that path and need its own migration. The timestamps are read only by the cold once-per-launch sweep. |
| 4 | If a key's re-verify fails, does the user hear about it? | **The manual action reports it. The automatic sweep stays log-only.** | The user pressed a button, so "cleared 12 keys, kept 1 that failed verification" is the honest result. Silence is how #952 went unnoticed. The automatic sweep has no one watching, so a log line is the right place for it. |
**30 days is a named constant, not a literal scattered through the sweep**, so changing it later is one edit and the tests can set it directly rather than manipulating clocks.
### Added 2026-10-23, after the mock-up review
| # | Question | Decision | Why |
|---|---|---|---|
| 5 | Does the manual action confirm before deleting? | **Yes, stating the scope**: how many copies, roughly how much space, how many messages are not affected, and that it cannot be undone. | It deletes and cannot be undone. See B1a; it needs a preview pass, and the mock-up's variants 8 to 10 are the approved shape. |
| 6 | "Compact" or "Clear Stale History"? | **Clear Stale History Now** | Owner's reason, and the better argument: the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. "Compact" describes `VACUUM`, which is an implementation detail. |
| 7 | Does an explicit press clear a key that has no timestamp yet? | **Yes.** The automatic sweep still refuses. | Found while building the preview. The "skip anything stamped this pass" guard exists so installing an update never deletes on sight, and it was being applied to the button too. Every install that migrated before #962 has no stamps, so the button would have reported "nothing to clear" against real reclaimable blobs. The owner's install was exactly that: 47 migrated keys, none stamped. `eligibleByAge` is now the one rule both paths share. |
## 10. Carried-in work
| Item | Goes to |
|---|---|
| Retention limit, capping days of history retained | #963 |
| Release-text disclosure for the first version carrying schema 2 | #953 |
| Whether rows need any backup or export story | not filed; raised on #943 and not asked for |

@ -0,0 +1,168 @@
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Storage card mockups</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;family=JetBrains+Mono:wght@400;600&amp;display=swap" rel="stylesheet">
<style>
/* Material 3, light scheme, blue seed, as main.dart actually configures it
(useMaterial3, ThemeMode.system, seed blue). Dark follows automatically and
is not drawn. Phone pane shown at 360 wide, the narrowest real target. */
:root{
--surf:#FDFCFF; --surfC:#FFFFFF; --surfCHigh:#F3F3FA; --surfCHighest:#E5E2EA;
--onSurf:#1B1B1F; --onSurfVar:#45464F; --outline:#767680; --outlineVar:#C7C5D0;
--prim:#0B57D0; --onPrim:#FFFFFF; --primCont:#D8E2FF; --onPrimCont:#001849;
--err:#BA1A1A; --errCont:#FFDAD6; --onErrCont:#410002;
--okCont:#C4EED0; --onOkCont:#002110;
--warnCont:#FFDEA6; --onWarnCont:#2A1800;
--page:#15151A; --pageInk:#D8D8E0; --pageDim:#8E8E99;
--sans:'Roboto',system-ui,sans-serif; --mono:'JetBrains Mono',monospace;
}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 48px}
h1{font-size:26px;font-weight:500;color:#fff}
h3{font-size:18px;font-weight:500;color:#9FC2FF;margin:30px 0 10px}
.lede{font-size:15px;color:var(--pageDim);margin:8px 0 10px;max-width:980px;line-height:1.5}
.lede b{color:var(--pageInk);font-weight:500}
.grid{display:flex;flex-wrap:wrap;gap:28px}
.card{width:360px}
.card h2{font-size:17px;font-weight:500;color:#fff}
.card .n{font-family:var(--mono);font-size:12px;color:#9FC2FF;margin-right:6px}
.card p{font-size:14px;color:var(--pageInk);margin:4px 0 10px;line-height:1.35;min-height:60px}
.card ul{font-size:13px;color:var(--pageDim);margin:10px 0 0 16px;line-height:1.4}
.card ul b{color:var(--pageInk);font-weight:500}
/* phone pane */
.dev{width:360px;border:1px solid #2c2c33;border-radius:12px;overflow:hidden;background:var(--surf)}
.appbar{height:56px;display:flex;align-items:center;gap:16px;padding:0 16px;background:var(--surfCHigh);color:var(--onSurf)}
.appbar .bk{font-size:20px;color:var(--onSurfVar)}
.appbar .t{font-size:20px;font-weight:400}
.pane{padding:16px;display:flex;flex-direction:column;gap:16px;background:var(--surf)}
.mc{background:var(--surfC);border-radius:12px;padding:16px 20px;color:var(--onSurf);border:1px solid var(--outlineVar)}
.mc .ct{font-size:16px;font-weight:500;margin-bottom:8px}
.mc .size{font-size:16px;margin-bottom:8px}
.mc .hint{font-size:12px;color:var(--onSurfVar);line-height:1.45;margin-bottom:12px}
.mc .res{font-size:14px;margin-top:12px;line-height:1.5}
.mc .res.kept{color:var(--onWarnCont);background:var(--warnCont);border-radius:8px;padding:8px 10px;margin-top:8px}
.mc .res.bad{color:var(--onErrCont);background:var(--errCont);border-radius:8px;padding:8px 10px}
.btn{display:inline-flex;align-items:center;justify-content:center;height:40px;padding:0 20px;border-radius:20px;
font-size:14px;font-weight:500;background:var(--primCont);color:var(--onPrimCont);border:none}
.btn.off{background:var(--surfCHighest);color:var(--outline)}
.btn.txt{background:none;color:var(--prim);padding:0 12px}
.btn.dang{background:var(--errCont);color:var(--onErrCont)}
.ghost{font-size:14px;color:var(--onSurfVar)}
/* dialog */
.scrim{background:rgba(0,0,0,.45);padding:28px 16px;display:flex;justify-content:center}
.dlg{background:var(--surfCHigh);border-radius:28px;padding:24px;max-width:312px;width:100%;color:var(--onSurf)}
.dlg .dt{font-size:24px;font-weight:400;line-height:1.25;margin-bottom:16px}
.dlg .db{font-size:14px;color:var(--onSurfVar);line-height:1.5;margin-bottom:12px}
.dlg .db b{color:var(--onSurf);font-weight:500}
.dlg .note{font-size:13px;border-radius:8px;padding:10px 12px;margin-bottom:12px;line-height:1.45}
.dlg .note.ok{background:var(--okCont);color:var(--onOkCont)}
.dlg .note.warn{background:var(--warnCont);color:var(--onWarnCont)}
.dlg .acts{display:flex;justify-content:flex-end;gap:8px;margin-top:8px}
.spin{display:inline-block;width:14px;height:14px;border:2px solid var(--outline);border-top-color:transparent;border-radius:50%;margin-right:8px;vertical-align:-2px}
.tag{font-family:var(--mono);font-size:11px;color:#9FC2FF}
</style>
</head>
<body>
<h1>Storage card and clear confirmation (Epic B, #966)</h1>
<p class="lede">Material 3, light scheme, blue seed, as <span class="tag">main.dart</span> configures it. Dark follows the same tokens and is not drawn. Phone pane at 360 wide, the narrowest real target; the Windows pane is the same widget in a wider column. Numbers are the owner's actual install on 2026-10-22: <b>70.9 MB database, 47 migrated keys, 40 with a stale copy, 29,975 messages, about 16.6 MB reclaimable</b>. Bullets under each card are the behaviour to build. <b>Owner-approved 2026-10-23:</b> all variants as drawn, and the label stays <b>Clear Stale History Now</b> rather than "Compact" &mdash; his reason is that the name generalises, so the same action can later cover clearing stale history for other reasons, such as the retention limit in #963. Variants 1 to 10 are built; 11 is the rejected label alternative, kept for the record.</p>
<h3>Where it lives</h3>
<div class="grid">
<div class="card"><h2><span class="n">1</span>App Settings, bottom of the pane</h2><p>A new <b>Storage</b> card after Cyr2Lat, last in the list. It is a read-only status plus one action, so it sits below the preference cards rather than among them.</p>
<div class="dev"><div class="appbar"><span class="bk">&#8249;</span><span class="t">App Settings</span></div>
<div class="pane">
<div class="mc"><div class="ct">Cyrillic to Latin</div><div class="hint" style="margin:0">Transliterate incoming Cyrillic text.</div></div>
<div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span></div>
</div></div>
<ul><li>Last card, so a destructive action is never the first thing under a thumb.</li><li>Size is read on build and after any clear. A failure to read it hides the row, never blocks the button (variant 7).</li><li>Same widget on Windows; only the column width differs.</li></ul></div>
</div>
<h3>The card's states, as built today</h3>
<div class="grid">
<div class="card"><h2><span class="n">2</span>Working</h2><p>The button disables and relabels while the sweep runs. A second tap in the same frame is also refused in code, because <span class="tag">setState</span> only schedules a rebuild.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn off"><span class="spin"></span>Clearing...</span></div></div></div>
<ul><li>Two concurrent sweeps would mean two concurrent <span class="tag">VACUUM</span>s.</li><li>Re-enables on success and on failure, or the action works exactly once per launch.</li></ul></div>
<div class="card"><h2><span class="n">3</span>Cleared</h2><p>Count and bytes returned, and the size row updates to what the sweep actually left behind rather than the number it started with.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Cleared 40 old copies, 16.6 MB returned.</div></div></div></div>
<ul><li>Bytes come from SQLite either side of the sweep, not from adding up blob lengths.</li><li>Pressing again is harmless: those keys have no copy left, so it reports nothing to clear.</li></ul></div>
<div class="card"><h2><span class="n">4</span>Cleared, with something kept back</h2><p>A key whose rows could not be verified keeps its copy and is <b>reported</b>, not merely logged. This is the case the Epic exists for.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Cleared 39 old copies, 16.2 MB returned.</div>
<div class="res kept">Kept 1 that could not be verified. Your messages are intact; nothing was deleted for those.</div></div></div></div>
<ul><li>Shown even when a refusal is the reason <b>nothing</b> was cleared, which is the most important case to surface, not the least.</li><li>The automatic 30-day sweep stays log-only: nobody is watching it.</li><li>Which keys and which records are named in the durable audit, not on screen.</li></ul></div>
<div class="card"><h2><span class="n">5</span>Nothing to clear</h2><p>The ordinary state for anyone who has already swept, or who has no migrated history yet.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Nothing to clear.</div></div></div></div>
<ul><li>Says so plainly rather than showing a zero-byte success.</li></ul></div>
<div class="card"><h2><span class="n">6</span>Failed</h2><p>It must not read as "something was half-deleted", and it must not claim nothing happened either, because the sweep deletes per key and a throw can follow real deletes.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res bad">Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.</div></div></div></div>
<ul><li>No exception text on screen; the reason goes to the log and the audit.</li></ul></div>
<div class="card"><h2><span class="n">7</span>Size unreadable</h2><p>A size we cannot read is not a reason to block clearing, so the row is left out and the action stays live.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span></div></div></div>
<ul><li>Logged as a warning, never surfaced as an error.</li></ul></div>
</div>
<h3>Proposed: confirm before deleting</h3>
<p class="lede">None of this exists. It needs a <b>preview pass</b> in the sweep: verify every eligible key and total it, without deleting, so the dialog can state real numbers rather than a guess. The verification then runs twice, once to preview and once under the key lock to delete, which is the cost of saying what will go before it goes.</p>
<div class="grid">
<div class="card"><h2><span class="n">8</span>Confirm, the normal case</h2><p>States what will be cleared, what is not affected, and that it cannot be undone. The action button carries the count so the last thing read is the scope.</p>
<div class="dev"><div class="scrim"><div class="dlg">
<div class="dt">Clear stale history?</div>
<div class="db">This removes <b>40 old copies</b> of history that has already moved to the new format, freeing about <b>16.6 MB</b>.</div>
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
<div class="note warn">This cannot be undone.</div>
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 40 copies</span></div>
</div></div></div>
<ul><li>Counts come from a real preview pass, not an estimate.</li><li>Cancel is the plain text button and sits left, so the destructive one is never the default target.</li><li>Dismissing by tapping outside or back cancels.</li></ul></div>
<div class="card"><h2><span class="n">9</span>Confirm, with a forecast refusal</h2><p>If the preview already knows a key cannot be verified, say so <b>before</b> the press rather than reporting it afterwards.</p>
<div class="dev"><div class="scrim"><div class="dlg">
<div class="dt">Clear stale history?</div>
<div class="db">This removes <b>39 old copies</b> of history that has already moved to the new format, freeing about <b>16.2 MB</b>.</div>
<div class="note ok">Your messages are not affected. All 29,975 stay.</div>
<div class="note warn">1 copy will be kept back because its messages could not be verified. This cannot be undone.</div>
<div class="acts"><span class="btn txt">Cancel</span><span class="btn dang">Clear 39 copies</span></div>
</div></div></div>
<ul><li>The count in the button excludes what will be kept, so it matches what actually goes.</li><li>A refusal discovered only at delete time still reports after the fact, as variant 4.</li></ul></div>
<div class="card"><h2><span class="n">10</span>Nothing eligible, no dialog</h2><p>With nothing to clear there is nothing to confirm, so the press reports straight away rather than opening a dialog to say "zero".</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 54.3 MB</div>
<div class="hint">When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.</div>
<span class="btn">Clear Stale History Now</span>
<div class="res">Nothing to clear.</div></div></div></div>
<ul><li>The preview runs on the press. Empty result means no dialog at all.</li><li>So the preview must be cheap enough to run on a tap: it reads and verifies, it does not write.</li></ul></div>
<div class="card"><h2><span class="n">11</span>Label: the open question</h2><p>The owner said "Compact"; the button says "Clear Stale History Now". Drawn here with his word in the title and the plain description in the body.</p>
<div class="dev"><div class="pane"><div class="mc"><div class="ct">Storage</div><div class="size">Message database: 70.9 MB</div>
<div class="hint">Compacting removes the old copy of history that has already moved to the new format, and returns the space. It happens on its own 30 days after the move.</div>
<span class="btn">Compact now</span></div></div></div>
<ul><li>"Compact" is what <span class="tag">VACUUM</span> does and reads less alarming; "Clear Stale History" says what is removed.</li><li>Owner's call. Either way the dialog in variant 8 states the scope.</li></ul></div>
</div>
</body></html>

@ -0,0 +1,280 @@
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Location screen and settings restructure mockups</title>
<style>
/* Doc chrome: Offband design-doc family, as the firmware GUI mockups.
Inside the frames: Flutter Material 3, drawn against the real widgets in
lib/screens/settings/settings_shell.dart (ListTile + leading Icon + subtitle
+ chevron, inside Cards, under a centred AppBar).
Self-contained on purpose: icons are inline SVG, fonts are system stacks.
Nothing here needs the network to render. */
:root{
--bg2:#161C19; --line:#34403A; --line2:#232C28;
--ink:#EFF3E8; --ink2:#BAC4B5; --dim:#8B9A91; --sig:#7BEFA8;
--warn:#FFA552; --bad:#FF7A6E;
--sans:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;
--mono:'Cascadia Mono',Consolas,'SF Mono',Menlo,monospace;
--page:#0a0d0c; --pageInk:#cfd6cc;
/* Material 3, blue seed, light. The client's actual scheme. */
--surface:#FDFBFF; --onSurface:#1A1C1E; --onSurfaceVar:#44474F;
--cardBg:#F2F3F7; --outline:#74777F; --outlineVar:#C4C6D0;
--primary:#0061A4; --secCont:#D6E3FF; --onSecCont:#001D36;
--ok:#1E6B39; --amber:#8A5000; --grey:#74777F;
}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 56px}
h1{font-size:25px;font-weight:600;color:var(--ink);letter-spacing:-.2px}
h3{font-size:17px;font-weight:600;color:var(--sig);margin:32px 0 12px}
.lede{font-size:14px;color:var(--dim);margin:8px 0 4px;max-width:1040px;line-height:1.55}
.lede b{color:var(--ink2);font-weight:500}
code{font-family:var(--mono);font-size:11.5px;color:var(--sig)}
.why code{color:var(--ink2)}
.flag{display:inline-block;font-family:var(--mono);font-size:10.5px;font-weight:600;color:#0a0d0c;background:var(--sig);border-radius:3px;padding:2px 7px}
.grid{display:flex;flex-wrap:wrap;gap:30px}
.card{width:324px}
.card h2{font-size:17px;font-weight:600;color:var(--ink)}
.card .n{font-family:var(--mono);font-size:12px;color:var(--sig);margin-right:7px}
.card>p{font-size:13.5px;color:var(--ink2);margin:5px 0 12px;line-height:1.45;min-height:58px}
.card ul{font-size:12.5px;color:var(--dim);margin:12px 0 0 16px;line-height:1.5}
.card li{margin-bottom:5px}
.card ul b{color:var(--ink2);font-weight:500}
.sub{font-size:12.5px;color:var(--dim);margin-bottom:8px}
.dev{border:1px solid #2a332f;border-radius:14px;overflow:hidden;background:#000}
.d-loc{width:324px;height:468px} .s-loc{width:390px;height:563px;transform:scale(.8308)}
.d-set{width:316px;height:600px} .s-set{width:390px;height:740px;transform:scale(.8103)}
.d-pan{width:316px;height:268px} .s-pan{width:390px;height:331px;transform:scale(.8103)}
.scr{transform-origin:0 0;background:var(--surface);color:var(--onSurface);
font-family:'Segoe UI',system-ui,Roboto,sans-serif;display:flex;flex-direction:column}
/* Material 3 parts */
.ic{width:24px;height:24px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;
stroke-linecap:round;stroke-linejoin:round}
.ic .f{fill:currentColor;stroke:none}
.ab{height:64px;flex:none;display:flex;align-items:center;padding:0 4px;position:relative}
.ab .nav{width:48px;height:48px;display:flex;align-items:center;justify-content:center;color:var(--onSurface)}
.ab .t{position:absolute;left:56px;right:56px;text-align:center;font-size:21px;color:var(--onSurface)}
.lv{flex:1;min-height:0;overflow:hidden}
.lv.p16{padding:16px}
.tile{display:flex;align-items:center;gap:16px;padding:10px 16px;min-height:56px}
.tile.two{min-height:72px}
.tile .lead{flex:none;color:var(--onSurfaceVar)}
.tile .txt{flex:1;min-width:0}
.tile .ti{font-size:15.5px;color:var(--onSurface);line-height:1.3}
.tile .ts{font-size:13px;color:var(--onSurfaceVar);line-height:1.35;margin-top:3px}
.tile .tr{flex:none;color:var(--onSurfaceVar)}
.tile .btn{flex:none;font-size:14px;font-weight:500;color:var(--primary);padding:10px 8px 10px 12px}
.tile.sel{background:var(--secCont)}
.tile.sel .ti,.tile.sel .lead,.tile.sel .ts,.tile.sel .tr{color:var(--onSecCont)}
.dv{height:1px;background:var(--outlineVar)}
.mcard{background:var(--cardBg);border-radius:12px;box-shadow:0 1px 3px rgba(0,0,0,.10);overflow:hidden;margin-bottom:16px}
.lbl{font-size:13px;color:var(--onSurfaceVar);padding:14px 16px 8px}
.segwrap{padding:0 16px 14px}
.seg{display:grid;border:1px solid var(--outline);border-radius:20px;overflow:hidden;height:40px}
.seg.c3{grid-template-columns:repeat(3,minmax(0,1fr))} .seg.c2{grid-template-columns:repeat(2,minmax(0,1fr))}
.seg>div{display:flex;align-items:center;justify-content:center;gap:5px;font-size:13.5px;
color:var(--onSurface);border-right:1px solid var(--outline);white-space:nowrap}
.seg>div:last-child{border-right:0}
.seg>div.on{background:var(--secCont);color:var(--onSecCont)}
.seg .ck{width:17px;height:17px;flex:none}
.ic-ok{color:var(--ok)} .ic-am{color:var(--amber)} .ic-gr{color:var(--grey)}
.badge{font-size:10.5px;color:#0a3d1a;background:#B7E6C4;border-radius:100px;padding:2px 8px;margin-left:8px;vertical-align:1px}
.keep{font-size:10.5px;color:var(--onSurfaceVar);margin-left:8px}
.why{display:flex;flex-wrap:wrap;gap:18px}
.why>div{width:436px;border-left:2px solid var(--sig);padding:2px 0 2px 13px}
.why.red>div{border-left-color:var(--bad)}
.why h4{font-size:14.5px;font-weight:600;color:var(--ink);margin-bottom:4px}
.why p{font-size:12.5px;color:var(--dim);line-height:1.55}
</style>
</head>
<body>
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>
<symbol id="i-back" viewBox="0 0 24 24"><path d="M19 12H5"/><path d="M12 19l-7-7 7-7"/></symbol>
<symbol id="i-chev" viewBox="0 0 24 24"><path d="M9 5l7 7-7 7"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></symbol>
<symbol id="i-pin" viewBox="0 0 24 24"><path d="M12 21.5S19 15 19 10a7 7 0 10-14 0c0 5 7 11.5 7 11.5z"/><circle cx="12" cy="10" r="2.6"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M12 6.8V12l3.6 2.1"/></symbol>
<symbol id="i-gpsfix" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.4"/><circle class="f" cx="12" cy="12" r="2.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22"/></symbol>
<symbol id="i-gpsoff" viewBox="0 0 24 24"><circle cx="12" cy="12" r="6.4"/><path d="M12 2v2.4M12 19.6V22M2 12h2.4M19.6 12H22"/><path d="M4.5 19.5l15-15"/></symbol>
<symbol id="i-pause" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M10.2 9.3v5.4M13.8 9.3v5.4"/></symbol>
<symbol id="i-hour" viewBox="0 0 24 24"><path d="M7 3h10M7 21h10"/><path d="M7 3c0 4.2 5 5.9 5 9s-5 4.8-5 9"/><path d="M17 3c0 4.2-5 5.9-5 9s5 4.8 5 9"/></symbol>
<symbol id="i-badge" viewBox="0 0 24 24"><rect x="3.2" y="6" width="17.6" height="14.4" rx="2.4"/><path d="M9 6V4.6A1.4 1.4 0 0110.4 3.2h3.2A1.4 1.4 0 0115 4.6V6"/><circle cx="12" cy="11.6" r="2.2"/><path d="M8.4 17.6c.7-1.5 2-2.2 3.6-2.2s2.9.7 3.6 2.2"/></symbol>
<symbol id="i-ant" viewBox="0 0 24 24"><circle cx="12" cy="6.4" r="2.8"/><path d="M12 9.2V21M7.5 21h9"/><path d="M6.6 10.4a7.6 7.6 0 0110.8 0"/><path d="M4.2 7.6a11 11 0 0115.6 0"/></symbol>
<symbol id="i-sensor" viewBox="0 0 24 24"><circle class="f" cx="12" cy="12" r="2.2"/><path d="M8.3 8.3a5.2 5.2 0 000 7.4M15.7 8.3a5.2 5.2 0 010 7.4"/><path d="M5.6 5.6a9 9 0 000 12.8M18.4 5.6a9 9 0 010 12.8"/></symbol>
<symbol id="i-shield" viewBox="0 0 24 24"><path d="M12 3.2l7.2 2.9v5.6c0 4.5-3 7.9-7.2 9.1-4.2-1.2-7.2-4.6-7.2-9.1V6.1z"/></symbol>
<symbol id="i-contacts" viewBox="0 0 24 24"><rect x="3.2" y="5.2" width="17.6" height="13.6" rx="2.2"/><circle cx="9.2" cy="10.8" r="2.3"/><path d="M5.8 16.4c.7-1.7 1.9-2.4 3.4-2.4s2.7.7 3.4 2.4"/><path d="M15.2 10h3.4M15.2 13.6h3.4"/></symbol>
<symbol id="i-block" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M6 18L18 6"/></symbol>
<symbol id="i-sms" viewBox="0 0 24 24"><path d="M20.8 15.2a2 2 0 01-2 2H8l-4.8 4V5a2 2 0 012-2h13.6a2 2 0 012 2z"/><circle class="f" cx="8.4" cy="10.4" r="1.1"/><circle class="f" cx="12" cy="10.4" r="1.1"/><circle class="f" cx="15.6" cy="10.4" r="1.1"/></symbol>
<symbol id="i-tune" viewBox="0 0 24 24"><path d="M3.6 7h12M18.4 7h2M3.6 12h4M10 12h10.4M3.6 17h10M16 17h4.4"/><circle cx="16.8" cy="7" r="2"/><circle cx="8.6" cy="12" r="2"/><circle cx="14.6" cy="17" r="2"/></symbol>
<symbol id="i-info" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><path d="M12 11.2v5"/><circle class="f" cx="12" cy="7.9" r="1"/></symbol>
<symbol id="i-person" viewBox="0 0 24 24"><circle cx="12" cy="8" r="3.6"/><path d="M4.8 20c1.5-3.6 4-5.2 7.2-5.2s5.7 1.6 7.2 5.2"/></symbol>
<symbol id="i-radiobtn" viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.6"/><circle class="f" cx="12" cy="12" r="4"/></symbol>
<symbol id="i-bell" viewBox="0 0 24 24"><path d="M18.4 16.4V11a6.4 6.4 0 10-12.8 0v5.4l-1.8 1.9h16.4z"/><path d="M10 20.2a2.2 2.2 0 004 0"/></symbol>
<symbol id="i-vol" viewBox="0 0 24 24"><path d="M4 9.2v5.6h3.6l5 4.2V5L7.6 9.2z"/><path d="M15.8 9.4a3.8 3.8 0 010 5.2M18.4 6.8a7.6 7.6 0 010 10.4"/></symbol>
</defs></svg>
<h1>Location screen and settings restructure (client #969, epic #975)</h1>
<p class="lede">Material 3 blue seed, light, drawn at 390&times;844 against the real widgets: <code>SettingsShell</code> renders each category as a <code>ListTile</code> with a leading <code>Icon</code>, a subtitle and a trailing chevron under a centred <code>AppBar</code>, and detail panes are <code>Card</code>s of <code>ListTile</code>s split by <code>Divider(height: 1)</code>. Icon choices match <code>settings_screen.dart</code>; they are drawn here as inline SVG so this file needs no network to render. Values are examples; <b>the bullets are the behavior to build</b>. GPS mode rides firmware <code>0xC5</code> sub-codes <code>0x0D</code> / <code>0x0E</code>, gated on caps byte 2 <code>0x20</code> (meshcore-firmware#1789). <span class="flag">Owner-approved 2026-10-23</span> <b>Approved as drawn:</b> one three-way GPS control above the coordinates, one consolidated status row between them, Location as a top-level category under Radio Settings, Radio stats unchanged for now, and button and buzzer split across Node Settings and Message Settings. <b>Corrected 2026-10-24:</b> wire facts only (the command is <code>0xC5</code>, not a new <code>0xC7</code>; the buzzer-only example boards; the sleep-interval floor). The design is unchanged.</p>
<h3>The Location screen, one control and three states</h3><div class="grid">
<div class="card"><h2><span class="n">1</span>GPS off</h2><p>The selector is the only on/off control. The status row goes quiet and the sleep row is gone, because neither has meaning here.</p>
<div class="dev d-loc"><div class="scr s-loc">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
<div class="lv p16">
<div class="mcard">
<div class="lbl">GPS</div>
<div class="segwrap"><div class="seg c3"><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>Off</div><div>On</div><div>Power save</div></div></div>
<div class="dv"></div>
<div class="tile two"><span class="lead ic-gr"><svg class="ic"><use href="#i-gpsoff"/></svg></span><div class="txt"><div class="ti">GPS is off</div><div class="ts">Showing the last stored position</div></div><span class="btn">Query</span></div>
</div>
<div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div>
</div></div></div>
<ul><li>Off writes <code>gps.en = 0</code> and <b>leaves the mode byte untouched</b>, matching <code>gpsStoredModeForPick</code>.</li><li>So Off then On returns to Power save, not to continuous On. That property is why this is one control and not two.</li><li>Coordinates stay editable with GPS off; they are the manual fallback.</li></ul></div>
<div class="card"><h2><span class="n">2</span>GPS on</h2><p>Continuous acquisition. The sleep row stays hidden: it governs Power save only, and a dead row invites someone to set it.</p>
<div class="dev d-loc"><div class="scr s-loc">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
<div class="lv p16">
<div class="mcard">
<div class="lbl">GPS</div>
<div class="segwrap"><div class="seg c3"><div>Off</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>On</div><div>Power save</div></div></div>
<div class="dv"></div>
<div class="tile two"><span class="lead ic-ok"><svg class="ic"><use href="#i-gpsfix"/></svg></span><div class="txt"><div class="ti">GPS is on</div><div class="ts">Fix 2 minutes ago, 3 satellites</div></div><span class="btn">Query</span></div>
</div>
<div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div>
</div></div></div>
<ul><li>On writes <code>gps.en = 1</code> and <code>gps.mode = 1</code> together, the way <code>setGpsMode()</code> does on the device.</li><li>A stored <code>0xFF</code> (never set) also displays as On, per <code>gpsModeFromPrefs</code>.</li><li>This is the costly state: about 48 mA, roughly 1.8 days on a 3000 mAh cell against 6.8 days with GPS off.</li></ul></div>
<div class="card"><h2><span class="n">3</span>Power save, backed off</h2><p>The state a badge at an event actually sits in. One status row carries activity, next attempt and last fix, so nothing is said twice.</p>
<div class="dev d-loc"><div class="scr s-loc">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
<div class="lv p16">
<div class="mcard">
<div class="lbl">GPS</div>
<div class="segwrap"><div class="seg c3"><div>Off</div><div>On</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>Power save</div></div></div>
<div class="dv"></div>
<div class="tile two"><span class="lead ic-am"><svg class="ic"><use href="#i-pause"/></svg></span><div class="txt"><div class="ti">Backed off</div><div class="ts">Next try in 48 min, last fix 2 min ago</div></div><span class="btn">Query</span></div>
<div class="dv"></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-hour"/></svg></span><div class="txt"><div class="ti">Sleep between fix attempts</div><div class="ts">Firmware default, minimum 5 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div>
<div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div>
</div></div></div>
<ul><li>Power save writes <code>gps.en = 1</code> and <code>gps.mode = 2</code>.</li><li><b>Backed off must be named.</b> Otherwise a user sees no fix and reads a working radio as broken. The firmware models five activity states and expects this to be the common one at an event.</li><li><b>0 is a legal value</b> meaning firmware default, so the reporting-interval rule that rejects anything under 60 must not be copied onto this field.</li><li>The radio raises 1 to 299 s to 300, because one fix attempt can run 180 s. The row shows the stored value from the reply, never what was typed.</li><li>No tuned default is offered: every measured indoor attempt at 30 minutes and beyond failed to acquire (firmware #1553).</li></ul></div>
<div class="card"><h2><span class="n">4</span>A build that cannot do Power save</h2><p>Most variants do not compile the duty cycle. The third option is absent rather than offered and ignored.</p>
<div class="dev d-loc"><div class="scr s-loc">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Location</span></div>
<div class="lv p16">
<div class="mcard">
<div class="lbl">GPS</div>
<div class="segwrap"><div class="seg c2"><div>Off</div><div class="on"><svg class="ic ck"><use href="#i-check"/></svg>On</div></div></div>
<div class="dv"></div>
<div class="tile two"><span class="lead ic-ok"><svg class="ic"><use href="#i-gpsfix"/></svg></span><div class="txt"><div class="ti">GPS is on</div><div class="ts">Fix 2 minutes ago, 3 satellites</div></div><span class="btn">Query</span></div>
</div>
<div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Coordinates</div><div class="ts">39.103118, -84.512020</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-clock"/></svg></span><div class="txt"><div class="ti">Position reporting interval</div><div class="ts">Every 15 minutes</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div>
</div></div></div>
<ul><li><code>OFFBAND_GPS_POWER_SAVE</code> is opt-in per variant and today is set <b>only on the QCC badge</b>.</li><li>The device guards its own screen with <code>gpsPowerSaveAvailable()</code> so it never offers a mode nothing drives. The client needs the same signal.</li><li>Firmware sends it as <code>ps_ok</code> in every GPS reply, so Power save is hidden per radio rather than per firmware version. The caps bit <code>0x20</code> alone would not do: a radio can speak the GPS sub-codes without the duty cycle.</li></ul></div>
</div>
<h3>Where it lives</h3><div class="grid">
<div class="card" style="width:688px"><h2><span class="n">5</span>Settings, current and proposed</h2><p>GPS sits two levels down today, inside Node Settings then the Location dialog, with its enable toggle duplicated in both. Location becomes its own category and owns GPS outright.</p>
<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px">
<div><div class="sub">Current</div>
<div class="dev d-set"><div class="scr s-set">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Settings</span></div>
<div class="lv">
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-badge"/></svg></span><div class="txt"><div class="ti">Node Settings</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-ant"/></svg></span><div class="txt"><div class="ti">Radio Settings</div><div class="ts">Frequency, power, spreading factor</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sensor"/></svg></span><div class="txt"><div class="ti">Radio stats</div><div class="ts">Noise floor, RSSI, SNR, and airtime</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-shield"/></svg></span><div class="txt"><div class="ti">Privacy Settings</div><div class="ts">Control what information is shared.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-contacts"/></svg></span><div class="txt"><div class="ti">Contacts</div><div class="ts">Settings for how contacts are added.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-block"/></svg></span><div class="txt"><div class="ti">Blocked</div><div class="ts">Users you've blocked</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sms"/></svg></span><div class="txt"><div class="ti">Message Settings</div><div class="ts">Notifications and message handling</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-tune"/></svg></span><div class="txt"><div class="ti">App Settings</div><div class="ts">Appearance, translation, and map preferences</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-info"/></svg></span><div class="txt"><div class="ti">Device Info</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div></div></div>
<div><div class="sub">Proposed</div>
<div class="dev d-set"><div class="scr s-set">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Settings</span></div>
<div class="lv">
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-badge"/></svg></span><div class="txt"><div class="ti">Node Settings</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-ant"/></svg></span><div class="txt"><div class="ti">Radio Settings</div><div class="ts">Frequency, power, spreading factor</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-pin"/></svg></span><div class="txt"><div class="ti">Location<span class="badge">new</span></div><div class="ts">GPS, coordinates, and reporting</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sensor"/></svg></span><div class="txt"><div class="ti">Radio stats<span class="keep">unchanged for now</span></div><div class="ts">Noise floor, RSSI, SNR, and airtime</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-shield"/></svg></span><div class="txt"><div class="ti">Privacy Settings</div><div class="ts">Control what information is shared.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-contacts"/></svg></span><div class="txt"><div class="ti">Contacts</div><div class="ts">Settings for how contacts are added.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-block"/></svg></span><div class="txt"><div class="ti">Blocked</div><div class="ts">Users you've blocked</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-sms"/></svg></span><div class="txt"><div class="ti">Message Settings</div><div class="ts">Notifications and message handling</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-tune"/></svg></span><div class="txt"><div class="ti">App Settings</div><div class="ts">Appearance, translation, and map preferences</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-info"/></svg></span><div class="txt"><div class="ti">Device Info</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div></div></div>
</div>
<ul><li>Location sits directly under Radio Settings and becomes the single home for GPS. The duplicate enable toggle in Node Settings goes away.</li><li>Radio stats stays for now by owner decision, to be revisited (#980). It is also reachable from the app-bar icon.</li><li>Category order otherwise unchanged; Observer still appears conditionally and is not drawn here.</li></ul></div>
<div class="card" style="width:688px"><h2><span class="n">6</span>Button and buzzer split across two panes</h2><p>One entry today, shown on button matrix or notify scope together. Boards such as the M5Stack Unit C6L, ThinkNode M9 and Wio Tracker L1 e-ink have a buzzer and no button, so they are not one feature.</p>
<div style="display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px">
<div><div class="sub">Node Settings keeps the button</div>
<div class="dev d-pan"><div class="scr s-pan">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Node Settings</span></div>
<div class="lv p16"><div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-person"/></svg></span><div class="txt"><div class="ti">Node name</div><div class="ts">Strycher</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-radiobtn"/></svg></span><div class="txt"><div class="ti">Button actions</div><div class="ts">Assign what the button does</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div>
</div></div></div>
<div><div class="sub">Message Settings gains the buzzer</div>
<div class="dev d-pan"><div class="scr s-pan">
<div class="ab"><span class="nav"><svg class="ic"><use href="#i-back"/></svg></span><span class="t">Message Settings</span></div>
<div class="lv p16"><div class="mcard">
<div class="tile two"><span class="lead"><svg class="ic"><use href="#i-bell"/></svg></span><div class="txt"><div class="ti">Notifications</div><div class="ts">When this phone alerts you</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile two sel"><span class="lead"><svg class="ic"><use href="#i-vol"/></svg></span><div class="txt"><div class="ti">Buzzer and tones<span class="badge">new</span></div><div class="ts">When this radio beeps, and which tone</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div>
</div></div></div>
</div>
<ul><li>Button actions stay under Node Settings. Buzzer and tones move beside Notifications, which Message Settings already advertises in its subtitle.</li><li>Split apart, each half needs its own capability gate: a buzzer-only radio must show tones and hide button actions.</li><li>Gates: Button actions on caps byte 2 <code>0x02</code>, Buzzer and tones on <code>0x01</code>. Firmware already sets the two independently, and the screen already shows each half from its own bit; what changes is the entry and where it lives.</li></ul></div>
</div>
<h3>Why these choices, so a later change knows what it is breaking</h3>
<div class="why">
<div><h4>One three-way control, not a toggle plus a picker</h4><p>The badge's own screen does exactly this: <code>setGpsMode()</code> at <code>MyMesh.h:458</code> writes both fields, and <code>gpsEnabledForMode</code> exists for the writer that sets both. What is forbidden is a bool-only writer clobbering the mode byte. An earlier draft had two controls and was wrong; #969's original wording pointed that way.</p></div>
<div><h4>One status row, not two</h4><p>Activity and last fix were separate blocks in the first draft. In a dense app that is one job taking two slots, so they are merged into a single <code>ListTile</code> between the selector and the coordinates.</p></div>
<div><h4>Sleep interval is not the reporting interval</h4><p><code>gps_interval</code> is a reporting cadence; <code>gps_ps_interval_s</code> is a power duty cycle (<code>NodePrefs.h:73-78</code>). They live in different cards so the difference is visible, and are never merged.</p></div>
<div><h4>Deferred, tracked separately</h4><p>GPS fix state in the Channels and Contacts headers is #974; it lands in the same shared app-bar widget as epic #613, so it must follow #614 rather than run beside it. Where Radio stats lives is #980.</p></div>
</div>
<div class="why red" style="margin-top:18px">
<div><h4>The save reply must echo what was stored</h4><p>The client renders the device's answer, never its own assumption. Choosing Off does not change the stored mode byte, so a client modelling its own write would show the wrong mode. Clamping has the same shape: the reporting interval is already constrained to 0 through 86400, so the user must see the clamped value, not what they typed. Delivered: the <code>0xC5</code> GPS reply carries the stored values after every write.</p></div>
<div><h4>Power save is hidden where the build cannot drive it</h4><p><code>OFFBAND_GPS_POWER_SAVE</code> is per variant and currently only on the QCC badge. The GPS reply's <code>ps_ok</code> byte says whether this radio can run it; without that, the client would offer a mode that does nothing.</p></div>
</div>
</body></html>

@ -0,0 +1,362 @@
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Badge settings parity mockups</title>
<style>
/* Doc chrome: Offband design-doc family. Inside the frames: Flutter Material 3,
drawn against the real widgets: the Node Settings card in settings_screen.dart
(_identityPane), DeviceUiView(part: buzzer) under the "Buzzer and tones" Scaffold
from message_settings_view.dart, the check-list dialog in
widgets/channel_notify_mode.dart, and the persistent _ErrorBanner.
Self-contained: inline SVG icons, system fonts, no network. */
:root{
--ink:#EFF3E8; --ink2:#BAC4B5; --dim:#8B9A91; --sig:#7BEFA8; --warn:#FFA552; --bad:#FF7A6E;
--sans:'Segoe UI',system-ui,-apple-system,Roboto,sans-serif;
--mono:'Cascadia Mono',Consolas,'SF Mono',Menlo,monospace;
--page:#0a0d0c; --pageInk:#cfd6cc;
--surface:#FDFBFF; --onSurface:#1A1C1E; --onSurfaceVar:#44474F;
--outline:#74777F; --outlineVar:#C4C6D0; --primary:#0061A4; --onPrimary:#FFFFFF;
--secC:#D6E3FF; --onSecC:#001D36; --cardBg:#F3F3FA;
--dialog:#F1EDF5; --scrim:rgba(0,0,0,.40);
--errC:#FFDAD6; --onErrC:#410002; --red:#BA1A1A; --track:#D1E4FF;
}
*{box-sizing:border-box;margin:0;padding:0}
body{background:var(--page);color:var(--pageInk);font-family:var(--sans);padding:24px 16px 56px}
h1{font-size:25px;font-weight:600;color:var(--ink)}
h3{font-size:17px;font-weight:600;color:var(--sig);margin:32px 0 12px}
.lede{font-size:14px;color:var(--dim);margin:8px 0 4px;max-width:1040px;line-height:1.55}
.lede b{color:var(--ink2);font-weight:500}
code{font-family:var(--mono);font-size:11.5px;color:var(--sig)}
.flag{display:inline-block;font-family:var(--mono);font-size:10.5px;font-weight:600;color:#0a0d0c;background:var(--sig);border-radius:3px;padding:2px 7px}
table.par{border-collapse:collapse;font-size:12.5px;max-width:1040px;width:100%;margin-top:4px}
.par th{text-align:left;color:var(--ink);font-weight:600;padding:7px 10px;border-bottom:1px solid #2a332f}
.par td{color:var(--ink2);padding:6px 10px;border-bottom:1px solid #1b2220;vertical-align:top;line-height:1.4}
.par td.ok{color:var(--sig)} .par td.new{color:var(--warn)}
.par code{color:var(--ink2)}
.grid{display:flex;flex-wrap:wrap;gap:30px}
.card{width:324px}
.card h2{font-size:17px;font-weight:600;color:var(--ink)}
.card .n{font-family:var(--mono);font-size:12px;color:var(--sig);margin-right:7px}
.card>p{font-size:13.5px;color:var(--ink2);margin:5px 0 12px;line-height:1.45;min-height:58px}
.card ul{font-size:12.5px;color:var(--dim);margin:12px 0 0 16px;line-height:1.5}
.card li{margin-bottom:5px}
.card ul b{color:var(--ink2);font-weight:500}
.dev{width:324px;height:620px;border:1px solid #2a332f;border-radius:14px;overflow:hidden;background:#000}
.scr{width:390px;height:746px;transform:scale(.8308);transform-origin:0 0;background:var(--surface);color:var(--onSurface);
font-family:'Segoe UI',system-ui,Roboto,sans-serif;position:relative;overflow:hidden}
.ic{width:24px;height:24px;display:block;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
.ic .f{fill:currentColor;stroke:none}
.ab{height:64px;display:flex;align-items:center;padding:0 4px;font-size:21px}
.ab .bk{width:48px;height:48px;display:flex;align-items:center;justify-content:center}
.ab .tt{flex:1;text-align:center;margin-right:48px}
.pad{padding:16px}
.mcard{background:var(--cardBg);border-radius:12px;overflow:hidden}
.sh{font-size:16px;font-weight:500;padding:16px 16px 4px}
.ex{font-size:14px;padding:0 16px 8px;line-height:1.4}
.tile{display:flex;align-items:center;gap:16px;padding:8px 16px;min-height:56px}
.tile .lead{flex:none;color:var(--onSurfaceVar)}
.tile .lead.on{color:var(--primary)}
.tile .txt{flex:1;min-width:0}
.tile .ti{font-size:15.5px;line-height:1.3}
.tile .ts{font-size:13px;color:var(--onSurfaceVar);margin-top:2px;line-height:1.35}
.tile .tr{flex:none;color:var(--onSurfaceVar)}
.tile .tr.pr{color:var(--primary)}
.tile.sel .ti,.tile.sel .ts{color:var(--primary)}
.tile.empty .ti{color:var(--onSurfaceVar)}
.tile.new{background:#E8DEF8}
.dv{height:1px;background:var(--outlineVar)}
.scrim{position:absolute;inset:0;background:var(--scrim)}
.dlg{position:absolute;left:24px;right:24px;top:60px;background:var(--dialog);border-radius:28px;padding:22px 0 10px}
.dlg .dt{font-size:22px;padding:0 24px 4px}
.dlg .ds{font-size:13.5px;color:var(--onSurfaceVar);padding:0 24px 10px;line-height:1.4}
.dlg .sec{font-size:12.5px;color:var(--onSurfaceVar);padding:10px 24px 2px;letter-spacing:.2px}
.dlg .tile{padding:4px 12px 4px 24px;min-height:46px}
.dlg .acts{display:flex;justify-content:flex-end;padding:8px 24px 6px;gap:8px}
.snack{position:absolute;left:12px;right:12px;bottom:16px;background:#322F35;color:#F5EFF7;border-radius:4px;padding:14px 16px;font-size:14px;line-height:1.4;display:flex;gap:12px;align-items:center}
.snack .a{color:#9ECAFF;font-weight:500;flex:none}
.seg{display:flex;margin:4px 16px 8px;border:1px solid var(--outline);border-radius:20px;overflow:hidden;height:40px}
.seg>span{flex:1;display:flex;align-items:center;justify-content:center;gap:6px;font-size:13.5px;font-weight:500;border-left:1px solid var(--outline)}
.seg>span:first-child{border-left:none}
.seg>span.on{background:var(--secC);color:var(--onSecC)}
.seg .ic{width:18px;height:18px}
.lab2{font-size:14px;padding:6px 16px 0;color:var(--onSurfaceVar)}
.fld{margin:8px 16px 0;border:1px solid var(--outline);border-radius:4px;padding:10px 12px;position:relative;min-height:150px}
.fld.focus{border:2px solid var(--primary);padding:9px 11px}
.fld .lab{position:absolute;top:-9px;left:9px;background:var(--surface);padding:0 4px;font-size:12px;color:var(--onSurfaceVar)}
.fld.focus .lab{color:var(--primary)}
.fld .val{font-family:var(--mono);font-size:13.5px;line-height:1.5;word-break:break-all}
.help{display:flex;justify-content:space-between;font-size:12px;color:var(--onSurfaceVar);padding:4px 28px 0}
.row{display:flex;gap:8px;justify-content:flex-end;padding:16px 16px 0}
.btn{height:40px;border-radius:20px;padding:0 22px;font-size:14px;font-weight:500;display:inline-flex;align-items:center;gap:8px}
.btn.fill{background:var(--primary);color:var(--onPrimary)}
.btn.tonal{background:var(--secC);color:var(--onSecC)}
.btn.outl{border:1px solid var(--outline);color:var(--primary)}
.btn.text{color:var(--primary);padding:0 12px}
.btn.text.red{color:var(--red)}
.btn .ic{width:18px;height:18px}
.ban{display:flex;align-items:center;gap:12px;margin:12px;padding:12px;border-radius:8px;background:var(--errC);color:var(--onErrC);font-size:14px;line-height:1.4}
.ban .x{flex:none;width:40px;height:40px;display:flex;align-items:center;justify-content:center}
.lin{height:4px;background:var(--track);margin:14px 16px 6px;border-radius:2px;overflow:hidden}
.lin>div{height:100%;background:var(--primary)}
.prog{font-size:13px;color:var(--onSurfaceVar);padding:0 16px}
.srch{margin:4px 16px 8px;height:48px;border-radius:24px;background:#ECE6F0;display:flex;align-items:center;gap:12px;padding:0 16px;color:var(--onSurfaceVar);font-size:15px}
.big{font-size:32px;font-weight:400;padding:8px 16px 0}
.why{display:flex;flex-wrap:wrap;gap:18px}
.why>div{width:436px;border-left:2px solid var(--sig);padding:2px 0 2px 13px}
.why h4{font-size:14.5px;font-weight:600;color:var(--ink);margin-bottom:4px}
.why p{font-size:12.5px;color:var(--dim);line-height:1.55}
.why code{color:var(--ink2)}
</style>
</head>
<body>
<svg width="0" height="0" style="position:absolute" aria-hidden="true"><defs>
<symbol id="i-back" viewBox="0 0 24 24"><path d="M20 12H5M11 5l-7 7 7 7"/></symbol>
<symbol id="i-rad-on" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle class="f" cx="12" cy="12" r="5"/></symbol>
<symbol id="i-rad-off" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/></symbol>
<symbol id="i-note" viewBox="0 0 24 24"><path d="M9 18V5.5l11-2.2V16"/><circle cx="6.5" cy="18" r="2.5"/><circle cx="17.5" cy="16" r="2.5"/></symbol>
<symbol id="i-mute" viewBox="0 0 24 24"><path d="M4 9.2v5.6h3.6l5 4.2V5L7.6 9.2z"/><path d="M16.5 9.5l5 5M21.5 9.5l-5 5"/></symbol>
<symbol id="i-follow" viewBox="0 0 24 24"><path d="M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"/><path d="M18 3.5v3.4h-3.4M6 20.5v-3.4h3.4"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path class="f" d="M10 8.3v7.4l5.8-3.7z"/></symbol>
<symbol id="i-add" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" stroke-dasharray="3 2.4"/><path d="M12 8v8M8 12h8"/></symbol>
<symbol id="i-chev" viewBox="0 0 24 24"><path d="M9.5 6l6 6-6 6"/></symbol>
<symbol id="i-check" viewBox="0 0 24 24"><path d="M20 6L9 17l-5-5"/></symbol>
<symbol id="i-err" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5"/><circle class="f" cx="12" cy="16.3" r="1.1"/></symbol>
<symbol id="i-close" viewBox="0 0 24 24"><path d="M6 6l12 12M18 6L6 18"/></symbol>
<symbol id="i-person" viewBox="0 0 24 24"><circle cx="12" cy="8.5" r="3.8"/><path d="M4.5 20c.8-3.8 3.8-5.8 7.5-5.8s6.7 2 7.5 5.8"/></symbol>
<symbol id="i-btn" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="4.2"/></symbol>
<symbol id="i-monitor" viewBox="0 0 24 24"><rect x="3" y="4.5" width="18" height="12" rx="1.5"/><path d="M9 20h6M12 16.5V20"/></symbol>
<symbol id="i-batt" viewBox="0 0 24 24"><rect x="7" y="4.5" width="10" height="16.5" rx="1.8"/><path d="M10 2.8h4"/><path class="f" d="M9 9h6v10H9z"/></symbol>
<symbol id="i-globe" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c2.6 2.6 3.8 5.6 3.8 9s-1.2 6.4-3.8 9c-2.6-2.6-3.8-5.6-3.8-9S9.4 5.6 12 3z"/></symbol>
<symbol id="i-search" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="6"/><path d="M15 15l5 5"/></symbol>
<symbol id="i-phone" viewBox="0 0 24 24"><rect x="6.5" y="2.8" width="11" height="18.4" rx="2"/><path d="M10.5 18h3"/></symbol>
<symbol id="i-bolt" viewBox="0 0 24 24"><path d="M13 3L5 13.5h6L10 21l8-10.5h-6z"/></symbol>
</defs></svg>
<h1>Badge settings, reachable from the app (client #970, #971, #975)</h1>
<p class="lede">Material 3 blue seed, light, drawn at 390&times;844 against the real widgets. Wire: <code>0xC5</code> as of meshcore-firmware <code>3e788e2a</code> (#1801, branch <code>epic/1788-client-settings</code>, running on QCC2), read 2026-10-25 in <code>OffbandConfigProtocol.h</code>; badge screens read in <code>BadgeScreens.cpp</code>, <code>BadgeLayout.h</code>, <code>TimeZones.h</code>, <code>BatteryGauge.h</code> at the same commit. Supersedes the #970 slot mockup sent 2026-10-24. Values are examples; <b>the bullets are the behavior to build</b>. Built under #970, #971, #986 and #987. <span class="flag">APPROVED 2026-10-25</span></p>
<h3>The badge's screens against the app</h3>
<table class="par">
<tr><th>Badge screen and row</th><th>Wire (0xC5 sub-code, caps byte 2)</th><th>App before</th><th>App after this</th></tr>
<tr><td>Tones &rsaquo; Sound (All, Self, None)</td><td><code>0x01/0x02</code>, <code>0x01</code></td><td class="ok">Buzzer and tones</td><td>unchanged (frame 2)</td></tr>
<tr><td>Tones &rsaquo; DM, Channel, Room, New contact, Ack, Sent</td><td><code>0x0F/0x10</code> EVTONE, <code>0x10</code></td><td class="new">missing</td><td>six rows + picker (frames 2, 4)</td></tr>
<tr><td>Each picker: Silent, Chime, Kerplop, Tick, Bloop, Drop, Knock, filled slots</td><td>same "picker's rule" on every set</td><td class="new">missing</td><td>one shared picker (frames 4, 7)</td></tr>
<tr><td>Picker plays each tune as you move</td><td><code>0x11</code> TUNE_PLAY, <code>0x10</code></td><td class="new">missing</td><td>play button per row (frames 3, 4, 5)</td></tr>
<tr><td>Tones &rsaquo; Custom: all eight slots, named or "(empty)"</td><td><code>0x09</code> SLOT_GET, <code>0x10</code></td><td class="new">missing</td><td>slot list (frame 3)</td></tr>
<tr><td>Custom &rsaquo; edit a slot (keyboard)</td><td><code>0x12</code> SLOT_READ + <code>0x0A</code> SLOT_SET, <code>0x10</code></td><td class="new">missing</td><td>editor, prefilled (frame 6)</td></tr>
<tr><td>Channel's own tone, with Default</td><td><code>0x0B/0x0C</code> CHTUNE, <code>0x10</code></td><td class="new">codec built, no screen</td><td>"Radio tone" in the channel sheet (frame 7)</td></tr>
<tr><td>Settings &rsaquo; Nav text, Message text</td><td><code>0x13</code> GET, <code>0x14</code> TEXT_SET, <code>0x40</code></td><td class="new">missing</td><td>Screen page (frame 8)</td></tr>
<tr><td>Settings &rsaquo; Screen off (15 s, 30 s, 1 m, 2 m, 5 m)</td><td><code>0x15</code> SCROFF_SET, <code>0x40</code></td><td class="new">missing</td><td>Screen page (frame 8)</td></tr>
<tr><td>Settings &rsaquo; Time zone (40 zones plus "not set", which shows ages)</td><td><code>0x16</code> TZ_SET, <code>0x40</code></td><td class="new">missing</td><td>zone list (frame 9)</td></tr>
<tr><td>Settings &rsaquo; Battery: 100% point, Set 100% here, Back to auto</td><td><code>0x17</code> BATT_SET, <code>0x40</code></td><td class="new">missing</td><td>Battery page (frames 10, 11)</td></tr>
<tr><td>Settings &rsaquo; GPS</td><td><code>0x0D/0x0E</code>, <code>0x20</code></td><td class="ok">Location (#977)</td><td>unchanged</td></tr>
<tr><td>Settings &rsaquo; Hibernate, Device pages</td><td>not settings (AmberForge 1350): an action and a navigation</td><td>n/a</td><td>n/a</td></tr>
</table>
<p class="lede">One caps change to carry into the code already written: <code>0x10</code> is now <b>TUNES</b> (slots, channel tone, event tones, preview), not channel tone alone, and the slot sub-codes moved from the buzzer bit to it. A radio with a buzzer but no tune engine advertises <code>0x01</code> without <code>0x10</code> and keeps today's scope-only screen.</p>
<h3>Buzzer and tones</h3><div class="grid">
<div class="card"><h2><span class="n">1</span>Node Settings gains Screen and Battery</h2><p>The badge's own hardware settings sit with Button actions, gated on <code>0x40</code>. A radio without it shows today's card.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Node Settings</span></div>
<div class="pad"><div class="mcard">
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-person"/></svg></span><div class="txt"><div class="ti">Node name</div><div class="ts">QCC2</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-btn"/></svg></span><div class="txt"><div class="ti">Button actions</div><div class="ts">Assign what the button does</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-monitor"/></svg></span><div class="txt"><div class="ti">Screen</div><div class="ts">Text size, screen off, time zone</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">Battery</div><div class="ts">100% at 4150 mV, learned</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="dv"></div>
<div style="padding:8px 16px 12px"><div style="font-size:13px;color:var(--onSurfaceVar)">Public key</div><div style="font-family:var(--mono);font-size:12px;margin-top:2px">a1f3 07c2 9e44 &hellip; 5b10</div></div>
</div></div>
</div></div>
<ul><li>Both rows appear only on a radio advertising caps byte 2 <code>0x40</code>. Today that means firmware built with the Offband screen set; a display fitted to a pyramid badge with that firmware gets them.</li><li>Battery's subtitle is the <code>SCREEN_GET</code> reply: the 100% point and where it came from, in the badge's words (default, learned, set).</li><li>Placement: owner decision 1.</li></ul></div>
<div class="card"><h2><span class="n">2</span>The scope, then the six tones</h2><p>The badge's Tones screen, in its order: Sound first, because nothing below can sound while it says None.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
<div class="sh">Device notification scope</div>
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">All</div><div class="ts">Beep for any received message</div></div></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Self</div><div class="ts">Beep only for direct messages and @[mentions]</div></div></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">None</div><div class="ts">Never beep</div></div></div>
<div class="sh">Tones</div>
<div class="ex">What this radio plays for each event.</div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">DM</div><div class="ts">Chime (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Channel</div><div class="ts">Kerplop (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Room</div><div class="ts">Mario</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">New contact</div><div class="ts">Bloop</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Ack</div><div class="ts">Silent</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Sent</div><div class="ts">Silent (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div>
<ul><li>Labels are the badge's own (<code>kToneEventRows</code>): DM, Channel, Room, New contact, Ack, Sent. <b>DM is one tone for every direct message</b>; there is no per-contact choice (#983 withdrawn).</li><li>Each subtitle is the <code>effective</code> byte from <code>EVTONE_GET</code>. When <code>stored</code> is 0xFF it adds "(radio default)", so a choice and a default never look alike.</li><li>The tones section exists only with caps <code>0x10</code>. With <code>0x01</code> alone the screen is today's scope rows.</li></ul></div>
<div class="card"><h2><span class="n">3</span>Custom tunes, every slot</h2><p>Scrolled down. All eight slots are rows, as on the badge: an empty slot is where you go to fill one.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Sent</div><div class="ts">Silent (radio default)</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
<div class="sh">Custom tunes</div>
<div class="ex">Eight tunes stored on this radio, in RTTTL. A saved tune can be picked for any event or channel.</div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">1 Mario</div><div class="ts">142 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">2 Zelda</div><div class="ts">96 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">3 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">4 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">5 Nokia</div><div class="ts">58 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">6 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">7 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
<div class="tile new empty"><span class="lead"><svg class="ic"><use href="#i-add"/></svg></span><div class="txt"><div class="ti">8 (empty)</div><div class="ts">Tap to add a tune</div></div></div>
</div></div>
<ul><li>"1 Mario" / "3 (empty)" is the badge's own label shape. Names and lengths are <code>SLOT_GET</code> replies, one per slot, read when the screen opens.</li><li>The play button sends <code>TUNE_PLAY</code> with the slot's id (8 + slot). Empty slots have none: there is nothing to hear.</li><li>Tap a row to edit it (frame 6).</li></ul></div>
<div class="card"><h2><span class="n">4</span>Pick a tone, hear it first</h2><p>One picker for all six events, with the badge's list. Play auditions on the radio; tapping the name chooses it.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
<div class="scrim"></div>
<div class="dlg">
<div class="dt">DM tone</div>
<div class="ds">Plays for every direct message.</div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Silent</div></div></div>
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Chime</div><div class="ts">Now playing for DMs</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Kerplop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Tick</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Bloop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Drop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Knock</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="sec">Your tunes</div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Mario</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Zelda</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Nokia</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="acts"><span class="btn text">Cancel</span></div>
</div>
</div></div>
<ul><li>The list is exactly what firmware accepts: the named built-ins (ids 0 to 6) and filled slots only. Empty slots are not offered, so a set is never refused for that.</li><li>Tapping a name sends <code>EVTONE_SET</code>; the dialog closes and the row changes only on the radio's reply, which carries stored and effective.</li><li><b>No Default row.</b> Firmware refuses 0xFF on an event, as the badge's own picker offers none (owner decision 3).</li><li>"Now playing" marks the effective tune, as the badge marks it "now".</li></ul></div>
<div class="card"><h2><span class="n">5</span>Why a preview made no sound</h2><p>The radio says why it refused. The app says it in words, as the badge does with "Buzzer: OFF".</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Buzzer and tones</span></div>
<div class="sh">Device notification scope</div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">All</div><div class="ts">Beep for any received message</div></div></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Self</div><div class="ts">Beep only for direct messages and @[mentions]</div></div></div>
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">None</div><div class="ts">Never beep</div></div></div>
<div class="sh">Custom tunes</div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">1 Mario</div><div class="ts">142 characters</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="snack"><span style="flex:1">Sound is off on this radio. Set the scope to All or Self to hear it.</span><span class="a">OK</span></div>
</div></div>
<ul><li><code>TUNE_PLAY</code> result 2 (sound off): this message, which stays until OK.</li><li>Result 1 (something more important is sounding): "The radio is playing a notification. Try again in a moment."</li><li>Result 0: nothing shown. The sound is the confirmation.</li></ul></div>
<div class="card"><h2><span class="n">6</span>Edit a slot, starting from what is there</h2><p>The editor reads the stored tune back first, so a filled slot opens with its text and can be changed, not only replaced.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Slot 1</span></div>
<div style="height:10px"></div>
<div class="fld focus"><span class="lab">RTTTL</span><div class="val">Mario:d=4,o=5,b=100:16e6,16e6,32p,8e6,16c6,8e6,8g6,8p,8g,8p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b</div></div>
<div class="help"><span>Plays as "Mario"</span><span>142 / 240</span></div>
<div class="row"><span class="btn text red">Clear slot</span><span class="btn outl"><svg class="ic"><use href="#i-play"/></svg>Play saved</span><span class="btn fill">Save</span></div>
<div class="lin" style="margin-top:22px"><div style="width:100%"></div></div>
<div class="prog">Read from the radio: 142 of 142 characters</div>
</div></div>
<ul><li>Opening sends <code>SLOT_READ</code> at offset 0, then again at offset + bytes while <code>more</code> is 1. The field is read-only and shows this bar until the read completes.</li><li>Typing is checked live with firmware's own <code>rtttlProblem()</code> and its words ("b= must be 1 or more"); Save stays disabled while there is a problem. Saving is the chunked <code>SLOT_SET</code>, then a re-read.</li><li><b>Play saved</b> plays what is on the radio, not unsaved typing: there is no command to play text that has not been saved. It is disabled while the text differs from the saved tune.</li><li>Clear sends the empty commit, after a confirm.</li></ul></div>
<div class="card"><h2><span class="n">7</span>A channel's tone names its Default</h2><p>The channel sheet's "Radio tone" picker (#971), now able to say what Default plays, the way the badge shows "Default Kerplop".</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="tt" style="margin:0 0 0 12px;text-align:left">Channels</span></div>
<div class="scrim"></div>
<div class="dlg">
<div class="dt">Radio tone</div>
<div class="ds">#okimesh</div>
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-follow"/></svg></span><div class="txt"><div class="ti">Default</div><div class="ts">Kerplop, the radio's channel tone</div></div><span class="tr pr"><svg class="ic"><use href="#i-check"/></svg></span></div>
<div class="dv" style="margin:4px 0"></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-mute"/></svg></span><div class="txt"><div class="ti">Silent</div></div></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Chime</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Kerplop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Tick</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Bloop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Drop</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Knock</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="sec">Your tunes</div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Mario</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-note"/></svg></span><div class="txt"><div class="ti">Zelda</div></div><span class="tr pr"><svg class="ic"><use href="#i-play"/></svg></span></div>
</div>
</div></div>
<ul><li>Same picker as frame 4 plus the Default row a conversation needs. Default writes stored 0; it is the only way to un-set a channel's tone.</li><li>Default's subtitle is the Channel event's <code>effective</code> tune from <code>EVTONE_GET</code> ev 1, so it names a real tune rather than "follows the radio".</li><li>Empty slots are hidden here too: firmware now refuses an empty slot for a channel (<code>3e788e2a</code>), which settles the first #971 question.</li><li>The row also sits in the channel chat screen's menu, from the same widget.</li></ul></div>
</div>
<h3>Screen and Battery</h3><div class="grid">
<div class="card"><h2><span class="n">8</span>Screen</h2><p>The badge's Nav text, Message text and Screen off rows, with the same choices and no others.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Screen</span></div>
<div class="sh">Text size</div>
<div class="lab2">Menus and lists</div>
<div class="seg"><span class="on"><svg class="ic"><use href="#i-check"/></svg>Large</span><span>Medium</span><span>Small</span></div>
<div class="lab2">Messages</div>
<div class="seg"><span>Large</span><span class="on"><svg class="ic"><use href="#i-check"/></svg>Medium</span><span>Small</span></div>
<div class="sh">Screen off</div>
<div class="ex">How long the screen stays on after the last key press.</div>
<div class="seg"><span>15 s</span><span>30 s</span><span class="on"><svg class="ic"><use href="#i-check"/></svg>1 m</span><span>2 m</span><span>5 m</span></div>
<div class="sh">Time zone</div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-globe"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">UTC-4 now. Message times show as clock times.</div></div><span class="tr"><svg class="ic"><use href="#i-chev"/></svg></span></div>
</div></div>
<ul><li>Every control is the <code>SCREEN_GET</code> reply; each change sends its SET and the controls redraw from the 14-byte re-read reply, never from the tap.</li><li>"Menus and lists" is the badge's Nav text, "Messages" its Message text (owner decision 4).</li><li>Screen off offers exactly the five steps firmware accepts. When <code>scr_stored</code> is 0 (compiled default), no segment is selected and the line reads "Board default: 1 m" from <code>scr_secs</code>; picking a step replaces it and there is no way back to 0, on the badge or here.</li></ul></div>
<div class="card"><h2><span class="n">9</span>Time zone</h2><p>The badge's 40 zones, its "not set", and a suggestion: the badge suggests from GPS, the app from the phone.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Time zone</span></div>
<div class="srch"><svg class="ic"><use href="#i-search"/></svg>Search zones</div>
<div class="tile new"><span class="lead"><svg class="ic"><use href="#i-phone"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">Matches this phone</div></div><span class="tr">UTC-4</span></div>
<div class="dv"></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">not set</div><div class="ts">Messages show their age</div></div></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">UTC</div></div><span class="tr">UTC+0</span></div>
<div class="tile sel"><span class="lead on"><svg class="ic"><use href="#i-rad-on"/></svg></span><div class="txt"><div class="ti">Eastern</div><div class="ts">Current</div></div><span class="tr">UTC-4</span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Central</div></div><span class="tr">UTC-5</span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Mountain</div></div><span class="tr">UTC-6</span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Arizona</div></div><span class="tr">UTC-7</span></div>
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-rad-off"/></svg></span><div class="txt"><div class="ti">Pacific</div></div><span class="tr">UTC-7</span></div>
</div></div>
<ul><li>The list is a copy of <code>TimeZones.h</code> <code>kZones</code>, in its order. AmberForge confirms it is append-only, so the index is stable; an index the app does not know is shown by number.</li><li>Offsets are computed with the zone's own daylight rule (US, EU, or none), as the badge's picker shows them.</li><li>"Matches this phone" picks the named zone whose rule and offset equal the phone's, else the fixed UTC offset, else nothing. It is a suggestion; tapping it sends <code>TZ_SET</code> like any row.</li><li>"not set" is storable (index 0), as on the badge.</li></ul></div>
<div class="card"><h2><span class="n">10</span>Battery</h2><p>The badge's Battery screen: where 100% is, how it got there, and its two actions.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Battery</span></div>
<div class="big">96%</div>
<div class="ex" style="padding-top:2px">Reading 4120 mV</div>
<div class="pad" style="padding-top:8px"><div class="mcard">
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">100% at 4150 mV</div><div class="ts">Learned after a full charge</div></div></div>
</div></div>
<div class="ex">The radio learns where full is after a complete charge. Set it by hand only if the bar never reaches 100% when charged.</div>
<div class="row" style="justify-content:flex-start"><span class="btn tonal"><svg class="ic"><use href="#i-bolt"/></svg>Set 100% here</span><span class="btn text">Back to auto</span></div>
</div></div>
<ul><li>The 100% point and its source (default, learned, set by hand) are the <code>batt_stored</code>, <code>batt_full</code> and <code>batt_pinned</code> bytes; the reading and percent are the battery report the app already receives.</li><li><b>Set 100% here</b> sends <code>BATT_SET 1</code>: the radio pins its own current reading, as the badge does. A confirm says "Only do this with the radio fully charged."</li><li><b>Back to auto</b> sends <code>BATT_SET 0</code>, shown only when something is learned or pinned.</li></ul></div>
<div class="card"><h2><span class="n">11</span>Refused, with the radio's reason</h2><p>The radio refuses a reading that is not a plausible full cell, and says which way it is wrong.</p>
<div class="dev"><div class="scr">
<div class="ab"><span class="bk"><svg class="ic"><use href="#i-back"/></svg></span><span class="tt">Battery</span></div>
<div class="ban"><svg class="ic"><use href="#i-err"/></svg><span style="flex:1">Not charged yet. Charge the radio fully, then set 100% again. Nothing was changed.</span><span class="x"><svg class="ic"><use href="#i-close"/></svg></span></div>
<div class="big">71%</div>
<div class="ex" style="padding-top:2px">Reading 3890 mV</div>
<div class="pad" style="padding-top:8px"><div class="mcard">
<div class="tile"><span class="lead"><svg class="ic"><use href="#i-batt"/></svg></span><div class="txt"><div class="ti">100% at 4200 mV</div><div class="ts">Default for this board</div></div></div>
</div></div>
<div class="row" style="justify-content:flex-start"><span class="btn tonal"><svg class="ic"><use href="#i-bolt"/></svg>Set 100% here</span></div>
</div></div>
<ul><li><code>ERR_BATT_NOT_CHARGED</code> (9): this message. <code>ERR_BATT_TOO_HIGH</code> (8): "The reading is higher than a full cell, so it was not used."</li><li>The existing persistent <code>_ErrorBanner</code>: it stays until dismissed.</li><li>Back to auto is absent: nothing is learned or pinned, matching the badge, which hides it then.</li></ul></div>
</div>
<h3>Owner decisions, 2026-10-25</h3>
<div class="why">
<div><h4>1. Screen and Battery under Node Settings</h4><p>They are this radio's own hardware settings, beside Button actions, and they appear only on radios that have them. The rejected alternative was a new top-level "Device display" category, which would be empty on most radios.</p></div>
<div><h4>2. Play is a separate button</h4><p>The badge auditions as you move because moving and choosing are separate keys. On a phone, a tap is the choice, so play is its own button and the name chooses. A preview never changes the setting.</p></div>
<div><h4>3. No way back to "radio default"</h4><p>Firmware refuses 0xFF on an event because the badge's picker has no Default row for events, and Screen off accepts only its five steps. The app matches that. A way back would be a firmware change.</p></div>
<div><h4>4. "Menus and lists" and "Messages"</h4><p>The badge says "Nav text" and "Message text", which fit 21 columns. The app has room to say what each governs.</p></div>
</div>
<h3>Why these choices</h3>
<div class="why">
<div><h4>The radio is the record, everywhere</h4><p>Every reply on this list re-reads after the write: EVTONE and CHTUNE carry stored and effective, SCREEN carries the whole set. The app draws only from replies, stores none of it, and so has nothing per radio to isolate (#853) or to drift.</p></div>
<div><h4>The app offers exactly what the badge offers</h4><p>Firmware refuses anything its own screens would not offer. Building each list from the same rule (named built-ins plus filled slots, five Screen off steps, three sizes, the zone table) means the app never offers a choice the radio will reject.</p></div>
</div>
</body></html>

@ -0,0 +1,38 @@
# Population classifier contract (F1, #862)
What the client's `DevicePopulation` classifier promises, what it consumes, and the one seam where the firmware's durable marker (decision D1) replaces the interim heuristic. This is the client's half of the D1 coordination; the firmware input is filed on [#857](https://github.com/OffbandMesh/meshcore-client/issues/857).
## Promise
Every capability decision in the client routes through `classifyDevicePopulation` (`lib/connector/device_population.dart`). No code reads `firmwareVerCode` comparisons at or above 14, or device-info frame offsets 82+, outside it — the population invariant is documented at the gate block in `meshcore_protocol.dart` and locked by the stock-ver-22 regression test.
| Population | Fork frames (0xC0–0xC6) | CLI frame 66 | How recognized today |
|---|---|---|---|
| `stockLegacy` (and every conflict/unknown) | no | no | fail-closed default |
| `stockModern` | no | yes | 82-byte device-info, ver ≥ 14, no contradicting version string |
| `offband` | per cap bits | no (flips at this seam post-absorb) | >82-byte device-info **corroborated** by the dual version string |
## Interim signals (in precedence order)
1. Device-info frame length: 82 = stock layout; 83/85 = fork layout (caps byte offsets 82/84).
2. Version string shape (`classifyVersionString`): bare semver = stock; semver-dash-remainder = Offband dual (incl. `X-X` release images, firmware#691, and git-describe bench tails); anything else corroborates nothing.
3. Ver code: only meaningful below 14 (pre-split floors ≥8, ≥13) or inside caps-anchored fork gates (15/17/22, config 14).
Conflicts (fork shape + stock/absent string, stock shape + dual string, ver > 32) classify `stockLegacy` with `conflict: true` and the evidence logged.
## The D1 seam
When firmware ships its durable population marker, **`classifyDevicePopulation` is the only place that learns to read it**; `Classification` and every caller are unchanged. The same change flips `allowsCliFrame` for post-absorb Offband devices. What the client needs from the marker, stated as requirements rather than a mechanism:
- carried in the device-info reply (no extra round trip),
- distinguishes fork from stock regardless of future stock frame growth (the 82-byte assumption is one upstream append away from dying),
- readable before any capability decision is taken,
- stable across the VER_CODE renumbering, whatever D1 picks.
## Known limitations (all fail closed)
- A fork device whose version string cannot be read loses fork features for that connection (uncorroborated shape).
- A hypothetical stock pre-release string (`vX.Y.Z-rc1`) reads as dual → inverse conflict → `stockLegacy`.
- A future stock device-info longer than 82 bytes will conflict with its stock version string → `stockLegacy` until the D1 marker exists. This is the designed behavior, not a bug: it is exactly the case the marker solves.
Agent: GentleGlacier (session f0c92a36)

@ -0,0 +1,132 @@
# Investigation: client↔firmware contracts for upstream 1.17.1/1.18.0 interop
Status: investigation, not a plan. Every claim is from a read of the named source this session (2026-10-17). Firmware tags read in the firmware repo's tag space; client read at `C:\Dev\meshcore-open` HEAD.
---
## A. The three management surfaces — as-is contracts
### A1. Upstream 1.18.0 CLI (new)
**Transports.**
- *Local:* `CMD_RUN_CLI_COMMAND` (66) → `RESP_CODE_CLI_REPLY` (29). Request `[66][ascii command]` (len ≥ 3); reply `[29][ascii reply]`, reply ≤ 165 bytes (`reply_buf[166]`). No request id — correlation only via the optional prefix (below). `[verified: MyMesh.cpp handleCmdFrame at companion-v1.18.0]`
- *Remote:* `TXT_TYPE_CLI_COMMAND` (3) inside `CMD_SEND_TXT_MSG` / `PAYLOAD_TYPE_TXT_MSG`. No ACK. Receiving **companion** executes only if contact flags bit **0x10** (`isRemoteCLIAllowed`) is set, else the text queues to the app as a message; reply returns as a normal `TXT_TYPE_CLI_DATA` message, +600 ms (`CLI_REPLY_DELAY_MILLIS`), timestamp uniquified. Receiving **repeater/room server**: type 3 treated exactly like CLI_DATA (room server: admin only). `[verified: BaseChatMesh.cpp, MyMesh.cpp (companion), simple_room_server/MyMesh.cpp at the tag]`
- *Serial:* same `handleCommand` behind the rescue CLI; RP2040 WiFi builds also serve it on USB serial.
**Correlation.** Optional 3-char prefix: a command whose `[2] == '|'` (len > 4) has its first 3 chars reflected at the reply start. Upstream-origin: present in 1.17.0 server roles, extended to the companion in 1.18.0 `[verified: grep at companion-v1.17.0 + 1.18.0]`. **The client already implements exactly this** (`RepeaterCommandService._nextPrefixToken` → `XX|`; reply match on `[2]=='|'`) with computed timeouts, 5 retries, sole-pending fallback for short commands, and 2-minute late-reply attribution `[verified: repeater_command_service.dart, whole file]`.
**Vocabulary.** (a) `CommonRadioPrefs` — strings preserved verbatim from the old CommonCLI: `get/set radio`, `freq`, `af`, `dutycycle`, `int.thresh`, `cad`, `radio.rxgain`, `tx`, `rxdelay`, `agc.reset.interval`, `path.hash.mode`, `multi.acks`, `txdelay`, `direct.txdelay` `[verified: CommonRadioPrefs.cpp whole file]`. (b) Companion built-ins: `set/get name` (rejects `[ ] \ : , ? *`), `set pin`, `reboot`, `poweroff`/`shutdown`, `board`, `ver`, `get/set tz.offset`, `power`, `gps diag`. (c) `wifi.*` under `ENABLE_WIFI_INTERFACE`: `set/get wifi.ssid`, `set wifi.pwd`, **`get wifi.pwd` → cleartext password**, `set wifi.clear`, `set/get wifi.enabled`, `get wifi.status` (`> connected|disconnected`), `get wifi.ip`; ssid/pwd/enabled apply at reboot. (d) Variant hook `board.handleCommand` (FEM `get/set radio.fem.*` on FEM boards only).
**Error semantics.** Text only: `"Unknown command"` appended after the (reflected) prefix; `"Error, ..."`/`"ERROR: ..."` strings per command. **No structured error codes, no ERR frame** — a client cannot distinguish failure classes without string matching.
**Gating.** No capability advert. Local CLI exists on every v14+ stock companion; `wifi.*` only on `ENABLE_WIFI_INTERFACE` builds — a client discovers absence only by the `Unknown command` reply.
### A2. Offband 0xC0 config (`CMD_OFFBAND_CONFIG`) — your way, in flight
**Frame contract** (client codec mirrors byte-for-byte): `[0xC0][op][ascii payload NUL]`. Ops `SET 0x00`, `GET 0x01`, `VIEW 0x02`, `BROKERS 0x03`. Responses `[0xC0][sub]`: `ACK 0x00`, `ERR 0x01` (text starts `ERROR`), `VALUE 0x02` (`key = value`), brokers stream `0x10/0x11/0x12`, view stream `0x20/0x21/0x22` `[verified: observer_config_client.dart:89-130]`.
**Keys/semantics.** `wifi.ssid` / `wifi.pwd` / `wifi.enabled` (+ `mqtt.*`, display) — **same key names as upstream's CLI** but: `wifi.pwd` is **write-only** (GET errors), storage is NVS (`"wifi"` ns), gating is `ver_code ≥ 14 AND cap bit` — observer `0x01`; companion `0x08` being delivered right now by [firmware#1448](https://github.com/OffbandMesh/meshcore-firmware/issues/1448) (BUILD in flight, BrownWaterfall) with a **planned VER_CODE bump 22→23**. The op/key/error contract for companions was settled on [firmware#365](https://github.com/OffbandMesh/meshcore-firmware/issues/365) (comments of 2026-07-24, per client#375's banner). TCP `:5000` exposure: standing owner-accepted risk, nothing required of the client.
**Client stack on this contract (shipped + in flight):** pure codec (`observer_config_client.dart`), device-agnostic `ConfigSourceService`, `ConfigProfile` with typed `wifi` section, write planner (orders `wifi.enabled` last, `wifi.pwd` is a danger key), `wifi.status` state model (`boot/cliRescue/awaitingSetup/staConnecting/staConnected/staFailed`), settings UI with write-only pwd field. Feature umbrella: [client#837](https://github.com/OffbandMesh/meshcore-client/issues/837) (companion + observer/companion upgrade + **saved networks** — the genuinely new work), children-to-be #375, #138, #795.
### A3. Observer `_sys` channel CLI
Channel-message CLI on the `_sys` system channel over the normal app link — the observer build's **only** management surface (no serial console). Allowlisted verbs `get/set/mqtt/wifi/display`; **rejects** `reboot`/`ota.`/`fs.`/`format`/shell metacharacters. Grammar: `<ns> <verb>` actions + `get|set <ns>.<field>`. Secrets write-only. `get wifi.status` kept as a backward-compat alias of `wifi status` `[verified: docs/observer-cli-commands.md at firmware-base]`. Behind it sits the fork's **+988-line CommonCLI delta** with ~30 fork-only command families (caplog, display, led, safety, telemetry, fem on/off, ota, cmd_poll, resetreason, hangtest…) `[verified: diff + string-set diff companion-v1.17.0 → firmware-base]`.
---
## B. Overlap and conflict matrix
### B1. Same command string, different contract
| Command | Upstream 1.18 CLI | Offband 0xC0 | Offband `_sys` |
|---|---|---|---|
| `get wifi.ssid` | returns SSID | VALUE reply, same meaning | returns SSID |
| `get wifi.pwd` | **cleartext password** | **ERR (write-only)** | **blocked (write-only)** |
| `set wifi.pwd …` | OK, reboot to apply | ACK, reboot/STA-retry | OK, reboot/STA-retry |
| wifi enable/disable | `set wifi.enabled 1/0` | `set wifi.enabled …` key | `wifi enable` / `wifi disable` verb |
| `get wifi.status` | `> connected/disconnected` | n/a (status via model) | alias of `wifi status` (rich STA state) |
| `reboot`/`poweroff` | **supported** | n/a | **deliberately rejected** |
| radio cmds (`set tx`, `get radio`, …) | CommonRadioPrefs | n/a | CommonCLI (same strings) + fork families |
The `get wifi.pwd` row is the sharpest: if the absorb lands upstream's companion `handleCommand` unmodified on Offband builds, the same string that today safely errors becomes a cleartext credential readback — including over the remote type-3 path (contact-permission-gated) and the unauthenticated TCP transport. That is a **firmware absorb decision**, not a client one; the client spec must assume either answer is possible per population.
### B2. Mechanism-level divergence
- **Gating:** upstream = implicit (build flags, probe-by-command); Offband = explicit cap bits (`0x01`/`0x08`, per-unit, never model/version). Client currently gates everything the Offband way.
- **Storage:** upstream JSON prefs (`wifi` object, new in 1.18) vs Offband NVS `"wifi"` ns — a device-side migration problem in the absorb; client-invisible except through behavior drift.
- **VER_CODE:** upstream spent 14 on "CLI exists"; the fork spent 14 on "0xC0 exists" and is heading to 23 (#1448) while upstream is at 14 and climbing. Every fork bump deepens the collision. The number is unusable cross-population without a discriminator.
- **Defaults:** upstream `wifi_enabled = 1` in code at the tag (a commit subject says 0 — code wins) with empty-SSID guard; fork policy flag also defaults enabled. Incidentally aligned.
### B3. Population behavior matrix (client's view)
| Function | stock 1.17.x | stock 1.18.0 | Offband today (ver 22) | Offband post-absorb |
|---|---|---|---|---|
| device-info caps bytes | absent (82 B) | absent (82 B) | present (83/85 B) | present (decision: layout survives) |
| frame 66 local CLI | — (unknown cmd) | **yes** | — | yes (inherits) |
| type 3 remote | servers: log+ignore · companions: **silent drop** | yes (0x10-gated) | silent drop | yes (0x10-gated) |
| 0xC0 config | — | — | observer `0x01`; companion `0x08` landing (#1448) | **decision** |
| `_sys` CLI | — | — | observers | **decision** |
| wifi via CLI `wifi.*` | — | ENABLE_WIFI_INTERFACE builds | — | **decision** (readback!) |
---
## C. Per-feature client contract specs, gaps, counted sizing
Sizing counts real tasks at your 3–5-pt standard, from the reuse verified above. These moved **down** from my rev-3 guess for CLI (console + correlation machinery already exist) and the hidden cost surfaced in F4 (reconciliation).
### F1 — population discriminator & gate rework (prerequisite for everything)
**Spec:** one `isOffbandFirmware`/population classifier consuming: device-info length (82 vs 83/85), ver code, caps bytes, firmware-version string (`<ob>-<mc>` dual format; release images show `X-X`, firmware#691). All capability gates (6 ver-code sites, caps parsing, GPS presence gate) and all new CLI gating route through it. Interim signal = frame shape; swap seam for the firmware's durable marker when the VER_CODE ruling lands (decision D1).
**Gaps:** none blocking the interim; durable signal blocked on D1.
**Tasks (6, ~20–26 pts):** classifier + population fixtures (4); caps-parse rerouting (3); ver-gate migration + channel-data 167→165 bound (4); version-string parser w/ #691 handling (3); durable-marker seam + contract doc (3); conformance sweep across 4 populations (4).
### F2 — companion CLI, local (frame 66)
**Spec:** codec `[66][prefix?][cmd]` / `[29][prefix?][reply]`; prefix `XX|` (shared with repeater service); reply ≤165; errors are strings (`Unknown command`, `Error…`) — client classifies by prefix-stripped text, nothing structured to parse; no pagination (long output truncates device-side); vocabulary per A1 (radio set, built-ins, wifi.* when built in, variant FEM). Offered **only** when F1 says stock ≥14 (today) — Offband devices gain it at absorb.
**Gaps (upstream contract):** no structured errors; no ERR frame distinct from text; no way to enumerate supported commands (probe-only); >165 replies silently cut.
**Tasks (6, ~21–27 pts):** codec + tests (3); local command service (frame round-trip, no mesh retries; extract shared prefix/correlation helper out of `RepeaterCommandService`) (4); console screen adapted from `repeater_cli_screen` pattern for the local device (5); gating + entry point via F1 (3); name-validation mirroring + command-reference strings/l10n (3); population tests incl. Offband-must-not-offer (3).
### F3 — remote CLI (type 3 + contact permission)
**Spec:** send = `CMD_SEND_TXT_MSG` with `txt_type 3` (client's builder already parameterizes type for CLI sends); permission = contact flags bit 0x10, **written with the existing add/update-contact frame — the flags byte is already in the client's builder** `[verified: meshcore_protocol.dart:1277]`; replies arrive as CLI_DATA with the reflected prefix → `RepeaterCommandService` machinery applies nearly wholesale (timeouts per #529's computed windows + the now-source-verified 600 ms device hold). Population rule: type 3 only to peers F1 places at 1.18+/post-absorb; type 1 remains the server default everywhere.
**Gaps (upstream contract):** a companion **without** 0x10 gives the sender *no* reply and no error — the command just lands as a message on the target's app; indistinguishable from packet loss on the sending side. The spec must define the client UX for that (timeout + explanatory state, never retry-spam). Room-server: type 3 is admin-gated like CLI_DATA — same existing behavior.
**Tasks (6, ~22–28 pts):** flags-0x10 model/getter/copyWith + contact-UI toggle + write-path test (4); population-aware type selection in the send path (4); service generalization companion-vs-repeater targets (4); inbound type-3 accept + render (today warn-dropped) + storage flag (4); no-permission UX per gap above (3); cross-population behavior tests (4).
### F4 — WiFi: the reconciliation (the real $5M corner)
This is not "add a WiFi screen". Three mechanisms now exist for the same keys; your architecture (#365→#1448, #837) is mid-flight on one of them; upstream shipped another; `_sys` carries a third grammar. **Client work splits into (a) what proceeds regardless and (b) what is blocked on firmware decisions D2–D4.**
**(a) Proceeds regardless (~5 tasks, 17–22 pts):** gating split per #837 — WiFi on `0x01||0x08`, brokers/display on `0x01` (3); #375 body correction + re-parent under #837 (part of same task); saved-networks local store (new `lib/storage/` module; PSK-at-rest decision D6 shapes it) (4+4: store + CRUD UI); apply-to-device over the existing 0xC0 write planner (4); status-readout tolerance for both vocabularies (fork rich states vs upstream connected/disconnected) (3).
**(b) Blocked on decisions:** any use of upstream `wifi.*` CLI for stock-1.18 devices (D4) ≈ +2 tasks (7–9 pts: CLI-backed adapter behind the same UI, reboot-to-apply UX); any change to the 0xC0 path if the absorb alters it (D2); `get wifi.pwd` handling if readback survives anywhere (mask, never log, never store from device) — spec'd now, applied per D2's outcome.
### Sizing rollup (client side, counted)
| Feature | Tasks | Points | Confidence |
|---|---|---|---|
| F1 discriminator | 6 | 20–26 | high — surfaces enumerated |
| F2 local CLI | 6 | 21–27 | high — reuse verified |
| F3 remote CLI | 6 | 22–28 | high — service reuse verified |
| F4 WiFi (a) unblocked | 5 | 17–22 | medium — PSK-at-rest open |
| F4 WiFi (b) decision-gated | 2–4 | 7–16 | low until D2/D4 |
| **Total** | **25–27** | **87–119** | |
Per-feature verification (bench against stock 1.17.1, stock 1.18.0, Offband current) is counted inside the test tasks above; device time is yours to schedule. **Not counted:** all firmware-side reconciliation (the CommonCLI 988-line re-merge, `_sys` fate, 0xC0-vs-CLI convergence, prefs-storage migration, VER_CODE strategy) — firmware's budget, not the client's, listed here only as dependencies.
---
## D. In-flight register (what the merge must not run over)
**Firmware:** #1448 (0xC0 on companion, cap 0x08, ver 22→23 — BUILD in flight); #365 (contract parent, `board:in-progress`); #325 (serial+WiFi coexistence, live credential-change); #295 chain (#300 shared config backend **done**, #301–#307 open — GUI config #305 names client screens); CLI-surface issues the upstream CLI refactor collides with: #891/#892 (CLI surface integrity + verification toolchain), #657 (led/display dispatch gaps on 1.17.0 base), #871 (serial writers vs framed protocol), #873 (ver/version identity), #893 (wifi CLI 20–25 s round-trip), #359 (unbounded sprintf in reply formatters — upstream's `reply_buf[166]` meets fork formatters here).
**Client:** #837 (WiFi feature, owner-scoped), #375 (needs 0x02→0x08 correction), #138, #795; CLI pain already filed: #529/#473 (timeout formula — the 600 ms hold is now source-verified), #531/#532/#528/#589 (reply matching/late replies — already fixed in the service), #83 (bulk config read).
## E. Decision points (yours; the client spec consumes the answers)
1. **D1 — VER_CODE strategy** for the fork vs upstream's 14+ (and #1448's planned 23): re-map, re-base, or an explicit Offband marker. Decides F1's durable signal. (Firmware decision; client input filed on client#857.)
2. **D2 — Offband companion config mechanism post-absorb:** 0xC0 (#1448 path), upstream `wifi.*` CLI, or both — and specifically whether `get wifi.pwd` readback is disabled in the absorb. Decides F4(b) and the security posture row in B1.
3. **D3 — `_sys` fate post-absorb:** retire into frame-66 CLI, adapt (keep allowlist, same grammar), or keep as-is for observers. Decides whether the client's `_sys` documentation/UX assumptions persist.
4. **D4 — does the client configure STOCK 1.18 WiFi** (via upstream CLI) or stay Offband-only? Scope call on #837.
5. **D5 — sequencing:** does #1448 land on the 1.17.0 base as planned (ver 23) before the absorb, or wait for D1? (Named because it moves the collision; the call is yours and BrownWaterfall's work is in flight.)
6. **D6 — saved-network PSK at rest** on the phone (restated from #837).
Agent: GentleGlacier (session f0c92a36)

@ -0,0 +1,102 @@
# Initiative PLAN: client interop with upstream MeshCore 1.17.1/1.18.0
Plan of record for the client side of the upstream-1.18 world. Grounded in the 2026-10-17 investigation (three-surface contracts, population matrix, in-flight register — to be committed beside this plan as `INVESTIGATION.md`). This is one master plan carrying four features; each feature's epics derive from here and refine only what this leaves unspecified.
## At a glance
Upstream 1.18.0 introduces a companion CLI (local frame 66/29, remote TXT type 3 gated by contact-flag 0x10) and CLI-based WiFi config, moved its version code into the range the fork already spent (14 vs 14–22), and left the fork's binary surfaces (0xC0 config, `_sys`, caps bytes) untouched but newly overlapped. The client must (1) stop inferring capability from numbers both sides now use differently, (2) gain the CLI surfaces, (3) extend its existing Offband WiFi architecture (#837) without colliding with the in-flight firmware work (#365/#1448/#325), and (4) stay correct against four populations: stock 1.17.x, stock 1.18.0, Offband today (ver 22), Offband post-absorb.
**What you get when this is done:** a client that correctly identifies what it is talking to; a device CLI console for any stock-1.18+ or post-absorb device; remote CLI to permitted contacts with a per-contact permission toggle; WiFi configuration (including saved networks) that works on Offband today and is one adapter away from stock 1.18 devices; and a verified behavior matrix across all four populations.
## 1. Diagnosis
Done — [client#857](https://github.com/OffbandMesh/meshcore-client/issues/857) carries the full-read wire inventory; `INVESTIGATION.md` carries the three-surface contracts, the conflict matrix (`get wifi.pwd`: upstream cleartext readback vs fork write-only is the sharpest row), the population matrix, and the in-flight register. Key verified reuse: the client's `RepeaterCommandService` already implements the exact `XX|` prefix-correlation contract upstream extended to companions; the contact-write frame already carries the flags byte; the 0xC0 codec and WiFi write-planner stack are shipped and live.
## 2. Scope
Four features under this initiative. Firmware-side reconciliation (CommonCLI re-merge, `_sys` fate, 0xC0-vs-CLI convergence, VER_CODE strategy, prefs migration) is **out of scope** — tracked as dependencies D1–D3/D5, firmware's budget.
- **F1 — population discriminator & capability-gate rework.** Prerequisite for everything.
- **F2 — companion CLI, local.** Frame 66/29 console.
- **F3 — remote CLI.** Type 3 + contact permission 0x10.
- **F4 — WiFi.** The #837 scope (gating split, saved networks, apply flow) plus the stock-1.18 adapter if D4 says yes.
Out of scope, recorded: repeater WiFi via GUI (per #837); any firmware change; any use of fork frames toward stock devices.
## 3. Epics
### F1 — discriminator & gating (2 epics, ~6 tasks, 20–26 pts)
- **E1.1 Classifier + gate migration.** `DevicePopulation` classifier (frame shape 82/83/85 + ver code + caps + version-string dual format with the #691 `X-X` caveat); all caps parsing and the six ver-code gates route through it; channel-data bound 167→165; a documented seam where the firmware's durable marker (D1) replaces the interim signal. Fails closed: unknown population = stock-least-capability, no fork frames emitted.
- **E1.2 Conformance verification.** Fixture matrix (stock-1.17 / stock-1.18 / Offband-22 / malformed) through every gate; no UI change lands here.
### F2 — companion CLI, local (2 epics, ~6 tasks, 21–27 pts)
- **E2.1 Codec + service + console.** Frame 66/29 codec; shared correlation helper extracted from `RepeaterCommandService`; local command service (no mesh retries, frame-level timeout); console screen adapted from the `repeater_cli_screen` pattern; **mockup for your approval before the screen is built**; name-validation mirroring; 165-byte reply bound surfaced honestly (device truncates).
- **E2.2 Feature verification.** Against stock 1.18.0 (full vocabulary incl. wifi.* on a WiFi build) and an Offband device (console must not be offered pre-absorb).
### F3 — remote CLI (2 epics, ~6 tasks, 22–28 pts)
- **E3.1 Permission + send/receive.** Contact-flag 0x10 toggle (model/storage/contact UI, existing write frame); population-aware type selection (type 3 only to 1.18+/post-absorb peers, type 1 stays the server default); service generalization to companion targets; inbound type-3 accept + render (today warn-dropped); the no-permission UX — a type-3 send to an unpermitted companion produces *no reply at all* (it lands as a message on the target's app), so the console shows the timeout with that explanation and never auto-retries into silence.
- **E3.2 Feature verification.** Cross-population behavior matrix incl. 1.17 server reject and 1.17 companion silent-drop.
### F4 — WiFi (2 epics now, 1 decision-gated, ~5–9 tasks, 17–38 pts)
- **E4.1 Gating split + apply flow.** WiFi section on `0x01 || 0x08`, brokers/display on `0x01` alone (#375 corrected and absorbed here); apply-to-device over the existing 0xC0 write planner; status readout tolerant of both vocabularies.
- **E4.2 Saved networks.** Local store (new `lib/storage/` module), CRUD UI, apply-to-this-device; PSK-at-rest per D6. Mockups for your approval before screens.
- **E4.3 (gated on D4) Stock-1.18 adapter.** The same WiFi UI backed by wifi.* CLI over F2's service for stock devices; reboot-to-apply UX; `get wifi.pwd` output treated as a secret everywhere (masked, never logged, never stored device-side values).
- **Feature verification** rides E4.2 (and E4.3 if taken): Offband device via 0xC0; stock 1.18 via CLI if D4 yes.
## 4. Order and dependencies
F1 → F2 → (F3, F4 in either order). E4.3 additionally needs D4. Nothing here waits on the firmware absorb: F1's interim signal covers all four populations today, and the D1 marker swaps in at one seam. Cross-repo dependency register: D1 (VER_CODE/marker), D2 (0xC0 vs CLI on Offband, `get wifi.pwd` fate), D3 (`_sys` fate — affects docs/UX only on the client), D5 (#1448 sequencing — its cap 0x08 + ver 23 are what E4.1's gate consumes).
## 5. Grants and authorization
Proposed grant terms (basis: 8 epic PRs + this plan's PR; client repo, no device flashing):
```grant-terms
plan: OffbandMesh/meshcore-client — upstream-1180-interop
chain: E1.1 → E1.2 → E2.1 → E2.2 → E3.1 → E3.2 → E4.1 → E4.2 [→ E4.3 if D4]
verification per epic: flutter analyze + flutter test green; feature-verification epics additionally bench evidence recorded on the issue
merges: 10 (plan PR + 8–9 epic PRs), held to chain order
flash budget: 0 (no device flashing in this plan; bench flashes, if you want fresh images, are yours)
duration: 30 days
```
Push/PR asks will reach you as permission prompts (Remote Control is on); merges are yours — every PR arrives as a full link you can merge from the phone.
## 6. Can't-tell branches
| Branch | When the code can't confirm | It does |
|---|---|---|
| Population classifier | frame malformed / signals conflict | classifies **stock-least-capability**: no fork frames, no CLI offer; logs the evidence |
| CLI reply correlation | reply prefix matches nothing pending | surfaces to log + unmatched sink, never completes a different command (#532 behavior kept) |
| Remote CLI send | peer population unknown | refuses type 3, offers type 1 or nothing (servers only) |
| WiFi apply | device reports neither vocabulary | shows raw reply text, writes nothing further |
| Saved-network apply | password absent (D6 = prompt-at-apply) | stops and asks the user; never sends empty |
No fail-open branches; nothing proceeds on an unconfirmed condition.
## 7. Verification
Per-epic: `flutter analyze` + `flutter test` (fixtures from E1.2 reused everywhere). Feature-verification epics: live matrix against stock 1.17.1, stock 1.18.0, Offband current — devices and scheduling yours; results with evidence on the issues. 1.17.1 needs only the confirmation pass (wire-identical to 1.17.0 by full-read inspection).
## 8. Done when
All four features' verification epics closed on recorded evidence; the client behaves per the population matrix in `INVESTIGATION.md` §B3; no capability decision anywhere keys on a bare ver-code comparison; #857, #375, #138 resolved or re-scoped under this structure.
## 9. Your choices
| # | Decision | My recommendation (basis) |
|---|---|---|
| D1 | VER_CODE strategy (firmware) | explicit Offband marker in device-info; client never reads bare ver-code cross-population. Interim classifier makes this non-blocking. |
| D2 | Offband config mechanism post-absorb + `get wifi.pwd` fate | keep 0xC0 as the structured surface (client already speaks it, write-only pwd preserved); disable the cleartext readback in the absorb. |
| D3 | `_sys` fate | keep through the absorb; revisit retirement after F2's console ships and a parity audit exists. Client plan unaffected either way. |
| D4 | Configure stock-1.18 WiFi from the client? | yes — E4.3 is 2 tasks once F2 exists; it makes the client useful on stock hardware. Toggleable scope. |
| D5 | #1448 sequencing | proceed as in flight (contract settled on #365); the absorb reconciles. Named because it moves VER_CODE to 23. |
| D6 | Saved-network PSK at rest | platform secure storage, per-network opt-in; alternative is prompt-at-apply (safer, more friction). |
| — | Issue filing | on plan approval: initiative + 4 features + E-epics with lifecycle tasks, per the counted sizing (25–27 tasks, 87–119 pts + E4.3's 7–16). |
## 10. Carried-in work
#857 (diagnosis record — re-parent), #375 (corrected into E4.1), #138 (profiles import/apply — feeds E4.2), #795 (caplog-forward settings — consumer of F4, stays outside this plan), #529/#473 timeout work (already shipped in the service F2/F3 reuse).
---
Agent: GentleGlacier (session f0c92a36)

@ -0,0 +1,110 @@
// Codec for the upstream 1.18 companion CLI frames (interop plan F2, #868):
// CMD_RUN_CLI_COMMAND (66) out, RESP_CODE_CLI_REPLY (29) back. Pure codec,
// no transport - mirrors the firmware contract at companion-v1.18.0
// (INVESTIGATION.md §A1):
// request [66][ascii command], frame length >= 3
// reply [29][ascii reply], reply text <= 165 bytes (reply_buf[166])
// Correlation rides the optional 3-char prefix `cc|`: a command whose third
// character is `|` (and length > 4 on the device) has those 3 chars reflected
// at the start of the reply. Same grammar the repeater CLI already uses.
//
// Only emit frame 66 to a device the population classifier places at
// stockModern (or post-absorb Offband, via the D1 seam) - see
// device_population.dart. The codec itself does not gate.
import 'dart:convert';
import 'dart:typed_data';
/// `CMD_RUN_CLI_COMMAND`, stock v14+.
const int cmdRunCliCommand = 66;
/// `RESP_CODE_CLI_REPLY`, the reply to [cmdRunCliCommand].
const int respCodeCliReply = 29;
/// The device truncates replies at this many text bytes (`reply_buf[166]`,
/// one byte spent on the frame code).
const int maxCliReplyPayload = 165;
final RegExp _prefixShape = RegExp(r'^..\|$');
/// Builds a `[66][command]` frame, optionally prepending a 3-char
/// correlation [prefix] of the `cc|` shape.
///
/// Throws [ArgumentError] on a blank command, a command too short for the
/// firmware's `len >= 3` floor (two command bytes minimum), or a prefix that
/// is not exactly three characters ending in `|` - fail closed rather than
/// emit a frame the device will misparse.
Uint8List buildRunCliCommandFrame(String command, {String? prefix}) {
final trimmed = command.trim();
if (trimmed.isEmpty) {
throw ArgumentError.value(command, 'command', 'must not be blank');
}
if (prefix != null && !_prefixShape.hasMatch(prefix)) {
throw ArgumentError.value(prefix, 'prefix', 'must be 3 chars ending in |');
}
final payload = '${prefix ?? ''}$trimmed';
if (payload.length < 2) {
throw ArgumentError.value(
command,
'command',
'firmware requires at least 2 command bytes (frame len >= 3)',
);
}
// The device CLI is an ASCII surface; encode fail-closed so a non-ASCII
// command throws here instead of reaching the device malformed (Gemini
// review, #881 finding 1).
final List<int> bytes;
try {
bytes = ascii.encode(payload);
} on ArgumentError {
throw ArgumentError.value(command, 'command', 'must be ASCII');
}
return Uint8List.fromList([cmdRunCliCommand, ...bytes]);
}
/// One decoded CLI reply.
class CliReply {
const CliReply({
required this.prefix,
required this.text,
required this.payloadLength,
});
/// The reflected `cc|` correlation token, when the reply carries one.
final String? prefix;
/// Reply text with any prefix stripped.
final String text;
/// Raw payload byte count (prefix included) - truncation happens on the
/// device BEFORE the prefix is stripped, so the bound is judged here, not
/// on [text] (Gemini review, #881 finding 2).
final int payloadLength;
/// True when the payload sits at the device's truncation bound - the reply
/// may have been cut and the UI should say so rather than present it as
/// complete.
bool get atReplyBound => payloadLength >= maxCliReplyPayload;
}
/// Parses a `[29][reply]` frame; null when [frame] is not a CLI reply.
/// Decoding is lenient (malformed bytes become U+FFFD) - a garbled reply is
/// still a reply, and dropping it would look like a timeout.
///
/// Prefix detection is positional (third character `|`), the same rule the
/// device and the repeater path use. A prefixless reply whose text happens to
/// carry `|` at index 2 mis-splits - inherent to the wire grammar, mitigated
/// by callers always sending a prefix so real replies reflect one.
CliReply? parseCliReply(Uint8List frame) {
if (frame.isEmpty || frame[0] != respCodeCliReply) return null;
final payloadLength = frame.length - 1;
final raw = utf8.decode(frame.sublist(1), allowMalformed: true);
if (raw.length >= 3 && raw[2] == '|') {
return CliReply(
prefix: raw.substring(0, 3),
text: raw.substring(3),
payloadLength: payloadLength,
);
}
return CliReply(prefix: null, text: raw, payloadLength: payloadLength);
}

@ -0,0 +1,217 @@
// Population classifier for the connected radio (initiative #860, F1 #862).
//
// Upstream MeshCore 1.18.0 moved FIRMWARE_VER_CODE into the range the Offband
// fork had already spent (stock 14 = "CLI frame 66 exists" vs fork 14..22 =
// 0xC0-era contract numbers), so a bare `firmwareVerCode >= N` comparison no
// longer means one thing. Every capability decision routes through this
// classifier instead of reading ver code or frame offsets directly.
//
// Interim signal (plan E1.1): the device-info reply's SHAPE. Stock ships
// exactly 82 bytes; the fork appends offband_caps at offset 82 and caps
// byte 2 at offset 84 [verified against companion-v1.18.0 and firmware-base,
// INVESTIGATION.md §A/§B3]. The firmware's durable marker (decision D1)
// replaces this at one seam -see classifyDevicePopulation's doc.
import 'dart:typed_data';
/// Which firmware family the connected radio belongs to, as far as wire
/// behavior is concerned.
enum DevicePopulation {
/// Stock MeshCore below ver 14, or anything this classifier cannot place:
/// the fail-closed default. No fork frames, no CLI frame.
stockLegacy,
/// Stock MeshCore ver 14+ (1.18.0 era): CLI frame 66/29 exists; fork
/// frames (0xC0..0xC6) and caps bytes do not.
stockModern,
/// Offband fork: caps byte(s) present; fork frames are gated by the
/// advertised cap bits as before. No CLI frame until the fork absorbs
/// upstream 1.18 (post-absorb devices flip [Classification.allowsCliFrame]
/// at the D1 seam, not here).
offband,
}
/// The classifier's verdict plus the coarse capability doors it opens.
/// Fine-grained gating (which 0xC command, which cap bit) stays where it is
/// today; these booleans only say which FAMILIES of frames may be emitted.
class Classification {
const Classification({
required this.population,
required this.conflict,
required this.evidence,
});
final DevicePopulation population;
/// True when the signals contradicted each other (for example a fork-length
/// frame carrying a stock version string). Conflicts classify as
/// [DevicePopulation.stockLegacy] -fail closed -and [evidence] says why.
final bool conflict;
/// Human-readable signal summary for logs; never parsed.
final String evidence;
/// Fork frames (0xC0..0xC6) may be emitted, subject to the existing
/// cap-bit gates.
bool get allowsOffbandFrames => population == DevicePopulation.offband;
/// CMD_RUN_CLI_COMMAND (66) may be emitted. Deliberately false for
/// [DevicePopulation.offband] on the current fork base; the absorb flips
/// this at the D1 seam together with the durable marker.
bool get allowsCliFrame => population == DevicePopulation.stockModern;
}
/// Stock device-info replies are exactly this long; the first fork byte
/// (offband_caps) sits at this offset. [verified: CMD_DEVICE_QUERY reply
/// construction at companion-v1.18.0 -82 bytes, unchanged from 1.17.x]
const int stockDeviceInfoLength = 82;
/// Upstream ver code that introduces the CLI frame (66/29).
const int stockCliMinVerCode = 14;
/// Highest FIRMWARE_VER_CODE this client knows to exist in the field on any
/// population (fork is at 22, moving to 23 on firmware#1448; stock is at 14).
/// A report far above this is treated as malformed rather than capable.
const int maxKnownVerCode = 32;
/// Classifies the connected radio from its device-info reply and the parsed
/// firmware-version string.
///
/// [deviceInfo] is the raw RESP_CODE_DEVICE_INFO frame. [firmwareVersion] is
/// the version string already extracted from it (null when absent/unreadable);
/// it is a SECONDARY signal -absence never blocks, only a positive
/// contradiction does. Task #878 replaces the contains-check below with the
/// full dual-format parser.
///
/// D1 SEAM: when the firmware ships its durable population marker, this
/// function is the single place that learns to read it; callers and the
/// [Classification] contract do not change.
Classification classifyDevicePopulation({
required Uint8List deviceInfo,
required String? firmwareVersion,
}) {
final length = deviceInfo.length;
// Malformed: too short to even carry a ver code, per the connector's own
// minimum (frame.length < 4 is discarded there too).
if (length < 4) {
return Classification(
population: DevicePopulation.stockLegacy,
conflict: false,
evidence: 'malformed device-info (len=$length)',
);
}
final verCode = deviceInfo[1];
final forkShape = length > stockDeviceInfoLength;
final versionLooksStock = _versionLooksStock(firmwareVersion);
if (verCode > maxKnownVerCode) {
return Classification(
population: DevicePopulation.stockLegacy,
conflict: true,
evidence: 'ver $verCode above any known population (len=$length)',
);
}
if (forkShape) {
if (versionLooksStock == false) {
// Positively Offband: fork-length frame AND the dual version form.
// Every verified fork build reports the dual form, including release
// images' X-X shape (firmware#691) and bench builds' git-describe
// suffixes, so requiring it costs nothing real and stops a corrupted
// stock frame from unlocking fork frames.
return Classification(
population: DevicePopulation.offband,
conflict: false,
evidence: 'caps byte present (len=$length, ver=$verCode)',
);
}
// Stock version string, or no readable version at all: the shape says
// fork but nothing corroborates it, so no fork frames get emitted on
// this connection (Gemini review, task #875 finding 1A).
return Classification(
population: DevicePopulation.stockLegacy,
conflict: true,
evidence:
'fork-shape frame (len=$length) but version string '
'"$firmwareVersion" does not corroborate',
);
}
// A stock-shape (82-byte) frame is definitively stock: the Offband fork
// always appends at least one caps byte (>=83 bytes), so a stock-shape frame
// can never be an Offband device. The version string is therefore NOT used to
// force a conflict in the stock direction. This replaces the old inverse
// conflict (#875 finding 2), which guarded an impossible case (an Offband
// device that failed to append caps) and misfired on real stock firmware:
// stock 1.18.0 reports "v1.18.0-81dbae5" (semver + git-describe hash), which
// reads as the dual form and hid the console on every real device (#946,
// found by E2.2 bench verification). The fork-shape branch above still
// requires dual-version corroboration, because emitting fork frames is the
// direction where being wrong is dangerous.
if (verCode >= stockCliMinVerCode) {
return Classification(
population: DevicePopulation.stockModern,
conflict: false,
evidence: 'stock-shape frame, ver=$verCode >= $stockCliMinVerCode',
);
}
return Classification(
population: DevicePopulation.stockLegacy,
conflict: false,
evidence: 'stock-shape frame, ver=$verCode',
);
}
/// What a firmware-version string positively claims about the population.
enum VersionStringShape {
/// Single `vX.Y.Z` (or `X.Y.Z`): the stock FIRMWARE_VERSION form.
stock,
/// The Offband dual form: a semver, a dash, then more -covering
/// `<ob>-<mc>` ("1.4.0-1.17.0"), the release-image `X-X` shape
/// ("1.4.0-1.4.0", firmware#691), and bench builds' git-describe tails
/// ("1.1.0-4-g9f2e1c3-dirty").
offbandDual,
/// Absent, empty, or nothing this parser recognizes. Never corroborates
/// anything: the classifier treats it as a missing signal, which on a
/// fork-shape frame means fail closed.
unknown,
}
// A stock version with a suffix (a git-describe hash like "v1.18.0-81dbae5",
// or a pre-release like "v1.19.0-rc1") parses as the dual form here. That no
// longer mis-classifies a stock device: a stock-shape (82-byte) frame is
// classified by its ver code regardless of the version string (#946), because
// the frame shape is definitive. This parser's dual verdict only matters on a
// FORK-shape frame, where it corroborates the caps bytes.
final RegExp _semver = RegExp(r'^v?\d+\.\d+\.\d+$');
final RegExp _dualPrefix = RegExp(r'^v?\d+\.\d+\.\d+-.+$');
/// Parses the device-info firmware-version field into its population claim
/// (#878). Pure and total: any input maps to exactly one shape.
VersionStringShape classifyVersionString(String? version) {
if (version == null) return VersionStringShape.unknown;
final v = version.trim();
if (v.isEmpty) return VersionStringShape.unknown;
if (_semver.hasMatch(v)) return VersionStringShape.stock;
if (_dualPrefix.hasMatch(v)) return VersionStringShape.offbandDual;
return VersionStringShape.unknown;
}
/// Adapter kept for the classifier's tri-state contract: true = positively
/// stock, false = positively Offband, null = no signal.
bool? _versionLooksStock(String? version) {
switch (classifyVersionString(version)) {
case VersionStringShape.stock:
return true;
case VersionStringShape.offbandDual:
return false;
case VersionStringShape.unknown:
return null;
}
}

File diff suppressed because it is too large Load Diff

@ -259,6 +259,10 @@ const int cmdImportPrivateKey = 24;
const int txtTypePlain = 0;
const int txtTypeCliData = 1;
const int txtTypeSigned = 2;
// Remote CLI command to a companion (upstream 1.18, TXT_TYPE_CLI_COMMAND).
// Repeaters/room servers treat it exactly like CLI_DATA; a pre-1.18 or
// Offband-pre-absorb companion silently drops it (surfaced as no reply).
const int txtTypeCliCommand = 3;
// Repeater request types (for server requests)
const int reqTypeGetStatus = 0x01;
@ -552,6 +556,15 @@ const int offbandCapBlock = 0x02;
/// FEM-bearing boards report false today.
const int offbandCapFemLna = 0x04;
// POPULATION INVARIANT (#875-#877): every `offbandCaps`-anchored gate below is
// safe against stock 1.18+ devices ONLY because the connector nulls the caps
// bytes unless the population classifier corroborates the fork layout
// (device_population.dart). The ver-code floors in these gates are FORK
// contract numbers; stock reuses 14+ with different meanings, so a bare
// `firmwareVerCode >=` comparison may only be added for codes BELOW 14
// (pre-split, same meaning everywhere: see supportsCompanionRadioStats >= 8
// and firmwareSupportsRegionScope >= 13) or behind a caps-anchored gate here.
bool firmwareSupportsOffbandFemLna(int? offbandCaps) =>
offbandCaps != null && (offbandCaps & offbandCapFemLna) != 0;
@ -593,6 +606,37 @@ bool firmwareSupportsButtonMatrix(int? offbandCaps2) =>
bool firmwareSupportsNotifyScope(int? offbandCaps2) =>
offbandCaps2 != null && (offbandCaps2 & offbandCap2NotifyScope) != 0;
/// The tune system over `0xC5` (#970, #971, #986): custom slots (0x09, 0x0A,
/// 0x12), channel tune (0x0B, 0x0C), event tones (0x0F, 0x10) and preview
/// (0x11). Firmware sets it where the UI plays every sound through its tune
/// engine, which needs a buzzer but is not implied by one, so a radio can
/// advertise the scope bit without this (meshcore-firmware `f3d30a88`).
const int offbandCap2Tunes = 0x10;
/// GPS mode and Power-save interval over `0xC5` sub-codes 0x0D / 0x0E (#969).
/// Firmware sets it where `ENV_INCLUDE_GPS == 1` (meshcore-firmware#1789).
///
/// It says the radio speaks the GPS sub-codes, NOT that it can run Power save:
/// the duty cycle is compiled per variant, and every GPS reply carries `ps_ok`
/// for that. Never offer Power save from this bit alone.
const int offbandCap2GpsMode = 0x20;
/// The badge's own display and battery settings over `0xC5` 0x13 to 0x17
/// (#987): text sizes, Screen off, time zone, battery full point.
const int offbandCap2ScreenSettings = 0x40;
/// True iff this radio answers the `0xC5` tune sub-codes.
bool firmwareSupportsTunes(int? offbandCaps2) =>
offbandCaps2 != null && (offbandCaps2 & offbandCap2Tunes) != 0;
/// True iff this radio answers the `0xC5` screen-settings sub-codes (#987).
bool firmwareSupportsScreenSettings(int? offbandCaps2) =>
offbandCaps2 != null && (offbandCaps2 & offbandCap2ScreenSettings) != 0;
/// True iff this radio answers the `0xC5` GPS-mode sub-codes (#969).
bool firmwareSupportsGpsMode(int? offbandCaps2) =>
offbandCaps2 != null && (offbandCaps2 & offbandCap2GpsMode) != 0;
bool firmwareSupportsOffbandCaplog(int? offbandCaps, int? firmwareVerCode) =>
offbandCaps != null &&
(offbandCaps & offbandCapCaplog) != 0 &&
@ -667,6 +711,176 @@ OffbandPktHash? parseOffbandPktHashReply(Uint8List frame) {
return OffbandPktHash(timestamp: ts, channelIdx: chan, hashHex: hashHex);
}
// --- Region flood-scoping + regions discovery (Feature #812, Epic #813).
//
// Stock MeshCore companion frames, verified against firmware source:
// - CMD_SET_FLOOD_SCOPE_KEY 54 (companion MyMesh.cpp:3512): sub-0 sets a 16-byte
// send-scope override ([54,0,key16]) or clears it to the node default ([54,0]);
// sub-1 ([54,1]) forces unscoped sends (FIRMWARE_VER_CODE 12+).
// - CMD_SET_DEFAULT_FLOOD_SCOPE 63 (MyMesh.cpp:3523): [63,name:31,key:16] sets
// the node default, bare [63] clears it.
// - CMD_GET_DEFAULT_FLOOD_SCOPE 64 (MyMesh.cpp:3540) -> RESP_CODE_DEFAULT_FLOOD_SCOPE
// 28: bare [28] = none, or [28,name:31,key:16].
// - Discovery is an ANON request: CMD_SEND_ANON_REQ 57 carrying
// [timestamp:4][ANON_REQ_TYPE_REGIONS 0x01][reply_path_len] (companion
// MyMesh.cpp:3114; repeater simple_repeater MyMesh.cpp:586-607,150-163). The
// repeater replies region names as a CSV; the companion forwards it to the app
// as PUSH_CODE_BINARY_RESPONSE 0x8C: [0x8C,0,tag:4,clock:4,CSV]. The tag is the
// request timestamp the firmware echoes in RESP_CODE_SENT.
const int cmdSetFloodScopeKey = 54;
const int cmdSetDefaultFloodScope = 63;
const int cmdGetDefaultFloodScope = 64;
const int respCodeDefaultFloodScope = 28;
const int anonReqTypeRegions = 0x01;
const int floodScopeSubSetKey = 0x00;
const int floodScopeSubUnscoped = 0x01;
/// Byte length of the on-wire region transport key and the default-scope name
/// field (firmware `TransportKey::key` and `default_scope_name`).
const int regionKeyLength = 16;
const int defaultScopeNameField = 31;
/// True iff the connected firmware supports region flood-scoping and regions
/// discovery. Floor is `FIRMWARE_VER_CODE` 13: `CMD_SEND_ANON_REQ` accepts a
/// non-contact repeater recipient at 13+ (companion `MyMesh.cpp:3118`), the path
/// regions discovery relies on; `CMD_SET_FLOOD_SCOPE_KEY` sub-0 is older (8+) and
/// sub-1 unscoped is 12+, both covered by 13. Fail-closed: the client must never
/// emit a region frame when this is false. (#813)
bool firmwareSupportsRegionScope(int? firmwareVerCode) =>
(firmwareVerCode ?? 0) >= 13;
/// Regions-discovery ANON request to [repeaterPubKey] (32 bytes). Wire after
/// the pubkey: `[ANON_REQ_TYPE_REGIONS 0x01][reply_path_len]`.
///
/// The firmware's `sendAnonReq` (BaseChatMesh) prepends its OWN 4-byte tag to
/// this payload before transmit, and returns that tag in `RESP_CODE_SENT`; the
/// repeater echoes it in the `0x8C` reply. So the client must NOT add a
/// timestamp/tag here: doing so shifts the request-type byte and the repeater
/// reads it as a login request, never regions (D1 bug, #836). Correlate the
/// reply by the `RESP_CODE_SENT` tag, not a client value.
///
/// [replyPathLenByte] is the firmware packed path-len byte and [replyPath] the
/// matching hop-hash bytes: the repeater routes its reply back along this path
/// as-is (MeshCore paths are bidirectional, Mesh.cpp:176-177), so pass the
/// repeater contact's own stored path for a multi-hop reply. An empty path
/// (`replyPathLenByte = 0`) is zero-hop, which only reaches an adjacent repeater.
Uint8List buildAnonRegionsRequestFrame(
Uint8List repeaterPubKey, {
int replyPathLenByte = 0,
Uint8List? replyPath,
}) {
final writer = BufferWriter();
writer.writeByte(cmdSendAnonReq);
writer.writeBytes(repeaterPubKey);
writer.writeByte(anonReqTypeRegions);
writer.writeByte(replyPathLenByte & 0xFF);
if (replyPath != null && replyPath.isNotEmpty) writer.writeBytes(replyPath);
return writer.toBytes();
}
/// Set the companion's flood send-scope override to [key], applied to subsequent
/// sends until cleared. Wire: `[54][0][key16]`. (FIRMWARE_VER_CODE 8+)
Uint8List buildSetFloodScopeKeyFrame(Uint8List key) {
final padded = Uint8List(regionKeyLength);
padded.setRange(0, min(key.length, regionKeyLength), key);
final writer = BufferWriter();
writer.writeByte(cmdSetFloodScopeKey);
writer.writeByte(floodScopeSubSetKey);
writer.writeBytes(padded);
return writer.toBytes();
}
/// Clear the flood send-scope override, reverting to the node default scope.
/// Wire: `[54][0]`. (FIRMWARE_VER_CODE 8+)
Uint8List buildClearFloodScopeFrame() =>
Uint8List.fromList([cmdSetFloodScopeKey, floodScopeSubSetKey]);
/// Force subsequent sends unscoped (no flood scope). Wire: `[54][1]`.
/// (FIRMWARE_VER_CODE 12+)
Uint8List buildFloodScopeUnscopedFrame() =>
Uint8List.fromList([cmdSetFloodScopeKey, floodScopeSubUnscoped]);
/// Set the node default flood scope to ([name],[key]). Wire:
/// `[63][name:31 NUL-padded][key:16]`. Firmware requires a name of 1..30 bytes.
Uint8List buildSetDefaultFloodScopeFrame(String name, Uint8List key) {
final padded = Uint8List(regionKeyLength);
padded.setRange(0, min(key.length, regionKeyLength), key);
final writer = BufferWriter();
writer.writeByte(cmdSetDefaultFloodScope);
writer.writeCString(name, defaultScopeNameField);
writer.writeBytes(padded);
return writer.toBytes();
}
/// Clear the node default flood scope. Wire: `[63]`.
Uint8List buildClearDefaultFloodScopeFrame() =>
Uint8List.fromList([cmdSetDefaultFloodScope]);
/// Query the node default flood scope. Wire: `[64]` -> RESP 28.
Uint8List buildGetDefaultFloodScopeFrame() =>
Uint8List.fromList([cmdGetDefaultFloodScope]);
/// A node's default flood scope, from a `RESP_CODE_DEFAULT_FLOOD_SCOPE` (28)
/// reply. [name] is empty when the node has no default scope set.
class DefaultFloodScope {
const DefaultFloodScope({required this.name, required this.key});
final String name;
final Uint8List key;
bool get isSet => name.isNotEmpty;
}
/// Parse a `RESP_CODE_DEFAULT_FLOOD_SCOPE` (28) reply. Returns null when [frame]
/// is not a RESP 28; otherwise a [DefaultFloodScope] whose [name] is empty when
/// the node reports no default (bare `[28]`).
DefaultFloodScope? parseDefaultFloodScopeReply(Uint8List frame) {
if (frame.isEmpty || frame[0] != respCodeDefaultFloodScope) return null;
if (frame.length < 1 + defaultScopeNameField + regionKeyLength) {
return DefaultFloodScope(name: '', key: Uint8List(0));
}
final reader = BufferReader(frame);
reader.readByte(); // resp code
final name = reader.readCStringGreedy(defaultScopeNameField);
final key = reader.readBytes(regionKeyLength);
return DefaultFloodScope(name: name, key: key);
}
/// A regions-discovery reply parsed from a `PUSH_CODE_BINARY_RESPONSE` (0x8C)
/// envelope: `[0x8C][0][tag:4][clock:4][CSV names]`. [tag] matches the
/// firmware-chosen tag returned in `RESP_CODE_SENT` for the request; names are
/// `#`-stripped and comma-separated, with `*` marking a wildcard.
class RegionsReply {
const RegionsReply({
required this.tag,
required this.clock,
required this.regionNames,
});
final int tag;
final int clock;
final List<String> regionNames;
}
/// Parse a `0x8C` frame as a regions reply. Returns null for a short or non-0x8C
/// frame. An empty name list is a valid reply (a repeater flooding no regions),
/// never a parse error. Callers match [RegionsReply.tag] to a request they sent;
/// `0x8C` is a generic binary-response envelope, so only interpret it as regions
/// for a tag that was a regions request.
RegionsReply? parseRegionsReply(Uint8List frame) {
if (frame.length < 10 || frame[0] != pushCodeBinaryResponse) return null;
final reader = BufferReader(frame);
reader.readByte(); // 0x8C
reader.readByte(); // reserved
final tag = reader.readUInt32LE();
final clock = reader.readUInt32LE();
final csv = reader.readCString();
final names = csv
.split(',')
.map((s) => s.trim())
.where((s) => s.isNotEmpty)
.toList();
return RegionsReply(tag: tag, clock: clock, regionNames: names);
}
const int statsTypeCore = 0;
const int statsTypeRadio = 1;
const int statsTypePackets = 2;
@ -811,6 +1025,11 @@ const int contactFlagFavorite = 0x01;
const int contactFlagTeleBase = 0x02; // 'base' permission includes battery
const int contactFlagTeleLoc = 0x04;
const int contactFlagTeleEnv = 0x08; //access environment sensors
// 0x10 (isRemoteCLIAllowed): this contact may run remote CLI (TXT type 3)
// commands on our radio. The receiving side checks it, so setting it here grants
// the contact permission to command THIS device. [verified: BaseChatMesh.cpp /
// MyMesh.cpp companion at companion-v1.18.0; INVESTIGATION.md section A]
const int contactFlagRemoteCliAllowed = 0x10;
const int contactPathLenOffset = 35;
const int contactPathOffset = 36;
const int contactNameOffset = 100;
@ -829,7 +1048,17 @@ const int msgTextOffset = 38;
class ParsedContactText {
final Uint8List senderPrefix;
final String text;
const ParsedContactText({required this.senderPrefix, required this.text});
/// The raw TXT type byte (plain 0, CLI_DATA 1, signed 2, CLI_COMMAND 3).
/// Some layouts carry it shifted left by 2; compare with both the raw value
/// and `txtType >> 2`, as the receive path does.
final int txtType;
const ParsedContactText({
required this.senderPrefix,
required this.text,
required this.txtType,
});
}
ParsedContactText? parseContactMessageText(Uint8List frame) {
@ -862,7 +1091,11 @@ ParsedContactText? parseContactMessageText(Uint8List frame) {
final text = message.readCString();
if (text.isEmpty) return null;
return ParsedContactText(senderPrefix: senderPrefix, text: text);
return ParsedContactText(
senderPrefix: senderPrefix,
text: text,
txtType: textType,
);
} catch (e) {
debugPrint('Error parsing contact message text: $e');
return null;
@ -923,6 +1156,19 @@ int pathHashSizeBytes(int pathLenRaw) => ((pathLenRaw >> 6) & 0x03) + 1;
int pathByteLength(int pathLenRaw) =>
pathHopCount(pathLenRaw) * pathHashSizeBytes(pathLenRaw);
/// Merges two stored path-len values for repeats of one message: both are the
/// raw packed byte (or the -1 flood sentinel / null when unknown), and the one
/// with the higher decoded hop count wins. Never feed a path BYTE length in
/// here: at 2/3-byte hash widths it is 2-3x the hop count and decodes as a
/// bogus width-1 count, which is how a 13-hop message rendered as 39 (#985).
int? mergePathLenRaw(int? existing, int? incoming) {
if (existing == null) return incoming;
if (incoming == null) return existing;
if (existing < 0) return incoming;
if (incoming < 0) return existing;
return pathHopCount(existing) >= pathHopCount(incoming) ? existing : incoming;
}
/// Packs a hop count and per-hop hash width into the firmware path-length byte.
///
/// Mirrors firmware `Packet::setPathHashSizeAndCount`. Sending a bare hop count
@ -1402,20 +1648,30 @@ int calculateMessageTimeout({
// Build CLI command text message frame (companion_radio format)
// Format: [cmd][txt_type][attempt][timestamp x4][pub_key_prefix x6][text...]\0
/// The CLI txt type for a command sent to a peer of [contactType] (#888).
/// Decided by ROLE, not firmware version: a companion (chat) takes the 1.18
/// command type; a repeater/room server takes the universal CLI_DATA type it
/// has always used. A Contact carries no version, and a non-1.18 companion
/// silently drops the command type, so role is both sufficient and safe. A
/// later refinement could pin a peer's version with a `ver` probe on connect.
int cliTxtTypeForContactType(int contactType) =>
contactType == advTypeChat ? txtTypeCliCommand : txtTypeCliData;
Uint8List buildSendCliCommandFrame(
Uint8List repeaterPubKey,
Uint8List peerPubKey,
String command, {
int attempt = 0,
int? timestampSeconds,
int txtType = txtTypeCliData,
}) {
final timestamp =
timestampSeconds ?? (DateTime.now().millisecondsSinceEpoch ~/ 1000);
final writer = BufferWriter();
writer.writeByte(cmdSendTxtMsg);
writer.writeByte(txtTypeCliData);
writer.writeByte(txtType);
writer.writeByte(attempt.clamp(0, 255));
writer.writeUInt32LE(timestamp);
writer.writeBytes(repeaterPubKey.sublist(0, 6));
writer.writeBytes(peerPubKey.sublist(0, 6));
writer.writeString(command);
writer.writeByte(0);
return writer.toBytes();

@ -1,5 +1,8 @@
import 'dart:typed_data';
import 'offband_screen_settings.dart';
import 'offband_tones.dart';
/// Headless-device UI configuration: the button-action matrix (#474) and the
/// device notification scope (#475).
///
@ -57,6 +60,17 @@ const int offbandUiScopeSet = 0x02;
const int offbandUiMatrixGet = 0x03;
const int offbandUiMatrixSet = 0x04;
/// Per-channel tune (#971, meshcore-firmware#1789). Both reply
/// `[0xC5][sub][ch][stored]`, the SET reply re-read after the write.
const int offbandUiChannelTuneGet = 0x0B;
const int offbandUiChannelTuneSet = 0x0C;
/// GPS mode and Power-save interval (#969, meshcore-firmware#1789). Both reply
/// with the same 14-byte state, the SET reply re-read after the write.
const int offbandUiGpsGet = 0x0D;
const int offbandUiGpsSet = 0x0E;
const int _gpsReplyLength = 14;
/// Shared error sub-code. The reply carries a reason byte rather than the
/// generic `[RESP_CODE_ERR][ERR_CODE_ILLEGAL_ARG]` pair, because both epics
/// require the user to be shown *why* an assignment was refused: "this board
@ -72,7 +86,22 @@ enum ButtonConfigError {
unknownSequence(0x02, 'This radio does not recognise that button sequence'),
noBuzzer(0x03, 'This radio has no buzzer'),
noGps(0x04, 'This radio has no GPS'),
malformed(0x05, 'The radio could not read the request');
malformed(0x05, 'The radio could not read the request'),
unsupportedIndicator(0x06, 'This radio has no display or LED to set'),
slotOffset(
0x07,
'The radio stopped accepting this tune partway through. Nothing was '
'changed. Try saving again.',
),
batteryTooHigh(
0x08,
'The reading is higher than a full cell, so it was not used.',
),
batteryNotCharged(
0x09,
'Not charged yet. Charge the radio fully, then set 100% again. Nothing '
'was changed.',
);
const ButtonConfigError(this.code, this.message);
final int code;
@ -89,6 +118,26 @@ enum ButtonConfigError {
}
}
/// Which `0xC5` surface a write targeted. The shared error frame
/// `[0xC5][0x7F][reason]` names no sub-code, so the client attributes an error
/// to the write it has outstanding, and each screen shows only its own.
enum DeviceUiSurface {
buttonMatrix,
notifyScope,
gpsMode,
channelTune,
eventTone,
tunePlay,
tuneSlot,
screenSettings,
}
/// The refusal reason for a GPS write. Reason 1 means Power save on a build
/// that cannot run it (meshcore-firmware#1789); the rest read as for buttons.
String describeGpsError(int code) => code == 0x01
? 'This radio cannot run Power save'
: ButtonConfigError.describe(code);
/// A button press sequence. Values are the wire encoding.
///
/// Long-press sequences are deliberately absent: firmware reserves long-press
@ -160,6 +209,132 @@ enum DeviceNotifyScope {
}
}
/// How GPS runs (#969). Values are the wire encoding and firmware's
/// `offband::GpsMode`.
///
/// One control writes this, the way the badge's own GPS screen does through
/// `setGpsMode()`: Off turns GPS off and leaves the remembered mode byte alone,
/// so Off then On returns to Power save rather than to continuous On.
enum GpsMode {
off(0),
on(1),
powerSave(2);
const GpsMode(this.code);
final int code;
static GpsMode? fromCode(int code) {
for (final m in GpsMode.values) {
if (m.code == code) return m;
}
return null;
}
}
/// What GPS is doing right now. Display only; firmware pins the bytes.
///
/// Backed off is the state a badge indoors at an event will usually be in, and
/// it reads as a fault unless it is named.
enum GpsActivity {
off(0),
on(1),
searching(2),
sleeping(3),
backedOff(4);
const GpsActivity(this.code);
final int code;
static GpsActivity? fromCode(int code) {
for (final a in GpsActivity.values) {
if (a.code == code) return a;
}
return null;
}
}
/// The radio's GPS state from a `0xC5` 0x0D or 0x0E reply.
///
/// Every field is what the device holds, never what the client asked for: the
/// SET reply is re-read after the write, so a clamped interval or an Off that
/// kept the remembered mode both show as they really are.
class GpsModeState {
/// The mode in effect, resolved by firmware from both stored fields.
final GpsMode mode;
/// The raw stored mode byte. `0xFF` means never set, which runs as On.
final int storedMode;
/// Whether this build can run Power save. Compiled per variant, so this is
/// the only honest answer to whether the option should be offered.
final bool powerSaveAvailable;
/// Null when a newer firmware reports a state this client does not know.
final GpsActivity? activity;
/// Sleep between fix attempts in Power save, in seconds. 0 = firmware
/// default. Firmware raises 1 to 299 to 300.
final int intervalSeconds;
/// Seconds until the next fix attempt, or 0.
final int waitSeconds;
const GpsModeState({
required this.mode,
required this.storedMode,
required this.powerSaveAvailable,
required this.activity,
required this.intervalSeconds,
required this.waitSeconds,
});
}
/// A channel's tune choice, as the radio stores it (#971).
///
/// Stored byte 0 means no choice: inherit the global channel tune. Any other
/// value is tune id + 1, and tune id 0 is Silent, a deliberate choice. Those
/// two must never collapse into one "none", because the user cannot tell from
/// the device which one they picked, so they are distinct values here and the
/// byte is never built by hand.
class ChannelTune {
const ChannelTune.inherit() : stored = 0;
const ChannelTune._(this.stored);
/// [tuneId] 0 is Silent. The stored byte is `tuneId + 1`, so 254 is the
/// highest id that fits.
factory ChannelTune.tune(int tuneId) {
if (tuneId < 0 || tuneId > 254) {
throw ArgumentError.value(tuneId, 'tuneId', 'must be 0 to 254');
}
return ChannelTune._(tuneId + 1);
}
factory ChannelTune.fromStored(int stored) => ChannelTune._(stored & 0xFF);
final int stored;
bool get inherits => stored == 0;
bool get isSilent => stored == 1;
/// Null when the channel inherits.
int? get tuneId => stored == 0 ? null : stored - 1;
@override
bool operator ==(Object other) =>
other is ChannelTune && other.stored == stored;
@override
int get hashCode => stored.hashCode;
}
/// One channel's tune, as a `0xC5` 0x0B or 0x0C reply reports it.
class ChannelTuneReply {
const ChannelTuneReply({required this.channel, required this.tune});
final int channel;
final ChannelTune tune;
}
/// The device's current button configuration, as reported by a GET.
class ButtonMatrix {
/// Sequence to action, only for sequences the device reported.
@ -209,6 +384,41 @@ Uint8List buildNotifyScopeGetFrame() =>
Uint8List buildNotifyScopeSetFrame(DeviceNotifyScope scope) =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiScopeSet, scope.code]);
int _channelByte(int channel) {
if (channel < 0 || channel > 0xFF) {
throw ArgumentError.value(channel, 'channel', 'must be 0 to 255');
}
return channel;
}
Uint8List buildChannelTuneGetFrame(int channel) => Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiChannelTuneGet,
_channelByte(channel),
]);
Uint8List buildChannelTuneSetFrame(int channel, ChannelTune tune) =>
Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiChannelTuneSet,
_channelByte(channel),
tune.stored,
]);
Uint8List buildGpsModeGetFrame() =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiGpsGet]);
/// `[0xC5][0x0E][mode][interval_s:4 LE]`. The interval always travels with the
/// mode, so a mode change must resend the current interval to keep it.
Uint8List buildGpsModeSetFrame(GpsMode mode, int intervalSeconds) {
final frame = Uint8List(7);
frame[0] = cmdOffbandDeviceUi;
frame[1] = offbandUiGpsSet;
frame[2] = mode.code;
ByteData.sublistView(frame).setUint32(3, intervalSeconds, Endian.little);
return frame;
}
/// Outcome of a `0xC5` / `0xC6` reply. Exactly one of the payload fields is
/// non-null; [errorMessage] is set when the device refused.
class OffbandUiReply {
@ -218,8 +428,24 @@ class OffbandUiReply {
final ButtonSequence? setSequence;
final ButtonAction? setAction;
final DeviceNotifyScope? scope;
final GpsModeState? gps;
final ChannelTuneReply? channelTune;
final EventToneReply? eventTone;
final TuneSlotReply? tuneSlot;
final TuneSlotAccepted? slotAccepted;
final TuneSlotChunk? slotChunk;
final TunePlayReply? tunePlay;
final ScreenSettingsState? screen;
final String? errorMessage;
/// The raw reason byte of a `0x7F` error, so a surface can word it for its
/// own context. Null on every other reply.
final int? errorCode;
/// The byte after the reason, when the error carries one: `ERR_SLOT_OFFSET`
/// sends the offset the radio expects next.
final int? errorDetail;
const OffbandUiReply({
required this.command,
required this.sub,
@ -227,7 +453,17 @@ class OffbandUiReply {
this.setSequence,
this.setAction,
this.scope,
this.gps,
this.channelTune,
this.eventTone,
this.tuneSlot,
this.slotAccepted,
this.slotChunk,
this.tunePlay,
this.screen,
this.errorMessage,
this.errorCode,
this.errorDetail,
});
bool get isError => errorMessage != null;
@ -242,12 +478,13 @@ OffbandUiReply? parseButtonMatrixReply(Uint8List frame) {
final sub = frame[1];
if (sub == offbandUiErr) {
final code = frame.length >= 3 ? frame[2] : 0x00;
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
errorMessage: ButtonConfigError.describe(
frame.length >= 3 ? frame[2] : 0x00,
),
errorMessage: ButtonConfigError.describe(code),
errorCode: code,
errorDetail: frame.length >= 4 ? frame[3] : null,
);
}
@ -316,3 +553,59 @@ OffbandUiReply? parseNotifyScopeReply(Uint8List frame) {
scope: scope,
);
}
/// Parse a `0xC5` channel-tune reply (0x0B or 0x0C). Null if this is not one,
/// or if it is truncated. Any stored byte is a valid value; which ones the
/// badge's picker offers is the firmware's to enforce, and it refuses the rest.
OffbandUiReply? parseChannelTuneReply(Uint8List frame) {
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
final sub = frame[1];
if (sub != offbandUiChannelTuneGet && sub != offbandUiChannelTuneSet) {
return null;
}
if (frame.length < 4) return null;
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
channelTune: ChannelTuneReply(
channel: frame[2],
tune: ChannelTune.fromStored(frame[3]),
),
);
}
/// Parse a `0xC5` GPS-mode reply (0x0D or 0x0E). Null if this is not one, or
/// if it is shorter than the 14 bytes the contract fixes: a partial state is
/// never shown as if it were the device's.
///
/// The shared 0x7F error is owned by [parseButtonMatrixReply], as for scope.
OffbandUiReply? parseGpsModeReply(Uint8List frame) {
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
final sub = frame[1];
if (sub != offbandUiGpsGet && sub != offbandUiGpsSet) return null;
if (frame.length < _gpsReplyLength) return null;
final mode = GpsMode.fromCode(frame[2]);
if (mode == null) {
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
errorMessage:
'The radio reported an unknown GPS mode '
'(0x${frame[2].toRadixString(16).padLeft(2, '0')})',
);
}
final data = ByteData.sublistView(frame);
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
gps: GpsModeState(
mode: mode,
storedMode: frame[3],
powerSaveAvailable: frame[4] != 0,
activity: GpsActivity.fromCode(frame[5]),
intervalSeconds: data.getUint32(6, Endian.little),
waitSeconds: data.getUint32(10, Endian.little),
),
);
}

@ -0,0 +1,150 @@
import 'dart:typed_data';
import 'offband_device_ui.dart';
/// The badge's own display and battery settings over `0xC5` (#987): both
/// text sizes, Screen off, time zone and the battery full point. Gated on caps
/// byte 2 `0x40` SCREEN_SETTINGS (meshcore-firmware `f3d30a88`).
///
/// Every reply, GET or SET, is the whole set re-read after the write:
/// `[0xC5][sub][nav][msg][scr_stored:2][scr_secs:2][tz][batt_stored:2]
/// [batt_full:2][batt_pinned]`, 14 bytes, all little-endian.
const int offbandUiScreenGet = 0x13;
const int offbandUiTextSet = 0x14;
const int offbandUiScreenOffSet = 0x15;
const int offbandUiTimeZoneSet = 0x16;
const int offbandUiBatterySet = 0x17;
const int _screenReplyLength = 14;
/// The three text sizes, in firmware's encoding (`BadgeLayout.h`).
enum BadgeTextSize {
large(0, 'Large'),
medium(1, 'Medium'),
small(2, 'Small');
const BadgeTextSize(this.code, this.label);
final int code;
final String label;
static BadgeTextSize? fromCode(int code) {
for (final s in BadgeTextSize.values) {
if (s.code == code) return s;
}
return null;
}
}
/// Which text size a TEXT_SET changes: the badge's Nav text or Message text.
enum BadgeTextTarget {
navigation(0),
messages(1);
const BadgeTextTarget(this.code);
final int code;
}
/// The Screen off steps the badge's row cycles through (`kScreenOffSteps`).
/// Firmware accepts exactly these and nothing else.
const List<int> screenOffSteps = [15, 30, 60, 120, 300];
String screenOffLabel(int secs) => secs < 60
? '$secs s'
: '${secs ~/ 60} m${secs % 60 == 0 ? '' : ' ${secs % 60} s'}';
/// The radio's screen and battery settings, from any `0x13` to `0x17` reply.
class ScreenSettingsState {
const ScreenSettingsState({
required this.navText,
required this.messageText,
required this.screenOffStored,
required this.screenOffSeconds,
required this.timeZone,
required this.batteryFullStored,
required this.batteryFullMv,
required this.batteryPinned,
});
/// Null when a newer firmware reports a size this client does not know.
final BadgeTextSize? navText;
final BadgeTextSize? messageText;
/// The Screen off preference in seconds; 0 means the board's compiled
/// timeout, which [screenOffSeconds] then reports.
final int screenOffStored;
final int screenOffSeconds;
/// Index into the badge's zone table; 0 is not set.
final int timeZone;
/// The learned or pinned full point in mV, 0 when there is neither.
final int batteryFullStored;
/// The mV the radio's battery bar treats as 100%.
final int batteryFullMv;
/// Set by hand, which auto-learn leaves alone.
final bool batteryPinned;
bool get screenOffIsDefault => screenOffStored == 0;
}
Uint8List buildScreenSettingsGetFrame() =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiScreenGet]);
Uint8List buildTextSizeSetFrame(BadgeTextTarget target, BadgeTextSize size) =>
Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiTextSet,
target.code,
size.code,
]);
Uint8List buildScreenOffSetFrame(int seconds) {
if (seconds < 0 || seconds > 0xFFFF) {
throw ArgumentError.value(seconds, 'seconds', 'must be 0 to 65535');
}
return Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiScreenOffSet,
seconds & 0xFF,
seconds >> 8,
]);
}
Uint8List buildTimeZoneSetFrame(int index) {
if (index < 0 || index > 0xFF) {
throw ArgumentError.value(index, 'index', 'must be 0 to 255');
}
return Uint8List.fromList([cmdOffbandDeviceUi, offbandUiTimeZoneSet, index]);
}
/// `pin` true pins the radio's own current reading as 100%; false hands the
/// full point back to auto-learn.
Uint8List buildBatteryFullSetFrame({required bool pin}) =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiBatterySet, pin ? 1 : 0]);
/// Parse a screen-settings reply. Null if this is not one, or if it is
/// shorter than the 14 bytes the contract fixes. The shared 0x7F error is
/// owned by [parseButtonMatrixReply].
OffbandUiReply? parseScreenSettingsReply(Uint8List frame) {
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
final sub = frame[1];
if (sub < offbandUiScreenGet || sub > offbandUiBatterySet) return null;
if (frame.length < _screenReplyLength) return null;
final data = ByteData.sublistView(frame);
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
screen: ScreenSettingsState(
navText: BadgeTextSize.fromCode(frame[2]),
messageText: BadgeTextSize.fromCode(frame[3]),
screenOffStored: data.getUint16(4, Endian.little),
screenOffSeconds: data.getUint16(6, Endian.little),
timeZone: frame[8],
batteryFullStored: data.getUint16(9, Endian.little),
batteryFullMv: data.getUint16(11, Endian.little),
batteryPinned: frame[13] != 0,
),
);
}

@ -0,0 +1,452 @@
import 'dart:typed_data';
import 'offband_device_ui.dart';
/// The radio's tune system over `0xC5` (#970, #971, #986): the built-in tune
/// table, the eight custom RTTTL slots, the six event tones and preview.
///
/// Gated on caps byte 2 `0x10` TUNES (meshcore-firmware `f3d30a88`). The
/// contract lives in firmware's `OffbandConfigProtocol.h`; the tables and the
/// validator below are ports of `Tunes.h` and `TuneSlots.h` at that commit.
const int offbandUiSlotGet = 0x09;
const int offbandUiSlotSet = 0x0A;
const int offbandUiEventToneGet = 0x0F;
const int offbandUiEventToneSet = 0x10;
const int offbandUiTunePlay = 0x11;
const int offbandUiSlotRead = 0x12;
/// The built-in tunes, by id. Firmware's table is append-only, so this copy
/// can only fall behind, never misname an id. A null name is a tune firmware
/// keeps out of its own picker (id 7, Trigger), so it is never offered here.
const List<String?> builtinTuneNames = [
'Silent',
'Chime',
'Kerplop',
'Tick',
'Bloop',
'Drop',
'Knock',
null,
];
const int tuneSilent = 0;
const int builtinTuneCount = 8;
const int tuneSlotCount = 8;
const int firstSlotTuneId = builtinTuneCount;
/// The longest RTTTL a slot holds (`kMaxRtttl`) and the longest name a slot
/// shows (`kMaxSlotName`).
const int maxSlotRtttl = 240;
const int maxSlotName = 12;
bool isSlotTuneId(int id) =>
id >= firstSlotTuneId && id < firstSlotTuneId + tuneSlotCount;
int slotTuneId(int slot) => firstSlotTuneId + slot;
/// Built-in ids the badge's picker lists, in its order.
List<int> get listedBuiltinTuneIds => [
for (var id = 0; id < builtinTuneNames.length; id++)
if (builtinTuneNames[id] != null) id,
];
/// One of the six events the badge's Tones screen sets. Values are firmware's
/// `offband::ToneEvent`, and the labels are the badge's own (`kToneEventRows`).
enum ToneEvent {
dm(0, 'DM'),
channel(1, 'Channel'),
room(2, 'Room'),
newContact(3, 'New contact'),
ack(4, 'Ack'),
sent(5, 'Sent');
const ToneEvent(this.code, this.label);
final int code;
final String label;
static ToneEvent? fromCode(int code) {
for (final e in ToneEvent.values) {
if (e.code == code) return e;
}
return null;
}
}
/// Stored byte meaning "nothing chosen": the board's compiled default plays.
const int tuneUnset = 0xFF;
/// An event's tune as the radio reports it. [effective] is what plays.
class EventToneState {
const EventToneState({required this.stored, required this.effective});
final int stored;
final int effective;
bool get isRadioDefault => stored == tuneUnset;
}
class EventToneReply {
const EventToneReply({required this.event, required this.state});
final ToneEvent event;
final EventToneState state;
}
/// What a custom slot holds, from `SLOT_GET`: its length and derived name,
/// never the tune itself. Length 0 is an empty slot.
class TuneSlotInfo {
const TuneSlotInfo({required this.length, required this.name});
final int length;
final String name;
bool get isEmpty => length == 0;
}
class TuneSlotReply {
const TuneSlotReply({required this.slot, required this.info});
final int slot;
final TuneSlotInfo info;
}
/// `SLOT_SET` progress: how many bytes the radio holds for the push in flight.
class TuneSlotAccepted {
const TuneSlotAccepted({required this.slot, required this.accepted});
final int slot;
final int accepted;
}
/// One `SLOT_READ` chunk.
class TuneSlotChunk {
const TuneSlotChunk({
required this.slot,
required this.offset,
required this.more,
required this.bytes,
});
final int slot;
final int offset;
final bool more;
final Uint8List bytes;
}
/// Why a preview did or did not sound (`offband::TonePlay`).
enum TunePlayResult {
played(0),
busy(1),
soundOff(2);
const TunePlayResult(this.code);
final int code;
static TunePlayResult? fromCode(int code) {
for (final r in TunePlayResult.values) {
if (r.code == code) return r;
}
return null;
}
}
class TunePlayReply {
const TunePlayReply({required this.tuneId, required this.result});
final int tuneId;
/// Null when a newer firmware reports a result this client does not know.
final TunePlayResult? result;
}
/// What the client knows of a radio's tunes, for naming an id.
///
/// [slots] holds the `SLOT_GET` replies read so far, by slot index.
String? tuneLabel(int id, Map<int, TuneSlotInfo> slots) {
if (id >= 0 && id < builtinTuneNames.length) return builtinTuneNames[id];
if (isSlotTuneId(id)) {
final info = slots[id - firstSlotTuneId];
if (info == null || info.isEmpty) return null;
return info.name.isEmpty ? 'Slot ${id - firstSlotTuneId + 1}' : info.name;
}
return null;
}
/// The ids a picker may offer: firmware's rule, a named built-in or a filled
/// slot. Firmware refuses everything else, so nothing else is shown.
List<int> offeredTuneIds(Map<int, TuneSlotInfo> slots) => [
...listedBuiltinTuneIds,
for (var s = 0; s < tuneSlotCount; s++)
if (slots[s] != null && !slots[s]!.isEmpty) slotTuneId(s),
];
Uint8List buildEventToneGetFrame(ToneEvent event) =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiEventToneGet, event.code]);
Uint8List buildEventToneSetFrame(ToneEvent event, int tuneId) =>
Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiEventToneSet,
event.code,
_byte(tuneId, 'tuneId'),
]);
Uint8List buildTunePlayFrame(int tuneId) => Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiTunePlay,
_byte(tuneId, 'tuneId'),
]);
Uint8List buildSlotGetFrame(int slot) =>
Uint8List.fromList([cmdOffbandDeviceUi, offbandUiSlotGet, _slotByte(slot)]);
Uint8List buildSlotReadFrame(int slot, int offset) => Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiSlotRead,
_slotByte(slot),
_byte(offset, 'offset'),
]);
/// `[0xC5][0x0A][slot][offset][more][bytes...]`. An empty final chunk at
/// offset 0 clears the slot.
Uint8List buildSlotSetFrame(int slot, int offset, bool more, List<int> bytes) =>
Uint8List.fromList([
cmdOffbandDeviceUi,
offbandUiSlotSet,
_slotByte(slot),
_byte(offset, 'offset'),
more ? 1 : 0,
...bytes,
]);
int _slotByte(int slot) {
if (slot < 0 || slot >= tuneSlotCount) {
throw ArgumentError.value(
slot,
'slot',
'must be 0 to ${tuneSlotCount - 1}',
);
}
return slot;
}
int _byte(int value, String name) {
if (value < 0 || value > 0xFF) {
throw ArgumentError.value(value, name, 'must be 0 to 255');
}
return value;
}
/// Parse a tune reply (0x09, 0x0A, 0x0F, 0x10, 0x11, 0x12). Null if this is
/// not one, or if it is truncated. The shared 0x7F error is owned by
/// [parseButtonMatrixReply].
OffbandUiReply? parseTuneReply(Uint8List frame) {
if (frame.length < 2 || frame[0] != respCodeOffbandDeviceUi) return null;
final sub = frame[1];
OffbandUiReply reply({
EventToneReply? eventTone,
TuneSlotReply? slot,
TuneSlotAccepted? accepted,
TuneSlotChunk? chunk,
TunePlayReply? play,
}) => OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
eventTone: eventTone,
tuneSlot: slot,
slotAccepted: accepted,
slotChunk: chunk,
tunePlay: play,
);
switch (sub) {
case offbandUiEventToneGet:
case offbandUiEventToneSet:
if (frame.length < 5) return null;
final event = ToneEvent.fromCode(frame[2]);
if (event == null) {
return OffbandUiReply(
command: respCodeOffbandDeviceUi,
sub: sub,
errorMessage:
'The radio reported an unknown tone event (${frame[2]})',
);
}
return reply(
eventTone: EventToneReply(
event: event,
state: EventToneState(stored: frame[3], effective: frame[4]),
),
);
case offbandUiSlotGet:
if (frame.length < 4) return null;
// The name is the rest of the frame, at most what the transport carried.
final name = String.fromCharCodes(frame.sublist(4));
return reply(
slot: TuneSlotReply(
slot: frame[2],
info: TuneSlotInfo(length: frame[3], name: name),
),
);
case offbandUiSlotSet:
if (frame.length < 4) return null;
return reply(
accepted: TuneSlotAccepted(slot: frame[2], accepted: frame[3]),
);
case offbandUiSlotRead:
if (frame.length < 5) return null;
return reply(
chunk: TuneSlotChunk(
slot: frame[2],
offset: frame[3],
more: frame[4] != 0,
bytes: Uint8List.fromList(frame.sublist(5)),
),
);
case offbandUiTunePlay:
if (frame.length < 4) return null;
return reply(
play: TunePlayReply(
tuneId: frame[2],
result: TunePlayResult.fromCode(frame[3]),
),
);
}
return null;
}
/// Why an RTTTL string is not safe to play, as firmware's `rtttlProblem()`
/// judges it. The same rule runs on the badge's editor and on every pushed
/// tune, so the app checks with it before sending: the radio can only answer
/// "malformed", and this says why.
enum RtttlProblem {
ok('OK'),
empty('Empty'),
noName('Needs a name'),
missingColon('Needs name:notes'),
badDefault('Bad d=, o= or b='),
zeroTempo('b= must be 1 or more'),
noNotes('No notes'),
ambiguousNote('Add d=, o= or b= first'),
strayColon('Bad name or d=/o=/b=');
const RtttlProblem(this.text);
/// Firmware's own words (`rtttlProblemText`), so the app and the badge
/// describe the same problem the same way.
final String text;
}
bool _isDigit(int c) => c >= 0x30 && c <= 0x39;
bool _isDefaultsSep(int c) => c == 0x2C || c == 0x3A;
const int _colon = 0x3A;
/// Port of firmware `rtttlProblem()` (`Tunes.h`, `f3d30a88`), step for step.
RtttlProblem rtttlProblem(String rtttl) {
final s = rtttl.codeUnits;
if (s.isEmpty) return RtttlProblem.empty;
int at(int i) => i < s.length ? s[i] : 0;
var p = 0;
while (at(p) != 0 && at(p) != _colon) {
p++;
}
if (at(p) == 0) return RtttlProblem.missingColon;
if (p == 0) return RtttlProblem.noName;
p++;
var sawDefault = false;
if (at(p) == 0x64 && at(p + 1) == 0x3D) {
p += 2;
var digits = 0;
while (_isDigit(at(p))) {
p++;
digits++;
}
if (digits == 0 || digits > 4) return RtttlProblem.badDefault;
if (!_isDefaultsSep(at(p))) return RtttlProblem.badDefault;
p++;
sawDefault = true;
}
if (at(p) == 0x6F && at(p + 1) == 0x3D) {
if (!_isDigit(at(p + 2))) return RtttlProblem.badDefault;
if (!_isDefaultsSep(at(p + 3))) return RtttlProblem.badDefault;
p += 4;
sawDefault = true;
}
if (at(p) == 0x62 && at(p + 1) == 0x3D) {
p += 2;
var digits = 0;
var bpm = 0;
while (_isDigit(at(p))) {
if (digits < 5) bpm = bpm * 10 + (at(p) - 0x30);
p++;
digits++;
}
if (digits == 0) return RtttlProblem.zeroTempo;
if (digits > 4) return RtttlProblem.badDefault;
if (bpm == 0) return RtttlProblem.zeroTempo;
if (!_isDefaultsSep(at(p))) return RtttlProblem.badDefault;
p++;
sawDefault = true;
}
if (at(p) == 0) return RtttlProblem.noNotes;
final c = at(p);
if (!sawDefault && (c == 0x64 || c == 0x6F || c == 0x62)) {
return RtttlProblem.ambiguousNote;
}
for (var q = p; q < s.length; q++) {
if (s[q] == _colon) return RtttlProblem.strayColon;
}
return RtttlProblem.ok;
}
/// The tune with its defaults rewritten into the order the badge's player
/// reads them (d=, o=, b=, each once), or null when that is not the fix.
///
/// The player reads defaults positionally, so RTTTL from elsewhere that lists
/// them in another order, or repeats one, is refused as a stray colon. This
/// rewrites only the header between the first two colons, and only when every
/// item there is a d=, o= or b= and a repeated key repeats the same value: two
/// different tempos are a choice the app cannot make for the user. The result
/// must pass [rtttlProblem], so a header fix never hides a second problem.
String? fixRtttlDefaultsOrder(String rtttl) {
if (rtttlProblem(rtttl) == RtttlProblem.ok) return null;
final first = rtttl.indexOf(':');
if (first < 0) return null;
final second = rtttl.indexOf(':', first + 1);
if (second < 0) return null;
final values = <String, String>{};
for (final raw in rtttl.substring(first + 1, second).split(',')) {
final item = raw.trim();
final eq = item.indexOf('=');
if (eq != 1) return null;
final key = item[0];
final value = item.substring(2).trim();
if (!const {'d', 'o', 'b'}.contains(key) || value.isEmpty) return null;
final held = values[key];
if (held != null && held != value) return null;
values[key] = value;
}
final header = [
for (final k in const ['d', 'o', 'b'])
if (values[k] != null) '$k=${values[k]}',
].join(',');
final fixed =
'${rtttl.substring(0, first)}:$header:${rtttl.substring(second + 1)}';
if (fixed == rtttl || rtttlProblem(fixed) != RtttlProblem.ok) return null;
return fixed;
}
/// Port of firmware `deriveSlotName()`: the text before the first colon,
/// trimmed and cut to [maxSlotName]. Empty when there is no usable name.
String deriveSlotName(String rtttl) {
final colon = rtttl.indexOf(':');
if (colon < 0) return '';
var name = rtttl
.substring(0, colon)
.replaceAll(RegExp(r'^[ \t]+|[ \t]+$'), '');
if (name.length > maxSlotName) name = name.substring(0, maxSlotName);
return name;
}

@ -0,0 +1,36 @@
/// The budget for automatic reconnects after a link drops (#997).
///
/// An automatic retry stops after [maxAttempts] attempts, or once the next one
/// would start more than [window] after the first, whichever comes first.
/// Only [reset] clears the count: an automatic attempt must never reset it,
/// which is what let the client retry an unreachable radio for hours (#995).
class ReconnectPolicy {
ReconnectPolicy({
this.maxAttempts = 5,
this.window = const Duration(minutes: 3),
});
final int maxAttempts;
final Duration window;
int _attempts = 0;
DateTime? _startedAt;
/// Attempts scheduled since the last [reset].
int get attempts => _attempts;
/// The delay before the next attempt, or null when the budget is spent.
Duration? nextDelay(DateTime now) {
if (_attempts >= maxAttempts) return null;
final startedAt = _startedAt ??= now;
final delay = Duration(seconds: 1 << _attempts);
if (now.add(delay).difference(startedAt) >= window) return null;
_attempts += 1;
return delay;
}
void reset() {
_attempts = 0;
_startedAt = null;
}
}

@ -0,0 +1,27 @@
// Mirrors the firmware's `set name` character rejection on the client (#885,
// interop plan F2/E2.1). The companion CommonCLI rejects these characters in a
// device name [verified: companion built-ins, INVESTIGATION.md section A], and
// a name carrying one comes back as a cryptic `ERROR` from the device. Catching
// it client-side lets the UI say exactly what is wrong before anything is sent.
//
// The device stays the authority: this is a convenience check, not a
// replacement for the device's own validation.
/// Characters the firmware's `set name` rejects.
const List<String> forbiddenDeviceNameChars = <String>[
'[',
']',
'\\',
':',
',',
'?',
'*',
];
/// The distinct forbidden characters present in [name], in the order they
/// appear in [forbiddenDeviceNameChars]. Empty when the name is valid.
List<String> forbiddenCharsIn(String name) =>
forbiddenDeviceNameChars.where(name.contains).toList();
/// True when [name] carries none of the forbidden characters.
bool isValidDeviceName(String name) => forbiddenCharsIn(name).isEmpty;

@ -0,0 +1,49 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:crypto/crypto.dart';
/// Region transport-key derivation, matching the MeshCore firmware
/// (`RegionMap.getTransportKeysFor` -> `TransportKeyStore.getAutoKeyFor`).
///
/// A public "hashtag" region's transport key is the first 16 bytes of
/// `SHA256` of the region name carrying exactly one leading `#`: auto-hashtag
/// names are hashed as stored, bare names get a `#` prepended. `$`-prefixed
/// regions are private, their keys live in a hardware keystore and are not
/// derivable from the name. Names discovered over the air arrive `#`-stripped,
/// so the client re-adds the `#` here.
const int _keyLength = 16;
/// True for a private (`$`-prefixed) region, whose key is not name-derivable.
bool isPrivateRegionName(String name) => name.trim().startsWith(r'$');
/// The region name as the firmware hashes it: exactly one leading `#`.
String normalizeHashtag(String name) {
final stripped = name.trim().replaceFirst(RegExp(r'^#+'), '');
return '#$stripped';
}
/// First 16 bytes of `SHA256("#"+name)`.
///
/// Returns null when [name] is blank or a private (`$`) region.
Uint8List? transportKeyForName(String name) {
final trimmed = name.trim();
if (trimmed.isEmpty || isPrivateRegionName(trimmed)) return null;
final digest = sha256.convert(utf8.encode(normalizeHashtag(trimmed))).bytes;
return Uint8List.fromList(digest.sublist(0, _keyLength));
}
/// The 2-byte on-air transport code the firmware stamps on a scoped packet:
/// `HMAC-SHA256(key, payloadType || payload)`, first two bytes read as a
/// little-endian `uint16` (firmware `TransportKey::calcTransportCode`).
int onAirCode(Uint8List key, int payloadType, Uint8List payload) {
final mac = Hmac(sha256, key).convert(<int>[payloadType, ...payload]).bytes;
return reserveTransportCode(mac[0] | (mac[1] << 8));
}
/// Firmware reserves `0x0000` and `0xFFFF`, bumping each by one.
int reserveTransportCode(int code) {
if (code == 0x0000) return 0x0001;
if (code == 0xFFFF) return 0xFFFE;
return code;
}

@ -24,6 +24,7 @@
"common_share": "Share",
"common_copy": "Copy",
"common_retry": "Retry",
"common_stop": "Stop",
"common_hide": "Hide",
"common_remove": "Remove",
"common_enable": "Enable",
@ -112,6 +113,29 @@
"scanner_connecting": "Connecting...",
"scanner_disconnecting": "Disconnecting...",
"scanner_notConnected": "Not connected",
"scanner_reconnecting": "Reconnecting to {deviceName} (attempt {attempt} of {maxAttempts})",
"@scanner_reconnecting": {
"placeholders": {
"deviceName": {
"type": "String"
},
"attempt": {
"type": "int"
},
"maxAttempts": {
"type": "int"
}
}
},
"scanner_reconnectGaveUp": "Couldn't reach {deviceName}",
"@scanner_reconnectGaveUp": {
"placeholders": {
"deviceName": {
"type": "String"
}
}
},
"connectBusy": "Busy with another connection. Try again in a moment.",
"scanner_connectedTo": "Connected to {deviceName}",
"@scanner_connectedTo": {
"placeholders": {
@ -159,6 +183,74 @@
"scanner_enableBluetooth": "Enable Bluetooth",
"device_quickSwitch": "Quick switch",
"device_meshcore": "MeshCore",
"deviceCli_title": "Device CLI",
"deviceCli_remoteTitle": "Remote CLI",
"@deviceCli_remoteTitle": {
"description": "Title of the CLI console when it targets a remote companion contact (#999); the contact's name is the subtitle."
},
"deviceCli_entrySubtitle": "Run commands on the connected radio",
"deviceCli_nameRejected": "Not sent - name can't contain: {chars}",
"@deviceCli_nameRejected": {
"description": "Console row when a `set name` command is blocked client-side; {chars} is the offending characters, space-separated.",
"placeholders": {
"chars": {
"type": "String"
}
}
},
"deviceCli_commandHint": "command...",
"deviceCli_emptyHint": "Commands run on the connected device",
"deviceCli_noReply": "{command}: no reply in {seconds} s",
"@deviceCli_noReply": {
"placeholders": {
"command": {
"type": "String"
},
"seconds": {
"type": "String"
}
}
},
"deviceCli_remoteNoReply": "{command}: no reply in {seconds} s. This radio may not allow remote CLI from you, or is unreachable. Not retried.",
"@deviceCli_remoteNoReply": {
"description": "Console row when a remote-CLI command to a companion times out (#891). A companion that has not granted remote CLI simply never replies, so this explains the silence and that the command was sent once, not retried.",
"placeholders": {
"command": {
"type": "String"
},
"seconds": {
"type": "String"
}
}
},
"deviceCli_remoteUnsupported": "{command}: not sent. Your radio's firmware doesn't support remote CLI.",
"@deviceCli_remoteUnsupported": {
"description": "Console row when the connected radio refuses to send a remote-CLI command because its firmware predates TXT_TYPE_CLI_COMMAND (#999). Nothing was transmitted.",
"placeholders": {
"command": {
"type": "String"
}
}
},
"deviceCli_sendFailed": "Send failed: {error}",
"@deviceCli_sendFailed": {
"placeholders": {
"error": {
"type": "String"
}
}
},
"deviceCli_truncatedByDevice": "reply truncated by the device",
"deviceCli_secretLongPressToCopy": "secret, long-press to copy",
"deviceCli_secretCopied": "Secret copied to clipboard",
"deviceCli_latencyMs": "{ms} ms",
"@deviceCli_latencyMs": {
"placeholders": {
"ms": {
"type": "int"
}
}
},
"settings_title": "Settings",
"settings_deviceInfo": "Device Info",
"settings_appSettings": "App Settings",
@ -176,6 +268,18 @@
"settings_nodeNameNotSet": "Not set",
"settings_nodeNameHint": "Enter node name",
"settings_nodeNameUpdated": "Name updated",
"settings_nodeNameInvalidChars": "Name can't contain: {chars}",
"@settings_nodeNameInvalidChars": {
"description": "Shown when a device name contains characters the firmware rejects; {chars} is the offending characters, space-separated.",
"placeholders": {
"chars": {
"type": "String"
}
}
},
"settings_syncQueuedMessages": "Sync queued messages now",
"settings_syncQueuedMessagesSubtitle": "Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.",
"settings_syncQueuedMessagesRequested": "Requested queued-message drain (force)",
"settings_radioSettings": "Radio Settings",
"settings_radioSettingsSubtitle": "Frequency, power, spreading factor",
"settings_radioSettingsUpdated": "Radio settings updated",
@ -200,6 +304,91 @@
"settings_locationIntervalInvalid": "Interval must be at least 60 seconds, and less than 86400 seconds.",
"settings_latitude": "Latitude",
"settings_longitude": "Longitude",
"settings_locationCategorySubtitle": "GPS, coordinates, and reporting",
"settings_locationCoordinates": "Coordinates",
"settings_locationNotSet": "Not set",
"settings_locationReportInterval": "Position reporting interval",
"settings_locationEveryMinutes": "{minutes, plural, =1{Every minute} other{Every {minutes} minutes}}",
"@settings_locationEveryMinutes": {
"placeholders": {
"minutes": {
"type": "int"
}
}
},
"settings_locationEverySeconds": "Every {seconds} seconds",
"@settings_locationEverySeconds": {
"placeholders": {
"seconds": {
"type": "int"
}
}
},
"settings_gpsModeLabel": "GPS",
"settings_gpsModeOff": "Off",
"settings_gpsModeOn": "On",
"settings_gpsModePowerSave": "Power save",
"settings_gpsActivityOff": "GPS is off",
"settings_gpsActivityOn": "GPS is on",
"settings_gpsActivitySearching": "Searching for a fix",
"settings_gpsActivitySleeping": "Sleeping between fixes",
"settings_gpsActivityBackedOff": "Backed off",
"settings_gpsOffDetail": "Showing the last stored position",
"settings_gpsNextTryMinutes": "{minutes, plural, =1{Next try in 1 min} other{Next try in {minutes} min}}",
"@settings_gpsNextTryMinutes": {
"placeholders": {
"minutes": {
"type": "int"
}
}
},
"settings_gpsNextTrySeconds": "Next try in {seconds} s",
"@settings_gpsNextTrySeconds": {
"placeholders": {
"seconds": {
"type": "int"
}
}
},
"settings_gpsLastFixMinutes": "{minutes, plural, =0{Last fix just now} =1{Last fix 1 min ago} other{Last fix {minutes} min ago}}",
"@settings_gpsLastFixMinutes": {
"placeholders": {
"minutes": {
"type": "int"
}
}
},
"settings_gpsSatellites": "{count, plural, =1{1 satellite} other{{count} satellites}}",
"@settings_gpsSatellites": {
"placeholders": {
"count": {
"type": "int"
}
}
},
"settings_gpsQuery": "Query",
"settings_gpsReading": "Reading GPS settings…",
"settings_gpsSleepTitle": "Sleep between fix attempts",
"settings_gpsSleepDefault": "Firmware default, minimum 5 minutes",
"settings_gpsSleepFieldLabel": "Seconds between attempts",
"settings_gpsSleepFieldHint": "0 for the firmware default. The radio raises anything under 300 to 300.",
"settings_gpsSleepInvalid": "Enter a whole number of seconds, 0 or more.",
"settings_buttonActions": "Button actions",
"settings_buttonActionsSubtitle": "Assign what the button does",
"settings_badgeScreen": "Screen",
"settings_badgeScreenSubtitle": "Text size, screen off, time zone",
"settings_badgeBattery": "Battery",
"settings_badgeBatterySubtitle": "100% at {mv} mV",
"@settings_badgeBatterySubtitle": {
"placeholders": {
"mv": {
"type": "int"
}
}
},
"settings_badgeBatteryReading": "Reading from the radio",
"settings_buzzerTones": "Buzzer and tones",
"settings_buzzerTonesSubtitle": "When this radio beeps",
"settings_contactSettings": "Contact Settings",
"settings_contactSettingsSubtitle": "Settings for how contacts are added.",
"settings_privacyMode": "Privacy Mode",
@ -598,6 +787,27 @@
}
},
"contact_info": "Contact Info",
"contact_rename": "Rename",
"contact_renameTitle": "Custom name",
"contact_renameHint": "Your name for this node",
"contact_renameExplain": "Only you see this. The node keeps its own name, and adverts keep that up to date.",
"contact_renameClear": "Clear",
"contact_renameTooLong": "Keep it under {max} characters",
"@contact_renameTooLong": {
"placeholders": {
"max": {
"type": "int"
}
}
},
"contact_nodeCallsItself": "Node name: {name}",
"@contact_nodeCallsItself": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"contact_settings": "Contact Settings",
"contact_telemetry": "Telemetry",
"contact_lastSeen": "Last seen",
@ -608,6 +818,12 @@
"contact_teleLocSubtitle": "Allow sharing location data",
"contact_teleEnv": "Telemetry Environment",
"contact_teleEnvSubtitle": "Allow sharing environment sensor data",
"contact_remoteCli": "Remote CLI",
"contact_remoteCliSubtitle": "Let this contact run CLI commands on your radio",
"contact_cliConsole": "CLI console",
"@contact_cliConsole": {
"description": "Chat app-bar menu action on a companion contact that opens the remote CLI console targeting that contact (#999)."
},
"channels_title": "Channels",
"channels_noChannelsConfigured": "No channels configured",
"channels_addPublicChannel": "Add Public Channel",
@ -2849,6 +3065,8 @@
"block_settingsTitle": "Blocked",
"block_settingsSubtitle": "Users you've blocked",
"block_none": "No blocked users",
"block_noRadio": "No radio connected",
"block_noRadioHint": "Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.",
"block_keysSection": "Blocked contacts",
"block_namesSection": "Blocked names",
"block_namesHint": "Name-only blocks (channel senders). Each upgrades to a full block once we learn their key.",
@ -3189,5 +3407,139 @@
"type": "int"
}
}
},
"discoverRegions_title": "Discover Regions",
"discoverRegions_subtitle": "Find the flood regions this repeater carries.",
"discoverRegions_loading": "Discovering regions from {name}...",
"@discoverRegions_loading": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"discoverRegions_source": "Regions carried by {name}",
"@discoverRegions_source": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"discoverRegions_empty": "{name} advertises no flood regions.",
"@discoverRegions_empty": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"discoverRegions_timeout": "No response from {name}. The repeater may be out of range.",
"@discoverRegions_timeout": {
"placeholders": {
"name": {
"type": "String"
}
}
},
"discoverRegions_error": "Could not discover regions.",
"discoverRegions_retry": "Retry",
"setRegionScope_menu": "Set Region Scope",
"setRegionScope_title": "Region scope for {channel}",
"@setRegionScope_title": {
"placeholders": {
"channel": {
"type": "String"
}
}
},
"setRegionScope_discover": "Discover from repeater",
"setRegionScope_none": "None (unscoped)",
"setRegionScope_save": "Save",
"setRegionScope_searchRepeaters": "Search repeaters",
"setRegionScope_pathNote": "You can only discover regions from a repeater you have a stored path to.",
"setRegionScope_noPath": "No stored path",
"storage_title": "Storage",
"storage_databaseSize": "Message database: {size}",
"@storage_databaseSize": {
"description": "Current size of the message database on this device (#962).",
"placeholders": {
"size": {
"type": "String"
}
}
},
"storage_staleHint": "When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.",
"@storage_staleHint": {
"description": "Explains what the Clear Stale History action does (#962)."
},
"storage_clearStaleNow": "Clear Stale History Now",
"storage_working": "Clearing...",
"storage_resultNothing": "Nothing to clear.",
"storage_resultCleared": "Cleared {count} old copies, {size} returned.",
"@storage_resultCleared": {
"description": "Result of a successful stale-history clear (#962).",
"placeholders": {
"count": {
"type": "int"
},
"size": {
"type": "String"
}
}
},
"storage_resultRefused": "Kept {count} that could not be verified. Your messages are intact; nothing was deleted for those.",
"@storage_resultRefused": {
"description": "Reported when the clear kept a copy back because its messages could not be verified against the new format (#962, owner decision: the button reports refusals rather than only logging them).",
"placeholders": {
"count": {
"type": "int"
}
}
},
"storage_confirmTitle": "Clear stale history?",
"storage_confirmBody": "This removes {count} old copies of history that has already moved to the new format, freeing about {size}.",
"@storage_confirmBody": {
"description": "Body of the confirmation shown before clearing stale history. The size is approximate because VACUUM's real figure depends on page rounding (#962).",
"placeholders": {
"count": {
"type": "int"
},
"size": {
"type": "String"
}
}
},
"storage_confirmSafe": "Your messages are not affected. All {count} stay.",
"@storage_confirmSafe": {
"description": "Reassurance in the clear confirmation: this deletes duplicate copies, not history (#962).",
"placeholders": {
"count": {
"type": "int"
}
}
},
"storage_confirmIrreversible": "This cannot be undone.",
"storage_confirmKeptBack": "{count} will be kept back because its messages could not be verified. This cannot be undone.",
"@storage_confirmKeptBack": {
"description": "Shown when the preview already knows a copy will be refused, so the user hears it before the press rather than after (#962).",
"placeholders": {
"count": {
"type": "int"
}
}
},
"storage_confirmAction": "Clear {count} copies",
"@storage_confirmAction": {
"description": "Confirm button. Carries the count so the scope is the last thing read before the tap (#962).",
"placeholders": {
"count": {
"type": "int"
}
}
},
"storage_resultFailed": "Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.",
"@storage_resultFailed": {
"description": "Shown when the clear threw. It must not claim nothing happened, because the sweep deletes per key and may have cleared some before failing (#962)."
}
}

@ -274,6 +274,12 @@ abstract class AppLocalizations {
/// **'Retry'**
String get common_retry;
/// No description provided for @common_stop.
///
/// In en, this message translates to:
/// **'Stop'**
String get common_stop;
/// No description provided for @common_hide.
///
/// In en, this message translates to:
@ -592,6 +598,24 @@ abstract class AppLocalizations {
/// **'Not connected'**
String get scanner_notConnected;
/// No description provided for @scanner_reconnecting.
///
/// In en, this message translates to:
/// **'Reconnecting to {deviceName} (attempt {attempt} of {maxAttempts})'**
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts);
/// No description provided for @scanner_reconnectGaveUp.
///
/// In en, this message translates to:
/// **'Couldn\'t reach {deviceName}'**
String scanner_reconnectGaveUp(String deviceName);
/// No description provided for @connectBusy.
///
/// In en, this message translates to:
/// **'Busy with another connection. Try again in a moment.'**
String get connectBusy;
/// No description provided for @scanner_connectedTo.
///
/// In en, this message translates to:
@ -700,6 +724,90 @@ abstract class AppLocalizations {
/// **'MeshCore'**
String get device_meshcore;
/// No description provided for @deviceCli_title.
///
/// In en, this message translates to:
/// **'Device CLI'**
String get deviceCli_title;
/// Title of the CLI console when it targets a remote companion contact (#999); the contact's name is the subtitle.
///
/// In en, this message translates to:
/// **'Remote CLI'**
String get deviceCli_remoteTitle;
/// No description provided for @deviceCli_entrySubtitle.
///
/// In en, this message translates to:
/// **'Run commands on the connected radio'**
String get deviceCli_entrySubtitle;
/// Console row when a `set name` command is blocked client-side; {chars} is the offending characters, space-separated.
///
/// In en, this message translates to:
/// **'Not sent - name can\'t contain: {chars}'**
String deviceCli_nameRejected(String chars);
/// No description provided for @deviceCli_commandHint.
///
/// In en, this message translates to:
/// **'command...'**
String get deviceCli_commandHint;
/// No description provided for @deviceCli_emptyHint.
///
/// In en, this message translates to:
/// **'Commands run on the connected device'**
String get deviceCli_emptyHint;
/// No description provided for @deviceCli_noReply.
///
/// In en, this message translates to:
/// **'{command}: no reply in {seconds} s'**
String deviceCli_noReply(String command, String seconds);
/// Console row when a remote-CLI command to a companion times out (#891). A companion that has not granted remote CLI simply never replies, so this explains the silence and that the command was sent once, not retried.
///
/// In en, this message translates to:
/// **'{command}: no reply in {seconds} s. This radio may not allow remote CLI from you, or is unreachable. Not retried.'**
String deviceCli_remoteNoReply(String command, String seconds);
/// Console row when the connected radio refuses to send a remote-CLI command because its firmware predates TXT_TYPE_CLI_COMMAND (#999). Nothing was transmitted.
///
/// In en, this message translates to:
/// **'{command}: not sent. Your radio\'s firmware doesn\'t support remote CLI.'**
String deviceCli_remoteUnsupported(String command);
/// No description provided for @deviceCli_sendFailed.
///
/// In en, this message translates to:
/// **'Send failed: {error}'**
String deviceCli_sendFailed(String error);
/// No description provided for @deviceCli_truncatedByDevice.
///
/// In en, this message translates to:
/// **'reply truncated by the device'**
String get deviceCli_truncatedByDevice;
/// No description provided for @deviceCli_secretLongPressToCopy.
///
/// In en, this message translates to:
/// **'secret, long-press to copy'**
String get deviceCli_secretLongPressToCopy;
/// No description provided for @deviceCli_secretCopied.
///
/// In en, this message translates to:
/// **'Secret copied to clipboard'**
String get deviceCli_secretCopied;
/// No description provided for @deviceCli_latencyMs.
///
/// In en, this message translates to:
/// **'{ms} ms'**
String deviceCli_latencyMs(int ms);
/// No description provided for @settings_title.
///
/// In en, this message translates to:
@ -766,6 +874,30 @@ abstract class AppLocalizations {
/// **'Name updated'**
String get settings_nodeNameUpdated;
/// Shown when a device name contains characters the firmware rejects; {chars} is the offending characters, space-separated.
///
/// In en, this message translates to:
/// **'Name can\'t contain: {chars}'**
String settings_nodeNameInvalidChars(String chars);
/// No description provided for @settings_syncQueuedMessages.
///
/// In en, this message translates to:
/// **'Sync queued messages now'**
String get settings_syncQueuedMessages;
/// No description provided for @settings_syncQueuedMessagesSubtitle.
///
/// In en, this message translates to:
/// **'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.'**
String get settings_syncQueuedMessagesSubtitle;
/// No description provided for @settings_syncQueuedMessagesRequested.
///
/// In en, this message translates to:
/// **'Requested queued-message drain (force)'**
String get settings_syncQueuedMessagesRequested;
/// No description provided for @settings_radioSettings.
///
/// In en, this message translates to:
@ -910,6 +1042,222 @@ abstract class AppLocalizations {
/// **'Longitude'**
String get settings_longitude;
/// No description provided for @settings_locationCategorySubtitle.
///
/// In en, this message translates to:
/// **'GPS, coordinates, and reporting'**
String get settings_locationCategorySubtitle;
/// No description provided for @settings_locationCoordinates.
///
/// In en, this message translates to:
/// **'Coordinates'**
String get settings_locationCoordinates;
/// No description provided for @settings_locationNotSet.
///
/// In en, this message translates to:
/// **'Not set'**
String get settings_locationNotSet;
/// No description provided for @settings_locationReportInterval.
///
/// In en, this message translates to:
/// **'Position reporting interval'**
String get settings_locationReportInterval;
/// No description provided for @settings_locationEveryMinutes.
///
/// In en, this message translates to:
/// **'{minutes, plural, =1{Every minute} other{Every {minutes} minutes}}'**
String settings_locationEveryMinutes(int minutes);
/// No description provided for @settings_locationEverySeconds.
///
/// In en, this message translates to:
/// **'Every {seconds} seconds'**
String settings_locationEverySeconds(int seconds);
/// No description provided for @settings_gpsModeLabel.
///
/// In en, this message translates to:
/// **'GPS'**
String get settings_gpsModeLabel;
/// No description provided for @settings_gpsModeOff.
///
/// In en, this message translates to:
/// **'Off'**
String get settings_gpsModeOff;
/// No description provided for @settings_gpsModeOn.
///
/// In en, this message translates to:
/// **'On'**
String get settings_gpsModeOn;
/// No description provided for @settings_gpsModePowerSave.
///
/// In en, this message translates to:
/// **'Power save'**
String get settings_gpsModePowerSave;
/// No description provided for @settings_gpsActivityOff.
///
/// In en, this message translates to:
/// **'GPS is off'**
String get settings_gpsActivityOff;
/// No description provided for @settings_gpsActivityOn.
///
/// In en, this message translates to:
/// **'GPS is on'**
String get settings_gpsActivityOn;
/// No description provided for @settings_gpsActivitySearching.
///
/// In en, this message translates to:
/// **'Searching for a fix'**
String get settings_gpsActivitySearching;
/// No description provided for @settings_gpsActivitySleeping.
///
/// In en, this message translates to:
/// **'Sleeping between fixes'**
String get settings_gpsActivitySleeping;
/// No description provided for @settings_gpsActivityBackedOff.
///
/// In en, this message translates to:
/// **'Backed off'**
String get settings_gpsActivityBackedOff;
/// No description provided for @settings_gpsOffDetail.
///
/// In en, this message translates to:
/// **'Showing the last stored position'**
String get settings_gpsOffDetail;
/// No description provided for @settings_gpsNextTryMinutes.
///
/// In en, this message translates to:
/// **'{minutes, plural, =1{Next try in 1 min} other{Next try in {minutes} min}}'**
String settings_gpsNextTryMinutes(int minutes);
/// No description provided for @settings_gpsNextTrySeconds.
///
/// In en, this message translates to:
/// **'Next try in {seconds} s'**
String settings_gpsNextTrySeconds(int seconds);
/// No description provided for @settings_gpsLastFixMinutes.
///
/// In en, this message translates to:
/// **'{minutes, plural, =0{Last fix just now} =1{Last fix 1 min ago} other{Last fix {minutes} min ago}}'**
String settings_gpsLastFixMinutes(int minutes);
/// No description provided for @settings_gpsSatellites.
///
/// In en, this message translates to:
/// **'{count, plural, =1{1 satellite} other{{count} satellites}}'**
String settings_gpsSatellites(int count);
/// No description provided for @settings_gpsQuery.
///
/// In en, this message translates to:
/// **'Query'**
String get settings_gpsQuery;
/// No description provided for @settings_gpsReading.
///
/// In en, this message translates to:
/// **'Reading GPS settings…'**
String get settings_gpsReading;
/// No description provided for @settings_gpsSleepTitle.
///
/// In en, this message translates to:
/// **'Sleep between fix attempts'**
String get settings_gpsSleepTitle;
/// No description provided for @settings_gpsSleepDefault.
///
/// In en, this message translates to:
/// **'Firmware default, minimum 5 minutes'**
String get settings_gpsSleepDefault;
/// No description provided for @settings_gpsSleepFieldLabel.
///
/// In en, this message translates to:
/// **'Seconds between attempts'**
String get settings_gpsSleepFieldLabel;
/// No description provided for @settings_gpsSleepFieldHint.
///
/// In en, this message translates to:
/// **'0 for the firmware default. The radio raises anything under 300 to 300.'**
String get settings_gpsSleepFieldHint;
/// No description provided for @settings_gpsSleepInvalid.
///
/// In en, this message translates to:
/// **'Enter a whole number of seconds, 0 or more.'**
String get settings_gpsSleepInvalid;
/// No description provided for @settings_buttonActions.
///
/// In en, this message translates to:
/// **'Button actions'**
String get settings_buttonActions;
/// No description provided for @settings_buttonActionsSubtitle.
///
/// In en, this message translates to:
/// **'Assign what the button does'**
String get settings_buttonActionsSubtitle;
/// No description provided for @settings_badgeScreen.
///
/// In en, this message translates to:
/// **'Screen'**
String get settings_badgeScreen;
/// No description provided for @settings_badgeScreenSubtitle.
///
/// In en, this message translates to:
/// **'Text size, screen off, time zone'**
String get settings_badgeScreenSubtitle;
/// No description provided for @settings_badgeBattery.
///
/// In en, this message translates to:
/// **'Battery'**
String get settings_badgeBattery;
/// No description provided for @settings_badgeBatterySubtitle.
///
/// In en, this message translates to:
/// **'100% at {mv} mV'**
String settings_badgeBatterySubtitle(int mv);
/// No description provided for @settings_badgeBatteryReading.
///
/// In en, this message translates to:
/// **'Reading from the radio'**
String get settings_badgeBatteryReading;
/// No description provided for @settings_buzzerTones.
///
/// In en, this message translates to:
/// **'Buzzer and tones'**
String get settings_buzzerTones;
/// No description provided for @settings_buzzerTonesSubtitle.
///
/// In en, this message translates to:
/// **'When this radio beeps'**
String get settings_buzzerTonesSubtitle;
/// No description provided for @settings_contactSettings.
///
/// In en, this message translates to:
@ -2314,6 +2662,48 @@ abstract class AppLocalizations {
/// **'Contact Info'**
String get contact_info;
/// No description provided for @contact_rename.
///
/// In en, this message translates to:
/// **'Rename'**
String get contact_rename;
/// No description provided for @contact_renameTitle.
///
/// In en, this message translates to:
/// **'Custom name'**
String get contact_renameTitle;
/// No description provided for @contact_renameHint.
///
/// In en, this message translates to:
/// **'Your name for this node'**
String get contact_renameHint;
/// No description provided for @contact_renameExplain.
///
/// In en, this message translates to:
/// **'Only you see this. The node keeps its own name, and adverts keep that up to date.'**
String get contact_renameExplain;
/// No description provided for @contact_renameClear.
///
/// In en, this message translates to:
/// **'Clear'**
String get contact_renameClear;
/// No description provided for @contact_renameTooLong.
///
/// In en, this message translates to:
/// **'Keep it under {max} characters'**
String contact_renameTooLong(int max);
/// No description provided for @contact_nodeCallsItself.
///
/// In en, this message translates to:
/// **'Node name: {name}'**
String contact_nodeCallsItself(String name);
/// No description provided for @contact_settings.
///
/// In en, this message translates to:
@ -2374,6 +2764,24 @@ abstract class AppLocalizations {
/// **'Allow sharing environment sensor data'**
String get contact_teleEnvSubtitle;
/// No description provided for @contact_remoteCli.
///
/// In en, this message translates to:
/// **'Remote CLI'**
String get contact_remoteCli;
/// No description provided for @contact_remoteCliSubtitle.
///
/// In en, this message translates to:
/// **'Let this contact run CLI commands on your radio'**
String get contact_remoteCliSubtitle;
/// Chat app-bar menu action on a companion contact that opens the remote CLI console targeting that contact (#999).
///
/// In en, this message translates to:
/// **'CLI console'**
String get contact_cliConsole;
/// No description provided for @channels_title.
///
/// In en, this message translates to:
@ -8506,6 +8914,18 @@ abstract class AppLocalizations {
/// **'No blocked users'**
String get block_none;
/// No description provided for @block_noRadio.
///
/// In en, this message translates to:
/// **'No radio connected'**
String get block_noRadio;
/// No description provided for @block_noRadioHint.
///
/// In en, this message translates to:
/// **'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.'**
String get block_noRadioHint;
/// No description provided for @block_keysSection.
///
/// In en, this message translates to:
@ -8979,6 +9399,192 @@ abstract class AppLocalizations {
/// In en, this message translates to:
/// **'{count, plural, =1{1 saved contact is no longer on the radio.} other{{count} saved contacts are no longer on the radio.}}'**
String contactSyncConfirmedGone(int count);
/// No description provided for @discoverRegions_title.
///
/// In en, this message translates to:
/// **'Discover Regions'**
String get discoverRegions_title;
/// No description provided for @discoverRegions_subtitle.
///
/// In en, this message translates to:
/// **'Find the flood regions this repeater carries.'**
String get discoverRegions_subtitle;
/// No description provided for @discoverRegions_loading.
///
/// In en, this message translates to:
/// **'Discovering regions from {name}...'**
String discoverRegions_loading(String name);
/// No description provided for @discoverRegions_source.
///
/// In en, this message translates to:
/// **'Regions carried by {name}'**
String discoverRegions_source(String name);
/// No description provided for @discoverRegions_empty.
///
/// In en, this message translates to:
/// **'{name} advertises no flood regions.'**
String discoverRegions_empty(String name);
/// No description provided for @discoverRegions_timeout.
///
/// In en, this message translates to:
/// **'No response from {name}. The repeater may be out of range.'**
String discoverRegions_timeout(String name);
/// No description provided for @discoverRegions_error.
///
/// In en, this message translates to:
/// **'Could not discover regions.'**
String get discoverRegions_error;
/// No description provided for @discoverRegions_retry.
///
/// In en, this message translates to:
/// **'Retry'**
String get discoverRegions_retry;
/// No description provided for @setRegionScope_menu.
///
/// In en, this message translates to:
/// **'Set Region Scope'**
String get setRegionScope_menu;
/// No description provided for @setRegionScope_title.
///
/// In en, this message translates to:
/// **'Region scope for {channel}'**
String setRegionScope_title(String channel);
/// No description provided for @setRegionScope_discover.
///
/// In en, this message translates to:
/// **'Discover from repeater'**
String get setRegionScope_discover;
/// No description provided for @setRegionScope_none.
///
/// In en, this message translates to:
/// **'None (unscoped)'**
String get setRegionScope_none;
/// No description provided for @setRegionScope_save.
///
/// In en, this message translates to:
/// **'Save'**
String get setRegionScope_save;
/// No description provided for @setRegionScope_searchRepeaters.
///
/// In en, this message translates to:
/// **'Search repeaters'**
String get setRegionScope_searchRepeaters;
/// No description provided for @setRegionScope_pathNote.
///
/// In en, this message translates to:
/// **'You can only discover regions from a repeater you have a stored path to.'**
String get setRegionScope_pathNote;
/// No description provided for @setRegionScope_noPath.
///
/// In en, this message translates to:
/// **'No stored path'**
String get setRegionScope_noPath;
/// No description provided for @storage_title.
///
/// In en, this message translates to:
/// **'Storage'**
String get storage_title;
/// Current size of the message database on this device (#962).
///
/// In en, this message translates to:
/// **'Message database: {size}'**
String storage_databaseSize(String size);
/// Explains what the Clear Stale History action does (#962).
///
/// In en, this message translates to:
/// **'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.'**
String get storage_staleHint;
/// No description provided for @storage_clearStaleNow.
///
/// In en, this message translates to:
/// **'Clear Stale History Now'**
String get storage_clearStaleNow;
/// No description provided for @storage_working.
///
/// In en, this message translates to:
/// **'Clearing...'**
String get storage_working;
/// No description provided for @storage_resultNothing.
///
/// In en, this message translates to:
/// **'Nothing to clear.'**
String get storage_resultNothing;
/// Result of a successful stale-history clear (#962).
///
/// In en, this message translates to:
/// **'Cleared {count} old copies, {size} returned.'**
String storage_resultCleared(int count, String size);
/// Reported when the clear kept a copy back because its messages could not be verified against the new format (#962, owner decision: the button reports refusals rather than only logging them).
///
/// In en, this message translates to:
/// **'Kept {count} that could not be verified. Your messages are intact; nothing was deleted for those.'**
String storage_resultRefused(int count);
/// No description provided for @storage_confirmTitle.
///
/// In en, this message translates to:
/// **'Clear stale history?'**
String get storage_confirmTitle;
/// Body of the confirmation shown before clearing stale history. The size is approximate because VACUUM's real figure depends on page rounding (#962).
///
/// In en, this message translates to:
/// **'This removes {count} old copies of history that has already moved to the new format, freeing about {size}.'**
String storage_confirmBody(int count, String size);
/// Reassurance in the clear confirmation: this deletes duplicate copies, not history (#962).
///
/// In en, this message translates to:
/// **'Your messages are not affected. All {count} stay.'**
String storage_confirmSafe(int count);
/// No description provided for @storage_confirmIrreversible.
///
/// In en, this message translates to:
/// **'This cannot be undone.'**
String get storage_confirmIrreversible;
/// Shown when the preview already knows a copy will be refused, so the user hears it before the press rather than after (#962).
///
/// In en, this message translates to:
/// **'{count} will be kept back because its messages could not be verified. This cannot be undone.'**
String storage_confirmKeptBack(int count);
/// Confirm button. Carries the count so the scope is the last thing read before the tap (#962).
///
/// In en, this message translates to:
/// **'Clear {count} copies'**
String storage_confirmAction(int count);
/// Shown when the clear threw. It must not claim nothing happened, because the sweep deletes per key and may have cleared some before failing (#962).
///
/// In en, this message translates to:
/// **'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.'**
String get storage_resultFailed;
}
class _AppLocalizationsDelegate

@ -80,6 +80,9 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get common_retry => 'Опитай отново';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Скриване';
@ -260,6 +263,20 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get scanner_notConnected => 'Не е свързан';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Свързано с $deviceName';
@ -326,6 +343,60 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Настройки';
@ -361,6 +432,22 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Името е актуализирано';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Настройки на радиопредавателя';
@ -440,6 +527,156 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get settings_longitude => 'Дължина';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Настройки за контакти';
@ -1253,6 +1490,32 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get contact_info => 'Контактна информация';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Настройки за контакти';
@ -1286,6 +1549,16 @@ class AppLocalizationsBg extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Позволи споделяне на данни от средносферните датчици';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Канали';
@ -5007,6 +5280,13 @@ class AppLocalizationsBg extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5300,4 +5580,125 @@ class AppLocalizationsBg extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get common_retry => 'Versuchen';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Ausblenden';
@ -263,6 +266,20 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get scanner_notConnected => 'Nicht verbunden';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Verbunden mit $deviceName';
@ -329,6 +346,60 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Einstellungen';
@ -364,6 +435,22 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Name aktualisiert';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Funk Einstellungen';
@ -442,6 +529,156 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get settings_longitude => 'Längengrad';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Kontakteinstellungen';
@ -1248,6 +1485,32 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get contact_info => 'Kontaktinformationen';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Kontakteinstellungen';
@ -1280,6 +1543,16 @@ class AppLocalizationsDe extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Teilen von Umgebungsensordaten zulassen';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanäle';
@ -5024,6 +5297,13 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5317,4 +5597,125 @@ class AppLocalizationsDe extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get common_retry => 'Retry';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Hide';
@ -258,6 +261,20 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get scanner_notConnected => 'Not connected';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Connected to $deviceName';
@ -323,6 +340,60 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Settings';
@ -358,6 +429,22 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Name updated';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Radio Settings';
@ -436,6 +523,156 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get settings_longitude => 'Longitude';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Contact Settings';
@ -1231,6 +1468,32 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get contact_info => 'Contact Info';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Contact Settings';
@ -1262,6 +1525,16 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => 'Allow sharing environment sensor data';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Channels';
@ -4930,6 +5203,13 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5223,4 +5503,125 @@ class AppLocalizationsEn extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get common_retry => 'Intentar';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Ocultar';
@ -261,6 +264,20 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get scanner_notConnected => 'No está conectado';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Conectado a $deviceName';
@ -327,6 +344,60 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Configuración';
@ -362,6 +433,22 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Nombre actualizado';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Configuración de Radio';
@ -440,6 +527,156 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get settings_longitude => 'Longitud';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Configuración de contacto';
@ -1248,6 +1485,32 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get contact_info => 'Información de contacto';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Configuración de contacto';
@ -1281,6 +1544,16 @@ class AppLocalizationsEs extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Permitir el intercambio de datos de sensores de entorno';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canales';
@ -5012,6 +5285,13 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5305,4 +5585,125 @@ class AppLocalizationsEs extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get common_retry => 'Réessayer';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Masquer';
@ -263,6 +266,20 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get scanner_notConnected => 'Non connecté';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Connecté à $deviceName';
@ -329,6 +346,60 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Paramètres';
@ -364,6 +435,22 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Nom mis à jour';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Paramètres Radio';
@ -443,6 +530,156 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get settings_longitude => 'Longitude';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Paramètres de contact';
@ -1253,6 +1490,32 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get contact_info => 'Informations de contact';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Paramètres de contact';
@ -1286,6 +1549,16 @@ class AppLocalizationsFr extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Autoriser le partage des données des capteurs d\'environnement';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canaux';
@ -5040,6 +5313,13 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5333,4 +5613,125 @@ class AppLocalizationsFr extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get common_retry => 'Újrapróbálja';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Elrejt';
@ -260,6 +263,20 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get scanner_notConnected => 'Nem csatlakozva';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Kapcsolódik a $deviceName-hez';
@ -326,6 +343,60 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Beállítások';
@ -361,6 +432,22 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Neve frissítve';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Rádióbeállítások';
@ -442,6 +529,156 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get settings_longitude => 'hosszúság';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Kapcsolat beállítások';
@ -1255,6 +1492,32 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get contact_info => 'Kapcsolattartási információk';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Kapcsolat beállítások';
@ -1287,6 +1550,16 @@ class AppLocalizationsHu extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Engedje meg az érzékelő adatok megosztását';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Csatornák';
@ -5029,6 +5302,13 @@ class AppLocalizationsHu extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5322,4 +5602,125 @@ class AppLocalizationsHu extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get common_retry => 'Riprova';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Nascondi';
@ -263,6 +266,20 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get scanner_notConnected => 'Non connesso';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Connesso a $deviceName';
@ -329,6 +346,60 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Impostazioni';
@ -364,6 +435,22 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Nome aggiornato';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Impostazioni Radio';
@ -442,6 +529,156 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get settings_longitude => 'Longitudine';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Impostazioni di contatto';
@ -1249,6 +1486,32 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get contact_info => 'Informazioni di Contatto';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Impostazioni di contatto';
@ -1282,6 +1545,16 @@ class AppLocalizationsIt extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Consenti la condivisione dei dati del sensore ambientale';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canali';
@ -5017,6 +5290,13 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5310,4 +5590,125 @@ class AppLocalizationsIt extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get common_retry => '再試';
@override
String get common_stop => 'Stop';
@override
String get common_hide => '隠す';
@ -252,6 +255,20 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get scanner_notConnected => '接続されていない';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return '$deviceName に接続';
@ -316,6 +333,60 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get device_meshcore => 'メッシュコア';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => '設定';
@ -350,6 +421,22 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get settings_nodeNameUpdated => '氏名変更';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'ラジオ設定';
@ -425,6 +512,156 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get settings_longitude => '経度';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => '連絡設定';
@ -1200,6 +1437,32 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get contact_info => '連絡先';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => '連絡設定';
@ -1230,6 +1493,16 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => '環境センサーのデータを共有することを許可する';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'チャンネル';
@ -4783,6 +5056,13 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5076,4 +5356,125 @@ class AppLocalizationsJa extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get common_retry => '다시 시도';
@override
String get common_stop => 'Stop';
@override
String get common_hide => '숨기다';
@ -251,6 +254,20 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get scanner_notConnected => '연결되지 않음';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return '$deviceName에 연결됨';
@ -315,6 +332,60 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get device_meshcore => '메쉬코어';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => '설정';
@ -349,6 +420,22 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get settings_nodeNameUpdated => '이름 변경';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => '라디오 설정';
@ -425,6 +512,156 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get settings_longitude => '경도';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => '연락처 설정';
@ -1195,6 +1432,32 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get contact_info => '연락처';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => '연락처 설정';
@ -1225,6 +1488,16 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => '환경 센서 데이터를 공유하도록 허용';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => '채널';
@ -4784,6 +5057,13 @@ class AppLocalizationsKo extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5077,4 +5357,125 @@ class AppLocalizationsKo extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get common_retry => 'Nogmaals proberen';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Verbergen';
@ -260,6 +263,20 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get scanner_notConnected => 'Niet verbonden';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Verbonden met $deviceName';
@ -325,6 +342,60 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Instellingen';
@ -360,6 +431,22 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Naam bijgewerkt';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Radio Instellingen';
@ -439,6 +526,156 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get settings_longitude => 'Lengtegraad';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Contactinstellingen';
@ -1242,6 +1479,32 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get contact_info => 'Contactinformatie';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Contactinstellingen';
@ -1273,6 +1536,16 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => 'Delen van omgevingsensordata toestaan';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanaal';
@ -4992,6 +5265,13 @@ class AppLocalizationsNl extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5285,4 +5565,125 @@ class AppLocalizationsNl extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get common_retry => 'Ponów';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Ukryj';
@ -264,6 +267,20 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get scanner_notConnected => 'Nie połączono';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Połączono z $deviceName';
@ -330,6 +347,60 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Ustawienia';
@ -365,6 +436,22 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Nazwa zaktualizowana';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Ustawienia radia';
@ -445,6 +532,156 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get settings_longitude => 'Długość';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Ustawienia kontaktów';
@ -1259,6 +1496,32 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get contact_info => 'Informacje kontaktowe';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Ustawienia kontaktowe';
@ -1292,6 +1555,16 @@ class AppLocalizationsPl extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Zezwalaj na udostępnianie danych czujników środowiskowych';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanały';
@ -5029,6 +5302,13 @@ class AppLocalizationsPl extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5322,4 +5602,125 @@ class AppLocalizationsPl extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get common_retry => 'Tentar novamente';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Esconder';
@ -262,6 +265,20 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get scanner_notConnected => 'Não está conectado';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Conectado a $deviceName';
@ -328,6 +345,60 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Configurações';
@ -363,6 +434,22 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Nome atualizado';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Configurações de Rádio';
@ -442,6 +529,156 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get settings_longitude => 'Longitude';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Configurações de Contato';
@ -1249,6 +1486,32 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get contact_info => 'Informações de Contato';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Configurações de Contato';
@ -1282,6 +1545,16 @@ class AppLocalizationsPt extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Permitir compartilhamento de dados do sensor de ambiente';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Canais';
@ -5005,6 +5278,13 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5298,4 +5578,125 @@ class AppLocalizationsPt extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get common_retry => 'Повторить';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Скрыть';
@ -263,6 +266,20 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get scanner_notConnected => 'Не подключено';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Подключено к $deviceName';
@ -328,6 +345,60 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Настройки';
@ -363,6 +434,22 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Имя обновлено';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Настройки радио';
@ -441,6 +528,156 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get settings_longitude => 'Долгота';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Настройки контактов';
@ -1250,6 +1487,32 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get contact_info => 'Контактная информация';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Настройки контактов';
@ -1283,6 +1546,16 @@ class AppLocalizationsRu extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Разрешить обмен данными датчиков окружающей среды';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Каналы';
@ -5023,6 +5296,13 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5316,4 +5596,125 @@ class AppLocalizationsRu extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get common_retry => 'Pokusť znova';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Skryť';
@ -261,6 +264,20 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get scanner_notConnected => 'Nezriadené';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Pripojené k $deviceName';
@ -327,6 +344,60 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Nastavenia';
@ -362,6 +433,22 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Meno aktualizované';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Nastavenia rádia';
@ -440,6 +527,156 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get settings_longitude => 'Dĺžka';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Nastavenia kontaktov';
@ -1241,6 +1478,32 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get contact_info => 'Kontaktné informácie';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Nastavenia kontaktov';
@ -1273,6 +1536,16 @@ class AppLocalizationsSk extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Povoliť zdieľanie údajov senzorov prostredia';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanály';
@ -4989,6 +5262,13 @@ class AppLocalizationsSk extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5282,4 +5562,125 @@ class AppLocalizationsSk extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get common_retry => 'Ponoviti';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Skrita';
@ -259,6 +262,20 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get scanner_notConnected => 'Nezavezan';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Povezan s $deviceName';
@ -325,6 +342,60 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Nastavitve';
@ -360,6 +431,22 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Ime posodobljeno';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Nastavitve radija';
@ -438,6 +525,156 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get settings_longitude => 'Dolžina';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Nastavitve stika';
@ -1238,6 +1475,32 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get contact_info => 'Kontaktni podatki';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Nastavitve stika';
@ -1270,6 +1533,16 @@ class AppLocalizationsSl extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Dovoli deljenje podatkov okoljskih senzorjev';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanali';
@ -4987,6 +5260,13 @@ class AppLocalizationsSl extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5280,4 +5560,125 @@ class AppLocalizationsSl extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get common_retry => 'Försök igen';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Dölj';
@ -259,6 +262,20 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get scanner_notConnected => 'Inte ansluten';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Ansluten till $deviceName';
@ -324,6 +341,60 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Inställningar';
@ -359,6 +430,22 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Namn uppdaterat';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Radioinställningar';
@ -437,6 +524,156 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get settings_longitude => 'Längdgrad';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Kontaktinställningar';
@ -1233,6 +1470,32 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get contact_info => 'Kontaktinformation';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Kontaktinställningar';
@ -1264,6 +1527,16 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => 'Tillåt delning av miljösensordata';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Kanaler';
@ -4962,6 +5235,13 @@ class AppLocalizationsSv extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5255,4 +5535,125 @@ class AppLocalizationsSv extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get common_retry => 'Повторити';
@override
String get common_stop => 'Stop';
@override
String get common_hide => 'Приховати';
@ -261,6 +264,20 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get scanner_notConnected => 'Не підключено';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return 'Підключено до $deviceName';
@ -327,6 +344,60 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get device_meshcore => 'MeshCore';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => 'Налаштування';
@ -362,6 +433,22 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get settings_nodeNameUpdated => 'Ім\'я оновлено';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => 'Налаштування радіо';
@ -439,6 +526,156 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get settings_longitude => 'Довгота';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => 'Налаштування контактів';
@ -1245,6 +1482,32 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get contact_info => 'Контактна інформація';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => 'Налаштування контактів';
@ -1278,6 +1541,16 @@ class AppLocalizationsUk extends AppLocalizations {
String get contact_teleEnvSubtitle =>
'Дозволити спільний доступ до даних датчиків середовища';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => 'Канали';
@ -5024,6 +5297,13 @@ class AppLocalizationsUk extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -5317,4 +5597,125 @@ class AppLocalizationsUk extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -80,6 +80,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get common_retry => '重试';
@override
String get common_stop => 'Stop';
@override
String get common_hide => '隐藏';
@ -249,6 +252,20 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get scanner_notConnected => '未连接';
@override
String scanner_reconnecting(String deviceName, int attempt, int maxAttempts) {
return 'Reconnecting to $deviceName (attempt $attempt of $maxAttempts)';
}
@override
String scanner_reconnectGaveUp(String deviceName) {
return 'Couldn\'t reach $deviceName';
}
@override
String get connectBusy =>
'Busy with another connection. Try again in a moment.';
@override
String scanner_connectedTo(String deviceName) {
return '已连接到 $deviceName';
@ -313,6 +330,60 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get device_meshcore => '网格核心';
@override
String get deviceCli_title => 'Device CLI';
@override
String get deviceCli_remoteTitle => 'Remote CLI';
@override
String get deviceCli_entrySubtitle => 'Run commands on the connected radio';
@override
String deviceCli_nameRejected(String chars) {
return 'Not sent - name can\'t contain: $chars';
}
@override
String get deviceCli_commandHint => 'command...';
@override
String get deviceCli_emptyHint => 'Commands run on the connected device';
@override
String deviceCli_noReply(String command, String seconds) {
return '$command: no reply in $seconds s';
}
@override
String deviceCli_remoteNoReply(String command, String seconds) {
return '$command: no reply in $seconds s. This radio may not allow remote CLI from you, or is unreachable. Not retried.';
}
@override
String deviceCli_remoteUnsupported(String command) {
return '$command: not sent. Your radio\'s firmware doesn\'t support remote CLI.';
}
@override
String deviceCli_sendFailed(String error) {
return 'Send failed: $error';
}
@override
String get deviceCli_truncatedByDevice => 'reply truncated by the device';
@override
String get deviceCli_secretLongPressToCopy => 'secret, long-press to copy';
@override
String get deviceCli_secretCopied => 'Secret copied to clipboard';
@override
String deviceCli_latencyMs(int ms) {
return '$ms ms';
}
@override
String get settings_title => '设置';
@ -347,6 +418,22 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get settings_nodeNameUpdated => '节点名称已更新';
@override
String settings_nodeNameInvalidChars(String chars) {
return 'Name can\'t contain: $chars';
}
@override
String get settings_syncQueuedMessages => 'Sync queued messages now';
@override
String get settings_syncQueuedMessagesSubtitle =>
'Force-pull messages the radio is holding, diagnostic for #51 (radio reports a count but the app shows none). Logs the flow for diagnostics.';
@override
String get settings_syncQueuedMessagesRequested =>
'Requested queued-message drain (force)';
@override
String get settings_radioSettings => '无线电设置';
@ -421,6 +508,156 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get settings_longitude => '经度';
@override
String get settings_locationCategorySubtitle =>
'GPS, coordinates, and reporting';
@override
String get settings_locationCoordinates => 'Coordinates';
@override
String get settings_locationNotSet => 'Not set';
@override
String get settings_locationReportInterval => 'Position reporting interval';
@override
String settings_locationEveryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Every $minutes minutes',
one: 'Every minute',
);
return '$_temp0';
}
@override
String settings_locationEverySeconds(int seconds) {
return 'Every $seconds seconds';
}
@override
String get settings_gpsModeLabel => 'GPS';
@override
String get settings_gpsModeOff => 'Off';
@override
String get settings_gpsModeOn => 'On';
@override
String get settings_gpsModePowerSave => 'Power save';
@override
String get settings_gpsActivityOff => 'GPS is off';
@override
String get settings_gpsActivityOn => 'GPS is on';
@override
String get settings_gpsActivitySearching => 'Searching for a fix';
@override
String get settings_gpsActivitySleeping => 'Sleeping between fixes';
@override
String get settings_gpsActivityBackedOff => 'Backed off';
@override
String get settings_gpsOffDetail => 'Showing the last stored position';
@override
String settings_gpsNextTryMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Next try in $minutes min',
one: 'Next try in 1 min',
);
return '$_temp0';
}
@override
String settings_gpsNextTrySeconds(int seconds) {
return 'Next try in $seconds s';
}
@override
String settings_gpsLastFixMinutes(int minutes) {
String _temp0 = intl.Intl.pluralLogic(
minutes,
locale: localeName,
other: 'Last fix $minutes min ago',
one: 'Last fix 1 min ago',
zero: 'Last fix just now',
);
return '$_temp0';
}
@override
String settings_gpsSatellites(int count) {
String _temp0 = intl.Intl.pluralLogic(
count,
locale: localeName,
other: '$count satellites',
one: '1 satellite',
);
return '$_temp0';
}
@override
String get settings_gpsQuery => 'Query';
@override
String get settings_gpsReading => 'Reading GPS settings…';
@override
String get settings_gpsSleepTitle => 'Sleep between fix attempts';
@override
String get settings_gpsSleepDefault => 'Firmware default, minimum 5 minutes';
@override
String get settings_gpsSleepFieldLabel => 'Seconds between attempts';
@override
String get settings_gpsSleepFieldHint =>
'0 for the firmware default. The radio raises anything under 300 to 300.';
@override
String get settings_gpsSleepInvalid =>
'Enter a whole number of seconds, 0 or more.';
@override
String get settings_buttonActions => 'Button actions';
@override
String get settings_buttonActionsSubtitle => 'Assign what the button does';
@override
String get settings_badgeScreen => 'Screen';
@override
String get settings_badgeScreenSubtitle => 'Text size, screen off, time zone';
@override
String get settings_badgeBattery => 'Battery';
@override
String settings_badgeBatterySubtitle(int mv) {
return '100% at $mv mV';
}
@override
String get settings_badgeBatteryReading => 'Reading from the radio';
@override
String get settings_buzzerTones => 'Buzzer and tones';
@override
String get settings_buzzerTonesSubtitle => 'When this radio beeps';
@override
String get settings_contactSettings => '联系人设置';
@ -1181,6 +1418,32 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get contact_info => '联系信息';
@override
String get contact_rename => 'Rename';
@override
String get contact_renameTitle => 'Custom name';
@override
String get contact_renameHint => 'Your name for this node';
@override
String get contact_renameExplain =>
'Only you see this. The node keeps its own name, and adverts keep that up to date.';
@override
String get contact_renameClear => 'Clear';
@override
String contact_renameTooLong(int max) {
return 'Keep it under $max characters';
}
@override
String contact_nodeCallsItself(String name) {
return 'Node name: $name';
}
@override
String get contact_settings => '联系人设置';
@ -1211,6 +1474,16 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get contact_teleEnvSubtitle => '允许共享环境传感器数据';
@override
String get contact_remoteCli => 'Remote CLI';
@override
String get contact_remoteCliSubtitle =>
'Let this contact run CLI commands on your radio';
@override
String get contact_cliConsole => 'CLI console';
@override
String get channels_title => '频道';
@ -4657,6 +4930,13 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get block_none => 'No blocked users';
@override
String get block_noRadio => 'No radio connected';
@override
String get block_noRadioHint =>
'Blocks belong to the radio that holds them. Connect a radio to see and change its blocked list.';
@override
String get block_keysSection => 'Blocked contacts';
@ -4950,4 +5230,125 @@ class AppLocalizationsZh extends AppLocalizations {
);
return '$_temp0';
}
@override
String get discoverRegions_title => 'Discover Regions';
@override
String get discoverRegions_subtitle =>
'Find the flood regions this repeater carries.';
@override
String discoverRegions_loading(String name) {
return 'Discovering regions from $name...';
}
@override
String discoverRegions_source(String name) {
return 'Regions carried by $name';
}
@override
String discoverRegions_empty(String name) {
return '$name advertises no flood regions.';
}
@override
String discoverRegions_timeout(String name) {
return 'No response from $name. The repeater may be out of range.';
}
@override
String get discoverRegions_error => 'Could not discover regions.';
@override
String get discoverRegions_retry => 'Retry';
@override
String get setRegionScope_menu => 'Set Region Scope';
@override
String setRegionScope_title(String channel) {
return 'Region scope for $channel';
}
@override
String get setRegionScope_discover => 'Discover from repeater';
@override
String get setRegionScope_none => 'None (unscoped)';
@override
String get setRegionScope_save => 'Save';
@override
String get setRegionScope_searchRepeaters => 'Search repeaters';
@override
String get setRegionScope_pathNote =>
'You can only discover regions from a repeater you have a stored path to.';
@override
String get setRegionScope_noPath => 'No stored path';
@override
String get storage_title => 'Storage';
@override
String storage_databaseSize(String size) {
return 'Message database: $size';
}
@override
String get storage_staleHint =>
'When your history moves to the new format, the old copy is kept for 30 days and then cleared on its own. You can clear it now instead.';
@override
String get storage_clearStaleNow => 'Clear Stale History Now';
@override
String get storage_working => 'Clearing...';
@override
String get storage_resultNothing => 'Nothing to clear.';
@override
String storage_resultCleared(int count, String size) {
return 'Cleared $count old copies, $size returned.';
}
@override
String storage_resultRefused(int count) {
return 'Kept $count that could not be verified. Your messages are intact; nothing was deleted for those.';
}
@override
String get storage_confirmTitle => 'Clear stale history?';
@override
String storage_confirmBody(int count, String size) {
return 'This removes $count old copies of history that has already moved to the new format, freeing about $size.';
}
@override
String storage_confirmSafe(int count) {
return 'Your messages are not affected. All $count stay.';
}
@override
String get storage_confirmIrreversible => 'This cannot be undone.';
@override
String storage_confirmKeptBack(int count) {
return '$count will be kept back because its messages could not be verified. This cannot be undone.';
}
@override
String storage_confirmAction(int count) {
return 'Clear $count copies';
}
@override
String get storage_resultFailed =>
'Could not finish, and some old copies may already have been cleared. Nothing was deleted that was not verified first, so your messages are intact.';
}

@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/foundation.dart';
@ -18,6 +20,7 @@ import 'services/app_settings_service.dart';
import 'services/notification_service.dart';
import 'services/ble_debug_log_service.dart';
import 'services/app_debug_log_service.dart';
import 'services/app_exit_info_service.dart';
import 'services/file_log_service.dart';
import 'services/background_service.dart';
import 'services/map_tile_cache_service.dart';
@ -29,6 +32,7 @@ import 'services/observer_config_service.dart';
import 'services/block_service.dart';
import 'services/window_geometry_service.dart';
import 'services/store_consolidation_service.dart';
import 'services/stale_history_sweep.dart';
import 'services/storage_health_service.dart';
import 'services/radio_preset_service.dart';
import 'storage/drift/blob_store.dart';
@ -82,6 +86,12 @@ void main() async {
// Initialize services
final storage = StorageService();
final connector = MeshCoreConnector();
// StorageService is shared with PathHistoryService and
// TimeoutPredictionService, so the connector cannot own it the way it owns
// the other per-radio stores. It still needs the device key on connect,
// because path history and delivery observations are per-radio now
// (#854, #856).
connector.storageService = storage;
final pathHistoryService = PathHistoryService(storage);
final meshTopologyService = MeshTopologyService();
final retryService = MessageRetryService();
@ -167,6 +177,47 @@ void main() async {
radioPresetService: radioPresetService,
),
);
// Report why the previous process died, if it did (#906). Scheduled after the
// first frame and deliberately not awaited: #334 is the leading hypothesis for
// the ANRs this exists to diagnose, so the collector must not itself add work
// to startup. The Android side does its query and trace reads on a background
// executor.
WidgetsBinding.instance.addPostFrameCallback((_) {
unawaited(AppExitInfoService.instance.collect());
// Reclaim the stale pre-migration history blobs (#962), once per launch.
//
// Same shape and the same reasoning as the collector above: after the
// first frame and not awaited, because storage hygiene must never be on
// the path to a usable screen. It is a no-op on almost every launch, since
// a key is swept once and then has no blob left to consider, so the
// VACUUM inside it is rare rather than per-launch.
//
// Caught HERE rather than inside the sweep. Nothing about reclaiming disk
// space is worth a broken start, but the manual action (#966) needs a
// failure it can report to the user, so `run` stays able to throw and this
// fire-and-forget call site is what absorbs it.
unawaited(
StaleHistorySweep(BlobStore.instance).run().catchError((
Object e,
StackTrace s,
) {
appLogger.error(
'The startup stale-history sweep failed and was skipped. No blob is '
'deleted on this path unless it was verified first, so the history '
'is intact: $e\n$s',
tag: 'Storage',
);
return const StaleHistoryOutcome(
cleared: [],
refused: [],
bytesBefore: 0,
bytesAfter: 0,
);
}),
);
});
}
void _registerThirdPartyLicenses() {

@ -158,11 +158,24 @@ class AppSettings {
/// written, so an older build can be rolled back to without losing mutes.
final Set<String> mutedChannels;
/// Per-channel notification level, keyed by [channelNotifyKey], the PSK
/// identity when known, else the slot index. Keying by PSK (not by display
/// name, and not by slot) means the setting survives a rename and does not
/// bleed across a slot reassignment (#193/#194).
/// Legacy flat per-channel notify map (pre-#839), keyed by `psk_<hex>` or a
/// bare slot index, with no per-radio scoping. Superseded by
/// [channelNotifyModesByRadio]. Retained only as migration input and for
/// rollback; never consulted by the live resolution. See #839.
final Map<String, ChannelNotifyMode> channelNotifyModes;
/// Per-radio per-channel notify level: device-key prefix (first 10 hex of the
/// connected radio's public key, like every other per-radio store) -> channel
/// PSK hex -> mode. Keyed by PSK within a radio so it survives a rename and
/// does not follow a reused slot (#193/#194); scoped by radio so one radio's
/// settings never bleed into another, and there is no bare-index fallback that
/// could (#839). `all` is the default and is never stored.
final Map<String, Map<String, ChannelNotifyMode>> channelNotifyModesByRadio;
/// One-time guard: true once the legacy flat map / mute set has been migrated
/// into [channelNotifyModesByRadio] for the first radio seen post-upgrade, so
/// a second radio does not inherit the ambiguous legacy state (#839).
final bool channelNotifyMigrated;
final bool mapShowDiscoveryContacts;
final String tcpServerAddress;
final int tcpServerPort;
@ -185,17 +198,6 @@ class AppSettings {
return profile.charMap;
}
/// Storage key for a channel's notify mode.
///
/// Mirrors the identity scheme [ChannelMessageStore] uses for history (#194):
/// the PSK hex when the channel is synced and its key is known, else the slot
/// index as a fallback. The `psk_` marker keeps the two spaces from colliding
/// (a PSK is 32 hex chars; an index is a small integer).
static String channelNotifyKey({required int channelIndex, String? pskHex}) {
if (pskHex != null && pskHex.isNotEmpty) return 'psk_$pskHex';
return '$channelIndex';
}
AppSettings({
this.clearPathOnMaxRetry = false,
this.mapShowRepeaters = true,
@ -234,6 +236,8 @@ class AppSettings {
this.unitSystem = UnitSystem.metric,
Set<String>? mutedChannels,
Map<String, ChannelNotifyMode>? channelNotifyModes,
Map<String, Map<String, ChannelNotifyMode>>? channelNotifyModesByRadio,
this.channelNotifyMigrated = false,
this.mapShowDiscoveryContacts = true,
this.tcpServerAddress = '',
this.tcpServerPort = 0,
@ -251,6 +255,7 @@ class AppSettings {
batteryChemistryByRepeaterId = batteryChemistryByRepeaterId ?? {},
mutedChannels = mutedChannels ?? {},
channelNotifyModes = channelNotifyModes ?? {},
channelNotifyModesByRadio = channelNotifyModesByRadio ?? {},
translationDownloadedModels = translationDownloadedModels ?? const [],
cyr2latProfiles =
cyr2latProfiles ??
@ -304,6 +309,13 @@ class AppSettings {
'channel_notify_modes': channelNotifyModes.map(
(key, mode) => MapEntry(key, mode.value),
),
'channel_notify_modes_by_radio': channelNotifyModesByRadio.map(
(prefix, modes) => MapEntry(
prefix,
modes.map((psk, mode) => MapEntry(psk, mode.value)),
),
),
'channel_notify_migrated': channelNotifyMigrated,
'map_show_discovery_contacts': mapShowDiscoveryContacts,
'tcp_server_address': tcpServerAddress,
'tcp_server_port': tcpServerPort,
@ -423,6 +435,19 @@ class AppSettings {
MapEntry(key.toString(), parseChannelNotifyMode(value)),
) ??
{},
channelNotifyModesByRadio:
(json['channel_notify_modes_by_radio'] as Map?)?.map(
(prefix, modes) => MapEntry(
prefix.toString(),
(modes as Map?)?.map(
(psk, value) =>
MapEntry(psk.toString(), parseChannelNotifyMode(value)),
) ??
<String, ChannelNotifyMode>{},
),
) ??
{},
channelNotifyMigrated: json['channel_notify_migrated'] as bool? ?? false,
mapShowDiscoveryContacts:
json['map_show_discovery_contacts'] as bool? ?? true,
tcpServerAddress: json['tcp_server_address'] as String? ?? '',
@ -521,6 +546,8 @@ class AppSettings {
UnitSystem? unitSystem,
Set<String>? mutedChannels,
Map<String, ChannelNotifyMode>? channelNotifyModes,
Map<String, Map<String, ChannelNotifyMode>>? channelNotifyModesByRadio,
bool? channelNotifyMigrated,
bool? mapShowDiscoveryContacts,
String? tcpServerAddress,
int? tcpServerPort,
@ -585,6 +612,10 @@ class AppSettings {
unitSystem: unitSystem ?? this.unitSystem,
mutedChannels: mutedChannels ?? this.mutedChannels,
channelNotifyModes: channelNotifyModes ?? this.channelNotifyModes,
channelNotifyModesByRadio:
channelNotifyModesByRadio ?? this.channelNotifyModesByRadio,
channelNotifyMigrated:
channelNotifyMigrated ?? this.channelNotifyMigrated,
mapShowDiscoveryContacts:
mapShowDiscoveryContacts ?? this.mapShowDiscoveryContacts,
tcpServerAddress: tcpServerAddress ?? this.tcpServerAddress,

@ -0,0 +1,159 @@
/// The badge's time zone table, a copy of firmware `src/helpers/TimeZones.h`
/// on meshcore-firmware `firmware-base` at `f3d30a88` (#987).
///
/// The radio stores a zone as an index into this list, so the order is the
/// contract. Firmware keeps it append-only ("Append only; never reorder"), so
/// a copy can only fall behind; an index past the end is shown by number.
library;
enum DstRule { none, us, eu }
class BadgeTimeZone {
const BadgeTimeZone(this.name, this.standardMinutes, this.rule);
final String name;
final int standardMinutes;
final DstRule rule;
}
const int timeZoneNotSet = 0;
const List<BadgeTimeZone> badgeTimeZones = [
BadgeTimeZone('not set', 0, DstRule.none),
BadgeTimeZone('UTC', 0, DstRule.none),
BadgeTimeZone('Eastern', -300, DstRule.us),
BadgeTimeZone('Central', -360, DstRule.us),
BadgeTimeZone('Mountain', -420, DstRule.us),
BadgeTimeZone('Arizona', -420, DstRule.none),
BadgeTimeZone('Pacific', -480, DstRule.us),
BadgeTimeZone('Alaska', -540, DstRule.us),
BadgeTimeZone('Hawaii', -600, DstRule.none),
BadgeTimeZone('UK', 0, DstRule.eu),
BadgeTimeZone('Central EU', 60, DstRule.eu),
BadgeTimeZone('Eastern EU', 120, DstRule.eu),
BadgeTimeZone('UTC-12', -720, DstRule.none),
BadgeTimeZone('UTC-11', -660, DstRule.none),
BadgeTimeZone('UTC-10', -600, DstRule.none),
BadgeTimeZone('UTC-9', -540, DstRule.none),
BadgeTimeZone('UTC-8', -480, DstRule.none),
BadgeTimeZone('UTC-7', -420, DstRule.none),
BadgeTimeZone('UTC-6', -360, DstRule.none),
BadgeTimeZone('UTC-5', -300, DstRule.none),
BadgeTimeZone('UTC-4', -240, DstRule.none),
BadgeTimeZone('UTC-3', -180, DstRule.none),
BadgeTimeZone('UTC-2', -120, DstRule.none),
BadgeTimeZone('UTC-1', -60, DstRule.none),
BadgeTimeZone('UTC+1', 60, DstRule.none),
BadgeTimeZone('UTC+2', 120, DstRule.none),
BadgeTimeZone('UTC+3', 180, DstRule.none),
BadgeTimeZone('UTC+4', 240, DstRule.none),
BadgeTimeZone('UTC+5', 300, DstRule.none),
BadgeTimeZone('UTC+6', 360, DstRule.none),
BadgeTimeZone('UTC+7', 420, DstRule.none),
BadgeTimeZone('UTC+8', 480, DstRule.none),
BadgeTimeZone('UTC+9', 540, DstRule.none),
BadgeTimeZone('UTC+10', 600, DstRule.none),
BadgeTimeZone('UTC+11', 660, DstRule.none),
BadgeTimeZone('UTC+12', 720, DstRule.none),
BadgeTimeZone('UTC+13', 780, DstRule.none),
BadgeTimeZone('UTC+14', 840, DstRule.none),
BadgeTimeZone('UTC-3:30', -210, DstRule.none),
BadgeTimeZone('UTC+5:30', 330, DstRule.none),
BadgeTimeZone('UTC+9:30', 570, DstRule.none),
];
/// The first fixed-offset zone (`kFirstFixed`).
const int _firstFixedZone = 12;
bool _isSet(int index) => index > 0 && index < badgeTimeZones.length;
/// The zone's name, or the raw index for one this client does not know.
String timeZoneName(int index) => index >= 0 && index < badgeTimeZones.length
? badgeTimeZones[index].name
: 'Zone $index';
int _nthSunday(int year, int month, int n) {
final first = DateTime.utc(year, month, 1);
final toSunday = (DateTime.sunday - first.weekday) % 7;
return 1 + toSunday + 7 * (n - 1);
}
int _lastSunday(int year, int month) {
final last = DateTime.utc(year, month + 1, 0);
return last.day - (last.weekday % 7);
}
/// Port of firmware `inDaylightSaving()`: US from 02:00 local on the second
/// Sunday of March to 02:00 local daylight time on the first Sunday of
/// November; EU from 01:00 UTC on the last Sunday of March to 01:00 UTC on
/// the last Sunday of October.
bool _inDaylightSaving(BadgeTimeZone z, DateTime utc) {
final y = utc.year;
switch (z.rule) {
case DstRule.us:
final start = DateTime.utc(
y,
3,
_nthSunday(y, 3, 2),
2,
).subtract(Duration(minutes: z.standardMinutes));
final end = DateTime.utc(
y,
11,
_nthSunday(y, 11, 1),
2,
).subtract(Duration(minutes: z.standardMinutes + 60));
return !utc.isBefore(start) && utc.isBefore(end);
case DstRule.eu:
final start = DateTime.utc(y, 3, _lastSunday(y, 3), 1);
final end = DateTime.utc(y, 10, _lastSunday(y, 10), 1);
return !utc.isBefore(start) && utc.isBefore(end);
case DstRule.none:
return false;
}
}
/// Minutes to add to UTC at [utc] in zone [index], daylight saving included.
/// Null for "not set" and for an index this client does not know.
int? timeZoneOffsetMinutes(int index, DateTime utc) {
if (!_isSet(index)) return null;
final z = badgeTimeZones[index];
return z.standardMinutes + (_inDaylightSaving(z, utc.toUtc()) ? 60 : 0);
}
/// "UTC-4", "UTC+5:30", "UTC+0".
String formatUtcOffset(int minutes) {
final sign = minutes < 0 ? '-' : '+';
final a = minutes.abs();
final mins = a % 60;
return 'UTC$sign${a ~/ 60}${mins == 0 ? '' : ':${mins.toString().padLeft(2, '0')}'}';
}
/// The zone that matches the phone, as the badge suggests one from GPS.
///
/// A named zone matches when its offset equals the phone's now, in January and
/// in July, so its daylight rule agrees as well as its current offset. Failing
/// that, the fixed zone for the phone's current offset. Null when nothing fits.
///
/// [offsetAt] is the phone's UTC offset at a local instant; injectable so the
/// match can be tested without depending on the machine's own zone.
int? suggestTimeZone({
required DateTime now,
required Duration Function(DateTime local) offsetAt,
}) {
final year = now.year;
final probes = [now, DateTime(year, 1, 15, 12), DateTime(year, 7, 15, 12)];
// From 2: UTC (1) is the fallback below, so a UK phone in winter is not
// offered plain UTC.
for (var i = 2; i < _firstFixedZone; i++) {
final matches = probes.every(
(t) => timeZoneOffsetMinutes(i, t.toUtc()) == offsetAt(t).inMinutes,
);
if (matches) return i;
}
final current = offsetAt(now).inMinutes;
if (current == 0) return 1;
for (var i = _firstFixedZone; i < badgeTimeZones.length; i++) {
if (badgeTimeZones[i].standardMinutes == current) return i;
}
return null;
}

@ -139,6 +139,23 @@ class ChannelMessage {
return pathHashSizeBytes(pl);
}
/// Hash width to group this message's path bytes with: the packet's own
/// declared width when a path-len byte was stored, else [deviceWidth], the
/// radio's device-wide mode, for legacy and flood-sentinel records. The
/// device-wide width belongs to the local radio, not to a packet that may
/// have originated under a different mode (#985).
int effectivePathHashWidth(int deviceWidth) {
final pl = pathLength;
if (pl == null || pl < 0) return deviceWidth < 1 ? 1 : deviceWidth;
return pathHashSizeBytes(pl);
}
/// The firmware path_len field is an unsigned packed byte. A signed read
/// turned every 3-byte-width value (>= 0x80) negative, which the flood
/// sentinel check then swallowed (#985). 0xFF is the firmware's
/// direct-route marker and maps to the -1 sentinel, as before.
static int _decodePathLenField(int raw) => raw == 0xFF ? -1 : raw;
ChannelMessage copyWith({
ChannelMessageStatus? status,
List<Repeat>? repeats,
@ -229,11 +246,11 @@ class ChannelMessage {
isOutgoing = (reader.readByte() & 0x01) != 0;
reader.skipBytes(1); // Skip reserved2
channelIdx = reader.readByte();
pathLen = reader.readInt8();
pathLen = _decodePathLenField(reader.readByte());
txtType = reader.readByte();
} else {
channelIdx = reader.readByte();
pathLen = reader.readInt8();
pathLen = _decodePathLenField(reader.readByte());
txtType = reader.readByte();
}
final timestampRaw = reader.readUInt32LE();

@ -5,7 +5,40 @@ import '../connector/meshcore_protocol.dart';
class Contact {
final Uint8List publicKey;
final String name;
/// The name this node last gave us, from its own signed advert or from an
/// unsigned contact-share card. Never the user's label. (#750)
///
/// Called "received" rather than "advert" deliberately: a contact-share card
/// is plain unsigned channel text, so a card-added contact carries a name here
/// that was never advertised by anyone. Whether a signed advert has ever been
/// seen is a separate question, answered by [isAdvertVerified].
///
/// **This is what goes on the wire and into storage.** Read [name] to display.
/// Sending [name] to the radio would overwrite the shared record of what the
/// node calls itself with one user's private label.
final String receivedName;
/// The user's own label for this node, or null when they have not set one.
///
/// Client-side only. Firmware holds a single `char name[32]` per contact
/// (`ContactInfo.h:10`) and has no override concept, so this can never be sent
/// to the radio. Stock MeshCore's CUSTOM NAME field works the same way.
final String? customName;
/// What to show the user: their own label if they set one, otherwise the name
/// the node gave us.
///
/// Every display site reads this, which is why it keeps the short name: an
/// existing or future read of `.name` is already correct and cannot forget.
/// An empty or whitespace-only custom name counts as unset, so clearing the
/// text field cannot leave a contact with a blank name and no way back.
String get name {
final custom = customName;
if (custom == null || custom.trim().isEmpty) return receivedName;
return custom;
}
final int type;
final int flags;
@ -38,7 +71,8 @@ class Contact {
Contact({
required this.publicKey,
required this.name,
required this.receivedName,
this.customName,
required this.type,
this.flags = 0,
required this.pathLength,
@ -89,9 +123,20 @@ class Contact {
bool get isFavorite => (flags & contactFlagFavorite) != 0;
/// A chat node (phone/radio companion), as opposed to a repeater, room
/// server or sensor. Remote CLI (#999) targets companions; repeaters and
/// room servers have their own CLI via the repeater hub.
bool get isCompanion => type == advTypeChat;
Contact copyWith({
Uint8List? publicKey,
String? name,
String? receivedName,
String? customName,
/// Clears the user's label so [name] falls back to [receivedName]. A null
/// `customName` means "leave it alone", the same as every other field here,
/// so removing one needs its own flag. (#750)
bool clearCustomName = false,
int? type,
int? flags,
int? pathLength,
@ -110,7 +155,8 @@ class Contact {
}) {
return Contact(
publicKey: publicKey ?? this.publicKey,
name: name ?? this.name,
receivedName: receivedName ?? this.receivedName,
customName: clearCustomName ? null : (customName ?? this.customName),
type: type ?? this.type,
flags: flags ?? this.flags,
pathLength: pathLength ?? this.pathLength,
@ -238,7 +284,8 @@ class Contact {
return Contact(
publicKey: pubKey,
name: name.isEmpty ? 'Unknown' : name,
// Straight off the wire, so a received name by definition. (#750)
receivedName: name.isEmpty ? 'Unknown' : name,
type: type,
flags: flags,
pathLength:
@ -275,8 +322,13 @@ class Contact {
///
/// Note this shares only the identity. It carries no path and no advert, so
/// the receiving side gets an unverified stub exactly as we do.
/// Shares [receivedName], never `.name`. A share payload becomes the
/// RECEIVED name on every device that imports it, so sending a custom name
/// would push one user's private label out as another operator's ground
/// truth, overwriting a signed advert name. Worse than sending it to our own
/// radio, because it propagates. (#750, found by the pre-PR review)
String toShareUri() =>
buildShareUri(publicKeyHex: publicKeyHex, name: name, type: type);
buildShareUri(publicKeyHex: publicKeyHex, name: receivedName, type: type);
/// Builds the reference-app contact share URI from raw parts.
///
@ -313,8 +365,12 @@ class Contact {
///
/// Use the URI form for a QR, a DM, or an out-of-band paste. Use this for a
/// channel.
String toChannelShare() =>
buildChannelShare(publicKeyHex: publicKeyHex, name: name, type: type);
/// Shares [receivedName], never `.name`. Same reason as [toShareUri]. (#750)
String toChannelShare() => buildChannelShare(
publicKeyHex: publicKeyHex,
name: receivedName,
type: type,
);
/// Builds the compact channel share from raw parts, so this device can share
/// its OWN identity without constructing a [Contact]. (#611)
@ -378,7 +434,10 @@ class Contact {
return Contact(
publicKey: publicKey,
name: name.isEmpty ? 'Unknown' : name,
// A contact-share card is unsigned channel text, so this name was chosen
// by whoever posted the card and may not be the key holder. Received, not
// the user's label, and not advertised either. (#750, #645)
receivedName: name.isEmpty ? 'Unknown' : name,
type: type,
flags: 0,
pathLength: -1,
@ -440,8 +499,9 @@ class Contact {
return Contact(
publicKey: publicKey,
// Matches fromFrame's convention for a nameless contact.
name: (name == null || name.isEmpty) ? 'Unknown' : name,
// Matches fromFrame's convention for a nameless contact. Received: the
// URI's author picked this name, the same as a card. (#750)
receivedName: (name == null || name.isEmpty) ? 'Unknown' : name,
type: type,
flags: 0,
// Flood until the mesh teaches us a path. Mirrors the firmware's
@ -476,4 +536,7 @@ class Contact {
bool get teleBaseEnabled => (flags & contactFlagTeleBase) != 0;
bool get teleLocEnabled => (flags & contactFlagTeleLoc) != 0;
bool get teleEnvEnabled => (flags & contactFlagTeleEnv) != 0;
/// This contact may run remote CLI (TXT type 3) commands on our radio (#887).
bool get remoteCliAllowed => (flags & contactFlagRemoteCliAllowed) != 0;
}

@ -13,6 +13,11 @@ class Message {
final DateTime timestamp;
final bool isOutgoing;
final bool isCli;
/// True when this is an inbound remote-CLI COMMAND (TXT type 3) another
/// contact sent to run on our radio, as opposed to [isCli] (a CLI data
/// reply). Rendered distinctly and never SMAZ-decoded (#890).
final bool isCliCommand;
final MessageStatus status;
final String? originalText;
final String? translatedText;
@ -68,6 +73,7 @@ class Message {
required this.timestamp,
required this.isOutgoing,
this.isCli = false,
this.isCliCommand = false,
this.status = MessageStatus.pending,
String? messageId,
this.originalText,
@ -113,6 +119,7 @@ class Message {
int? pathLength,
Uint8List? pathBytes,
bool? isCli,
bool? isCliCommand,
Object? originalText = _unset,
Object? translatedText = _unset,
Object? translatedLanguageCode = _unset,
@ -133,6 +140,7 @@ class Message {
timestamp: timestamp,
isOutgoing: isOutgoing,
isCli: isCli ?? this.isCli,
isCliCommand: isCliCommand ?? this.isCliCommand,
status: status ?? this.status,
messageId: messageId,
originalText: originalText == _unset

@ -0,0 +1,32 @@
import 'dart:typed_data';
import 'package:meshcore_open/helpers/region_key.dart';
/// A flood region as discovered from a repeater.
///
/// [name] is the `#`-stripped region name the firmware reports over the air.
/// Value equality is by name so a discovery service can dedupe replies.
class Region {
final String name;
const Region(this.name);
/// A wildcard region (matches a family of names) rather than a single one.
bool get isWildcard => name.contains('*');
/// A private region whose key is not derivable from its name.
bool get isPrivate => isPrivateRegionName(name);
/// The 16-byte transport key for this region, or null when it is private
/// or blank.
Uint8List? get transportKey => transportKeyForName(name);
@override
bool operator ==(Object other) => other is Region && other.name == name;
@override
int get hashCode => name.hashCode;
@override
String toString() => 'Region($name)';
}

@ -28,7 +28,10 @@ import '../models/translation_support.dart';
import '../models/app_settings.dart';
import '../services/app_settings_service.dart';
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_tone.dart';
import '../services/block_service.dart';
import '../services/chat_text_scale_service.dart';
import '../services/translation_service.dart';
@ -320,6 +323,46 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
);
}
/// Open the Set Region Scope picker for the current channel (#815).
Future<void> _openRegionScopeDialog() async {
final connector = context.read<MeshCoreConnector>();
final channelIndex = _currentChannel.index;
final current = await connector.channelRegionScope(channelIndex);
final repeaters = connector.contacts
.where((c) => c.type == advTypeRepeater)
.map(
(c) => RepeaterChoice(
name: c.name,
pubKey: c.publicKey,
// A direct (0-hop) repeater has pathLength 0 and an empty path and
// is reachable (the best case). Only pathLength -1 (flood/unknown)
// has no usable route, so only that is treated as "no path".
hasPath: c.pathLength >= 0,
),
)
.toList();
final service = RegionDiscoveryService(
(pub, timeout) =>
connector.discoverRegions(repeaterPubKey: pub, timeout: timeout),
);
if (!mounted) {
service.dispose();
return;
}
await showDialog<void>(
context: context,
builder: (dialogContext) => ChannelRegionScopeDialog(
channelName: _currentChannel.name,
currentScope: current,
repeaters: repeaters,
service: service,
onSave: (region) =>
connector.setChannelRegionScope(channelIndex, region),
),
);
service.dispose();
}
/// Switch to another channel picked from the nav panel.
///
/// Swaps the conversation in place rather than pushing a route, so a pinned
@ -431,10 +474,16 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
onSelected: (value) {
if (value == 'notifications') {
showChannelNotifyModeDialog(context, widget.channel);
} else if (value == 'radioTone') {
final connector = context.read<MeshCoreConnector>();
requestChannelRadioTone(connector, _currentChannel.index);
showChannelRadioToneDialog(context, _currentChannel);
} else if (value == 'clearChat') {
context.read<MeshCoreConnector>().clearMessagesForChannel(
_currentChannel.index,
);
} else if (value == 'setRegionScope') {
_openRegionScopeDialog();
}
},
itemBuilder: (context) => [
@ -445,8 +494,10 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
Icon(
channelNotifyModeIcon(
context.read<AppSettingsService>().channelNotifyMode(
identityKey: channelNotifyKeyFor(widget.channel),
channelName: widget.channel.name,
devicePrefix: context
.read<MeshCoreConnector>()
.selfPublicKeyHex,
pskHex: widget.channel.pskHex,
),
),
size: 20,
@ -456,6 +507,28 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
],
),
),
if (context.read<MeshCoreConnector>().supportsTunes)
const PopupMenuItem(
value: 'radioTone',
child: Row(
children: [
Icon(Icons.music_note_outlined, size: 20),
SizedBox(width: 12),
Text('Radio tone'),
],
),
),
if (context.read<MeshCoreConnector>().supportsRegionScope)
PopupMenuItem(
value: 'setRegionScope',
child: Row(
children: [
const Icon(Icons.travel_explore, size: 20),
const SizedBox(width: 12),
Text(context.l10n.setRegionScope_menu),
],
),
),
PopupMenuItem(
value: 'clearChat',
child: Row(
@ -869,7 +942,11 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
Widget _buildMessageBubble(ChannelMessage message, double textScale) {
final settingsService = context.watch<AppSettingsService>();
final enableTracing = settingsService.settings.enableMessageTracing;
final hashWidth = context.read<MeshCoreConnector>().pathHashByteWidth;
// The packet's own hash width; device-wide mode only for legacy records
// with no stored path-len byte (#985).
final hashWidth = message.effectivePathHashWidth(
context.read<MeshCoreConnector>().pathHashByteWidth,
);
final isOutgoing = message.isOutgoing;
final gifUrl = GifHelper.resolveGifUrl(message.text);
final gifReplyName = gifUrl != null
@ -1710,8 +1787,13 @@ class _ChannelChatScreenState extends State<ChannelChatScreen> {
/// truncated with … to fit the channel byte budget, fired directly. (#106)
void _sendRouteReply(ChannelMessage message) {
final connector = context.read<MeshCoreConnector>();
final w = connector.pathHashByteWidth;
final hops = message.pathBytes.length ~/ (w < 1 ? 1 : w);
final w = message.effectivePathHashWidth(connector.pathHashByteWidth);
// Same number the hop badge shows; byte division is only the fallback for
// records with no decodable path-len byte (#985).
final decodedHops = message.hopCount;
final hops = (decodedHops != null && decodedHops >= 0)
? decodedHops
: message.pathBytes.length ~/ w;
final prefix =
'@[${message.senderName}] ↩ ${context.l10n.chat_hopsCount(hops)} · via ';
final maxBytes = maxChannelMessageBytes(

@ -51,13 +51,19 @@ class ChannelMessagePathScreen extends StatelessWidget {
final primaryPath = !channelMessage && !message.isOutgoing
? Uint8List.fromList(primaryPathTmp.reversed.toList())
: primaryPathTmp;
final hashWidth = connector.pathHashByteWidth;
// The packet's own declared width; the device-wide mode only covers
// legacy records with no stored path-len byte. Grouping a foreign
// packet's hashes by the local radio's mode contradicted the decoded
// hop count on this same screen, 19 vs 39 on one packet (#985).
final hashWidth = message.effectivePathHashWidth(
connector.pathHashByteWidth,
);
final hops = _buildPathHops(primaryPath, connector, l10n, hashWidth);
final hasHopDetails = primaryPath.isNotEmpty;
// Observed = bytes we hold / this path's width. Claimed = the hop count
// the path-len byte already carries; dividing it again halved it. (#309)
final observedLabel = _formatObservedHops(
primaryPath.length ~/ message.pathHashSize,
primaryPath.length ~/ hashWidth,
message.hopCount,
l10n,
);
@ -78,9 +84,7 @@ class ChannelMessagePathScreen extends StatelessWidget {
flipPathAround: true,
reversePathAround:
!(!channelMessage && !message.isOutgoing),
pathHashByteWidth: context
.read<MeshCoreConnector>()
.pathHashByteWidth,
pathHashByteWidth: hashWidth,
),
),
),
@ -183,7 +187,11 @@ class ChannelMessagePathScreen extends StatelessWidget {
Widget _buildPathVariants(BuildContext context, List<Uint8List> variants) {
final l10n = context.l10n;
final hashWidth = context.read<MeshCoreConnector>().pathHashByteWidth;
// Variants are repeats of the same origin's packet, so the message's own
// width applies to them too (#985).
final hashWidth = message.effectivePathHashWidth(
context.read<MeshCoreConnector>().pathHashByteWidth,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@ -493,7 +501,9 @@ class _ChannelMessagePathMapScreenState
: selectedPathTmp;
final selectedIndex = _indexForPath(selectedPath, observedPaths);
final hashWidth = connector.pathHashByteWidth;
final hashWidth = widget.message.effectivePathHashWidth(
connector.pathHashByteWidth,
);
final hops = _buildPathHops(
selectedPath,
connector,
@ -653,7 +663,9 @@ class _ChannelMessagePathMapScreenState
ValueChanged<int> onSelected,
) {
final l10n = context.l10n;
final hashWidth = context.read<MeshCoreConnector>().pathHashByteWidth;
final hashWidth = widget.message.effectivePathHashWidth(
context.read<MeshCoreConnector>().pathHashByteWidth,
);
final selectedPath = paths[selectedIndex];
final label = selectedPath.isPrimary
? l10n.channelPath_primaryPath(selectedIndex + 1)

@ -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_tone.dart';
import '../widgets/battery_optimization_banner.dart';
import '../helpers/snack_bar_builder.dart';
import 'channel_chat_screen.dart';
@ -490,8 +491,8 @@ class _ChannelsScreenState extends State<ChannelsScreen>
final parentContext = context;
final settingsService = context.read<AppSettingsService>();
final notifyMode = settingsService.channelNotifyMode(
identityKey: channelNotifyKeyFor(channel),
channelName: channel.name,
devicePrefix: connector.selfPublicKeyHex,
pskHex: channel.pskHex,
);
showModalBottomSheet(
@ -534,6 +535,18 @@ class _ChannelsScreenState extends State<ChannelsScreen>
}
},
),
// 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(
channel: channel,
onTap: () async {
Navigator.pop(sheetContext);
await Future.delayed(const Duration(milliseconds: 100));
if (parentContext.mounted) {
showChannelRadioToneDialog(parentContext, channel);
}
},
),
ListTile(
leading: const Icon(Icons.delete_outline, color: Colors.red),
title: Text(

@ -38,6 +38,7 @@ import '../widgets/elements_ui.dart';
import '../widgets/mention_autocomplete.dart';
import '../helpers/emoji_shortcodes.dart';
import 'channel_message_path_screen.dart';
import 'device_cli_screen.dart';
import 'map_screen.dart';
import '../utils/emoji_utils.dart';
import '../widgets/emoji_picker.dart';
@ -353,6 +354,15 @@ class _ChatScreenState extends State<ChatScreen> {
),
);
}
if (value == 'cliConsole') {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DeviceCliScreen(remoteContact: widget.contact),
),
);
}
if (value == 'clearChat') {
connector.clearMessagesForContact(widget.contact);
}
@ -402,6 +412,22 @@ class _ChatScreenState extends State<ChatScreen> {
],
),
),
// Remote CLI is a companion feature (#999), and the
// connected radio must speak the 1.18 CLI to send it.
if (DeviceCliScreen.offersRemoteConsole(
contact: widget.contact,
classification: connector.classification,
))
PopupMenuItem(
value: 'cliConsole',
child: Row(
children: [
const Icon(Icons.terminal, size: 20),
const SizedBox(width: 12),
Text(context.l10n.contact_cliConsole),
],
),
),
PopupMenuItem(
value: 'clearChat',
child: Row(
@ -1536,7 +1562,8 @@ class _ChatScreenState extends State<ChatScreen> {
final canTranslateMessage =
translationService.canTranslateIncoming(
text: message.text,
isCli: message.isCli,
// A received command is a CLI string, never translate it (#890).
isCli: message.isCli || message.isCliCommand,
isOutgoing: message.isOutgoing,
) &&
(message.translatedText?.trim().isEmpty ?? true);

@ -29,6 +29,7 @@ import '../widgets/empty_state.dart';
import '../widgets/blocked_badge.dart';
import '../widgets/app_shell.dart';
import '../widgets/contact_filter_rail.dart';
import '../widgets/contact_rename_dialog.dart';
import '../widgets/contact_settings_dialog.dart';
import '../widgets/path_selection_dialog.dart';
import '../widgets/repeater_login_dialog.dart';
@ -1310,8 +1311,25 @@ class _ContactsScreenState extends State<ContactsScreen>
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Stock parity: any node can carry a custom name, and the node's
// own name stays underneath where the user can still see it. (#750)
ListTile(
leading: const Icon(Icons.drive_file_rename_outline),
title: Text(context.l10n.contact_rename),
subtitle: contact.customName == null
? null
: Text(
context.l10n.contact_nodeCallsItself(
contact.receivedName,
),
),
onTap: () {
Navigator.pop(sheetContext);
showContactRenameDialog(context, contact);
},
),
// Same destination as the chat ellipsis -> Contact settings (#351).
// First item, so the destructive Block tile stays separated below.
// Kept above the destructive Block tile, which stays below.
ListTile(
leading: const Icon(Icons.settings_outlined),
title: Text(context.l10n.contact_settings),

@ -0,0 +1,580 @@
// CLI console (#883 local, #999 remote; interop plan F2/E2.1 + F3/E3.1). The
// local-device counterpart of RepeaterCliScreen, built to the owner-approved
// mockup on #883, and - with a [remoteContact] - the surface for remote CLI to
// a companion over the mesh. One console, one transcript; the transport
// ([CliConsoleTransport]) is what differs (local frame 66/29 vs remote TXT
// type-3). Same pattern, minus path/flood selection and retries: one send per
// command, a timeout surfaced as its own transcript row.
//
// Secrecy rule (W3/F4, applied here from day one): a reply to a command that
// names a secret (anything containing "pwd"/"password") renders masked and is
// only recoverable via long-press-to-copy; its cleartext never enters the
// widget tree as selectable text and is never logged by this screen.
//
// Population gating is NOT here: offering the local console only where the
// classifier allows frame 66 is #884; offering the remote console only on a
// companion contact is the entry point in chat_screen (#999).
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../connector/device_population.dart';
import '../connector/meshcore_connector.dart';
import '../helpers/device_name_validator.dart';
import '../helpers/snack_bar_builder.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../services/cli_console_transport.dart';
enum _EntryKind { command, reply, timeout, sendFailed }
class _ConsoleEntry {
_ConsoleEntry.command(this.text)
: kind = _EntryKind.command,
isError = false,
secret = false,
truncated = false,
latencyMs = null;
_ConsoleEntry.reply(
this.text, {
required this.latencyMs,
required this.truncated,
required this.secret,
required this.isError,
}) : kind = _EntryKind.reply;
_ConsoleEntry.timeout(this.text)
: kind = _EntryKind.timeout,
isError = true,
secret = false,
truncated = false,
latencyMs = null;
_ConsoleEntry.sendFailed(this.text)
: kind = _EntryKind.sendFailed,
isError = true,
secret = false,
truncated = false,
latencyMs = null;
final _EntryKind kind;
/// For a secret reply this still holds the cleartext (it is the long-press
/// copy source) - rendering is what masks it, so nothing here may be handed
/// to a logger or a selectable widget when [secret] is set.
final String text;
final bool isError;
final bool secret;
final bool truncated;
final int? latencyMs;
}
class DeviceCliScreen extends StatefulWidget {
const DeviceCliScreen({
super.key,
this.commandTimeout,
this.remoteContact,
this.transportOverride,
});
/// Per-command reply window; null uses the transport's default. Tests shrink
/// it so a timeout row renders without a 10 s pump. The remote transport
/// computes its own mesh window and ignores this.
final Duration? commandTimeout;
/// When set, the console runs CLI on this remote contact over the mesh
/// (type-3 for a companion, #999) instead of the connected device.
final Contact? remoteContact;
/// Test seam: a transport to use instead of building one from
/// [remoteContact]. Lets a test drive a deterministic reply or timeout. The
/// screen takes ownership and disposes it.
@visibleForTesting
final CliConsoleTransport? transportOverride;
/// Whether to offer the remote console for [contact]. Two conditions, both
/// required: the target is a companion (repeaters and room servers have
/// their own CLI via the repeater hub), and the CONNECTED radio speaks the
/// 1.18 CLI. A pre-1.18 radio refuses to send a type-3 command
/// (companion-v1.17.1 accepts only plain and CLI_DATA in CMD_SEND_TXT_MSG;
/// 1.18.0 adds CLI_COMMAND), so offering the console there would only
/// produce failures. Type-3 send and the local CLI frame shipped together
/// in 1.18, so this reuses the local console's gate. A null classification
/// (disconnected, or not yet classified) offers nothing.
static bool offersRemoteConsole({
required Contact contact,
required Classification? classification,
}) => contact.isCompanion && (classification?.allowsCliFrame ?? false);
@override
State<DeviceCliScreen> createState() => _DeviceCliScreenState();
}
class _DeviceCliScreenState extends State<DeviceCliScreen> {
final TextEditingController _commandController = TextEditingController();
final FocusNode _commandFocusNode = FocusNode();
final ScrollController _scrollController = ScrollController();
final List<_ConsoleEntry> _entries = [];
int _historyIndex = -1;
CliConsoleTransport? _transport;
bool get _isRemote => widget.remoteContact != null;
@override
void initState() {
super.initState();
final connector = Provider.of<MeshCoreConnector>(context, listen: false);
_transport =
widget.transportOverride ??
(widget.remoteContact == null
? LocalCliTransport(connector)
: RemoteCliTransport(connector, widget.remoteContact!));
}
@override
void dispose() {
_transport?.dispose();
_commandController.dispose();
_commandFocusNode.dispose();
_scrollController.dispose();
super.dispose();
}
/// The device-side handlers echo secrets in cleartext (stock `get wifi.pwd`
/// reads back the stored password, INVESTIGATION.md section C) - the client
/// is the only place masking can happen, so match generously.
static bool isSecretCommand(String command) {
final c = command.toLowerCase();
return c.contains('pwd') || c.contains('password');
}
/// The wire has no error codes; stock firmware answers errors as plain
/// "Unknown command" / "Error..." strings (INVESTIGATION.md section A1), so
/// error styling is string-matched, exactly as the mockup states.
static bool looksLikeErrorReply(String text) {
final t = text.trimLeft();
return t.startsWith('Unknown command') || t.startsWith('Error');
}
/// Extracts the name argument of a `set name <value>` command (any casing,
/// any inner spacing), or null when the command is not one. #885 mirrors the
/// device's own name-character rejection before the frame is sent.
static String? setNameArg(String command) {
final m = RegExp(
r'^set\s+name\s+(.+)$',
caseSensitive: false,
).firstMatch(command.trim());
return m?.group(1);
}
Future<void> _sendCommand() async {
final command = _commandController.text.trim();
if (command.isEmpty) return;
final transport = _transport;
if (transport == null) return;
// Mirror the firmware's `set name` character rejection locally: show the
// typed command and a rejection row, and never send the frame (#885).
final nameArg = setNameArg(command);
if (nameArg != null) {
final bad = forbiddenCharsIn(nameArg);
if (bad.isNotEmpty) {
setState(() {
_entries.add(_ConsoleEntry.command(command));
_entries.add(
_ConsoleEntry.sendFailed(
context.l10n.deviceCli_nameRejected(bad.join(' ')),
),
);
});
_commandController.clear();
_historyIndex = -1;
_commandFocusNode.requestFocus();
_scrollToBottom();
return;
}
}
final secret = isSecretCommand(command);
setState(() {
_entries.add(_ConsoleEntry.command(command));
});
_commandController.clear();
_historyIndex = -1;
_commandFocusNode.requestFocus();
_scrollToBottom();
final stopwatch = Stopwatch()..start();
_ConsoleEntry entry;
try {
final reply = await transport.run(
command,
timeout: widget.commandTimeout,
);
stopwatch.stop();
entry = _ConsoleEntry.reply(
reply.text,
latencyMs: stopwatch.elapsedMilliseconds,
truncated: reply.atReplyBound,
secret: secret,
isError: looksLikeErrorReply(reply.text),
);
} on CliConsoleTimeout catch (e) {
if (!mounted) return;
// A remote companion that has not granted us remote CLI simply never
// replies, so a timeout is as likely a permission answer as a lost
// packet. The remote row says so and notes we did not retry (#891); the
// local row keeps the plain frame-timeout wording. The permission hint
// assumes a companion target - the only remote entry (chat_screen) is
// companion-gated; a repeater target would need different wording.
entry = _ConsoleEntry.timeout(
_isRemote
? context.l10n.deviceCli_remoteNoReply(command, e.secondsText)
: context.l10n.deviceCli_noReply(command, e.secondsText),
);
} on CliConsoleUnsupported {
if (!mounted) return;
// The connected radio refused the send itself (pre-1.18 firmware), so
// nothing went out: say so now instead of waiting out a timeout that
// would blame the target.
entry = _ConsoleEntry.sendFailed(
context.l10n.deviceCli_remoteUnsupported(command),
);
} catch (e) {
if (!mounted) return;
entry = _ConsoleEntry.sendFailed(
context.l10n.deviceCli_sendFailed(e.toString()),
);
}
if (!mounted) return;
setState(() {
_entries.add(entry);
});
_scrollToBottom();
}
void _scrollToBottom() {
Future.delayed(const Duration(milliseconds: 100), () {
if (_scrollController.hasClients) {
_scrollController.animateTo(
_scrollController.position.maxScrollExtent,
duration: const Duration(milliseconds: 200),
curve: Curves.easeOut,
);
}
});
}
void _navigateHistory(bool up) {
final commands = _entries
.where((e) => e.kind == _EntryKind.command)
.map((e) => e.text)
.toList()
.reversed
.toList();
if (commands.isEmpty) return;
if (up) {
if (_historyIndex < commands.length - 1) {
_historyIndex++;
}
} else {
if (_historyIndex > 0) {
_historyIndex--;
} else {
_historyIndex = -1;
_commandController.clear();
return;
}
}
if (_historyIndex >= 0 && _historyIndex < commands.length) {
_commandController.text = commands[_historyIndex];
_commandController.selection = TextSelection.fromPosition(
TextPosition(offset: _commandController.text.length),
);
}
}
void _clearHistory() {
setState(() {
_entries.clear();
_historyIndex = -1;
});
}
void _copySecret(String cleartext) {
Clipboard.setData(ClipboardData(text: cleartext));
showDismissibleSnackBar(
context,
content: Text(context.l10n.deviceCli_secretCopied),
);
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final connector = context.watch<MeshCoreConnector>();
final String title;
final String subtitle;
if (_isRemote) {
title = l10n.deviceCli_remoteTitle;
subtitle = widget.remoteContact!.name;
} else {
title = l10n.deviceCli_title;
final name = connector.selfName;
final version = connector.firmwareVersion;
subtitle = [
if (name != null && name.isNotEmpty) name,
if (version != null && version.isNotEmpty) '($version)',
].join(' ');
}
return Scaffold(
appBar: AppBar(
title: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(title),
if (subtitle.isNotEmpty)
Text(
subtitle,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.normal,
),
),
],
),
centerTitle: false,
actions: [
IconButton(
icon: const Icon(Icons.clear_all),
tooltip: l10n.repeater_clearHistory,
onPressed: _entries.isEmpty ? null : _clearHistory,
),
],
),
body: Column(
children: [
Expanded(
child: _entries.isEmpty ? _buildEmptyState() : _buildTranscript(),
),
const Divider(height: 1),
_buildCommandInput(),
],
),
);
}
Widget _buildEmptyState() {
final l10n = context.l10n;
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.terminal, size: 64, color: Colors.grey[400]),
const SizedBox(height: 16),
Text(
l10n.repeater_noCommandsSent,
style: TextStyle(fontSize: 16, color: Colors.grey[600]),
),
const SizedBox(height: 8),
Text(
l10n.deviceCli_emptyHint,
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
),
],
),
);
}
Widget _buildTranscript() {
return ListView.builder(
controller: _scrollController,
padding: const EdgeInsets.all(16),
itemCount: _entries.length,
itemBuilder: (context, index) => _buildEntry(_entries[index]),
);
}
Widget _buildEntry(_ConsoleEntry entry) {
final scheme = Theme.of(context).colorScheme;
final isCommand = entry.kind == _EntryKind.command;
final badgeColor = entry.isError
? scheme.errorContainer
: isCommand
? scheme.primaryContainer
: scheme.secondaryContainer;
final badgeIconColor = entry.isError
? scheme.onErrorContainer
: isCommand
? scheme.onPrimaryContainer
: scheme.onSecondaryContainer;
final badgeIcon = switch (entry.kind) {
_EntryKind.command => Icons.chevron_right,
_EntryKind.reply when entry.isError => Icons.warning_amber,
_EntryKind.reply => Icons.arrow_back,
_EntryKind.timeout => Icons.timer_off_outlined,
_EntryKind.sendFailed => Icons.warning_amber,
};
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.all(6),
decoration: BoxDecoration(
color: badgeColor,
borderRadius: BorderRadius.circular(4),
),
child: Icon(badgeIcon, size: 16, color: badgeIconColor),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
entry.secret ? _buildSecretText(entry) : _buildPlainText(entry),
if (entry.truncated) _buildTruncationBadge(),
],
),
),
if (entry.latencyMs != null) ...[
const SizedBox(width: 8),
Text(
context.l10n.deviceCli_latencyMs(entry.latencyMs!),
style: TextStyle(
fontSize: 11,
color: Theme.of(context).colorScheme.outline,
),
),
],
],
),
);
}
Widget _buildPlainText(_ConsoleEntry entry) {
final scheme = Theme.of(context).colorScheme;
final color = entry.isError
? scheme.error
: entry.kind == _EntryKind.command
? scheme.primary
: scheme.onSurface;
return SelectableText(
entry.text,
style: TextStyle(fontFamily: 'monospace', fontSize: 13, color: color),
);
}
/// Masked rendering: fixed-width dots regardless of the secret's length
/// (the dot count must not leak it), cleartext only via long-press copy.
Widget _buildSecretText(_ConsoleEntry entry) {
final scheme = Theme.of(context).colorScheme;
return GestureDetector(
onLongPress: () => _copySecret(entry.text),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
'●' * 8,
style: TextStyle(
fontFamily: 'monospace',
fontSize: 13,
color: scheme.onSurface,
),
),
const SizedBox(width: 8),
Flexible(
child: Text(
context.l10n.deviceCli_secretLongPressToCopy,
style: TextStyle(
fontSize: 12,
fontStyle: FontStyle.italic,
color: scheme.outline,
),
),
),
],
),
);
}
Widget _buildTruncationBadge() {
final scheme = Theme.of(context).colorScheme;
return Padding(
padding: const EdgeInsets.only(top: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.content_cut, size: 12, color: scheme.tertiary),
const SizedBox(width: 4),
Flexible(
child: Text(
context.l10n.deviceCli_truncatedByDevice,
style: TextStyle(
fontSize: 11,
fontStyle: FontStyle.italic,
color: scheme.tertiary,
),
),
),
],
),
);
}
Widget _buildCommandInput() {
final l10n = context.l10n;
return Container(
padding: const EdgeInsets.all(12),
color: Theme.of(context).colorScheme.surface,
child: SafeArea(
child: Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_upward, size: 20),
tooltip: l10n.repeater_previousCommand,
onPressed: () => _navigateHistory(true),
),
IconButton(
icon: const Icon(Icons.arrow_downward, size: 20),
tooltip: l10n.repeater_nextCommand,
onPressed: () => _navigateHistory(false),
),
const SizedBox(width: 8),
Expanded(
child: TextField(
controller: _commandController,
focusNode: _commandFocusNode,
decoration: InputDecoration(
hintText: l10n.deviceCli_commandHint,
border: const OutlineInputBorder(),
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 12,
),
prefixText: '> ',
),
style: const TextStyle(fontFamily: 'monospace'),
textInputAction: TextInputAction.send,
onSubmitted: (_) => _sendCommand(),
),
),
const SizedBox(width: 8),
IconButton.filled(
icon: const Icon(Icons.send),
onPressed: _sendCommand,
),
],
),
),
);
}
}

@ -0,0 +1,184 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../models/contact.dart';
import '../services/region_discovery_service.dart';
/// Discover the flood regions a repeater advertises (Feature #812, Epic #814).
///
/// Launched from the repeater hub for a specific repeater, so the source node
/// is [repeater]; the reply carries only region names and the repeater clock
/// (there is no per-region SNR on the wire). Each outcome renders distinctly:
/// loading, the region list, no-regions, timeout, or error.
class DiscoverRegionsScreen extends StatefulWidget {
const DiscoverRegionsScreen({
super.key,
required this.repeater,
this.service,
});
final Contact repeater;
/// Test seam: inject a service with a fake discoverer. In production the
/// service is built from the connector.
final RegionDiscoveryService? service;
@override
State<DiscoverRegionsScreen> createState() => _DiscoverRegionsScreenState();
}
class _DiscoverRegionsScreenState extends State<DiscoverRegionsScreen> {
late final RegionDiscoveryService _service;
late final bool _ownsService;
@override
void initState() {
super.initState();
final injected = widget.service;
_ownsService = injected == null;
if (injected != null) {
_service = injected;
} else {
final connector = context.read<MeshCoreConnector>();
_service = RegionDiscoveryService(
(pub, timeout) =>
connector.discoverRegions(repeaterPubKey: pub, timeout: timeout),
);
}
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _start();
});
}
void _start() => _service.discover(widget.repeater.publicKey);
@override
void dispose() {
if (_ownsService) _service.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return Scaffold(
appBar: AppBar(
title: Text(l10n.discoverRegions_title),
centerTitle: true,
),
body: ListenableBuilder(
listenable: _service,
builder: (context, _) => _body(l10n),
),
);
}
Widget _body(AppLocalizations l10n) {
final name = widget.repeater.name;
switch (_service.status) {
case RegionDiscoveryStatus.idle:
case RegionDiscoveryStatus.loading:
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 16),
Text(l10n.discoverRegions_loading(name)),
],
),
);
case RegionDiscoveryStatus.success:
return _regionList(l10n);
case RegionDiscoveryStatus.empty:
return _message(
stateKey: 'discoverRegionsEmpty',
icon: Icons.location_off,
text: l10n.discoverRegions_empty(name),
l10n: l10n,
);
case RegionDiscoveryStatus.timeout:
return _message(
stateKey: 'discoverRegionsTimeout',
icon: Icons.timer_off,
text: l10n.discoverRegions_timeout(name),
l10n: l10n,
);
case RegionDiscoveryStatus.error:
return _message(
stateKey: 'discoverRegionsError',
icon: Icons.error_outline,
text: _service.errorMessage ?? l10n.discoverRegions_error,
l10n: l10n,
);
}
}
Widget _regionList(AppLocalizations l10n) {
return Column(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
const Icon(Icons.cell_tower),
const SizedBox(width: 8),
Expanded(
child: Text(
l10n.discoverRegions_source(widget.repeater.name),
style: Theme.of(context).textTheme.titleMedium,
),
),
],
),
),
const Divider(height: 1),
Expanded(
child: ListView.builder(
itemCount: _service.regions.length,
itemBuilder: (context, i) {
final region = _service.regions[i];
return ListTile(
leading: Icon(region.isWildcard ? Icons.public : Icons.tag),
title: Text(region.name),
);
},
),
),
],
);
}
Widget _message({
required String stateKey,
required IconData icon,
required String text,
required AppLocalizations l10n,
}) {
return Center(
key: Key(stateKey),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 48),
const SizedBox(height: 12),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 32),
child: Text(text, textAlign: TextAlign.center),
),
Padding(
padding: const EdgeInsets.only(top: 16),
child: ElevatedButton(
key: const Key('discoverRegionsRetry'),
onPressed: _start,
child: Text(l10n.discoverRegions_retry),
),
),
],
),
);
}
}

@ -378,7 +378,10 @@ class _PathTraceMapScreenState extends State<PathTraceMapScreen> {
path: Uint8List(0),
pathLength: 0,
publicKey: connector.selfPublicKey ?? Uint8List(0),
name: context.l10n.pathTrace_you,
// A synthetic tile for this device, not a real contact. There is no
// user label to override, so the localized "You" is the received name
// and `.name` returns it unchanged. (#750)
receivedName: context.l10n.pathTrace_you,
type: advTypeChat,
latitude: connector.selfLatitude,
longitude: connector.selfLongitude,

@ -10,6 +10,8 @@ import 'repeater_cli_screen.dart';
import 'repeater_settings_screen.dart';
import 'telemetry_screen.dart';
import 'neighbors_screen.dart';
import 'discover_regions_screen.dart';
import '../connector/meshcore_connector.dart';
class RepeaterHubScreen extends StatelessWidget {
final Contact repeater;
@ -27,6 +29,7 @@ class RepeaterHubScreen extends StatelessWidget {
Widget build(BuildContext context) {
final l10n = context.l10n;
final settingsService = context.watch<AppSettingsService>();
final connector = context.watch<MeshCoreConnector>();
final chemistry = settingsService.batteryChemistryForRepeater(
repeater.publicKeyHex,
);
@ -262,6 +265,25 @@ class RepeaterHubScreen extends StatelessWidget {
);
},
),
if (connector.supportsRegionScope) const SizedBox(height: 12),
// Discover Regions (firmware-gated)
if (connector.supportsRegionScope)
_buildManagementCard(
context,
icon: Icons.travel_explore,
title: l10n.discoverRegions_title,
subtitle: l10n.discoverRegions_subtitle,
color: Colors.teal,
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
DiscoverRegionsScreen(repeater: repeater),
),
);
},
),
if (isAdmin) const SizedBox(height: 12),
// Settings button
if (isAdmin)

@ -264,6 +264,31 @@ class _ScannerScreenState extends State<ScannerScreen> {
break;
}
// An automatic retry, or one that gave up, says so and offers a way out,
// rather than a bare "Connecting..." nobody can stop (#997).
final target = connector.autoReconnectTargetName ?? '';
Widget? action;
if (connector.isAutoReconnecting) {
statusText = l10n.scanner_reconnecting(
target,
connector.autoReconnectAttempt,
connector.autoReconnectMaxAttempts,
);
statusColor = Colors.orange;
action = TextButton(
onPressed: connector.stopAutoReconnect,
child: Text(l10n.common_stop),
);
} else if (connector.autoReconnectGaveUp &&
connector.state == MeshCoreConnectionState.disconnected) {
statusText = l10n.scanner_reconnectGaveUp(target);
statusColor = Colors.red;
action = TextButton(
onPressed: connector.retryLastDevice,
child: Text(l10n.common_retry),
);
}
return Container(
width: double.infinity,
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
@ -272,10 +297,13 @@ class _ScannerScreenState extends State<ScannerScreen> {
children: [
Icon(Icons.circle, size: 12, color: statusColor),
const SizedBox(width: 8),
Text(
statusText,
style: TextStyle(color: statusColor, fontWeight: FontWeight.w500),
Expanded(
child: Text(
statusText,
style: TextStyle(color: statusColor, fontWeight: FontWeight.w500),
),
),
?action,
],
),
);

@ -11,11 +11,12 @@ import '../../services/app_settings_service.dart';
import '../../services/translation_service.dart';
import '../../helpers/settings_persist.dart';
import '../../helpers/snack_bar_builder.dart';
import '../../widgets/storage_reclaim_card.dart';
import '../map_cache_screen.dart';
/// Embeddable view (no Scaffold) for the App Settings shell pane.
///
/// Renders appearance, translation, battery, map, and Cyr2Lat cards.
/// Renders appearance, translation, battery, map, Cyr2Lat and storage cards.
/// Notifications and message-handling settings live in [MessageSettingsView];
/// app debug logging lives in the Debug category on the settings screen.
class AppSettingsView extends StatelessWidget {
@ -44,6 +45,10 @@ class AppSettingsView extends StatelessWidget {
_buildMapSettingsCard(context, settingsService),
const SizedBox(height: 16),
_buildCyr2LatCard(context, settingsService),
const SizedBox(height: 16),
// #962. Its own widget rather than another card in this file,
// which is already past a thousand lines.
const StorageReclaimCard(),
],
);
},

@ -0,0 +1,125 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../connector/offband_device_ui.dart';
import '../../connector/offband_screen_settings.dart';
import '../../widgets/device_ui_error_banner.dart';
/// Where the badge's battery bar puts 100%, and how it got there (#987):
/// the badge's own Battery screen, with its two actions. Gated on caps byte 2
/// `0x40`. English-only, matching [DeviceUiView].
class BadgeBatteryView extends StatefulWidget {
const BadgeBatteryView({super.key});
@override
State<BadgeBatteryView> createState() => _BadgeBatteryViewState();
}
/// Where the full point came from, in the badge's terms (default, learned,
/// set). Shared with the Node Settings row.
String batteryFullSource(ScreenSettingsState s) => s.batteryFullStored == 0
? 'Default for this board'
: s.batteryPinned
? 'Set by hand'
: 'Learned after a full charge';
class _BadgeBatteryViewState extends State<BadgeBatteryView> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) context.read<MeshCoreConnector>().requestScreenSettings();
});
}
Future<void> _pin(MeshCoreConnector connector) async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Set 100% here?'),
content: const Text(
'Only do this with the radio fully charged. The radio uses its '
'current reading as full, and stops learning it.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Set 100% here'),
),
],
),
);
if (confirmed == true) await connector.setBatteryFull(pin: true);
}
@override
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
final s = connector.screenSettings;
final error = connector.deviceUiError;
final textTheme = Theme.of(context).textTheme;
final mv = connector.batteryMillivolts;
final pct = connector.batteryPercent;
return ListView(
padding: const EdgeInsets.all(16),
children: [
if (error != null &&
connector.deviceUiErrorSurface == DeviceUiSurface.screenSettings)
DeviceUiErrorBanner(
message: error,
onDismiss: connector.clearDeviceUiError,
margin: const EdgeInsets.only(bottom: 12),
),
if (pct != null) Text('$pct%', style: textTheme.headlineMedium),
if (mv != null) Text('Reading $mv mV'),
const SizedBox(height: 12),
if (s == null)
const ListTile(
leading: SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
title: Text('Reading battery settings from the radio'),
)
else ...[
Card(
child: ListTile(
leading: const Icon(Icons.battery_std),
title: Text('100% at ${s.batteryFullMv} mV'),
subtitle: Text(batteryFullSource(s)),
),
),
const SizedBox(height: 8),
const Text(
'The radio learns where full is after a complete charge. Set it by '
'hand only if the bar never reaches 100% when charged.',
),
const SizedBox(height: 16),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton.tonalIcon(
onPressed: () => _pin(connector),
icon: const Icon(Icons.bolt),
label: const Text('Set 100% here'),
),
// Only when there is something to hand back, as on the badge.
if (s.batteryFullStored != 0)
TextButton(
onPressed: () => connector.setBatteryFull(pin: false),
child: const Text('Back to auto'),
),
],
),
],
],
);
}
}

@ -0,0 +1,262 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../connector/offband_device_ui.dart';
import '../../connector/offband_screen_settings.dart';
import '../../models/badge_time_zones.dart';
import '../../widgets/device_ui_error_banner.dart';
/// The badge's own screen settings (#987): its Nav text, Message text, Screen
/// off and Time zone rows, with the same choices and no others. Gated on caps
/// byte 2 `0x40`; the Node Settings row that leads here is gated the same way.
///
/// Every control draws from the radio's re-read reply, never from the tap.
/// English-only, matching [DeviceUiView].
class BadgeScreenView extends StatefulWidget {
const BadgeScreenView({super.key});
@override
State<BadgeScreenView> createState() => _BadgeScreenViewState();
}
class _BadgeScreenViewState extends State<BadgeScreenView> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) context.read<MeshCoreConnector>().requestScreenSettings();
});
}
@override
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
final s = connector.screenSettings;
final error = connector.deviceUiError;
return ListView(
children: [
if (error != null &&
connector.deviceUiErrorSurface == DeviceUiSurface.screenSettings)
DeviceUiErrorBanner(
message: error,
onDismiss: connector.clearDeviceUiError,
),
if (s == null)
const ListTile(
leading: SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
title: Text('Reading screen settings from the radio'),
)
else ...[
const _Header('Text size'),
// The badge's Nav text and Message text, named for what they govern
// (owner decision 2026-10-25).
_TextSizeRow(
label: 'Menus and lists',
value: s.navText,
onChanged: (v) =>
connector.setTextSize(BadgeTextTarget.navigation, v),
),
_TextSizeRow(
label: 'Messages',
value: s.messageText,
onChanged: (v) =>
connector.setTextSize(BadgeTextTarget.messages, v),
),
const _Header('Screen off'),
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'How long the screen stays on after the last key press.',
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: SegmentedButton<int>(
segments: [
for (final secs in screenOffSteps)
ButtonSegment(value: secs, label: Text(screenOffLabel(secs))),
],
selected: {
if (screenOffSteps.contains(s.screenOffStored))
s.screenOffStored,
},
emptySelectionAllowed: true,
onSelectionChanged: (v) {
if (v.isNotEmpty) connector.setScreenOff(v.first);
},
),
),
if (!screenOffSteps.contains(s.screenOffStored))
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Text(
s.screenOffIsDefault
? 'Board default: ${screenOffLabel(s.screenOffSeconds)}'
: 'Set to ${screenOffLabel(s.screenOffStored)} elsewhere',
style: Theme.of(context).textTheme.bodySmall,
),
),
const _Header('Time zone'),
ListTile(
leading: const Icon(Icons.public),
title: Text(timeZoneName(s.timeZone)),
subtitle: Text(_zoneSubtitle(s.timeZone)),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TimeZonePickerScreen(current: s.timeZone),
),
),
),
],
],
);
}
String _zoneSubtitle(int index) {
final offset = timeZoneOffsetMinutes(index, DateTime.now().toUtc());
if (offset == null) {
return index == timeZoneNotSet
? 'Messages show their age'
: 'A zone this app does not know';
}
return '${formatUtcOffset(offset)} now. Message times show as clock times.';
}
}
class _Header extends StatelessWidget {
const _Header(this.title);
final String title;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 4),
child: Text(title, style: Theme.of(context).textTheme.titleMedium),
);
}
class _TextSizeRow extends StatelessWidget {
const _TextSizeRow({
required this.label,
required this.value,
required this.onChanged,
});
final String label;
final BadgeTextSize? value;
final ValueChanged<BadgeTextSize> onChanged;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label),
const SizedBox(height: 4),
SizedBox(
width: double.infinity,
child: SegmentedButton<BadgeTextSize>(
segments: [
for (final size in BadgeTextSize.values)
ButtonSegment(value: size, label: Text(size.label)),
],
selected: {?value},
emptySelectionAllowed: true,
onSelectionChanged: (v) {
if (v.isNotEmpty) onChanged(v.first);
},
),
),
],
),
);
}
}
/// The badge's zone list, with "not set" and a suggestion from the phone's
/// own zone, as the badge suggests one from GPS.
class TimeZonePickerScreen extends StatefulWidget {
const TimeZonePickerScreen({super.key, required this.current});
final int current;
@override
State<TimeZonePickerScreen> createState() => _TimeZonePickerScreenState();
}
class _TimeZonePickerScreenState extends State<TimeZonePickerScreen> {
String _query = '';
void _choose(int index) {
context.read<MeshCoreConnector>().setTimeZone(index);
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final now = DateTime.now();
final suggested = suggestTimeZone(
now: now,
offsetAt: (local) => local.timeZoneOffset,
);
final q = _query.trim().toLowerCase();
bool shown(int i) => q.isEmpty || timeZoneName(i).toLowerCase().contains(q);
final scheme = Theme.of(context).colorScheme;
Widget zoneTile(int i, {bool suggestion = false}) {
final offset = timeZoneOffsetMinutes(i, now.toUtc());
final selected = !suggestion && i == widget.current;
return ListTile(
leading: suggestion
? const Icon(Icons.smartphone)
: Icon(
selected
? Icons.radio_button_checked
: Icons.radio_button_unchecked,
color: selected ? scheme.primary : null,
),
title: Text(timeZoneName(i)),
subtitle: suggestion
? const Text('Matches this phone')
: selected
? const Text('Current')
: i == timeZoneNotSet
? const Text('Messages show their age')
: null,
trailing: offset == null ? null : Text(formatUtcOffset(offset)),
selected: selected,
onTap: () => _choose(i),
);
}
return Scaffold(
appBar: AppBar(title: const Text('Time zone'), centerTitle: true),
body: ListView(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: SearchBar(
hintText: 'Search zones',
leading: const Icon(Icons.search),
onChanged: (v) => setState(() => _query = v),
),
),
if (suggested != null && shown(suggested)) ...[
zoneTile(suggested, suggestion: true),
const Divider(height: 1),
],
for (var i = 0; i < badgeTimeZones.length; i++)
if (shown(i)) zoneTile(i),
],
),
);
}
}

@ -17,6 +17,42 @@ class BlockedView extends StatelessWidget {
Widget build(BuildContext context) {
return Consumer2<BlockService, MeshCoreConnector>(
builder: (context, block, connector, child) {
// No radio connected is NOT the same as nothing blocked, and before
// #507 both rendered as "No blocked users". Blocks are per radio
// (#471), so with none connected there is no list to show rather than
// an empty one, and saying "no blocked users" invited the reader to
// conclude their blocks had been lost.
if (block.selfKeyHex == null) {
return ListView(
padding: const EdgeInsets.all(16),
children: [
Padding(
padding: const EdgeInsets.symmetric(vertical: 48),
child: Column(
children: [
Icon(
Icons.radio_button_unchecked,
size: 40,
color: Colors.grey[500],
),
const SizedBox(height: 12),
Text(context.l10n.block_noRadio),
const SizedBox(height: 8),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(
context.l10n.block_noRadioHint,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 12, color: Colors.grey[600]),
),
),
],
),
),
],
);
}
final keys = block.blockedKeys.toList()..sort();
final names = block.blockedNames.keys.toList()..sort();
final indicator = _offloadIndicator(context, connector);

@ -3,6 +3,10 @@ import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../connector/offband_device_ui.dart';
import '../../connector/offband_tones.dart';
import '../../widgets/device_ui_error_banner.dart';
import '../../widgets/radio_tone.dart';
import 'tune_slot_editor_screen.dart';
/// Settings for a headless device's physical UI: the button-action matrix
/// (#474) and the device notification scope (#475).
@ -13,13 +17,22 @@ import '../../connector/offband_device_ui.dart';
///
/// English-only for now, matching the serial-capture pane (#430); localization
/// is a follow-up rather than a blocker on shipping the capability.
///
/// Shows one [part] at a time (#978): button actions open from Node Settings,
/// the buzzer from Message Settings. They are separate features with separate
/// bits, and boards with a buzzer and no button exist.
class DeviceUiView extends StatefulWidget {
const DeviceUiView({super.key});
const DeviceUiView({super.key, required this.part});
final DeviceUiPart part;
@override
State<DeviceUiView> createState() => _DeviceUiViewState();
}
/// Which half of the device UI a [DeviceUiView] shows.
enum DeviceUiPart { buttons, buzzer }
class _DeviceUiViewState extends State<DeviceUiView> {
@override
void initState() {
@ -29,17 +42,41 @@ class _DeviceUiViewState extends State<DeviceUiView> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final c = context.read<MeshCoreConnector>();
c.requestButtonMatrix();
c.requestNotifyScope();
switch (widget.part) {
case DeviceUiPart.buttons:
c.requestButtonMatrix();
case DeviceUiPart.buzzer:
c.requestNotifyScope();
if (c.supportsTunes) {
c.requestEventTones();
c.requestTuneSlots();
}
}
});
}
/// An error is shown on the screen it belongs to. One that could not be
/// attributed to a write is shown on both halves rather than hidden.
bool _ownsError(DeviceUiSurface? surface) => switch (surface) {
null => true,
DeviceUiSurface.buttonMatrix => widget.part == DeviceUiPart.buttons,
DeviceUiSurface.notifyScope ||
DeviceUiSurface.channelTune ||
DeviceUiSurface.eventTone ||
DeviceUiSurface.tunePlay ||
DeviceUiSurface.tuneSlot => widget.part == DeviceUiPart.buzzer,
DeviceUiSurface.gpsMode || DeviceUiSurface.screenSettings => false,
};
@override
Widget build(BuildContext context) {
return Consumer<MeshCoreConnector>(
builder: (context, connector, _) {
final showButtons = connector.supportsButtonMatrix;
final showScope = connector.supportsNotifyScope;
final showButtons =
widget.part == DeviceUiPart.buttons &&
connector.supportsButtonMatrix;
final showScope =
widget.part == DeviceUiPart.buzzer && connector.supportsNotifyScope;
// A radio advertising neither bit has no button and no buzzer to
// configure, so it gets nothing. The tile that leads here is gated the
// same way, so this is a belt-and-braces guard rather than a path a
@ -82,8 +119,9 @@ class _DeviceUiViewState extends State<DeviceUiView> {
}
return ListView(
children: [
if (connector.deviceUiError != null)
_ErrorBanner(
if (connector.deviceUiError != null &&
_ownsError(connector.deviceUiErrorSurface))
DeviceUiErrorBanner(
message: connector.deviceUiError!,
onDismiss: connector.clearDeviceUiError,
),
@ -98,7 +136,25 @@ class _DeviceUiViewState extends State<DeviceUiView> {
),
),
..._scopeTiles(connector),
const Divider(height: 24),
// The badge's Tones screen, in its order: the scope gates every
// tone below it (#986, #970). Needs the tune engine, 0x10.
if (connector.supportsTunes) ...[
const _SectionHeader('Tones'),
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text('What this radio plays for each event.'),
),
..._eventToneTiles(connector),
const _SectionHeader('Custom tunes'),
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'Eight tunes stored on this radio, in RTTTL. A saved tune '
'can be picked for any event or channel.',
),
),
..._slotTiles(connector),
],
],
if (showButtons) ...[
const _SectionHeader('Button actions'),
@ -156,6 +212,111 @@ class _DeviceUiViewState extends State<DeviceUiView> {
.toList();
}
/// The six events, each naming the tune that plays. "(radio default)" marks
/// one nobody has chosen, so a choice and a default never look alike.
List<Widget> _eventToneTiles(MeshCoreConnector connector) {
return ToneEvent.values.map((event) {
final state = connector.eventTone(event);
if (state == null) {
return ListTile(
leading: const Icon(Icons.music_note_outlined),
title: Text(event.label),
subtitle: const Text('Reading from the radio'),
);
}
final name =
tuneLabel(state.effective, connector.tuneSlots) ??
'Tune ${state.effective}';
return ListTile(
leading: Icon(tuneIcon(state.effective)),
title: Text(event.label),
subtitle: Text(state.isRadioDefault ? '$name (radio default)' : name),
trailing: const Icon(Icons.chevron_right),
onTap: () => _pickEventTone(connector, event, state),
);
}).toList();
}
Future<void> _pickEventTone(
MeshCoreConnector connector,
ToneEvent event,
EventToneState state,
) async {
// No Default row: firmware refuses 0xFF on an event, as the badge's own
// picker offers none (owner decision 2026-10-25).
final choice = await showTunePickerDialog(
context,
title: '${event.label} tone',
description: event == ToneEvent.dm
? 'Plays for every direct message.'
: null,
current: state.effective,
);
if (choice is TuneIdChoice) await connector.setEventTone(event, choice.id);
}
/// All eight slots, as the badge lists them: an empty slot is where you go
/// to fill one, so it is a row too.
List<Widget> _slotTiles(MeshCoreConnector connector) {
return [
for (var slot = 0; slot < tuneSlotCount; slot++)
_slotTile(connector, slot, connector.tuneSlots[slot]),
];
}
Widget _slotTile(MeshCoreConnector connector, int slot, TuneSlotInfo? info) {
final number = slot + 1;
if (info == null) {
return ListTile(
leading: const Icon(Icons.music_note_outlined),
title: Text('$number'),
subtitle: const Text('Reading from the radio'),
);
}
void open() => Navigator.push(
context,
MaterialPageRoute(
builder: (_) => TuneSlotEditorScreen(slot: slot, info: info),
),
);
if (info.isEmpty) {
return ListTile(
leading: const Icon(Icons.add_circle_outline),
title: Text('$number (empty)'),
subtitle: const Text('Tap to add a tune'),
onTap: open,
);
}
final name = info.name.isEmpty ? 'Slot $number' : info.name;
return ListTile(
leading: const Icon(Icons.music_note_outlined),
title: Text('$number $name'),
subtitle: Text('${info.length} characters'),
trailing: IconButton(
icon: const Icon(Icons.play_circle_outline),
color: Theme.of(context).colorScheme.primary,
tooltip: 'Play on the radio',
onPressed: () => _play(connector, slotTuneId(slot)),
),
onTap: open,
);
}
Future<void> _play(MeshCoreConnector connector, int id) async {
final messenger = ScaffoldMessenger.of(context);
final note = describeTunePlay(await connector.playTune(id));
if (note == null) return;
// Stays until OK: an explanation the user cannot finish reading is not
// one.
messenger.showSnackBar(
SnackBar(
content: Text(note),
duration: const Duration(days: 1),
action: SnackBarAction(label: 'OK', onPressed: () {}),
),
);
}
List<Widget> _buttonTiles(MeshCoreConnector connector) {
final matrix = connector.buttonMatrix;
if (matrix == null) {
@ -207,41 +368,3 @@ class _SectionHeader extends StatelessWidget {
child: Text(title, style: Theme.of(context).textTheme.titleMedium),
);
}
/// Persistent error banner. Stays until dismissed rather than flashing, per the
/// error-visibility rule: an error the user cannot finish reading is not a
/// surfaced error.
class _ErrorBanner extends StatelessWidget {
const _ErrorBanner({required this.message, required this.onDismiss});
final String message;
final VoidCallback onDismiss;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Container(
margin: const EdgeInsets.all(12),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: scheme.errorContainer,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(Icons.error_outline, color: scheme.onErrorContainer),
const SizedBox(width: 12),
Expanded(
child: Text(
message,
style: TextStyle(color: scheme.onErrorContainer),
),
),
IconButton(
icon: Icon(Icons.close, color: scheme.onErrorContainer),
onPressed: onDismiss,
),
],
),
);
}
}

@ -0,0 +1,748 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../connector/offband_device_ui.dart';
import '../../helpers/snack_bar_builder.dart';
import '../../l10n/l10n.dart';
import '../../models/offband_gps_status.dart';
import '../../utils/app_logger.dart';
/// Embeddable view (no Scaffold) for the Location settings pane (#977).
///
/// The single home for GPS: the GPS control and its status, the node's
/// coordinates, and the position reporting interval. These used to sit in Node
/// Settings and a Location dialog, with the GPS toggle in both. The radio sees
/// the same writes as before: the same custom vars, the same validation, the
/// same error messages.
///
/// One deliberate difference: coordinates and the reporting interval now save
/// independently. In the old dialog an empty or invalid interval returned early
/// and silently skipped the coordinates as well.
///
/// On a radio that advertises caps byte 2 `0x20` (#969) the GPS card is one
/// Off / On / Power save control with one status row, per the approved mockups
/// in `docs/initiatives/standalone/975-settings-restructure/`. Everything shown
/// there is the device's reply, never the request. Other radios keep the plain
/// on/off toggle above, unchanged.
class LocationView extends StatefulWidget {
const LocationView({super.key});
@override
State<LocationView> createState() => _LocationViewState();
}
class _LocationViewState extends State<LocationView> {
OffbandGpsStatus? _gpsStatus;
bool _queryingGps = false;
bool _queriedOnce = false;
/// Activity and the wait to the next attempt change on their own, so while
/// this pane is open the GPS state is re-read on a slow cadence. One 2-byte
/// request every 30 s, and only while visible.
Timer? _gpsRefresh;
static const _gpsRefreshEvery = Duration(seconds: 30);
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_refreshGpsMode(context.read<MeshCoreConnector>());
});
_gpsRefresh = Timer.periodic(_gpsRefreshEvery, (_) {
if (mounted) _refreshGpsMode(context.read<MeshCoreConnector>());
});
}
@override
void dispose() {
_gpsRefresh?.cancel();
super.dispose();
}
/// Re-read GPS mode, and the 0xC1 fix details that give the last-fix line.
///
/// Unawaited on purpose (a timer and a button call it), so a send that fails
/// because the link dropped mid-refresh is logged rather than escaping.
void _refreshGpsMode(MeshCoreConnector connector) {
if (!connector.supportsGpsMode) return;
connector.requestGpsMode().catchError((Object e) {
appLogger.warn('GPS mode refresh failed: $e', tag: 'Location');
});
if (connector.supportsOffbandGps) {
connector
.requestOffbandGps()
.then((s) {
if (mounted && s != null) setState(() => _gpsStatus = s);
})
.catchError((Object e) {
appLogger.warn('GPS fix refresh failed: $e', tag: 'Location');
});
}
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final connector = context.watch<MeshCoreConnector>();
final customVars = connector.currentCustomVars ?? const <String, String>{};
// A radio with no GPS hardware reports no `gps` custom var at all, which is
// how the old screens decided to hide the GPS controls too.
final hasGps = customVars.containsKey('gps');
return ListView(
padding: const EdgeInsets.all(16),
children: [
if (connector.supportsGpsMode) ...[
_gpsModeCard(connector),
const SizedBox(height: 16),
] else if (hasGps) ...[
Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SwitchListTile(
secondary: const Icon(Icons.gps_fixed),
title: Text(l10n.settings_locationGPSEnable),
subtitle: Text(l10n.settings_locationGPSEnableSubtitle),
value: customVars['gps'] == '1',
onChanged: (value) => _setGpsEnabled(connector, value),
),
if (connector.supportsOffbandGps)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
child: _buildGpsQuerySection(
context,
_gpsStatus ?? connector.offbandGpsStatus,
() => _queryGps(connector),
),
),
],
),
),
const SizedBox(height: 16),
],
Card(
child: Column(
children: [
ListTile(
leading: const Icon(Icons.location_on_outlined),
title: Text(l10n.settings_locationCoordinates),
subtitle: Text(_coordinatesText(connector)),
trailing: const Icon(Icons.chevron_right),
onTap: () => _editCoordinates(connector),
),
if (hasGps) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.schedule),
title: Text(l10n.settings_locationReportInterval),
subtitle: Text(_intervalText(customVars)),
trailing: const Icon(Icons.chevron_right),
onTap: () => _editReportInterval(connector, customVars),
),
],
],
),
),
],
);
}
/// #969: one control for whether AND how GPS runs, the way the badge's own
/// screen writes it, then one status row, then the Power-save sleep.
Widget _gpsModeCard(MeshCoreConnector connector) {
final l10n = context.l10n;
final state = connector.gpsModeState;
final error = connector.deviceUiErrorSurface == DeviceUiSurface.gpsMode
? connector.deviceUiError
: null;
final children = <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
child: Text(
l10n.settings_gpsModeLabel,
style: Theme.of(context).textTheme.labelLarge,
),
),
];
if (state == null) {
children.add(
ListTile(
leading: const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
),
title: Text(l10n.settings_gpsReading),
),
);
} else {
children.addAll([
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 14),
child: SizedBox(
width: double.infinity,
child: SegmentedButton<GpsMode>(
segments: [
ButtonSegment(
value: GpsMode.off,
label: Text(l10n.settings_gpsModeOff),
),
ButtonSegment(
value: GpsMode.on,
label: Text(l10n.settings_gpsModeOn),
),
// Offered only where this build can run it: a radio speaking
// the GPS sub-codes without the duty cycle says so in ps_ok.
if (state.powerSaveAvailable)
ButtonSegment(
value: GpsMode.powerSave,
label: Text(l10n.settings_gpsModePowerSave),
),
],
selected: {state.mode},
onSelectionChanged: (picked) =>
connector.setGpsMode(picked.first),
),
),
),
const Divider(height: 1),
_gpsStatusTile(connector, state),
if (state.mode == GpsMode.powerSave) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.hourglass_empty),
title: Text(l10n.settings_gpsSleepTitle),
subtitle: Text(
state.intervalSeconds == 0
? l10n.settings_gpsSleepDefault
: _durationText(state.intervalSeconds),
),
trailing: const Icon(Icons.chevron_right),
onTap: () => _editSleepInterval(connector, state),
),
],
]);
}
if (error != null) {
// Held until dismissed: a refusal the user cannot finish reading is not
// surfaced at all (SAFELANE §6).
children.addAll([
const Divider(height: 1),
ListTile(
leading: Icon(
Icons.error_outline,
color: Theme.of(context).colorScheme.error,
),
title: Text(error),
trailing: IconButton(
icon: const Icon(Icons.close),
tooltip: MaterialLocalizations.of(context).closeButtonTooltip,
onPressed: connector.clearDeviceUiError,
),
),
]);
}
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
),
);
}
/// One row for what GPS is doing: activity, next attempt, and last fix, so
/// nothing on the card is said twice.
Widget _gpsStatusTile(MeshCoreConnector connector, GpsModeState state) {
final l10n = context.l10n;
final activity = state.activity;
final (IconData icon, Color color, String title) = switch (activity) {
GpsActivity.off => (
Icons.gps_off,
Colors.grey,
l10n.settings_gpsActivityOff,
),
GpsActivity.on => (
Icons.gps_fixed,
Colors.green,
l10n.settings_gpsActivityOn,
),
GpsActivity.searching => (
Icons.gps_not_fixed,
Colors.orange,
l10n.settings_gpsActivitySearching,
),
GpsActivity.sleeping => (
Icons.bedtime_outlined,
Colors.blueGrey,
l10n.settings_gpsActivitySleeping,
),
GpsActivity.backedOff => (
Icons.pause_circle_outline,
Colors.orange,
l10n.settings_gpsActivityBackedOff,
),
// A state newer firmware knows and this client does not: say what the
// mode is rather than guess at what it is doing.
null => switch (state.mode) {
GpsMode.off => (
Icons.gps_off,
Colors.grey,
l10n.settings_gpsActivityOff,
),
GpsMode.on => (
Icons.gps_fixed,
Colors.green,
l10n.settings_gpsActivityOn,
),
GpsMode.powerSave => (
Icons.gps_not_fixed,
Colors.orange,
l10n.settings_gpsModePowerSave,
),
},
};
final details = <String>[];
if (state.mode == GpsMode.off) {
details.add(l10n.settings_gpsOffDetail);
} else {
if (state.waitSeconds > 0) {
details.add(
state.waitSeconds >= 60
? l10n.settings_gpsNextTryMinutes(
(state.waitSeconds / 60).round(),
)
: l10n.settings_gpsNextTrySeconds(state.waitSeconds),
);
}
final fix = _gpsStatus ?? connector.offbandGpsStatus;
final at = fix?.timestampUtc;
if (at != null) {
final ago = DateTime.now().toUtc().difference(at.toUtc()).inMinutes;
details.add(l10n.settings_gpsLastFixMinutes(ago < 0 ? 0 : ago));
}
final sats = fix?.satellites;
if (sats != null && sats > 0 && state.waitSeconds == 0) {
details.add(l10n.settings_gpsSatellites(sats));
}
}
return ListTile(
leading: Icon(icon, color: color),
title: Text(title),
subtitle: details.isEmpty ? null : Text(details.join(', ')),
trailing: TextButton(
onPressed: () => _refreshGpsMode(connector),
child: Text(l10n.settings_gpsQuery),
),
);
}
String _durationText(int seconds) {
final l10n = context.l10n;
if (seconds % 60 == 0) {
return l10n.settings_locationEveryMinutes(seconds ~/ 60);
}
return l10n.settings_locationEverySeconds(seconds);
}
/// The sleep interval. 0 is a legal value meaning the firmware default, so
/// the reporting interval's 60-second floor must not be copied here. The
/// radio raises 1 to 299 to 300, and the row shows what it stored.
void _editSleepInterval(MeshCoreConnector connector, GpsModeState state) {
final l10n = context.l10n;
final controller = TextEditingController(
text: state.intervalSeconds.toString(),
);
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(l10n.settings_gpsSleepTitle),
content: TextField(
controller: controller,
decoration: InputDecoration(
labelText: l10n.settings_gpsSleepFieldLabel,
helperText: l10n.settings_gpsSleepFieldHint,
helperMaxLines: 3,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: false,
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () {
final text = controller.text.trim();
final seconds = text.isEmpty ? 0 : int.tryParse(text);
Navigator.pop(dialogContext);
if (seconds == null || seconds < 0 || seconds > 0xFFFFFFFF) {
// Held until tapped away: an error that vanishes on a timer
// before it is read is not surfaced (SAFELANE §6).
showDismissibleSnackBar(
context,
content: Text(l10n.settings_gpsSleepInvalid),
persist: true,
);
return;
}
connector.setGpsMode(state.mode, intervalSeconds: seconds);
},
child: Text(l10n.common_save),
),
],
),
);
}
String _coordinatesText(MeshCoreConnector connector) {
final lat = connector.selfLatitude;
final lon = connector.selfLongitude;
if (lat == null || lon == null) return context.l10n.settings_locationNotSet;
return '${lat.toStringAsFixed(6)}, ${lon.toStringAsFixed(6)}';
}
String _intervalText(Map<String, String> customVars) {
final l10n = context.l10n;
final seconds = int.tryParse(customVars['gps_interval'] ?? '');
if (seconds == null || seconds <= 0) return l10n.settings_locationNotSet;
if (seconds % 60 == 0) {
return l10n.settings_locationEveryMinutes(seconds ~/ 60);
}
return l10n.settings_locationEverySeconds(seconds);
}
Future<void> _setGpsEnabled(MeshCoreConnector connector, bool value) async {
try {
await connector.setCustomVar(value ? 'gps:1' : 'gps:0');
} catch (_) {
if (mounted) {
showDismissibleSnackBar(
context,
content: const Text(
'Could not update GPS setting. Please try again.',
),
);
}
}
}
Future<void> _queryGps(MeshCoreConnector connector) async {
setState(() => _queryingGps = true);
final s = await connector.requestOffbandGps();
if (!mounted) return;
setState(() {
_queryingGps = false;
_queriedOnce = true;
_gpsStatus = s;
});
}
Widget _buildGpsQuerySection(
BuildContext context,
OffbandGpsStatus? status,
VoidCallback onRefresh,
) {
final l10n = context.l10n;
final theme = Theme.of(context);
Widget row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label),
Text(value, style: const TextStyle(fontWeight: FontWeight.w500)),
],
),
);
final children = <Widget>[
const Divider(),
Row(
children: [
Expanded(
child: Text(
l10n.settings_gpsStatusTitle,
style: theme.textTheme.titleSmall,
),
),
if (_queryingGps)
const Padding(
padding: EdgeInsets.all(8),
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
)
else
IconButton(
icon: const Icon(Icons.refresh),
tooltip: l10n.settings_gpsStatusRefresh,
onPressed: onRefresh,
),
],
),
];
if (status != null) {
final live = status.hasLiveFix;
final color = live ? Colors.green : Colors.orange;
children.add(
Row(
children: [
Icon(
live ? Icons.gps_fixed : Icons.gps_off,
size: 18,
color: color,
),
const SizedBox(width: 8),
Expanded(
child: Text(
live
? l10n.settings_gpsStatusLiveFix
: l10n.settings_gpsStatusNoFix,
style: TextStyle(color: color, fontWeight: FontWeight.w600),
),
),
],
),
);
children.add(const SizedBox(height: 8));
final coords = (status.latitude != null && status.longitude != null)
? '${status.latitude!.toStringAsFixed(6)}, '
'${status.longitude!.toStringAsFixed(6)}'
: '—';
children.add(row(l10n.settings_gpsStatusCoords, coords));
children.add(
row(l10n.settings_gpsStatusSats, status.satellites?.toString() ?? '—'),
);
children.add(
row(
l10n.settings_gpsStatusAltitude,
status.altitudeCm != null
? '${(status.altitudeCm! / 100).toStringAsFixed(1)} m'
: '—',
),
);
final t = status.timestampUtc?.toLocal();
final ml = MaterialLocalizations.of(context);
final timeStr = t == null
? '—'
: '${ml.formatCompactDate(t)} '
'${ml.formatTimeOfDay(TimeOfDay.fromDateTime(t))}';
children.add(row(l10n.settings_gpsStatusTime, timeStr));
} else {
children.add(
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
_queriedOnce
? l10n.settings_gpsStatusNoResponse
: l10n.settings_gpsStatusTapRefresh,
style: theme.textTheme.bodySmall,
),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
);
}
void _editCoordinates(MeshCoreConnector connector) {
final l10n = context.l10n;
final latController = TextEditingController(
text: connector.selfLatitude?.toStringAsFixed(6) ?? '',
);
final lonController = TextEditingController(
text: connector.selfLongitude?.toStringAsFixed(6) ?? '',
);
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(l10n.settings_locationCoordinates),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: latController,
decoration: InputDecoration(
labelText: l10n.settings_latitude,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
const SizedBox(height: 16),
TextField(
controller: lonController,
decoration: InputDecoration(
labelText: l10n.settings_longitude,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
Navigator.pop(dialogContext);
final latText = latController.text.trim();
final lonText = lonController.text.trim();
if (latText.isEmpty && lonText.isEmpty) return;
final lat = latText.isNotEmpty
? double.tryParse(latText)
: connector.selfLatitude;
final lon = lonText.isNotEmpty
? double.tryParse(lonText)
: connector.selfLongitude;
if (lat == null || lon == null) {
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationBothRequired),
);
return;
}
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationInvalid),
);
return;
}
try {
await connector.setNodeLocation(lat: lat, lon: lon);
await connector.refreshDeviceInfo();
} catch (_) {
messenger.showSnackBar(
const SnackBar(
content: Text(
'Could not update location. Please try again.',
),
),
);
return;
}
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationUpdated),
);
},
child: Text(l10n.common_save),
),
],
),
);
}
void _editReportInterval(
MeshCoreConnector connector,
Map<String, String> customVars,
) {
final l10n = context.l10n;
// Same default the old dialog pre-filled: 900 seconds when the radio has
// not reported an interval.
final current = int.tryParse(customVars['gps_interval'] ?? '') ?? 900;
final intervalController = TextEditingController(text: current.toString());
showDialog(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(l10n.settings_locationReportInterval),
content: TextField(
controller: intervalController,
decoration: InputDecoration(
labelText: l10n.settings_locationIntervalSec,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: false,
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
Navigator.pop(dialogContext);
final intervalText = intervalController.text.trim();
if (intervalText.isEmpty) return;
final interval = int.tryParse(intervalText);
if (interval == null || interval < 60 || interval >= 86400) {
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationIntervalInvalid),
);
return;
}
try {
await connector.setCustomVar('gps_interval:$interval');
await connector.refreshDeviceInfo();
} catch (_) {
messenger.showSnackBar(
const SnackBar(
content: Text(
'Could not update location. Please try again.',
),
),
);
return;
}
if (!mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationUpdated),
);
},
child: Text(l10n.common_save),
),
],
),
);
}
}

@ -1,16 +1,19 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../l10n/l10n.dart';
import '../../services/app_settings_service.dart';
import '../../services/notification_service.dart';
import '../../helpers/settings_persist.dart';
import '../../helpers/snack_bar_builder.dart';
import 'device_ui_view.dart';
/// Embeddable view (no Scaffold) for the Message Settings shell pane.
///
/// Renders notification toggles and message-handling settings. Both cards read
/// and write only [AppSettingsService].
/// Renders notification toggles and message-handling settings, which read and
/// write only [AppSettingsService]. Between them, on a radio with a buzzer,
/// sits the entry to the radio's own buzzer settings (#978).
class MessageSettingsView extends StatelessWidget {
const MessageSettingsView({super.key});
@ -23,6 +26,7 @@ class MessageSettingsView extends StatelessWidget {
children: [
_buildNotificationsCard(context, settingsService),
const SizedBox(height: 16),
const _RadioBuzzerEntry(),
_buildMessagingCard(context, settingsService),
],
);
@ -404,3 +408,40 @@ class MessageSettingsView extends StatelessWidget {
);
}
}
/// Entry to the radio's buzzer settings (#978), shown only where the radio
/// advertises a buzzer (caps byte 2 `0x01`). Separate from the card above,
/// which governs whether this PHONE notifies; this governs the radio.
class _RadioBuzzerEntry extends StatelessWidget {
const _RadioBuzzerEntry();
@override
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
if (!connector.supportsNotifyScope) return const SizedBox.shrink();
final l10n = context.l10n;
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Card(
child: ListTile(
leading: const Icon(Icons.volume_up_outlined),
title: Text(l10n.settings_buzzerTones),
subtitle: Text(l10n.settings_buzzerTonesSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(
title: Text(l10n.settings_buzzerTones),
centerTitle: true,
),
body: const DeviceUiView(part: DeviceUiPart.buzzer),
),
),
),
),
),
);
}
}

@ -0,0 +1,324 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import '../../connector/meshcore_connector.dart';
import '../../connector/offband_device_ui.dart';
import '../../connector/offband_tones.dart';
import '../../widgets/device_ui_error_banner.dart';
import '../../widgets/radio_tone.dart';
/// Edit one custom tune slot on the radio (#970).
///
/// Opens with the stored tune read back (`SLOT_READ`), so a filled slot can be
/// changed rather than only replaced. Typing is checked with firmware's own
/// validator and words before anything is sent, since the radio can only
/// answer "malformed". Saving is the chunked `SLOT_SET`; the radio replaces
/// the slot only on the final chunk, so a failed save changes nothing.
///
/// English-only, matching [DeviceUiView].
class TuneSlotEditorScreen extends StatefulWidget {
const TuneSlotEditorScreen({
super.key,
required this.slot,
required this.info,
});
final int slot;
final TuneSlotInfo info;
@override
State<TuneSlotEditorScreen> createState() => _TuneSlotEditorScreenState();
}
class _TuneSlotEditorScreenState extends State<TuneSlotEditorScreen> {
final _controller = TextEditingController();
/// What the radio holds, once read. Null while reading, or if the read
/// failed: then the slot's content is unknown and Play saved is off.
String? _saved;
bool _reading = false;
int _readBytes = 0;
bool _saving = false;
int _sentBytes = 0;
int _sendTotal = 0;
@override
void initState() {
super.initState();
_controller.addListener(() => setState(() {}));
if (widget.info.isEmpty) {
_saved = '';
} else {
WidgetsBinding.instance.addPostFrameCallback((_) => _read());
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
Future<void> _read() async {
final connector = context.read<MeshCoreConnector>();
setState(() => _reading = true);
final text = await connector.readTuneSlot(
widget.slot,
onProgress: (n) {
if (mounted) setState(() => _readBytes = n);
},
);
if (!mounted) return;
setState(() {
_reading = false;
_saved = text;
if (text != null) _controller.text = text;
});
}
bool get _busy => _reading || _saving;
String get _text => _controller.text;
bool get _dirty => _text != (_saved ?? '');
Future<void> _save() async {
final connector = context.read<MeshCoreConnector>();
final navigator = Navigator.of(context);
final text = _text;
setState(() {
_saving = true;
_sentBytes = 0;
_sendTotal = text.length;
});
final ok = await connector.saveTuneSlot(
widget.slot,
text,
onProgress: (sent, total) {
if (mounted) setState(() => _sentBytes = sent);
},
);
if (!mounted) return;
setState(() {
_saving = false;
if (ok) _saved = text;
});
if (!ok) return;
// Pop after the rebuild, so PopScope sees the saved state and does not
// ask to discard a tune that was just saved.
await WidgetsBinding.instance.endOfFrame;
if (mounted) navigator.pop();
}
Future<void> _clear() async {
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text('Clear slot ${widget.slot + 1}?'),
content: const Text(
'The tune is removed from the radio. Events and channels using it '
'stop playing it.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Cancel'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Clear'),
),
],
),
);
if (confirmed != true || !mounted) return;
_controller.text = '';
await _save();
}
Future<void> _playSaved() async {
final connector = context.read<MeshCoreConnector>();
final messenger = ScaffoldMessenger.of(context);
final note = describeTunePlay(
await connector.playTune(slotTuneId(widget.slot)),
);
if (note == null) return;
messenger.showSnackBar(
SnackBar(
content: Text(note),
duration: const Duration(days: 1),
action: SnackBarAction(label: 'OK', onPressed: () {}),
),
);
}
Future<bool> _confirmDiscard() async {
final discard = await showDialog<bool>(
context: context,
builder: (dialogContext) => AlertDialog(
title: const Text('Discard changes?'),
content: const Text('This tune has not been saved to the radio.'),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: const Text('Keep editing'),
),
TextButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: const Text('Discard'),
),
],
),
);
return discard == true;
}
@override
Widget build(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
final scheme = Theme.of(context).colorScheme;
final problem = rtttlProblem(_text);
final emptyText = _text.isEmpty;
// Firmware's own words fit 21 badge columns and do not say that order is
// the problem, which it usually is for RTTTL from elsewhere. When the
// header is the only fault, say so and offer the fix.
final orderFix = emptyText ? null : fixRtttlDefaultsOrder(_text);
final helper = emptyText
? (_saved == null ? '' : 'Type or paste an RTTTL tune')
: problem == RtttlProblem.ok
? 'Plays as "${deriveSlotName(_text)}"'
: orderFix != null
? 'The badge reads d=, o=, b= in that order, each once'
: problem.text;
final helperIsProblem = !emptyText && problem != RtttlProblem.ok;
final savedHasTune = _saved != null && _saved!.isNotEmpty;
final error = connector.deviceUiError;
final showError =
error != null &&
(connector.deviceUiErrorSurface == DeviceUiSurface.tuneSlot ||
connector.deviceUiErrorSurface == DeviceUiSurface.tunePlay);
return PopScope(
// Held while a read or save is in flight: leaving would abandon it
// halfway, and the radio would keep the old tune.
canPop: !_dirty && !_busy,
onPopInvokedWithResult: (didPop, _) async {
if (didPop) return;
if (_busy) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Wait for the radio to finish, then go back.'),
),
);
return;
}
final navigator = Navigator.of(context);
if (await _confirmDiscard()) navigator.pop();
},
child: Scaffold(
appBar: AppBar(
title: Text('Slot ${widget.slot + 1}'),
centerTitle: true,
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
if (showError)
DeviceUiErrorBanner(
message: error,
onDismiss: connector.clearDeviceUiError,
margin: const EdgeInsets.only(bottom: 12),
),
TextField(
controller: _controller,
readOnly: _busy,
minLines: 4,
maxLines: 8,
maxLength: maxSlotRtttl,
keyboardType: TextInputType.visiblePassword,
autocorrect: false,
enableSuggestions: false,
// RTTTL is plain ASCII on one line; the radio stores bytes.
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[\x20-\x7E]')),
],
style: const TextStyle(fontFamily: 'monospace'),
decoration: InputDecoration(
labelText: 'RTTTL',
border: const OutlineInputBorder(),
helperText: helperIsProblem ? null : helper,
errorText: helperIsProblem ? helper : null,
),
),
const SizedBox(height: 8),
Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 8,
children: [
if (orderFix != null)
TextButton(
onPressed: _busy ? null : () => _controller.text = orderFix,
child: const Text('Fix order'),
),
TextButton(
onPressed: _busy || !savedHasTune ? null : _clear,
style: TextButton.styleFrom(foregroundColor: scheme.error),
child: const Text('Clear slot'),
),
OutlinedButton.icon(
onPressed: _busy || !savedHasTune || _dirty
? null
: _playSaved,
icon: const Icon(Icons.play_circle_outline),
label: const Text('Play saved'),
),
FilledButton(
onPressed:
_busy ||
!_dirty ||
emptyText ||
problem != RtttlProblem.ok
? null
: _save,
child: const Text('Save'),
),
],
),
if (_reading) ...[
const SizedBox(height: 16),
LinearProgressIndicator(
value: widget.info.length == 0
? null
: _readBytes / widget.info.length,
),
const SizedBox(height: 6),
Text(
'Reading from the radio: $_readBytes of '
'${widget.info.length} characters',
),
],
if (_saving) ...[
const SizedBox(height: 16),
LinearProgressIndicator(
value: _sendTotal == 0 ? null : _sentBytes / _sendTotal,
),
const SizedBox(height: 6),
Text(
_sendTotal == 0
? 'Clearing the slot'
: 'Sending to the radio: $_sentBytes of $_sendTotal '
'characters',
),
],
const SizedBox(height: 16),
Text(
'Play saved plays what is on the radio, so it is off while there '
'are unsaved changes.',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
);
}
}

@ -4,7 +4,6 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meshcore_open/utils/gpx_export.dart';
import 'package:meshcore_open/widgets/elements_ui.dart';
import 'package:provider/provider.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.dart';
@ -12,10 +11,10 @@ import 'package:url_launcher/url_launcher.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../l10n/l10n.dart';
import '../models/offband_gps_status.dart';
import '../models/radio_preset.dart';
import '../models/radio_settings.dart';
import '../services/app_debug_log_service.dart';
import '../services/app_exit_info_service.dart';
import '../services/app_settings_service.dart';
import '../services/radio_preset_service.dart';
import '../connector/observer_config_client.dart';
@ -26,9 +25,14 @@ import 'settings/app_settings_view.dart';
import 'settings/message_settings_view.dart';
import 'settings/observer_settings_view.dart';
import 'settings/blocked_view.dart';
import 'settings/badge_battery_view.dart';
import 'settings/badge_screen_view.dart';
import 'settings/device_ui_view.dart';
import 'settings/location_view.dart';
import '../helpers/device_name_validator.dart';
import 'app_debug_log_screen.dart';
import 'ble_debug_log_screen.dart';
import 'device_cli_screen.dart';
import 'export_config_screen.dart';
import 'import_config_screen.dart';
import 'serial_capture_screen.dart';
@ -37,6 +41,21 @@ import 'companion_radio_stats_screen.dart';
import '../widgets/radio_preset_picker.dart';
import '../widgets/sync_progress_overlay.dart';
/// True only in a build that passed `--dart-define=OFFBAND_ANR_TEST=true`.
///
/// Gates the force-an-ANR row in the Experimental section. The Experimental
/// section itself ships in release behind a 7-tap unlock, which is not enough
/// protection for a control whose whole job is to hang the app, so the row is
/// compiled out entirely unless a build asks for it (#906). Deliberately NOT
/// read from `dart_defines.json`, because that file feeds every build.
const bool _anrTestBuild = bool.fromEnvironment('OFFBAND_ANR_TEST');
/// Show the row only where it can actually do something. Exit records are
/// Android-only, so on a desktop test build the flag alone would leave a button
/// that does nothing.
bool get _showAnrTestRow =>
_anrTestBuild && AppExitInfoService.isSupportedPlatform;
/// Convert device coding-rate value (1-4 on some firmware, 5-8 on others)
/// to the UI enum range (always 5-8).
int _toUiCodingRate(int deviceCr) {
@ -169,6 +188,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
subtitle: l10n.settings_radioSettingsSubtitle,
builder: _radioRangePane,
),
// #977: the single home for GPS, directly under Radio Settings.
SettingsCategory(
icon: Icons.location_on_outlined,
title: l10n.settings_location,
subtitle: l10n.settings_locationCategorySubtitle,
builder: (_) => const LocationView(),
),
SettingsCategory(
icon: Icons.sensors_outlined,
title: l10n.radioStats_settingsTile,
@ -276,6 +302,56 @@ class _SettingsScreenState extends State<SettingsScreen> {
: null,
),
),
if (_showAnrTestRow) const SizedBox(height: 16),
if (_showAnrTestRow)
// Test-only, and absent from any normal build: the constant below is
// false unless the build passes OFFBAND_ANR_TEST, so this row is
// compiled out of the shipped artifact. Hanging the main thread is the
// only way to produce a real ANR record to read back (#906/#911); no
// adb command induces one. Label is deliberately not localized, since
// it never reaches a user.
//
// The subtitle says to keep tapping for a reason. Android's only
// relevant trigger is "has not responded to an input event within 5
// seconds", and it documents no time-based trigger for a blocked main
// thread. A freeze with nothing pending can therefore recover with no
// ANR, no process death and no exit record to read back.
Card(
child: ListTile(
leading: const Icon(Icons.hourglass_disabled),
title: const Text('Force an ANR, native side (test build only)'),
subtitle: const Text(
'Freezes the UI for 20 seconds in the Android layer. KEEP '
'TAPPING the screen while it is frozen: Android raises an ANR '
'only when an input event goes unanswered for 5 seconds, so a '
'freeze with nothing pending just recovers. Then let the dialog '
'close the app, reopen, and export the debug log.',
),
onTap: () => AppExitInfoService.instance.forceMainThreadBlock(),
),
),
if (_showAnrTestRow) const SizedBox(height: 16),
if (_showAnrTestRow)
// The second trigger exists because the first one cannot answer the
// question the Epic was filed for (#931). Blocking the Android main
// thread yields a Java stack, which proved the capture works but says
// nothing about our Dart frames. The real ANRs block on the Dart UI
// isolate inside the JSON stringifier, so this one blocks there, the
// same way, and its trace should match the Play clusters' shape.
Card(
child: ListTile(
leading: const Icon(Icons.data_object),
title: const Text('Force an ANR, Dart side (test build only)'),
subtitle: const Text(
'Freezes the UI for 20 seconds by encoding JSON on the Dart '
'isolate, which is what the real ANRs do. Same procedure: KEEP '
'TAPPING while frozen, let the dialog close the app, reopen, '
'then export. Use this one to see whether our own Dart function '
'names show up in the trace.',
),
onTap: () => AppExitInfoService.instance.forceDartIsolateBlock(),
),
),
const SizedBox(height: 16),
// Disable, not just hide: turns off every experimental toggle and
// re-locks the section, so nothing keeps running invisibly (#553).
@ -336,6 +412,18 @@ class _SettingsScreenState extends State<SettingsScreen> {
Widget _radioStatsPane(BuildContext context) =>
const CompanionRadioStatsBody();
void _pushBadgePage(BuildContext context, String title, Widget body) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(title: Text(title), centerTitle: true),
body: body,
),
),
);
}
Widget _identityPane(BuildContext context) {
final l10n = context.l10n;
final connector = context.watch<MeshCoreConnector>();
@ -355,54 +443,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
trailing: const Icon(Icons.chevron_right),
onTap: () => _editNodeName(context, connector),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.location_on_outlined),
title: Text(l10n.settings_location),
subtitle: Text(l10n.settings_locationSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () => _editLocation(context, connector),
),
if (connector.currentCustomVars?.containsKey('gps') ?? false) ...[
const Divider(height: 1),
SwitchListTile(
secondary: const Icon(Icons.gps_fixed),
title: Text(l10n.settings_locationGPSEnable),
subtitle: Text(l10n.settings_locationGPSEnableSubtitle),
value: connector.currentCustomVars?['gps'] == '1',
onChanged: (value) async {
try {
await connector.setCustomVar(value ? 'gps:1' : 'gps:0');
} catch (_) {
if (context.mounted) {
showDismissibleSnackBar(
context,
content: const Text(
'Could not update GPS setting. Please try again.',
),
);
}
}
},
),
],
// Button and buzzer: device UI config (#474/#475). Owner-placed
// under Node Settings, directly above the public key.
// Location and the GPS toggle moved to their own category (#977).
// Button actions (#474), directly above the public key. The
// buzzer moved to Message Settings (#978): boards with a buzzer
// and no button exist, so the two are separate entries on
// separate bits.
//
// Gated STRICTLY on the capability bits. A radio without the
// hardware has no button to configure, so it gets no tile, no
// screen and no command. This is the negative test in #474:
// "A device that does not advertise the bit shows no screen and
// the client emits no command."
if (connector.supportsButtonMatrix ||
connector.supportsNotifyScope) ...[
// Gated STRICTLY on the capability bit. A radio without a button
// gets no tile, no screen and no command. This is the negative
// test in #474: "A device that does not advertise the bit shows
// no screen and the client emits no command."
if (connector.supportsButtonMatrix) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.radio_button_checked_outlined),
title: const Text('Button and buzzer'),
subtitle: const Text(
'Assign button actions and set when this radio beeps',
),
title: Text(l10n.settings_buttonActions),
subtitle: Text(l10n.settings_buttonActionsSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
@ -410,16 +466,51 @@ class _SettingsScreenState extends State<SettingsScreen> {
MaterialPageRoute(
builder: (context) => Scaffold(
appBar: AppBar(
title: const Text('Button and buzzer'),
title: Text(l10n.settings_buttonActions),
centerTitle: true,
),
body: const DeviceUiView(),
body: const DeviceUiView(part: DeviceUiPart.buttons),
),
),
);
},
),
],
// The badge's own screen and battery settings (#987), beside
// Button actions (owner decision 2026-10-25). Strictly on the
// 0x40 bit: no bit, no rows, no command.
if (connector.supportsScreenSettings) ...[
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.monitor),
title: Text(l10n.settings_badgeScreen),
subtitle: Text(l10n.settings_badgeScreenSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () => _pushBadgePage(
context,
l10n.settings_badgeScreen,
const BadgeScreenView(),
),
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.battery_std),
title: Text(l10n.settings_badgeBattery),
subtitle: Text(
connector.screenSettings == null
? l10n.settings_badgeBatteryReading
: l10n.settings_badgeBatterySubtitle(
connector.screenSettings!.batteryFullMv,
),
),
trailing: const Icon(Icons.chevron_right),
onTap: () => _pushBadgePage(
context,
l10n.settings_badgeBattery,
const BadgeBatteryView(),
),
),
],
if (connector.selfPublicKey != null) ...[
const Divider(height: 1),
Padding(
@ -523,21 +614,22 @@ class _SettingsScreenState extends State<SettingsScreen> {
Widget _actionsPane(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
// Config import/export and the GPX exports moved here from Debug (#902):
// they are user operations, not diagnostics.
return ListView(
padding: const EdgeInsets.all(16),
children: [_buildActionsCard(context, connector)],
children: [
_buildActionsCard(context, connector),
const SizedBox(height: 16),
_buildExportCard(connector),
],
);
}
Widget _diagnosticsPane(BuildContext context) {
final connector = context.watch<MeshCoreConnector>();
return ListView(
padding: const EdgeInsets.all(16),
children: [
_buildDebugCard(context),
const SizedBox(height: 16),
_buildExportCard(connector),
],
children: [_buildDebugCard(context)],
);
}
@ -760,6 +852,20 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.sync_problem_outlined),
title: Text(l10n.settings_syncQueuedMessages),
subtitle: Text(l10n.settings_syncQueuedMessagesSubtitle),
trailing: const Icon(Icons.download),
onTap: () {
context.read<MeshCoreConnector>().syncQueuedMessages(force: true);
showDismissibleSnackBar(
context,
content: Text(l10n.settings_syncQueuedMessagesRequested),
);
},
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.restart_alt, color: Colors.orange),
title: Text(l10n.settings_rebootDevice),
@ -873,6 +979,13 @@ class _SettingsScreenState extends State<SettingsScreen> {
Widget _buildDebugCard(BuildContext context) {
final l10n = context.l10n;
final settingsService = context.watch<AppSettingsService>();
// #884: the Device CLI console is offered only when the connected radio
// speaks the frame-66 CLI (stock v14+ today; Offband flips allowsCliFrame
// at the upstream-1.18 absorb). select() so only this gate flipping
// rebuilds the pane, not every connector update (the #81 lesson).
final cliCapable = context.select<MeshCoreConnector, bool>(
(c) => c.classification?.allowsCliFrame ?? false,
);
return Card(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@ -884,21 +997,19 @@ class _SettingsScreenState extends State<SettingsScreen> {
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
),
ListTile(
leading: const Icon(Icons.bluetooth_outlined),
title: Text(l10n.settings_companionDebugLog),
subtitle: Text(l10n.settings_companionDebugLogSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
if (cliCapable) ...[
ListTile(
leading: const Icon(Icons.terminal),
title: Text(l10n.deviceCli_title),
subtitle: Text(l10n.deviceCli_entrySubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const BleDebugLogScreen(),
),
);
},
),
const Divider(height: 1),
MaterialPageRoute(builder: (_) => const DeviceCliScreen()),
),
),
const Divider(height: 1),
],
SwitchListTile(
secondary: const Icon(Icons.bug_report_outlined),
title: Text(l10n.appSettings_appDebugLogging),
@ -931,6 +1042,21 @@ class _SettingsScreenState extends State<SettingsScreen> {
},
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.bluetooth_outlined),
title: Text(l10n.settings_companionDebugLog),
subtitle: Text(l10n.settings_companionDebugLogSubtitle),
trailing: const Icon(Icons.chevron_right),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const BleDebugLogScreen(),
),
);
},
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.code_outlined),
title: Text(l10n.settings_appDebugLog),
@ -980,24 +1106,6 @@ class _SettingsScreenState extends State<SettingsScreen> {
);
},
),
const Divider(height: 1),
ListTile(
leading: const Icon(Icons.sync_problem_outlined),
title: const Text('Sync queued messages now'),
subtitle: const Text(
'Force-pull messages the radio is holding, diagnostic for #51 '
'(radio reports a count but the app shows none). Logs the flow '
'for diagnostics.',
),
trailing: const Icon(Icons.download),
onTap: () {
context.read<MeshCoreConnector>().syncQueuedMessages(force: true);
showDismissibleSnackBar(
context,
content: const Text('Requested queued-message drain (force)'),
);
},
),
],
),
);
@ -1099,366 +1207,59 @@ class _SettingsScreenState extends State<SettingsScreen> {
void _editNodeName(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
final controller = TextEditingController(text: connector.selfName ?? '');
String? errorText;
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(l10n.settings_nodeName),
content: TextField(
controller: controller,
decoration: InputDecoration(
hintText: l10n.settings_nodeNameHint,
border: const OutlineInputBorder(),
),
maxLength: 31,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () async {
Navigator.pop(context);
await connector.setNodeName(controller.text);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_nodeNameUpdated),
);
},
child: Text(l10n.common_save),
),
],
),
);
}
Widget _buildGpsQuerySection(
BuildContext context,
OffbandGpsStatus? status,
bool querying,
bool queriedOnce,
VoidCallback onRefresh,
) {
final l10n = context.l10n;
final theme = Theme.of(context);
Widget row(String label, String value) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label),
Text(value, style: const TextStyle(fontWeight: FontWeight.w500)),
],
),
);
final children = <Widget>[
const SizedBox(height: 8),
const Divider(),
Row(
children: [
Expanded(
child: Text(
l10n.settings_gpsStatusTitle,
style: theme.textTheme.titleSmall,
),
),
if (querying)
const Padding(
padding: EdgeInsets.all(8),
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
builder: (context) => StatefulBuilder(
builder: (context, setLocalState) {
// #885: mirror the firmware's `set name` character rejection so a
// bad name is caught here, not bounced as a cryptic device ERROR.
void revalidate(String value) {
final bad = forbiddenCharsIn(value);
setLocalState(() {
errorText = bad.isEmpty
? null
: l10n.settings_nodeNameInvalidChars(bad.join(' '));
});
}
return AlertDialog(
title: Text(l10n.settings_nodeName),
content: TextField(
controller: controller,
onChanged: revalidate,
decoration: InputDecoration(
hintText: l10n.settings_nodeNameHint,
border: const OutlineInputBorder(),
errorText: errorText,
),
)
else
IconButton(
icon: const Icon(Icons.refresh),
tooltip: l10n.settings_gpsStatusRefresh,
onPressed: onRefresh,
maxLength: 31,
),
],
),
];
if (status != null) {
final live = status.hasLiveFix;
final color = live ? Colors.green : Colors.orange;
children.add(
Row(
children: [
Icon(
live ? Icons.gps_fixed : Icons.gps_off,
size: 18,
color: color,
),
const SizedBox(width: 8),
Expanded(
child: Text(
live
? l10n.settings_gpsStatusLiveFix
: l10n.settings_gpsStatusNoFix,
style: TextStyle(color: color, fontWeight: FontWeight.w600),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
),
],
),
);
children.add(const SizedBox(height: 8));
final coords = (status.latitude != null && status.longitude != null)
? '${status.latitude!.toStringAsFixed(6)}, '
'${status.longitude!.toStringAsFixed(6)}'
: '—';
children.add(row(l10n.settings_gpsStatusCoords, coords));
children.add(
row(l10n.settings_gpsStatusSats, status.satellites?.toString() ?? '—'),
);
children.add(
row(
l10n.settings_gpsStatusAltitude,
status.altitudeCm != null
? '${(status.altitudeCm! / 100).toStringAsFixed(1)} m'
: '—',
),
);
final t = status.timestampUtc?.toLocal();
final ml = MaterialLocalizations.of(context);
final timeStr = t == null
? '—'
: '${ml.formatCompactDate(t)} '
'${ml.formatTimeOfDay(TimeOfDay.fromDateTime(t))}';
children.add(row(l10n.settings_gpsStatusTime, timeStr));
} else {
children.add(
Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Text(
queriedOnce
? l10n.settings_gpsStatusNoResponse
: l10n.settings_gpsStatusTapRefresh,
style: theme.textTheme.bodySmall,
),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: children,
);
}
void _editLocation(BuildContext context, MeshCoreConnector connector) {
final l10n = context.l10n;
final latController = TextEditingController();
final lonController = TextEditingController();
final intervalController = TextEditingController();
latController.text = connector.selfLatitude?.toStringAsFixed(6) ?? '';
lonController.text = connector.selfLongitude?.toStringAsFixed(6) ?? '';
// Safe access to custom vars - may be null before device responds
final customVars = connector.currentCustomVars ?? {};
final bool hasGPS = customVars.containsKey("gps");
bool isGPSEnabled = customVars["gps"] == "1";
// Read current interval or default to 900 (15 minutes)
final currentInterval =
int.tryParse(customVars["gps_interval"] ?? "") ?? 900;
intervalController.text = currentInterval.toString();
OffbandGpsStatus? gpsStatus = connector.offbandGpsStatus;
bool queryingGps = false;
bool queriedOnce = false;
showDialog(
context: context,
builder: (dialogContext) => StatefulBuilder(
builder: (context, setDialogState) => AlertDialog(
title: Text(l10n.settings_location),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: latController,
decoration: InputDecoration(
labelText: l10n.settings_latitude,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
const SizedBox(height: 16),
TextField(
controller: lonController,
decoration: InputDecoration(
labelText: l10n.settings_longitude,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
),
if (hasGPS) ...[
const SizedBox(height: 16),
TextField(
controller: intervalController,
decoration: InputDecoration(
labelText: l10n.settings_locationIntervalSec,
border: const OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: false,
signed: false,
),
),
const SizedBox(height: 16),
FeatureToggleRow(
title: l10n.settings_locationGPSEnable,
subtitle: l10n.settings_locationGPSEnableSubtitle,
value: isGPSEnabled,
onChanged: (value) async {
setDialogState(() => isGPSEnabled = value);
try {
await connector.setCustomVar(value ? "gps:1" : "gps:0");
} catch (_) {
if (context.mounted) {
showDismissibleSnackBar(
context,
content: const Text(
'Could not update GPS setting. Please try again.',
),
);
}
}
},
),
if (connector.supportsOffbandGps)
_buildGpsQuerySection(
context,
gpsStatus,
queryingGps,
queriedOnce,
() async {
setDialogState(() => queryingGps = true);
final s = await connector.requestOffbandGps();
if (!dialogContext.mounted) return;
setDialogState(() {
queryingGps = false;
queriedOnce = true;
gpsStatus = s;
});
},
),
],
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(l10n.common_cancel),
),
TextButton(
onPressed: () async {
final messenger = ScaffoldMessenger.of(context);
Navigator.pop(context);
if (hasGPS) {
final intervalText = intervalController.text.trim();
if (intervalText.isEmpty) {
return;
}
final interval = int.tryParse(intervalText);
if (interval == null || interval < 60 || interval >= 86400) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationIntervalInvalid),
);
return;
}
try {
await connector.setCustomVar("gps_interval:$interval");
await connector.refreshDeviceInfo();
} catch (_) {
messenger.showSnackBar(
const SnackBar(
content: Text(
'Could not update location. Please try again.',
),
),
);
TextButton(
onPressed: () async {
if (!isValidDeviceName(controller.text)) {
revalidate(controller.text); // show the error, keep open
return;
}
Navigator.pop(context);
await connector.setNodeName(controller.text);
await connector.refreshDeviceInfo();
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationUpdated),
);
}
final latText = latController.text.trim();
final lonText = lonController.text.trim();
if (latText.isEmpty && lonText.isEmpty) {
return;
}
final currentLat = connector.selfLatitude;
final currentLon = connector.selfLongitude;
final lat = latText.isNotEmpty
? double.tryParse(latText)
: currentLat;
final lon = lonText.isNotEmpty
? double.tryParse(lonText)
: currentLon;
if (lat == null || lon == null) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationBothRequired),
);
return;
}
if (lat < -90 || lat > 90 || lon < -180 || lon > 180) {
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationInvalid),
content: Text(l10n.settings_nodeNameUpdated),
);
return;
}
try {
await connector.setNodeLocation(lat: lat, lon: lon);
await connector.refreshDeviceInfo();
} catch (_) {
messenger.showSnackBar(
const SnackBar(
content: Text(
'Could not update location. Please try again.',
),
),
);
return;
}
if (!context.mounted) return;
showDismissibleSnackBar(
context,
content: Text(l10n.settings_locationUpdated),
);
},
child: Text(l10n.common_save),
),
],
),
},
child: Text(l10n.common_save),
),
],
);
},
),
);
}

@ -6,6 +6,7 @@ import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../services/app_settings_service.dart';
import '../utils/app_logger.dart';
import '../utils/platform_info.dart';
import '../widgets/adaptive_app_bar_title.dart';
import '../helpers/snack_bar_builder.dart';
@ -244,9 +245,17 @@ class _TcpScreenState extends State<TcpScreen> {
}
Future<void> _connectTcp() async {
if (_connector.state == MeshCoreConnectionState.connecting ||
_connector.state == MeshCoreConnectionState.connected ||
_connector.state == MeshCoreConnectionState.disconnecting) {
// An automatic BLE retry yields to this connect (#997). Anything else
// that holds the connection is said out loud, never dropped silently.
if (!_connector.isAutoReconnecting &&
(_connector.state == MeshCoreConnectionState.connecting ||
_connector.state == MeshCoreConnectionState.connected ||
_connector.state == MeshCoreConnectionState.disconnecting)) {
appLogger.warn(
'TCP connect ignored: connection is ${_connector.state}',
tag: 'TcpScreen',
);
showDismissibleSnackBar(context, content: Text(context.l10n.connectBusy));
return;
}

@ -315,8 +315,12 @@ class _UsbScreenState extends State<UsbScreen> {
Future<void> _pollHotPlug() async {
if (_isLoadingPorts) return;
if (!mounted) return;
// Don't poll while connecting or connected.
if (_connector.state != MeshCoreConnectionState.disconnected) return;
// Don't poll while connecting or connected, unless that is only an
// automatic BLE retry the user can preempt from this screen (#997).
if (_connector.state != MeshCoreConnectionState.disconnected &&
!_connector.isAutoReconnecting) {
return;
}
try {
final ports = await _connector.listUsbPorts();
if (!mounted) return;
@ -361,7 +365,17 @@ class _UsbScreenState extends State<UsbScreen> {
}
Future<void> _connectPort(String port) async {
if (_connector.state != MeshCoreConnectionState.disconnected) return;
// An automatic BLE retry yields to this connect (#997). Anything else
// that holds the connection is said out loud, never dropped silently.
if (_connector.state != MeshCoreConnectionState.disconnected &&
!_connector.isAutoReconnecting) {
appLogger.warn(
'Connect tap for $port ignored: connection is ${_connector.state}',
tag: 'UsbScreen',
);
showDismissibleSnackBar(context, content: Text(context.l10n.connectBusy));
return;
}
final rawPortName = normalizeUsbPortName(port);
appLogger.info(

@ -0,0 +1,589 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../storage/prefs_manager.dart';
import 'file_log_service.dart';
/// One `ApplicationExitInfo` record, as the platform channel delivers it.
class ExitRecord {
const ExitRecord({
required this.reason,
required this.reasonName,
required this.timestampMs,
required this.pid,
this.description,
this.processName,
this.importance = 0,
this.pssKb = 0,
this.rssKb = 0,
this.status = 0,
this.traceBytes,
this.traceUnavailable,
this.traceTruncated = false,
});
factory ExitRecord.fromMap(Map<Object?, Object?> map) {
int asInt(Object? v) => v is int ? v : (v is num ? v.toInt() : 0);
return ExitRecord(
reason: asInt(map['reason']),
reasonName: map['reasonName'] as String? ?? 'UNKNOWN',
timestampMs: asInt(map['timestampMs']),
pid: asInt(map['pid']),
description: map['description'] as String?,
processName: map['processName'] as String?,
importance: asInt(map['importance']),
pssKb: asInt(map['pssKb']),
rssKb: asInt(map['rssKb']),
status: asInt(map['status']),
traceBytes: map['traceBytes'] as Uint8List?,
traceUnavailable: map['traceUnavailable'] as String?,
traceTruncated: map['traceTruncated'] as bool? ?? false,
);
}
final int reason;
final String reasonName;
final int timestampMs;
final int pid;
final String? description;
final String? processName;
final int importance;
final int pssKb;
final int rssKb;
final int status;
final Uint8List? traceBytes;
final String? traceUnavailable;
final bool traceTruncated;
/// Reasons that mean the app was killed or broke, as opposed to a routine
/// stop. Drives the log level so an ANR does not read like a normal exit.
bool get isNoteworthy => const {
'ANR',
'CRASH',
'CRASH_NATIVE',
'LOW_MEMORY',
'EXCESSIVE_RESOURCE_USAGE',
'FREEZER',
'INITIALIZATION_FAILURE',
}.contains(reasonName);
}
/// Every message this service can surface, in one place.
///
/// They live here rather than inline so the tests can assert each one is
/// produced by its own failure and absent on the happy path, which is the
/// standing requirement for anything handed over for testing. The alternative
/// would be faking `path_provider` to read the log file back, and there is no
/// precedent for that in this test suite.
abstract final class ExitInfoMessages {
static const String notAndroid =
'exit-info capture is Android only, skipping';
static const String nullResult =
'getExitRecords returned null, nothing logged';
static String unsupported(Object? reason, Object? sdkInt) =>
'exit-info capture unavailable: ${reason ?? 'unknown'} (sdkInt=$sdkInt); '
'devices below API 30 keep no exit records';
static String queryFailed(String code, String? message) =>
'exit-info query failed: $code ${message ?? ''}'.trimRight();
static String captureFailed(Object error) =>
'exit-info capture failed: $error';
static String traceDirMissing(int pid) =>
'no logs directory, trace for pid $pid not written';
static String traceWriteFailed(String name, Object error) =>
'could not write trace $name: $error';
static String pruneFailed(Object error) => 'trace pruning failed: $error';
static String listFailed(Object error) => 'could not list trace dir: $error';
static String watermarkReadFailed(Object error) =>
'could not read exit watermark, treating as first run: $error';
static String watermarkWriteFailed(Object error) =>
'could not persist exit watermark, may re-log: $error';
static String forceBlockFailed(Object error) =>
'forceMainThreadBlock failed: $error';
/// Not an error. Logged when the Dart isolate block ran its full duration
/// without the system raising an ANR, which means no input went unanswered.
/// Says why, so the tester is not left guessing (#931).
static String dartBlockSurvived(int millis, int encodedBytes) =>
'dart isolate block ran ${millis}ms and encoded $encodedBytes bytes, '
'but no ANR was raised: Android raises one only when an input event goes '
'unanswered for 5 seconds, so keep tapping the screen during the freeze';
/// Fragments that must never appear in a line produced on the happy path.
static const List<String> failureMarkers = [
'unavailable:',
'failed',
'could not',
'no logs directory',
];
}
/// What [selectExitRecords] decided to do with a batch of records.
class ExitSelection {
const ExitSelection({
required this.records,
required this.backfill,
required this.traceBudget,
required this.newWatermarkMs,
});
/// Only the records newer than the watermark, newest first.
final List<ExitRecord> records;
/// True on the first run, when there is no watermark yet and the system's
/// buffer may hold months of history.
final bool backfill;
/// How many of [records] may have their trace written out.
final int traceBudget;
/// Where the watermark moves to, or null when nothing was new.
final int? newWatermarkMs;
}
/// Pick the records that have not been logged yet.
///
/// [all] arrives newest first, as `getHistoricalProcessExitReasons` returns it.
/// Records with a timestamp equal to the watermark were already logged, so the
/// comparison is strictly greater. Two records sharing a millisecond are both
/// greater than the watermark in the same pass, so both are kept and neither is
/// lost when the watermark then advances past them.
ExitSelection selectExitRecords(
List<ExitRecord> all,
int? watermarkMs, {
int backfillTraceCap = 3,
}) {
final backfill = watermarkMs == null;
final fresh = backfill
? List<ExitRecord>.of(all)
: all.where((r) => r.timestampMs > watermarkMs).toList();
if (fresh.isEmpty) {
return const ExitSelection(
records: [],
backfill: false,
traceBudget: 0,
newWatermarkMs: null,
);
}
var highest = fresh.first.timestampMs;
for (final r in fresh) {
if (r.timestampMs > highest) highest = r.timestampMs;
}
return ExitSelection(
records: fresh,
backfill: backfill,
traceBudget: backfill
? (fresh.length < backfillTraceCap ? fresh.length : backfillTraceCap)
: fresh.length,
newWatermarkMs: highest,
);
}
/// Human-readable form of the `RunningAppProcessInfo` importance value. Whether
/// the process was in the foreground is the first thing you want to know about
/// an ANR, since a cached-process hang is not user-visible.
String importanceName(int importance) {
switch (importance) {
case 100:
return 'FOREGROUND';
case 125:
return 'FOREGROUND_SERVICE';
case 200:
return 'VISIBLE';
case 230:
return 'PERCEPTIBLE';
case 300:
return 'SERVICE';
case 350:
return 'CANT_SAVE_STATE';
case 400:
return 'CACHED';
case 1000:
return 'GONE';
default:
return importance == 0 ? 'unknown' : 'IMPORTANCE_$importance';
}
}
/// Memory figures are documented in kB and are 0 when the system never sampled
/// the process, so 0 is rendered as unknown rather than as a real measurement.
String _memory(int kb) => kb <= 0 ? 'unknown' : '${kb}kB';
String _traceField(ExitRecord record, String? writtenFileName) {
if (writtenFileName != null) {
return record.traceTruncated
? 'trace=$writtenFileName(truncated)'
: 'trace=$writtenFileName';
}
final why = record.traceUnavailable;
return 'trace=none${why == null ? '' : '($why)'}';
}
/// The log line for one exit record, in the same shape the app log already
/// uses: `<iso8601> [LEVEL/Tag] message`.
String formatExitLine(
ExitRecord record, {
required bool backfill,
String? writtenFileName,
DateTime? now,
}) {
final stamp = (now ?? DateTime.now()).toIso8601String();
final level = record.isNoteworthy ? 'WARN' : 'INFO';
final at = DateTime.fromMillisecondsSinceEpoch(
record.timestampMs,
isUtc: true,
).toIso8601String();
final desc = record.description;
final parts = <String>[
'reason=${record.reasonName}(${record.reason})',
if (desc != null && desc.isNotEmpty) 'desc="$desc"',
'at=$at',
'pid=${record.pid}',
if (record.processName != null) 'proc=${record.processName}',
'importance=${importanceName(record.importance)}',
'pss=${_memory(record.pssKb)}',
'rss=${_memory(record.rssKb)}',
'status=${record.status}',
_traceField(record, writtenFileName),
if (backfill) 'backfill=true',
];
return '$stamp [$level/ExitInfo] ${parts.join(' ')}';
}
/// `anr-<utc>-<pid>.txt`. The UTC stamp sorts lexicographically, which is what
/// lets the pruner treat a plain name sort as chronological.
String traceFileName(int timestampMs, int pid) {
final t = DateTime.fromMillisecondsSinceEpoch(timestampMs, isUtc: true);
String two(int v) => v.toString().padLeft(2, '0');
final stamp =
'${t.year}${two(t.month)}${two(t.day)}T'
'${two(t.hour)}${two(t.minute)}${two(t.second)}Z';
return 'anr-$stamp-$pid.txt';
}
/// Which trace files to delete, given every file's name and size.
///
/// Keeps at most [keep] of the newest and holds the total at or under
/// [ceilingBytes], dropping oldest first. Names sort chronologically, so the
/// caller does not need file timestamps. The newest file is never deleted, even
/// when it alone exceeds the ceiling: a trace too big to keep is still the one
/// piece of evidence worth having.
List<String> traceFilesToPrune(
Map<String, int> sizesByName, {
int keep = 5,
int ceilingBytes = 1024 * 1024,
}) {
final names = sizesByName.keys.toList()..sort();
final doomed = <String>[];
final surviving = names.toList();
while (surviving.length > keep) {
doomed.add(surviving.removeAt(0));
}
var total = surviving.fold<int>(0, (sum, n) => sum + (sizesByName[n] ?? 0));
while (total > ceilingBytes && surviving.length > 1) {
final oldest = surviving.removeAt(0);
total -= sizesByName[oldest] ?? 0;
doomed.add(oldest);
}
return doomed;
}
/// Reports why the app's previous processes died, by reading the system's own
/// exit records on the next launch and writing them into the debug log (#906).
///
/// Android only, API 30 and up. Everywhere else this is a no-op that says so
/// once. ANR traces go to a file beside `offband.log` with a pointer line in the
/// log itself, because the log export only ever ships the active log file, and a
/// trace written inline would both evict surrounding context and later rotate
/// away.
class AppExitInfoService {
AppExitInfoService._();
static final AppExitInfoService instance = AppExitInfoService._();
static const MethodChannel _channel = MethodChannel(
'meshcore_open/app_exit_info',
);
/// SharedPreferences key holding the highest exit timestamp already logged.
static const String watermarkKey = 'anr_last_exit_ts_ms';
static const String traceDirName = 'anr';
static const int keepTraceFiles = 5;
static const int traceDirCeilingBytes = 1024 * 1024;
static const int backfillTraceCap = 3;
bool _ran = false;
/// Exit records exist only on Android. Public so the test trigger in Settings
/// can hide itself rather than offering a button that does nothing.
static bool get isSupportedPlatform =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.android;
static bool get _isAndroid => isSupportedPlatform;
/// The directory ANR traces are written to, or null when file logging is
/// unavailable. Used by the log export so the traces ship with the log.
static Directory? get traceDir {
final logs = FileLogService.instance.logDir;
if (logs == null) return null;
return Directory('${logs.path}${Platform.pathSeparator}$traceDirName');
}
/// Any ANR trace files currently on disk, oldest first. Empty when there are
/// none, when the directory does not exist, or when it cannot be listed.
static Future<List<File>> traceFiles() async {
final dir = traceDir;
if (dir == null) return const [];
try {
if (!await dir.exists()) return const [];
return (await dir.list().toList()).whereType<File>().toList()
..sort((a, b) => a.path.compareTo(b.path));
} catch (error) {
instance._log('WARN', ExitInfoMessages.listFailed(error));
return const [];
}
}
/// Read the system's exit records and log anything not logged before.
///
/// Safe to call once per launch; a second call is a no-op. Never throws: a
/// diagnostic must not be able to break startup. Every failure path writes a
/// line, so nothing here is silent.
Future<void> collect() async {
if (_ran) return;
_ran = true;
if (!_isAndroid) {
_log('INFO', ExitInfoMessages.notAndroid);
return;
}
try {
final raw = await _channel.invokeMapMethod<String, Object?>(
'getExitRecords',
);
if (raw == null) {
_log('WARN', ExitInfoMessages.nullResult);
return;
}
if (raw['supported'] != true) {
_log(
'INFO',
ExitInfoMessages.unsupported(raw['unsupportedReason'], raw['sdkInt']),
);
return;
}
final records = (raw['records'] as List?)
?.whereType<Map<Object?, Object?>>()
.map(ExitRecord.fromMap)
.toList();
if (records == null || records.isEmpty) return;
await _report(records);
} on PlatformException catch (error) {
// The query failed. Leave the watermark alone so the next launch retries.
_log('WARN', ExitInfoMessages.queryFailed(error.code, error.message));
} catch (error) {
_log('WARN', ExitInfoMessages.captureFailed(error));
}
}
Future<void> _report(List<ExitRecord> records) async {
final selection = selectExitRecords(
records,
_readWatermark(),
backfillTraceCap: backfillTraceCap,
);
if (selection.records.isEmpty) return;
var tracesWritten = 0;
for (final record in selection.records) {
String? writtenName;
final bytes = record.traceBytes;
if (bytes != null &&
bytes.isNotEmpty &&
tracesWritten < selection.traceBudget) {
writtenName = await _writeTrace(record, bytes);
if (writtenName != null) tracesWritten++;
}
FileLogService.instance.write(
formatExitLine(
record,
backfill: selection.backfill,
writtenFileName: writtenName,
),
);
}
await _prune();
await _writeWatermark(selection.newWatermarkMs);
// FileLogService batches on a 2 second timer, so without this the lines
// above can be lost if the process dies again before the next flush,
// leaving a trace file on disk with nothing pointing at it.
await FileLogService.instance.flushAndGetActiveFile();
}
Future<String?> _writeTrace(ExitRecord record, Uint8List bytes) async {
final dir = traceDir;
if (dir == null) {
_log('WARN', ExitInfoMessages.traceDirMissing(record.pid));
return null;
}
final name = traceFileName(record.timestampMs, record.pid);
try {
await dir.create(recursive: true);
await File(
'${dir.path}${Platform.pathSeparator}$name',
).writeAsBytes(bytes, flush: true);
return name;
} catch (error) {
// Reported into the main log, which is a different file and so is likely
// still writable even when this one is not.
_log('WARN', ExitInfoMessages.traceWriteFailed(name, error));
return null;
}
}
Future<void> _prune() async {
final files = await traceFiles();
if (files.isEmpty) return;
try {
final sizes = <String, int>{};
for (final f in files) {
sizes[f.uri.pathSegments.last] = await f.length();
}
final doomed = traceFilesToPrune(
sizes,
keep: keepTraceFiles,
ceilingBytes: traceDirCeilingBytes,
);
for (final name in doomed) {
for (final f in files) {
if (f.uri.pathSegments.last == name) {
await f.delete();
break;
}
}
}
} catch (error) {
_log('WARN', ExitInfoMessages.pruneFailed(error));
}
}
int? _readWatermark() {
try {
return PrefsManager.instance.getInt(watermarkKey);
} catch (error) {
// Treated as a first run, which backfills under a cap and says so.
_log('WARN', ExitInfoMessages.watermarkReadFailed(error));
return null;
}
}
Future<void> _writeWatermark(int? value) async {
if (value == null) return;
try {
await PrefsManager.instance.setInt(watermarkKey, value);
} catch (error) {
// Worth surfacing: the same records will be logged again next launch.
_log('WARN', ExitInfoMessages.watermarkWriteFailed(error));
}
}
/// Test-only hook, called from the owner-only Experimental section in builds
/// compiled with `OFFBAND_ANR_TEST`. Hangs the Android main thread so the
/// system raises a real ANR, which is the only way to produce a record to
/// read back (#911).
Future<void> forceMainThreadBlock({int millis = 20000}) async {
if (!_isAndroid) return;
try {
await _channel.invokeMethod<int>('forceMainThreadBlock', {
'millis': millis,
});
} catch (error) {
_log('WARN', ExitInfoMessages.forceBlockFailed(error));
}
}
/// Test-only, same double gating as [forceMainThreadBlock]. Blocks the **Dart
/// UI isolate** instead of the Android main thread, and blocks it the way the
/// real ANRs do rather than with an artificial spin (#931).
///
/// Why this exists separately. The Kotlin block produces a Java stack, so it
/// proved the capture works but could say nothing about whether our own Dart
/// frames survive into a trace. The Play clusters show the real ANRs blocking
/// on this isolate inside the JSON stringifier and under allocation pressure,
/// so encoding a large nested structure in a loop should yield a trace of the
/// same shape, and answer whether any of our Dart frames resolve.
///
/// It spins on purpose. Any `await` inside the loop would yield to the event
/// loop, the isolate would keep answering input, and no ANR would fire.
Future<void> forceDartIsolateBlock({int millis = 20000}) async {
if (!isSupportedPlatform) return;
final payload = _blockPayload();
// Stopwatch, not DateTime.now(): the wall clock can move backwards (NTP, or
// the tester changing it) and would push the deadline away, leaving the app
// frozen well past the intended window or indefinitely. The Kotlin block
// already uses a monotonic source, so this matches it.
final elapsed = Stopwatch()..start();
var encoded = 0;
while (elapsed.elapsedMilliseconds < millis) {
encoded += jsonEncode(payload).length;
}
// Only reached when the process survived, so the tester gets told why.
_log('WARN', ExitInfoMessages.dartBlockSurvived(millis, encoded));
await FileLogService.instance.flushAndGetActiveFile();
}
/// Shaped like the stores #334 is about: many keyed entries, each a nested
/// object, which is what gets JSON-encoded on this isolate in the real bug.
static Map<String, Object?> _blockPayload() => {
for (var i = 0; i < 400; i++)
'entry_$i': {
'id': i,
'name': 'contact-$i',
'path': List<int>.generate(24, (j) => (i + j) & 0xFF),
'meta': {
'lastSeen': i * 1000,
'snr': -(i % 40),
'flags': const ['a', 'b', 'c'],
},
'text': 'x' * 64,
},
};
/// Visible for tests so a second `collect()` can be exercised.
@visibleForTesting
void resetForTest() => _ran = false;
void _log(String level, String message) {
FileLogService.instance.write(
'${DateTime.now().toIso8601String()} [$level/ExitInfo] $message',
);
}
}

@ -237,42 +237,51 @@ class AppSettingsService extends ChangeNotifier {
await updateSettings(_settings.copyWith(unitSystem: value));
}
/// Per-channel notification level.
///
/// Resolution order: the PSK-keyed mode when one is set, else the legacy
/// name-keyed mute (so a channel muted before this feature existed still
/// reports [ChannelNotifyMode.off]), else [ChannelNotifyMode.all].
///
/// [identityKey] comes from [AppSettings.channelNotifyKey]; the caller
/// resolves the slot index to a PSK.
/// First 10 hex of the connected radio's key, matching every other per-radio
/// store. Empty when no radio is connected -> the caller gets the default.
static String _scopePrefix(String devicePrefix) =>
devicePrefix.length > 10 ? devicePrefix.substring(0, 10) : devicePrefix;
/// Resolve a channel's notify mode for the CONNECTED radio ([devicePrefix])
/// by its [pskHex]. No bare-index fallback and no cross-radio legacy fallback:
/// an unknown scope (no radio, or PSK not yet synced) resolves to the default
/// `all` rather than inheriting another radio's or slot's state (#839).
ChannelNotifyMode channelNotifyMode({
required String identityKey,
required String channelName,
required String devicePrefix,
required String? pskHex,
}) {
final mode = _settings.channelNotifyModes[identityKey];
if (mode != null) return mode;
if (_settings.mutedChannels.contains(channelName)) {
return ChannelNotifyMode.off;
final prefix = _scopePrefix(devicePrefix);
if (prefix.isEmpty || pskHex == null || pskHex.isEmpty) {
return ChannelNotifyMode.all;
}
return ChannelNotifyMode.all;
return _settings.channelNotifyModesByRadio[prefix]?[pskHex] ??
ChannelNotifyMode.all;
}
/// Store a channel's notify mode for the connected radio. Keyed only by
/// ([devicePrefix], [pskHex]); when either is unknown this is a no-op so we
/// never write an unscoped or index-keyed entry. `all` removes the single
/// entry (it is the default), so set-and-back genuinely resets (#839).
Future<void> setChannelNotifyMode({
required String identityKey,
required String devicePrefix,
required String? pskHex,
required String channelName,
required ChannelNotifyMode mode,
}) async {
final modes = Map<String, ChannelNotifyMode>.from(
_settings.channelNotifyModes,
);
final prefix = _scopePrefix(devicePrefix);
if (prefix.isEmpty || pskHex == null || pskHex.isEmpty) return;
final byRadio = _copyByRadio();
final radioModes = byRadio.putIfAbsent(prefix, () => {});
if (mode == ChannelNotifyMode.all) {
modes.remove(identityKey); // `all` is the default; don't store it.
radioModes.remove(pskHex);
if (radioModes.isEmpty) byRadio.remove(prefix);
} else {
modes[identityKey] = mode;
radioModes[pskHex] = mode;
}
// Keep the legacy name-keyed set in sync so rolling back to a build without
// notify modes still honours an Off channel. Remove after one release.
// Keep the legacy name-keyed set written (rollback compat only; it is not
// consulted by the resolution above). Remove after one release.
final muted = Set<String>.from(_settings.mutedChannels);
if (mode == ChannelNotifyMode.off) {
muted.add(channelName);
@ -281,25 +290,67 @@ class AppSettingsService extends ChangeNotifier {
}
await updateSettings(
_settings.copyWith(channelNotifyModes: modes, mutedChannels: muted),
_settings.copyWith(
channelNotifyModesByRadio: byRadio,
mutedChannels: muted,
),
);
}
bool isChannelMuted(String channelName) {
return _settings.mutedChannels.contains(channelName);
}
/// One-time migration of the pre-#839 global state into the FIRST radio seen
/// after upgrade. Called by the connector once that radio's channels are
/// known. Later radios start clean, so the ambiguous legacy state never
/// bleeds across radios. [pskByChannelIndex] / [pskByChannelName] resolve the
/// legacy index- and name-keyed entries to a PSK; unresolvable ones drop.
Future<void> migrateLegacyChannelNotify({
required String devicePrefix,
required Map<int, String> pskByChannelIndex,
required Map<String, String> pskByChannelName,
}) async {
if (_settings.channelNotifyMigrated) return;
final prefix = _scopePrefix(devicePrefix);
if (prefix.isEmpty) return;
final byRadio = _copyByRadio();
final radioModes = byRadio.putIfAbsent(prefix, () => {});
// 1) psk_<hex> entries map straight across; 2) <index> entries resolve via
// the connected radio's channel table (index entries that don't resolve are
// ambiguous and dropped); later writes override earlier.
_settings.channelNotifyModes.forEach((key, mode) {
if (mode == ChannelNotifyMode.all) return;
if (key.startsWith('psk_')) {
radioModes[key.substring(4)] = mode;
} else {
final idx = int.tryParse(key);
final psk = idx == null ? null : pskByChannelIndex[idx];
if (psk != null && psk.isNotEmpty) radioModes[psk] = mode;
}
});
Future<void> muteChannel(String channelName) async {
final updated = Set<String>.from(_settings.mutedChannels)..add(channelName);
await updateSettings(_settings.copyWith(mutedChannels: updated));
}
// 3) legacy name-keyed mutes become Off on their resolved PSK.
for (final name in _settings.mutedChannels) {
final psk = pskByChannelName[name];
if (psk != null && psk.isNotEmpty) {
radioModes[psk] = ChannelNotifyMode.off;
}
}
Future<void> unmuteChannel(String channelName) async {
final updated = Set<String>.from(_settings.mutedChannels)
..remove(channelName);
await updateSettings(_settings.copyWith(mutedChannels: updated));
if (radioModes.isEmpty) byRadio.remove(prefix);
await updateSettings(
_settings.copyWith(
channelNotifyModesByRadio: byRadio,
channelNotifyMigrated: true,
),
);
}
Map<String, Map<String, ChannelNotifyMode>> _copyByRadio() => {
for (final e in _settings.channelNotifyModesByRadio.entries)
e.key: Map<String, ChannelNotifyMode>.from(e.value),
};
Future<void> setTcpServerAddress(String value) async {
await updateSettings(_settings.copyWith(tcpServerAddress: value));
}

@ -0,0 +1,259 @@
// What the CLI console (device_cli_screen) talks to (#999, plan F3/E3.1). The
// console renders the same transcript whether the CLI runs on the connected
// radio (local frame 66/29) or on a remote contact over the mesh (TXT type
// chosen by role, #888/#889). This abstracts the two transports behind one
// run()->CliReply call and one timeout type, so the screen holds no
// transport-specific branches.
//
// No auto-retry on the remote leg: a companion that has not granted us remote
// CLI (contact flag 0x10 on its side) queues our command as a plain message and
// never replies, so retrying only spams the mesh. One send, then a timeout the
// console explains (#891). Repeaters use their own screen and keep their retry
// behavior there.
import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';
import '../connector/cli_command_codec.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../models/contact.dart';
import 'local_cli_service.dart';
import 'repeater_command_service.dart';
/// A CLI command's window closed with no reply, regardless of transport. Both
/// underlying services carry their own timeout type; the console catches only
/// this one so its handling reads the same for a local or a remote command.
class CliConsoleTimeout implements Exception {
const CliConsoleTimeout({required this.command, required this.secondsText});
final String command;
/// The armed window in seconds to one decimal, e.g. `10.0`.
final String secondsText;
@override
String toString() => 'CLI command timed out after $secondsText s';
}
/// The connected radio refused to send a remote CLI command at all: its
/// firmware does not accept TXT_TYPE_CLI_COMMAND (pre-1.18 answers
/// ERR_CODE_UNSUPPORTED_CMD). Distinct from [CliConsoleTimeout], which means
/// the command went out and the target never answered.
class CliConsoleUnsupported implements Exception {
const CliConsoleUnsupported({required this.command});
final String command;
@override
String toString() => 'The connected radio does not support remote CLI';
}
/// One CLI transport for the console: the connected device, or a remote contact.
abstract class CliConsoleTransport {
/// Runs [command] and completes with the correlated reply, or throws
/// [CliConsoleTimeout] when the window closes with no answer. Other failures
/// (codec rejection, send error) surface as their own exceptions.
Future<CliReply> run(String command, {Duration? timeout});
void dispose();
}
/// CLI on the connected radio, over frame 66/29.
class LocalCliTransport implements CliConsoleTransport {
LocalCliTransport(MeshCoreConnector connector, {LocalCliService? service})
: _service = service ?? LocalCliService(connector);
final LocalCliService _service;
@override
Future<CliReply> run(String command, {Duration? timeout}) async {
try {
return await _service.run(command, timeout: timeout);
} on LocalCliTimeout catch (e) {
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
}
}
@override
void dispose() => _service.dispose();
}
/// CLI on a remote contact over the mesh. The txt type is chosen by the
/// target's role (#888/#889): a companion gets TXT_TYPE_CLI_COMMAND, a
/// repeater/room server the universal CLI_DATA. The reply returns as a contact
/// message carrying the reflected `cc|` prefix; this listens for it and feeds it
/// to the shared correlation in [RepeaterCommandService].
class RemoteCliTransport implements CliConsoleTransport {
RemoteCliTransport(
this._connector,
this._target, {
RepeaterCommandService? service,
}) : _service = service ?? RepeaterCommandService(_connector) {
// A companion is a human chat node, so a late/unmatched reply must never
// log its text: a slow `get wifi.pwd` round trip would otherwise write the
// password to the app log, which the console's masking cannot undo. Match
// LocalCliService, which always withholds (#999 review).
_service.redactUnmatchedReplyText = true;
_sub = _connector.receivedFrames.listen(_onFrame);
}
final MeshCoreConnector _connector;
final Contact _target;
final RepeaterCommandService _service;
StreamSubscription<Uint8List>? _sub;
bool _disposed = false;
/// Rejection channel for the command in flight: completed with
/// [CliConsoleUnsupported] when the radio refuses the send outright.
///
/// It only listens while [_armed]: from the moment the text frame is written
/// (the `onAttempt` hook fires after the path update and runs straight into
/// the frame write, with no yield in between) until the radio answers that
/// write. The firmware answers each CMD_SEND_TXT_MSG at once, in order: a
/// pre-1.18 radio with ERR_CODE_UNSUPPORTED_CMD for type 3; a 1.18 radio with
/// RESP_CODE_SENT carrying an expected-ack of 0, since a CLI command expects
/// no ack (companion-v1.18.0 CMD_SEND_TXT_MSG). A plain DM's SENT carries a
/// real ack hash, so it never closes the window.
///
/// ERR_CODE_UNSUPPORTED_CMD is also the firmware's answer to any unknown
/// command. Arming at the write, rather than at [run], keeps an unrelated
/// refusal from failing a valid command. The residual exposure is one
/// landing inside our own send's round trip, on a radio where the connector
/// already withholds fork frames.
///
/// One command at a time: a new [run] replaces the channel, and the replaced
/// command falls back to its timeout rather than risk misattribution.
Completer<CliReply>? _sendWindow;
String? _sendWindowCommand;
bool _armed = false;
void _onFrame(Uint8List frame) {
if (_disposed || frame.isEmpty) return;
if (frame[0] == respCodeSent) {
// [RESP_CODE_SENT][is_flood][expected_ack x4][est_timeout x4]. Only a
// command send's SENT (ack 0) answers ours.
if (_armed &&
frame.length >= 6 &&
frame[2] == 0 &&
frame[3] == 0 &&
frame[4] == 0 &&
frame[5] == 0) {
_armed = false;
}
return;
}
if (frame[0] == respCodeErr) {
final code = frame.length > 1 ? frame[1] : -1;
final window = _sendWindow;
if (_armed &&
code == errCodeUnsupportedCmd &&
window != null &&
!window.isCompleted) {
_armed = false;
window.completeError(
CliConsoleUnsupported(command: _sendWindowCommand ?? ''),
);
}
return;
}
if (frame[0] != respCodeContactMsgRecv &&
frame[0] != respCodeContactMsgRecvV3) {
return;
}
final parsed = parseContactMessageText(frame);
if (parsed == null) return;
if (!_matchesTargetPrefix(parsed.senderPrefix)) return;
// Only a CLI_DATA reply answers a command. A plain chat message, or an
// inbound type-3 command, from the SAME companion must not complete our
// pending command - without this it would hit handleResponse's unprefixed
// sole-pending fallback and render "hey, you there?" as the CLI reply
// (#999 review). Some layouts carry the type shifted; check both.
final t = parsed.txtType;
if (t != txtTypeCliData && (t >> 2) != txtTypeCliData) return;
// Routes to the waiting command's future (or is logged if its window
// already closed, #589). handleResponse resolves the target from its key,
// so the possibly-stale [_target] is fine here.
_service.handleResponse(_resolveTarget(), parsed.text);
}
bool _matchesTargetPrefix(Uint8List prefix) {
final key = _target.publicKey;
if (key.length < 6 || prefix.length < 6) return false;
for (var i = 0; i < 6; i++) {
if (prefix[i] != key[i]) return false;
}
return true;
}
/// The contact's path can be updated after this transport is built, so re-read
/// the live contact by key at send time and fall back to the original.
Contact _resolveTarget() {
for (final c in _connector.contacts) {
if (c.publicKeyHex == _target.publicKeyHex) return c;
}
return _target;
}
@override
Future<CliReply> run(String command, {Duration? timeout}) async {
final window = Completer<CliReply>();
_sendWindow = window;
_sendWindowCommand = command;
_armed = false;
try {
// Whichever lands first: the reply (or its timeout), or the radio
// refusing the send. Future.any keeps handlers on the loser, so its later
// timeout is absorbed rather than surfacing as an unhandled error.
return await Future.any([_send(command, window), window.future]);
} finally {
if (identical(_sendWindow, window)) {
_sendWindow = null;
_armed = false;
}
}
}
Future<CliReply> _send(String command, Completer<CliReply> window) async {
// retries: 1 - one send, no auto-retry. See the file header.
try {
final text = await _service.sendCommand(
_resolveTarget(),
command,
retries: 1,
// Fires after the path update, immediately before the text frame is
// written: arm the rejection window here, not earlier.
onAttempt: (_) {
if (identical(_sendWindow, window)) _armed = true;
},
);
// payloadLength drives CliReply.atReplyBound (the local 165-byte device
// bound). A remote reply is a reassembled mesh message, so that bound is
// not meaningful and truncation cannot be detected here; the stripped
// text length keeps atReplyBound false rather than faking a cut (#999).
return CliReply(
prefix: null,
text: text,
payloadLength: utf8.encode(text).length,
);
} on RepeaterCommandTimeout catch (e) {
throw CliConsoleTimeout(command: command, secondsText: e.secondsText);
}
}
@override
void dispose() {
_disposed = true;
_sub?.cancel();
_sub = null;
// Release a command still waiting, so its run() cannot hang.
final window = _sendWindow;
_sendWindow = null;
_armed = false;
if (window != null && !window.isCompleted) {
window.completeError(StateError('RemoteCliTransport disposed'));
}
_service.dispose();
}
}

@ -0,0 +1,41 @@
// Shared `cc|` correlation grammar (#882): one allocator and one splitter for
// every CLI path - the repeater text-message CLI (RepeaterCommandService) and
// the local frame-66 console (LocalCliService). The grammar is the device's:
// a 3-char token ending in `|`, reflected at the start of the reply when the
// command carried one.
/// Allocates `XX|` correlation tokens: two uppercase hex digits and a pipe,
/// cycling through 256 values and skipping any currently in flight.
class PrefixAllocator {
int _counter = 0;
String next(Set<String> inUse) {
for (var i = 0; i < 256; i++) {
final value = _counter++ & 0xFF;
final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|';
if (!inUse.contains(token)) return token;
}
return '00|';
}
}
/// A reply split into its reflected correlation token and payload.
class Correlated {
const Correlated({required this.prefix, required this.payload});
final String? prefix;
final String payload;
}
/// Splits [raw] on the positional prefix rule (third character `|`). The
/// payload keeps its leading whitespace trimmed, matching the repeater path's
/// long-standing behavior.
Correlated splitCorrelated(String raw) {
if (raw.length >= 3 && raw[2] == '|') {
return Correlated(
prefix: raw.substring(0, 3),
payload: raw.substring(3).trimLeft(),
);
}
return Correlated(prefix: null, payload: raw);
}

@ -73,6 +73,28 @@ class FileLogService {
return _writer?.activeFile;
}
/// Flush pending lines and return every log file on disk, newest first.
///
/// The export needs all of them, not just the active one: a line written once
/// at startup, such as an exit-record pointer, can rotate into `.1.log` after
/// a couple of MiB of ordinary logging, and the rotated files were previously
/// unreachable so that context was simply lost (#906). Empty when file logging
/// is unavailable.
Future<List<File>> flushAndGetAllFiles() async {
await _flush();
final w = _writer;
if (w == null) return const [];
try {
return await w.existingFiles();
} catch (_) {
// Degrade to the active file rather than failing the export outright:
// this is the logger, so it cannot report its own listing failure
// anywhere, and handing over one log beats handing over none.
final active = w.activeFile;
return await active.exists() ? <File>[active] : const <File>[];
}
}
/// Cancel the periodic flush and flush once more. The singleton normally lives
/// for the app's lifetime; this is for a clean shutdown / tests.
Future<void> dispose() async {

@ -0,0 +1,125 @@
// Local device CLI over frame 66/29 (#882, plan F2/E2.1). Sends
// CMD_RUN_CLI_COMMAND to the CONNECTED radio and completes with the
// correlated RESP_CODE_CLI_REPLY. No mesh legs, so no retries: the transport
// is the connected link, and a lost frame surfaces as a timeout.
//
// Population gating is NOT here: callers (the console entry point, #884)
// must only construct/offer this where the classifier allows frame 66.
import 'dart:async';
import '../connector/cli_command_codec.dart';
import '../connector/meshcore_connector.dart';
import '../utils/app_logger.dart';
import 'command_correlation.dart';
/// Thrown when the device does not answer inside the window.
class LocalCliTimeout implements Exception {
const LocalCliTimeout({required this.command, required this.timeout});
final String command;
final Duration timeout;
/// The armed window in seconds to one decimal, e.g. `10.0` - same shape as
/// [RepeaterCommandTimeout.secondsText] so UI strings read alike.
String get secondsText => (timeout.inMilliseconds / 1000).toStringAsFixed(1);
@override
String toString() => 'CLI command timed out after $secondsText s';
}
class LocalCliService {
LocalCliService(this._connector) {
_detach = _connector.addCliReplyListenerForLocalCli(_handleReply);
}
final MeshCoreConnector _connector;
final PrefixAllocator _prefixes = PrefixAllocator();
final Map<String, Completer<CliReply>> _pending = {};
final Map<String, Timer> _timeouts = {};
void Function()? _detach;
/// Default window for a local round trip. Generous: some device handlers
/// (WiFi status on a busy radio) run tens of milliseconds, and BLE
/// notification scheduling adds more; nothing on the local link should
/// legitimately take longer than this.
static const Duration defaultTimeout = Duration(seconds: 10);
/// Sends [command] to the connected device; completes with the correlated
/// reply or throws [LocalCliTimeout] / [ArgumentError] (codec rejections).
Future<CliReply> run(String command, {Duration? timeout}) async {
final window = timeout ?? defaultTimeout;
final prefix = _prefixes.next(_pending.keys.toSet());
final frame = buildRunCliCommandFrame(command, prefix: prefix);
final completer = Completer<CliReply>();
_pending[prefix] = completer;
_timeouts[prefix] = Timer(window, () {
final waiting = _pending.remove(prefix);
_timeouts.remove(prefix);
if (waiting != null && !waiting.isCompleted) {
waiting.completeError(
LocalCliTimeout(command: command, timeout: window),
);
}
});
try {
await _connector.sendFrame(frame);
} catch (e) {
_cleanup(prefix);
rethrow;
}
try {
return await completer.future;
} finally {
_cleanup(prefix);
}
}
void _handleReply(CliReply reply) {
final prefix = reply.prefix;
final waiting = prefix != null ? _pending.remove(prefix) : null;
if (waiting != null && !waiting.isCompleted) {
_timeouts.remove(prefix)?.cancel();
waiting.complete(reply);
return;
}
// Every command this service sends carries a prefix, so an unmatched or
// prefixless reply answers something that already timed out (or another
// sender). Log it - never guess it onto a waiting command (#532's rule).
// The reply TEXT is withheld: a late reply to a secret command (e.g.
// `get wifi.pwd`) would otherwise write cleartext to the app log, which the
// screen's masking cannot undo (Gemini review, #883). The correlation token
// and byte length carry the debug value without the content.
appLogger.warn(
'CLI reply matched no pending command '
'(prefix: ${prefix ?? 'none'}, ${reply.payloadLength} bytes); '
'text withheld',
tag: 'LocalCli',
);
}
void _cleanup(String prefix) {
_timeouts.remove(prefix)?.cancel();
_pending.remove(prefix);
}
void dispose() {
_detach?.call();
_detach = null;
for (final t in _timeouts.values) {
t.cancel();
}
_timeouts.clear();
for (final c in _pending.values) {
if (!c.isCompleted) {
c.completeError(
const LocalCliTimeout(command: '(disposed)', timeout: Duration.zero),
);
}
}
_pending.clear();
}
}

@ -0,0 +1,106 @@
import 'package:flutter/foundation.dart';
import '../connector/meshcore_protocol.dart';
import '../models/region.dart';
/// Where a discovery run can land. Each non-success state is distinct so the UI
/// can render it as itself (an empty reply is not success; a timeout is not an
/// error). (#814)
enum RegionDiscoveryStatus { idle, loading, success, empty, timeout, error }
/// Sends one regions-discovery request to a repeater and returns the reply, or
/// null on timeout. In production this is [MeshCoreConnector.discoverRegions];
/// tests inject a fake so the lifecycle can be exercised without a radio.
typedef RegionsDiscoverer =
Future<RegionsReply?> Function(Uint8List repeaterPubKey, Duration timeout);
/// Drives Discover Regions: ask a chosen repeater which flood regions it
/// advertises, dedupe them, and expose a single discovery state for the UI.
class RegionDiscoveryService extends ChangeNotifier {
RegionDiscoveryService(this._discover);
final RegionsDiscoverer _discover;
RegionDiscoveryStatus _status = RegionDiscoveryStatus.idle;
List<Region> _regions = const [];
int? _clock;
String? _errorMessage;
bool _disposed = false;
RegionDiscoveryStatus get status => _status;
List<Region> get regions => _regions;
/// The repeater's clock from the last successful reply (for clock display).
int? get clock => _clock;
/// A human-readable reason when [status] is [RegionDiscoveryStatus.error].
String? get errorMessage => _errorMessage;
bool get isLoading => _status == RegionDiscoveryStatus.loading;
/// Discover regions from [repeaterPubKey] (a 32-byte node key). Concurrent
/// starts are ignored while one is in flight.
Future<void> discover(
Uint8List repeaterPubKey, {
Duration timeout = const Duration(seconds: 10),
}) async {
if (_status == RegionDiscoveryStatus.loading) return;
_status = RegionDiscoveryStatus.loading;
_regions = const [];
_errorMessage = null;
_safeNotify();
try {
final reply = await _discover(repeaterPubKey, timeout);
if (reply == null) {
_status = RegionDiscoveryStatus.timeout;
} else {
_clock = reply.clock;
final regions = _dedupe(reply.regionNames);
if (regions.isEmpty) {
_status = RegionDiscoveryStatus.empty;
} else {
_regions = regions;
_status = RegionDiscoveryStatus.success;
}
}
} catch (e) {
_status = RegionDiscoveryStatus.error;
_errorMessage = e.toString();
}
// The screen may have been popped (and this service disposed) while the
// discovery future was in flight; notifying a disposed ChangeNotifier
// throws, so guard it.
_safeNotify();
}
/// Return to the idle state, clearing any prior result.
void reset() {
_status = RegionDiscoveryStatus.idle;
_regions = const [];
_clock = null;
_errorMessage = null;
_safeNotify();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
void _safeNotify() {
if (!_disposed) notifyListeners();
}
/// Dedupe by [Region] value-equality, preserving first-seen order.
List<Region> _dedupe(List<String> names) {
final seen = <Region>{};
final out = <Region>[];
for (final name in names) {
final region = Region(name);
if (seen.add(region)) out.add(region);
}
return out;
}
}

@ -5,6 +5,7 @@ import '../models/path_selection.dart';
import '../connector/meshcore_connector.dart';
import '../connector/meshcore_protocol.dart';
import '../utils/app_logger.dart';
import 'command_correlation.dart';
/// A repeater reply that arrived with no command waiting to receive it.
///
@ -69,7 +70,7 @@ class RepeaterCommandService {
final Map<String, String> _commandPrefixes = {};
final Map<String, String> _pendingByPrefix = {};
final Map<String, _ExpiredCommand> _expiredCommands = {};
int _prefixCounter = 0;
final PrefixAllocator _prefixes = PrefixAllocator();
static const int maxRetries = 5;
@ -89,10 +90,20 @@ class RepeaterCommandService {
/// them in front of users (#589).
void Function(UnmatchedRepeaterResponse)? onUnmatchedResponse;
/// When set, the late/unmatched log withholds the reply text and the command
/// string, logging only lengths. The remote CLI console sets this so a
/// slow `get wifi.pwd` reply never writes the password to the app log, the
/// same guarantee [LocalCliService] gives (#999 review). Default false keeps
/// the repeater path's existing diagnostics.
bool redactUnmatchedReplyText = false;
RepeaterCommandService(this._connector);
/// Send a CLI command to a repeater with automatic retries
/// Returns a future that completes when a response is received or after max retries
/// Send a CLI command to a contact (a repeater/room server OR a companion)
/// with automatic retries. Returns a future that completes when a response is
/// received or after max retries. The message type is chosen by the target's
/// role (#888/#889): a companion gets TXT_TYPE_CLI_COMMAND, a repeater/room
/// server the universal CLI_DATA; the reply path is identical for both.
Future<String> sendCommand(
Contact repeater,
String command, {
@ -158,6 +169,9 @@ class RepeaterCommandService {
framedCommand,
attempt: attempt,
timestampSeconds: timestampSeconds,
// The target split: companions take the 1.18 command type, repeaters and
// room servers the universal CLI_DATA type (#888/#889).
txtType: cliTxtTypeForContactType(repeater.type),
);
final responseBytes = frame.length > maxFrameSize
? frame.length
@ -208,12 +222,10 @@ class RepeaterCommandService {
final repeaterKey = repeater.publicKeyHex;
_pruneExpiredCommands();
String? prefix;
String responsePayload = responseText;
if (responseText.length >= 3 && responseText[2] == '|') {
prefix = responseText.substring(0, 3);
responsePayload = responseText.substring(3).trimLeft();
}
// Shared `cc|` grammar (#882): same splitter the local frame-66 path uses.
final correlated = splitCorrelated(responseText);
final prefix = correlated.prefix;
final responsePayload = correlated.payload;
// A reply that carries a prefix is self-identifying. If that prefix matches
// nothing pending, the answer belongs to a command that already completed
@ -250,16 +262,25 @@ class RepeaterCommandService {
: DateTime.now().difference(expired.expiredAt);
if (expired != null) {
final commandText = redactUnmatchedReplyText
? '(withheld)'
: '"${expired.command}"';
final payloadText = redactUnmatchedReplyText
? '${responsePayload.length} chars, text withheld'
: responsePayload;
appLogger.warn(
'Late reply to "${expired.command}" from $repeaterKey arrived '
'Late reply to $commandText from $repeaterKey arrived '
'${sinceTimeout!.inMilliseconds}ms after its window closed: '
'$responsePayload',
'$payloadText',
tag: 'RepeaterCommand',
);
} else {
final payloadText = redactUnmatchedReplyText
? '${responsePayload.length} chars, text withheld'
: responsePayload;
appLogger.warn(
'Reply from $repeaterKey matched no pending or recently expired '
'command (prefix: ${prefix ?? 'none'}): $responsePayload',
'command (prefix: ${prefix ?? 'none'}): $payloadText',
tag: 'RepeaterCommand',
);
}
@ -352,14 +373,5 @@ class RepeaterCommandService {
onUnmatchedResponse = null;
}
String _nextPrefixToken() {
for (var i = 0; i < 256; i++) {
final value = _prefixCounter++ & 0xFF;
final token = '${value.toRadixString(16).padLeft(2, '0').toUpperCase()}|';
if (!_pendingByPrefix.containsKey(token)) {
return token;
}
}
return '00|';
}
String _nextPrefixToken() => _prefixes.next(_pendingByPrefix.keys.toSet());
}

@ -0,0 +1,344 @@
import '../storage/channel_message_store.dart';
import '../storage/drift/blob_store.dart';
import '../storage/message_store.dart';
import '../utils/app_logger.dart';
/// How long a migrated key keeps its stale blob before the sweep reclaims it.
///
/// Owner decision, 2026-10-22: 30 days. One full month of real use, matching
/// the monthly granularity of the Play install and crash reports he reads, so
/// a migration problem has a reporting cycle to surface in before the snapshot
/// goes. A named constant so changing it is one edit and tests can pass their
/// own window instead of manipulating clocks.
const Duration staleHistoryWindow = Duration(days: 30);
/// What a sweep did. Byte counts come from SQLite, not from adding up blob
/// lengths, so they are what actually changed rather than what should have.
class StaleHistoryOutcome {
const StaleHistoryOutcome({
required this.cleared,
required this.refused,
required this.bytesBefore,
required this.bytesAfter,
});
/// Keys whose stale blob was verified redundant and deleted.
final List<String> cleared;
/// Keys that were eligible by age but **kept**, because the blob could not
/// be verified against the rows. Surfaced to the user by the manual action
/// (#966); the automatic sweep logs them.
final List<String> refused;
final int bytesBefore;
final int bytesAfter;
int get bytesReclaimed => bytesBefore - bytesAfter;
bool get didAnything => cleared.isNotEmpty;
}
/// What a sweep WOULD do, for the confirmation dialog (#962).
class StaleHistoryPreview {
const StaleHistoryPreview({
required this.eligible,
required this.refused,
required this.approximateBytes,
required this.messagesKept,
});
/// Keys whose stale copy is verified redundant and would be deleted.
final List<String> eligible;
/// Keys already known to be unverifiable, so they would be kept. Saying so
/// before the press beats reporting it afterwards.
final List<String> refused;
/// Blob bytes that would go.
///
/// **Approximate on purpose.** It is the sum of the blob lengths, which is
/// not the same as what `VACUUM` returns to the filesystem: page rounding
/// and existing free pages both move the real figure. The dialog says
/// "about", and the result afterwards reports what actually changed.
final int approximateBytes;
/// Total stored messages, so the dialog can say what is NOT affected. The
/// reassurance is the point: this action deletes, and the user needs to know
/// their history is not what is being deleted.
final int messagesKept;
bool get hasWork => eligible.isNotEmpty;
}
/// Deletes the frozen pre-migration blob of a key that has been on rows long
/// enough, and returns the space to the filesystem (#962).
///
/// The blob a migrated key leaves behind is a snapshot taken at the migration
/// moment, not a mirror: nothing writes it afterwards. So it protects the
/// pre-migration history against a migration or read-path bug found later, and
/// protects nothing that arrived since, which is single-copy from the instant
/// it lands either way. After [staleHistoryWindow] that protection has had its
/// chance and the duplicate is just cost.
///
/// Every delete is gated on asking the rows again, immediately, rather than
/// trusting the marker. A key that cannot be verified keeps its blob and says
/// so, and is never retried in a loop: a refusal that silently repeats forever
/// is what made #952 invisible for days.
class StaleHistorySweep {
StaleHistorySweep(this._blobs);
final BlobStore _blobs;
/// Only these two key shapes have a row equivalent. `contacts`,
/// `discovered_contacts` and `path_history_` live in blobs as their ONLY
/// storage, so they are never candidates, and this is asserted by name in
/// the tests rather than left to the marker to get right.
static const List<String> _historyPrefixes = [
'channel_messages_',
'messages_',
];
static bool isHistoryKey(String key) => _historyPrefixes.any(key.startsWith);
/// The converter for a key, chosen by its shape. Channel and direct
/// histories encode differently, and using the wrong one would make every
/// record look missing, which refuses rather than deletes.
static BlobToRowsCallback converterFor(String key) =>
key.startsWith('channel_messages_')
? channelHistoryToRows
: dmHistoryToRows;
/// Whether a key is old enough to reclaim. The ONE age rule, shared by
/// [preview] and [run], so the dialog cannot promise what the sweep will not
/// do.
///
/// A key with no timestamp, or one stamped during this pass, has no age to
/// judge. For the automatic sweep that means **not eligible**: the stamp
/// exists so installing an update never deletes a blob on sight. For an
/// explicit press it means **eligible**, because a user asking to clear now
/// is not an app update. Treating the two the same made the button report
/// "nothing to clear" on any install that migrated before #962, which is
/// every real install, since none of their keys carry a stamp yet.
static bool eligibleByAge({
required DateTime? migratedAt,
required bool freshlyStamped,
required Duration window,
required DateTime at,
required bool includeNewlyStamped,
}) {
if (freshlyStamped || migratedAt == null) return includeNewlyStamped;
return at.difference(migratedAt) >= window;
}
/// What a sweep would do, without doing any of it (#962).
///
/// The confirmation dialog states real numbers rather than an estimate, so
/// the verification has to run before the delete rather than as part of it.
/// The cost is that it happens twice for a confirmed clear: once here, once
/// under the key lock in [run]. That is the price of saying what will go
/// before it goes.
///
/// Writes nothing. In particular it does not stamp, so calling it never
/// changes what a later [run] does.
Future<StaleHistoryPreview> preview({
Duration? olderThan,
DateTime? now,
bool includeNewlyStamped = false,
}) async {
final window = olderThan ?? staleHistoryWindow;
final at = now ?? DateTime.now();
final eligible = <String>[];
final refused = <String>[];
var bytes = 0;
for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) {
if (!isHistoryKey(key)) continue;
if (!await _blobs.isOnMessageRows(key)) continue;
if (!eligibleByAge(
migratedAt: await _blobs.messageRowsMigratedAt(key),
freshlyStamped: false,
window: window,
at: at,
includeNewlyStamped: includeNewlyStamped,
)) {
continue;
}
final blob = await _blobs.read(key);
if (blob == null) continue; // already reclaimed
final missing = await _blobs.missingFromRows(key, converterFor(key));
if (missing == null || missing.isNotEmpty) {
refused.add(key);
continue;
}
eligible.add(key);
bytes += blob.length;
}
return StaleHistoryPreview(
eligible: eligible,
refused: refused,
approximateBytes: bytes,
messagesKept: await _blobs.totalMessageRows(),
);
}
/// Runs one sweep.
///
/// [olderThan] defaults to [staleHistoryWindow]; [now] exists so tests can
/// choose a moment rather than wait. Backfills a timestamp onto any
/// already-migrated key that has none. [includeNewlyStamped] decides whether
/// such a key can be cleared on the same pass: false for the automatic
/// sweep, true for an explicit press. See [eligibleByAge].
Future<StaleHistoryOutcome> run({
Duration? olderThan,
DateTime? now,
bool includeNewlyStamped = false,
}) async {
final window = olderThan ?? staleHistoryWindow;
final at = now ?? DateTime.now();
final bytesBefore = await _blobs.databaseSizeBytes();
// Stamp first. A key seen for the first time gets the full window from
// now, so updating the app never deletes a blob on the spot.
final stamped = await _blobs.backfillMigratedAt(now: at);
final cleared = <String>[];
final refused = <String>[];
for (final key in (await _blobs.messageStoreKeys()).toList()..sort()) {
if (!isHistoryKey(key)) continue;
if (!await _blobs.isOnMessageRows(key)) continue;
if (!eligibleByAge(
migratedAt: await _blobs.messageRowsMigratedAt(key),
freshlyStamped: stamped.contains(key),
window: window,
at: at,
includeNewlyStamped: includeNewlyStamped,
)) {
continue;
}
// Verify and delete under the key's own lock, as one step. Deciding on
// one call and deleting on another leaves a window, and a delete made on
// a stale answer cannot be taken back.
final result = await _blobs.reclaimVerifiedHistoryBlob(
key,
converterFor(key),
);
if (result.deleted) {
cleared.add(key);
continue;
}
final missing = result.missing;
if (missing == null) {
// Unverifiable, NOT verified-empty. Keep it.
refused.add(key);
continue;
}
if (missing.isNotEmpty) {
appLogger.error(
'Keeping the stale blob for $key: ${missing.length} of its records '
'have no row (e.g. ${missing.take(3).join(', ')}). The blob stays '
'the only copy of those and is not deleted.',
tag: 'Storage',
);
refused.add(key);
}
// Otherwise there was no blob left to reclaim: not cleared, not refused.
}
if (cleared.isNotEmpty) {
// VACUUM takes an exclusive lock and rebuilds the file, so database
// access queues behind it. It does NOT block the UI thread: drift_flutter
// runs SQLite in a spawned isolate (`_isolateEntrypoint` ->
// `DriftIsolate.inCurrent`), so this is a stall on history-backed reads
// rather than an ANR, which is the distinction that matters for an app
// whose storage work started as an ANR investigation.
//
// It is also close to once per install: a key is cleared once and then
// has no blob to consider, so later launches delete nothing and never
// reach here. Measured at 0.6 s on the owner's 70.9 MiB database. The
// duration is logged because that is a number worth watching in the
// field rather than assuming.
final sw = Stopwatch()..start();
try {
await _blobs.vacuum();
appLogger.info(
'VACUUM took ${sw.elapsedMilliseconds} ms after clearing '
'${cleared.length} stale blob(s).',
tag: 'Storage',
);
} catch (e) {
// The deletes already happened and were each verified; VACUUM only
// affects file size, so a failure here costs space and not data. The
// next sweep retries it.
appLogger.warn(
'Deleted ${cleared.length} stale blob(s) but VACUUM failed, so the '
'space is free for reuse and not yet returned to the filesystem: '
'$e',
tag: 'Storage',
);
}
}
// A sweep that deleted blobs correctly must not be reported as a failure
// because the closing size read threw. The deletes are the work; the byte
// count is reporting. Falling back to `bytesBefore` makes the reclaimed
// figure read as 0, which understates rather than invents, and keeps the
// manual action from telling the user nothing happened when something did
// (Gemini review).
int bytesAfter;
try {
bytesAfter = await _blobs.databaseSizeBytes();
} catch (e) {
appLogger.warn(
'Cleared ${cleared.length} stale blob(s) but could not read the '
'database size afterwards, so the reclaimed figure reads as 0: $e',
tag: 'Storage',
);
bytesAfter = bytesBefore;
}
if (cleared.isNotEmpty || refused.isNotEmpty) {
// Names the keys, not just a count. "Cleared 40" is not an audit trail
// for a delete that cannot be undone.
appLogger.info(
'Stale history sweep: cleared ${cleared.length}, kept '
'${refused.length} that could not be verified, '
'${bytesBefore - bytesAfter} bytes returned.\n'
'cleared: ${cleared.join(', ')}'
'${refused.isEmpty ? '' : '\nkept: ${refused.join(', ')}'}',
tag: 'Storage',
);
// And durably, because the log above is gated on the app-debug-logging
// setting, which is off by default. Without this an irreversible delete
// would leave no trail at all on a normal install.
try {
await _blobs.appendReclaimAudit(
at: at,
cleared: cleared,
refused: refused,
bytesBefore: bytesBefore,
bytesAfter: bytesAfter,
);
} catch (e) {
appLogger.warn(
'Could not write the reclaim audit entry: $e',
tag: 'Storage',
);
}
}
return StaleHistoryOutcome(
cleared: cleared,
refused: refused,
bytesBefore: bytesBefore,
bytesAfter: bytesAfter,
);
}
}

@ -230,7 +230,11 @@ StockChannel toStockChannel(Channel channel) =>
StockContact toStockContact(Contact contact) {
return StockContact(
type: contact.type,
name: contact.name,
// receivedName, never `.name`. A stock config file is an interchange
// format other operators import, where a name reads as what the node
// calls itself. Exporting one user's private label would hand it to
// everyone who loads the file. (#750, T33)
name: contact.receivedName,
publicKey: contact.publicKey,
flags: contact.flags,
latitude: contact.latitude ?? 0,

@ -308,6 +308,10 @@ class StockConfigImportService {
hashWidth: path == null || path.hashWidth == 0 ? 1 : path.hashWidth,
type: contact.type,
flags: contact.flags,
// `contact` here is a StockContact parsed from an imported stock
// config file, not our Contact. It has no custom-name concept, and
// its name is what the file says the node calls itself, so this is
// already a received name. Allowlisted in the T14 guard. (#750)
name: contact.name,
lat: contact.latitude,
lon: contact.longitude,

@ -1,11 +1,12 @@
import 'dart:convert';
import '../models/delivery_observation.dart';
import '../models/path_history.dart';
import '../storage/drift/blob_store.dart';
import '../storage/prefs_manager.dart';
import '../utils/app_logger.dart';
class StorageService {
static const String _pathHistoryPrefix = 'path_history_';
static const String _pendingMessagesKey = 'pending_messages';
static const String _repeaterPasswordsKey = 'repeater_passwords';
static const String _repeaterAutoClockSyncAfterLoginKey =
'repeater_auto_clock_sync_after_login';
@ -43,72 +44,127 @@ class StorageService {
await prefs.setString(_repeaterAutoClockSyncAfterLoginKey, jsonStr);
}
/// First 10 hex of the connected radio's public key, like every per-radio
/// store. Set on connect.
///
/// Path history is what THIS radio learned about reaching a contact. Keyed
/// by contact alone (the pre-#854 scheme) a route measured by a 1 W handheld
/// was applied to a repeater, and the reverse.
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String _pathKey(String contactPubKeyHex) =>
'$_pathHistoryPrefix$publicKeyHex$contactPubKeyHex';
/// Per-radio, and in drift rather than SharedPreferences (#854, #924).
///
/// Two changes in one migration, because doing them separately would mean
/// two migrations over the same data. Prefs is a settings store: on Windows
/// every write re-encodes and rewrites the whole file, and this one store
/// held 2,092 keys and 86% of a 4.28 MB file, which made every unrelated
/// settings write cost ~32 ms (#923).
///
/// With no radio key set this loads nothing and never writes, so it cannot
/// read or clobber anything. That is the #754 precedent.
Future<void> savePathHistory(
String contactPubKeyHex,
ContactPathHistory history,
) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final jsonStr = jsonEncode(history.toJson());
await prefs.setString(key, jsonStr);
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.write(
_pathKey(contactPubKeyHex),
jsonEncode(history.toJson()),
);
}
Future<ContactPathHistory?> loadPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
final jsonStr = prefs.getString(key);
if (jsonStr == null) return null;
if (publicKeyHex.isEmpty) return null;
final jsonStr = await BlobStore.instance.read(_pathKey(contactPubKeyHex));
if (jsonStr == null || jsonStr.isEmpty) return null;
try {
final json = jsonDecode(jsonStr) as Map<String, dynamic>;
return ContactPathHistory.fromJson(contactPubKeyHex, json);
} catch (e) {
appLogger.error(
'Failed to decode path history for $contactPubKeyHex: $e',
tag: 'Storage',
);
return null;
}
}
Future<void> clearPathHistory(String contactPubKeyHex) async {
final prefs = PrefsManager.instance;
final key = '$_pathHistoryPrefix$contactPubKeyHex';
await prefs.remove(key);
if (publicKeyHex.isEmpty) return;
await BlobStore.instance.delete(_pathKey(contactPubKeyHex));
}
/// Clears this radio's path history only. Another radio's routes are not
/// touched, which they were before #854 because the key had no radio in it.
Future<void> clearAllPathHistories() async {
final prefs = PrefsManager.instance;
final keys = prefs.getKeys();
final pathHistoryKeys = keys.where(
(key) => key.startsWith(_pathHistoryPrefix),
);
for (final key in pathHistoryKeys) {
await prefs.remove(key);
if (publicKeyHex.isEmpty) return;
final mine = '$_pathHistoryPrefix$publicKeyHex';
for (final key in await BlobStore.instance.keysWithPrefix(mine)) {
await BlobStore.instance.delete(key);
}
}
Future<Map<String, String>> loadPendingMessages() async {
/// Removes the pre-#854 untagged `path_history_<contact>` keys from
/// SharedPreferences, a chunk at a time, yielding between chunks.
///
/// These cannot be migrated: the key records which CONTACT a route reaches
/// and never which radio measured it, so attributing them to a radio would
/// be a guess. The owner's decision (plan §9, decision 1) is to delete them
/// rather than orphan them, because routes relearn in normal use and here
/// the orphaned data is itself the performance problem.
///
/// Chunked because each `remove` re-encodes and rewrites the whole prefs
/// file. Measured against the owner's real file: 2,092 keys, **12.7 s of
/// total work**, mean 6.1 ms, but 32 ms for the first removal and under
/// 1 ms by the last, because the file collapses from 4.28 MB to 45 KB as it
/// goes. One unbroken pass would block for 12.7 s, well past the 5 s
/// watchdog, which is the very failure #917 just fixed. [chunkSize] keeps
/// any single block near 20 removals' worth and the yield lets the UI
/// breathe between them.
///
/// Returns how many keys it removed. Safe to call repeatedly: when there is
/// nothing left it does no writes at all.
Future<int> purgeLegacyPathHistory({int chunkSize = 20}) async {
final prefs = PrefsManager.instance;
final jsonStr = prefs.getString(_pendingMessagesKey);
// A legacy key is one in PREFS. The new scheme writes to drift, so the
// two backends cannot be confused and no length or shape heuristic is
// needed to tell them apart.
final legacy = prefs
.getKeys()
.where((k) => k.startsWith(_pathHistoryPrefix))
.toList();
if (legacy.isEmpty) return 0;
if (jsonStr == null) return {};
appLogger.info(
'Purging ${legacy.length} pre-#854 untagged path_history keys from '
'prefs, $chunkSize at a time. These record which contact a route '
'reaches and never which radio measured it, so they cannot be '
'attributed; routes relearn in normal use (#854, plan decision 1).',
tag: 'Storage',
);
try {
final json = jsonDecode(jsonStr) as Map<String, dynamic>;
return json.map((key, value) => MapEntry(key, value as String));
} catch (e) {
return {};
var removed = 0;
for (var i = 0; i < legacy.length; i++) {
await prefs.remove(legacy[i]);
removed++;
if ((i + 1) % chunkSize == 0) {
// Let the UI isolate run. Without this the whole purge is one block.
await Future<void>.delayed(Duration.zero);
}
}
}
Future<void> savePendingMessages(Map<String, String> pending) async {
final prefs = PrefsManager.instance;
final jsonStr = jsonEncode(pending);
await prefs.setString(_pendingMessagesKey, jsonStr);
}
Future<void> clearPendingMessages() async {
final prefs = PrefsManager.instance;
await prefs.remove(_pendingMessagesKey);
appLogger.info(
'Purged $removed legacy path_history keys. Every remaining prefs write '
'is now cheaper in proportion (#923).',
tag: 'Storage',
);
return removed;
}
/// Save a repeater password by public key hex
@ -159,17 +215,32 @@ class StorageService {
await prefs.remove(_repeaterPasswordsKey);
}
String get _observationsKey => '$_deliveryObservationsKey$publicKeyHex';
/// Per-radio (#856).
///
/// These feed the ACK-timeout prediction model. On one global key, a
/// repeater's 45-second deliveries trained the model a 1 W handheld then
/// used, and the reverse. Silent accuracy loss rather than a visible
/// failure, which is why nobody reported it.
///
/// Stays in SharedPreferences, unlike path history: this is one small key
/// (3,091 bytes and 14 entries on the owner's install), not 2,092 keys and
/// 86% of the file, so there is no cost argument for moving it and a move
/// would be churn.
Future<void> saveDeliveryObservations(
List<DeliveryObservation> observations,
) async {
if (publicKeyHex.isEmpty) return;
final prefs = PrefsManager.instance;
final jsonStr = jsonEncode(observations.map((o) => o.toJson()).toList());
await prefs.setString(_deliveryObservationsKey, jsonStr);
await prefs.setString(_observationsKey, jsonStr);
}
Future<List<DeliveryObservation>> loadDeliveryObservations() async {
if (publicKeyHex.isEmpty) return [];
final prefs = PrefsManager.instance;
final jsonStr = prefs.getString(_deliveryObservationsKey);
final jsonStr = prefs.getString(_observationsKey);
if (jsonStr == null) return [];
@ -179,12 +250,37 @@ class StorageService {
.map((e) => DeliveryObservation.fromJson(e as Map<String, dynamic>))
.toList();
} catch (e) {
appLogger.error(
'Failed to decode delivery observations: $e',
tag: 'Storage',
);
return [];
}
}
Future<void> clearDeliveryObservations() async {
if (publicKeyHex.isEmpty) return;
await PrefsManager.instance.remove(_observationsKey);
}
/// Removes the pre-#856 untagged global observation list.
///
/// One key, so no chunking is needed. Deleted rather than attributed to a
/// radio (plan §9, decision 1): it is a mixture of every radio's RF timing,
/// and mixed data is worse than no data for the model, which retrains from
/// live sends within normal use.
///
/// Returns true if there was one to remove.
Future<bool> purgeLegacyDeliveryObservations() async {
final prefs = PrefsManager.instance;
if (!prefs.containsKey(_deliveryObservationsKey)) return false;
await prefs.remove(_deliveryObservationsKey);
appLogger.info(
'Purged the pre-#856 global delivery-observation list. It mixed every '
'radio\'s RF timing, so it is deleted rather than attributed; the '
'model retrains per radio from live sends (#856).',
tag: 'Storage',
);
return true;
}
}

@ -1,5 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:meshcore_open/utils/app_logger.dart';
import '../models/channel_message.dart';
@ -8,6 +8,98 @@ import '../helpers/reaction_helper.dart';
import '../helpers/smaz.dart';
import 'drift/blob_store.dart';
/// Merges `incomingJson` into the stored channel history, off the UI isolate.
///
/// Top-level because `compute` sends it to another isolate; a closure capturing
/// the store would not be sendable. Visible (not `_`-private) only so the test
/// can call it directly and assert the merge semantics without an isolate.
///
/// Semantics are deliberately identical to the inline merge this replaced:
/// upsert by [ChannelMessageStore._mergeKey], the incoming copy wins so edits,
/// reactions and status updates are captured, and the result is sorted by
/// timestamp. Deletion has its own path, so this never resurrects a deleted
/// message.
///
/// **Throws** when the stored JSON will not decode, rather than merging into an
/// empty base. [BlobStore.mergeOffThread] logs and declines to write, so a
/// blob that cannot be read is never replaced by a truncated one (#334's
/// original inline behaviour, preserved).
String mergeChannelHistoryJson((String?, String) input) {
final (stored, incomingJson) = input;
final byKey = <String, ChannelMessage>{};
if (stored != null && stored.isNotEmpty) {
// No try/catch: a decode failure must propagate so the caller refuses the
// write. Swallowing it here would silently truncate the history.
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = ChannelMessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[ChannelMessageStore._mergeKey(m)] = m;
}
}
for (final e in jsonDecode(incomingJson) as List<dynamic>) {
final m = ChannelMessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[ChannelMessageStore._mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
return jsonEncode(merged.map(ChannelMessageStore._messageToJson).toList());
}
/// Drops the record whose merge key is `target` from a channel history blob.
///
/// `input` is `(storedJson, targetMergeKey)`. Top-level and static-only so
/// `compute` can send it (#919). Returns null, so nothing is written, when
/// there is no history or the target is not in it: re-encoding 5 MB to change
/// nothing is exactly the cost this Epic exists to stop paying.
///
/// Throws on undecodable stored JSON, which `mergeOffThread` turns into a
/// refused write. That matches the inline code it replaces, which logged and
/// left the blob alone.
String? dropFromChannelHistoryJson((String?, String) input) {
final (stored, target) = input;
if (stored == null || stored.isEmpty) return null;
final kept = <ChannelMessage>[];
var removed = false;
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = ChannelMessageStore._messageFromJson(e as Map<String, dynamic>);
if (ChannelMessageStore._mergeKey(m) == target) {
removed = true;
} else {
kept.add(m);
}
}
if (!removed) return null;
return jsonEncode(kept.map(ChannelMessageStore._messageToJson).toList());
}
/// Converts a whole channel-history blob into one row per message (#920).
///
/// Top-level so `compute` can send it. Returns exactly one row per element of
/// the source array, with no dedupe and no sorting: the migration's gate
/// compares this count against an independent count of the blob, and does its
/// own deduping, so doing either here would defeat the check.
///
/// Throws on undecodable JSON, which the migration turns into a refusal that
/// leaves the blob as the source of truth.
List<MessageRowInput> channelHistoryToRows(String blobJson) {
return (jsonDecode(blobJson) as List<dynamic>).map((e) {
final map = e as Map<String, dynamic>;
final m = ChannelMessageStore._messageFromJson(map);
return MessageRowInput(
mergeKey: ChannelMessageStore._mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
// The source map, re-encoded, NOT a re-serialisation of the decoded
// object. A round trip through the model would quietly rewrite any field
// the model defaults, and this is a move, not a rewrite.
payload: jsonEncode(map),
);
}).toList();
}
class ChannelMessageStore {
static const String _keyPrefix = 'channel_messages_';
@ -75,39 +167,45 @@ class ChannelMessageStore {
// resurrects a message the user deleted.
final key = _storageKey(channelIndex);
final blobs = BlobStore.instance;
// Serialise the whole read-modify-write against other saves/deletes on this
// key so two concurrent saves cannot clobber each other (Gemini review).
await blobs.synchronized(key, () async {
final byKey = <String, ChannelMessage>{};
final existing = await blobs.readWithPrefsFallback(key);
if (existing != null && existing.isNotEmpty) {
try {
for (final e in jsonDecode(existing) as List<dynamic>) {
final m = _messageFromJson(e as Map<String, dynamic>);
byKey[_mergeKey(m)] = m;
}
} catch (e) {
// SAFELANE 6: never merge into an empty base and truncate silently.
appLogger.error(
'Failed to decode existing channel $channelIndex history before '
'merge; aborting save to avoid truncation: $e',
tag: 'Storage',
);
return;
}
}
for (final m in messages) {
byKey[_mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
await blobs.write(key, jsonEncode(merged.map(_messageToJson).toList()));
});
// Rows (#920): one upsert per message in the list, which costs the same
// whether 50 or 50,000 messages are already stored. #919 moved the
// whole-history re-encode to another isolate; this removes it. The cost is
// proportional to the in-memory window being saved, never to the history.
if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) {
await blobs.upsertMessageRows(key, messages.map(_toRow));
return;
}
// Blob fallback, for a key whose migration was refused. Still correct,
// still off the UI isolate (#919): only the INCOMING messages are encoded
// here, and decoding the stored history, merging and re-encoding it runs on
// another isolate. `mergeOffThread` keeps the per-key serialisation that
// stops two saves clobbering each other, and fails closed: if the stored
// JSON will not decode, the key is not written.
final incoming = jsonEncode(messages.map(_messageToJson).toList());
await blobs.mergeOffThread(key, incoming, mergeChannelHistoryJson);
}
static MessageRowInput _toRow(ChannelMessage m) => MessageRowInput(
mergeKey: _mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
payload: jsonEncode(_messageToJson(m)),
);
/// The store's own history encoding, for tests that need a blob fixture.
///
/// Exists so a test never hand-writes one: a hand-rolled fixture rots the
/// moment a non-null field joins the schema, which is exactly how the #919
/// tests first failed. Saving through [saveChannelMessages] cannot serve that
/// purpose any more, because saves write rows now.
@visibleForTesting
static String encodeHistoryForTest(List<ChannelMessage> messages) =>
jsonEncode(messages.map(_messageToJson).toList());
/// Stable identity for merge/dedupe. messageId when present, else a composite
/// that distinguishes distinct messages that share no id.
String _mergeKey(ChannelMessage m) {
static String _mergeKey(ChannelMessage m) {
if (m.messageId.isNotEmpty) return 'id:${m.messageId}';
// Include the sender: two different senders can post identical text at the
// same timestamp without a messageId, and would otherwise collide and lose
@ -122,6 +220,11 @@ class ChannelMessageStore {
/// Removes a single message from the persisted history. The explicit delete
/// path (#343): save merges and never removes, so deletion cannot go through
/// save.
///
/// On rows this is a single-row DELETE (#920). On the blob fallback the
/// decode and re-encode run off the UI isolate (#919), because a delete
/// rewrites the whole blob and so blocked the UI for as long as a save did,
/// right when the user had just tapped something.
Future<void> removeChannelMessage(
int channelIndex,
ChannelMessage message,
@ -129,26 +232,15 @@ class ChannelMessageStore {
if (publicKeyHex.isEmpty) return;
final key = _storageKey(channelIndex);
final blobs = BlobStore.instance;
await blobs.synchronized(key, () async {
final existing = await blobs.readWithPrefsFallback(key);
if (existing == null || existing.isEmpty) return;
final List<dynamic> raw;
try {
raw = jsonDecode(existing) as List<dynamic>;
} catch (e) {
appLogger.error(
'Failed to decode channel $channelIndex history for delete: $e',
tag: 'Storage',
);
return;
}
final target = _mergeKey(message);
final kept = raw
.map((e) => _messageFromJson(e as Map<String, dynamic>))
.where((m) => _mergeKey(m) != target)
.toList();
await blobs.write(key, jsonEncode(kept.map(_messageToJson).toList()));
});
if (await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows)) {
await blobs.deleteMessageRow(key, _mergeKey(message));
return;
}
await blobs.mergeOffThread(
key,
_mergeKey(message),
dropFromChannelHistoryJson,
);
}
/// Load messages for a specific channel
@ -161,6 +253,19 @@ class ChannelMessageStore {
}
final blobs = BlobStore.instance;
final key = _storageKey(channelIndex);
// Rows (#920). The legacy-key adoption below works on blobs, so it has to
// run before this key can be considered settled: a key with no blob and no
// rows is migrated as "empty" and would then never adopt its slot-index
// history. So rows are only authoritative once they exist OR the blob is
// genuinely empty after adoption had its chance.
if (await blobs.isOnMessageRows(key)) {
final payloads = await blobs.messagePayloads(key);
if (payloads.isNotEmpty) {
return _decodePayloads(payloads, key);
}
}
// Bulk data lives in drift (#335); the fallback covers an unmigrated key
// and logs loudly if it fires.
String? jsonString = await blobs.readWithPrefsFallback(key);
@ -214,6 +319,12 @@ class ChannelMessageStore {
if (jsonString == null || jsonString.isEmpty) {
return [];
}
// The blob holds history that is not in rows yet, either because this key
// has never been migrated or because adoption above just brought legacy
// history in. Move it now so the next load and every save is on rows.
await blobs.ensureMessageRowsMigrated(key, channelHistoryToRows);
try {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
return jsonList.map((json) => _messageFromJson(json)).toList();
@ -223,14 +334,34 @@ class ChannelMessageStore {
}
}
List<ChannelMessage> _decodePayloads(List<String> payloads, String key) {
final out = <ChannelMessage>[];
for (final p in payloads) {
try {
out.add(_messageFromJson(jsonDecode(p) as Map<String, dynamic>));
} catch (e) {
// One unreadable row must not cost the whole channel. Unlike the blob,
// where a bad byte took every message with it, rows fail one at a time.
appLogger.error(
'Skipping an undecodable message row in $key: $e',
tag: 'Storage',
);
}
}
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.
Future<void> clearChannelMessages(int channelIndex) async {
final blobs = BlobStore.instance;
await blobs.deleteEverywhere(_storageKey(channelIndex));
await blobs.deleteEverywhere(_indexKey(channelIndex));
for (final key in {_storageKey(channelIndex), _indexKey(channelIndex)}) {
await blobs.deleteEverywhere(key);
// Rows as well, or a clear would leave the history readable (#920).
await blobs.deleteMessageRows(key);
}
}
/// Clear all channel messages
@ -238,11 +369,16 @@ class ChannelMessageStore {
final blobs = BlobStore.instance;
for (final key in await blobs.keysWithPrefix(keyFor)) {
await blobs.deleteEverywhere(key);
await blobs.deleteMessageRows(key);
}
// Row-only keys have no blob left to list, so clear by row key too.
for (final key in await blobs.messageStoreKeys()) {
if (key.startsWith(keyFor)) await blobs.deleteMessageRows(key);
}
}
/// Convert ChannelMessage to JSON map
Map<String, dynamic> _messageToJson(ChannelMessage msg) {
static Map<String, dynamic> _messageToJson(ChannelMessage msg) {
return {
'senderKey': msg.senderKey != null ? base64Encode(msg.senderKey!) : null,
'senderName': msg.senderName,
@ -273,7 +409,7 @@ class ChannelMessageStore {
}
/// Convert JSON map to ChannelMessage
ChannelMessage _messageFromJson(Map<String, dynamic> json) {
static ChannelMessage _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText;
return ChannelMessage(
@ -325,7 +461,7 @@ class ChannelMessageStore {
);
}
Map<String, dynamic> _repeatToJson(Repeat repeat) {
static Map<String, dynamic> _repeatToJson(Repeat repeat) {
return {
'repeaterKey': repeat.repeaterKey != null
? base64Encode(repeat.repeaterKey!)
@ -336,7 +472,7 @@ class ChannelMessageStore {
};
}
Repeat _repeatFromJson(Map<String, dynamic> json) {
static Repeat _repeatFromJson(Map<String, dynamic> json) {
return Repeat(
repeaterKey: json['repeaterKey'] != null
? Uint8List.fromList(base64Decode(json['repeaterKey']))

@ -0,0 +1,39 @@
import '../utils/app_logger.dart';
import 'prefs_manager.dart';
/// Per-channel region scope, persisted per device (Feature #812, Epic #815).
///
/// Stores the region name a channel's outgoing messages should ride, keyed by
/// the first 10 hex chars of the connected device's public key (the same
/// scoping the other channel stores use). The name is the `#`-stripped region
/// name from discovery; null/absent means the channel is unscoped.
class ChannelRegionScopeStore {
static const String _keyPrefix = 'channel_region_scope_';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String _key(int channelIndex) => '$_keyPrefix${publicKeyHex}_$channelIndex';
/// The region name scoping [channelIndex], or null when unscoped.
Future<String?> scopeFor(int channelIndex) async {
if (publicKeyHex.isEmpty) return null;
return PrefsManager.instance.getString(_key(channelIndex));
}
/// Scope [channelIndex] to [regionName].
Future<void> setScope(int channelIndex, String regionName) async {
if (publicKeyHex.isEmpty) {
appLogger.warn('No device key set; cannot save channel region scope.');
return;
}
await PrefsManager.instance.setString(_key(channelIndex), regionName);
}
/// Remove the region scope on [channelIndex] (back to unscoped).
Future<void> clearScope(int channelIndex) async {
if (publicKeyHex.isEmpty) return;
await PrefsManager.instance.remove(_key(channelIndex));
}
}

@ -8,10 +8,23 @@ import 'drift/blob_store.dart';
class ContactDiscoveryStore {
static const String _keyPrefix = 'discovered_contacts';
/// First 10 hex of the connected radio's key, like every other per-radio
/// store. Discovered contacts are what THIS radio heard, so they are scoped
/// per radio and never shared across radios on the same host (#754). The
/// legacy unscoped `discovered_contacts` blob is left orphaned; the list
/// self-heals as each radio re-hears adverts.
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String get _keyFor => '$_keyPrefix$publicKeyHex';
Future<List<Contact>> loadContacts() async {
// No connected radio -> no list (never the shared/legacy blob).
if (publicKeyHex.isEmpty) return [];
// Bulk data lives in drift (#335), not SharedPreferences. The fallback
// covers a key the migration has not moved yet and logs loudly if it fires.
final jsonStr = await BlobStore.instance.readWithPrefsFallback(_keyPrefix);
final jsonStr = await BlobStore.instance.readWithPrefsFallback(_keyFor);
if (jsonStr == null) return [];
try {
@ -30,14 +43,20 @@ class ContactDiscoveryStore {
}
Future<void> saveContacts(List<Contact> contacts) async {
// No connected radio -> don't write an unscoped/shared blob.
if (publicKeyHex.isEmpty) return;
final jsonList = contacts.map(_toJson).toList();
await BlobStore.instance.write(_keyPrefix, jsonEncode(jsonList));
await BlobStore.instance.write(_keyFor, jsonEncode(jsonList));
}
Map<String, dynamic> _toJson(Contact contact) {
return {
'publicKey': base64Encode(contact.publicKey),
'name': contact.name,
// The RECEIVED name, never `contact.name`. Same one-way data loss as
// `contact_store`: the getter would persist a user label into this key
// and the next load would read it back as what the node calls itself.
// (#750)
'name': contact.receivedName,
'type': contact.type,
'flags': contact.flags,
'pathLength': contact.pathLength,
@ -63,7 +82,8 @@ class ContactDiscoveryStore {
final lastModifiedMs = json['lastModified'] as int?;
return Contact(
publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)),
name: json['name'] as String? ?? 'Unknown',
// Fallback retained for the same reason as `contact_store`. (T31)
receivedName: json['name'] as String? ?? 'Unknown',
type: json['type'] as int? ?? 0,
flags: json['flags'] as int? ?? 0,
pathLength: json['pathLength'] as int? ?? -1,

@ -4,12 +4,56 @@ import 'prefs_manager.dart';
class ContactSettingsStore {
static const String _cyr2latKeyPrefix = 'contact_cyr2lat_';
/// Per-contact custom display name, the user's own label. (#750)
///
/// This lives here rather than in `contact_store` on purpose. That record is
/// rebuilt from the radio's contact-sync data, where no custom name exists,
/// so a save after a sync would wipe it. Keyed by pubkey hex here, a sync
/// cannot reach it.
static const String _customNameKeyPrefix = 'contact_customname_';
String publicKeyHex = '';
set setPublicKeyHex(String value) =>
publicKeyHex = value.length > 10 ? value.substring(0, 10) : '';
String get keyForCyr2Lat => '$_cyr2latKeyPrefix$publicKeyHex';
String get keyForCustomName => '$_customNameKeyPrefix$publicKeyHex';
/// The user's label for [contactKeyHex], or null when they have not set one.
Future<String?> loadCustomName(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot load contact custom name.',
);
return null;
}
final prefs = PrefsManager.instance;
return prefs.getString('$keyForCustomName$contactKeyHex');
}
/// Sets or clears the user's label for [contactKeyHex].
///
/// Null, empty and whitespace-only all **remove** the entry rather than
/// storing a blank. This is the second enforcement point for that rule, after
/// `Contact.name`: a UI that passes an empty string cannot leave a contact
/// with a blank display name and no way back. (T9d, T9e, T29, T30)
Future<void> saveCustomName(String contactKeyHex, String? name) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(
'Public key hex is not set. Cannot save contact custom name.',
);
return;
}
final prefs = PrefsManager.instance;
final key = '$keyForCustomName$contactKeyHex';
if (name == null || name.trim().isEmpty) {
await prefs.remove(key);
} else {
await prefs.setString(key, name);
}
}
Future<bool> loadCyr2LatEnabled(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn(

@ -104,7 +104,17 @@ class ContactStore {
Map<String, dynamic> _toJson(Contact contact) {
return {
'publicKey': base64Encode(contact.publicKey),
'name': contact.name,
// The RECEIVED name, never `contact.name`. Reading the getter here would
// write the user's custom name into this key, and the next load would
// read it back as the received name. The real name the node gave us
// would be destroyed permanently, with no advert able to restore it,
// because the contact would already appear to have that name. (#750)
//
// `customName` is deliberately NOT stored here. This record is rebuilt
// from radio contact-sync data, where no custom name exists, so a save
// after a sync would wipe it. It lives in `contact_settings_store`,
// keyed by pubkey hex, which a sync cannot reach.
'name': contact.receivedName,
'type': contact.type,
'flags': contact.flags,
'pathLength': contact.pathLength,
@ -142,7 +152,10 @@ class ContactStore {
}
return Contact(
publicKey: Uint8List.fromList(base64Decode(json['publicKey'] as String)),
name: json['name'] as String? ?? 'Unknown',
// Keep the `?? 'Unknown'`: a legacy row can carry a null or missing name,
// and `receivedName` is non-nullable, so dropping this fallback during
// the rename would crash the load for anyone holding such a row. (T31)
receivedName: json['name'] as String? ?? 'Unknown',
type: json['type'] as int? ?? 0,
flags: json['flags'] as int? ?? 0,
// Records written before #309 have no 'pathHashWidth' and their path was

@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'package:drift/drift.dart';
import 'package:flutter/foundation.dart';
import '../../utils/app_logger.dart';
@ -138,6 +139,673 @@ class BlobStore {
await (_db.delete(_db.storedBlobs)..where((t) => t.key.equals(key))).go();
}
// ---------------------------------------------------------------------------
// Per-message rows (#920)
//
// The blob API above keeps a whole history in one row, so every save paid for
// every message that came before it. These methods work one message at a
// time. They live on BlobStore rather than in a second class because both
// APIs must use the SAME OffbandDatabase instance: opening the database twice
// is an error on the web backends, and a second singleton would be one
// mistake away from doing exactly that.
// ---------------------------------------------------------------------------
/// Inserts or updates [rows] under [storeKey] in one transaction.
///
/// Upserts on `(storeKey, mergeKey)`, which is the same identity the blob
/// merge deduped on, so saving a message that is already stored updates it
/// instead of duplicating it. Cost is proportional to [rows], not to the
/// history already stored, which is the entire point.
Future<void> upsertMessageRows(
String storeKey,
Iterable<MessageRowInput> rows,
) async {
if (rows.isEmpty) return;
await _db.batch((b) {
b.insertAllOnConflictUpdate(
_db.messageRecords,
rows
.map(
(r) => MessageRecordsCompanion.insert(
storeKey: storeKey,
mergeKey: r.mergeKey,
timestampMs: r.timestampMs,
payload: r.payload,
),
)
.toList(),
);
});
}
/// The stored message payloads for [storeKey], oldest first.
///
/// Ordering and paging happen in SQLite, so loading the most recent N no
/// longer means decoding the whole history first. [limit] with no [offset]
/// returns the NEWEST [limit] messages, still in oldest-first order, because
/// that is what a chat screen opens with.
Future<List<String>> messagePayloads(
String storeKey, {
int? limit,
int? offset,
}) async {
final q = _db.select(_db.messageRecords)
..where((t) => t.storeKey.equals(storeKey));
if (limit != null) {
q.orderBy([
(t) => OrderingTerm(expression: t.timestampMs, mode: OrderingMode.desc),
]);
q.limit(limit, offset: offset);
final newestFirst = await q.get();
return newestFirst.reversed.map((r) => r.payload).toList();
}
q.orderBy([(t) => OrderingTerm(expression: t.timestampMs)]);
final rows = await q.get();
return rows.map((r) => r.payload).toList();
}
/// Every stored identity under [storeKey].
///
/// The migration's readback gate asks this, not [messageRowCount], because
/// the question that matters is whether any record from the blob is MISSING
/// from rows. A total count cannot answer that once rows may legitimately
/// hold messages the frozen blob does not (#952).
Future<Set<String>> messageMergeKeys(String storeKey) async {
final key = _db.messageRecords.mergeKey;
final rows =
await (_db.selectOnly(_db.messageRecords)
..addColumns([key])
..where(_db.messageRecords.storeKey.equals(storeKey)))
.get();
return rows.map((r) => r.read(key)!).toSet();
}
/// Which of [storeKey]'s blob records have no row, or **null** when that
/// cannot be determined (#962).
///
/// The migration gate's readback check, as a question anyone can ask without
/// migrating anything. The sweep asks it again immediately before deleting a
/// blob rather than trusting the marker, which is the difference between
/// "we recorded that this migrated" and "we just confirmed it".
///
/// Empty means every blob record is present as a row and the blob is
/// genuinely redundant. **Null means the question could not be answered** -
/// the blob would not decode - and a caller must treat that as a refusal,
/// never as "nothing is missing". Those two are deliberately different
/// values: conflating them is how a sweep would delete the one copy of an
/// unreadable history.
Future<List<String>?> missingFromRows(
String storeKey,
BlobToRowsCallback toRows,
) async {
final blob = await readWithPrefsFallback(storeKey);
if (blob == null || blob.isEmpty) return const [];
final int sourceCount;
final List<MessageRowInput> rows;
try {
// The converter's own output cannot be the measure of the converter.
// `countJsonArrayElements` decodes the blob and does nothing but count,
// in a separate `compute`, exactly as the migration gate does. Without
// it a converter that silently dropped a record would report every
// record it produced as present and this would delete the blob holding
// the only copy of the one it dropped (Gemini review).
sourceCount = await compute(countJsonArrayElements, blob);
rows = await compute(toRows, blob);
} catch (e) {
appLogger.error(
'Cannot verify $storeKey against its rows: its ${blob.length} char '
'blob will not decode ($e). Treating this as unverifiable; the blob '
'is kept.',
tag: 'Storage',
);
return null;
}
if (rows.length != sourceCount) {
appLogger.error(
'Cannot verify $storeKey against its rows: its blob holds '
'$sourceCount records but the converter produced ${rows.length}. '
'Treating this as unverifiable; the blob is kept.',
tag: 'Storage',
);
return null;
}
return _absentFrom(
rows.map((r) => r.mergeKey),
await messageMergeKeys(storeKey),
);
}
/// Verifies [storeKey]'s stale blob against its rows and deletes it **only**
/// if every record is accounted for, as one atomic step (#962).
///
/// The verify and the delete have to hold the same per-key lock. Checking
/// and then deleting through two separate calls leaves a window, and a
/// delete decided on a stale answer is not recoverable (Gemini review). This
/// also serialises the reclaim against [ensureMessageRowsMigrated] and
/// [mergeOffThread], which take the same lock, so the sweep cannot run
/// against a key mid-migration.
///
/// `deleted` says whether a blob actually went, so the caller does not have
/// to infer it. `missing` is null when the blob could not be verified at all
/// and the key must be refused, empty when nothing was missing, and
/// otherwise the records that have no row.
///
/// Nothing inside the locked section may take the same lock again: the chain
/// is not re-entrant and would deadlock. Everything called here reads.
Future<({bool deleted, List<String>? missing})> reclaimVerifiedHistoryBlob(
String storeKey,
BlobToRowsCallback toRows,
) {
return synchronized(storeKey, () async {
if (await read(storeKey) == null) {
return (deleted: false, missing: const <String>[]);
}
final missing = await missingFromRows(storeKey, toRows);
if (missing == null || missing.isNotEmpty) {
return (deleted: false, missing: missing);
}
await delete(storeKey);
return (deleted: true, missing: const <String>[]);
});
}
/// The one place the "no blob record is missing from rows" rule lives.
///
/// Both the migration gate and the sweep decide by this. The gate cannot
/// just call [missingFromRows], because it has already decoded the blob and
/// a second `compute` over multiple megabytes on the migration path would
/// cost more than the duplication saves. Sharing the comparison keeps the
/// RULE single even though the decode is not.
static List<String> _absentFrom(
Iterable<String> wanted,
Set<String> stored,
) => wanted.where((k) => !stored.contains(k)).toSet().toList();
/// The database's size in bytes, from SQLite itself.
///
/// `page_count * page_size` rather than the file length, so it works for an
/// in-memory database in tests and does not need the file path. It counts
/// free pages, which is the point: it is what shows that a `DELETE` alone
/// reclaims nothing.
Future<int> databaseSizeBytes() async {
Future<int> pragma(String name) async {
final row = await _db.customSelect('PRAGMA $name').getSingle();
return row.data.values.first as int;
}
return (await pragma('page_count')) * (await pragma('page_size'));
}
/// Rebuilds the database, returning free pages to the filesystem.
///
/// Required: deleting rows marks pages free for reuse and does not shrink
/// anything. Measured on the owner's database, deleting all 40 migrated
/// blobs moved the file from 74,350,592 bytes to 74,350,592 bytes.
///
/// It removes nothing of its own. Verified against a copy of a real
/// database: 291 kept keys including all 98 unmigrated history blobs came
/// through hash-identical, with the row count unchanged.
Future<void> vacuum() => _db.customStatement('VACUUM');
/// Every stored message, across every key.
///
/// For the clear-confirmation dialog, which has to say what is NOT being
/// deleted (#962).
Future<int> totalMessageRows() async {
final count = _db.messageRecords.mergeKey.count();
final row = await (_db.selectOnly(
_db.messageRecords,
)..addColumns([count])).getSingle();
return row.read(count) ?? 0;
}
/// How many messages are stored under [storeKey].
Future<int> messageRowCount(String storeKey) async {
final count = _db.messageRecords.mergeKey.count();
final row =
await (_db.selectOnly(_db.messageRecords)
..addColumns([count])
..where(_db.messageRecords.storeKey.equals(storeKey)))
.getSingle();
return row.read(count) ?? 0;
}
/// Removes one message. O(1), with no history rewrite.
Future<void> deleteMessageRow(String storeKey, String mergeKey) async {
await (_db.delete(_db.messageRecords)..where(
(t) => t.storeKey.equals(storeKey) & t.mergeKey.equals(mergeKey),
))
.go();
}
/// Removes every message under [storeKey], for the stores' clear paths.
Future<void> deleteMessageRows(String storeKey) async {
await (_db.delete(
_db.messageRecords,
)..where((t) => t.storeKey.equals(storeKey))).go();
}
/// Store keys that already have rows, so a caller can tell a migrated key
/// from one still on the blob path without reading any payloads.
Future<Set<String>> messageStoreKeys() async {
final key = _db.messageRecords.storeKey;
final rows =
await (_db.selectOnly(_db.messageRecords)
..addColumns([key])
..groupBy([key]))
.get();
return rows.map((r) => r.read(key)!).toSet();
}
/// Holds the set of store keys whose blob has been moved into rows.
///
/// A separate marker rather than "this key has rows" because those are not
/// the same statement. A key can have rows and an incomplete migration at
/// the same time, and treating rows as proof of completeness is how a
/// half-migrated history would read as a whole one.
static const String migratedMarkerKey = '__msgrows_migrated';
Set<String>? _migratedKeys;
Future<Set<String>> _loadMigratedKeys() async {
if (_migratedKeys != null) return _migratedKeys!;
final raw = await read(migratedMarkerKey);
if (raw == null || raw.isEmpty) return _migratedKeys = <String>{};
try {
return _migratedKeys = (jsonDecode(raw) as List<dynamic>)
.cast<String>()
.toSet();
} catch (e) {
// Refuse to guess. An unreadable marker means every key is treated as
// unmigrated, which is the safe direction: the blobs are all still there.
appLogger.error(
'Could not decode the row-migration marker, treating every key as '
'unmigrated (the blobs are intact): $e',
tag: 'Storage',
);
return _migratedKeys = <String>{};
}
}
Future<void> _markMigrated(String storeKey) async {
await synchronized(migratedMarkerKey, () async {
final keys = await _loadMigratedKeys();
if (keys.contains(storeKey)) return;
keys.add(storeKey);
await write(migratedMarkerKey, jsonEncode(keys.toList()));
});
await _stampMigratedAt(storeKey);
}
/// Whether [storeKey] reads from rows. False means its blob is still the
/// source of truth.
Future<bool> isOnMessageRows(String storeKey) async =>
(await _loadMigratedKeys()).contains(storeKey);
@visibleForTesting
void resetMigratedKeyCache() {
_migratedKeys = null;
_migratedAt = null;
}
/// When each migrated key migrated, as epoch milliseconds (#962).
///
/// Deliberately a SECOND blob rather than reshaping [migratedMarkerKey] into
/// a map. That marker is read on every save and every load through
/// [_loadMigratedKeys]'s cache, so changing its shape would put a migration
/// of its own on the hottest storage path. These timestamps are read only by
/// the once-per-launch sweep, which is cold. Owner decision 2026-10-22.
static const String migratedAtKey = '__msgrows_migrated_at';
Map<String, int>? _migratedAt;
Future<Map<String, int>> _loadMigratedAt() async {
if (_migratedAt != null) return _migratedAt!;
final raw = await read(migratedAtKey);
if (raw == null || raw.isEmpty) return _migratedAt = <String, int>{};
try {
return _migratedAt = (jsonDecode(raw) as Map<String, dynamic>).map(
(k, v) => MapEntry(k, v as int),
);
} catch (e) {
// Same safe direction as the marker: an unreadable file means no key has
// a known migration time, so nothing is old enough to sweep and every
// blob stays. Re-stamped on the next pass.
appLogger.error(
'Could not decode the row-migration timestamps, so no blob will be '
'treated as stale (every blob is intact): $e',
tag: 'Storage',
);
return _migratedAt = <String, int>{};
}
}
Future<void> _stampMigratedAt(String storeKey, [DateTime? at]) async {
await synchronized(migratedAtKey, () async {
final stamps = await _loadMigratedAt();
if (at == null && stamps.containsKey(storeKey)) return;
stamps[storeKey] = (at ?? DateTime.now()).millisecondsSinceEpoch;
await write(migratedAtKey, jsonEncode(stamps));
});
}
/// A durable record of what each reclaim sweep deleted (#962).
///
/// Why this exists rather than relying on the log: `appLogger` is gated on
/// the app-debug-logging setting, which is **off by default**, so the only
/// trail of an irreversible delete would not exist on a normal install. And
/// the log previously recorded a count, never which keys went. "Cleared 40"
/// is not an audit trail.
///
/// Written into the database itself, so it survives restarts and the logging
/// toggle, and can be read back without the app running.
static const String reclaimAuditKey = '__msgrows_reclaim_audit';
/// How many sweeps the audit keeps. A key is cleared once and then has no
/// blob to consider again, so this operation is close to once per install
/// and a handful of entries is a generous history rather than a stingy one.
static const int reclaimAuditEntries = 5;
/// Appends one sweep's outcome to the audit, oldest entries dropped.
///
/// The key lists are stored in full: naming what was deleted is the entire
/// point, and truncating them would recreate the "Cleared 40" problem.
Future<void> appendReclaimAudit({
required DateTime at,
required List<String> cleared,
required List<String> refused,
required int bytesBefore,
required int bytesAfter,
}) async {
await synchronized(reclaimAuditKey, () async {
final entries = await reclaimAudit();
entries.add({
'at': at.toIso8601String(),
'cleared': cleared,
'refused': refused,
'bytesBefore': bytesBefore,
'bytesAfter': bytesAfter,
});
while (entries.length > reclaimAuditEntries) {
entries.removeAt(0);
}
await write(reclaimAuditKey, jsonEncode(entries));
});
}
/// The reclaim audit, oldest first. Empty when nothing has ever been swept.
Future<List<Map<String, dynamic>>> reclaimAudit() async {
final raw = await read(reclaimAuditKey);
if (raw == null || raw.isEmpty) return <Map<String, dynamic>>[];
try {
return (jsonDecode(raw) as List<dynamic>)
.cast<Map<String, dynamic>>()
.toList();
} catch (e) {
// An unreadable audit must not stop a sweep, and must not be silently
// replaced either: it is logged and the next append starts a fresh list.
appLogger.error(
'Could not decode the reclaim audit; the next sweep starts a new '
'one: $e',
tag: 'Storage',
);
return <Map<String, dynamic>>[];
}
}
/// When [storeKey] migrated to rows, or null if it has not or is unstamped.
Future<DateTime?> messageRowsMigratedAt(String storeKey) async {
final ms = (await _loadMigratedAt())[storeKey];
return ms == null ? null : DateTime.fromMillisecondsSinceEpoch(ms);
}
/// Stamps any already-migrated key that has no timestamp, with [now].
///
/// The backfill for installs that migrated before #962 shipped. Such a key
/// is stamped on first sight rather than treated as eligible, so updating
/// the app never deletes a blob on the spot: every key gets the full window
/// measured from when we first knew about it. Returns the keys stamped.
Future<List<String>> backfillMigratedAt({DateTime? now}) async {
final marked = await _loadMigratedKeys();
final stamps = await _loadMigratedAt();
final missing = marked.where((k) => !stamps.containsKey(k)).toList()
..sort();
for (final k in missing) {
await _stampMigratedAt(k, now ?? DateTime.now());
}
if (missing.isNotEmpty) {
appLogger.info(
'Stamped ${missing.length} already-migrated key(s) with a migration '
'time for the first time. Each starts its stale window from now, so '
'nothing is swept on this launch.',
tag: 'Storage',
);
}
return missing;
}
@visibleForTesting
Future<void> setMessageRowsMigratedAtForTest(String storeKey, DateTime at) =>
_stampMigratedAt(storeKey, at);
/// Moves [storeKey]'s blob into rows, once, and reports whether the key is
/// now on rows (#920).
///
/// Idempotent and safe to call on every save and load: a key already marked
/// migrated returns immediately from an in-memory set.
///
/// The gate, in order:
///
/// 1. No blob, or an empty one, means there is nothing to move. The key is
/// marked migrated and starts on rows.
/// 2. The blob's top-level element count is measured **independently of
/// [toRows]**, by a decode that does nothing but count. Asking the
/// converter how many records it saw would be a check that cannot fail;
/// the first version of this did exactly that and a deliberately lossy
/// converter sailed through it.
/// 3. [toRows] decodes the blob **off the UI isolate**, because it is the
/// same multi-megabyte decode #919 moved. If it throws, nothing is
/// written and the key stays on the blob. It must return one row per
/// source element; a shortfall against step 2 refuses the migration.
/// 4. The rows are inserted in one transaction, so a failure part-way leaves
/// no partial set behind.
/// 5. The stored identities are read back and every DISTINCT merge key from
/// the blob must be among them. Rows BEYOND that set are fine.
///
/// Steps 2 and 5 together close the loop from blob element to stored row,
/// and either can fail on its own.
///
/// Step 5 compared totals until #952. That was wrong in one direction: once
/// a key is on rows its blob is frozen, so an earlier refused attempt or a
/// newer message leaves rows the blob can never contain, the counts can
/// never be brought level again, and the key is refused on every future
/// attempt forever. Four of the owner's keys were stuck that way, including
/// his two largest channels. "No blob record is missing" is the invariant
/// that was actually wanted; it still catches a short insert, which is what
/// the step is for.
///
/// **The blob is never deleted**, not even on a verified match. Rows become
/// the read and write path and the blob is left untouched. Reclaiming that
/// space is deliberately a separate, owner-gated step: the moment the delete
/// runs is the moment a mistake stops being recoverable.
///
/// A mismatch keeps the key on the blob path, which still works, and says so
/// loudly. It does not retry: a count that did not match once will not match
/// on a loop, and a retry would just hammer the same keys.
Future<bool> ensureMessageRowsMigrated(
String storeKey,
BlobToRowsCallback toRows,
) async {
if (await isOnMessageRows(storeKey)) return true;
return synchronized(storeKey, () async {
// Re-check inside the lock: a concurrent save may have migrated it while
// this call waited its turn.
if (await isOnMessageRows(storeKey)) return true;
final blob = await readWithPrefsFallback(storeKey);
if (blob == null || blob.isEmpty) {
await _markMigrated(storeKey);
return true;
}
final int sourceCount;
final List<MessageRowInput> rows;
try {
sourceCount = await compute(countJsonArrayElements, blob);
rows = await compute(toRows, blob);
} catch (e, stack) {
appLogger.error(
'Row migration of $storeKey FAILED while decoding its ${blob.length} '
'char blob: $e. Nothing was written and the key still reads from the '
'blob.\n$stack',
tag: 'Storage',
);
return false;
}
if (rows.length != sourceCount) {
appLogger.error(
'Row migration of $storeKey REFUSED: the blob holds $sourceCount '
'records but the converter produced ${rows.length} rows. Nothing '
'was written. The blob is kept and still the source of truth.',
tag: 'Storage',
);
return false;
}
final deduped = <String, MessageRowInput>{};
for (final r in rows) {
deduped[r.mergeKey] = r;
}
if (deduped.length != rows.length) {
appLogger.warn(
'Row migration of $storeKey: the blob held ${rows.length} records '
'but only ${deduped.length} distinct identities, so '
'${rows.length - deduped.length} were duplicates. Comparing against '
'the distinct count.',
tag: 'Storage',
);
}
try {
await upsertMessageRows(storeKey, deduped.values);
} catch (e, stack) {
appLogger.error(
'Row migration of $storeKey FAILED while inserting '
'${deduped.length} rows: $e. The blob is untouched and still the '
'source of truth for this key.\n$stack',
tag: 'Storage',
);
return false;
}
final storedKeys = await messageMergeKeys(storeKey);
final missing = _absentFrom(deduped.keys, storedKeys);
if (missing.isNotEmpty) {
appLogger.error(
'Row migration of $storeKey REFUSED: ${missing.length} of the '
'${deduped.length} records in the blob are not present as rows after '
'the insert (e.g. ${missing.take(3).join(', ')}). The blob is kept, '
'nothing is deleted, and this key keeps reading from the blob.',
tag: 'Storage',
);
return false;
}
// Rows beyond the blob's contents are expected, not a fault: once a key
// is on rows the blob is frozen, so an earlier refused attempt or a
// newer message leaves rows the blob will never contain. Comparing
// TOTALS here is what trapped four of the owner's keys permanently
// (#952), because the two numbers could never be brought back level.
final extra = storedKeys.length - deduped.length;
if (extra > 0) {
appLogger.info(
'Row migration of $storeKey: $extra row(s) beyond the '
'${deduped.length} in the blob were already stored. Every blob '
'record is present, so the migration stands.',
tag: 'Storage',
);
}
await _markMigrated(storeKey);
appLogger.info(
'Row migration of $storeKey: ${deduped.length} messages now stored as '
'rows. The blob is retained untouched (#920).',
tag: 'Storage',
);
return true;
});
}
/// Read-modify-write for a bulk key with the decode, merge and re-encode run
/// **off the UI isolate** (#919).
///
/// Why this exists: the stores hold one JSON blob per key, so saving a single
/// message decodes, rebuilds and re-encodes the entire history. Measured on
/// the owner's live database, the largest channel is 5.38 MB holding 9,230
/// messages, and one save costs **134 ms** on a desktop CPU (decode 50,
/// rebuild 38, encode 51), scaling about 14 ms per 1,000 records. Saves on a
/// key are serialised by [synchronized], so a burst of arriving messages pays
/// that cost once each, back to back. Five messages on a phone five to ten
/// times slower than a desktop crosses Android's five-second input-dispatch
/// watchdog, which is what 25 ANR clusters on Play reported (#334).
///
/// This does not make the work cheaper, only concurrent: the ~11 MB of string
/// and map allocation per save still happens, on another isolate. Removing
/// the cost needs one row per message (#920).
///
/// [merge] **must be a top-level or static function**: `compute` sends it to
/// another isolate, and a closure capturing `this` is not sendable. It
/// receives `(storedJson, payload)` and returns the JSON to store, or null to
/// leave the key untouched.
///
/// [payload] is whatever single string the callback needs alongside the
/// stored blob: the incoming batch as JSON when saving, the merge key of the
/// record to drop when deleting. The callback defines its meaning; this
/// method only carries it across the isolate boundary.
///
/// Fails closed. If [merge] throws, including on malformed stored JSON, the
/// error is logged and **the key is not written**, so a corrupt or
/// undecodable blob can never be overwritten by a truncated one. This is the
/// same refusal the stores already made inline; it does not fall back to
/// merging on the UI isolate.
///
/// On web `compute` runs [merge] inline, because web has no isolates. That is
/// documented `compute` behaviour, not a silent degradation: web keeps the
/// cost it has today and gains nothing here, which #920 fixes for every
/// platform at once.
///
/// Returns true when the key was written.
Future<bool> mergeOffThread(
String key,
String payload,
BlobMergeCallback merge,
) {
return synchronized(key, () async {
final stored = await readWithPrefsFallback(key);
final String? merged;
try {
merged = await compute(merge, (stored, payload));
} catch (e, stack) {
appLogger.error(
'Off-thread merge FAILED for $key (stored '
'${stored?.length ?? "null"} chars, payload '
'${payload.length} chars): $e. The key was NOT written, so '
'nothing was truncated.\n$stack',
tag: 'Storage',
);
return false;
}
if (merged == null) return false;
await write(key, merged);
return true;
});
}
/// Unions an [incoming] bulk value into the stored value for [key] by element
/// identity (message id / public key), keeping the stored copy on conflict and
/// adding only what is missing. Used to consolidate stores found in old
@ -347,6 +1015,48 @@ class BlobStore {
}
}
/// Counts the top-level elements of a JSON array, and nothing else.
///
/// Exists so [BlobStore.ensureMessageRowsMigrated] can learn how many records
/// a blob holds without asking the converter it is checking. Top-level so
/// `compute` can send it.
int countJsonArrayElements(String json) =>
(jsonDecode(json) as List<dynamic>).length;
/// Turns one history blob into per-message rows, run on another isolate.
///
/// Must be a top-level or static function so `compute` can send it. Takes the
/// raw blob JSON and returns one [MessageRowInput] per message. Throwing is the
/// correct response to an undecodable blob: [BlobStore.ensureMessageRowsMigrated]
/// turns that into a refused migration and leaves the blob as the source of
/// truth.
typedef BlobToRowsCallback = List<MessageRowInput> Function(String blobJson);
/// One message on its way into [MessageRecords] (#920).
///
/// A plain record rather than a drift companion so the stores can build it
/// without importing the generated code, and so the merge key and timestamp
/// are named at the call site instead of being positional.
class MessageRowInput {
const MessageRowInput({
required this.mergeKey,
required this.timestampMs,
required this.payload,
});
final String mergeKey;
final int timestampMs;
final String payload;
}
/// Merge step for [BlobStore.mergeOffThread], run on another isolate.
///
/// Takes `(storedJson, payload)` and returns the JSON to store, or null to
/// leave the key untouched. Must be a top-level or static function so `compute`
/// can send it; a record of two strings crosses the boundary, so sendability is
/// not in question.
typedef BlobMergeCallback = String? Function((String?, String) input);
/// Mutable tally of a migration run; surfaced in the log and used by tests.
class MigrationReport {
int migrated = 0;

@ -13,6 +13,40 @@ import 'db_snapshot_web.dart' if (dart.library.io) 'db_snapshot_io.dart';
part 'offband_database.g.dart';
/// Thrown when the database on disk is at a NEWER schema than this build
/// understands (#943).
///
/// The upgrade to schema 2 is one-way by design, so this is a refusal and not
/// a recoverable condition. It exists to make that refusal legible: drift
/// would otherwise run this build's `onUpgrade` for a downgrade and then stamp
/// `user_version` backwards, leaving no trace that the database had been on a
/// newer build.
class OffbandSchemaDowngrade implements Exception {
const OffbandSchemaDowngrade({
required this.from,
required this.to,
this.databasePath,
});
/// The schema the database on disk is at.
final int from;
/// The newest schema this build understands.
final int to;
/// Where that database is, when it could be resolved.
final String? databasePath;
@override
String toString() =>
'OffbandSchemaDowngrade: this database is at schema $from and this '
'build only understands $to. A newer version of the app has already '
'migrated it, and that upgrade is one-way, so this build cannot open '
'it. Install the newer version again, or restore a pre-migration copy '
'of the database, which loses everything received since.'
'${databasePath == null ? '' : ' Database: $databasePath'}';
}
/// Bulk data store (#335). Replaces SharedPreferences for message history,
/// contacts and discovered contacts.
///
@ -28,7 +62,7 @@ part 'offband_database.g.dart';
/// IndexedDB and runs in a worker rather than on the UI thread.
///
/// Settings stay in SharedPreferences. Only bulk data moves here.
@DriftDatabase(tables: [StoredBlobs])
@DriftDatabase(tables: [StoredBlobs, MessageRecords])
class OffbandDatabase extends _$OffbandDatabase {
OffbandDatabase([QueryExecutor? executor])
: super(executor ?? _defaultExecutor());
@ -315,7 +349,83 @@ class OffbandDatabase extends _$OffbandDatabase {
}
@override
int get schemaVersion => 1;
int get schemaVersion => 2;
/// Schema 2 adds [MessageRecords] (#920). Purely additive: [StoredBlobs] is
/// untouched and keeps every byte it had.
///
/// That is true of the data and NOT of a downgrade, which is what #943
/// corrects. drift has no "newer schema" refusal: it compares the stored
/// `user_version` against [schemaVersion] for inequality and routes BOTH
/// directions into this callback. The pre-#917 build declared schema 1 and
/// no strategy at all, so it got drift's default `onUpgrade`, which throws,
/// and so it could never reach the blobs it would have found.
///
/// A downgrade therefore has to be refused HERE, which is what the first
/// branch below does (#943, owner decision 2026-10-22). Without it the
/// `from < 2` guard let a future schema open silently, and drift then
/// stamped `user_version` back down, erasing the only record the database
/// had ever been on a newer build.
///
/// Downgrades are deliberately unsupported rather than made to work. Once a
/// key is on rows its blob is frozen, so an older build would read stale
/// history and write into the blob while this one reads rows, orphaning
/// everything it received. Supporting a downgrade would mean dual-writing
/// the blob on every save, which is the cost #917 exists to remove.
/// `test/storage/schema_downgrade_test.dart` pins all of this.
@override
MigrationStrategy get migration => MigrationStrategy(
onUpgrade: (m, from, to) async {
if (from > to) {
// Logged BEFORE the path lookup and before the throw, deliberately.
// This runs inside drift's beforeOpen, so it fires on whichever
// isolate issued the first query, and whoever catches the exception
// decides what the user sees. A downgrade that only stopped
// background work, with nothing in the log, would be the quiet
// failure this branch exists to replace (Gemini review).
appLogger.error(
'Refusing to open the database: it is at schema $from and this '
'build understands $to. The upgrade to a newer schema is one-way '
'(#943).',
tag: 'Storage',
);
// Best-effort: path_provider has no web implementation, and on the
// platforms where a downgrade is reachable this reads environment
// variables rather than a platform channel, and has already resolved
// once to open this database. A message without the path still beats
// the silent version rewrite it replaces.
String? path;
try {
path = await pinnedDatabasePath();
} catch (_) {}
throw OffbandSchemaDowngrade(from: from, to: to, databasePath: path);
}
if (from < 2) {
await m.createTable(messageRecords);
await m.createIndex(
Index(
'idx_message_records_store_ts',
'CREATE INDEX IF NOT EXISTS idx_message_records_store_ts '
'ON message_records (store_key, timestamp_ms)',
),
);
appLogger.info(
'drift schema $from -> $to: created message_records (#920). '
'stored_blobs untouched.',
);
}
},
beforeOpen: (details) async {
// A fresh database is created at the current schema, so onUpgrade never
// runs for it and the index would be missing.
if (details.wasCreated) {
await customStatement(
'CREATE INDEX IF NOT EXISTS idx_message_records_store_ts '
'ON message_records (store_key, timestamp_ms)',
);
}
},
);
/// Step-1 gate for #335: proves the database opens, writes and reads back on
/// the current platform. Deliberately trivial - no user data is involved, so
@ -352,3 +462,46 @@ class StoredBlobs extends Table {
@override
Set<Column> get primaryKey => {key};
}
/// One row per message, replacing one element of a [StoredBlobs] JSON array
/// each (#920).
///
/// Why this exists: with the whole history in one blob, saving a single message
/// decoded, rebuilt and re-encoded every message that came before it. On the
/// owner's largest channel that was 9,230 records and 134 ms of work per
/// arriving message, and #919 could only move that cost to another isolate,
/// not remove it. One row per message makes a save an upsert of one row.
///
/// [storeKey] is deliberately the SAME key the blob used, not a new scheme.
/// All of the per-radio and per-channel scoping rules (#194, #472) already live
/// in those keys, so reusing them means this table inherits that scoping
/// unchanged, and the migration becomes a per-key operation with an exact
/// record count to verify against.
///
/// [payload] holds the per-message JSON exactly as the stores already emit it,
/// rather than a column per field. That keeps the migration a pure re-key with
/// no field mapping that could silently drop or coerce a value, lets the
/// stores reuse their existing encoders, and means a new message field needs
/// no second data migration. The trade: message fields are not SQL-queryable.
/// Columns can be added beside the payload later without another migration if
/// that is ever wanted.
class MessageRecords extends Table {
@override
String get tableName => 'message_records';
/// The store key this message belongs to, byte-identical to the blob key.
TextColumn get storeKey => text()();
/// Stable per-message identity: the stores' existing `_mergeKey`. Upserting
/// on it preserves exactly the dedupe semantics the blob merge had.
TextColumn get mergeKey => text()();
/// Sender-claimed time in epoch milliseconds, for ordering and paging. An
/// INTEGER column so ORDER BY and LIMIT happen in SQLite, not in Dart.
IntColumn get timestampMs => integer()();
TextColumn get payload => text()();
@override
Set<Column> get primaryKey => {storeKey, mergeKey};
}

@ -1,5 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import '../models/message.dart';
import '../models/translation_support.dart';
import '../helpers/reaction_helper.dart';
@ -8,6 +8,80 @@ import '../utils/app_logger.dart';
import 'drift/blob_store.dart';
import 'prefs_manager.dart';
/// Merges a DM history blob with an incoming batch, entirely in JSON.
///
/// Top-level and free of any instance state so `compute` can send it to
/// another isolate (#919). Both arguments and the result are JSON strings, so
/// only two strings cross the isolate boundary rather than the object graph.
///
/// Throws if [stored] is not decodable. That is deliberate: `mergeOffThread`
/// turns the throw into a refused write, which keeps an unreadable blob intact
/// instead of replacing a whole history with just the incoming batch.
String mergeDmHistoryJson((String?, String) input) {
final (stored, incomingJson) = input;
final byKey = <String, Message>{};
if (stored != null && stored.isNotEmpty) {
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = MessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[MessageStore._mergeKey(m)] = m;
}
}
for (final e in jsonDecode(incomingJson) as List<dynamic>) {
final m = MessageStore._messageFromJson(e as Map<String, dynamic>);
byKey[MessageStore._mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
return jsonEncode(merged.map(MessageStore._messageToJson).toList());
}
/// Drops the record whose merge key is `target` from a DM history blob.
///
/// `input` is `(storedJson, targetMergeKey)`. Returns null, so nothing is
/// written, when there is no history or the target is not in it. Throws on
/// undecodable stored JSON, which `mergeOffThread` turns into a refused write.
String? dropFromDmHistoryJson((String?, String) input) {
final (stored, target) = input;
if (stored == null || stored.isEmpty) return null;
final kept = <Message>[];
var removed = false;
for (final e in jsonDecode(stored) as List<dynamic>) {
final m = MessageStore._messageFromJson(e as Map<String, dynamic>);
if (MessageStore._mergeKey(m) == target) {
removed = true;
} else {
kept.add(m);
}
}
if (!removed) return null;
return jsonEncode(kept.map(MessageStore._messageToJson).toList());
}
/// Converts a whole DM-history blob into one row per message (#920).
///
/// Top-level so `compute` can send it. One row per source element, with no
/// dedupe and no sorting: the migration counts the blob independently and does
/// its own deduping, so doing either here would defeat its gate.
List<MessageRowInput> dmHistoryToRows(String blobJson) {
return (jsonDecode(blobJson) as List<dynamic>).map((e) {
final map = e as Map<String, dynamic>;
final m = MessageStore._messageFromJson(map);
return MessageRowInput(
mergeKey: MessageStore._mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
// The source map re-encoded, not a re-serialisation of the decoded
// object: a round trip through the model would rewrite any field the
// model defaults, and this is a move, not a rewrite.
payload: jsonEncode(map),
);
}).toList();
}
class MessageStore {
static const String _keyPrefix = 'messages_';
@ -31,63 +105,55 @@ class MessageStore {
// (removeMessage).
final key = '$keyFor$contactKeyHex';
final blobs = BlobStore.instance;
await blobs.synchronized(key, () async {
final byKey = <String, Message>{};
final existing = await blobs.readWithPrefsFallback(key);
if (existing != null && existing.isNotEmpty) {
try {
for (final e in jsonDecode(existing) as List<dynamic>) {
final m = _messageFromJson(e as Map<String, dynamic>);
byKey[_mergeKey(m)] = m;
}
} catch (e) {
appLogger.error(
'Failed to decode existing DM history before merge; aborting save '
'to avoid truncation: $e',
tag: 'Storage',
);
return;
}
}
for (final m in messages) {
byKey[_mergeKey(m)] = m;
}
final merged = byKey.values.toList()
..sort((a, b) => a.timestamp.compareTo(b.timestamp));
await blobs.write(key, jsonEncode(merged.map(_messageToJson).toList()));
});
// Rows (#920): one upsert per message being saved, costing the same at
// 50,000 messages of history as at 50.
if (await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows)) {
await blobs.upsertMessageRows(key, messages.map(_toRow));
return;
}
// Blob fallback for a key whose migration was refused. Off the UI isolate
// (#919): only the INCOMING messages are encoded here, and `mergeOffThread`
// keeps the per-key serialisation and fails closed, so an undecodable blob
// is logged and left alone rather than overwritten by a truncated one.
final incoming = jsonEncode(messages.map(_messageToJson).toList());
await blobs.mergeOffThread(key, incoming, mergeDmHistoryJson);
}
String _mergeKey(Message m) {
static MessageRowInput _toRow(Message m) => MessageRowInput(
mergeKey: _mergeKey(m),
timestampMs: m.timestamp.millisecondsSinceEpoch,
payload: jsonEncode(_messageToJson(m)),
);
/// The store's own history encoding, for tests that need a blob fixture.
/// Saves write rows now, so a test can no longer get one by saving.
@visibleForTesting
static String encodeHistoryForTest(List<Message> messages) =>
jsonEncode(messages.map(_messageToJson).toList());
static String _mergeKey(Message m) {
if (m.messageId.isNotEmpty) return 'id:${m.messageId}';
return 'x:${m.senderKeyHex}:${m.timestamp.millisecondsSinceEpoch}:${m.text}';
}
/// Explicit delete path (#343): save merges and never removes.
///
/// On rows this is a single-row DELETE (#920). On the blob fallback the
/// decode and re-encode run off the UI isolate (#919), with the per-key
/// serialisation this path did not have before: it was a read-modify-write
/// outside [BlobStore.synchronized], so a save landing after a delete could
/// resurrect the deleted message.
Future<void> removeMessage(String contactKeyHex, Message message) async {
if (publicKeyHex.isEmpty) return;
final key = '$keyFor$contactKeyHex';
final existing = await BlobStore.instance.readWithPrefsFallback(key);
if (existing == null || existing.isEmpty) return;
final List<dynamic> raw;
try {
raw = jsonDecode(existing) as List<dynamic>;
} catch (e) {
appLogger.error(
'Failed to decode DM history for delete: $e',
tag: 'Storage',
);
final blobs = BlobStore.instance;
if (await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows)) {
await blobs.deleteMessageRow(key, _mergeKey(message));
return;
}
final target = _mergeKey(message);
final kept = raw
.map((e) => _messageFromJson(e as Map<String, dynamic>))
.where((m) => _mergeKey(m) != target)
.toList();
await BlobStore.instance.write(
key,
jsonEncode(kept.map(_messageToJson).toList()),
);
await blobs.mergeOffThread(key, _mergeKey(message), dropFromDmHistoryJson);
}
Future<List<Message>> loadMessages(String contactKeyHex) async {
@ -97,9 +163,18 @@ class MessageStore {
}
final key = '$keyFor$contactKeyHex';
final oldKey = '$_keyPrefix$contactKeyHex';
final blobs = BlobStore.instance;
// Rows (#920). Only short-circuits when rows actually exist: a key marked
// migrated with no rows must still fall through to the legacy-key adoption
// below, or history stored under an older key would never be picked up.
if (await blobs.isOnMessageRows(key)) {
final payloads = await blobs.messagePayloads(key);
if (payloads.isNotEmpty) return _decodePayloads(payloads, key);
}
// Bulk data lives in drift (#335); fallback covers an unmigrated key and
// logs loudly if it fires.
final blobs = BlobStore.instance;
String? jsonString = await blobs.readWithPrefsFallback(key);
if (jsonString == null || jsonString.isEmpty) {
@ -124,6 +199,11 @@ class MessageStore {
return [];
}
// Blob history that is not in rows yet, either never migrated or just
// adopted from a legacy key. Move it so the next load and every save runs
// on rows.
await blobs.ensureMessageRowsMigrated(key, dmHistoryToRows);
try {
final jsonList = jsonDecode(jsonString) as List<dynamic>;
return jsonList.map((json) => _messageFromJson(json)).toList();
@ -132,6 +212,23 @@ class MessageStore {
}
}
List<Message> _decodePayloads(List<String> payloads, String key) {
final out = <Message>[];
for (final p in payloads) {
try {
out.add(_messageFromJson(jsonDecode(p) as Map<String, dynamic>));
} catch (e) {
// One bad row costs one message. On the blob, one bad byte cost the
// whole conversation.
appLogger.error(
'Skipping an undecodable message row in $key: $e',
tag: 'Storage',
);
}
}
return out;
}
Future<void> clearMessages(String contactKeyHex) async {
if (publicKeyHex.isEmpty) {
appLogger.warn('Public key hex is not set. Cannot clear messages.');
@ -142,15 +239,18 @@ class MessageStore {
// copy must not survive a clear and reappear via the read fallback.
await BlobStore.instance.delete(key);
await PrefsManager.instance.remove(key);
// Rows too, or a cleared conversation stays readable (#920).
await BlobStore.instance.deleteMessageRows(key);
}
Map<String, dynamic> _messageToJson(Message msg) {
static Map<String, dynamic> _messageToJson(Message msg) {
return {
'senderKey': base64Encode(msg.senderKey),
'text': msg.text,
'timestamp': msg.timestamp.millisecondsSinceEpoch,
'isOutgoing': msg.isOutgoing,
'isCli': msg.isCli,
'isCliCommand': msg.isCliCommand,
'status': msg.status.index,
'messageId': msg.messageId,
'originalText': msg.originalText,
@ -181,10 +281,12 @@ class MessageStore {
};
}
Message _messageFromJson(Map<String, dynamic> json) {
static Message _messageFromJson(Map<String, dynamic> json) {
final rawText = json['text'] as String;
final isCli = json['isCli'] as bool? ?? false;
final decodedText = isCli
final isCliCommand = json['isCliCommand'] as bool? ?? false;
// Neither a CLI reply nor a CLI command is SMAZ-compressed on the wire.
final decodedText = (isCli || isCliCommand)
? rawText
: (Smaz.tryDecodePrefixed(rawText) ?? rawText);
return Message(
@ -193,6 +295,7 @@ class MessageStore {
timestamp: DateTime.fromMillisecondsSinceEpoch(json['timestamp'] as int),
isOutgoing: json['isOutgoing'] as bool,
isCli: isCli,
isCliCommand: isCliCommand,
status: MessageStatus.values[json['status'] as int],
messageId: json['messageId'] as String?,
originalText: json['originalText'] as String?,

@ -0,0 +1,365 @@
/// The declared scoping verdict for every persistence surface (#853, #936).
///
/// Feature #853's acceptance bar is that "every store has a verified scoping
/// verdict (per-radio or deliberately-global) and no hole remains". Until this
/// file existed, the only way to check that was for a human to re-read an audit
/// in an issue body, which is how #754 and #856 survived three earlier bleed
/// fixes. This file is that audit, in code, with a test that fails when a new
/// candidate key appears undeclared.
///
/// **Adding a storage key means adding a row here.** The test in
/// `test/storage/scoping_inventory_test.dart` scans `lib/` for the shape every
/// key in this repo uses, a `const String` whose value is lower snake_case, and
/// fails if one is not classified below. A key that is not a storage key goes
/// in [nonStorageConstants] with a reason, so "it isn't a key" is a written
/// claim rather than a silence.
library;
enum ScopingVerdict {
/// Scoped by the first 10 hex of the connected radio's public key, the
/// scheme every per-radio store in this repo uses. Radio A's data is never
/// visible while radio B is connected.
perRadio,
/// Global, and that is correct. The reason is mandatory: without it a later
/// audit re-opens the surface as a hole, which is exactly the churn #853
/// exists to end.
globalOnPurpose,
/// Global, and that is a defect. Each of these has an open issue. The test
/// asserts the set matches the known holes, so a NEW hole cannot hide among
/// them and a FIXED one cannot be left mislabelled.
knownHole,
}
class StorageSurface {
const StorageSurface(
this.key, {
required this.verdict,
required this.reason,
required this.owner,
this.issue,
});
/// The key or key prefix exactly as the source declares it.
final String key;
final ScopingVerdict verdict;
/// Why this verdict. For [ScopingVerdict.perRadio], where the scoping comes
/// from. For [ScopingVerdict.globalOnPurpose], why radio scoping would be
/// wrong. For [ScopingVerdict.knownHole], what bleeds.
final String reason;
/// The file that owns the key, so a reader can go check.
final String owner;
/// Required for [ScopingVerdict.knownHole], so every hole is tracked.
final int? issue;
}
/// Every persistence surface in the client, with its verdict.
const List<StorageSurface> storageSurfaces = [
// ---------------------------------------------------------------------------
// Per-radio. Each is fed the device-key prefix on connect.
// ---------------------------------------------------------------------------
StorageSurface(
'channel_messages_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key, then PSK identity within the radio (#194), '
'so history survives a channel rename and does not follow a reused '
'slot. The cross-radio bleed was #472',
owner: 'lib/storage/channel_message_store.dart',
),
StorageSurface(
'messages_',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key + contact key',
owner: 'lib/storage/message_store.dart',
),
StorageSurface(
'channels',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key',
owner: 'lib/storage/channel_store.dart',
),
StorageSurface(
'channel_order_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key; display order is per radio because the '
'channel list is',
owner: 'lib/storage/channel_order_store.dart',
),
StorageSurface(
'channel_region_scope_',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key',
owner: 'lib/storage/channel_region_scope_store.dart',
),
StorageSurface(
'contacts',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key; a contact list belongs to the radio that '
'holds it',
owner: 'lib/storage/contact_store.dart',
),
StorageSurface(
'contact_groups',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key; groups reference that radio\'s contacts',
owner: 'lib/storage/contact_group_store.dart',
),
StorageSurface(
'contact_unread_count',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key; unread counts follow the message history',
owner: 'lib/storage/unread_store.dart',
),
StorageSurface(
'discovered_contacts',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key since #754. A discovered node is what THIS '
'radio heard. An unset key loads nothing and never writes, so it '
'cannot touch the orphaned legacy blob',
owner: 'lib/storage/contact_discovery_store.dart',
),
StorageSurface(
'communities_v1',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key',
owner: 'lib/storage/community_store.dart',
),
StorageSurface(
'channel_cyr2lat_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key + channel index, via keyForCyr2Lat. NOT '
'previously audited: #853\'s audit listed channel_settings_store as '
'one surface, but it owns two keys and this inventory found the '
'second',
owner: 'lib/storage/channel_settings_store.dart',
),
StorageSurface(
'contact_cyr2lat_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key + contact key. NOT previously audited, same '
'reason as channel_cyr2lat_',
owner: 'lib/storage/contact_settings_store.dart',
),
StorageSurface(
'contact_customname_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key + contact key, via keyForCustomName. The user\'s '
'own label for a contact (#750). Per-radio for the same reason as its '
'neighbour in this store. Deliberately NOT in contact_store: that '
'record is rebuilt from radio contact-sync data, where no custom name '
'exists, so a save after a sync would wipe the rename',
owner: 'lib/storage/contact_settings_store.dart',
),
StorageSurface(
'block_keys_v1',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key. A blank radio is no longer offloaded the '
'client list (#471)',
owner: 'lib/storage/block_store.dart',
),
StorageSurface(
'block_names_v1',
verdict: ScopingVerdict.perRadio,
reason: 'prefix + device key, alongside block_keys_v1',
owner: 'lib/storage/block_store.dart',
),
// ---------------------------------------------------------------------------
// Known holes. Each has an issue and each is fixed in Epic B (#937).
// ---------------------------------------------------------------------------
StorageSurface(
'path_history_',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key + contact key, in DRIFT, since #854 and #924. '
'Was keyed by contact alone in prefs, so a route measured by a 1 W '
'handheld was applied to a repeater. The move out of prefs went with '
'the scoping because that one store held 2,092 keys and 86% of a '
'4.28 MB file, and every prefs write re-encodes the whole file '
'(#923). Unset key loads nothing and never writes',
owner: 'lib/services/storage_service.dart',
),
StorageSurface(
'delivery_observations',
verdict: ScopingVerdict.perRadio,
reason:
'prefix + device key since #856. Was one global list, so a '
'repeater\'s 45-second deliveries trained the ACK-timeout model a '
'1 W handheld then used. Stays in prefs unlike path history: one '
'small key, 3,091 bytes and 14 entries on the owner\'s install, so '
'there is no cost argument for moving it',
owner: 'lib/services/storage_service.dart',
),
// `pending_messages` (#855) was listed here and is GONE, not reclassified.
// It had no callers anywhere in lib/ or test/ and the key was absent from
// the owner's live prefs, so the fix was deletion rather than scoping. The
// inventory's "declared but vanished from source" check is what keeps that
// honest in the other direction: if the key ever comes back, the gate fails
// until somebody declares it and says why.
// ---------------------------------------------------------------------------
// Global on purpose. The reason is the point: it stops a later audit
// re-opening these as holes.
// ---------------------------------------------------------------------------
StorageSurface(
'client_install_id',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'the identity of this app INSTALL, not of any radio. Scoping it '
'per radio would mint a new install id per radio, which is the '
'opposite of what it is for',
owner: 'lib/storage/client_id_store.dart',
),
StorageSurface(
'app_settings',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'app-wide UX: theme, language, units, map and notification '
'preferences. The per-radio data it does carry is scoped INSIDE it, by '
'channelNotifyModesByRadio: device key -> channel PSK -> mode (#839). '
'So the blob is global and the radio-specific part within it is not',
owner: 'lib/models/app_settings.dart',
),
StorageSurface(
'repeater_passwords',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'keyed by the repeater NODE, not by the radio connecting to it. '
'The same repeater has the same password whichever radio reaches it, '
'so per-radio scoping would make the user re-enter it per radio',
owner: 'lib/services/storage_service.dart',
),
StorageSurface(
'repeater_auto_clock_sync_after_login',
verdict: ScopingVerdict.globalOnPurpose,
reason: 'keyed by repeater node, same reasoning as repeater_passwords',
owner: 'lib/services/storage_service.dart',
),
StorageSurface(
'map_removed_marker_ids',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'a set of node ids the user dismissed from the map. "Do not show '
'me this node" is a statement about the NODE, like repeater_passwords, '
'not about the radio that happened to hear it. NOT previously audited: '
'surfaced by this inventory, see #936',
owner: 'lib/services/map_marker_service.dart',
),
StorageSurface(
'map_tile_cache',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'cached OSM tiles. Geography does not depend on which radio is '
'connected, and per-radio caching would multiply the download',
owner: 'lib/services/map_tile_cache_service.dart',
),
StorageSurface(
'radio_presets_v1_',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'prefix + preset FILE name. A cached catalogue of region presets '
'fetched from assets or upstream, not state belonging to a radio. NOT '
'previously audited: surfaced by this inventory',
owner: 'lib/services/radio_preset_service.dart',
),
StorageSurface(
'anr_last_exit_ts_ms',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'watermark for which ApplicationExitInfo records have been '
'processed (#906). A property of the app process, not of a radio. NOT '
'previously audited: surfaced by this inventory',
owner: 'lib/services/app_exit_info_service.dart',
),
StorageSurface(
'__msgrows_migrated',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'the set of store keys whose blob has been moved into message rows '
'(#920). Global because the keys it lists are themselves already '
'radio-scoped, so scoping the marker would scope it twice',
owner: 'lib/storage/drift/blob_store.dart',
),
StorageSurface(
'__msgrows_migrated_at',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'when each migrated store key migrated, for the stale-blob sweep '
'(#962). Global for the same reason as __msgrows_migrated: it is keyed '
'BY those store keys, which already carry the radio, so scoping it '
'would scope it twice. Kept separate from that marker because the '
'marker is read on every save and load through a cache, and reshaping '
'it into a map would put a migration on the hottest storage path',
owner: 'lib/storage/drift/blob_store.dart',
),
StorageSurface(
'__msgrows_reclaim_audit',
verdict: ScopingVerdict.globalOnPurpose,
reason:
'a durable record of what each stale-blob sweep deleted (#962). Global '
'because one sweep spans every radio and the entries name store keys, '
'which already carry the radio. It exists because the app log is gated '
'on a setting that is off by default, so an irreversible delete would '
'otherwise leave no trail at all; capped at the last few sweeps',
owner: 'lib/storage/drift/blob_store.dart',
),
];
/// Constants that match the key shape but are not persistence keys.
///
/// This list exists so "that is not a storage key" has to be written down and
/// justified, instead of a new key slipping through because nobody looked.
const Map<String, String> nonStorageConstants = {
'offband_store': 'the drift database FILE name, not a key within it',
'__all__':
'the sentinel value for "all groups" in the contacts filter '
'(UiViewStateService). A filter VALUE, not a key, and not persisted '
'under this name',
'__reaction_send__':
'a prefix for an in-memory send-queue id in the '
'connector, distinguishing a reaction send from a message send. Never '
'reaches storage',
'psk_':
'a marker inside a channel-history key, distinguishing a PSK '
'identity from a legacy slot index (#194). Not a key by itself',
'anr':
'a log tag / exit-reason discriminator in the ANR capture path, not '
'persisted under this name',
'los_error_select_start_end':
'an in-memory error sentinel in the line-of-sight screen, assigned to '
'_error and compared against. Never written to storage',
'los_error_invalid_input': 'the same, for invalid input',
'los_error_elevation_unavailable':
'the same, raised by the line-of-sight service when elevation data is '
'missing. Never written to storage',
// MQTT broker config field names. These are keys within a config map that is
// itself persisted under another surface, not top-level storage keys.
'auth_type': 'MQTT broker config field name',
'ca_cert': 'MQTT broker config field name',
'enabled': 'MQTT broker config field name',
'password': 'MQTT broker config field name',
'port': 'MQTT broker config field name',
'topic_prefix': 'MQTT broker config field name',
'transport': 'MQTT broker config field name',
'url': 'MQTT broker config field name',
'username': 'MQTT broker config field name',
'jwt_aud': 'JWT claim name in a broker auth payload',
'jwt_email': 'JWT claim name',
'jwt_owner': 'JWT claim name',
'jwt_refresh': 'JWT claim name',
'jwt_token': 'JWT claim name',
'iata_override': 'a field name within a config payload, not a storage key',
};

@ -24,6 +24,34 @@ class FileLogWriter {
File get activeFile => File('${dir.path}/$baseName.log');
File _rotated(int n) => File('${dir.path}/$baseName.$n.log');
/// Every log file that exists, newest first: the active file then the rotated
/// ones.
///
/// The rotation naming lives here rather than in callers, so an exporter does
/// not have to duplicate the scheme. Needed because a line written once, at
/// startup, can rotate out of the active file long before the user exports,
/// and until now nothing could reach the rotated files at all (#906).
///
/// One directory listing rather than a per-name `exists()` walk: the periodic
/// flush can rotate while this is awaiting, and a walk could return a name it
/// had just confirmed and that rotation then renamed, which would hand the
/// exporter a path that no longer resolves and fail the whole share.
Future<List<File>> existingFiles() async {
if (!await dir.exists()) return const [];
final byName = <String, File>{};
for (final entry in await dir.list(followLinks: false).toList()) {
if (entry is File) byName[entry.uri.pathSegments.last] = entry;
}
final ordered = <File>[];
final active = byName['$baseName.log'];
if (active != null) ordered.add(active);
for (var n = 1; n < maxFiles; n++) {
final rotated = byName['$baseName.$n.log'];
if (rotated != null) ordered.add(rotated);
}
return ordered;
}
/// Append [line] (a trailing newline is added), rotating first if it would
/// push the active file past [maxBytes].
Future<void> writeLine(String line) async {

@ -6,6 +6,7 @@ import 'package:flutter/material.dart';
import 'package:share_plus/share_plus.dart';
import '../l10n/l10n.dart';
import '../services/app_exit_info_service.dart';
import '../services/file_log_service.dart';
import 'log_web_download.dart';
@ -66,14 +67,39 @@ class LogExport {
// possibly-deactivated widget after the await.
final messenger = ScaffoldMessenger.of(context);
final l10n = context.l10n;
final file = await FileLogService.instance.flushAndGetActiveFile();
// On mobile, take every log file rather than just the active one, and the
// ANR traces with them (#906). Two reasons: a trace lives beside the log
// rather than inside it, and a pointer line written once at startup can
// rotate into `.1.log` before the user exports, which would hand over a
// trace with its metadata line missing. Desktop keeps its single-file Save
// As: there are no exit records off Android.
final List<File> logs;
if (_isMobile) {
logs = await FileLogService.instance.flushAndGetAllFiles();
} else {
final active = await FileLogService.instance.flushAndGetActiveFile();
logs = active == null ? const <File>[] : <File>[active];
}
final candidates = <File>[
...logs,
if (_isMobile) ...await AppExitInfoService.traceFiles(),
];
// Last-moment existence check. Rotation renames files underneath us and a
// trace can be pruned, so a path collected a moment ago may already be
// gone; handing a missing path to the share sheet fails the whole export
// rather than one attachment.
final present = <File>[];
for (final f in candidates) {
if (await f.exists()) present.add(f);
}
await _exportFile(
messenger,
file: file,
file: present.isEmpty ? null : present.first,
fileName: _defaultFileName,
subject: l10n.debugLog_shareSubject,
unavailableMessage: l10n.debugLog_logUnavailable,
savedMessage: l10n.debugLog_logSaved,
extraFiles: present.skip(1).toList(),
);
}
@ -104,6 +130,7 @@ class LogExport {
required String subject,
required String unavailableMessage,
required String savedMessage,
List<File> extraFiles = const [],
}) async {
if (file == null) {
messenger.showSnackBar(SnackBar(content: Text(unavailableMessage)));
@ -111,7 +138,13 @@ class LogExport {
}
if (_isMobile) {
await SharePlus.instance.share(
ShareParams(subject: subject, files: [XFile(file.path)]),
ShareParams(
subject: subject,
files: [
XFile(file.path),
for (final extra in extraFiles) XFile(extra.path),
],
),
);
return;
}

@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../connector/meshcore_connector.dart';
import '../l10n/l10n.dart';
import '../models/app_settings.dart';
import '../models/channel.dart';
@ -10,13 +11,6 @@ import '../services/app_settings_service.dart';
/// Channels list and from inside a channel's chat (#275). Single implementation
/// so the two entry points cannot drift.
/// Notify-mode storage key for [channel]: its PSK identity, so the setting
/// survives a rename and does not follow a reused slot (#259).
String channelNotifyKeyFor(Channel channel) => AppSettings.channelNotifyKey(
channelIndex: channel.index,
pskHex: channel.pskHex,
);
IconData channelNotifyModeIcon(ChannelNotifyMode mode) {
switch (mode) {
case ChannelNotifyMode.all:
@ -41,10 +35,10 @@ String channelNotifyModeLabel(BuildContext context, ChannelNotifyMode mode) {
void showChannelNotifyModeDialog(BuildContext context, Channel channel) {
final settingsService = context.read<AppSettingsService>();
final identityKey = channelNotifyKeyFor(channel);
final devicePrefix = context.read<MeshCoreConnector>().selfPublicKeyHex;
final current = settingsService.channelNotifyMode(
identityKey: identityKey,
channelName: channel.name,
devicePrefix: devicePrefix,
pskHex: channel.pskHex,
);
showDialog<void>(
@ -63,7 +57,8 @@ void showChannelNotifyModeDialog(BuildContext context, Channel channel) {
onTap: () async {
Navigator.pop(dialogContext);
await settingsService.setChannelNotifyMode(
identityKey: identityKey,
devicePrefix: devicePrefix,
pskHex: channel.pskHex,
channelName: channel.name,
mode: mode,
);

@ -0,0 +1,232 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../l10n/l10n.dart';
import '../services/region_discovery_service.dart';
/// A repeater the user can discover regions from (name + 32-byte key).
/// [hasPath] is whether a stored path to it exists; without one the companion
/// can only flood the request and the repeater ignores it, so it cannot be
/// selected.
class RepeaterChoice {
const RepeaterChoice({
required this.name,
required this.pubKey,
this.hasPath = true,
});
final String name;
final Uint8List pubKey;
final bool hasPath;
}
/// Pick the flood region a channel's outgoing messages ride (Feature #812,
/// Epic #815). Discovers regions from a chosen repeater (via the injected
/// [service]) and lets the user select one, or None to leave the channel
/// unscoped. Persisting the choice is the caller's job, via [onSave].
class ChannelRegionScopeDialog extends StatefulWidget {
const ChannelRegionScopeDialog({
super.key,
required this.channelName,
required this.currentScope,
required this.repeaters,
required this.service,
required this.onSave,
});
final String channelName;
final String? currentScope;
final List<RepeaterChoice> repeaters;
final RegionDiscoveryService service;
final Future<void> Function(String? region) onSave;
@override
State<ChannelRegionScopeDialog> createState() =>
_ChannelRegionScopeDialogState();
}
class _ChannelRegionScopeDialogState extends State<ChannelRegionScopeDialog> {
// Alpha-sorted once (case-insensitive), so the picker is predictable even
// with many repeater contacts (D1 finding: an unsorted list was unusable).
late final List<RepeaterChoice> _sortedRepeaters = [...widget.repeaters]
..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
late RepeaterChoice? _repeater = _firstWithPath();
String _repeaterFilter = '';
late String? _selected = widget.currentScope;
RepeaterChoice? _firstWithPath() {
for (final r in _sortedRepeaters) {
if (r.hasPath) return r;
}
return null;
}
void _discover() {
final repeater = _repeater;
if (repeater != null && repeater.hasPath) {
widget.service.discover(repeater.pubKey);
}
}
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
return AlertDialog(
title: Text(l10n.setRegionScope_title(widget.channelName)),
content: SizedBox(
width: double.maxFinite,
child: ListenableBuilder(
listenable: widget.service,
builder: (context, _) => _content(l10n),
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(MaterialLocalizations.of(context).cancelButtonLabel),
),
ElevatedButton(
key: const Key('regionScopeSave'),
onPressed: () async {
await widget.onSave(_selected);
if (context.mounted) Navigator.of(context).pop();
},
child: Text(l10n.setRegionScope_save),
),
],
);
}
Widget _content(AppLocalizations l10n) {
final repeaterName = _repeater?.name ?? '';
final children = <Widget>[];
if (_sortedRepeaters.isNotEmpty) {
final filter = _repeaterFilter.toLowerCase();
final searching = filter.isNotEmpty;
// Default view shows only repeaters with a stored path (the only ones
// that can answer). A search surfaces pathless matches too, but greyed
// out and non-selectable, so the user sees it exists and why it is
// blocked (D1 Option 1).
final filtered = _sortedRepeaters.where((r) {
if (!r.name.toLowerCase().contains(filter)) return false;
return searching || r.hasPath;
}).toList();
children.add(
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
l10n.setRegionScope_pathNote,
style: Theme.of(context).textTheme.bodySmall,
),
),
);
children.add(
TextField(
key: const Key('regionScopeRepeaterSearch'),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search),
hintText: l10n.setRegionScope_searchRepeaters,
),
onChanged: (v) => setState(() => _repeaterFilter = v),
),
);
children.add(
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: ListView(
shrinkWrap: true,
children: [
for (final r in filtered)
ListTile(
dense: true,
enabled: r.hasPath,
leading: const Icon(Icons.cell_tower),
title: Text(r.name),
subtitle: r.hasPath ? null : Text(l10n.setRegionScope_noPath),
trailing: identical(r, _repeater)
? const Icon(Icons.check)
: null,
selected: identical(r, _repeater),
onTap: r.hasPath ? () => setState(() => _repeater = r) : null,
),
],
),
),
);
children.add(
Align(
alignment: Alignment.centerLeft,
child: TextButton.icon(
key: const Key('regionScopeDiscover'),
icon: const Icon(Icons.travel_explore),
label: Text(l10n.setRegionScope_discover),
onPressed:
(widget.service.isLoading ||
_repeater == null ||
!_repeater!.hasPath)
? null
: _discover,
),
),
);
children.add(const Divider(height: 1));
}
switch (widget.service.status) {
case RegionDiscoveryStatus.loading:
children.add(
const Padding(
padding: EdgeInsets.all(12),
child: Center(child: CircularProgressIndicator()),
),
);
case RegionDiscoveryStatus.timeout:
children.add(Text(l10n.discoverRegions_timeout(repeaterName)));
case RegionDiscoveryStatus.error:
children.add(
Text(widget.service.errorMessage ?? l10n.discoverRegions_error),
);
case RegionDiscoveryStatus.empty:
children.add(Text(l10n.discoverRegions_empty(repeaterName)));
case RegionDiscoveryStatus.idle:
case RegionDiscoveryStatus.success:
break;
}
children.add(
ListTile(
key: const Key('regionScopeNone'),
title: Text(l10n.setRegionScope_none),
trailing: _selected == null ? const Icon(Icons.check) : null,
selected: _selected == null,
onTap: () => setState(() => _selected = null),
),
);
// Current scope first (so it stays visible even before a re-discovery),
// then the discovered regions, alpha-sorted, deduped by name.
final names = <String>{};
if (widget.currentScope != null) names.add(widget.currentScope!);
final discovered = widget.service.regions.map((r) => r.name).toList()
..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()));
names.addAll(discovered);
for (final name in names) {
children.add(
ListTile(
title: Text(name),
trailing: _selected == name ? const Icon(Icons.check) : null,
selected: _selected == name,
onTap: () => setState(() => _selected = name),
),
);
}
return SingleChildScrollView(
child: Column(mainAxisSize: MainAxisSize.min, children: children),
);
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save

Powered by TurnKey Linux.