diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0b362774..96fb3534 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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 }} diff --git a/.github/workflows/flutter_dart.yml b/.github/workflows/flutter_dart.yml index d8123689..9f7f4a53 100644 --- a/.github/workflows/flutter_dart.yml +++ b/.github/workflows/flutter_dart.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 02f15b87..d0a08899 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/android/app/src/main/kotlin/com/meshcore/meshcore_open/AppExitInfoFunctions.kt b/android/app/src/main/kotlin/com/meshcore/meshcore_open/AppExitInfoFunctions.kt new file mode 100644 index 00000000..0c0dcd5b --- /dev/null +++ b/android/app/src/main/kotlin/com/meshcore/meshcore_open/AppExitInfoFunctions.kt @@ -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>(), + ), + ) + 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> { + // 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 { + val record = mutableMapOf( + "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) { + 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("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. + } + } + } + } +} diff --git a/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt index 27136ea1..a13128f8 100644 --- a/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt +++ b/android/app/src/main/kotlin/com/meshcore/meshcore_open/MainActivity.kt @@ -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() } } diff --git a/discord/1.7.0.md b/discord/1.7.0.md new file mode 100644 index 00000000..6f25ee1a --- /dev/null +++ b/discord/1.7.0.md @@ -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 diff --git a/docs/initiatives/standalone/812-region-scoping/OUTCOMES.md b/docs/initiatives/standalone/812-region-scoping/OUTCOMES.md new file mode 100644 index 00000000..ad706d72 --- /dev/null +++ b/docs/initiatives/standalone/812-region-scoping/OUTCOMES.md @@ -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) diff --git a/docs/initiatives/standalone/812-region-scoping/PLAN.md b/docs/initiatives/standalone/812-region-scoping/PLAN.md new file mode 100644 index 00000000..3864c14b --- /dev/null +++ b/docs/initiatives/standalone/812-region-scoping/PLAN.md @@ -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. diff --git a/docs/initiatives/standalone/853-radio-profile-isolation/PLAN.md b/docs/initiatives/standalone/853-radio-profile-isolation/PLAN.md new file mode 100644 index 00000000..e53fee95 --- /dev/null +++ b/docs/initiatives/standalone/853-radio-profile-isolation/PLAN.md @@ -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_` 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_` 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_` 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. diff --git a/docs/initiatives/standalone/917-storage-save-path/PLAN.md b/docs/initiatives/standalone/917-storage-save-path/PLAN.md new file mode 100644 index 00000000..6f7ab634 --- /dev/null +++ b/docs/initiatives/standalone/917-storage-save-path/PLAN.md @@ -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. diff --git a/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md b/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md new file mode 100644 index 00000000..2f087abb --- /dev/null +++ b/docs/initiatives/standalone/962-stale-blob-reclamation/PLAN.md @@ -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 | diff --git a/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html b/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html new file mode 100644 index 00000000..1aa65721 --- /dev/null +++ b/docs/initiatives/standalone/962-stale-blob-reclamation/epic-b-storage-mockups.html @@ -0,0 +1,168 @@ + + + + +Storage card mockups + + + + +

Storage card and clear confirmation (Epic B, #966)

+

Material 3, light scheme, blue seed, as main.dart 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: 70.9 MB database, 47 migrated keys, 40 with a stale copy, 29,975 messages, about 16.6 MB reclaimable. Bullets under each card are the behaviour to build. Owner-approved 2026-10-23: all variants as drawn, and the label stays Clear Stale History Now rather than "Compact" — 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.

+ +

Where it lives

+
+

1App Settings, bottom of the pane

A new Storage 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.

+
‹App Settings
+
+
Cyrillic to Latin
Transliterate incoming Cyrillic text.
+
Storage
Message database: 70.9 MB
+
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.
+Clear Stale History Now
+
+
  • Last card, so a destructive action is never the first thing under a thumb.
  • Size is read on build and after any clear. A failure to read it hides the row, never blocks the button (variant 7).
  • Same widget on Windows; only the column width differs.
+
+ +

The card's states, as built today

+
+ +

2Working

The button disables and relabels while the sweep runs. A second tap in the same frame is also refused in code, because setState only schedules a rebuild.

+
Storage
Message database: 70.9 MB
+
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.
+Clearing...
+
  • Two concurrent sweeps would mean two concurrent VACUUMs.
  • Re-enables on success and on failure, or the action works exactly once per launch.
+ +

3Cleared

Count and bytes returned, and the size row updates to what the sweep actually left behind rather than the number it started with.

+
Storage
Message database: 54.3 MB
+
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.
+Clear Stale History Now +
Cleared 40 old copies, 16.6 MB returned.
+
  • Bytes come from SQLite either side of the sweep, not from adding up blob lengths.
  • Pressing again is harmless: those keys have no copy left, so it reports nothing to clear.
+ +

4Cleared, with something kept back

A key whose rows could not be verified keeps its copy and is reported, not merely logged. This is the case the Epic exists for.

+
Storage
Message database: 54.3 MB
+
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.
+Clear Stale History Now +
Cleared 39 old copies, 16.2 MB returned.
+
Kept 1 that could not be verified. Your messages are intact; nothing was deleted for those.
+
  • Shown even when a refusal is the reason nothing was cleared, which is the most important case to surface, not the least.
  • The automatic 30-day sweep stays log-only: nobody is watching it.
  • Which keys and which records are named in the durable audit, not on screen.
+ +

5Nothing to clear

The ordinary state for anyone who has already swept, or who has no migrated history yet.

+
Storage
Message database: 54.3 MB
+
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.
+Clear Stale History Now +
Nothing to clear.
+
  • Says so plainly rather than showing a zero-byte success.
+ +

6Failed

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.

+
Storage
Message database: 70.9 MB
+
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.
+Clear Stale History Now +
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.
+
  • No exception text on screen; the reason goes to the log and the audit.
+ +

7Size unreadable

A size we cannot read is not a reason to block clearing, so the row is left out and the action stays live.

+
Storage
+
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.
+Clear Stale History Now
+
  • Logged as a warning, never surfaced as an error.
+ +
+ +

Proposed: confirm before deleting

+

None of this exists. It needs a preview pass 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.

+
+ +

8Confirm, the normal case

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.

+
+
Clear stale history?
+
This removes 40 old copies of history that has already moved to the new format, freeing about 16.6 MB.
+
Your messages are not affected. All 29,975 stay.
+
This cannot be undone.
+
CancelClear 40 copies
+
+
  • Counts come from a real preview pass, not an estimate.
  • Cancel is the plain text button and sits left, so the destructive one is never the default target.
  • Dismissing by tapping outside or back cancels.
+ +

9Confirm, with a forecast refusal

If the preview already knows a key cannot be verified, say so before the press rather than reporting it afterwards.

+
+
Clear stale history?
+
This removes 39 old copies of history that has already moved to the new format, freeing about 16.2 MB.
+
Your messages are not affected. All 29,975 stay.
+
1 copy will be kept back because its messages could not be verified. This cannot be undone.
+
CancelClear 39 copies
+
+
  • The count in the button excludes what will be kept, so it matches what actually goes.
  • A refusal discovered only at delete time still reports after the fact, as variant 4.
+ +

10Nothing eligible, no dialog

With nothing to clear there is nothing to confirm, so the press reports straight away rather than opening a dialog to say "zero".

+
Storage
Message database: 54.3 MB
+
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.
+Clear Stale History Now +
Nothing to clear.
+
  • The preview runs on the press. Empty result means no dialog at all.
  • So the preview must be cheap enough to run on a tap: it reads and verifies, it does not write.
+ +

11Label: the open question

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.

+
Storage
Message database: 70.9 MB
+
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.
+Compact now
+
  • "Compact" is what VACUUM does and reads less alarming; "Clear Stale History" says what is removed.
  • Owner's call. Either way the dialog in variant 8 states the scope.
+ +
+ diff --git a/docs/initiatives/standalone/975-settings-restructure/settings-location-mockups.html b/docs/initiatives/standalone/975-settings-restructure/settings-location-mockups.html new file mode 100644 index 00000000..485a0545 --- /dev/null +++ b/docs/initiatives/standalone/975-settings-restructure/settings-location-mockups.html @@ -0,0 +1,280 @@ + + + + +Location screen and settings restructure mockups + + + + + + +

Location screen and settings restructure (client #969, epic #975)

+

Material 3 blue seed, light, drawn at 390×844 against the real widgets: SettingsShell renders each category as a ListTile with a leading Icon, a subtitle and a trailing chevron under a centred AppBar, and detail panes are Cards of ListTiles split by Divider(height: 1). Icon choices match settings_screen.dart; they are drawn here as inline SVG so this file needs no network to render. Values are examples; the bullets are the behavior to build. GPS mode rides firmware 0xC5 sub-codes 0x0D / 0x0E, gated on caps byte 2 0x20 (meshcore-firmware#1789). Owner-approved 2026-10-23 Approved as drawn: 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. Corrected 2026-10-24: wire facts only (the command is 0xC5, not a new 0xC7; the buzzer-only example boards; the sleep-interval floor). The design is unchanged.

+ +

The Location screen, one control and three states

+ +

1GPS off

The selector is the only on/off control. The status row goes quiet and the sleep row is gone, because neither has meaning here.

+
+
Location
+
+
+
GPS
+
Off
On
Power save
+
+
GPS is off
Showing the last stored position
Query
+
+
+
Coordinates
39.103118, -84.512020
+
+
Position reporting interval
Every 15 minutes
+
+
+
  • Off writes gps.en = 0 and leaves the mode byte untouched, matching gpsStoredModeForPick.
  • So Off then On returns to Power save, not to continuous On. That property is why this is one control and not two.
  • Coordinates stay editable with GPS off; they are the manual fallback.
+ +

2GPS on

Continuous acquisition. The sleep row stays hidden: it governs Power save only, and a dead row invites someone to set it.

+
+
Location
+
+
+
GPS
+
Off
On
Power save
+
+
GPS is on
Fix 2 minutes ago, 3 satellites
Query
+
+
+
Coordinates
39.103118, -84.512020
+
+
Position reporting interval
Every 15 minutes
+
+
+
  • On writes gps.en = 1 and gps.mode = 1 together, the way setGpsMode() does on the device.
  • A stored 0xFF (never set) also displays as On, per gpsModeFromPrefs.
  • This is the costly state: about 48 mA, roughly 1.8 days on a 3000 mAh cell against 6.8 days with GPS off.
+ +

3Power save, backed off

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.

+
+
Location
+
+
+
GPS
+
Off
On
Power save
+
+
Backed off
Next try in 48 min, last fix 2 min ago
Query
+
+
Sleep between fix attempts
Firmware default, minimum 5 minutes
+
+
+
Coordinates
39.103118, -84.512020
+
+
Position reporting interval
Every 15 minutes
+
+
+
  • Power save writes gps.en = 1 and gps.mode = 2.
  • Backed off must be named. 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.
  • 0 is a legal value meaning firmware default, so the reporting-interval rule that rejects anything under 60 must not be copied onto this field.
  • 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.
  • No tuned default is offered: every measured indoor attempt at 30 minutes and beyond failed to acquire (firmware #1553).
+ +

4A build that cannot do Power save

Most variants do not compile the duty cycle. The third option is absent rather than offered and ignored.

+
+
Location
+
+
+
GPS
+
Off
On
+
+
GPS is on
Fix 2 minutes ago, 3 satellites
Query
+
+
+
Coordinates
39.103118, -84.512020
+
+
Position reporting interval
Every 15 minutes
+
+
+
  • OFFBAND_GPS_POWER_SAVE is opt-in per variant and today is set only on the QCC badge.
  • The device guards its own screen with gpsPowerSaveAvailable() so it never offers a mode nothing drives. The client needs the same signal.
  • Firmware sends it as ps_ok in every GPS reply, so Power save is hidden per radio rather than per firmware version. The caps bit 0x20 alone would not do: a radio can speak the GPS sub-codes without the duty cycle.
+ +
+ +

Where it lives

+ +

5Settings, current and proposed

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.

+
+ +
Current
+
+
Settings
+
+
Node Settings
+
Radio Settings
Frequency, power, spreading factor
+
Radio stats
Noise floor, RSSI, SNR, and airtime
+
Privacy Settings
Control what information is shared.
+
Contacts
Settings for how contacts are added.
+
Blocked
Users you've blocked
+
Message Settings
Notifications and message handling
+
App Settings
Appearance, translation, and map preferences
+
Device Info
+
+ +
Proposed
+
+
Settings
+
+
Node Settings
+
Radio Settings
Frequency, power, spreading factor
+
Locationnew
GPS, coordinates, and reporting
+
Radio statsunchanged for now
Noise floor, RSSI, SNR, and airtime
+
Privacy Settings
Control what information is shared.
+
Contacts
Settings for how contacts are added.
+
Blocked
Users you've blocked
+
Message Settings
Notifications and message handling
+
App Settings
Appearance, translation, and map preferences
+
Device Info
+
+ +
+
  • Location sits directly under Radio Settings and becomes the single home for GPS. The duplicate enable toggle in Node Settings goes away.
  • Radio stats stays for now by owner decision, to be revisited (#980). It is also reachable from the app-bar icon.
  • Category order otherwise unchanged; Observer still appears conditionally and is not drawn here.
+ +

6Button and buzzer split across two panes

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.

+
+ +
Node Settings keeps the button
+
+
Node Settings
+
+
Node name
Strycher
+
+
Button actions
Assign what the button does
+
+
+ +
Message Settings gains the buzzer
+
+
Message Settings
+
+
Notifications
When this phone alerts you
+
+
Buzzer and tonesnew
When this radio beeps, and which tone
+
+
+ +
+
  • Button actions stay under Node Settings. Buzzer and tones move beside Notifications, which Message Settings already advertises in its subtitle.
  • Split apart, each half needs its own capability gate: a buzzer-only radio must show tones and hide button actions.
  • Gates: Button actions on caps byte 2 0x02, Buzzer and tones on 0x01. 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.
+ +
+ +

Why these choices, so a later change knows what it is breaking

+
+

One three-way control, not a toggle plus a picker

The badge's own screen does exactly this: setGpsMode() at MyMesh.h:458 writes both fields, and gpsEnabledForMode 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.

+

One status row, not two

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 ListTile between the selector and the coordinates.

+

Sleep interval is not the reporting interval

gps_interval is a reporting cadence; gps_ps_interval_s is a power duty cycle (NodePrefs.h:73-78). They live in different cards so the difference is visible, and are never merged.

+

Deferred, tracked separately

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.

+
+
+

The save reply must echo what was stored

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 0xC5 GPS reply carries the stored values after every write.

+

Power save is hidden where the build cannot drive it

OFFBAND_GPS_POWER_SAVE is per variant and currently only on the QCC badge. The GPS reply's ps_ok byte says whether this radio can run it; without that, the client would offer a mode that does nothing.

+
+ + diff --git a/docs/initiatives/standalone/975-settings-restructure/tones-screen-parity-mockups.html b/docs/initiatives/standalone/975-settings-restructure/tones-screen-parity-mockups.html new file mode 100644 index 00000000..df8c018c --- /dev/null +++ b/docs/initiatives/standalone/975-settings-restructure/tones-screen-parity-mockups.html @@ -0,0 +1,362 @@ + + + + +Badge settings parity mockups + + + + + + +

Badge settings, reachable from the app (client #970, #971, #975)

+

Material 3 blue seed, light, drawn at 390×844 against the real widgets. Wire: 0xC5 as of meshcore-firmware 3e788e2a (#1801, branch epic/1788-client-settings, running on QCC2), read 2026-10-25 in OffbandConfigProtocol.h; badge screens read in BadgeScreens.cpp, BadgeLayout.h, TimeZones.h, BatteryGauge.h at the same commit. Supersedes the #970 slot mockup sent 2026-10-24. Values are examples; the bullets are the behavior to build. Built under #970, #971, #986 and #987. APPROVED 2026-10-25

+ +

The badge's screens against the app

+ + + + + + + + + + + + + + + +
Badge screen and rowWire (0xC5 sub-code, caps byte 2)App beforeApp after this
Tones › Sound (All, Self, None)0x01/0x02, 0x01Buzzer and tonesunchanged (frame 2)
Tones › DM, Channel, Room, New contact, Ack, Sent0x0F/0x10 EVTONE, 0x10missingsix rows + picker (frames 2, 4)
Each picker: Silent, Chime, Kerplop, Tick, Bloop, Drop, Knock, filled slotssame "picker's rule" on every setmissingone shared picker (frames 4, 7)
Picker plays each tune as you move0x11 TUNE_PLAY, 0x10missingplay button per row (frames 3, 4, 5)
Tones › Custom: all eight slots, named or "(empty)"0x09 SLOT_GET, 0x10missingslot list (frame 3)
Custom › edit a slot (keyboard)0x12 SLOT_READ + 0x0A SLOT_SET, 0x10missingeditor, prefilled (frame 6)
Channel's own tone, with Default0x0B/0x0C CHTUNE, 0x10codec built, no screen"Radio tone" in the channel sheet (frame 7)
Settings › Nav text, Message text0x13 GET, 0x14 TEXT_SET, 0x40missingScreen page (frame 8)
Settings › Screen off (15 s, 30 s, 1 m, 2 m, 5 m)0x15 SCROFF_SET, 0x40missingScreen page (frame 8)
Settings › Time zone (40 zones plus "not set", which shows ages)0x16 TZ_SET, 0x40missingzone list (frame 9)
Settings › Battery: 100% point, Set 100% here, Back to auto0x17 BATT_SET, 0x40missingBattery page (frames 10, 11)
Settings › GPS0x0D/0x0E, 0x20Location (#977)unchanged
Settings › Hibernate, Device pagesnot settings (AmberForge 1350): an action and a navigationn/an/a
+

One caps change to carry into the code already written: 0x10 is now TUNES (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 0x01 without 0x10 and keeps today's scope-only screen.

+ +

Buzzer and tones

+ +

1Node Settings gains Screen and Battery

The badge's own hardware settings sit with Button actions, gated on 0x40. A radio without it shows today's card.

+
+
Node Settings
+
+
Node name
QCC2
+
+
Button actions
Assign what the button does
+
+
Screen
Text size, screen off, time zone
+
+
Battery
100% at 4150 mV, learned
+
+
Public key
a1f3 07c2 9e44 … 5b10
+
+
+
  • Both rows appear only on a radio advertising caps byte 2 0x40. Today that means firmware built with the Offband screen set; a display fitted to a pyramid badge with that firmware gets them.
  • Battery's subtitle is the SCREEN_GET reply: the 100% point and where it came from, in the badge's words (default, learned, set).
  • Placement: owner decision 1.
+ +

2The scope, then the six tones

The badge's Tones screen, in its order: Sound first, because nothing below can sound while it says None.

+
+
Buzzer and tones
+
Device notification scope
+
All
Beep for any received message
+
Self
Beep only for direct messages and @[mentions]
+
None
Never beep
+
Tones
+
What this radio plays for each event.
+
DM
Chime (radio default)
+
Channel
Kerplop (radio default)
+
Room
Mario
+
New contact
Bloop
+
Ack
Silent
+
Sent
Silent (radio default)
+
+
  • Labels are the badge's own (kToneEventRows): DM, Channel, Room, New contact, Ack, Sent. DM is one tone for every direct message; there is no per-contact choice (#983 withdrawn).
  • Each subtitle is the effective byte from EVTONE_GET. When stored is 0xFF it adds "(radio default)", so a choice and a default never look alike.
  • The tones section exists only with caps 0x10. With 0x01 alone the screen is today's scope rows.
+ +

3Custom tunes, every slot

Scrolled down. All eight slots are rows, as on the badge: an empty slot is where you go to fill one.

+
+
Buzzer and tones
+
Sent
Silent (radio default)
+
Custom tunes
+
Eight tunes stored on this radio, in RTTTL. A saved tune can be picked for any event or channel.
+
1 Mario
142 characters
+
2 Zelda
96 characters
+
3 (empty)
Tap to add a tune
+
4 (empty)
Tap to add a tune
+
5 Nokia
58 characters
+
6 (empty)
Tap to add a tune
+
7 (empty)
Tap to add a tune
+
8 (empty)
Tap to add a tune
+
+
  • "1 Mario" / "3 (empty)" is the badge's own label shape. Names and lengths are SLOT_GET replies, one per slot, read when the screen opens.
  • The play button sends TUNE_PLAY with the slot's id (8 + slot). Empty slots have none: there is nothing to hear.
  • Tap a row to edit it (frame 6).
+ +

4Pick a tone, hear it first

One picker for all six events, with the badge's list. Play auditions on the radio; tapping the name chooses it.

+
+
Buzzer and tones
+
+
+
DM tone
+
Plays for every direct message.
+
Silent
+
Chime
Now playing for DMs
+
Kerplop
+
Tick
+
Bloop
+
Drop
+
Knock
+
Your tunes
+
Mario
+
Zelda
+
Nokia
+
Cancel
+
+
+
  • 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.
  • Tapping a name sends EVTONE_SET; the dialog closes and the row changes only on the radio's reply, which carries stored and effective.
  • No Default row. Firmware refuses 0xFF on an event, as the badge's own picker offers none (owner decision 3).
  • "Now playing" marks the effective tune, as the badge marks it "now".
+ +

5Why a preview made no sound

The radio says why it refused. The app says it in words, as the badge does with "Buzzer: OFF".

+
+
Buzzer and tones
+
Device notification scope
+
All
Beep for any received message
+
Self
Beep only for direct messages and @[mentions]
+
None
Never beep
+
Custom tunes
+
1 Mario
142 characters
+
Sound is off on this radio. Set the scope to All or Self to hear it.OK
+
+
  • TUNE_PLAY result 2 (sound off): this message, which stays until OK.
  • Result 1 (something more important is sounding): "The radio is playing a notification. Try again in a moment."
  • Result 0: nothing shown. The sound is the confirmation.
+ +

6Edit a slot, starting from what is there

The editor reads the stored tune back first, so a filled slot opens with its text and can be changed, not only replaced.

+
+
Slot 1
+
+
RTTTL
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
+
Plays as "Mario"142 / 240
+
Clear slotPlay savedSave
+
+
Read from the radio: 142 of 142 characters
+
+
  • Opening sends SLOT_READ at offset 0, then again at offset + bytes while more is 1. The field is read-only and shows this bar until the read completes.
  • Typing is checked live with firmware's own rtttlProblem() and its words ("b= must be 1 or more"); Save stays disabled while there is a problem. Saving is the chunked SLOT_SET, then a re-read.
  • Play saved 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.
  • Clear sends the empty commit, after a confirm.
+ +

7A channel's tone names its Default

The channel sheet's "Radio tone" picker (#971), now able to say what Default plays, the way the badge shows "Default Kerplop".

+
+
Channels
+
+
+
Radio tone
+
#okimesh
+
Default
Kerplop, the radio's channel tone
+
+
Silent
+
Chime
+
Kerplop
+
Tick
+
Bloop
+
Drop
+
Knock
+
Your tunes
+
Mario
+
Zelda
+
+
+
  • 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.
  • Default's subtitle is the Channel event's effective tune from EVTONE_GET ev 1, so it names a real tune rather than "follows the radio".
  • Empty slots are hidden here too: firmware now refuses an empty slot for a channel (3e788e2a), which settles the first #971 question.
  • The row also sits in the channel chat screen's menu, from the same widget.
+ +
+ +

Screen and Battery

+ +

8Screen

The badge's Nav text, Message text and Screen off rows, with the same choices and no others.

+
+
Screen
+
Text size
+
Menus and lists
+
LargeMediumSmall
+
Messages
+
LargeMediumSmall
+
Screen off
+
How long the screen stays on after the last key press.
+
15 s30 s1 m2 m5 m
+
Time zone
+
Eastern
UTC-4 now. Message times show as clock times.
+
+
  • Every control is the SCREEN_GET reply; each change sends its SET and the controls redraw from the 14-byte re-read reply, never from the tap.
  • "Menus and lists" is the badge's Nav text, "Messages" its Message text (owner decision 4).
  • Screen off offers exactly the five steps firmware accepts. When scr_stored is 0 (compiled default), no segment is selected and the line reads "Board default: 1 m" from scr_secs; picking a step replaces it and there is no way back to 0, on the badge or here.
+ +

9Time zone

The badge's 40 zones, its "not set", and a suggestion: the badge suggests from GPS, the app from the phone.

+
+
Time zone
+
Search zones
+
Eastern
Matches this phone
UTC-4
+
+
not set
Messages show their age
+
UTC
UTC+0
+
Eastern
Current
UTC-4
+
Central
UTC-5
+
Mountain
UTC-6
+
Arizona
UTC-7
+
Pacific
UTC-7
+
+
  • The list is a copy of TimeZones.h kZones, 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.
  • Offsets are computed with the zone's own daylight rule (US, EU, or none), as the badge's picker shows them.
  • "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 TZ_SET like any row.
  • "not set" is storable (index 0), as on the badge.
+ +

10Battery

The badge's Battery screen: where 100% is, how it got there, and its two actions.

+
+
Battery
+
96%
+
Reading 4120 mV
+
+
100% at 4150 mV
Learned after a full charge
+
+
The radio learns where full is after a complete charge. Set it by hand only if the bar never reaches 100% when charged.
+
Set 100% hereBack to auto
+
+
  • The 100% point and its source (default, learned, set by hand) are the batt_stored, batt_full and batt_pinned bytes; the reading and percent are the battery report the app already receives.
  • Set 100% here sends BATT_SET 1: the radio pins its own current reading, as the badge does. A confirm says "Only do this with the radio fully charged."
  • Back to auto sends BATT_SET 0, shown only when something is learned or pinned.
+ +

11Refused, with the radio's reason

The radio refuses a reading that is not a plausible full cell, and says which way it is wrong.

+
+
Battery
+
Not charged yet. Charge the radio fully, then set 100% again. Nothing was changed.
+
71%
+
Reading 3890 mV
+
+
100% at 4200 mV
Default for this board
+
+
Set 100% here
+
+
  • ERR_BATT_NOT_CHARGED (9): this message. ERR_BATT_TOO_HIGH (8): "The reading is higher than a full cell, so it was not used."
  • The existing persistent _ErrorBanner: it stays until dismissed.
  • Back to auto is absent: nothing is learned or pinned, matching the badge, which hides it then.
+ +
+ +

Owner decisions, 2026-10-25

+
+

1. Screen and Battery under Node Settings

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.

+

2. Play is a separate button

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.

+

3. No way back to "radio default"

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.

+

4. "Menus and lists" and "Messages"

The badge says "Nav text" and "Message text", which fit 21 columns. The app has room to say what each governs.

+
+ +

Why these choices

+
+

The radio is the record, everywhere

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.

+

The app offers exactly what the badge offers

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.

+
+ + diff --git a/docs/initiatives/upstream-1180-interop/CLASSIFIER-CONTRACT.md b/docs/initiatives/upstream-1180-interop/CLASSIFIER-CONTRACT.md new file mode 100644 index 00000000..a6e5b156 --- /dev/null +++ b/docs/initiatives/upstream-1180-interop/CLASSIFIER-CONTRACT.md @@ -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) diff --git a/docs/initiatives/upstream-1180-interop/INVESTIGATION.md b/docs/initiatives/upstream-1180-interop/INVESTIGATION.md new file mode 100644 index 00000000..9f9dacc0 --- /dev/null +++ b/docs/initiatives/upstream-1180-interop/INVESTIGATION.md @@ -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: ` ` actions + `get|set .`. 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 (`-` 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) diff --git a/docs/initiatives/upstream-1180-interop/PLAN.md b/docs/initiatives/upstream-1180-interop/PLAN.md new file mode 100644 index 00000000..d6b4a046 --- /dev/null +++ b/docs/initiatives/upstream-1180-interop/PLAN.md @@ -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) diff --git a/lib/connector/cli_command_codec.dart b/lib/connector/cli_command_codec.dart new file mode 100644 index 00000000..0942ac51 --- /dev/null +++ b/lib/connector/cli_command_codec.dart @@ -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 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); +} diff --git a/lib/connector/device_population.dart b/lib/connector/device_population.dart new file mode 100644 index 00000000..b3802972 --- /dev/null +++ b/lib/connector/device_population.dart @@ -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 + /// `-` ("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; + } +} diff --git a/lib/connector/meshcore_connector.dart b/lib/connector/meshcore_connector.dart index 3cdfb2c6..b46f7240 100644 --- a/lib/connector/meshcore_connector.dart +++ b/lib/connector/meshcore_connector.dart @@ -29,6 +29,7 @@ import '../helpers/cayenne_lpp.dart'; import '../helpers/path_helper.dart'; import '../services/app_debug_log_service.dart'; import '../services/ble_debug_log_service.dart'; +import '../services/storage_service.dart'; import '../services/linux_ble_error_classifier.dart'; import '../services/linux_ble_pairing_service_stub.dart' if (dart.library.io) '../services/linux_ble_pairing_service.dart'; @@ -45,6 +46,7 @@ import '../services/queue_sync_file_log_stub.dart' if (dart.library.io) '../services/queue_sync_file_log_io.dart'; import 'meshcore_connector_usb.dart'; import 'meshcore_connector_tcp.dart'; +import 'reconnect_policy.dart'; import '../storage/channel_message_store.dart'; import '../storage/channel_order_store.dart'; import '../storage/channel_settings_store.dart'; @@ -59,8 +61,14 @@ import '../utils/app_logger.dart'; import '../utils/battery_utils.dart'; import '../utils/platform_info.dart'; import 'meshcore_uuids.dart'; +import 'cli_command_codec.dart'; +import 'device_population.dart'; import 'meshcore_protocol.dart'; +import '../helpers/region_key.dart'; +import '../storage/channel_region_scope_store.dart'; import 'offband_device_ui.dart'; +import 'offband_screen_settings.dart'; +import 'offband_tones.dart'; import 'caplog_reassembler.dart'; class DirectRepeater { @@ -341,7 +349,19 @@ class MeshCoreConnector extends ChangeNotifier { int _radioStatsPollRefCount = 0; final ValueNotifier radioStatsNotifier = ValueNotifier(null); - int _reconnectAttempts = 0; + final ReconnectPolicy _reconnectPolicy = ReconnectPolicy(); + + /// True while the BLE connect in flight was started by the automatic retry, + /// not by the user. A user connect may abandon it; it may not abandon a + /// user's. (#997) + bool _autoReconnectInFlight = false; + + /// True once the retry budget ran out, until the user connects again. (#997) + bool _autoReconnectGaveUp = false; + + /// Bumped whenever a BLE connect starts or is abandoned. An attempt that + /// finds it changed has been superseded and must stop touching shared state. + int _connectGeneration = 0; bool _notifyListenersDirty = false; static const Duration _notifyListenersDebounce = Duration(milliseconds: 50); @@ -384,12 +404,35 @@ class MeshCoreConnector extends ChangeNotifier { String? _firmwareVersion; String? _deviceModel; int? _offbandCaps; + + /// Listeners for RESP_CODE_CLI_REPLY (29) frames (#882). The connector only + /// routes; correlation and timeouts live in LocalCliService. + final List _cliReplyListeners = []; + + /// Registers [listener] for CLI replies; returns the detach callback. + void Function() addCliReplyListenerForLocalCli( + void Function(CliReply) listener, + ) { + _cliReplyListeners.add(listener); + return () => _cliReplyListeners.remove(listener); + } + + Classification? _classification; int? _offbandCaps2; bool? _femLnaEnabled; ButtonMatrix? _buttonMatrix; String? _lastDeviceUiSuppression; DeviceNotifyScope? _deviceNotifyScope; String? _deviceUiError; + DeviceUiSurface? _deviceUiErrorSurface; + DeviceUiSurface? _pendingDeviceUiWrite; + GpsModeState? _gpsModeState; + final Map _channelTunes = {}; + final Map _eventTones = {}; + final Map _tuneSlots = {}; + ScreenSettingsState? _screenSettings; + bool _tuneSlotTransferActive = false; + final List<_DeviceUiWaiter> _deviceUiWaiters = []; int _pathHashByteWidth = 1; CompanionRadioStats? _latestRadioStats; Stopwatch? _airtimeBumpStopwatch; @@ -530,6 +573,7 @@ class MeshCoreConnector extends ChangeNotifier { bool _channelSyncInFlight = false; Timer? _channelSyncTimeout; Timer? _channelsChangedDebounce; + Timer? _advertReconcileDebounce; int _channelSyncRetries = 0; int _nextChannelIndexToRequest = 0; int _totalChannelsToRequest = 0; @@ -552,11 +596,33 @@ class MeshCoreConnector extends ChangeNotifier { final MessageStore _messageStore = MessageStore(); final ChannelOrderStore _channelOrderStore = ChannelOrderStore(); final ChannelSettingsStore _channelSettingsStore = ChannelSettingsStore(); + final ChannelRegionScopeStore _channelRegionScopeStore = + ChannelRegionScopeStore(); final ContactSettingsStore _contactSettingsStore = ContactSettingsStore(); + + /// Custom names by pubkey hex, the in-memory mirror of what + /// `contact_settings_store` holds. (#750) + /// + /// Needed because `contact_store` deliberately does not persist the custom + /// name: that record is rebuilt from radio contact-sync data, so a save + /// after a sync would wipe it. The cost of keeping it out of there is that + /// the live `Contact` objects have to be reattached to it, which is what + /// [_withCustomName] does at every path that rebuilds one. + final Map _customNames = {}; + final ContactStore _contactStore = ContactStore(); final ContactDiscoveryStore _discoveryContactStore = ContactDiscoveryStore(); final ChannelStore _channelStore = ChannelStore(); final UnreadStore _unreadStore = UnreadStore(); + + /// Injected from `main()`, because `StorageService` is shared with + /// `PathHistoryService` and `TimeoutPredictionService` and so cannot be + /// owned here like the stores above. + /// + /// Needed since #854 and #856: path history and delivery observations are + /// per-radio now, so this service needs the device key on connect like + /// every other per-radio store. + StorageService? storageService; List _cachedChannels = []; final Map _channelCyr2LatEnabled = {}; final Map _channelCyr2LatProfileId = {}; @@ -689,6 +755,16 @@ class MeshCoreConnector extends ChangeNotifier { _activeTransport == MeshCoreTransportType.usb; bool get isAutoReconnectScheduled => _shouldAutoReconnect && (_reconnectTimer?.isActive ?? false); + + /// An automatic retry is scheduled or in flight. (#997) + bool get isAutoReconnecting => + _autoReconnectInFlight || isAutoReconnectScheduled; + int get autoReconnectAttempt => _reconnectPolicy.attempts; + int get autoReconnectMaxAttempts => _reconnectPolicy.maxAttempts; + bool get autoReconnectGaveUp => _autoReconnectGaveUp; + + /// The radio the automatic retry is aimed at, for the status bar. + String? get autoReconnectTargetName => _lastDeviceDisplayName; String? get activeTcpEndpoint => _tcpConnector.activeEndpoint; bool get isTcpTransportConnected => _state == MeshCoreConnectionState.connected && @@ -846,6 +922,11 @@ class MeshCoreConnector extends ChangeNotifier { /// null on older firmware that sends a shorter frame. int? get offbandCaps => _offbandCaps; + /// Population verdict from the last device-info reply (#875/#876); null + /// before one arrives. Capability decisions route through this, never + /// through bare ver-code or frame-offset reads. + Classification? get classification => _classification; + /// Second `offband_caps` bitfield (frame offset 84, firmware #508). Null when /// the frame is too short, which means "no byte-2 capabilities" and is never /// an error: every radio predating #508 reports null here. (#480) @@ -857,6 +938,41 @@ class MeshCoreConnector extends ChangeNotifier { /// Whether this radio exposes a settable device notification scope (#475). bool get supportsNotifyScope => firmwareSupportsNotifyScope(_offbandCaps2); + /// Whether this radio answers the `0xC5` GPS-mode sub-codes (#969). Says + /// nothing about Power save, which [GpsModeState.powerSaveAvailable] answers. + bool get supportsGpsMode => firmwareSupportsGpsMode(_offbandCaps2); + + /// Last GPS state the radio reported, or null if not read yet. + GpsModeState? get gpsModeState => _gpsModeState; + + /// Whether this radio answers the `0xC5` tune sub-codes: custom slots, + /// channel tune, event tones and preview (caps byte 2 `0x10`). + bool get supportsTunes => firmwareSupportsTunes(_offbandCaps2); + + /// Whether this radio answers the screen-settings sub-codes (#987). + bool get supportsScreenSettings => + firmwareSupportsScreenSettings(_offbandCaps2); + + /// The tune the radio reported for [channel], or null if not read yet. + ChannelTune? channelTuneFor(int channel) => _channelTunes[channel]; + + /// The tune the radio reported for [event], or null if not read yet. + EventToneState? eventTone(ToneEvent event) => _eventTones[event]; + + /// `SLOT_GET` replies read so far, by slot index. + Map get tuneSlots => Map.unmodifiable(_tuneSlots); + + /// The radio's screen and battery settings, or null if not read yet. + ScreenSettingsState? get screenSettings => _screenSettings; + + /// True while a slot is being read or saved. One at a time: firmware takes + /// one push per slot, and a second would displace the first. + bool get tuneSlotTransferActive => _tuneSlotTransferActive; + + /// Which surface [deviceUiError] belongs to, so a screen shows only its own. + /// Null when the error could not be attributed to an outstanding write. + DeviceUiSurface? get deviceUiErrorSurface => _deviceUiErrorSurface; + /// Whether this radio answers the 0xC6 packet-hash query (#524/#611). bool get supportsPktHash => firmwareSupportsPktHash(_offbandCaps2, _firmwareVerCode); @@ -891,6 +1007,7 @@ class MeshCoreConnector extends ChangeNotifier { void clearDeviceUiError() { if (_deviceUiError == null) return; _deviceUiError = null; + _deviceUiErrorSurface = null; notifyListeners(); } @@ -956,6 +1073,8 @@ class MeshCoreConnector extends ChangeNotifier { return; } _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.buttonMatrix; _appDebugLogService?.info( 'matrix SET -> ${sequence.label} = ${action.label} ' '[0xC5][0x04][0x${sequence.code.toRadixString(16).padLeft(2, '0')}]' @@ -981,6 +1100,8 @@ class MeshCoreConnector extends ChangeNotifier { return; } _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.notifyScope; _appDebugLogService?.info( 'scope SET -> ${scope.label} ' '[0xC5][0x02][0x${scope.code.toRadixString(16).padLeft(2, '0')}]', @@ -989,6 +1110,368 @@ class MeshCoreConnector extends ChangeNotifier { await sendFrame(buildNotifyScopeSetFrame(scope)); } + /// Ask the radio which tune [channel] plays (#971). + Future requestChannelTune(int channel) async { + if (!_deviceUiGateOpen('chtune GET', advertised: supportsTunes)) { + return; + } + _appDebugLogService?.info( + 'chtune GET -> [0xC5][0x0B][$channel]', + tag: 'DeviceUI', + ); + await sendFrame(buildChannelTuneGetFrame(channel)); + } + + /// Set which tune [channel] plays. Local state follows the device's re-read + /// reply, never the request, so a refused choice is never shown as saved. + Future setChannelTune(int channel, ChannelTune tune) async { + if (!_deviceUiGateOpen('chtune SET', advertised: supportsTunes)) { + return; + } + _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.channelTune; + _appDebugLogService?.info( + 'chtune SET -> ch=$channel stored=${tune.stored} ' + '(${tune.inherits + ? 'inherit' + : tune.isSilent + ? 'silent' + : 'tune ${tune.tuneId}'}) ' + '[0xC5][0x0C]', + tag: 'DeviceUI', + ); + await sendFrame(buildChannelTuneSetFrame(channel, tune)); + } + + /// Ask the radio how GPS is running (#969). + Future requestGpsMode() async { + if (!_deviceUiGateOpen('gps GET', advertised: supportsGpsMode)) return; + _appDebugLogService?.info('gps GET -> [0xC5][0x0D]', tag: 'DeviceUI'); + await sendFrame(buildGpsModeGetFrame()); + } + + /// Set how GPS runs, and optionally the Power-save interval. + /// + /// The interval always travels with the mode on the wire, so when + /// [intervalSeconds] is omitted the radio's current interval is resent. That + /// needs a state read first: sending an interval the client does not know + /// would silently reset the user's, so without one this refuses, visibly. + /// As with the other surfaces, local state follows the device's reply only. + Future setGpsMode(GpsMode mode, {int? intervalSeconds}) async { + if (!_deviceUiGateOpen('gps SET', advertised: supportsGpsMode)) return; + final interval = intervalSeconds ?? _gpsModeState?.intervalSeconds; + if (interval == null || interval < 0 || interval > 0xFFFFFFFF) { + _deviceUiErrorSurface = DeviceUiSurface.gpsMode; + _deviceUiError = interval == null + ? 'GPS settings have not been read from the radio yet. Try again.' + : 'That interval is out of range'; + _appDebugLogService?.warn( + 'gps SET suppressed: ${interval == null ? 'state not read, interval unknown' : 'interval $interval out of range'}', + tag: 'DeviceUI', + ); + notifyListeners(); + return; + } + _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.gpsMode; + _appDebugLogService?.info( + 'gps SET -> mode=${mode.name} interval=${interval}s ' + '[0xC5][0x0E][0x${mode.code.toRadixString(16).padLeft(2, '0')}]', + tag: 'DeviceUI', + ); + await sendFrame(buildGpsModeSetFrame(mode, interval)); + } + + /// Send [frame] and wait for the reply [matches] accepts, or for a refusal + /// attributed to [surface]. Null on timeout. + /// + /// The multi-frame flows (slot read, slot save) and preview need the answer + /// before their next step; the single-frame settings do not, and keep the + /// fire-and-forget shape the rest of this command uses. + Future _sendDeviceUiAndAwait( + Uint8List frame, + DeviceUiSurface surface, + bool Function(OffbandUiReply reply) matches, { + Duration timeout = const Duration(seconds: 4), + }) async { + final waiter = _DeviceUiWaiter(surface, matches); + _deviceUiWaiters.add(waiter); + _pendingDeviceUiWrite = surface; + try { + await sendFrame(frame); + return await waiter.completer.future.timeout( + timeout, + onTimeout: () => null, + ); + } finally { + _deviceUiWaiters.remove(waiter); + // Answered or not, this request is no longer outstanding, so a later + // refusal must not be pinned on it. + if (_pendingDeviceUiWrite == surface) _pendingDeviceUiWrite = null; + } + } + + /// Hand [reply] to the first waiter that wants it. A refusal carries no + /// sub-code, so it goes to the waiter on the surface it was attributed to. + void _offerDeviceUiReply(OffbandUiReply reply, {DeviceUiSurface? errorOn}) { + for (final w in _deviceUiWaiters) { + final wanted = reply.isError + ? errorOn != null && w.surface == errorOn + : w.matches(reply); + if (wanted && !w.completer.isCompleted) { + w.completer.complete(reply); + return; + } + } + } + + void _setDeviceUiError(DeviceUiSurface surface, String message) { + _deviceUiErrorSurface = surface; + _deviceUiError = message; + _appDebugLogService?.warn('${surface.name}: $message', tag: 'DeviceUI'); + notifyListeners(); + } + + /// Read all six event tones (#986). + Future requestEventTones() async { + if (!_deviceUiGateOpen('evtone GET', advertised: supportsTunes)) return; + for (final event in ToneEvent.values) { + await sendFrame(buildEventToneGetFrame(event)); + } + } + + /// Set the tune [event] plays. The id must be one the picker offers; the + /// radio refuses the rest, and the row changes only on its re-read reply. + Future setEventTone(ToneEvent event, int tuneId) async { + if (!_deviceUiGateOpen('evtone SET', advertised: supportsTunes)) return; + _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.eventTone; + _appDebugLogService?.info( + 'evtone SET -> ${event.label} = $tuneId [0xC5][0x10]', + tag: 'DeviceUI', + ); + await sendFrame(buildEventToneSetFrame(event, tuneId)); + } + + /// Audition [tuneId] on the radio. Null when the radio did not answer, or + /// refused the id (the refusal is then shown like any other). + Future playTune(int tuneId) async { + if (!_deviceUiGateOpen('play', advertised: supportsTunes)) return null; + // A refusal names no sub-code, so a preview sent mid-transfer could take + // the transfer's refusal, or hand it one. + if (_tuneSlotTransferActive) return null; + _appDebugLogService?.info('play -> $tuneId [0xC5][0x11]', tag: 'DeviceUI'); + final reply = await _sendDeviceUiAndAwait( + buildTunePlayFrame(tuneId), + DeviceUiSurface.tunePlay, + (r) => r.tunePlay?.tuneId == tuneId, + ); + final result = reply?.tunePlay?.result; + _appDebugLogService?.info( + 'play reply: ${result?.name ?? (reply == null ? 'no answer' : 'refused')}', + tag: 'DeviceUI', + ); + return result; + } + + /// Read every slot's name and length (#970). + Future requestTuneSlots() async { + if (!_deviceUiGateOpen('slot GET', advertised: supportsTunes)) return; + for (var slot = 0; slot < tuneSlotCount; slot++) { + await sendFrame(buildSlotGetFrame(slot)); + } + } + + /// A slot's whole stored tune, read in chunks, or null if the read failed. + /// [onProgress] reports bytes read so far. + Future readTuneSlot( + int slot, { + void Function(int bytesRead)? onProgress, + }) async { + if (!_deviceUiGateOpen('slot READ', advertised: supportsTunes)) { + return null; + } + if (_tuneSlotTransferActive) return null; + _tuneSlotTransferActive = true; + notifyListeners(); + try { + final out = []; + while (true) { + final offset = out.length; + final reply = await _sendDeviceUiAndAwait( + buildSlotReadFrame(slot, offset), + DeviceUiSurface.tuneSlot, + (r) => r.slotChunk?.slot == slot && r.slotChunk?.offset == offset, + ); + final chunk = reply?.slotChunk; + if (chunk == null) { + if (reply == null) { + _setDeviceUiError( + DeviceUiSurface.tuneSlot, + 'The radio did not answer while reading this tune.', + ); + } + return null; + } + out.addAll(chunk.bytes); + onProgress?.call(out.length); + if (!chunk.more) break; + // A chunk that says more but carries nothing would loop forever. + if (chunk.bytes.isEmpty || out.length > maxSlotRtttl) { + _setDeviceUiError( + DeviceUiSurface.tuneSlot, + 'The radio sent this tune in a shape the app cannot read.', + ); + return null; + } + } + _appDebugLogService?.info( + 'slot READ: slot=$slot ${out.length} bytes', + tag: 'DeviceUI', + ); + return latin1.decode(out); + } finally { + _tuneSlotTransferActive = false; + notifyListeners(); + } + } + + /// Save [rtttl] to [slot] in chunks sized to the transport, then re-read the + /// slot. An empty [rtttl] clears it. True only when the radio committed it. + /// + /// The radio replaces a slot only on the final chunk, so a push that fails + /// partway leaves the old tune intact. A displaced push (`ERR_SLOT_OFFSET`) + /// restarts from 0 once; a second refusal stops and is shown. + Future saveTuneSlot( + int slot, + String rtttl, { + void Function(int bytesSent, int total)? onProgress, + }) async { + if (!_deviceUiGateOpen('slot SET', advertised: supportsTunes)) { + return false; + } + if (_tuneSlotTransferActive) return false; + final bytes = latin1.encode(rtttl); + if (bytes.length > maxSlotRtttl) { + _setDeviceUiError( + DeviceUiSurface.tuneSlot, + 'A tune can be at most $maxSlotRtttl characters.', + ); + return false; + } + _deviceUiError = null; + _deviceUiErrorSurface = null; + _tuneSlotTransferActive = true; + notifyListeners(); + try { + final chunkSize = math.max(1, effectiveMaxFrameSize - 5); + for (var attempt = 0; attempt < 2; attempt++) { + final outcome = await _pushTuneSlot(slot, bytes, chunkSize, onProgress); + if (outcome == _SlotPush.committed) { + _deviceUiError = null; + _deviceUiErrorSurface = null; + await _sendDeviceUiAndAwait( + buildSlotGetFrame(slot), + DeviceUiSurface.tuneSlot, + (r) => r.tuneSlot?.slot == slot, + ); + _appDebugLogService?.info( + 'slot SET committed: slot=$slot ${bytes.length} bytes', + tag: 'DeviceUI', + ); + return true; + } + if (outcome != _SlotPush.displaced) return false; + } + return false; + } finally { + _tuneSlotTransferActive = false; + notifyListeners(); + } + } + + Future<_SlotPush> _pushTuneSlot( + int slot, + List bytes, + int chunkSize, + void Function(int bytesSent, int total)? onProgress, + ) async { + var offset = 0; + do { + final end = math.min(offset + chunkSize, bytes.length); + final more = end < bytes.length; + final reply = await _sendDeviceUiAndAwait( + buildSlotSetFrame(slot, offset, more, bytes.sublist(offset, end)), + DeviceUiSurface.tuneSlot, + (r) => r.slotAccepted?.slot == slot, + ); + if (reply == null) { + _setDeviceUiError( + DeviceUiSurface.tuneSlot, + 'The radio did not answer while saving this tune. Nothing was ' + 'changed.', + ); + return _SlotPush.failed; + } + if (reply.isError) { + return reply.errorCode == ButtonConfigError.slotOffset.code + ? _SlotPush.displaced + : _SlotPush.failed; + } + // Mid-push the radio counts what it holds; anything but the end of this + // chunk means another push took over. + if (more && reply.slotAccepted!.accepted != end) { + return _SlotPush.displaced; + } + // A commit answers 0. Anything else is not a commit, whatever it is. + if (!more && reply.slotAccepted!.accepted != 0) { + _setDeviceUiError( + DeviceUiSurface.tuneSlot, + 'The radio did not confirm saving this tune. Nothing was changed.', + ); + return _SlotPush.failed; + } + offset = end; + onProgress?.call(offset, bytes.length); + } while (offset < bytes.length); + return _SlotPush.committed; + } + + /// Read the badge's screen and battery settings (#987). + Future requestScreenSettings() async { + if (!_deviceUiGateOpen('screen GET', advertised: supportsScreenSettings)) { + return; + } + await sendFrame(buildScreenSettingsGetFrame()); + } + + Future _sendScreenSet(String what, Uint8List frame) async { + if (!_deviceUiGateOpen(what, advertised: supportsScreenSettings)) return; + _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = DeviceUiSurface.screenSettings; + _appDebugLogService?.info('$what -> $frame', tag: 'DeviceUI'); + await sendFrame(frame); + } + + Future setTextSize(BadgeTextTarget target, BadgeTextSize size) => + _sendScreenSet('text SET', buildTextSizeSetFrame(target, size)); + + /// [seconds] must be one of [screenOffSteps]; the radio refuses the rest. + Future setScreenOff(int seconds) => + _sendScreenSet('scroff SET', buildScreenOffSetFrame(seconds)); + + Future setTimeZone(int index) => + _sendScreenSet('tz SET', buildTimeZoneSetFrame(index)); + + /// Pin the radio's own current reading as 100%, or hand the full point back + /// to auto-learn. The radio refuses a reading that is not a full cell. + Future setBatteryFull({required bool pin}) => + _sendScreenSet('batt SET', buildBatteryFullSetFrame(pin: pin)); + /// Re-read whatever headless-UI state this radio supports. Called after every /// device-info reply so a scope changed by triple-press on the device is /// never displayed stale, and so frame-arrival order does not matter. (#475) @@ -1002,11 +1485,21 @@ class MeshCoreConnector extends ChangeNotifier { _lastDeviceUiSuppression = null; _deviceNotifyScope = null; _deviceUiError = null; + _deviceUiErrorSurface = null; + _pendingDeviceUiWrite = null; + _gpsModeState = null; + _channelTunes.clear(); + _eventTones.clear(); + _tuneSlots.clear(); + _screenSettings = null; } void _reconcileDeviceUi() { if (supportsButtonMatrix) requestButtonMatrix(); if (supportsNotifyScope) requestNotifyScope(); + if (supportsGpsMode) requestGpsMode(); + // Node Settings names the battery full point in its Battery row. + if (supportsScreenSettings) requestScreenSettings(); } /// Single entry point for `0xC5`: both surfaces and the shared error sub-code @@ -1022,19 +1515,188 @@ class MeshCoreConnector extends ChangeNotifier { return; } final scope = parseNotifyScopeReply(frame); - if (scope != null) _handleNotifyScopeReply(scope); + if (scope != null) { + _handleNotifyScopeReply(scope); + return; + } + final gps = parseGpsModeReply(frame); + if (gps != null) { + _handleGpsModeReply(gps); + return; + } + final tune = parseChannelTuneReply(frame); + if (tune != null) { + _handleChannelTuneReply(tune); + return; + } + final tunes = parseTuneReply(frame); + if (tunes != null) { + _handleTuneReply(tunes); + return; + } + final screen = parseScreenSettingsReply(frame); + if (screen != null) { + _handleScreenSettingsReply(screen); + return; + } + _appDebugLogService?.warn( + '0xC5 reply not understood (sub=0x' + '${frame.length > 1 ? frame[1].toRadixString(16).padLeft(2, '0') : '??'}, ' + 'len=${frame.length})', + tag: 'DeviceUI', + ); } - void _handleButtonMatrixReply(OffbandUiReply reply) { + /// A `0x7F` refusal. The frame names no sub-code, so it is attributed to the + /// write outstanding when it arrived; a refusal with none is still shown and + /// logged, just not claimed by any one screen. + void _handleDeviceUiError(OffbandUiReply reply) { + final surface = _pendingDeviceUiWrite; + _pendingDeviceUiWrite = null; + _deviceUiErrorSurface = surface; + _deviceUiError = + surface == DeviceUiSurface.gpsMode && reply.errorCode != null + ? describeGpsError(reply.errorCode!) + : reply.errorMessage; + final what = switch (surface) { + DeviceUiSurface.buttonMatrix => 'Button config', + DeviceUiSurface.notifyScope => 'Notification scope', + DeviceUiSurface.gpsMode => 'GPS mode', + DeviceUiSurface.channelTune => 'Channel tune', + DeviceUiSurface.eventTone => 'Event tone', + DeviceUiSurface.tunePlay => 'Tune preview', + DeviceUiSurface.tuneSlot => 'Tune slot', + DeviceUiSurface.screenSettings => 'Screen settings', + null => 'Device UI request', + }; + _appDebugLogService?.warn( + '$what refused: $_deviceUiError' + '${reply.errorDetail == null ? '' : ' (detail ${reply.errorDetail})'}', + tag: 'DeviceUI', + ); + _offerDeviceUiReply(reply, errorOn: surface); + notifyListeners(); + } + + void _handleTuneReply(OffbandUiReply reply) { if (reply.isError) { + _setDeviceUiError(DeviceUiSurface.eventTone, reply.errorMessage!); + return; + } + if (_pendingDeviceUiWrite == DeviceUiSurface.eventTone && + reply.sub == offbandUiEventToneSet) { + _pendingDeviceUiWrite = null; + } + final ev = reply.eventTone; + if (ev != null) { + _eventTones[ev.event] = ev.state; + _appDebugLogService?.info( + 'evtone reply: ${ev.event.label} stored=${ev.state.stored} ' + 'effective=${ev.state.effective}', + tag: 'DeviceUI', + ); + } + final slot = reply.tuneSlot; + if (slot != null && slot.slot >= 0 && slot.slot < tuneSlotCount) { + _tuneSlots[slot.slot] = slot.info; + } + _offerDeviceUiReply(reply); + notifyListeners(); + } + + void _handleScreenSettingsReply(OffbandUiReply reply) { + if (_pendingDeviceUiWrite == DeviceUiSurface.screenSettings && + reply.sub != offbandUiScreenGet) { + _pendingDeviceUiWrite = null; + } + final s = reply.screen!; + _screenSettings = s; + _appDebugLogService?.info( + 'screen reply: nav=${s.navText?.name} msg=${s.messageText?.name} ' + 'scroff=${s.screenOffStored}/${s.screenOffSeconds}s tz=${s.timeZone} ' + 'batt=${s.batteryFullStored}/${s.batteryFullMv}mV ' + 'pinned=${s.batteryPinned}', + tag: 'DeviceUI', + ); + notifyListeners(); + } + + void _handleChannelTuneReply(OffbandUiReply reply) { + final t = reply.channelTune; + if (t == null) { + // Not reachable today: parseChannelTuneReply always carries a value. + _appDebugLogService?.warn('chtune reply with no value', tag: 'DeviceUI'); + return; + } + final isWrite = reply.sub == offbandUiChannelTuneSet; + if (isWrite && _pendingDeviceUiWrite == DeviceUiSurface.channelTune) { + _pendingDeviceUiWrite = null; + } + _channelTunes[t.channel] = t.tune; + _appDebugLogService?.info( + 'chtune reply: ch=${t.channel} stored=${t.tune.stored} ' + '(${isWrite ? 'write confirmed' : 'read'})', + tag: 'DeviceUI', + ); + notifyListeners(); + } + + void _handleGpsModeReply(OffbandUiReply reply) { + if (reply.isError) { + _deviceUiErrorSurface = DeviceUiSurface.gpsMode; _deviceUiError = reply.errorMessage; _appDebugLogService?.warn( - 'Button config refused: ${reply.errorMessage}', + 'GPS mode reply rejected: ${reply.errorMessage}', tag: 'DeviceUI', ); notifyListeners(); return; } + final g = reply.gps; + if (g == null) { + // Not reachable today: parseGpsModeReply returns an error reply whenever + // it cannot build a state. Checked rather than asserted across files. + _appDebugLogService?.warn('gps reply with no state', tag: 'DeviceUI'); + return; + } + final isWrite = reply.sub == offbandUiGpsSet; + if (isWrite && _pendingDeviceUiWrite == DeviceUiSurface.gpsMode) { + _pendingDeviceUiWrite = null; + } + _gpsModeState = g; + _appDebugLogService?.info( + 'gps reply: mode=${g.mode.name} ' + 'stored=0x${g.storedMode.toRadixString(16).padLeft(2, '0')} ' + 'ps_ok=${g.powerSaveAvailable ? 1 : 0} ' + 'activity=${g.activity?.name ?? 'unknown'} ' + 'interval=${g.intervalSeconds}s wait=${g.waitSeconds}s ' + '(${isWrite ? 'write confirmed' : 'read'})', + tag: 'DeviceUI', + ); + // The radio's gps_enabled is what this reply resolved, and the legacy + // `gps` custom var mirrors it. Keep the mirror honest so the 0xC1 poll + // follows a mode change made here, but never invent the var on a radio + // that did not report one. + final vars = _currentCustomVars; + if (vars != null && vars.containsKey('gps')) { + final enabled = g.mode == GpsMode.off ? '0' : '1'; + if (vars['gps'] != enabled) { + vars['gps'] = enabled; + _reconcileGpsPolling(); + } + } + notifyListeners(); + } + + void _handleButtonMatrixReply(OffbandUiReply reply) { + if (reply.isError) { + _handleDeviceUiError(reply); + return; + } + if (_pendingDeviceUiWrite == DeviceUiSurface.buttonMatrix && + reply.sub == offbandUiMatrixSet) { + _pendingDeviceUiWrite = null; + } if (reply.matrix != null) { final m = reply.matrix!; _appDebugLogService?.info( @@ -1066,7 +1728,12 @@ class MeshCoreConnector extends ChangeNotifier { } void _handleNotifyScopeReply(OffbandUiReply reply) { + if (_pendingDeviceUiWrite == DeviceUiSurface.notifyScope && + reply.sub == offbandUiScopeSet) { + _pendingDeviceUiWrite = null; + } if (reply.isError) { + _deviceUiErrorSurface = DeviceUiSurface.notifyScope; _deviceUiError = reply.errorMessage; _appDebugLogService?.warn( 'Notification scope refused: ${reply.errorMessage}', @@ -1575,6 +2242,64 @@ class MeshCoreConnector extends ChangeNotifier { notifyListeners(); } + /// Reattaches the stored custom name to [contact], if the user set one. + /// + /// Call this anywhere a `Contact` is built from the radio or from + /// `contact_store`, because neither source carries the custom name. Paths + /// that use `copyWith` on an EXISTING contact do not need it: `copyWith` + /// preserves `customName` unless `clearCustomName` is passed. (#750) + /// Loads the stored custom names for [keys] into [_customNames] in one pass. + /// + /// Batched rather than per-contact for the reason documented on + /// `_ensureContactCyr2LatSettingLoaded`: a notify per contact rebuilds the + /// tree twice per contact, and each rebuild walks the contact list. + Future _loadCustomNames(Iterable keys) async { + final loaded = await Future.wait([ + for (final key in keys) + _contactSettingsStore + .loadCustomName(key) + .then((name) => MapEntry(key, name)), + ]); + for (final entry in loaded) { + final name = entry.value; + if (name != null && name.trim().isNotEmpty) { + _customNames[entry.key] = name; + } + } + } + + Contact _withCustomName(Contact contact) { + final custom = _customNames[contact.publicKeyHex]; + if (custom == null) return contact; + return contact.copyWith(customName: custom); + } + + /// The user's label for a contact, or null. Read by the contacts UI. + String? customNameFor(String contactKeyHex) => _customNames[contactKeyHex]; + + /// Sets or clears the user's label for a contact. + /// + /// Null, empty and whitespace-only all clear it, matching `Contact.name` and + /// the store, so a user who deletes the field's text cannot end up with a + /// blank name and no way back. (T34b, T34c) + Future setContactCustomName(String contactKeyHex, String? name) async { + final cleaned = (name == null || name.trim().isEmpty) ? null : name; + if (cleaned == null) { + _customNames.remove(contactKeyHex); + } else { + _customNames[contactKeyHex] = cleaned; + } + await _contactSettingsStore.saveCustomName(contactKeyHex, cleaned); + + final index = _contacts.indexWhere((c) => c.publicKeyHex == contactKeyHex); + if (index >= 0) { + _contacts[index] = cleaned == null + ? _contacts[index].copyWith(clearCustomName: true) + : _contacts[index].copyWith(customName: cleaned); + } + notifyListeners(); + } + Future setContactCyr2LatEnabled( String contactKeyHex, bool enabled, @@ -1720,9 +2445,17 @@ class MeshCoreConnector extends ChangeNotifier { _knownContactKeys ..clear() ..addAll(cached.map((c) => c.publicKeyHex)); + // Custom names first, so the contacts below are hydrated with them in one + // pass rather than rebuilt a second time. Without this a restart silently + // loses every rename the user made, because contact_store does not hold + // them on purpose. (#750, T35) + // Cleared first: custom names are per radio, so a switch must not carry the + // previous radio's labels onto contacts both radios hold. (#750, T37) + _customNames.clear(); + await _loadCustomNames(cached.map((c) => c.publicKeyHex)); _contacts ..clear() - ..addAll(cached); + ..addAll(cached.map(_withCustomName)); // Load every contact's settings without notifying per contact, then // notify once. Per-contact notification rebuilt the whole tree 2x per // contact (600 rebuilds for 300 contacts), and each rebuild walks the @@ -2296,6 +3029,10 @@ class MeshCoreConnector extends ChangeNotifier { required String portName, int baudRate = 115200, }) async { + if (_autoReconnectInFlight) { + await _abandonAutoReconnect('USB connect to $portName started'); + } + await _awaitDisconnectInFlight('USB connect to $portName'); if (_state == MeshCoreConnectionState.connecting || _state == MeshCoreConnectionState.connected) { _appDebugLogService?.warn( @@ -2382,6 +3119,10 @@ class MeshCoreConnector extends ChangeNotifier { } Future connectTcp({required String host, required int port}) async { + if (_autoReconnectInFlight) { + await _abandonAutoReconnect('TCP connect to $host:$port started'); + } + await _awaitDisconnectInFlight('TCP connect to $host:$port'); if (_state == MeshCoreConnectionState.connecting || _state == MeshCoreConnectionState.connected) { _appDebugLogService?.warn( @@ -2511,6 +3252,11 @@ class MeshCoreConnector extends ChangeNotifier { (activeTransport != MeshCoreTransportType.tcp || !tcpManagerConnected); } + /// Sets the self public key so tests can drive the incoming-message path, + /// which bails when no self identity is known. + @visibleForTesting + void setSelfPublicKeyForTest(Uint8List key) => _selfPublicKey = key; + @visibleForTesting static bool shouldResetStateAfterTcpConnectAbort({ required MeshCoreConnectionState state, @@ -2524,15 +3270,38 @@ class MeshCoreConnector extends ChangeNotifier { BluetoothDevice device, { String? displayName, Future Function()? linuxPairingPinProvider, + }) => _connectBle( + device, + displayName: displayName, + linuxPairingPinProvider: linuxPairingPinProvider, + auto: false, + ); + + Future _connectBle( + BluetoothDevice device, { + String? displayName, + Future Function()? linuxPairingPinProvider, + required bool auto, }) async { + final attemptLabel = displayName ?? device.remoteId.toString(); + if (!auto && _autoReconnectInFlight) { + await _abandonAutoReconnect('Connect to $attemptLabel started'); + } + await _awaitDisconnectInFlight('Connect to $attemptLabel'); if (_state == MeshCoreConnectionState.connecting || _state == MeshCoreConnectionState.connected) { + _appDebugLogService?.warn( + 'connect ignored: already $_state', + tag: 'BLE Connect', + ); return; } + final generation = _beginConnectAttempt(auto: auto); _activeTransport = MeshCoreTransportType.bluetooth; await stopScan(); + if (generation != _connectGeneration) return; _setState(MeshCoreConnectionState.connecting); _device = device; _deviceId = device.remoteId.toString(); @@ -2546,7 +3315,6 @@ class MeshCoreConnector extends ChangeNotifier { _lastDeviceDisplayName = _deviceDisplayName; _manualDisconnect = false; _bleReleaseUnconfirmed = false; - _cancelReconnectTimer(); _bleInitialSyncStarted = false; if (PlatformInfo.isWeb) { _resetConnectionHandshakeState(); @@ -2566,6 +3334,7 @@ class MeshCoreConnector extends ChangeNotifier { _notifySubscription = null; await _mtuSubscription?.cancel(); _mtuSubscription = null; + _throwIfSuperseded(generation); _connectionSubscription = device.connectionState.listen((state) { if (state == BluetoothConnectionState.disconnected && isConnected) { _handleDisconnection(); @@ -2758,6 +3527,7 @@ class MeshCoreConnector extends ChangeNotifier { // message byte budget recover from the 20-byte floor once the real value // is known (#592). await _mtuSubscription?.cancel(); + _throwIfSuperseded(generation); _mtuSubscription = device.mtu.listen((mtu) { _appDebugLogService?.info('MTU now: $mtu', tag: 'BLE Connect'); _logComposerBudget('mtu'); @@ -2792,6 +3562,7 @@ class MeshCoreConnector extends ChangeNotifier { } } + _throwIfSuperseded(generation); BluetoothService? uartService; for (var service in services) { if (service.uuid.toString().toLowerCase() == MeshCoreUuids.service) { @@ -2863,6 +3634,7 @@ class MeshCoreConnector extends ChangeNotifier { } } } + _throwIfSuperseded(generation); _notifySubscription = _txCharacteristic!.onValueReceived.listen( _handleFrame, onError: (error, stackTrace) { @@ -2871,6 +3643,8 @@ class MeshCoreConnector extends ChangeNotifier { }, ); + _autoReconnectInFlight = false; + _cancelReconnectTimer(); _setState(MeshCoreConnectionState.connected); if (_shouldGateInitialChannelSync) { _hasReceivedDeviceInfo = false; @@ -2878,6 +3652,17 @@ class MeshCoreConnector extends ChangeNotifier { } await _startBleInitialSync(); } catch (e) { + if (e is _ConnectSuperseded || generation != _connectGeneration) { + // Stop, or a newer connect, took over. Whoever did that already tore + // this attempt down; touching state now would clobber theirs. (#997) + // attemptLabel, not _deviceDisplayName: by now a newer connect may + // have overwritten that with its own radio's name. + _appDebugLogService?.info( + 'Connect to $attemptLabel abandoned: superseded', + tag: 'BLE Connect', + ); + return; + } _appDebugLogService?.error('Connection error: $e', tag: 'BLE Connect'); final errorText = e.toString(); final lowerErrorText = errorText.toLowerCase(); @@ -3167,6 +3952,36 @@ class MeshCoreConnector extends ChangeNotifier { unawaited(service.loadForDevice(key == null ? null : pubKeyToHex(key))); } + /// Drops the identity that scopes every per-radio store, so a read before + /// the next radio's SELF_INFO returns nothing instead of the last radio's + /// data (#158). + /// + /// Every store below treats an empty key as "no radio": loads nothing, + /// writes nothing. That is deliberate and is the #754 precedent, so this is + /// a fail-closed reset rather than a cache invalidation. + /// + /// `_selfPublicKey` goes too, because `channels_screen` builds its own store + /// from `selfPublicKeyHex` rather than sharing these instances, so clearing + /// only the stores here would leave that path reading a stale prefix. + @visibleForTesting + void clearStorageScopeKeysForTest() => _clearStorageScopeKeys(); + + void _clearStorageScopeKeys() { + _selfPublicKey = null; + _channelMessageStore.setPublicKeyHex = ''; + _messageStore.setPublicKeyHex = ''; + _channelOrderStore.setPublicKeyHex = ''; + _channelSettingsStore.setPublicKeyHex = ''; + _channelRegionScopeStore.setPublicKeyHex = ''; + _contactSettingsStore.setPublicKeyHex = ''; + _contactStore.setPublicKeyHex = ''; + _channelStore.setPublicKeyHex = ''; + _unreadStore.setPublicKeyHex = ''; + _discoveryContactStore.setPublicKeyHex = ''; + storageService?.setPublicKeyHex = ''; + _applySelfKeyToBlockService(); + } + void _resetConnectionHandshakeState() { _selfPublicKey = null; _applySelfKeyToBlockService(); @@ -3197,6 +4012,20 @@ class MeshCoreConnector extends ChangeNotifier { void resetConnectionHandshakeStateForTest() => _resetConnectionHandshakeState(); + /// Scopes the contact stores to [radioKeyHex] and hydrates the cache, which + /// normally happens as part of the connect handshake. (#750) + @visibleForTesting + Future loadContactCacheForTest(String radioKeyHex) async { + _contactStore.setPublicKeyHex = radioKeyHex; + _contactSettingsStore.setPublicKeyHex = radioKeyHex; + await loadContactCache(); + } + + /// Scopes the contact settings store without a connect handshake. (#750) + @visibleForTesting + void setContactSettingsKeyForTest(String radioKeyHex) => + _contactSettingsStore.setPublicKeyHex = radioKeyHex; + /// Feeds a device frame through the normal dispatch, so parse paths can be /// exercised without a radio. (#578) @visibleForTesting @@ -3209,6 +4038,26 @@ class MeshCoreConnector extends ChangeNotifier { @visibleForTesting void setConnectedForTest() => _state = MeshCoreConnectionState.connected; + @visibleForTesting + void setAppDebugLogServiceForTest(AppDebugLogService service) => + _appDebugLogService = service; + + /// The state a BLE link leaves behind: a radio to go back to. (#997) + @visibleForTesting + void primeAutoReconnectForTest(String deviceId) { + _lastDeviceId = deviceId; + _lastDeviceDisplayName = deviceId; + _activeTransport = MeshCoreTransportType.bluetooth; + _manualDisconnect = false; + } + + /// Starts an automatic attempt through the real bookkeeping, without BLE. + @visibleForTesting + void beginAutoReconnectAttemptForTest() { + _beginConnectAttempt(auto: true); + _setState(MeshCoreConnectionState.connecting); + } + @visibleForTesting Map> get channelMessagesForTest => _channelMessages; @@ -3289,25 +4138,57 @@ class MeshCoreConnector extends ChangeNotifier { (_activeTransport == MeshCoreTransportType.bluetooth && PlatformInfo.isWeb); + /// Cancels a scheduled retry and starts a fresh retry budget. Only for a + /// user action or a successful connect, never for an automatic attempt: + /// that reset is what kept the delay at 1 s for hours (#995). void _cancelReconnectTimer() { _reconnectTimer?.cancel(); _reconnectTimer = null; - _reconnectAttempts = 0; + _reconnectPolicy.reset(); + _autoReconnectGaveUp = false; + } + + /// Bookkeeping at the start of every BLE connect. Returns the attempt's + /// generation, which it checks after each await. (#997) + int _beginConnectAttempt({required bool auto}) { + _autoReconnectInFlight = auto; + if (auto) { + _reconnectTimer?.cancel(); + _reconnectTimer = null; + } else { + _cancelReconnectTimer(); + } + return ++_connectGeneration; } - int _nextReconnectDelayMs() { - final attempt = _reconnectAttempts < 6 ? _reconnectAttempts : 6; - _reconnectAttempts += 1; - final delayMs = 1000 * (1 << attempt); - return delayMs > 30000 ? 30000 : delayMs; + /// Called after each await in a BLE connect that precedes a write to shared + /// connection state, so an abandoned attempt stops before it writes. + void _throwIfSuperseded(int generation) { + if (generation != _connectGeneration) throw const _ConnectSuperseded(); } void _scheduleReconnect() { if (!_shouldAutoReconnect) return; if (_reconnectTimer?.isActive == true) return; - final delayMs = _nextReconnectDelayMs(); - _reconnectTimer = Timer(Duration(milliseconds: delayMs), () async { + final target = _lastDeviceDisplayName ?? _lastDeviceId; + final delay = _reconnectPolicy.nextDelay(DateTime.now()); + if (delay == null) { + _autoReconnectGaveUp = true; + _appDebugLogService?.warn( + 'Auto-reconnect stopped: $target not reached after ' + '${_reconnectPolicy.attempts} attempt(s)', + tag: 'Connection', + ); + notifyListeners(); + return; + } + _appDebugLogService?.info( + 'Auto-reconnect attempt ${_reconnectPolicy.attempts} of ' + '${_reconnectPolicy.maxAttempts} to $target in ${delay.inSeconds}s', + tag: 'Connection', + ); + _reconnectTimer = Timer(delay, () async { if (!_shouldAutoReconnect) return; if (_state == MeshCoreConnectionState.connecting || _state == MeshCoreConnectionState.connected) { @@ -3322,18 +4203,99 @@ class MeshCoreConnector extends ChangeNotifier { if (device == null) return; try { - await connect(device, displayName: _lastDeviceDisplayName); + await _connectBle( + device, + displayName: _lastDeviceDisplayName, + auto: true, + ); } catch (_) { - _scheduleReconnect(); + // A failed attempt has already scheduled the next one, through + // disconnect(manual: false), or spent the budget. } }); + notifyListeners(); } + /// Ends an automatic retry, in flight or scheduled, so the user can act. + /// The attempt in flight sees its generation change and stops. (#997) + Future _abandonAutoReconnect(String reason) async { + _appDebugLogService?.info( + '$reason: abandoning automatic reconnect', + tag: 'Connection', + ); + _connectGeneration++; + final wasInFlight = _autoReconnectInFlight; + _autoReconnectInFlight = false; + if (wasInFlight) { + await disconnect(manual: true); + } else { + _manualDisconnect = true; + _cancelReconnectTimer(); + notifyListeners(); + } + } + + /// The status bar's Stop button: end an automatic retry now. (#997) + Future stopAutoReconnect() async { + if (!isAutoReconnecting && !_autoReconnectGaveUp) return; + await _abandonAutoReconnect('Stop pressed'); + } + + /// The status bar's Retry button after the retry gave up: a user connect to + /// the same radio, with a fresh budget. (#997) + Future retryLastDevice() async { + final device = + _lastDevice ?? + (_lastDeviceId == null ? null : BluetoothDevice.fromId(_lastDeviceId!)); + if (device == null) return; + await connect(device, displayName: _lastDeviceDisplayName); + } + + /// The disconnect in progress, if any. A connect waits for it, and a second + /// disconnect joins it, because its tail clears the device, name and state + /// and would wipe a connection started on top of it. (#997) + Future? _disconnectInFlight; + Future disconnect({ bool manual = true, bool skipBleDeviceDisconnect = false, + }) { + final inFlight = _disconnectInFlight; + if (inFlight != null) { + if (manual) { + // The running disconnect may be an automatic one that is about to + // schedule a retry; a manual caller means no retry. + _manualDisconnect = true; + _cancelReconnectTimer(); + } + return inFlight; + } + final running = _disconnect( + manual: manual, + skipBleDeviceDisconnect: skipBleDeviceDisconnect, + ); + _disconnectInFlight = running; + return running.whenComplete(() { + if (identical(_disconnectInFlight, running)) _disconnectInFlight = null; + }); + } + + Future _awaitDisconnectInFlight(String what) async { + final inFlight = _disconnectInFlight; + if (inFlight == null) return; + _appDebugLogService?.info( + '$what waiting for the previous disconnect to finish', + tag: 'Connection', + ); + await inFlight; + } + + Future _disconnect({ + required bool manual, + required bool skipBleDeviceDisconnect, }) async { if (_state == MeshCoreConnectionState.disconnecting) return; + _autoReconnectInFlight = false; final transportAtDisconnect = _activeTransport; final transportLabel = switch (transportAtDisconnect) { MeshCoreTransportType.bluetooth => 'BLE', @@ -3421,6 +4383,7 @@ class MeshCoreConnector extends ChangeNotifier { _deviceDisplayName = null; _deviceId = null; _contacts.clear(); + _customNames.clear(); // per radio: none may outlive the link (#750, T37b) _discoveredContacts.clear(); _conversations.clear(); _loadedConversationKeys.clear(); @@ -3432,7 +4395,18 @@ class MeshCoreConnector extends ChangeNotifier { _clientRepeat = null; _rememberedNonRepeatRadioState = null; _firmwareVerCode = null; + _classification = null; + // Capability bytes die with the connection, like the ver code above: a + // disconnect must not leave the previous radio's capabilities showing + // until the next device-info lands (Gemini review, task #876). + _offbandCaps = null; + _offbandCaps2 = null; + _femLnaEnabled = null; _blockListRetryTimer?.cancel(); + // Per-connection debounce timers must die with the connection so a timer + // scheduled against this radio can't fire against the next one (#838 review). + _advertReconcileDebounce?.cancel(); + _channelsChangedDebounce?.cancel(); _blockDumpInFlight = false; _blockKeysTouchedDuringDump.clear(); _firmwareVersion = null; @@ -3940,6 +4914,31 @@ class MeshCoreConnector extends ChangeNotifier { await getContacts(since: _latestContactLastmod(), preserveExisting: true); } + /// True when the connected radio's own auto-add policy covers this contact + /// type, i.e. the radio would have stored a new advert of this type (subject + /// to its hop/capacity limits, which only the radio enforces). Mirrors the + /// radio's type policy so a reconcile is nudged only when the radio might + /// actually hold something new. (#838) + bool _isAutoAddEligible(int type) => + (_autoAddUsers && type == advTypeChat) || + (_autoAddRepeaters && type == advTypeRepeater) || + (_autoAddRoomServers && type == advTypeRoom) || + (_autoAddSensors && type == advTypeSensor); + + /// Coalesce a burst of new adverts into a single incremental contact sync so + /// a node the radio actually added surfaces without a manual sync, while a + /// node it rejected simply never comes back in the stream. (#838) + static const Duration _advertReconcileWindow = Duration(milliseconds: 800); + + void _scheduleContactReconcile() { + if (!isConnected || _isLoadingContacts) return; + _advertReconcileDebounce?.cancel(); + _advertReconcileDebounce = Timer(_advertReconcileWindow, () { + if (!isConnected || _isLoadingContacts) return; + unawaited(refreshContactsSinceLastmod()); + }); + } + /// The latest short full sync, kept until dismissed or a complete sync. ContactSyncShortfall? get contactSyncShortfall => _contactSyncShortfall; @@ -4345,7 +5344,10 @@ class MeshCoreConnector extends ChangeNotifier { hashWidth: hashWidth, type: contact.type, flags: contact.flags, - name: contact.name, + // receivedName, never `.name`. The radio's contact table is the + // shared record of what this node calls itself; the user's label is + // ours alone and there is nowhere on the device to put it. (#750, T11) + name: contact.receivedName, ), ); // USB writes return instantly (no BLE flow control), so give the firmware @@ -4378,6 +5380,7 @@ class MeshCoreConnector extends ChangeNotifier { bool? teleBase, bool? teleLoc, bool? teleEnv, + bool? remoteCli, }) async { if (!isConnected) return; final latestContact = @@ -4402,6 +5405,11 @@ class MeshCoreConnector extends ChangeNotifier { ? (updatedFlags | contactFlagTeleEnv) : (updatedFlags & ~contactFlagTeleEnv)) : updatedFlags; + updatedFlags = remoteCli != null + ? (remoteCli + ? (updatedFlags | contactFlagRemoteCliAllowed) + : (updatedFlags & ~contactFlagRemoteCliAllowed)) + : updatedFlags; await sendFrame( buildUpdateContactPathFrame( @@ -4411,7 +5419,7 @@ class MeshCoreConnector extends ChangeNotifier { hashWidth: latestContact.pathHashWidth, type: latestContact.type, flags: updatedFlags, - name: latestContact.name, + name: latestContact.receivedName, // never `.name` (#750, T11) ), ); @@ -4421,7 +5429,9 @@ class MeshCoreConnector extends ChangeNotifier { if (index >= 0) { _contacts[index] = _contacts[index].copyWith( type: latestContact.type, - name: latestContact.name, + // Received, not `.name`: copying the getter would move one contact's + // custom name onto another's received field. (#750) + receivedName: latestContact.receivedName, pathLength: latestContact.pathLength, path: latestContact.path, flags: updatedFlags, @@ -4687,7 +5697,8 @@ class MeshCoreConnector extends ChangeNotifier { _pendingChannelSentQueue.add(reactionQueueId); await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); try { - await sendFrame( + await _sendChannelFrameScoped( + channel.index, buildSendChannelTextMsgFrame( channel.index, text, @@ -4729,7 +5740,8 @@ class MeshCoreConnector extends ChangeNotifier { final outboundText = prepareChannelOutboundText(channel.index, text); await _waitForRadioQuiet(lastInboundRxTime: _lastChannelMsgRxTime); try { - await sendFrame( + await _sendChannelFrameScoped( + channel.index, buildSendChannelTextMsgFrame( channel.index, outboundText, @@ -4758,6 +5770,86 @@ class MeshCoreConnector extends ChangeNotifier { } } + /// Send a channel frame, applying the channel's region scope on the wire if + /// one is configured (Feature #812, Epic #815). Fail-closed: a scoped channel + /// on firmware that cannot scope is blocked, never sent unscoped; the scope is + /// set before the send and cleared to the node default after. + Future _sendChannelFrameScoped( + int channelIndex, + Uint8List frame, { + String? channelSendQueueId, + bool expectsGenericAck = false, + }) async { + final regionName = await _channelRegionScopeStore.scopeFor(channelIndex); + if (regionName == null) { + await sendFrame( + frame, + channelSendQueueId: channelSendQueueId, + expectsGenericAck: expectsGenericAck, + ); + return; + } + if (!supportsRegionScope) { + throw StateError( + 'channel $channelIndex is region-scoped to "$regionName" but the ' + 'firmware does not support region scoping', + ); + } + final key = transportKeyForName(regionName); + if (key == null) { + throw StateError( + 'cannot derive a transport key for region "$regionName"', + ); + } + try { + // Inside the try so a lost ack on the set (the firmware may already have + // applied the scope) still runs the clear below, rather than leaking the + // scope onto the next unscoped send. + await setChannelSendScope(key); + await sendFrame( + frame, + channelSendQueueId: channelSendQueueId, + expectsGenericAck: expectsGenericAck, + ); + } finally { + try { + await clearSendScope(); + } catch (e) { + appLogger.warn( + 'failed to clear region send-scope after a channel send: $e', + tag: 'Region', + ); + } + } + } + + @visibleForTesting + ChannelRegionScopeStore get channelRegionScopeStoreForTest => + _channelRegionScopeStore; + + @visibleForTesting + Future sendChannelFrameScopedForTest( + int channelIndex, + Uint8List frame, + ) => _sendChannelFrameScoped(channelIndex, frame); + + /// The region name scoping [channelIndex], or null when unscoped (#815). + Future channelRegionScope(int channelIndex) => + _channelRegionScopeStore.scopeFor(channelIndex); + + /// Set (or, with null, clear) the region scope for [channelIndex] (#815). + Future setChannelRegionScope( + int channelIndex, + String? regionName, + ) async { + if (regionName == null) { + await _channelRegionScopeStore.clearScope(channelIndex); + } else { + await _channelRegionScopeStore.setScope(channelIndex, regionName); + } + notifyListeners(); + } + Future removeContact(Contact contact) async { if (!isConnected) return; @@ -4831,7 +5923,10 @@ class MeshCoreConnector extends ChangeNotifier { -1, type: stub.type, flags: 0, - name: stub.name, + // A card or QR stub carries the shared name as its received name, so + // this is unchanged in practice. Reading `.name` would still be wrong: + // a user could rename before the add completes. (#750, T13) + name: stub.receivedName, // The whole point of this path. Anything else here would trip the // firmware advert replay guard and leave the contact permanently deaf // to its own adverts. See buildUpdateContactPathFrame. (#620) @@ -4859,7 +5954,7 @@ class MeshCoreConnector extends ChangeNotifier { hashWidth: contact.pathHashWidth, type: contact.type, flags: contact.flags, - name: contact.name, + name: contact.receivedName, // never `.name` (#750, T11) lat: contact.latitude, lon: contact.longitude, lastModified: contact.lastSeen, @@ -4878,7 +5973,7 @@ class MeshCoreConnector extends ChangeNotifier { _handleContactAdvert( Contact( publicKey: contact.publicKey, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, @@ -5255,6 +6350,33 @@ class MeshCoreConnector extends ChangeNotifier { // Apply ordering and notify UI _applyChannelOrder(); notifyListeners(); + + // #839: one-time migration of the pre-per-radio notify state into THIS + // radio (the first synced after upgrade). The service guards itself with a + // persisted flag, so this is a no-op on every later sync and later radio. + _migrateLegacyChannelNotifyForThisRadio(); + } + + void _migrateLegacyChannelNotifyForThisRadio() { + final service = _appSettingsService; + if (service == null || service.settings.channelNotifyMigrated) return; + final prefix = selfPublicKeyHex; + if (prefix.isEmpty || _channels.isEmpty) return; + final pskByIndex = {}; + final pskByName = {}; + for (final channel in _channels) { + final psk = channel.pskHex; + if (psk.isEmpty) continue; + pskByIndex[channel.index] = psk; + pskByName[channel.name] = psk; + } + unawaited( + service.migrateLegacyChannelNotify( + devicePrefix: prefix, + pskByChannelIndex: pskByIndex, + pskByChannelName: pskByName, + ), + ); } void _cleanupChannelSync({required bool completed}) { @@ -5721,6 +6843,198 @@ class MeshCoreConnector extends ChangeNotifier { } } + // --- Region flood-scoping + regions discovery (Feature #812, Epic #813). + // Frames and parsers live in meshcore_protocol.dart; this is the connector + // wiring, modeled on the 0xC6 pkt-hash request/reply correlation above. + + Completer? _defaultFloodScopeCompleter; + + /// True iff the connected firmware supports region flood-scoping + discovery. + bool get supportsRegionScope => firmwareSupportsRegionScope(_firmwareVerCode); + + @visibleForTesting + void setFirmwareVerCodeForTest(int? value) => _firmwareVerCode = value; + void setOffbandCapsForTest(int? value) => _offbandCaps = value; + + @visibleForTesting + Message? parseContactMessageForTest(Uint8List frame) => + _parseContactMessage(frame); + + void _guardRegionScope() { + if (!supportsRegionScope) { + throw StateError('firmware does not support region scoping'); + } + } + + /// Discover the flood regions a reachable repeater advertises. Sends an anon + /// regions request to [repeaterPubKey] (32 bytes). + /// + /// Correlation: the firmware generates the anon-request tag and returns it in + /// the `RESP_CODE_SENT` ack; the repeater echoes that same tag in its `0x8C` + /// reply. So we learn the tag from the ack that follows our send, then match + /// the `0x8C` by it (the client cannot pick the tag, #836). Returns null on + /// timeout. Throws [StateError] when the firmware does not support region + /// scoping (fail-closed; callers gate the UI on [supportsRegionScope]). + Future discoverRegions({ + required Uint8List repeaterPubKey, + Duration timeout = const Duration(seconds: 10), + }) async { + _guardRegionScope(); + // One auto-retry: a single anon-request round-trip can drop over LoRa and a + // retry usually gets through; a genuinely unreachable repeater still ends in + // a timeout after both attempts (#836, D1 Option A). + for (var attempt = 0; attempt < 2; attempt++) { + final reply = await _discoverRegionsOnce(repeaterPubKey, timeout); + if (reply != null) return reply; + } + return null; + } + + Future _discoverRegionsOnce( + Uint8List repeaterPubKey, + Duration timeout, + ) async { + // Reply travels back along the repeater's own stored path (firmware routes + // it as-is), so a multi-hop repeater can answer. Empty => zero-hop. + final (replyPathLenByte, replyPath) = _regionReplyPathFor(repeaterPubKey); + final completer = Completer(); + int? tag; // firmware tag, learned from the RESP_CODE_SENT after we send + void finish(RegionsReply? reply) { + if (!completer.isCompleted) completer.complete(reply); + } + + Timer timer = Timer(timeout, () => finish(null)); + final sub = receivedFrames.listen((frame) { + if (frame.isEmpty) return; + if (tag == null && frame[0] == respCodeSent && frame.length >= 10) { + tag = readUint32LE(frame, 2); + // Re-arm to the firmware's own round-trip estimate (scales with hops), + // rather than a fixed guess, when it is larger than the floor. + final estMs = readUint32LE(frame, 6); + if (estMs > timeout.inMilliseconds) { + timer.cancel(); + timer = Timer( + Duration(milliseconds: estMs + 3000), + () => finish(null), + ); + } + return; + } + if (tag != null && frame[0] == pushCodeBinaryResponse) { + final reply = parseRegionsReply(frame); + if (reply != null && reply.tag == tag) finish(reply); + } + }); + try { + await sendFrame( + buildAnonRegionsRequestFrame( + repeaterPubKey, + replyPathLenByte: replyPathLenByte, + replyPath: replyPath, + ), + ); + return await completer.future; + } catch (e) { + appLogger.warn('regions discovery failed: $e', tag: 'Region'); + return null; + } finally { + timer.cancel(); + await sub.cancel(); + } + } + + /// The regions reply path for [repeaterPubKey], as (packed path-len byte, + /// hop-hash bytes), taken from the repeater contact's stored path. Returns + /// (0, empty) when the repeater is unknown or has no path, which the firmware + /// treats as a zero-hop reply (only an adjacent repeater can answer). The list + /// is never filtered on this: stored paths go stale as the companion moves, so + /// a repeater that looks far (or pathless) may still answer, and one that looks + /// near may not. + (int, Uint8List) _regionReplyPathFor(Uint8List repeaterPubKey) { + final hex = pubKeyToHex(repeaterPubKey); + for (final c in _contacts) { + if (pubKeyToHex(c.publicKey) == hex) { + if (c.pathLength >= 0 && c.path.isNotEmpty) { + return (encodePathLen(c.pathLength, c.pathHashWidth), c.path); + } + return (0, Uint8List(0)); + } + } + return (0, Uint8List(0)); + } + + /// Override the companion's flood send-scope with [key] (16 bytes) for + /// subsequent sends. (CMD 54 sub-0) + Future setChannelSendScope(Uint8List key) async { + _guardRegionScope(); + await sendFrame(buildSetFloodScopeKeyFrame(key)); + } + + /// Clear the send-scope override, reverting to the node default. (CMD 54 sub-0) + Future clearSendScope() async { + _guardRegionScope(); + await sendFrame(buildClearFloodScopeFrame()); + } + + /// Force subsequent sends unscoped. (CMD 54 sub-1) + Future setSendUnscoped() async { + _guardRegionScope(); + await sendFrame(buildFloodScopeUnscopedFrame()); + } + + /// Set the node default flood scope to ([name],[key]). (CMD 63) + Future setDefaultFloodScope(String name, Uint8List key) async { + _guardRegionScope(); + await sendFrame(buildSetDefaultFloodScopeFrame(name, key)); + } + + /// Clear the node default flood scope. (CMD 63, bare) + Future clearDefaultFloodScope() async { + _guardRegionScope(); + await sendFrame(buildClearDefaultFloodScopeFrame()); + } + + /// Query the node default flood scope. Returns null on timeout, or a + /// [DefaultFloodScope] whose name is empty when the node has none. (CMD 64) + Future getDefaultFloodScope({ + Duration timeout = const Duration(seconds: 5), + }) async { + _guardRegionScope(); + // RESP 28 carries no correlation tag, so only one query can be outstanding. + // Coalesce a concurrent caller onto the in-flight request (the default scope + // is a single global value, so they want the same answer); otherwise the + // second call would orphan the first's completer to a spurious timeout. + final inFlight = _defaultFloodScopeCompleter; + if (inFlight != null) return inFlight.future; + final completer = Completer(); + _defaultFloodScopeCompleter = completer; + final timer = Timer(timeout, () { + if (!completer.isCompleted) completer.complete(null); + }); + try { + await sendFrame(buildGetDefaultFloodScopeFrame()); + return await completer.future; + } catch (e) { + appLogger.warn('get default flood scope failed: $e', tag: 'Region'); + return null; + } finally { + timer.cancel(); + if (identical(_defaultFloodScopeCompleter, completer)) { + _defaultFloodScopeCompleter = null; + } + } + } + + /// Routes a RESP_CODE_DEFAULT_FLOOD_SCOPE (28) reply to a waiting query. + void _handleDefaultFloodScopeReply(Uint8List frame) { + final parsed = parseDefaultFloodScopeReply(frame); + if (parsed == null) return; + final completer = _defaultFloodScopeCompleter; + if (completer != null && !completer.isCompleted) { + completer.complete(parsed); + } + } + /// Ask firmware for the on-air packet hash of a channel message we sent, /// keyed by (ts, chan) (0xC6, #524). Returns null on timeout / error frame. Future _queryPacketHash( @@ -5917,6 +7231,21 @@ class MeshCoreConnector extends ChangeNotifier { final toImport = nodeSet.difference(local).difference(touched); final toPush = local.difference(nodeSet).difference(touched); unawaited(blockService.importKeys(toImport)); + // #471 Option A: a radio that reports an EMPTY block list is treated as + // blank. Do NOT auto-offload the client's blocks onto it, which made + // fresh/erased radios come up pre-blocked. The client stays the source of + // truth; blocks reach a radio only by an explicit user action. A radio that + // already holds blocks still unions normally. + if (nodeSet.isEmpty) { + if (toPush.isNotEmpty) { + _appDebugLogService?.info( + 'Radio reports no blocks; not offloading ${toPush.length} ' + 'client block(s) onto a blank radio (#471)', + tag: 'Block', + ); + } + return; + } for (final key in toPush) { _pushBlockChange(key, true); } @@ -6084,6 +7413,9 @@ class MeshCoreConnector extends ChangeNotifier { case cmdOffbandPktHash: _handleOffbandPktHashFrame(frame); break; + case respCodeDefaultFloodScope: + _handleDefaultFloodScopeReply(frame); + break; case respCodeOffbandDeviceUi: _handleDeviceUiReply(frame); break; @@ -6206,6 +7538,14 @@ class MeshCoreConnector extends ChangeNotifier { () => unawaited(getChannels(force: true)), ); break; + case respCodeCliReply: + final reply = parseCliReply(frame); + if (reply != null) { + for (final l in List.of(_cliReplyListeners)) { + l(reply); + } + } + break; case respCodeChannelInfo: _handleChannelInfo(frame); break; @@ -6436,10 +7776,20 @@ class MeshCoreConnector extends ChangeNotifier { _messageStore.setPublicKeyHex = selfPublicKeyHex; _channelOrderStore.setPublicKeyHex = selfPublicKeyHex; _channelSettingsStore.setPublicKeyHex = selfPublicKeyHex; + _channelRegionScopeStore.setPublicKeyHex = selfPublicKeyHex; _contactSettingsStore.setPublicKeyHex = selfPublicKeyHex; _contactStore.setPublicKeyHex = selfPublicKeyHex; _channelStore.setPublicKeyHex = selfPublicKeyHex; _unreadStore.setPublicKeyHex = selfPublicKeyHex; + // Discovered contacts are what THIS radio heard; scope them per radio so + // they don't bleed across radios on one host (#754). The startup load that + // follows clears and reloads the in-memory list from this radio's key. + _discoveryContactStore.setPublicKeyHex = selfPublicKeyHex; + // Path history and delivery observations, same reasoning (#854, #856): a + // route or an ACK timing is what THIS radio measured. Unset, both load + // nothing and never write, so a read before this point cannot serve + // another radio's data. + storageService?.setPublicKeyHex = selfPublicKeyHex; // Now that we have self info, we can load all the persisted data for this // node. Each step is timed: this sequence has stalled the UI isolate for @@ -6473,6 +7823,24 @@ class MeshCoreConnector extends ChangeNotifier { await step('channelMessages', () => loadAllChannelMessages()); await step('unreadState', loadUnreadState); await step('discoveredContacts', _loadDiscoveredContactCache); + + // One-time cleanup of the pre-#854/#856 untagged keys, after the loads so + // it never delays first paint. Both are no-ops once done, so this is safe + // to run on every connect, and both chunk or are small enough not to + // block: the path-history purge measured 12.7 s of total work on the + // owner's 2,092 keys and yields every 20 removals (plan decision 1). + await step('purgeLegacyStorage', () async { + final removed = await storageService?.purgeLegacyPathHistory() ?? 0; + final hadObs = + await storageService?.purgeLegacyDeliveryObservations() ?? false; + if (removed > 0 || hadObs) { + appLogger.info( + 'Legacy storage purge: $removed path-history keys, ' + '${hadObs ? "the" : "no"} global observation list (#854, #856)', + tag: 'Storage', + ); + } + }); } /// Extract the additive `offband_caps` byte from a device-info reply. @@ -6553,14 +7921,36 @@ class MeshCoreConnector extends ChangeNotifier { } else { _appDebugLogService?.info(widthNote, tag: 'Device'); } - // Offband config capability v14+ (byte 82). Extracted + bounds-checked in a - // testable helper; offset verified against firmware (see parseOffbandCaps). - _offbandCaps = parseOffbandCaps(frame); - // FEM LNA state rides one byte past the caps byte on v16+ (#304). Primary - // read on connect, a 0xC3 GET is only the fallback. - _femLnaEnabled = parseFemLnaState(frame); - // Second caps byte rides at offset 84, past the FEM state byte (#480). - _offbandCaps2 = parseOffbandCaps2(frame); + // Population first (#875/#876): stock 1.18 moved FIRMWARE_VER_CODE into + // the fork's spent range, so the caps bytes are only read once the + // classifier corroborates the fork layout. On a conflict every Offband + // field stays null -the same signals the fork absence always sent. + _classification = classifyDevicePopulation( + deviceInfo: frame, + firmwareVersion: info.version, + ); + if (_classification!.conflict) { + _appDebugLogService?.warn( + 'Population conflict, Offband surfaces disabled: ' + '${_classification!.evidence}', + tag: 'Device', + ); + } + if (_classification!.allowsOffbandFrames) { + // Offband config capability v14+ (byte 82). Extracted + bounds-checked + // in a testable helper; offset verified against firmware (see + // parseOffbandCaps). + _offbandCaps = parseOffbandCaps(frame); + // FEM LNA state rides one byte past the caps byte on v16+ (#304). + // Primary read on connect, a 0xC3 GET is only the fallback. + _femLnaEnabled = parseFemLnaState(frame); + // Second caps byte rides at offset 84, past the FEM state byte (#480). + _offbandCaps2 = parseOffbandCaps2(frame); + } else { + _offbandCaps = null; + _femLnaEnabled = null; + _offbandCaps2 = null; + } // Capability-gated features are invisible when a bit is clear, which looks // identical to a bug. Log the raw inputs so "the toggle didn't appear" can // be told apart from "this radio says it can't". (#304) @@ -6984,37 +8374,46 @@ class MeshCoreConnector extends ChangeNotifier { // Preserve user-selected path settings and previously known GPS when // refreshed frames omit coordinates (lat/lon encoded as 0,0). - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, - latitude: contact.latitude ?? existing.latitude, - longitude: contact.longitude ?? existing.longitude, + // `contact` is built from the device frame, which carries no custom + // name, so copyWith from it drops the user's label. Reattach it. (#750) + _contacts[existingIndex] = _withCustomName( + contact.copyWith( + lastMessageAt: mergedLastMessageAt, + pathOverride: existing.pathOverride, // Preserve user's path choice + pathOverrideBytes: existing.pathOverrideBytes, + latitude: contact.latitude ?? existing.latitude, + longitude: contact.longitude ?? existing.longitude, + ), ); appLogger.info( 'After merge: pathOverride=${_contacts[existingIndex].pathOverride}, devicePath=${_pathDiag(_contacts[existingIndex].path, _contacts[existingIndex].pathLength, _contacts[existingIndex].pathHashWidth)}', tag: 'Connector', ); + } else if (isContact) { + // The contact sync stream is radio truth; it is the only thing that + // populates the persisted list. + _contacts.add(_withCustomName(contact)); + appLogger.info( + 'Added new contact ${contact.name}: pathLen=${_pathDiag(contact.path, contact.pathLength, contact.pathHashWidth)}', + tag: 'Connector', + ); } else { - if ((_autoAddUsers && contact.type == advTypeChat) || - (_autoAddRepeaters && contact.type == advTypeRepeater) || - (_autoAddRoomServers && contact.type == advTypeRoom) || - (_autoAddSensors && contact.type == advTypeSensor) || - isContact) { - _contacts.add(contact); - appLogger.info( - 'Added new contact ${contact.name}: pathLen=${_pathDiag(contact.path, contact.pathLength, contact.pathHashWidth)}', - tag: 'Connector', - ); - } else { - appLogger.info( - "Discovered contact ${contact.name} (type ${contact.typeLabelRaw}) not added due to auto-add settings", - tag: 'Connector', - ); - notifyListeners(); - return; - } + // #838: a live advert (NEW_ADVERT push) is NOT proof the radio stored + // the node. The firmware fires it even for adverts it rejects (beyond + // the auto-add hop limit, or when the contact table is full), and the + // client applies neither limit, so promoting them here drifted a + // long-lived session hundreds of contacts above radio truth. Keep it in + // discovery (added above) and, when the radio's own policy would have + // added it, nudge a reconcile so a genuinely-new contact still surfaces + // without a manual sync. + appLogger.info( + "Discovered contact ${contact.name} (type ${contact.typeLabelRaw}) left in discovery; not a synced contact", + tag: 'Connector', + ); + if (_isAutoAddEligible(contact.type)) _scheduleContactReconcile(); + notifyListeners(); + return; } _knownContactKeys.add(contact.publicKeyHex); _loadMessagesForContact(contact.publicKeyHex); @@ -7092,10 +8491,13 @@ class MeshCoreConnector extends ChangeNotifier { ); // CRITICAL: Preserve user's path override when contact is refreshed from device - _contacts[existingIndex] = contact.copyWith( - lastMessageAt: mergedLastMessageAt, - pathOverride: existing.pathOverride, // Preserve user's path choice - pathOverrideBytes: existing.pathOverrideBytes, + // Built from the device frame, so reattach the user's label. (#750) + _contacts[existingIndex] = _withCustomName( + contact.copyWith( + lastMessageAt: mergedLastMessageAt, + pathOverride: existing.pathOverride, // Preserve user's path choice + pathOverrideBytes: existing.pathOverrideBytes, + ), ); appLogger.info( @@ -7103,7 +8505,7 @@ class MeshCoreConnector extends ChangeNotifier { tag: 'Connector', ); } else { - _contacts.add(contact); + _contacts.add(_withCustomName(contact)); appLogger.info( 'Added new contact ${contact.name}: pathLen=${contact.pathLength}', tag: 'Connector', @@ -7345,6 +8747,16 @@ class MeshCoreConnector extends ChangeNotifier { return; } + // CLI traffic stays in the CLI console only. A CLI reply (type-1) or an + // inbound CLI command (type-3) is correlated by the console through the + // receivedFrames listener; it must never enter the chat thread, bump the + // contact's last-message, or raise unread. CLI and chat are separate + // surfaces - drop CLI out of the message pipeline here (#999). + if (message.isCli || message.isCliCommand) { + _handleQueuedMessageReceived(); + return; + } + final contact = _contacts.cast().firstWhere( (c) => c?.publicKeyHex == message!.senderKeyHex, orElse: () => null, @@ -7511,7 +8923,13 @@ class MeshCoreConnector extends ChangeNotifier { final isPlain = shiftedType == txtTypePlain || rawType == txtTypePlain || isSigned; final isCli = shiftedType == txtTypeCliData || rawType == txtTypeCliData; - if (!isPlain && !isCli) { + // An inbound remote-CLI COMMAND (type 3): a contact asking to run a + // command on our radio. It reaches the app as a message (the firmware + // queues it when the sender lacks the 0x10 grant), so render it rather + // than dropping it (#890). + final isCliCommand = + shiftedType == txtTypeCliCommand || rawType == txtTypeCliCommand; + if (!isPlain && !isCli && !isCliCommand) { appLogger.warn( 'Unknown message type received: txtType=$txtType, shifted=$shiftedType, raw=$rawType', ); @@ -7522,7 +8940,7 @@ class MeshCoreConnector extends ChangeNotifier { appLogger.warn('Received message with empty text, ignoring'); return null; } - final decodedText = isCli + final decodedText = (isCli || isCliCommand) ? msgText : (Smaz.tryDecodePrefixed(msgText) ?? msgText); @@ -7543,6 +8961,7 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: timestamp, isOutgoing: isOutgoing, isCli: isCli, + isCliCommand: isCliCommand, status: isOutgoing ? MessageStatus.sent : MessageStatus.delivered, pathLength: pathLength == 0xFF ? 0 : pathLength, pathBytes: Uint8List(0), @@ -7810,11 +9229,8 @@ class MeshCoreConnector extends ChangeNotifier { // the setting survives a rename and does not follow a reused slot (#259). // Evaluated against resolvedText so a translated mention still matches. final mode = _appSettingsService!.channelNotifyMode( - identityKey: AppSettings.channelNotifyKey( - channelIndex: channelIndex, - pskHex: _findChannelByIndex(channelIndex)?.pskHex, - ), - channelName: label, + devicePrefix: selfPublicKeyHex, + pskHex: _findChannelByIndex(channelIndex)?.pskHex, ); switch (mode) { case ChannelNotifyMode.off: @@ -7963,7 +9379,11 @@ class MeshCoreConnector extends ChangeNotifier { timestamp: DateTime.fromMillisecondsSinceEpoch(timestampRaw * 1000), isOutgoing: false, status: ChannelMessageStatus.sent, - pathLength: packet.isFlood ? packet.hopCount : 0, + // The raw packed byte (hop count low 6 bits, hash width high 2), + // same encoding fromFrame stores. Storing the stripped hop count + // here lost the width, so a 3-byte-hash path later decoded as + // width 1 and the byte length leaked in as the hop count (#985). + pathLength: packet.isFlood ? packet.pathLenRaw : 0, pathBytes: packet.pathBytes, channelIndex: channel.index, rxTime: DateTime.now(), @@ -8804,10 +10224,9 @@ class MeshCoreConnector extends ChangeNotifier { existing.pathVariants, processedMessage.pathVariants, ); - final mergedPathLength = _mergePathLength( + final mergedPathLength = mergePathLenRaw( existing.pathLength, processedMessage.pathLength, - mergedPathBytes.length, ); final newRepeatCount = existing.repeatCount + 1; final promotedFromPending = @@ -8946,18 +10365,6 @@ class MeshCoreConnector extends ChangeNotifier { return existing; } - int? _mergePathLength(int? existing, int? incoming, int observedLength) { - if (existing == null) { - if (incoming == null) return observedLength > 0 ? observedLength : null; - return incoming >= observedLength ? incoming : observedLength; - } - if (incoming == null) { - return existing >= observedLength ? existing : observedLength; - } - final merged = existing >= incoming ? existing : incoming; - return merged >= observedLength ? merged : observedLength; - } - List _mergePathVariants( List existing, List incoming, @@ -9008,6 +10415,10 @@ class MeshCoreConnector extends ChangeNotifier { _notifySubscription = null; _connectionSubscription?.cancel(); _connectionSubscription = null; + // Per-connection debounce timers must not survive the drop and fire against + // the next radio (#838 review). + _advertReconcileDebounce?.cancel(); + _channelsChangedDebounce?.cancel(); _device = null; _rxCharacteristic = null; @@ -9015,6 +10426,18 @@ class MeshCoreConnector extends ChangeNotifier { // Preserve deviceId and displayName for UI display during reconnection // They're only cleared on manual disconnect via disconnect() method _hasReceivedDeviceInfo = false; + // But NOT the identity that scopes stored data (#158). A manual + // disconnect() clears _selfPublicKey; an unexpected drop did not, so + // every per-radio store, and the one channels_screen builds from + // `selfPublicKeyHex`, kept the previous radio's prefix. Connect a + // DIFFERENT radio after a drop and any read before its SELF_INFO lands + // served the old radio's history. Desktop-only in practice, which is + // where #158 was seen. + // + // Cleared here so those reads fail closed and return nothing, the #754 + // precedent. The names above stay, so the UI can still say which radio it + // is reconnecting to; it is only the data-scoping identity that goes. + _clearStorageScopeKeys(); _maxContacts = _defaultMaxContacts; _maxChannels = _defaultMaxChannels; _resetSyncProgressState(); @@ -9156,6 +10579,7 @@ class MeshCoreConnector extends ChangeNotifier { _gpsLocationPollTimer?.cancel(); _radioStatsPollTimer?.cancel(); _channelsChangedDebounce?.cancel(); + _advertReconcileDebounce?.cancel(); _contactRequestWatchdog?.cancel(); _pendingKeyCheck?.timer?.cancel(); _recoverySettleTimer?.cancel(); @@ -9308,7 +10732,7 @@ class MeshCoreConnector extends ChangeNotifier { Contact( rawPacket: frame, publicKey: publicKey, - name: name, + receivedName: name, type: type, pathLength: pathBytes.isEmpty ? -1 : pathBytes.length, path: Uint8List.fromList( @@ -9392,7 +10816,7 @@ class MeshCoreConnector extends ChangeNotifier { final newContact = Contact( rawPacket: rawPacket, publicKey: publicKey, - name: name, + receivedName: name, type: type, pathLength: path.length, path: Uint8List.fromList( @@ -9402,17 +10826,19 @@ class MeshCoreConnector extends ChangeNotifier { longitude: longitude, lastSeen: DateTime.fromMillisecondsSinceEpoch(timestamp * 1000), ); - if ((_autoAddUsers && type == advTypeChat) || - (_autoAddRepeaters && type == advTypeRepeater) || - (_autoAddRoomServers && type == advTypeRoom) || - (_autoAddSensors && type == advTypeSensor)) { - _handleContactAdvert(newContact); + // #838: a raw overheard advert is not proof the radio stored the node, so + // it never joins the persisted contact list (that is what drifted a long + // session above radio truth). It feeds discovery, and when the radio's own + // auto-add policy would have added it, a reconcile pulls the radio's real + // entry in. The persisted list stays a mirror of the contact sync. + if (_isAutoAddEligible(type)) { _handleDiscovery( newContact, rawPacket, noNotify: true, addActive: true, ); + _scheduleContactReconcile(); } else { _handleDiscovery(newContact, rawPacket); } @@ -9439,7 +10865,14 @@ class MeshCoreConnector extends ChangeNotifier { _contacts[existingIndex] = existing.copyWith( latitude: hasLocation ? latitude : existing.latitude, longitude: hasLocation ? longitude : existing.longitude, - name: hasName ? name : existing.name, + // The received name updates; the user's custom name is untouched, so + // what they see does not move. This is the whole point of #750: before + // it, an advert took the user's chosen name back every time, which is + // why the client could never hold one. `copyWith` leaves `customName` + // alone unless `clearCustomName` is passed, so nothing else is needed + // here. A nameless advert (`hasName` false) must not blank the + // received name either. (T15, T16, T18, T19) + receivedName: hasName ? name : existing.receivedName, path: Uint8List.fromList(path.reversed.toList()), pathLength: path.length, lastMessageAt: mergedLastMessageAt, @@ -9531,7 +10964,7 @@ class MeshCoreConnector extends ChangeNotifier { _discoveredContacts[existingIndex] = _discoveredContacts[existingIndex] .copyWith( rawPacket: rawPacket, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, @@ -9549,7 +10982,7 @@ class MeshCoreConnector extends ChangeNotifier { final disContact = Contact( rawPacket: rawPacket, publicKey: contact.publicKey, - name: contact.name, + receivedName: contact.receivedName, type: contact.type, pathLength: contact.pathLength, path: contact.path, @@ -9651,8 +11084,6 @@ class _RawPacket { bool get isFlood => routeType == _routeFlood || routeType == _routeTransportFlood; - - int get hopCount => pathLenRaw & 63; } class _ParsedText { @@ -9683,3 +11114,19 @@ class _PendingCommandAck { _PendingCommandAck({required this.commandCode, this.channelSendQueueId}); } + +/// A `0xC5` request waiting for its reply. +class _DeviceUiWaiter { + _DeviceUiWaiter(this.surface, this.matches); + final DeviceUiSurface surface; + final bool Function(OffbandUiReply reply) matches; + final Completer completer = Completer(); +} + +/// How one pass of a slot push ended. +enum _SlotPush { committed, displaced, failed } + +/// A BLE connect that Stop or a newer connect took over (#997). +class _ConnectSuperseded implements Exception { + const _ConnectSuperseded(); +} diff --git a/lib/connector/meshcore_protocol.dart b/lib/connector/meshcore_protocol.dart index 42eaac68..5b3c9ab8 100644 --- a/lib/connector/meshcore_protocol.dart +++ b/lib/connector/meshcore_protocol.dart @@ -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 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(); diff --git a/lib/connector/offband_device_ui.dart b/lib/connector/offband_device_ui.dart index e5eb837e..8a5ba6bb 100644 --- a/lib/connector/offband_device_ui.dart +++ b/lib/connector/offband_device_ui.dart @@ -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), + ), + ); +} diff --git a/lib/connector/offband_screen_settings.dart b/lib/connector/offband_screen_settings.dart new file mode 100644 index 00000000..059f964b --- /dev/null +++ b/lib/connector/offband_screen_settings.dart @@ -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 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, + ), + ); +} diff --git a/lib/connector/offband_tones.dart b/lib/connector/offband_tones.dart new file mode 100644 index 00000000..de5b6c6c --- /dev/null +++ b/lib/connector/offband_tones.dart @@ -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 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 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 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 offeredTuneIds(Map 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 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 = {}; + 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; +} diff --git a/lib/connector/reconnect_policy.dart b/lib/connector/reconnect_policy.dart new file mode 100644 index 00000000..6576fd54 --- /dev/null +++ b/lib/connector/reconnect_policy.dart @@ -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; + } +} diff --git a/lib/helpers/device_name_validator.dart b/lib/helpers/device_name_validator.dart new file mode 100644 index 00000000..5b9b584f --- /dev/null +++ b/lib/helpers/device_name_validator.dart @@ -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 forbiddenDeviceNameChars = [ + '[', + ']', + '\\', + ':', + ',', + '?', + '*', +]; + +/// The distinct forbidden characters present in [name], in the order they +/// appear in [forbiddenDeviceNameChars]. Empty when the name is valid. +List forbiddenCharsIn(String name) => + forbiddenDeviceNameChars.where(name.contains).toList(); + +/// True when [name] carries none of the forbidden characters. +bool isValidDeviceName(String name) => forbiddenCharsIn(name).isEmpty; diff --git a/lib/helpers/region_key.dart b/lib/helpers/region_key.dart new file mode 100644 index 00000000..e3e0e1f8 --- /dev/null +++ b/lib/helpers/region_key.dart @@ -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([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; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index fdf9b684..d039c6c7 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -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)." } } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 44ba49de..b7012c2e 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -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 diff --git a/lib/l10n/app_localizations_bg.dart b/lib/l10n/app_localizations_bg.dart index 2fd77ebc..d35b52de 100644 --- a/lib/l10n/app_localizations_bg.dart +++ b/lib/l10n/app_localizations_bg.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart index 1f63620c..35cd8db8 100644 --- a/lib/l10n/app_localizations_de.dart +++ b/lib/l10n/app_localizations_de.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 7ebc75d8..54bf3d39 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart index 0d527d9f..4e46d975 100644 --- a/lib/l10n/app_localizations_es.dart +++ b/lib/l10n/app_localizations_es.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart index d1cf3027..219de29e 100644 --- a/lib/l10n/app_localizations_fr.dart +++ b/lib/l10n/app_localizations_fr.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_hu.dart b/lib/l10n/app_localizations_hu.dart index a516594c..c08c1cb2 100644 --- a/lib/l10n/app_localizations_hu.dart +++ b/lib/l10n/app_localizations_hu.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart index de89e16b..91389a7e 100644 --- a/lib/l10n/app_localizations_it.dart +++ b/lib/l10n/app_localizations_it.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart index b8362371..d3010fdd 100644 --- a/lib/l10n/app_localizations_ja.dart +++ b/lib/l10n/app_localizations_ja.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 1de3d95f..39187c25 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_nl.dart b/lib/l10n/app_localizations_nl.dart index da8decb5..b6236c72 100644 --- a/lib/l10n/app_localizations_nl.dart +++ b/lib/l10n/app_localizations_nl.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_pl.dart b/lib/l10n/app_localizations_pl.dart index e5e4f026..fe5b39ba 100644 --- a/lib/l10n/app_localizations_pl.dart +++ b/lib/l10n/app_localizations_pl.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart index d4b996fe..7ce0252f 100644 --- a/lib/l10n/app_localizations_pt.dart +++ b/lib/l10n/app_localizations_pt.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 09fe6091..37a816a1 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_sk.dart b/lib/l10n/app_localizations_sk.dart index b6f39379..25689cce 100644 --- a/lib/l10n/app_localizations_sk.dart +++ b/lib/l10n/app_localizations_sk.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_sl.dart b/lib/l10n/app_localizations_sl.dart index e6703edb..3c70d749 100644 --- a/lib/l10n/app_localizations_sl.dart +++ b/lib/l10n/app_localizations_sl.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_sv.dart b/lib/l10n/app_localizations_sv.dart index 6496c2c5..637ec25d 100644 --- a/lib/l10n/app_localizations_sv.dart +++ b/lib/l10n/app_localizations_sv.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_uk.dart b/lib/l10n/app_localizations_uk.dart index ed5534da..08d295ab 100644 --- a/lib/l10n/app_localizations_uk.dart +++ b/lib/l10n/app_localizations_uk.dart @@ -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.'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index 939a329a..e7790698 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -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.'; } diff --git a/lib/main.dart b/lib/main.dart index b5e6bd5b..81c32a0c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -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() { diff --git a/lib/models/app_settings.dart b/lib/models/app_settings.dart index 7e95baa1..44b7983b 100644 --- a/lib/models/app_settings.dart +++ b/lib/models/app_settings.dart @@ -158,11 +158,24 @@ class AppSettings { /// written, so an older build can be rolled back to without losing mutes. final Set 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_` 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 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> 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? mutedChannels, Map? channelNotifyModes, + Map>? 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)), + ) ?? + {}, + ), + ) ?? + {}, + 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? mutedChannels, Map? channelNotifyModes, + Map>? 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, diff --git a/lib/models/badge_time_zones.dart b/lib/models/badge_time_zones.dart new file mode 100644 index 00000000..ee494e14 --- /dev/null +++ b/lib/models/badge_time_zones.dart @@ -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 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; +} diff --git a/lib/models/channel_message.dart b/lib/models/channel_message.dart index b84a69bc..0ed910e7 100644 --- a/lib/models/channel_message.dart +++ b/lib/models/channel_message.dart @@ -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? 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(); diff --git a/lib/models/contact.dart b/lib/models/contact.dart index f4d1dc6b..d50acde2 100644 --- a/lib/models/contact.dart +++ b/lib/models/contact.dart @@ -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; } diff --git a/lib/models/message.dart b/lib/models/message.dart index 71281c7b..0ac888aa 100644 --- a/lib/models/message.dart +++ b/lib/models/message.dart @@ -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 diff --git a/lib/models/region.dart b/lib/models/region.dart new file mode 100644 index 00000000..f2d65bac --- /dev/null +++ b/lib/models/region.dart @@ -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)'; +} diff --git a/lib/screens/channel_chat_screen.dart b/lib/screens/channel_chat_screen.dart index 3ccdefd8..dd2cfbf4 100644 --- a/lib/screens/channel_chat_screen.dart +++ b/lib/screens/channel_chat_screen.dart @@ -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 { ); } + /// Open the Set Region Scope picker for the current channel (#815). + Future _openRegionScopeDialog() async { + final connector = context.read(); + 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( + 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 { onSelected: (value) { if (value == 'notifications') { showChannelNotifyModeDialog(context, widget.channel); + } else if (value == 'radioTone') { + final connector = context.read(); + requestChannelRadioTone(connector, _currentChannel.index); + showChannelRadioToneDialog(context, _currentChannel); } else if (value == 'clearChat') { context.read().clearMessagesForChannel( _currentChannel.index, ); + } else if (value == 'setRegionScope') { + _openRegionScopeDialog(); } }, itemBuilder: (context) => [ @@ -445,8 +494,10 @@ class _ChannelChatScreenState extends State { Icon( channelNotifyModeIcon( context.read().channelNotifyMode( - identityKey: channelNotifyKeyFor(widget.channel), - channelName: widget.channel.name, + devicePrefix: context + .read() + .selfPublicKeyHex, + pskHex: widget.channel.pskHex, ), ), size: 20, @@ -456,6 +507,28 @@ class _ChannelChatScreenState extends State { ], ), ), + if (context.read().supportsTunes) + const PopupMenuItem( + value: 'radioTone', + child: Row( + children: [ + Icon(Icons.music_note_outlined, size: 20), + SizedBox(width: 12), + Text('Radio tone'), + ], + ), + ), + if (context.read().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 { Widget _buildMessageBubble(ChannelMessage message, double textScale) { final settingsService = context.watch(); final enableTracing = settingsService.settings.enableMessageTracing; - final hashWidth = context.read().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().pathHashByteWidth, + ); final isOutgoing = message.isOutgoing; final gifUrl = GifHelper.resolveGifUrl(message.text); final gifReplyName = gifUrl != null @@ -1710,8 +1787,13 @@ class _ChannelChatScreenState extends State { /// truncated with โ€ฆ to fit the channel byte budget, fired directly. (#106) void _sendRouteReply(ChannelMessage message) { final connector = context.read(); - 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( diff --git a/lib/screens/channel_message_path_screen.dart b/lib/screens/channel_message_path_screen.dart index 7014c342..c82caa15 100644 --- a/lib/screens/channel_message_path_screen.dart +++ b/lib/screens/channel_message_path_screen.dart @@ -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() - .pathHashByteWidth, + pathHashByteWidth: hashWidth, ), ), ), @@ -183,7 +187,11 @@ class ChannelMessagePathScreen extends StatelessWidget { Widget _buildPathVariants(BuildContext context, List variants) { final l10n = context.l10n; - final hashWidth = context.read().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().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 onSelected, ) { final l10n = context.l10n; - final hashWidth = context.read().pathHashByteWidth; + final hashWidth = widget.message.effectivePathHashWidth( + context.read().pathHashByteWidth, + ); final selectedPath = paths[selectedIndex]; final label = selectedPath.isPrimary ? l10n.channelPath_primaryPath(selectedIndex + 1) diff --git a/lib/screens/channels_screen.dart b/lib/screens/channels_screen.dart index 3bdf221a..1b2ec301 100644 --- a/lib/screens/channels_screen.dart +++ b/lib/screens/channels_screen.dart @@ -27,6 +27,7 @@ import '../widgets/channel_drawer_list.dart'; import '../widgets/sync_progress_overlay.dart'; import '../widgets/unread_badge.dart'; import '../widgets/channel_notify_mode.dart'; +import '../widgets/radio_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 final parentContext = context; final settingsService = context.read(); 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 } }, ), + // 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( diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 0718a3e7..f7678864 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -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 { ), ); } + 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 { ], ), ), + // 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 { 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); diff --git a/lib/screens/contacts_screen.dart b/lib/screens/contacts_screen.dart index adc9899b..fa5d05b7 100644 --- a/lib/screens/contacts_screen.dart +++ b/lib/screens/contacts_screen.dart @@ -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 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), diff --git a/lib/screens/device_cli_screen.dart b/lib/screens/device_cli_screen.dart new file mode 100644 index 00000000..cf438cec --- /dev/null +++ b/lib/screens/device_cli_screen.dart @@ -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 createState() => _DeviceCliScreenState(); +} + +class _DeviceCliScreenState extends State { + 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(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 ` 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 _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(); + 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, + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/discover_regions_screen.dart b/lib/screens/discover_regions_screen.dart new file mode 100644 index 00000000..9c49066e --- /dev/null +++ b/lib/screens/discover_regions_screen.dart @@ -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 createState() => _DiscoverRegionsScreenState(); +} + +class _DiscoverRegionsScreenState extends State { + 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(); + _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), + ), + ), + ], + ), + ); + } +} diff --git a/lib/screens/path_trace_map.dart b/lib/screens/path_trace_map.dart index a4dc3fb6..32bc4fee 100644 --- a/lib/screens/path_trace_map.dart +++ b/lib/screens/path_trace_map.dart @@ -378,7 +378,10 @@ class _PathTraceMapScreenState extends State { 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, diff --git a/lib/screens/repeater_hub_screen.dart b/lib/screens/repeater_hub_screen.dart index 5b1e30ca..083cc48f 100644 --- a/lib/screens/repeater_hub_screen.dart +++ b/lib/screens/repeater_hub_screen.dart @@ -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(); + final connector = context.watch(); 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) diff --git a/lib/screens/scanner_screen.dart b/lib/screens/scanner_screen.dart index 359d8ee6..47e67267 100644 --- a/lib/screens/scanner_screen.dart +++ b/lib/screens/scanner_screen.dart @@ -264,6 +264,31 @@ class _ScannerScreenState extends State { 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 { 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, ], ), ); diff --git a/lib/screens/settings/app_settings_view.dart b/lib/screens/settings/app_settings_view.dart index 5486422f..7fcfe8f7 100644 --- a/lib/screens/settings/app_settings_view.dart +++ b/lib/screens/settings/app_settings_view.dart @@ -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(), ], ); }, diff --git a/lib/screens/settings/badge_battery_view.dart b/lib/screens/settings/badge_battery_view.dart new file mode 100644 index 00000000..4014784c --- /dev/null +++ b/lib/screens/settings/badge_battery_view.dart @@ -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 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 { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) context.read().requestScreenSettings(); + }); + } + + Future _pin(MeshCoreConnector connector) async { + final confirmed = await showDialog( + 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(); + 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'), + ), + ], + ), + ], + ], + ); + } +} diff --git a/lib/screens/settings/badge_screen_view.dart b/lib/screens/settings/badge_screen_view.dart new file mode 100644 index 00000000..baf42794 --- /dev/null +++ b/lib/screens/settings/badge_screen_view.dart @@ -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 createState() => _BadgeScreenViewState(); +} + +class _BadgeScreenViewState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) context.read().requestScreenSettings(); + }); + } + + @override + Widget build(BuildContext context) { + final connector = context.watch(); + 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( + 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 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( + 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 createState() => _TimeZonePickerScreenState(); +} + +class _TimeZonePickerScreenState extends State { + String _query = ''; + + void _choose(int index) { + context.read().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), + ], + ), + ); + } +} diff --git a/lib/screens/settings/blocked_view.dart b/lib/screens/settings/blocked_view.dart index 438e2120..1005264f 100644 --- a/lib/screens/settings/blocked_view.dart +++ b/lib/screens/settings/blocked_view.dart @@ -17,6 +17,42 @@ class BlockedView extends StatelessWidget { Widget build(BuildContext context) { return Consumer2( 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); diff --git a/lib/screens/settings/device_ui_view.dart b/lib/screens/settings/device_ui_view.dart index 95f56190..c0a8d016 100644 --- a/lib/screens/settings/device_ui_view.dart +++ b/lib/screens/settings/device_ui_view.dart @@ -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 createState() => _DeviceUiViewState(); } +/// Which half of the device UI a [DeviceUiView] shows. +enum DeviceUiPart { buttons, buzzer } + class _DeviceUiViewState extends State { @override void initState() { @@ -29,17 +42,41 @@ class _DeviceUiViewState extends State { WidgetsBinding.instance.addPostFrameCallback((_) { if (!mounted) return; final c = context.read(); - 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( 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 { } 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 { ), ), ..._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 { .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 _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 _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 _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 _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 _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, - ), - ], - ), - ); - } -} diff --git a/lib/screens/settings/location_view.dart b/lib/screens/settings/location_view.dart new file mode 100644 index 00000000..2d0cd830 --- /dev/null +++ b/lib/screens/settings/location_view.dart @@ -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 createState() => _LocationViewState(); +} + +class _LocationViewState extends State { + 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()); + }); + _gpsRefresh = Timer.periodic(_gpsRefreshEvery, (_) { + if (mounted) _refreshGpsMode(context.read()); + }); + } + + @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(); + final customVars = connector.currentCustomVars ?? const {}; + // 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 = [ + 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( + 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 = []; + 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 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 _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 _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 = [ + 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 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), + ), + ], + ), + ); + } +} diff --git a/lib/screens/settings/message_settings_view.dart b/lib/screens/settings/message_settings_view.dart index 151cc602..a81f615f 100644 --- a/lib/screens/settings/message_settings_view.dart +++ b/lib/screens/settings/message_settings_view.dart @@ -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(); + 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), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/screens/settings/tune_slot_editor_screen.dart b/lib/screens/settings/tune_slot_editor_screen.dart new file mode 100644 index 00000000..fcc6dd97 --- /dev/null +++ b/lib/screens/settings/tune_slot_editor_screen.dart @@ -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 createState() => _TuneSlotEditorScreenState(); +} + +class _TuneSlotEditorScreenState extends State { + 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 _read() async { + final connector = context.read(); + 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 _save() async { + final connector = context.read(); + 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 _clear() async { + final confirmed = await showDialog( + 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 _playSaved() async { + final connector = context.read(); + 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 _confirmDiscard() async { + final discard = await showDialog( + 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(); + 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, + ), + ], + ), + ), + ); + } +} diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dart index 9b6f9c14..9c1d4414 100644 --- a/lib/screens/settings_screen.dart +++ b/lib/screens/settings_screen.dart @@ -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 { 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 { : 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 { 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(); @@ -355,54 +443,22 @@ class _SettingsScreenState extends State { 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 { 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 { Widget _actionsPane(BuildContext context) { final connector = context.watch(); + // 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(); 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 { }, ), 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().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 { Widget _buildDebugCard(BuildContext context) { final l10n = context.l10n; final settingsService = context.watch(); + // #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( + (c) => c.classification?.allowsCliFrame ?? false, + ); return Card( child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -884,21 +997,19 @@ class _SettingsScreenState extends State { 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 { }, ), 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 { ); }, ), - 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().syncQueuedMessages(force: true); - showDismissibleSnackBar( - context, - content: const Text('Requested queued-message drain (force)'), - ); - }, - ), ], ), ); @@ -1099,366 +1207,59 @@ class _SettingsScreenState extends State { 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 = [ - 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), + ), + ], + ); + }, ), ); } diff --git a/lib/screens/tcp_screen.dart b/lib/screens/tcp_screen.dart index a0d71922..b51d3766 100644 --- a/lib/screens/tcp_screen.dart +++ b/lib/screens/tcp_screen.dart @@ -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 { } Future _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; } diff --git a/lib/screens/usb_screen.dart b/lib/screens/usb_screen.dart index d4265467..01ddb112 100644 --- a/lib/screens/usb_screen.dart +++ b/lib/screens/usb_screen.dart @@ -315,8 +315,12 @@ class _UsbScreenState extends State { Future _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 { } Future _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( diff --git a/lib/services/app_exit_info_service.dart b/lib/services/app_exit_info_service.dart new file mode 100644 index 00000000..dd2fa9cd --- /dev/null +++ b/lib/services/app_exit_info_service.dart @@ -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 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 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 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 all, + int? watermarkMs, { + int backfillTraceCap = 3, +}) { + final backfill = watermarkMs == null; + final fresh = backfill + ? List.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: ` [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 = [ + '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--.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 traceFilesToPrune( + Map sizesByName, { + int keep = 5, + int ceilingBytes = 1024 * 1024, +}) { + final names = sizesByName.keys.toList()..sort(); + final doomed = []; + + final surviving = names.toList(); + while (surviving.length > keep) { + doomed.add(surviving.removeAt(0)); + } + + var total = surviving.fold(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> traceFiles() async { + final dir = traceDir; + if (dir == null) return const []; + try { + if (!await dir.exists()) return const []; + return (await dir.list().toList()).whereType().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 collect() async { + if (_ran) return; + _ran = true; + + if (!_isAndroid) { + _log('INFO', ExitInfoMessages.notAndroid); + return; + } + + try { + final raw = await _channel.invokeMapMethod( + '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(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 _report(List 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 _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 _prune() async { + final files = await traceFiles(); + if (files.isEmpty) return; + try { + final sizes = {}; + 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 _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 forceMainThreadBlock({int millis = 20000}) async { + if (!_isAndroid) return; + try { + await _channel.invokeMethod('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 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 _blockPayload() => { + for (var i = 0; i < 400; i++) + 'entry_$i': { + 'id': i, + 'name': 'contact-$i', + 'path': List.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', + ); + } +} diff --git a/lib/services/app_settings_service.dart b/lib/services/app_settings_service.dart index 8f41bf0c..21a267be 100644 --- a/lib/services/app_settings_service.dart +++ b/lib/services/app_settings_service.dart @@ -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 setChannelNotifyMode({ - required String identityKey, + required String devicePrefix, + required String? pskHex, required String channelName, required ChannelNotifyMode mode, }) async { - final modes = Map.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.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 migrateLegacyChannelNotify({ + required String devicePrefix, + required Map pskByChannelIndex, + required Map pskByChannelName, + }) async { + if (_settings.channelNotifyMigrated) return; + final prefix = _scopePrefix(devicePrefix); + if (prefix.isEmpty) return; + + final byRadio = _copyByRadio(); + final radioModes = byRadio.putIfAbsent(prefix, () => {}); + + // 1) psk_ entries map straight across; 2) 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 muteChannel(String channelName) async { - final updated = Set.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 unmuteChannel(String channelName) async { - final updated = Set.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> _copyByRadio() => { + for (final e in _settings.channelNotifyModesByRadio.entries) + e.key: Map.from(e.value), + }; + Future setTcpServerAddress(String value) async { await updateSettings(_settings.copyWith(tcpServerAddress: value)); } diff --git a/lib/services/cli_console_transport.dart b/lib/services/cli_console_transport.dart new file mode 100644 index 00000000..0580f2b6 --- /dev/null +++ b/lib/services/cli_console_transport.dart @@ -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 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 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? _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? _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 run(String command, {Duration? timeout}) async { + final window = Completer(); + _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 _send(String command, Completer 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(); + } +} diff --git a/lib/services/command_correlation.dart b/lib/services/command_correlation.dart new file mode 100644 index 00000000..9e617d07 --- /dev/null +++ b/lib/services/command_correlation.dart @@ -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 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); +} diff --git a/lib/services/file_log_service.dart b/lib/services/file_log_service.dart index 703333e0..3827a627 100644 --- a/lib/services/file_log_service.dart +++ b/lib/services/file_log_service.dart @@ -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> 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() ? [active] : const []; + } + } + /// 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 dispose() async { diff --git a/lib/services/local_cli_service.dart b/lib/services/local_cli_service.dart new file mode 100644 index 00000000..7e79e843 --- /dev/null +++ b/lib/services/local_cli_service.dart @@ -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> _pending = {}; + final Map _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 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(); + _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(); + } +} diff --git a/lib/services/region_discovery_service.dart b/lib/services/region_discovery_service.dart new file mode 100644 index 00000000..298203b2 --- /dev/null +++ b/lib/services/region_discovery_service.dart @@ -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 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 _regions = const []; + int? _clock; + String? _errorMessage; + bool _disposed = false; + + RegionDiscoveryStatus get status => _status; + List 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 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 _dedupe(List names) { + final seen = {}; + final out = []; + for (final name in names) { + final region = Region(name); + if (seen.add(region)) out.add(region); + } + return out; + } +} diff --git a/lib/services/repeater_command_service.dart b/lib/services/repeater_command_service.dart index 12d4cad4..845e4a12 100644 --- a/lib/services/repeater_command_service.dart +++ b/lib/services/repeater_command_service.dart @@ -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 _commandPrefixes = {}; final Map _pendingByPrefix = {}; final Map _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 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()); } diff --git a/lib/services/stale_history_sweep.dart b/lib/services/stale_history_sweep.dart new file mode 100644 index 00000000..b6e9bcc1 --- /dev/null +++ b/lib/services/stale_history_sweep.dart @@ -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 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 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 eligible; + + /// Keys already known to be unverifiable, so they would be kept. Saying so + /// before the press beats reporting it afterwards. + final List 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 _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 preview({ + Duration? olderThan, + DateTime? now, + bool includeNewlyStamped = false, + }) async { + final window = olderThan ?? staleHistoryWindow; + final at = now ?? DateTime.now(); + + final eligible = []; + final refused = []; + 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 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 = []; + final refused = []; + + 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, + ); + } +} diff --git a/lib/services/stock_config_export_service.dart b/lib/services/stock_config_export_service.dart index a968accc..3c9e46c0 100644 --- a/lib/services/stock_config_export_service.dart +++ b/lib/services/stock_config_export_service.dart @@ -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, diff --git a/lib/services/stock_config_import_service.dart b/lib/services/stock_config_import_service.dart index 39f574ed..9f2db4a2 100644 --- a/lib/services/stock_config_import_service.dart +++ b/lib/services/stock_config_import_service.dart @@ -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, diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 0c78c592..d1d3f1a4 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -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 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 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; return ContactPathHistory.fromJson(contactPubKeyHex, json); } catch (e) { + appLogger.error( + 'Failed to decode path history for $contactPubKeyHex: $e', + tag: 'Storage', + ); return null; } } Future 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 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> loadPendingMessages() async { + /// Removes the pre-#854 untagged `path_history_` 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 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; - 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.delayed(Duration.zero); + } } - } - - Future savePendingMessages(Map pending) async { - final prefs = PrefsManager.instance; - final jsonStr = jsonEncode(pending); - await prefs.setString(_pendingMessagesKey, jsonStr); - } - Future 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 saveDeliveryObservations( List 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> 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)) .toList(); } catch (e) { + appLogger.error( + 'Failed to decode delivery observations: $e', + tag: 'Storage', + ); return []; } } Future 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 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; } } diff --git a/lib/storage/channel_message_store.dart b/lib/storage/channel_message_store.dart index 831a5791..9c5bd445 100644 --- a/lib/storage/channel_message_store.dart +++ b/lib/storage/channel_message_store.dart @@ -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 = {}; + + 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) { + final m = ChannelMessageStore._messageFromJson(e as Map); + byKey[ChannelMessageStore._mergeKey(m)] = m; + } + } + + for (final e in jsonDecode(incomingJson) as List) { + final m = ChannelMessageStore._messageFromJson(e as Map); + 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 = []; + var removed = false; + for (final e in jsonDecode(stored) as List) { + final m = ChannelMessageStore._messageFromJson(e as Map); + 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 channelHistoryToRows(String blobJson) { + return (jsonDecode(blobJson) as List).map((e) { + final map = e as Map; + 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 = {}; - final existing = await blobs.readWithPrefsFallback(key); - if (existing != null && existing.isNotEmpty) { - try { - for (final e in jsonDecode(existing) as List) { - final m = _messageFromJson(e as Map); - 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 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 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 raw; - try { - raw = jsonDecode(existing) as List; - } 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)) - .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; return jsonList.map((json) => _messageFromJson(json)).toList(); @@ -223,14 +334,34 @@ class ChannelMessageStore { } } + List _decodePayloads(List payloads, String key) { + final out = []; + for (final p in payloads) { + try { + out.add(_messageFromJson(jsonDecode(p) as Map)); + } 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 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 _messageToJson(ChannelMessage msg) { + static Map _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 json) { + static ChannelMessage _messageFromJson(Map json) { final rawText = json['text'] as String; final decodedText = Smaz.tryDecodePrefixed(rawText) ?? rawText; return ChannelMessage( @@ -325,7 +461,7 @@ class ChannelMessageStore { ); } - Map _repeatToJson(Repeat repeat) { + static Map _repeatToJson(Repeat repeat) { return { 'repeaterKey': repeat.repeaterKey != null ? base64Encode(repeat.repeaterKey!) @@ -336,7 +472,7 @@ class ChannelMessageStore { }; } - Repeat _repeatFromJson(Map json) { + static Repeat _repeatFromJson(Map json) { return Repeat( repeaterKey: json['repeaterKey'] != null ? Uint8List.fromList(base64Decode(json['repeaterKey'])) diff --git a/lib/storage/channel_region_scope_store.dart b/lib/storage/channel_region_scope_store.dart new file mode 100644 index 00000000..89995266 --- /dev/null +++ b/lib/storage/channel_region_scope_store.dart @@ -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 scopeFor(int channelIndex) async { + if (publicKeyHex.isEmpty) return null; + return PrefsManager.instance.getString(_key(channelIndex)); + } + + /// Scope [channelIndex] to [regionName]. + Future 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 clearScope(int channelIndex) async { + if (publicKeyHex.isEmpty) return; + await PrefsManager.instance.remove(_key(channelIndex)); + } +} diff --git a/lib/storage/contact_discovery_store.dart b/lib/storage/contact_discovery_store.dart index 7622fdb9..1e8d9971 100644 --- a/lib/storage/contact_discovery_store.dart +++ b/lib/storage/contact_discovery_store.dart @@ -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> 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 saveContacts(List 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 _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, diff --git a/lib/storage/contact_settings_store.dart b/lib/storage/contact_settings_store.dart index 17832586..7bc427ee 100644 --- a/lib/storage/contact_settings_store.dart +++ b/lib/storage/contact_settings_store.dart @@ -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 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 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 loadCyr2LatEnabled(String contactKeyHex) async { if (publicKeyHex.isEmpty) { appLogger.warn( diff --git a/lib/storage/contact_store.dart b/lib/storage/contact_store.dart index 9a647864..d478dd22 100644 --- a/lib/storage/contact_store.dart +++ b/lib/storage/contact_store.dart @@ -104,7 +104,17 @@ class ContactStore { Map _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 diff --git a/lib/storage/drift/blob_store.dart b/lib/storage/drift/blob_store.dart index ea75b9f3..e14662cc 100644 --- a/lib/storage/drift/blob_store.dart +++ b/lib/storage/drift/blob_store.dart @@ -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 upsertMessageRows( + String storeKey, + Iterable 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> 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> 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?> missingFromRows( + String storeKey, + BlobToRowsCallback toRows, + ) async { + final blob = await readWithPrefsFallback(storeKey); + if (blob == null || blob.isEmpty) return const []; + + final int sourceCount; + final List 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? missing})> reclaimVerifiedHistoryBlob( + String storeKey, + BlobToRowsCallback toRows, + ) { + return synchronized(storeKey, () async { + if (await read(storeKey) == null) { + return (deleted: false, missing: const []); + } + final missing = await missingFromRows(storeKey, toRows); + if (missing == null || missing.isNotEmpty) { + return (deleted: false, missing: missing); + } + await delete(storeKey); + return (deleted: true, missing: const []); + }); + } + + /// 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 _absentFrom( + Iterable wanted, + Set 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 databaseSizeBytes() async { + Future 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 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 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 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 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 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> 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? _migratedKeys; + + Future> _loadMigratedKeys() async { + if (_migratedKeys != null) return _migratedKeys!; + final raw = await read(migratedMarkerKey); + if (raw == null || raw.isEmpty) return _migratedKeys = {}; + try { + return _migratedKeys = (jsonDecode(raw) as List) + .cast() + .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 = {}; + } + } + + Future _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 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? _migratedAt; + + Future> _loadMigratedAt() async { + if (_migratedAt != null) return _migratedAt!; + final raw = await read(migratedAtKey); + if (raw == null || raw.isEmpty) return _migratedAt = {}; + try { + return _migratedAt = (jsonDecode(raw) as Map).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 = {}; + } + } + + Future _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 appendReclaimAudit({ + required DateTime at, + required List cleared, + required List 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>> reclaimAudit() async { + final raw = await read(reclaimAuditKey); + if (raw == null || raw.isEmpty) return >[]; + try { + return (jsonDecode(raw) as List) + .cast>() + .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 >[]; + } + } + + /// When [storeKey] migrated to rows, or null if it has not or is unstamped. + Future 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> 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 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 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 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 = {}; + 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 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).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 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; diff --git a/lib/storage/drift/offband_database.dart b/lib/storage/drift/offband_database.dart index 0c91e57c..d9fd98c5 100644 --- a/lib/storage/drift/offband_database.dart +++ b/lib/storage/drift/offband_database.dart @@ -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 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 get primaryKey => {storeKey, mergeKey}; +} diff --git a/lib/storage/message_store.dart b/lib/storage/message_store.dart index d7951531..edefa2af 100644 --- a/lib/storage/message_store.dart +++ b/lib/storage/message_store.dart @@ -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 = {}; + + if (stored != null && stored.isNotEmpty) { + for (final e in jsonDecode(stored) as List) { + final m = MessageStore._messageFromJson(e as Map); + byKey[MessageStore._mergeKey(m)] = m; + } + } + + for (final e in jsonDecode(incomingJson) as List) { + final m = MessageStore._messageFromJson(e as Map); + 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 = []; + var removed = false; + for (final e in jsonDecode(stored) as List) { + final m = MessageStore._messageFromJson(e as Map); + 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 dmHistoryToRows(String blobJson) { + return (jsonDecode(blobJson) as List).map((e) { + final map = e as Map; + 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 = {}; - final existing = await blobs.readWithPrefsFallback(key); - if (existing != null && existing.isNotEmpty) { - try { - for (final e in jsonDecode(existing) as List) { - final m = _messageFromJson(e as Map); - 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 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 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 raw; - try { - raw = jsonDecode(existing) as List; - } 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)) - .where((m) => _mergeKey(m) != target) - .toList(); - await BlobStore.instance.write( - key, - jsonEncode(kept.map(_messageToJson).toList()), - ); + await blobs.mergeOffThread(key, _mergeKey(message), dropFromDmHistoryJson); } Future> 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; return jsonList.map((json) => _messageFromJson(json)).toList(); @@ -132,6 +212,23 @@ class MessageStore { } } + List _decodePayloads(List payloads, String key) { + final out = []; + for (final p in payloads) { + try { + out.add(_messageFromJson(jsonDecode(p) as Map)); + } 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 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 _messageToJson(Message msg) { + static Map _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 json) { + static Message _messageFromJson(Map 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?, diff --git a/lib/storage/scoping_inventory.dart b/lib/storage/scoping_inventory.dart new file mode 100644 index 00000000..8c7d2858 --- /dev/null +++ b/lib/storage/scoping_inventory.dart @@ -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 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 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', +}; diff --git a/lib/utils/file_log_writer.dart b/lib/utils/file_log_writer.dart index 625222f7..c64693ff 100644 --- a/lib/utils/file_log_writer.dart +++ b/lib/utils/file_log_writer.dart @@ -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> existingFiles() async { + if (!await dir.exists()) return const []; + final byName = {}; + for (final entry in await dir.list(followLinks: false).toList()) { + if (entry is File) byName[entry.uri.pathSegments.last] = entry; + } + final ordered = []; + 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 writeLine(String line) async { diff --git a/lib/utils/log_export.dart b/lib/utils/log_export.dart index 2532cf4e..8d17f319 100644 --- a/lib/utils/log_export.dart +++ b/lib/utils/log_export.dart @@ -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 logs; + if (_isMobile) { + logs = await FileLogService.instance.flushAndGetAllFiles(); + } else { + final active = await FileLogService.instance.flushAndGetActiveFile(); + logs = active == null ? const [] : [active]; + } + final candidates = [ + ...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 = []; + 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 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; } diff --git a/lib/widgets/channel_notify_mode.dart b/lib/widgets/channel_notify_mode.dart index c87486bf..b58b13e9 100644 --- a/lib/widgets/channel_notify_mode.dart +++ b/lib/widgets/channel_notify_mode.dart @@ -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(); - final identityKey = channelNotifyKeyFor(channel); + final devicePrefix = context.read().selfPublicKeyHex; final current = settingsService.channelNotifyMode( - identityKey: identityKey, - channelName: channel.name, + devicePrefix: devicePrefix, + pskHex: channel.pskHex, ); showDialog( @@ -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, ); diff --git a/lib/widgets/channel_region_scope_dialog.dart b/lib/widgets/channel_region_scope_dialog.dart new file mode 100644 index 00000000..58cd3548 --- /dev/null +++ b/lib/widgets/channel_region_scope_dialog.dart @@ -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 repeaters; + final RegionDiscoveryService service; + final Future Function(String? region) onSave; + + @override + State createState() => + _ChannelRegionScopeDialogState(); +} + +class _ChannelRegionScopeDialogState extends State { + // 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 _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 = []; + + 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 = {}; + 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), + ); + } +} diff --git a/lib/widgets/contact_rename_dialog.dart b/lib/widgets/contact_rename_dialog.dart new file mode 100644 index 00000000..c3fc21f1 --- /dev/null +++ b/lib/widgets/contact_rename_dialog.dart @@ -0,0 +1,138 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../l10n/l10n.dart'; +import '../models/contact.dart'; + +/// The longest custom name we accept. +/// +/// There is no wire constraint: a custom name never leaves this device, so +/// #636's grapheme truncation does not apply to it. The cap exists so a tile +/// stays readable, and it matches the 32-byte on-wire name field closely +/// enough that it will not surprise anyone coming from stock. Counted in +/// characters rather than bytes, since bytes would mean "shorter for CJK" for +/// no reason here. (#750) +const int maxCustomNameLength = 32; + +/// Lets the user give a contact their own name, the way stock MeshCore's +/// CUSTOM NAME field does. (#750) +/// +/// The node keeps its own name underneath, and adverts keep that up to date, +/// so renaming never costs accuracy. Clearing reverts to whatever the node +/// last told us, which may be newer than what was shown when the rename +/// happened. +Future showContactRenameDialog(BuildContext context, Contact contact) => + showDialog( + context: context, + builder: (_) => _ContactRenameDialog(contact: contact), + ); + +class _ContactRenameDialog extends StatefulWidget { + const _ContactRenameDialog({required this.contact}); + + final Contact contact; + + @override + State<_ContactRenameDialog> createState() => _ContactRenameDialogState(); +} + +class _ContactRenameDialogState extends State<_ContactRenameDialog> { + late final TextEditingController _controller = TextEditingController( + text: widget.contact.customName ?? '', + ); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + bool get _tooLong => _controller.text.characters.length > maxCustomNameLength; + + Future _save() async { + if (_tooLong) return; + final connector = context.read(); + final navigator = Navigator.of(context); + // An empty or whitespace-only field is a clear, not a blank name. + // Normalized HERE as well as in the connector and the store, so none of + // the three is load-bearing on its own and the dialog never hands a blank + // downstream to be cleaned up. (T29, T30) + final typed = _controller.text; + await connector.setContactCustomName( + widget.contact.publicKeyHex, + typed.trim().isEmpty ? null : typed, + ); + navigator.pop(); + } + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + + return AlertDialog( + title: Text(l10n.contact_renameTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _controller, + autofocus: true, + decoration: InputDecoration( + hintText: l10n.contact_renameHint, + // Present only while the input is actually too long, absent when + // it is valid. (T27) + errorText: _tooLong + ? l10n.contact_renameTooLong(maxCustomNameLength) + : null, + ), + onChanged: (_) => setState(() {}), + onSubmitted: (_) => _save(), + ), + const SizedBox(height: 12), + // What the node calls itself, shown at the moment of the decision + // and only when it differs from what is typed, so the user can see + // the name they are overriding rather than having to remember it. + // (T25, T26) + if (_controller.text.trim() != widget.contact.receivedName) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Text( + l10n.contact_nodeCallsItself(widget.contact.receivedName), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + // Says plainly that this is local and that accuracy is not lost, so + // nobody has to guess what renaming costs them. + Text( + l10n.contact_renameExplain, + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + actions: [ + TextButton( + onPressed: () async { + final connector = context.read(); + final navigator = Navigator.of(context); + await connector.setContactCustomName( + widget.contact.publicKeyHex, + null, + ); + navigator.pop(); + }, + child: Text(l10n.contact_renameClear), + ), + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.common_cancel), + ), + FilledButton( + onPressed: _tooLong ? null : _save, + child: Text(l10n.common_save), + ), + ], + ); + } +} diff --git a/lib/widgets/contact_settings_dialog.dart b/lib/widgets/contact_settings_dialog.dart index 31c32650..5c865e15 100644 --- a/lib/widgets/contact_settings_dialog.dart +++ b/lib/widgets/contact_settings_dialog.dart @@ -23,6 +23,7 @@ void showContactSettingsDialog(BuildContext context, Contact contact) { bool teleBaseEnabled = contact.teleBaseEnabled; bool teleLocEnabled = contact.teleLocEnabled; bool teleEnvEnabled = contact.teleEnvEnabled; + bool remoteCliEnabled = contact.remoteCliAllowed; showDialog( context: context, builder: (context) => StatefulBuilder( @@ -115,6 +116,16 @@ void showContactSettingsDialog(BuildContext context, Contact contact) { setDialogState(() => teleEnvEnabled = value); }, ), + const Divider(height: 8), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: Text(context.l10n.contact_remoteCli), + subtitle: Text(context.l10n.contact_remoteCliSubtitle), + value: remoteCliEnabled, + onChanged: (value) { + setDialogState(() => remoteCliEnabled = value); + }, + ), ], ), ), @@ -126,6 +137,7 @@ void showContactSettingsDialog(BuildContext context, Contact contact) { teleBase: teleBaseEnabled, teleLoc: teleLocEnabled, teleEnv: teleEnvEnabled, + remoteCli: remoteCliEnabled, ); Navigator.pop(context); }, diff --git a/lib/widgets/device_ui_error_banner.dart b/lib/widgets/device_ui_error_banner.dart new file mode 100644 index 00000000..1aa52a4d --- /dev/null +++ b/lib/widgets/device_ui_error_banner.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart'; + +/// The radio's refusal of a device-UI write, shown until dismissed rather than +/// flashed: an error the user cannot finish reading is not a surfaced error. +class DeviceUiErrorBanner extends StatelessWidget { + const DeviceUiErrorBanner({ + super.key, + required this.message, + required this.onDismiss, + this.margin = const EdgeInsets.all(12), + }); + + final String message; + final VoidCallback onDismiss; + final EdgeInsetsGeometry margin; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Container( + margin: margin, + 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, + ), + ], + ), + ); + } +} diff --git a/lib/widgets/radio_tone.dart b/lib/widgets/radio_tone.dart new file mode 100644 index 00000000..5edf75e9 --- /dev/null +++ b/lib/widgets/radio_tone.dart @@ -0,0 +1,332 @@ +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../connector/offband_device_ui.dart'; +import '../connector/offband_tones.dart'; +import '../models/channel.dart'; + +/// The radio's tune picker (#971, #986), shared by the six event tones and a +/// channel's own tone, so every entry point offers the same list the badge's +/// picker does. A channel's "Radio tone" row lives here too, reachable from +/// the Channels sheet and the channel chat menu, so the two cannot drift. +/// +/// English-only, matching [DeviceUiView] which hosts the event rows. + +IconData tuneIcon(int? id) => id == null + ? Icons.sync + : id == tuneSilent + ? Icons.volume_off_outlined + : Icons.music_note_outlined; + +/// The radio's reason a preview made no sound, or null when it played. +String? describeTunePlay(TunePlayResult? result) => switch (result) { + TunePlayResult.played => null, + TunePlayResult.busy => + 'The radio is playing a notification. Try again in a moment.', + TunePlayResult.soundOff => + 'Sound is off on this radio. Set the scope to All or Self to hear it.', + null => 'The radio did not play that tune.', +}; + +/// A tune choice from [showTunePickerDialog]. +sealed class TuneChoice { + const TuneChoice(); +} + +/// "Default": no choice, follow the radio's tone. Offered only to a channel. +class DefaultTuneChoice extends TuneChoice { + const DefaultTuneChoice(); +} + +class TuneIdChoice extends TuneChoice { + const TuneIdChoice(this.id); + final int id; +} + +/// Show the picker. [current] is the row to mark; null marks Default. Returns +/// the choice, or null when the user cancels. +/// +/// The play button auditions on the radio and never chooses; tapping a name +/// chooses (owner decision 2026-10-25). Only what firmware accepts is listed: +/// named built-ins and filled slots. +Future showTunePickerDialog( + BuildContext context, { + required String title, + String? description, + required int? current, + String? defaultSubtitle, + bool withDefault = false, +}) { + return showDialog( + context: context, + builder: (dialogContext) => _TunePickerDialog( + title: title, + description: description, + current: current, + defaultSubtitle: defaultSubtitle, + withDefault: withDefault, + ), + ); +} + +class _TunePickerDialog extends StatefulWidget { + const _TunePickerDialog({ + required this.title, + required this.description, + required this.current, + required this.defaultSubtitle, + required this.withDefault, + }); + + final String title; + final String? description; + final int? current; + final String? defaultSubtitle; + final bool withDefault; + + @override + State<_TunePickerDialog> createState() => _TunePickerDialogState(); +} + +class _TunePickerDialogState extends State<_TunePickerDialog> { + /// A preview's refusal, shown inside the dialog: a snackbar would sit + /// behind the dialog's scrim. + String? _playNote; + + Future _play(MeshCoreConnector connector, int id) async { + setState(() => _playNote = null); + final result = await connector.playTune(id); + if (!mounted) return; + setState(() => _playNote = describeTunePlay(result)); + } + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Consumer( + builder: (context, connector, _) { + final slots = connector.tuneSlots; + final ids = offeredTuneIds(slots); + final builtins = ids.where((id) => !isSlotTuneId(id)).toList(); + final custom = ids.where(isSlotTuneId).toList(); + + Widget row(int id) { + final selected = id == widget.current; + return ListTile( + leading: Icon(tuneIcon(id)), + title: Text(tuneLabel(id, slots) ?? 'Tune $id'), + subtitle: selected ? const Text('Current') : null, + selected: selected, + trailing: id == tuneSilent + ? null + : IconButton( + icon: const Icon(Icons.play_circle_outline), + color: scheme.primary, + tooltip: 'Play on the radio', + onPressed: () => _play(connector, id), + ), + onTap: () => Navigator.pop(context, TuneIdChoice(id)), + ); + } + + return AlertDialog( + title: Text(widget.title), + contentPadding: const EdgeInsets.symmetric(vertical: 8), + content: SizedBox( + width: double.maxFinite, + child: ListView( + shrinkWrap: true, + children: [ + if (widget.description != null) + Padding( + padding: const EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text(widget.description!), + ), + if (_playNote != null) + Padding( + padding: const EdgeInsets.fromLTRB(24, 0, 24, 8), + child: Text( + _playNote!, + style: TextStyle(color: scheme.error), + ), + ), + if (widget.withDefault) ...[ + ListTile( + leading: Icon(tuneIcon(null)), + title: const Text('Default'), + subtitle: widget.defaultSubtitle == null + ? null + : Text(widget.defaultSubtitle!), + selected: widget.current == null, + trailing: widget.current == null + ? const Icon(Icons.check) + : null, + onTap: () => + Navigator.pop(context, const DefaultTuneChoice()), + ), + const Divider(height: 1), + ], + for (final id in builtins) row(id), + if (custom.isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(24, 12, 24, 4), + child: Text( + 'Your tunes', + style: Theme.of(context).textTheme.labelMedium, + ), + ), + for (final id in custom) row(id), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: const Text('Cancel'), + ), + ], + ); + }, + ); + } +} + +/// What a channel's Default plays: the Channel event's effective tune, when +/// the radio has reported it. +String _defaultSubtitle(MeshCoreConnector connector) { + final effective = connector.eventTone(ToneEvent.channel)?.effective; + final name = effective == null + ? null + : tuneLabel(effective, connector.tuneSlots); + return name == null + ? 'The radio\'s channel tone' + : '$name, the radio\'s channel tone'; +} + +/// The subtitle for a channel's Radio tone row. +String channelRadioToneLabel(MeshCoreConnector connector, int channel) { + final tune = connector.channelTuneFor(channel); + if (tune == null) return 'Reading from the radio'; + if (tune.inherits) return 'Default'; + return tuneLabel(tune.tuneId!, connector.tuneSlots) ?? 'Tune ${tune.tuneId}'; +} + +/// Read what the Radio tone row and its picker need. +void requestChannelRadioTone(MeshCoreConnector connector, int channel) { + connector.requestChannelTune(channel); + connector.requestEventTones(); + connector.requestTuneSlots(); +} + +/// Show the radio's refusal of a write to [surface] as a snackbar that stays +/// until dismissed, for screens with no banner of their own. Watches for a few +/// seconds after the write; a confirmed write shows nothing. +void showRefusalWhenItArrives( + BuildContext context, + MeshCoreConnector connector, + DeviceUiSurface surface, +) { + final messenger = ScaffoldMessenger.maybeOf(context); + if (messenger == null) return; + late final VoidCallback listener; + listener = () { + final error = connector.deviceUiError; + if (connector.deviceUiErrorSurface != surface || error == null) return; + connector.removeListener(listener); + messenger.showSnackBar( + SnackBar( + content: Text(error), + duration: const Duration(days: 1), + action: SnackBarAction( + label: 'OK', + onPressed: connector.clearDeviceUiError, + ), + ), + ); + }; + connector.addListener(listener); + Future.delayed( + const Duration(seconds: 5), + () => connector.removeListener(listener), + ); +} + +Future showChannelRadioToneDialog( + BuildContext context, + Channel channel, +) async { + final connector = context.read(); + final tune = connector.channelTuneFor(channel.index); + final choice = await showTunePickerDialog( + context, + title: 'Radio tone', + description: channel.name, + current: tune?.tuneId, + defaultSubtitle: _defaultSubtitle(connector), + withDefault: true, + ); + if (choice != null && context.mounted) { + showRefusalWhenItArrives(context, connector, DeviceUiSurface.channelTune); + } + switch (choice) { + case DefaultTuneChoice(): + await connector.setChannelTune( + channel.index, + const ChannelTune.inherit(), + ); + case TuneIdChoice(:final id): + await connector.setChannelTune(channel.index, ChannelTune.tune(id)); + case null: + break; + } +} + +/// The channel sheet's Radio tone row. Reads the channel's tune when shown, so +/// its subtitle is the radio's answer. Shown only with caps byte 2 `0x10`. +class ChannelRadioToneTile extends StatefulWidget { + const ChannelRadioToneTile({ + super.key, + required this.channel, + required this.onTap, + }); + + final Channel channel; + final VoidCallback onTap; + + @override + State createState() => _ChannelRadioToneTileState(); +} + +class _ChannelRadioToneTileState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final c = context.read(); + if (c.supportsTunes) requestChannelRadioTone(c, widget.channel.index); + }); + } + + @override + Widget build(BuildContext context) { + final connector = context.watch(); + if (!connector.supportsTunes) return const SizedBox.shrink(); + final tune = connector.channelTuneFor(widget.channel.index); + return ListTile( + leading: Icon(tune == null ? Icons.sync : tuneIcon(tune.tuneId)), + title: const Text('Radio tone'), + subtitle: Text(channelRadioToneLabel(connector, widget.channel.index)), + onTap: widget.onTap, + ); + } +} + +/// Whether [surface]'s refusal belongs on a tone screen. +bool isToneSurface(DeviceUiSurface? surface) => + surface == DeviceUiSurface.channelTune || + surface == DeviceUiSurface.eventTone || + surface == DeviceUiSurface.tunePlay || + surface == DeviceUiSurface.tuneSlot; diff --git a/lib/widgets/storage_reclaim_card.dart b/lib/widgets/storage_reclaim_card.dart new file mode 100644 index 00000000..4e25a273 --- /dev/null +++ b/lib/widgets/storage_reclaim_card.dart @@ -0,0 +1,293 @@ +import 'package:flutter/material.dart'; + +import '../l10n/app_localizations.dart'; +import '../l10n/l10n.dart'; +import '../services/stale_history_sweep.dart'; +import '../storage/drift/blob_store.dart'; +import '../utils/app_logger.dart'; + +/// "Clear Stale History Now": the manual trigger for the #962 sweep. +/// +/// A migrated message key keeps a frozen copy of its history, which the sweep +/// reclaims 30 days later on its own. This is for not waiting. +/// +/// Its own widget rather than another card inside `app_settings_view.dart`, +/// which is already past a thousand lines, and so that B2's tests can drive it +/// without standing up the whole settings screen. +/// +/// Stateful, against the repo's usual StatelessWidget-plus-Consumer habit, +/// because the running flag and the last result are local to this card and +/// belong to no service. +class StorageReclaimCard extends StatefulWidget { + const StorageReclaimCard({ + super.key, + BlobStore? blobs, + Future Function()? runPreview, + Future Function()? runSweep, + Future Function()? readSize, + }) : _blobs = blobs, + _runPreview = runPreview, + _runSweep = runSweep, + _readSize = readSize; + + /// Injectable for tests; production reads the singleton. + final BlobStore? _blobs; + + /// The preview, injectable for the same reason as the sweep. + final Future Function()? _runPreview; + + /// The sweep, injectable. + /// + /// Not only for convenience: the real sweep uses `compute`, and an isolate + /// deadlocks `pumpAndSettle` inside `flutter_test`'s fake-async zone. The + /// sweep's own behaviour is covered by Epic A's unit tests, which run under + /// plain `test()` where isolates work. What is left to prove here is that + /// this card reports each outcome correctly, and that is testable without + /// re-running the engine. + final Future Function()? _runSweep; + + /// The size read, injectable for the same reason. + final Future Function()? _readSize; + + @override + State createState() => _StorageReclaimCardState(); +} + +class _StorageReclaimCardState extends State { + BlobStore get _blobs => widget._blobs ?? BlobStore.instance; + + bool _running = false; + int? _sizeBytes; + StaleHistoryOutcome? _result; + Object? _error; + + @override + void initState() { + super.initState(); + _refreshSize(); + } + + Future _refreshSize() async { + try { + final size = await (widget._readSize ?? _blobs.databaseSizeBytes)(); + if (mounted) setState(() => _sizeBytes = size); + } catch (e) { + // A size we cannot read is not worth an error state: the action below + // still works, and the row simply shows nothing. + appLogger.warn('Could not read the database size: $e', tag: 'Storage'); + } + } + + Future _clear() async { + // The disabled button is not enough on its own. `setState` only schedules + // a rebuild, so two taps inside one frame both see an `onPressed` that is + // still non-null and both reach here, which would run two sweeps and two + // VACUUMs concurrently (Gemini review). + if (_running) return; + setState(() { + _running = true; + _result = null; + _error = null; + }); + try { + // Ask what WOULD go, then ask the user, then do it. Mockup variants 8 + // to 10, owner-approved 2026-10-23: a delete this size has to state its + // scope before it runs. + final preview = await (widget._runPreview ?? _defaultPreview)(); + if (!mounted) return; + + // Nothing to clear means nothing to confirm. Reporting straight away + // beats opening a dialog to say zero (variant 10). + if (!preview.hasWork) { + setState( + () => _result = StaleHistoryOutcome( + cleared: const [], + refused: preview.refused, + bytesBefore: _sizeBytes ?? 0, + bytesAfter: _sizeBytes ?? 0, + ), + ); + return; + } + + final go = await _confirm(preview); + if (!go || !mounted) return; + + // `olderThan: Duration.zero` with `includeNewlyStamped` is the whole + // point of the button: every migrated key is eligible immediately, even + // one stamped on this very pass. It skips the WAIT, not the safety; the + // per-key verification under the lock is unchanged. + final outcome = await (widget._runSweep ?? _defaultSweep)(); + if (!mounted) return; + setState(() { + _result = outcome; + _sizeBytes = outcome.bytesAfter; + }); + } catch (e, s) { + appLogger.error('Clear stale history failed: $e\n$s', tag: 'Storage'); + if (!mounted) return; + setState(() => _error = e); + } finally { + if (mounted) setState(() => _running = false); + } + } + + Future _defaultPreview() => StaleHistorySweep( + _blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + Future _defaultSweep() => StaleHistorySweep( + _blobs, + ).run(olderThan: Duration.zero, includeNewlyStamped: true); + + /// The confirmation. Returns false on Cancel, on a tap outside, and on back. + Future _confirm(StaleHistoryPreview p) async { + final l10n = context.l10n; + final scheme = Theme.of(context).colorScheme; + final count = p.eligible.length; + + final ok = await showDialog( + context: context, + builder: (context) => AlertDialog( + title: Text(l10n.storage_confirmTitle), + content: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l10n.storage_confirmBody(count, _mb(p.approximateBytes))), + const SizedBox(height: 12), + _note( + l10n.storage_confirmSafe(p.messagesKept), + Icons.check, + scheme.secondaryContainer, + scheme.onSecondaryContainer, + ), + const SizedBox(height: 8), + _note( + p.refused.isEmpty + ? l10n.storage_confirmIrreversible + : l10n.storage_confirmKeptBack(p.refused.length), + Icons.warning_amber, + scheme.tertiaryContainer, + scheme.onTertiaryContainer, + ), + ], + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: Text(l10n.common_cancel), + ), + FilledButton.tonal( + // Carries the count, so the last thing read before the tap is the + // scope of what it does. + onPressed: () => Navigator.of(context).pop(true), + style: FilledButton.styleFrom( + backgroundColor: scheme.errorContainer, + foregroundColor: scheme.onErrorContainer, + ), + child: Text(l10n.storage_confirmAction(count)), + ), + ], + ), + ); + return ok ?? false; + } + + Widget _note(String text, IconData icon, Color bg, Color fg) => Container( + width: double.infinity, + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(8), + ), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, size: 16, color: fg), + const SizedBox(width: 6), + Expanded( + child: Text(text, style: TextStyle(fontSize: 13, color: fg)), + ), + ], + ), + ); + + static String _mb(int bytes) => + '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB'; + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l10n.storage_title, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + if (_sizeBytes != null) + Text(l10n.storage_databaseSize(_mb(_sizeBytes!))), + const SizedBox(height: 8), + Text( + l10n.storage_staleHint, + style: TextStyle(fontSize: 12, color: Colors.grey[600]), + ), + const SizedBox(height: 12), + Align( + alignment: Alignment.centerLeft, + child: FilledButton.tonal( + onPressed: _running ? null : _clear, + child: Text( + _running ? l10n.storage_working : l10n.storage_clearStaleNow, + ), + ), + ), + ?_resultLine(l10n), + ], + ), + ), + ); + } + + Widget? _resultLine(AppLocalizations l10n) { + if (_error != null) { + return Padding( + padding: const EdgeInsets.only(top: 12), + child: Text( + l10n.storage_resultFailed, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ); + } + final r = _result; + if (r == null) return null; + + final lines = [ + if (r.cleared.isEmpty) + l10n.storage_resultNothing + else + l10n.storage_resultCleared( + r.cleared.length, + _mb(r.bytesReclaimed < 0 ? 0 : r.bytesReclaimed), + ), + // Owner decision 2026-10-22: the button reports what it refused, it does + // not just log it. A key kept back because its rows could not be + // verified is the single most useful thing this action can tell you, and + // staying quiet about it is how #952 went unnoticed for days. + if (r.refused.isNotEmpty) l10n.storage_resultRefused(r.refused.length), + ]; + + return Padding( + padding: const EdgeInsets.only(top: 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [for (final line in lines) Text(line)], + ), + ); + } +} diff --git a/play/1.7.0.txt b/play/1.7.0.txt new file mode 100644 index 00000000..7dbcfe1d --- /dev/null +++ b/play/1.7.0.txt @@ -0,0 +1,3 @@ +Offband Meshcore 1.7.0 + +Message history moves to a faster storage format on first launch. After updating, earlier versions of the app cannot open it. Each radio now keeps its own contacts, blocks, and notification settings. The contact list follows your radio, with no phantom contacts. Give any contact a custom name. Region scoping for channels, a tidier Settings, and a steadier Bluetooth reconnect. diff --git a/pubspec.yaml b/pubspec.yaml index c34e5ee2..61ec2e79 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev # https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html # In Windows, build-name is used as the major, minor, and patch parts # of the product and file versions while build-number is used as the build suffix. -version: 1.6.0+67 +version: 1.7.0+68 environment: sdk: ^3.9.2 diff --git a/release-notes/1.7.0.md b/release-notes/1.7.0.md new file mode 100644 index 00000000..6fc88e19 --- /dev/null +++ b/release-notes/1.7.0.md @@ -0,0 +1,105 @@ +## Offband Meshcore 1.7.0 + +A foundations release. Message history moves to a new storage format that stays fast no +matter how much of it you have, every radio you connect now keeps its own data, and the +contact list follows what your radio actually holds. On top of that: custom contact +names, region scoping for channels, a reorganized Settings, a CLI console for stock +MeshCore 1.18 companions, and a steadier Bluetooth reconnect. Over 100 changes since +1.6.0. + +### Please read before updating: a one-way storage upgrade + +The first time 1.7.0 starts, it converts your message history to a new database format. +**After that, going back to an earlier version of the app is not possible**: older +versions cannot open the converted database. Your messages carry over; the conversion +checks every conversation and keeps the original data for any it cannot verify. + +The old copy of your history is kept for 30 days and then cleared automatically. Until +then the database is larger than before, because it briefly holds your history twice. +To reclaim that space now, use **App Settings > Storage > Clear Stale History Now**. It +asks first, shows what will be cleared, and never touches your messages. Anything it +cannot verify, it keeps and tells you so (#917, #919, #920, #943, #952, #962, #965, #966). + +### Message storage that keeps up + +- History is stored **one row per message** instead of one large block per + conversation, so receiving a message costs the same at 50,000 messages of history as + at 50 (#920). +- Saving, merging, and deleting history now run **off the UI thread**, so a long + channel no longer stalls the screen (#919). + +### Every radio keeps its own data + +If you use more than one radio, switching between them no longer mixes their data: + +- **Discovered nodes** belong to the radio that heard them (#754). +- **Blocked contacts** belong to the radio that holds them, and a brand-new radio no + longer comes up with another radio's blocks (#471). With no radio connected, the + Blocked pane says so instead of looking empty (#938). +- **Channel notification modes** are set per radio and can be reset properly (#839). +- **Path history and delivery records** are kept per radio (#937). +- After a dropped connection, connecting a different radio no longer briefly shows the + previous radio's history (#939). Isolation is checked across radio switches and app + restarts (#940). + +### Contacts that match your radio + +- The contact list now comes from your radio's own contact sync. Overheard adverts the + radio rejected (past its hop limit or capacity) no longer pile up as phantom + contacts, and a contact the radio does store still appears on its own, with no + manual sync needed (#838). +- **Custom names**: give any contact a name of your own. Adverts keep updating what the + node calls itself underneath without moving your label, and where the two differ you + can see both. Your label is never sent over the air or included in exports or + contact shares. Custom names belong to the radio you set them on (#750). + +### Region scoping + +- **Discover the regions** a repeater knows, then **set a channel's region scope** so + its messages flood only within that region. The repeater picker is searchable and + lists the repeaters you can actually reach (#812, #830, #836). +- Requires MeshCore companion firmware 1.16 or newer, or current Offband firmware. On + older firmware the option stays hidden. + +### Settings, reorganized + +- **Location** is its own Settings category and the one place for GPS (#977). +- **Button actions** stay in Node Settings, and **Buzzer and tones** moves to Message + Settings, since some boards have a buzzer and no buttons (#978). +- Config import and export, GPX exports, and "Sync queued messages now" moved to + **Actions**, and the Debug section is reordered (#902). +- Event tones, custom tune editing, screen settings, and a GPS Off / On / Power save + control are built in, and appear only on a radio whose Offband firmware supports + them. That firmware is not released yet, so for now these stay hidden (#969, #970, + #971, #981, #986, #987). + +### CLI for stock MeshCore 1.18 companions + +- A **Device CLI console** for the connected radio, at the top of the Debug section, + with per-reply timing and secret replies masked (#868). +- **Remote CLI** to another companion over the mesh, from the chat menu's CLI console + action, plus a per-contact **Remote CLI** permission toggle that controls who may run + CLI on your radio. CLI traffic stays in the console and out of your chat (#870). +- Both need a stock MeshCore 1.18 companion; on other firmware they stay hidden. + +### Bluetooth and stability + +- **Automatic reconnect is bounded**: it stops after 5 attempts or 3 minutes, + whichever comes first, **Stop** ends it immediately, and a connection you start + yourself always takes over (#997). +- A connection started while a disconnect was still finishing no longer leaves the + status stuck and the composer unusable (#997). +- Windows: fixed a crash when closing the app (#989). + +### Fixes + +- Messages with 2- or 3-byte path hashes show the right hop count (a 13-hop message + no longer reads as 39 hops), and the Packet Path screen agrees with the chat (#985). +- The Device CLI console now appears on stock MeshCore 1.18.0 radios whose version + string carries a build suffix (#946). + +### For troubleshooting + +- On Android 11 and newer, the exported debug log now includes the system's own record + of why the app last stopped, including any "app not responding" trace, so a report + can explain a freeze without anyone digging (#906). diff --git a/test/benchmarks/anr_block_time_bench.dart b/test/benchmarks/anr_block_time_bench.dart new file mode 100644 index 00000000..4b380d46 --- /dev/null +++ b/test/benchmarks/anr_block_time_bench.dart @@ -0,0 +1,201 @@ +// Epic A verification benchmark (#919 / #917): how long does saving one +// channel message block the isolate that draws the UI? +// +// The filename ends in `_bench`, not `_test`, so a bare `flutter test` does +// not collect it: the numbers depend on the machine and on a local copy of a +// real database, which makes this a measurement tool rather than a gate. It +// lives under test/ anyway so the analyzer treats it as test code. The +// non-flaky gate is test/storage/blob_merge_runs_off_main_isolate_test.dart. +// +// Run it: +// 1. copy a real database somewhere local, e.g. +// cp "$APPDATA/Offband MeshCore/offband_store.sqlite" /tmp/live_copy.sqlite +// 2. flutter test test/benchmarks/anr_block_time_bench.dart \ +// --dart-define=BENCH_DB=/tmp/live_copy.sqlite +// +// Without BENCH_DB it synthesises a payload of a comparable size, which is +// fine for a regression check and useless as evidence about real data. +// +// What it measures: a 1 ms heartbeat timer runs on the main isolate while the +// save happens. The largest gap between heartbeats IS the UI freeze, which is +// what Android's input-dispatch watchdog kills an app for. Wall-clock duration +// of the save is reported too, because the point of Epic A is that those two +// numbers come apart: the work still takes just as long, it just stops +// happening where the UI lives. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const String _benchDb = String.fromEnvironment('BENCH_DB'); + +/// Records the worst gap between 1 ms heartbeats while [action] runs. A gap is +/// time the main isolate was not free to do anything, UI included. +/// +/// The yield before `cancel` is load-bearing. A periodic timer cannot fire +/// while the isolate is blocked, so the gap only becomes visible on the first +/// tick *after* the block; cancelling the moment the action returns throws that +/// tick away and reports a block of 0 ms. Verified: a bare 200 ms busy-wait +/// with no trailing yield measured `fires=0, worst=0ms`, and the same block +/// with a yield measured 200 ms. +/// +/// [fires] is reported for the same reason. A run with few fires has not +/// proven anything, whatever its gap says. +Future<({int maxGapMs, int wallMs, int fires})> _withHeartbeat( + Future Function() action, +) async { + var last = DateTime.now(); + var worst = 0; + var fires = 0; + final beat = Timer.periodic(const Duration(milliseconds: 1), (_) { + final now = DateTime.now(); + final gap = now.difference(last).inMilliseconds; + if (gap > worst) worst = gap; + last = now; + fires++; + }); + final sw = Stopwatch()..start(); + last = DateTime.now(); + await action(); + final wall = sw.elapsedMilliseconds; + // Let the overdue tick land before the timer goes away. + for (var i = 0; i < 3; i++) { + await Future.delayed(Duration.zero); + } + beat.cancel(); + return (maxGapMs: worst, wallMs: wall, fires: fires); +} + +void main() { + test( + 'one save: UI-isolate block time, old path vs new path', + () async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + + String payload; + if (_benchDb.isNotEmpty && File(_benchDb).existsSync()) { + final source = OffbandDatabase(NativeDatabase(File(_benchDb))); + final rows = await source + .customSelect( + 'select value from stored_blobs ' + 'order by length(value) desc limit 1', + ) + .get(); + payload = rows.single.data['value'] as String; + await source.close(); + // ignore: avoid_print + print('payload: real, from $_benchDb'); + } else { + // ignore: avoid_print + print( + 'payload: SYNTHETIC (pass --dart-define=BENCH_DB=... for real ' + 'data; these numbers are not evidence about production)', + ); + final one = jsonEncode({ + 'senderName': 'synthetic', + 'text': 'x' * 120, + 'timestamp': 1700000000000, + 'isOutgoing': false, + 'channelIndex': 0, + 'messageId': 'id', + 'status': 0, + }); + payload = '[${List.filled(9230, one).join(',')}]'; + } + // ignore: avoid_print + print( + 'payload size: ${payload.length} chars ' + '(${(payload.length / 1048576).toStringAsFixed(2)} MiB)', + ); + + final db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + final blobs = BlobStore.instance; + + // One more message arriving, encoded the way the store encodes it. + final incoming = jsonEncode([ + { + 'senderName': 'bench', + 'text': 'the message that just arrived', + 'timestamp': 1800000000000, + 'isOutgoing': false, + 'channelIndex': 0, + 'messageId': 'bench-1', + 'status': 0, + }, + ]); + + // OLD path: exactly what the store did before #919, calling the very + // same merge function inline instead of through compute. Not a strawman: + // the only difference is where it runs. + await blobs.write('old', payload); + final old = await _withHeartbeat(() async { + final stored = await blobs.readWithPrefsFallback('old'); + final merged = mergeChannelHistoryJson((stored, incoming)); + await blobs.write('old', merged); + }); + + // NEW path. + await blobs.write('new', payload); + final fresh = await _withHeartbeat( + () => blobs.mergeOffThread('new', incoming, mergeChannelHistoryJson), + ); + + // A burst of five, which is the case that crosses the watchdog. + await blobs.write('burst_old', payload); + final burstOld = await _withHeartbeat(() async { + for (var i = 0; i < 5; i++) { + final stored = await blobs.readWithPrefsFallback('burst_old'); + await blobs.write( + 'burst_old', + mergeChannelHistoryJson((stored, incoming)), + ); + } + }); + + await blobs.write('burst_new', payload); + final burstNew = await _withHeartbeat(() async { + for (var i = 0; i < 5; i++) { + await blobs.mergeOffThread( + 'burst_new', + incoming, + mergeChannelHistoryJson, + ); + } + }); + + void report(String label, ({int maxGapMs, int wallMs, int fires}) r) { + // ignore: avoid_print + print( + '${label.padRight(26)} UI blocked ${r.maxGapMs}ms ' + 'wall ${r.wallMs}ms (heartbeats ${r.fires})', + ); + } + + // ignore: avoid_print + print(''); + report('1 save, inline (pre-#919)', old); + report('1 save, off-thread (#919)', fresh); + report('5 saves, inline', burstOld); + report('5 saves, off-thread', burstNew); + + await db.close(); + BlobStore.clearTestOverride(); + + // Sanity, not a threshold: the off-thread path must not block longer + // than the inline one. Real thresholds are the owner's device check. + expect(fresh.maxGapMs, lessThanOrEqualTo(old.maxGapMs)); + expect(burstNew.maxGapMs, lessThanOrEqualTo(burstOld.maxGapMs)); + }, + timeout: const Timeout(Duration(minutes: 5)), + ); +} diff --git a/test/benchmarks/legacy_purge_rehearsal_bench.dart b/test/benchmarks/legacy_purge_rehearsal_bench.dart new file mode 100644 index 00000000..6083b883 --- /dev/null +++ b/test/benchmarks/legacy_purge_rehearsal_bench.dart @@ -0,0 +1,189 @@ +// Epic B verification (#937): rehearse the legacy purge against a copy of a +// REAL prefs file and report what it costs and what it leaves behind. +// +// Named `_bench`, not `_test`, so a bare `flutter test` does not collect it: +// it needs a copy of a real prefs file and its numbers are machine-specific. +// The non-flaky gates live in test/services/radio_isolation_bleed_test.dart. +// +// Run it: +// flutter test test/benchmarks/legacy_purge_rehearsal_bench.dart \ +// --dart-define=BENCH_PREFS="$APPDATA/Offband/Offband Meshcore/shared_preferences.json" +// +// It never writes to the file it is given; the contents are loaded into the +// SharedPreferences mock. Without BENCH_PREFS it says it measured nothing +// rather than synthesising a file, because a rehearsal on invented data +// rehearses nothing. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/path_history.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const String _benchPrefs = String.fromEnvironment('BENCH_PREFS'); + +void main() { + test( + 'legacy purge against a real prefs file', + () async { + if (_benchPrefs.isEmpty || !File(_benchPrefs).existsSync()) { + // ignore: avoid_print + print( + 'SKIPPED: no BENCH_PREFS. Pass ' + '--dart-define=BENCH_PREFS=. ' + 'Nothing was measured.', + ); + return; + } + + final raw = File(_benchPrefs).readAsStringSync(); + final decoded = jsonDecode(raw) as Map; + + // SharedPreferences stores keys with a `flutter.` prefix; the mock + // expects them without it. + final seed = {}; + for (final e in decoded.entries) { + final k = e.key.startsWith('flutter.') ? e.key.substring(8) : e.key; + final v = e.value; + if (v is String) seed[k] = v; + if (v is bool) seed[k] = v; + if (v is int) seed[k] = v; + if (v is double) seed[k] = v; + if (v is List) seed[k] = v.map((x) => x.toString()).toList(); + } + + final legacyBefore = seed.keys + .where((k) => k.startsWith('path_history_')) + .length; + final hadGlobalObs = seed.containsKey('delivery_observations'); + + // ignore: avoid_print + print('source: $_benchPrefs'); + // ignore: avoid_print + print( + 'seeded ${seed.length} keys, ${raw.length} bytes of JSON\n' + ' legacy path_history keys: $legacyBefore\n' + ' global delivery_observations present: $hadGlobalObs', + ); + + expect( + legacyBefore, + greaterThan(0), + reason: + 'nothing to rehearse: this prefs file has no legacy keys, so ' + 'it measured nothing', + ); + + SharedPreferences.setMockInitialValues(seed); + PrefsManager.reset(); + await PrefsManager.initialize(); + final db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + final storage = StorageService()..setPublicKeyHex = 'a' * 20; + + // A route stored under the NEW scheme before the purge, to prove the + // purge does not take scoped data with it. + await storage.savePathHistory('cafebabe', _history('cafebabe')); + + // Heartbeat on the main isolate, as in #919's harness: the worst gap + // between beats is the UI freeze the purge would cause. + var last = DateTime.now(); + var worst = 0; + var beats = 0; + final beat = Timer.periodic(const Duration(milliseconds: 1), (_) { + final now = DateTime.now(); + final gap = now.difference(last).inMilliseconds; + if (gap > worst) worst = gap; + last = now; + beats++; + }); + + final sw = Stopwatch()..start(); + last = DateTime.now(); + final removed = await storage.purgeLegacyPathHistory(); + final obsRemoved = await storage.purgeLegacyDeliveryObservations(); + final wall = sw.elapsedMilliseconds; + for (var i = 0; i < 3; i++) { + await Future.delayed(Duration.zero); + } + beat.cancel(); + + final legacyAfter = PrefsManager.instance + .getKeys() + .where((k) => k.startsWith('path_history_')) + .length; + + // ignore: avoid_print + print(''); + // ignore: avoid_print + print('purged $removed path-history keys, observations: $obsRemoved'); + // ignore: avoid_print + print(' wall ${wall}ms worst UI block ${worst}ms beats $beats'); + // ignore: avoid_print + print( + ' !! THOSE TWO TIMINGS ARE NOT THE REAL COST. The\n' + ' SharedPreferences test mock is an in-memory map, so it does\n' + ' NOT do the whole-file re-encode and rewrite that every real\n' + ' `remove` performs on Windows. This rehearsal proves\n' + ' CORRECTNESS: every legacy key gone, scoped data intact,\n' + ' idempotent. For the real cost, simulated against this same\n' + ' file at the plugin\'s actual behaviour: 12.7 s of total work,\n' + ' mean 6.1 ms, 32 ms for the first removal falling below 1 ms by\n' + ' the last as the file collapses 4.28 MB -> 45 KB. That is why\n' + ' the purge yields every 20 removals instead of running flat.', + ); + // ignore: avoid_print + print(' legacy keys left: $legacyAfter'); + // ignore: avoid_print + print( + ' prefs keys remaining: ${PrefsManager.instance.getKeys().length}', + ); + + expect(removed, legacyBefore, reason: 'every legacy key must go'); + expect(legacyAfter, 0); + expect(obsRemoved, hadGlobalObs); + // Deliberately NOT asserting a time bound. The mock does not reproduce + // the plugin's whole-file rewrite, so any threshold here would pass + // regardless of how slow the purge is in production and would be a + // check that cannot fail. + expect( + beats, + greaterThan(10), + reason: 'the heartbeat ran, so the harness itself worked', + ); + expect( + await storage.loadPathHistory('cafebabe'), + isNotNull, + reason: + 'THE point of the rehearsal: the purge removes the unscoped ' + 'legacy keys and leaves this radio\'s scoped history intact', + ); + + await db.close(); + BlobStore.clearTestOverride(); + }, + timeout: const Timeout(Duration(minutes: 10)), + ); +} + +ContactPathHistory _history(String contact) => ContactPathHistory( + contactPubKeyHex: contact, + recentPaths: [ + PathRecord( + hopCount: 2, + tripTimeMs: 500, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + wasFloodDiscovery: false, + pathBytes: const [1, 2, 3], + successCount: 1, + failureCount: 0, + ), + ], +); diff --git a/test/benchmarks/real_db_row_migration_bench.dart b/test/benchmarks/real_db_row_migration_bench.dart new file mode 100644 index 00000000..63a172d3 --- /dev/null +++ b/test/benchmarks/real_db_row_migration_bench.dart @@ -0,0 +1,339 @@ +// Epic B verification (#920 / #917): migrate a REAL database into rows and +// prove nothing was lost, then show that a save no longer cares how much +// history is already stored. +// +// Named `_bench`, not `_test`, so a bare `flutter test` does not collect it: +// it needs a copy of a real database and its numbers are machine-specific. +// The non-flaky gates live in test/storage/message_rows_*_test.dart. +// +// Run it: +// flutter test test/benchmarks/real_db_row_migration_bench.dart \ +// --dart-define=BENCH_DB="$APPDATA/Offband MeshCore/offband_store.sqlite" +// +// The file named by BENCH_DB is COPIED first and never written to. Without it +// the whole file reports why it ran nothing and passes, because a benchmark +// that silently invents data is worse than one that says it has none. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const String _benchDb = String.fromEnvironment('BENCH_DB'); + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDown(BlobStore.clearTestOverride); + + test( + 'count parity: every message in a real database survives', + () async { + if (_benchDb.isEmpty || !File(_benchDb).existsSync()) { + // ignore: avoid_print + print( + 'SKIPPED: no BENCH_DB. Pass --dart-define=BENCH_DB=. Nothing was measured.', + ); + return; + } + + final work = File( + '${Directory.systemTemp.path}/offband_row_migration_bench.sqlite', + ); + if (work.existsSync()) work.deleteSync(); + File(_benchDb).copySync(work.path); + // ignore: avoid_print + print( + 'working on a copy: ${work.path} ' + '(${(work.lengthSync() / 1048576).toStringAsFixed(2)} MiB)', + ); + + final db = OffbandDatabase(NativeDatabase(work)); + final blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + + // Snapshot every message-history blob BEFORE anything touches it: the key, + // its exact bytes and how many records it holds, counted here rather than + // by the converter under test. + final before = {}; + final rows = await db + .customSelect('SELECT key, value FROM stored_blobs') + .get(); + for (final r in rows) { + final key = r.data['key'] as String; + if (!key.startsWith('channel_messages_') && + !key.startsWith('messages_')) { + continue; + } + final value = r.data['value'] as String; + if (value.isEmpty) continue; + int records; + try { + records = (jsonDecode(value) as List).length; + } catch (e) { + // ignore: avoid_print + print(' ! $key does not decode at all, skipping: $e'); + continue; + } + before[key] = ( + length: value.length, + records: records, + hash: value.hashCode, + ); + } + + expect( + before, + isNotEmpty, + reason: + 'the named database holds no message history, so this ' + 'measured nothing', + ); + + var totalRecords = 0; + var totalRows = 0; + final refused = []; + final sw = Stopwatch()..start(); + + for (final entry in before.entries) { + final key = entry.key; + final converter = key.startsWith('channel_messages_') + ? channelHistoryToRows + : dmHistoryToRows; + final ok = await blobs.ensureMessageRowsMigrated(key, converter); + final stored = await blobs.messageRowCount(key); + totalRecords += entry.value.records; + totalRows += stored; + if (!ok) refused.add(key); + } + final elapsed = sw.elapsedMilliseconds; + + // ignore: avoid_print + print(''); + // ignore: avoid_print + print( + 'keys migrated : ${before.length - refused.length}' + ' of ${before.length}', + ); + // ignore: avoid_print + print('records in blobs : $totalRecords'); + // ignore: avoid_print + print('rows stored : $totalRows'); + // ignore: avoid_print + print('elapsed : ${elapsed}ms'); + if (refused.isNotEmpty) { + // ignore: avoid_print + print('REFUSED (still on their blob):'); + for (final k in refused) { + // ignore: avoid_print + print(' $k (${before[k]!.records} records)'); + } + } + + // The blobs must come out untouched. This is the promise that makes the + // migration recoverable. + final after = await db + .customSelect('SELECT key, value FROM stored_blobs') + .get(); + for (final r in after) { + final key = r.data['key'] as String; + final snapshot = before[key]; + if (snapshot == null) continue; + final value = r.data['value'] as String; + expect( + value.length, + snapshot.length, + reason: '$key changed length, so the migration wrote to a blob', + ); + expect( + value.hashCode, + snapshot.hash, + reason: '$key changed content, so the migration wrote to a blob', + ); + } + + // A record can legitimately vanish only as a duplicate identity, never + // otherwise, so rows may be fewer but must never exceed, and a shortfall + // has to be explainable. + expect( + totalRows, + lessThanOrEqualTo(totalRecords), + reason: 'more rows than records means the migration invented messages', + ); + if (totalRows != totalRecords) { + // ignore: avoid_print + print( + 'NOTE: ${totalRecords - totalRows} records collapsed into existing ' + 'identities (duplicates in the source blobs) or belong to refused ' + 'keys. Per-key detail is in the log above.', + ); + } + expect( + refused, + isEmpty, + reason: + 'every key in a real database should migrate; a refusal is a ' + 'finding, not a pass', + ); + + await db.close(); + }, + timeout: const Timeout(Duration(minutes: 10)), + ); + + test( + 'the one-time migration does not freeze the UI isolate', + () async { + // The question an existing install actually asks: when this ships and + // the biggest channel migrates on first open, does the app lock up? + // Measured the way #919 measured it, with a 1 ms heartbeat on the main + // isolate; the worst gap between beats is the freeze. + if (_benchDb.isEmpty || !File(_benchDb).existsSync()) { + // ignore: avoid_print + print('SKIPPED: no BENCH_DB. Nothing was measured.'); + return; + } + + final work = File( + '${Directory.systemTemp.path}/offband_row_migration_ui.sqlite', + ); + if (work.existsSync()) work.deleteSync(); + File(_benchDb).copySync(work.path); + + // `createInBackground`, not a plain NativeDatabase, because that is what + // ships: `drift_flutter`'s `driftDatabase()` hosts the connection in a + // background isolate. Measuring on a same-isolate connection charges SQL + // execution to the UI isolate and overstates the freeze, which is what + // the first version of this test did: it read 166 ms where the + // production-shaped connection reads 64 ms. + final db = OffbandDatabase(NativeDatabase.createInBackground(work)); + final blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + + final biggest = await db + .customSelect( + 'SELECT key, length(value) AS n FROM stored_blobs ' + "WHERE key LIKE 'channel_messages_%' " + 'ORDER BY length(value) DESC LIMIT 1', + ) + .getSingle(); + final key = biggest.data['key'] as String; + final size = biggest.data['n'] as int; + + var last = DateTime.now(); + var worst = 0; + var beats = 0; + final beat = Timer.periodic(const Duration(milliseconds: 1), (_) { + final now = DateTime.now(); + final gap = now.difference(last).inMilliseconds; + if (gap > worst) worst = gap; + last = now; + beats++; + }); + final sw = Stopwatch()..start(); + last = DateTime.now(); + final ok = await blobs.ensureMessageRowsMigrated( + key, + channelHistoryToRows, + ); + final wall = sw.elapsedMilliseconds; + // The overdue beat has to land before the timer goes away, or a real + // block reads as 0 ms. Learned the hard way in #919. + for (var i = 0; i < 3; i++) { + await Future.delayed(Duration.zero); + } + beat.cancel(); + + // ignore: avoid_print + print(''); + // ignore: avoid_print + print( + 'migrating the largest channel: ' + '${(size / 1048576).toStringAsFixed(2)} MiB, ' + '${await blobs.messageRowCount(key)} messages', + ); + // ignore: avoid_print + print(' UI blocked ${worst}ms wall ${wall}ms (heartbeats $beats)'); + + expect(ok, isTrue); + expect( + beats, + greaterThan(10), + reason: 'too few heartbeats to trust the gap figure', + ); + + await db.close(); + }, + timeout: const Timeout(Duration(minutes: 10)), + ); + + test( + 'per-message save cost is flat across history length', + () async { + final db = OffbandDatabase(NativeDatabase.memory()); + final blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + + String payloadFor(int i) => jsonEncode({ + 'senderName': 's', + 'text': 'message number $i with a realistic amount of text in it', + 'timestamp': 1700000000000 + i, + 'isOutgoing': false, + 'channelIndex': 0, + 'messageId': 'id$i', + 'status': 0, + }); + + // ignore: avoid_print + print(''); + // ignore: avoid_print + print('history size one more save'); + for (final size in [500, 5000, 50000]) { + final key = 'k$size'; + await blobs.upsertMessageRows(key, [ + for (var i = 0; i < size; i++) + MessageRowInput( + mergeKey: 'id:id$i', + timestampMs: 1700000000000 + i, + payload: payloadFor(i), + ), + ]); + + final samples = []; + for (var n = 0; n < 20; n++) { + final sw = Stopwatch()..start(); + await blobs.upsertMessageRows(key, [ + MessageRowInput( + mergeKey: 'id:new$n', + timestampMs: 1800000000000 + n, + payload: payloadFor(900000 + n), + ), + ]); + samples.add(sw.elapsedMicroseconds); + } + samples.sort(); + final median = samples[samples.length ~/ 2]; + // ignore: avoid_print + print( + '${size.toString().padLeft(11)} ' + '${(median / 1000).toStringAsFixed(3)} ms', + ); + } + + await db.close(); + }, + timeout: const Timeout(Duration(minutes: 10)), + ); +} diff --git a/test/benchmarks/stale_history_sweep_bench.dart b/test/benchmarks/stale_history_sweep_bench.dart new file mode 100644 index 00000000..9cf54919 --- /dev/null +++ b/test/benchmarks/stale_history_sweep_bench.dart @@ -0,0 +1,180 @@ +// Epic A verification (#965 / #962): run the production sweep over a copy of a +// REAL database and prove what it did, and what it left alone. +// +// Named `_bench`, not `_test`, so a bare `flutter test` does not collect it: +// it needs a copy of a real database and its numbers are machine-specific. The +// non-flaky gates live in test/storage/stale_history_sweep_test.dart. +// +// Run it: +// flutter test test/benchmarks/stale_history_sweep_bench.dart \ +// --dart-define=BENCH_DB="$APPDATA/Offband MeshCore/offband_store.sqlite" +// +// The file named by BENCH_DB is COPIED first and never written to. Without it +// the file reports why it ran nothing and passes, because a check that +// silently invents data is worse than one that says it has none. +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/stale_history_sweep.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const String _benchDb = String.fromEnvironment('BENCH_DB'); + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDown(BlobStore.clearTestOverride); + + test( + 'the sweep reclaims real blobs and touches nothing else', + () async { + if (_benchDb.isEmpty || !File(_benchDb).existsSync()) { + // ignore: avoid_print + print( + 'SKIPPED: no BENCH_DB. Pass --dart-define=BENCH_DB=. Nothing was measured.', + ); + return; + } + + final work = File( + '${Directory.systemTemp.path}/offband_stale_sweep_bench.sqlite', + ); + if (work.existsSync()) work.deleteSync(); + File(_benchDb).copySync(work.path); + // ignore: avoid_print + print( + 'working on a copy: ${work.path} ' + '(${(work.lengthSync() / 1048576).toStringAsFixed(2)} MiB)', + ); + + final db = OffbandDatabase(NativeDatabase(work)); + final blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + + // Fingerprint EVERY blob before, so what survives can be compared byte for + // byte rather than counted. + final before = {}; + for (final key in await blobs.keysWithPrefix('')) { + final v = await blobs.read(key); + if (v != null) { + before[key] = sha256.convert(utf8.encode(v)).toString(); + } + } + final rowsBefore = await db + .customSelect('SELECT COUNT(*) AS c FROM message_records') + .getSingle() + .then((r) => r.data['c'] as int); + final sizeBefore = await blobs.databaseSizeBytes(); + + // Age every migrated key past the window. Without this the sweep is + // correctly a no-op on a database that migrated minutes ago, and the run + // would prove nothing. + final marked = await blobs.messageStoreKeys(); + final aged = DateTime.now().subtract( + staleHistoryWindow + const Duration(days: 1), + ); + var eligible = 0; + for (final key in marked) { + if (!StaleHistorySweep.isHistoryKey(key)) continue; + if (!await blobs.isOnMessageRows(key)) continue; + await blobs.setMessageRowsMigratedAtForTest(key, aged); + eligible++; + } + // ignore: avoid_print + print( + 'blob keys: ${before.length}, migrated history keys aged: $eligible', + ); + + expect( + eligible, + greaterThan(0), + reason: + 'this database has no migrated history key, so the sweep cannot ' + 'show anything. Not a pass.', + ); + + final outcome = await StaleHistorySweep(blobs).run(); + final sizeAfter = await blobs.databaseSizeBytes(); + + // ignore: avoid_print + print( + 'cleared ${outcome.cleared.length}, refused ${outcome.refused.length}, ' + '${sizeBefore - sizeAfter} bytes returned ' + '(${((sizeBefore - sizeAfter) / 1048576).toStringAsFixed(2)} MiB)', + ); + for (final k in outcome.refused) { + // ignore: avoid_print + print(' REFUSED (blob kept): $k'); + } + + // What it cleared must be gone, and nothing else may have changed. + for (final k in outcome.cleared) { + expect( + await blobs.read(k), + isNull, + reason: '$k should have been cleared', + ); + } + final changed = []; + final missing = []; + for (final entry in before.entries) { + if (outcome.cleared.contains(entry.key)) continue; + final v = await blobs.read(entry.key); + if (v == null) { + missing.add(entry.key); + } else if (sha256.convert(utf8.encode(v)).toString() != entry.value) { + changed.add(entry.key); + } + } + // ignore: avoid_print + print( + 'kept keys missing: ${missing.length}, byte-changed: ${changed.length}', + ); + + expect( + missing, + isEmpty, + reason: 'the sweep removed a blob it did not report', + ); + expect(changed, isEmpty, reason: 'VACUUM must not alter a kept blob'); + + final rowsAfter = await db + .customSelect('SELECT COUNT(*) AS c FROM message_records') + .getSingle() + .then((r) => r.data['c'] as int); + expect( + rowsAfter, + rowsBefore, + reason: 'the history itself must survive losing its stale snapshot', + ); + + final integrity = await db + .customSelect('PRAGMA integrity_check') + .getSingle() + .then((r) => r.data.values.first as String); + // ignore: avoid_print + print('integrity_check: $integrity, rows $rowsBefore -> $rowsAfter'); + expect(integrity, 'ok'); + + expect( + sizeAfter, + lessThan(sizeBefore), + reason: 'a sweep that cleared blobs must return space', + ); + + await db.close(); + }, + timeout: const Timeout(Duration(minutes: 5)), + ); +} diff --git a/test/benchmarks/stuck_key_recovery_bench.dart b/test/benchmarks/stuck_key_recovery_bench.dart new file mode 100644 index 00000000..f9192d48 --- /dev/null +++ b/test/benchmarks/stuck_key_recovery_bench.dart @@ -0,0 +1,192 @@ +// #952 verification: the keys the old gate trapped recover against a REAL +// database, with no healing migration. +// +// Named `_bench`, not `_test`, so a bare `flutter test` does not collect it: +// it needs a copy of a real database. The non-flaky gates live in +// test/storage/migration_readback_gate_test.dart. +// +// Run it: +// flutter test test/benchmarks/stuck_key_recovery_bench.dart \ +// --dart-define=BENCH_DB="$APPDATA/Offband MeshCore/offband_store.sqlite" +// +// The file named by BENCH_DB is COPIED first and never written to. Without it +// the file reports why it ran nothing and passes, because a check that +// silently invents data is worse than one that says it has none. +import 'dart:convert'; +import 'dart:io'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const String _benchDb = String.fromEnvironment('BENCH_DB'); + +/// Non-empty `messageId`s in a history blob, read straight from the JSON. +/// +/// Deliberately not via the converter: this is used to check the converter's +/// output, so sharing its code would make the check circular. +List _messageIdsIn(String? blob) { + if (blob == null || blob.isEmpty) return const []; + return (jsonDecode(blob) as List) + .map((e) => (e as Map)['messageId'] as String?) + .whereType() + .where((id) => id.isNotEmpty) + .toList(); +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDown(BlobStore.clearTestOverride); + + test( + 'every key with rows but no marker migrates on next access', + () async { + if (_benchDb.isEmpty || !File(_benchDb).existsSync()) { + // ignore: avoid_print + print( + 'SKIPPED: no BENCH_DB. Pass --dart-define=BENCH_DB=. Nothing was measured.', + ); + return; + } + + final work = File( + '${Directory.systemTemp.path}/offband_stuck_key_recovery.sqlite', + ); + if (work.existsSync()) work.deleteSync(); + File(_benchDb).copySync(work.path); + // ignore: avoid_print + print( + 'working on a copy: ${work.path} ' + '(${(work.lengthSync() / 1048576).toStringAsFixed(2)} MiB)', + ); + + final db = OffbandDatabase(NativeDatabase(work)); + final blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + + // The stuck shape, identified without using the code under test: a key + // that has rows and is NOT in the migrated marker. + final withRows = await blobs.messageStoreKeys(); + final marked = {}; + final rawMarker = await blobs.read(BlobStore.migratedMarkerKey); + if (rawMarker != null && rawMarker.isNotEmpty) { + marked.addAll((jsonDecode(rawMarker) as List).cast()); + } + final stuck = withRows.difference(marked).toList()..sort(); + + // ignore: avoid_print + print( + 'keys with rows: ${withRows.length}, marked migrated: ${marked.length}, ' + 'rows but unmarked: ${stuck.length}', + ); + + if (stuck.isEmpty) { + // ignore: avoid_print + print( + 'This database has no key in the stuck shape, so it cannot show the ' + 'recovery. Not a pass for #952.', + ); + markTestSkipped('no stuck keys in the named database'); + await db.close(); + return; + } + + final recovered = []; + final refused = []; + + for (final key in stuck) { + final blob = await blobs.read(key); + final records = blob == null || blob.isEmpty + ? 0 + : (jsonDecode(blob) as List).length; + final rowsBefore = await blobs.messageRowCount(key); + + final ok = await blobs.ensureMessageRowsMigrated( + key, + key.startsWith('channel_messages_') + ? channelHistoryToRows + : dmHistoryToRows, + ); + + final rowsAfter = await blobs.messageRowCount(key); + // ignore: avoid_print + print( + ' ${ok ? 'MIGRATED' : 'REFUSED '} blob=$records rows $rowsBefore' + ' -> $rowsAfter $key', + ); + (ok ? recovered : refused).add(key); + + if (ok) { + expect( + rowsAfter, + greaterThanOrEqualTo(records), + reason: '$key lost records while migrating', + ); + expect(await blobs.isOnMessageRows(key), isTrue); + + // Counts alone would pass against a converter that produced the + // right NUMBER of rows with the wrong contents (Gemini review). + // Identity and payloads are checked too, derived from the raw blob + // rather than from the converter under test, so this is not + // circular. + // + // Only records carrying a messageId are identity-checked: the `x:` + // fallback merge key would mean reimplementing the converter here, + // which would make the check circular again. The count assertion + // above still covers those. + final ids = _messageIdsIn(blob); + final stored = await blobs.messageMergeKeys(key); + final absent = ids.where((id) => !stored.contains('id:$id')).toList(); + expect( + absent, + isEmpty, + reason: + '$key: ${absent.length} of ${ids.length} identified messages ' + 'in the blob have no row carrying their identity', + ); + + final payloads = await blobs.messagePayloads(key); + expect( + payloads.where((p) => p.trim().length <= 2), + isEmpty, + reason: '$key stored empty payloads', + ); + } + } + + // ignore: avoid_print + print('recovered: ${recovered.length}, still refused: ${refused.length}'); + + expect( + refused, + isEmpty, + reason: + 'these keys are still stuck, so #952 is not fixed for this ' + 'database: $refused', + ); + + // The blobs are retained, as #920 promises, so nothing here is destructive. + for (final key in recovered) { + expect( + await blobs.read(key), + isNotNull, + reason: '$key lost its retained blob', + ); + } + + await db.close(); + }, + timeout: const Timeout(Duration(minutes: 5)), + ); +} diff --git a/test/channel_path_len_test.dart b/test/channel_path_len_test.dart new file mode 100644 index 00000000..145ca1a8 --- /dev/null +++ b/test/channel_path_len_test.dart @@ -0,0 +1,124 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/channel_message.dart'; + +// #985: a 13-hop message with 3-byte path hashes (packed path-len 0x8D) +// rendered as "39 hops". Three defects: the V3 path_len field was read +// signed (0x8D became -115, swallowed as the flood sentinel), the log-RX +// ingress stored the width-stripped hop count, and the repeat merge +// substituted the path BYTE length into the packed field. + +Uint8List _v3Frame({required int pathLen, String text = 'Dee3: hi'}) { + final textBytes = text.codeUnits; + return Uint8List.fromList([ + respCodeChannelMsgRecvV3, + 0, // SNR + 0, // reserved1 (bit0 = outgoing) + 0, // reserved2 + 2, // channel_idx + pathLen, + txtTypePlain, + 0x40, 0xE2, 0x01, 0x00, // timestamp LE + ...textBytes, + ]); +} + +Uint8List _legacyFrame({required int pathLen, String text = 'Dee3: hi'}) { + final textBytes = text.codeUnits; + return Uint8List.fromList([ + respCodeChannelMsgRecv, + 2, // channel_idx + pathLen, + txtTypePlain, + 0x40, 0xE2, 0x01, 0x00, // timestamp LE + ...textBytes, + ]); +} + +void main() { + group('ChannelMessage.fromFrame path-len decode (#985)', () { + test( + '3-byte-width packed byte stays unsigned: 0x8D = 13 hops, width 3', + () { + final m = ChannelMessage.fromFrame(_v3Frame(pathLen: 0x8D))!; + expect(m.pathLength, 0x8D); + expect(m.hopCount, 13); + expect(m.pathHashSize, 3); + }, + ); + + test('2-byte-width packed byte: 0x53 = 19 hops, width 2', () { + final m = ChannelMessage.fromFrame(_v3Frame(pathLen: 0x53))!; + expect(m.hopCount, 19); + expect(m.pathHashSize, 2); + }); + + test('0xFF stays the direct-route sentinel (-1)', () { + final m = ChannelMessage.fromFrame(_v3Frame(pathLen: 0xFF))!; + expect(m.pathLength, -1); + expect(m.hopCount, -1); + }); + + test('legacy (non-V3) frame decodes the same way', () { + final m = ChannelMessage.fromFrame(_legacyFrame(pathLen: 0x8D))!; + expect(m.pathLength, 0x8D); + expect(m.hopCount, 13); + expect(m.pathHashSize, 3); + }); + }); + + group('effectivePathHashWidth (#985)', () { + ChannelMessage msg(int? pathLength) => ChannelMessage( + senderName: 'Dee3', + text: 'hi', + timestamp: DateTime.fromMillisecondsSinceEpoch(0), + isOutgoing: false, + status: ChannelMessageStatus.sent, + pathLength: pathLength, + ); + + test('uses the packet\'s own width when a path-len byte is stored', () { + expect(msg(0x8D).effectivePathHashWidth(2), 3); + expect(msg(0x53).effectivePathHashWidth(1), 2); + expect(msg(13).effectivePathHashWidth(2), 1); + }); + + test('falls back to the device width for legacy/sentinel records', () { + expect(msg(null).effectivePathHashWidth(2), 2); + expect(msg(-1).effectivePathHashWidth(3), 3); + expect(msg(null).effectivePathHashWidth(0), 1); + }); + }); + + group('mergePathLenRaw (#985)', () { + test('null and sentinel yield to the real packed byte', () { + expect(mergePathLenRaw(null, 0x8D), 0x8D); + expect(mergePathLenRaw(0x8D, null), 0x8D); + expect(mergePathLenRaw(-1, 0x8D), 0x8D); + expect(mergePathLenRaw(0x8D, -1), 0x8D); + expect(mergePathLenRaw(null, null), isNull); + }); + + test('higher decoded hop count wins, compared in hops not raw bytes', () { + // 0x8E = 14 hops at width 3; 0x8D = 13 hops at width 3. + expect(mergePathLenRaw(0x8D, 0x8E), 0x8E); + // 19 hops at width 2 (0x53) beats 13 hops at width 2 (0x4D). + expect(mergePathLenRaw(0x4D, 0x53), 0x53); + // A width-1 count is NOT outranked by a packed byte's raw magnitude: + // 20 hops at width 1 beats 13 hops at width 3 (raw 0x8D = 141). + expect(mergePathLenRaw(0x8D, 20), 20); + }); + + test('regression: the Dee3 scenario decodes to 13 hops, never 39', () { + // Two repeats of the same packet, both carrying packed 0x8D. The old + // merge substituted the 39-byte path length, which decoded as + // "39 hops at width 1". + final merged = mergePathLenRaw(0x8D, 0x8D)!; + expect(pathHopCount(merged), 13); + expect(pathHashSizeBytes(merged), 3); + expect(pathByteLength(merged), 39); + }); + }); +} diff --git a/test/cli_command_codec_test.dart b/test/cli_command_codec_test.dart new file mode 100644 index 00000000..a94de415 --- /dev/null +++ b/test/cli_command_codec_test.dart @@ -0,0 +1,101 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/cli_command_codec.dart'; + +void main() { + group('buildRunCliCommandFrame', () { + test('plain command', () { + final f = buildRunCliCommandFrame('get radio'); + expect(f[0], cmdRunCliCommand); + expect(ascii.decode(f.sublist(1)), 'get radio'); + }); + + test('with correlation prefix', () { + final f = buildRunCliCommandFrame('get radio', prefix: '0A|'); + expect(ascii.decode(f.sublist(1)), '0A|get radio'); + }); + + test('rejects an empty command', () { + expect(() => buildRunCliCommandFrame(''), throwsArgumentError); + expect(() => buildRunCliCommandFrame(' '), throwsArgumentError); + }); + + test('rejects a command shorter than the firmware minimum', () { + // Firmware requires frame len >= 3, i.e. at least 2 command bytes. + expect(() => buildRunCliCommandFrame('b'), throwsArgumentError); + }); + + test('rejects a malformed prefix', () { + expect( + () => buildRunCliCommandFrame('ver', prefix: '0A'), + throwsArgumentError, + ); + expect( + () => buildRunCliCommandFrame('ver', prefix: 'ABCD|'), + throwsArgumentError, + ); + }); + }); + + group('parseCliReply', () { + Uint8List reply(String text) => + Uint8List.fromList([respCodeCliReply, ...ascii.encode(text)]); + + test('reply with reflected prefix', () { + final r = parseCliReply(reply('0A|> 910.525,62.5,7,5')); + expect(r, isNotNull); + expect(r!.prefix, '0A|'); + expect(r.text, '> 910.525,62.5,7,5'); + }); + + test('reply without prefix', () { + final r = parseCliReply(reply('Unknown command')); + expect(r!.prefix, isNull); + expect(r.text, 'Unknown command'); + }); + + test('empty reply text', () { + final r = parseCliReply(Uint8List.fromList([respCodeCliReply])); + expect(r!.text, ''); + expect(r.prefix, isNull); + }); + + test('wrong frame code returns null', () { + final r = parseCliReply(Uint8List.fromList([13, 65, 66])); + expect(r, isNull); + }); + + test('a short reply whose third byte is not | is all text', () { + final r = parseCliReply(reply('ok')); + expect(r!.prefix, isNull); + expect(r.text, 'ok'); + }); + + test('device truncation bound is judged on the RAW payload, prefix' + ' included', () { + // A real truncated reply: total payload exactly 165 bytes, of which + // 3 are the reflected prefix (post-strip text is only 162). + final r = parseCliReply(reply('0A|${'x' * (maxCliReplyPayload - 3)}')); + expect(r!.payloadLength, maxCliReplyPayload); + expect(r.atReplyBound, isTrue); + final short = parseCliReply(reply('0A|ok')); + expect(short!.atReplyBound, isFalse); + }); + + test('non-ASCII commands are rejected at build time', () { + expect( + () => buildRunCliCommandFrame('set name ฮฉmega'), + throwsArgumentError, + ); + }); + + test('non-ascii bytes decode leniently rather than throwing', () { + final r = parseCliReply( + Uint8List.fromList([respCodeCliReply, 0x4F, 0x4B, 0xFF]), + ); + expect(r!.text.startsWith('OK'), isTrue); + }); + }); +} diff --git a/test/connector/advert_discovery_only_test.dart b/test/connector/advert_discovery_only_test.dart new file mode 100644 index 00000000..d1843dda --- /dev/null +++ b/test/connector/advert_discovery_only_test.dart @@ -0,0 +1,185 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #838 Option A (sync is truth): a live advert the client overhears must NOT be +// promoted into the persisted contact list (that is what drifted a long session +// above radio truth). It feeds discovery only, and nudges a reconcile so a +// contact the radio actually added still surfaces. Only the sync stream, which +// is radio truth, populates the contact list. +Uint8List _u32(int v) => + Uint8List(4)..buffer.asByteData().setUint32(0, v, Endian.little); + +/// A contact-stream / NEW_ADVERT frame in the respCodeContact layout. +Uint8List _contactFrame( + int keyByte, + String name, { + int code = respCodeContact, +}) { + final b = BytesBuilder() + ..addByte(code) + ..add(List.filled(32, keyByte)) + ..addByte(advTypeChat) + ..addByte(0) // flags + ..addByte(0xFF) // flood path + ..add(List.filled(64, 0)) + ..add(Uint8List(32)..setRange(0, name.length, name.codeUnits)) + ..add(_u32(1790000000)) + ..add(_u32(0)) + ..add(_u32(0)) + ..add(_u32(1790000000)); + return b.toBytes(); +} + +/// A raw over-the-air advert wrapped in PUSH_CODE_LOG_RX_DATA (0x88), the +/// firehose the radio sends for everything it hears. routeType 0x01 keeps it +/// off the flood/direct transport-byte path. +Uint8List _rxAdvertFrame(int keyByte, String name) { + final header = (payloadTypeADVERT << 2) | 0x01; + final payload = BytesBuilder() + ..add(List.filled(32, keyByte)) + ..add(_u32(1790000000)) // timestamp + ..add(List.filled(64, 0)) // signature + ..addByte(advTypeChat | 0x80) // type + hasName + ..add(name.codeUnits) + ..addByte(0); // C-string terminator + return (BytesBuilder() + ..addByte(pushCodeLogRxData) + ..addByte(0) // snr + ..addByte(0) // rssi + ..addByte(header) + ..addByte(0) // pathLenRaw -> no path + ..add(payload.toBytes())) + .toBytes(); +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + // The radio's auto-add policy says chat nodes are eligible; pre-fix this is + // exactly what made the client promote every overheard chat advert. + connector.handleFrameForTest( + Uint8List.fromList([respCodeAutoAddConfig, autoAddChatFlag]), + ); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Set contactNames() => + connector.contactsForTest.map((c) => c.name).toSet(); + Set discoveredNames() => + connector.discoveredContactsForTest.map((c) => c.name).toSet(); + int getContactsRequests() => + sent.where((f) => f.isNotEmpty && f[0] == cmdGetContacts).length; + + test( + 'a NEW_ADVERT push for an unknown node stays out of the contact list', + () async { + connector.handleFrameForTest( + _contactFrame(0x44, 'Delta', code: pushCodeNewAdvert), + ); + await Future.delayed(Duration.zero); + + expect( + contactNames(), + isNot(contains('Delta')), + reason: 'a live advert must not be promoted to a persisted contact', + ); + expect( + discoveredNames(), + contains('Delta'), + reason: 'it belongs in discovery instead', + ); + }, + ); + + test( + 'a raw over-the-air advert (0x88) stays out of the contact list', + () async { + connector.handleFrameForTest(_rxAdvertFrame(0x55, 'Echo')); + await Future.delayed(Duration.zero); + + expect(contactNames(), isNot(contains('Echo'))); + expect(discoveredNames(), contains('Echo')); + }, + ); + + test( + 'an unknown auto-add-eligible advert nudges a contact reconcile', + () async { + final before = getContactsRequests(); + connector.handleFrameForTest( + _contactFrame(0x66, 'Foxtrot', code: pushCodeNewAdvert), + ); + // The reconcile is debounced; give it room to fire. + await Future.delayed(const Duration(milliseconds: 1200)); + + expect( + getContactsRequests(), + greaterThan(before), + reason: 'a new advert should pull the radio truth, not add locally', + ); + }, + ); + + test( + 'the contact sync stream still populates the list (sync is truth)', + () async { + await connector.getContacts(); + connector.handleFrameForTest( + Uint8List.fromList([respCodeContactsStart, ..._u32(1)]), + ); + connector.handleFrameForTest(_contactFrame(0x77, 'Golf')); + connector.handleFrameForTest( + Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]), + ); + await Future.delayed(Duration.zero); + + expect(contactNames(), contains('Golf')); + }, + ); + + test('a NEW_ADVERT for an EXISTING contact still refreshes it', () async { + await connector.getContacts(); + connector.handleFrameForTest( + Uint8List.fromList([respCodeContactsStart, ..._u32(1)]), + ); + connector.handleFrameForTest(_contactFrame(0x88, 'Hotel')); + connector.handleFrameForTest( + Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]), + ); + await Future.delayed(Duration.zero); + expect(contactNames(), contains('Hotel')); + + // A later advert for the same node must keep it (it is radio truth). + connector.handleFrameForTest( + _contactFrame(0x88, 'Hotel', code: pushCodeNewAdvert), + ); + await Future.delayed(Duration.zero); + expect(contactNames(), contains('Hotel')); + }); +} diff --git a/test/connector/auto_reconnect_test.dart b/test/connector/auto_reconnect_test.dart new file mode 100644 index 00000000..f7fd32f2 --- /dev/null +++ b/test/connector/auto_reconnect_test.dart @@ -0,0 +1,148 @@ +// Bounded, interruptible auto-reconnect (#997, design on #995). +// +// 2026-10-25: after a T1000-E dropped, the Windows client retried it about +// every 14 s for 7.7 hours, and nothing else could connect meanwhile. Two +// causes: every automatic attempt reset the attempt counter, and every connect +// path refused to start while an automatic attempt held the state at +// `connecting`, the BLE and USB-screen paths silently. + +import 'package:flutter_blue_plus/flutter_blue_plus.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _radio = 'E1:2C:3A:4B:5C:6D'; + +void main() { + late MeshCoreConnector connector; + late AppDebugLogService log; + + bool logged(String fragment) => + log.entries.any((e) => e.message.contains(fragment)); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + log = AppDebugLogService()..setEnabled(true); + connector = MeshCoreConnector()..setAppDebugLogServiceForTest(log); + connector.primeAutoReconnectForTest(_radio); + }); + + tearDown(() => connector.stopAutoReconnect()); + + // The radio drops; the retry is scheduled; the attempt starts and fails. + Future failOneAttempt() async { + connector.beginAutoReconnectAttemptForTest(); + await connector.disconnect(manual: false); + } + + group('the retry is bounded and backs off (#997 items 1, 2)', () { + test('an automatic attempt does not reset the attempt count', () async { + await connector.disconnect(manual: false); + expect(connector.autoReconnectAttempt, 1); + + await failOneAttempt(); + + expect( + connector.autoReconnectAttempt, + 2, + reason: + 'the bug: each automatic attempt reset this to 0, so the ' + 'delay stayed at 1 s forever', + ); + }); + + test('the retry gives up after five attempts', () async { + await connector.disconnect(manual: false); + for (var i = 0; i < 5; i++) { + await failOneAttempt(); + } + + expect(connector.autoReconnectGaveUp, isTrue); + expect(connector.isAutoReconnecting, isFalse); + expect(connector.isAutoReconnectScheduled, isFalse); + expect(logged('Auto-reconnect stopped'), isTrue); + }); + }); + + group('the user can always take over (#997 items 3, 4, 5)', () { + test('Stop ends an in-flight automatic attempt', () async { + connector.beginAutoReconnectAttemptForTest(); + expect(connector.isAutoReconnecting, isTrue); + + await connector.stopAutoReconnect(); + + expect(connector.state, MeshCoreConnectionState.disconnected); + expect(connector.isAutoReconnecting, isFalse); + expect(connector.isAutoReconnectScheduled, isFalse); + }); + + test('Stop also cancels a scheduled retry', () async { + await connector.disconnect(manual: false); + expect(connector.isAutoReconnectScheduled, isTrue); + + await connector.stopAutoReconnect(); + + expect(connector.isAutoReconnectScheduled, isFalse); + expect(connector.isAutoReconnecting, isFalse); + }); + + test( + 'a TCP connect started during an automatic attempt is not refused', + () async { + connector.beginAutoReconnectAttemptForTest(); + + // Nothing listens on port 9 here; the connect fails, which is fine. The + // point is that it is attempted rather than refused. + try { + await connector.connectTcp(host: '127.0.0.1', port: 9); + } catch (_) {} + + expect(logged('connectTcp ignored'), isFalse); + expect(logged('abandoning automatic reconnect'), isTrue); + }, + ); + + test('a BLE connect refused while connected says so in the log', () async { + connector.setConnectedForTest(); + + await connector.connect(BluetoothDevice.fromId('00:11:22:33:44:55')); + + expect(logged('connect ignored: already'), isTrue); + }); + + test( + 'a connect started during a disconnect waits for it to finish', + () async { + // Owner test 2026-10-26: Stop, then connect to another radio 6 s later. + // The Stop disconnect was still releasing the T1000-E, the new connect + // started on top of it, and the disconnect's tail then wiped the new + // link's device and name (status stuck, frame size stuck at 20). + connector.beginAutoReconnectAttemptForTest(); + final stopping = connector.stopAutoReconnect(); + + try { + await connector.connectTcp(host: '127.0.0.1', port: 9); + } catch (_) {} + await stopping; + + final messages = log.entries.map((e) => e.message).toList(); + final disconnectDone = messages.indexWhere( + (m) => m.startsWith('Disconnect complete'), + ); + final tcpStart = messages.indexWhere( + (m) => m.startsWith('connectTcp: endpoint='), + ); + expect(tcpStart, isNot(-1)); + expect( + disconnectDone, + lessThan(tcpStart), + reason: 'the new connect must not start until the old link is down', + ); + }, + ); + }); +} diff --git a/test/connector/block_offload_fresh_radio_test.dart b/test/connector/block_offload_fresh_radio_test.dart new file mode 100644 index 00000000..d422ae93 --- /dev/null +++ b/test/connector/block_offload_fresh_radio_test.dart @@ -0,0 +1,110 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/services/block_service.dart'; +import 'package:meshcore_open/services/message_retry_service.dart'; +import 'package:meshcore_open/services/path_history_service.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #471 Option A: connecting to a radio that reports an EMPTY block list must not +// offload the client's block list onto it (that made fresh/erased radios come +// up pre-blocked). A radio that already holds blocks still unions normally. +void main() { + final clientKey = 'cc' * 32; // 32-byte key, all 0xcc + final extraKey = 'ee' * 32; + + late OffbandDatabase db; + late MeshCoreConnector connector; + late BlockService block; + late List sent; + + // Block-list dump framing: START [0xC2 0x03 0xFF count], KEY [0xC2 0x03 idx key32], END [0xC2 0x03 0xFE]. + Uint8List start(int count) => + Uint8List.fromList([cmdOffbandBlock, offbandBlockList, 0xFF, count]); + Uint8List key(int idx, int keyByte) => Uint8List.fromList([ + cmdOffbandBlock, + offbandBlockList, + idx, + ...List.filled(32, keyByte), + ]); + Uint8List end() => + Uint8List.fromList([cmdOffbandBlock, offbandBlockList, 0xFE]); + + List blockAddFrames() => sent + .where( + (f) => + f.length > 1 && f[0] == cmdOffbandBlock && f[1] == offbandBlockAdd, + ) + .toList(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + block = BlockService(); + connector.initialize( + retryService: MessageRetryService(), + pathHistoryService: PathHistoryService(StorageService()), + blockService: block, + ); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + // Make the radio block-capable so a push WOULD fire but for the guard. + connector.setFirmwareVerCodeForTest(15); + connector.setOffbandCapsForTest(offbandCapBlock); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test( + 'a radio reporting no blocks is NOT offloaded the client list', + () async { + await block.importKeys({clientKey}); // client has a block + sent.clear(); + + connector.handleFrameForTest(start(0)); + connector.handleFrameForTest(end()); + await Future.delayed(Duration.zero); + + expect( + blockAddFrames(), + isEmpty, + reason: 'a blank radio must not inherit the client block list', + ); + }, + ); + + test( + 'a radio that already holds blocks still unions the client extras', + () async { + await block.importKeys({clientKey, extraKey}); + sent.clear(); + + // Radio holds clientKey (0xcc) already, but not extraKey (0xee). + connector.handleFrameForTest(start(1)); + connector.handleFrameForTest(key(0, 0xcc)); + connector.handleFrameForTest(end()); + await Future.delayed(Duration.zero); + + final pushed = blockAddFrames(); + expect(pushed.length, 1, reason: 'only the extra block is offloaded'); + // The pushed key is extraKey (0xee...), not the one the radio already had. + expect(pushed.single.sublist(2), List.filled(32, 0xee)); + }, + ); +} diff --git a/test/connector/build_update_contact_path_frame_test.dart b/test/connector/build_update_contact_path_frame_test.dart index 9b76c2de..9d4273b4 100644 --- a/test/connector/build_update_contact_path_frame_test.dart +++ b/test/connector/build_update_contact_path_frame_test.dart @@ -2,6 +2,7 @@ import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; void main() { // Frame layout per the doc comment on buildUpdateContactPathFrame: @@ -220,4 +221,63 @@ void main() { expect(frame[pathLenOffset], 0xFF); }); }); + + group('remote-CLI permission flag on the write path (#887)', () { + // 1 cmd + 32 pubKey + 1 type = 34. + const int flagsOffset = 34; + + test('the 0x10 bit rides the flags byte when set', () { + final frame = buildUpdateContactPathFrame( + pubKey, + path, + path.length, + flags: contactFlagRemoteCliAllowed, + ); + expect( + frame[flagsOffset] & contactFlagRemoteCliAllowed, + contactFlagRemoteCliAllowed, + ); + }); + + test('remote-CLI coexists with telemetry flags in the one byte', () { + final frame = buildUpdateContactPathFrame( + pubKey, + path, + path.length, + flags: contactFlagRemoteCliAllowed | contactFlagTeleBase, + ); + expect(frame[flagsOffset] & contactFlagRemoteCliAllowed, isNonZero); + expect(frame[flagsOffset] & contactFlagTeleBase, isNonZero); + }); + + test('a frame without the permission carries a clear 0x10 bit', () { + final frame = buildUpdateContactPathFrame( + pubKey, + path, + path.length, + flags: contactFlagTeleBase, + ); + expect(frame[flagsOffset] & contactFlagRemoteCliAllowed, 0); + }); + + test('Contact.remoteCliAllowed reflects the 0x10 bit', () { + Contact withFlags(int flags) => Contact( + publicKey: Uint8List(32), + receivedName: 'X', + type: 1, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.now(), + flags: flags, + ); + expect(withFlags(contactFlagRemoteCliAllowed).remoteCliAllowed, isTrue); + expect(withFlags(contactFlagTeleBase).remoteCliAllowed, isFalse); + expect( + withFlags( + contactFlagRemoteCliAllowed | contactFlagFavorite, + ).remoteCliAllowed, + isTrue, + ); + }); + }); } diff --git a/test/connector/channel_scope_send_test.dart b/test/connector/channel_scope_send_test.dart new file mode 100644 index 00000000..404da8a9 --- /dev/null +++ b/test/connector/channel_scope_send_test.dart @@ -0,0 +1,87 @@ +// Epic #815 T C3: per-send region scoping around a channel send. +// Drives the scoping helper via its test seam, capturing the frame sequence. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// Known vector: first 16 bytes of SHA256("#oki"). +final _okiKey = Uint8List.fromList([ + 0x59, 0x9f, 0xe2, 0x54, 0x60, 0x02, 0x70, 0x9f, // + 0xa4, 0x93, 0xb1, 0x5d, 0xe5, 0x8b, 0xdd, 0x0d, +]); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late MeshCoreConnector connector; + final frame = Uint8List.fromList([cmdSendChannelTxtMsg, 0, 1, 2, 3]); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + connector.setConnectedForTest(); + connector.setFirmwareVerCodeForTest(22); + connector.channelRegionScopeStoreForTest.setPublicKeyHex = + 'aabbccddee0011223344'; + }); + + test('an unscoped channel sends the frame alone', () async { + final sent = []; + connector.sendFrameOverrideForTest = sent.add; + await connector.sendChannelFrameScopedForTest(0, frame); + expect(sent, hasLength(1)); + expect(sent.single, frame); + }); + + test('a scoped channel sets the key, sends, then clears', () async { + await connector.channelRegionScopeStoreForTest.setScope(0, 'oki'); + final sent = []; + connector.sendFrameOverrideForTest = sent.add; + await connector.sendChannelFrameScopedForTest(0, frame); + expect(sent, hasLength(3)); + // set scope: [54, 0, key16] + expect(sent[0][0], cmdSetFloodScopeKey); + expect(sent[0][1], floodScopeSubSetKey); + expect(sent[0].sublist(2), _okiKey); + // the message + expect(sent[1], frame); + // clear scope: [54, 0] + expect(sent[2], [cmdSetFloodScopeKey, floodScopeSubSetKey]); + }); + + test( + 'a scoped channel on unsupported firmware is blocked, nothing sent', + () async { + await connector.channelRegionScopeStoreForTest.setScope(0, 'oki'); + connector.setFirmwareVerCodeForTest(7); + final sent = []; + connector.sendFrameOverrideForTest = sent.add; + await expectLater( + connector.sendChannelFrameScopedForTest(0, frame), + throwsStateError, + ); + expect(sent, isEmpty); + }, + ); + + test('a failed set-scope still attempts a clear (no scope leak)', () async { + await connector.channelRegionScopeStoreForTest.setScope(0, 'oki'); + var calls = 0; + connector.sendFrameOverrideForTest = (_) { + calls++; + if (calls == 1) throw Exception('lost ack on set-scope'); + }; + await expectLater( + connector.sendChannelFrameScopedForTest(0, frame), + throwsA(isA()), + ); + // call 1 = set-scope (threw); call 2 = clear-scope run from the finally. + expect(calls, 2); + }); +} diff --git a/test/connector/channel_sender_resolution_test.dart b/test/connector/channel_sender_resolution_test.dart index b5213a76..4e6182c0 100644 --- a/test/connector/channel_sender_resolution_test.dart +++ b/test/connector/channel_sender_resolution_test.dart @@ -11,7 +11,7 @@ import 'package:meshcore_open/models/contact.dart'; /// namesake case the UI must never resolve on the user's behalf. Contact _contact(String name, int keyByte, {int type = advTypeChat}) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), diff --git a/test/connector/channel_tune_connector_test.dart b/test/connector/channel_tune_connector_test.dart new file mode 100644 index 00000000..577494c0 --- /dev/null +++ b/test/connector/channel_tune_connector_test.dart @@ -0,0 +1,124 @@ +// #971: the connector side of per-channel tune over 0xC5 0x0B / 0x0C. Pins +// the gate (no 0x10, no frame), the bytes sent, that local state follows only +// the device's re-read reply, that inherit and Silent stay distinct end to +// end, and that a refusal lands on the channel-tune surface. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// RESP_CODE_DEVICE_INFO from an Offband radio (fork length, dual version), +/// caps byte 2 at offset 84. A stock-shaped frame would have its caps ignored. +List deviceInfo({required int caps2}) { + final v = ascii.encode('1.5.0-1.17.0'); + final f = Uint8List(85); + f[0] = 13; + f[1] = 22; + f.setRange(60, 60 + v.length, v); + f[84] = caps2; + return f; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List> sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + sent = []; + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (data) => sent.add(data.toList()); + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + bool sentTune() => sent.any( + (f) => + f.length >= 2 && + f[0] == cmdOffbandDeviceUi && + (f[1] == offbandUiChannelTuneGet || f[1] == offbandUiChannelTuneSet), + ); + + test('a radio without 0x10 never sees a channel-tune frame', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x01)); + await connector.requestChannelTune(0); + await connector.setChannelTune(0, ChannelTune.tune(0)); + + expect(connector.supportsTunes, isFalse); + expect(sentTune(), isFalse); + }); + + test('get and set send the documented bytes', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + sent.clear(); + + await connector.requestChannelTune(2); + await connector.setChannelTune(2, const ChannelTune.inherit()); + + expect( + sent, + equals([ + [0xC5, 0x0B, 0x02], + [0xC5, 0x0C, 0x02, 0x00], + ]), + ); + }); + + test('a write is not shown until the radio confirms it', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + await connector.setChannelTune(2, ChannelTune.tune(5)); + + expect(connector.channelTuneFor(2), isNull); + + connector.handleFrameForTest([0xC5, 0x0C, 0x02, 0x06]); + expect(connector.channelTuneFor(2)!.tuneId, equals(5)); + }); + + test('inherit and Silent stay distinct through a round trip', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + connector.handleFrameForTest([0xC5, 0x0B, 0x00, 0x00]); + connector.handleFrameForTest([0xC5, 0x0B, 0x01, 0x01]); + + expect(connector.channelTuneFor(0)!.inherits, isTrue); + expect(connector.channelTuneFor(0)!.isSilent, isFalse); + expect(connector.channelTuneFor(1)!.isSilent, isTrue); + expect(connector.channelTuneFor(1)!.inherits, isFalse); + }); + + test('a refusal after a tune write is the tune surface\'s', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + await connector.setChannelTune(2, ChannelTune.tune(99)); + connector.handleFrameForTest([0xC5, 0x7F, 0x05]); + + expect(connector.deviceUiErrorSurface, DeviceUiSurface.channelTune); + expect(connector.deviceUiError, ButtonConfigError.malformed.message); + // Refused, so nothing changed on the radio and nothing is shown as set. + expect(connector.channelTuneFor(2), isNull); + }); + + test('a new radio does not inherit the previous radio\'s tunes', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + connector.handleFrameForTest([0xC5, 0x0B, 0x00, 0x03]); + expect(connector.channelTuneFor(0), isNotNull); + + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + expect(connector.channelTuneFor(0), isNull); + }); +} diff --git a/test/connector/cli_txt_type_test.dart b/test/connector/cli_txt_type_test.dart new file mode 100644 index 00000000..0e5378de --- /dev/null +++ b/test/connector/cli_txt_type_test.dart @@ -0,0 +1,65 @@ +// #888: role-based CLI txt-type selection for remote CLI. +// +// A companion (chat) gets the 1.18 command type; a repeater/room server gets +// the universal CLI_DATA type. The user types the command, so the frame is a +// passthrough: the type byte changes, the command does not. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +void main() { + group('cliTxtTypeForContactType (#888)', () { + test('a companion gets the 1.18 command type', () { + expect(cliTxtTypeForContactType(advTypeChat), txtTypeCliCommand); + expect(txtTypeCliCommand, 3); + }); + + test('a repeater keeps the universal CLI_DATA type', () { + expect(cliTxtTypeForContactType(advTypeRepeater), txtTypeCliData); + }); + + test('a room server keeps the universal CLI_DATA type', () { + expect(cliTxtTypeForContactType(advTypeRoom), txtTypeCliData); + }); + }); + + group('buildSendCliCommandFrame carries the chosen type (#888)', () { + final pubKey = Uint8List.fromList(List.generate(32, (i) => i)); + // [cmd][type][attempt][ts x4][pubKey x6][command][0] + const int typeOffset = 1; + const int commandOffset = 1 + 1 + 1 + 4 + 6; + + test( + 'defaults to CLI_DATA, so the existing repeater path is unchanged', + () { + final frame = buildSendCliCommandFrame(pubKey, 'get radio'); + expect(frame[typeOffset], txtTypeCliData); + }, + ); + + test('emits the command type when asked (companion path)', () { + final frame = buildSendCliCommandFrame( + pubKey, + 'get radio', + txtType: txtTypeCliCommand, + ); + expect(frame[typeOffset], txtTypeCliCommand); + }); + + test('the command is passed through byte-identical regardless of type', () { + const command = '0A|set tx 22'; + final frame = buildSendCliCommandFrame( + pubKey, + command, + txtType: txtTypeCliCommand, + ); + final written = ascii.decode( + frame.sublist(commandOffset, commandOffset + command.length), + ); + expect(written, command); + }); + }); +} diff --git a/test/connector/contact_frame_naming_test.dart b/test/connector/contact_frame_naming_test.dart new file mode 100644 index 00000000..c1581227 --- /dev/null +++ b/test/connector/contact_frame_naming_test.dart @@ -0,0 +1,284 @@ +// Custom Name override for contacts (#750), task 750.2: the radio boundary. +// +// The radio's contact table is the shared record of what a node calls itself. +// A user's private label must never reach it. Firmware holds a single +// `char name[32]` per contact (`ContactInfo.h:10`), so writing the custom name +// there would overwrite the real one for no gain. +// +// This is the hole the type system cannot see: every frame-builder call site +// reads `.name`, which still compiles after the 750.1 rename and silently +// sends the custom name. T14 is a source-reading guard because nothing else +// can hold it. +// +// Tests T10 to T14 and T33 from the plan of record, +// docs/initiatives/standalone/750-contact-naming/PLAN.md. + +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/services/stock_config_export_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _received = 'KQ4EZN-Repeater'; +const _custom = 'ChuckTheRepeater'; + +Contact _contact({String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x33)), + receivedName: _received, + customName: customName, + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +/// True when [needle] appears anywhere in [frame] as UTF-8 bytes. +bool _frameContains(Uint8List frame, String needle) { + final n = utf8.encode(needle); + for (var i = 0; i + n.length <= frame.length; i++) { + var hit = true; + for (var j = 0; j < n.length; j++) { + if (frame[i + j] != n[j]) { + hit = false; + break; + } + } + if (hit) return true; + } + return false; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + group('the radio receives the received name, never the custom one (#750)', () { + test( + 'T10 + a renamed contact still sends what the node calls itself', + () async { + await connector.addContactByKey(_contact(customName: _custom)); + + expect(sent, isNotEmpty, reason: 'a frame should have been emitted'); + expect(_frameContains(sent.single, _received), isTrue); + }, + ); + + test('T11 - the custom name appears nowhere in the frame bytes', () async { + // The guard that stops a private label reaching the shared contact + // table. `contact.name` would be '$_custom' here. + await connector.addContactByKey(_contact(customName: _custom)); + + expect( + _frameContains(sent.single, _custom), + isFalse, + reason: 'the user label must not cross the wire', + ); + }); + + test( + 'T12 + with no custom name the frame is unchanged from before', + () async { + // Proves this change is behaviour-neutral for every existing path. + await connector.addContactByKey(_contact()); + final withoutCustom = sent.single; + + sent.clear(); + await connector.addContactByKey(_contact(customName: _custom)); + final withCustom = sent.single; + + expect(withCustom, equals(withoutCustom)); + }, + ); + + test( + 'T13 + a card stub sends the card name, which is its received name', + () async { + // A stub built from a contact-share card has the card's name as its + // received name and no custom name, so nothing changes for the add path. + await connector.addContactByKey(_contact()); + + expect(_frameContains(sent.single, _received), isTrue); + }, + ); + }); + + group('T33 the stock config export is an interchange format (#750)', () { + // A stock config file is loaded by other operators, where a contact name + // reads as what that node calls itself. Exporting one user's private label + // would hand it to everyone who imports the file. + // + // Written after the fix rather than before it, unlike the rest of this + // file, so it is falsified below instead: breaking the export line must + // make this test fail and nothing else. + test('+ the export carries the received name', () { + final stock = toStockContact(_contact(customName: _custom)); + + expect(stock.name, _received); + }); + + test('- the custom name is absent from the exported record', () { + final stock = toStockContact(_contact(customName: _custom)); + + expect(stock.name, isNot(contains(_custom))); + }); + }); + + group('T36 sharing a renamed contact does not leak the label (#750)', () { + // Found by the pre-PR adversarial review, not by me, and not reachable by + // T14 because contact.dart was not in its watched list. A share payload + // becomes the RECEIVED name on every device that imports it, so this leak + // propagates to other operators rather than stopping at our own radio. + test( + '- the channel share carries the received name, not the custom one', + () { + final shared = _contact(customName: _custom).toChannelShare(); + + expect(shared, contains(_received)); + expect(shared, isNot(contains(_custom))); + }, + ); + + test('- the share URI carries the received name, not the custom one', () { + final shared = _contact(customName: _custom).toShareUri(); + + expect(shared, contains(Uri.encodeComponent(_received))); + expect(shared, isNot(contains(_custom))); + }); + + test('+ with no custom name both share formats are unchanged', () { + expect(_contact().toChannelShare(), contains(_received)); + expect(_contact().toShareUri(), contains(Uri.encodeComponent(_received))); + }); + }); + + group('T14 source guard: no name-write site reads the display getter', () { + // KNOWN LIMIT, measured not assumed. This guard matches `name: .name` + // and therefore CANNOT see an intra-class read, where the getter is reached + // as bare `name` with an implicit `this`. That is exactly where the share + // leak T36 covers was living, inside contact.dart, and reverting the fix + // was confirmed to leave this guard green while T36 failed. + // + // Widening the regex to catch bare `name:` is not possible without flooding + // on legitimate parameter pass-through: the static build* helpers in + // contact.dart take a `name` parameter and forward it, which is correct. + // + // So: this guard covers CROSS-class reads. Intra-class reads are covered + // behaviourally, by T36 and T11. Do not add a site to contact.dart and + // assume this test is watching it. + // The compiler cannot catch these: `.name` still resolves after the 750.1 + // rename, so a site that reads it compiles and silently sends or stores + // the user's label. Nine sites were found by grep during 750.1; this test + // fails if any of them regresses or a tenth appears. + const watched = [ + // Added after the pre-PR review found the leak this list had missed: + // toShareUri and toChannelShare both read `.name`, and a share payload + // becomes the RECEIVED name on every device that imports it. The guard + // was only watching the radio and the stores, not the paths that send a + // name to other operators. (#750) + 'lib/models/contact.dart', + 'lib/connector/meshcore_connector.dart', + 'lib/services/stock_config_import_service.dart', + 'lib/services/stock_config_export_service.dart', + 'lib/storage/contact_store.dart', + 'lib/storage/contact_discovery_store.dart', + ]; + + // Reviewed exceptions, matched on line CONTENT rather than line number so + // an edit above them does not quietly re-open the hole, and a genuinely + // new offender still fails. + // + // `Channel` has no custom-name concept: its name is not a per-contact user + // label, there is no override to confuse it with, and the stock channel + // record wants exactly that string. (reviewed 2026-10-20) + // `StockContact` is a record 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 it is already a received name. + // This site was in the nine the plan correction listed; analyze proved it + // was never wrong, so the real count of Contact-typed sites is eight. + // (reviewed 2026-10-20) + // Keyed by PATH. An exception in one file must never excuse the same line + // in another: `name: contact.name,` is correct in the import service and + // wrong in the connector, where `contact` is ours. + const allowed = >{ + 'lib/services/stock_config_export_service.dart': { + 'StockChannel(name: channel.name, secret: channel.psk);', + }, + 'lib/services/stock_config_import_service.dart': {'name: contact.name,'}, + }; + + test('no watched file passes a Contact display name into a name field', () { + final offenders = []; + // Matches `name: .name` and `'name': .name`, which is how + // every one of the nine sites looked before 750.1 and 750.2 fixed them. + final bad = RegExp(r"""'?name'?\s*:\s*[A-Za-z_][A-Za-z0-9_]*\.name\b"""); + + for (final path in watched) { + final lines = File(path).readAsLinesSync(); + for (var i = 0; i < lines.length; i++) { + final line = lines[i].trim(); + final exempt = allowed[path]?.contains(line) ?? false; + if (bad.hasMatch(line) && !exempt) { + offenders.add('$path:${i + 1}: $line'); + } + } + } + + expect( + offenders, + isEmpty, + reason: + 'these sites send or store a name. They must read receivedName, ' + 'never the .name getter, which returns the user custom name when ' + 'one is set. See PLAN.md section 2, "the one hole".', + ); + }); + + test('the frame-builder call-site count is still five', () { + // A sixth caller is not forbidden, but it must be reviewed against the + // rule above rather than slipping in unnoticed. + var calls = 0; + for (final path in watched) { + calls += RegExp( + 'buildUpdateContactPathFrame\\(', + ).allMatches(File(path).readAsStringSync()).length; + } + + expect( + calls, + 5, + reason: + 'a new buildUpdateContactPathFrame caller appeared or one was ' + 'removed. Confirm it passes receivedName, then update this count.', + ); + }); + }); +} diff --git a/test/connector/contact_sync_test.dart b/test/connector/contact_sync_test.dart index 8752e3f6..793b95ce 100644 --- a/test/connector/contact_sync_test.dart +++ b/test/connector/contact_sync_test.dart @@ -44,7 +44,7 @@ Uint8List get _end => Uint8List.fromList([respCodeEndOfContacts, ..._u32(0)]); Contact _saved(int keyByte, String name) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: advTypeChat, pathLength: -1, path: Uint8List(0), diff --git a/test/connector/custom_name_lifecycle_test.dart b/test/connector/custom_name_lifecycle_test.dart new file mode 100644 index 00000000..0674de0a --- /dev/null +++ b/test/connector/custom_name_lifecycle_test.dart @@ -0,0 +1,246 @@ +// Custom Name override for contacts (#750), task 750.3: the live lifecycle. +// +// The custom name is stored in contact_settings_store keyed by pubkey, so it +// has to be reattached to the live Contact objects. Two paths drop it if the +// wiring is missing, and both are silent: +// +// 1. cache hydrate rebuilds every Contact from contact_store, which does not +// hold the custom name on purpose (a radio sync would wipe it there); +// 2. radio contact-sync replaces an existing Contact with one built from the +// device frame, where no custom name exists. +// +// Tests T15 to T22 from the plan, plus T34 and T35 for the two paths above. +// +// T15 to T22 guard behaviour that 750.1 already delivered, so they pass on +// arrival and are regression guards rather than watched failures. T34 and T35 +// are the watched ones for this task. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _radioKey = 'd549bbfbd003e580'; +const _received = 'KQ4EZN-Repeater'; +const _custom = 'Chuck'; + +Uint8List _key(int b) => Uint8List.fromList(List.filled(32, b)); + +Contact _contact({ + int keyByte = 0x44, + String receivedName = _received, + String? customName, +}) => Contact( + publicKey: _key(keyByte), + receivedName: receivedName, + customName: customName, + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.contactsForTest.clear(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + group('a custom name survives the paths that rebuild a Contact (#750)', () { + test('T35 - cache hydrate restores the custom name', () async { + // contact_store deliberately does not persist customName, so without + // this wiring a restart silently loses every rename the user made. + final store = ContactStore()..setPublicKeyHex = _radioKey; + final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + await store.saveContacts([_contact()]); + await settings.saveCustomName(_contact().publicKeyHex, _custom); + + await connector.loadContactCacheForTest(_radioKey); + + final loaded = connector.contactsForTest.single; + expect(loaded.customName, _custom); + expect(loaded.name, _custom); + expect( + loaded.receivedName, + _received, + reason: 'the received name must survive alongside it', + ); + }); + + test( + 'T37 - a custom name does not follow a switch to another radio', + () async { + // Owner decision on #750: custom names are per radio. The same node held + // by two radios must show radio B's (absent) label after a switch from + // radio A, never A's label carried over in memory. + const otherRadio = 'a1b2c3d4e5f60718'; + await (ContactStore()..setPublicKeyHex = _radioKey).saveContacts([ + _contact(), + ]); + await (ContactSettingsStore()..setPublicKeyHex = _radioKey) + .saveCustomName(_contact().publicKeyHex, _custom); + await (ContactStore()..setPublicKeyHex = otherRadio).saveContacts([ + _contact(), + ]); + + await connector.loadContactCacheForTest(_radioKey); + expect(connector.contactsForTest.single.name, _custom); + + await connector.loadContactCacheForTest(otherRadio); + + final loaded = connector.contactsForTest.single; + expect(loaded.customName, isNull); + expect(loaded.name, _received); + expect(connector.customNameFor(_contact().publicKeyHex), isNull); + }, + ); + + test( + 'T37b - disconnect drops the radio\'s custom names from memory', + () async { + // Between a disconnect and the next radio's hydrate, nothing may still + // answer with the previous radio's label. + connector.setContactSettingsKeyForTest(_radioKey); + connector.contactsForTest.add(_contact()); + await connector.setContactCustomName(_contact().publicKeyHex, _custom); + + await connector.disconnect(); + + expect(connector.customNameFor(_contact().publicKeyHex), isNull); + }, + ); + + test('T35b + a contact with no custom name hydrates unchanged', () async { + final store = ContactStore()..setPublicKeyHex = _radioKey; + await store.saveContacts([_contact()]); + + await connector.loadContactCacheForTest(_radioKey); + + final loaded = connector.contactsForTest.single; + expect(loaded.customName, isNull); + expect(loaded.name, _received); + }); + + test( + 'T34 + setting a custom name persists it and shows immediately', + () async { + final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + connector.setContactSettingsKeyForTest(_radioKey); + connector.contactsForTest.add(_contact()); + + await connector.setContactCustomName(_contact().publicKeyHex, _custom); + + expect(connector.contactsForTest.single.name, _custom); + expect( + await settings.loadCustomName(_contact().publicKeyHex), + _custom, + reason: 'it must reach storage, not just memory', + ); + }, + ); + + test( + 'T34b + clearing a custom name reverts to the received name', + () async { + final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + connector.setContactSettingsKeyForTest(_radioKey); + connector.contactsForTest.add(_contact(customName: _custom)); + + await connector.setContactCustomName(_contact().publicKeyHex, null); + + expect(connector.contactsForTest.single.customName, isNull); + expect(connector.contactsForTest.single.name, _received); + expect(await settings.loadCustomName(_contact().publicKeyHex), isNull); + }, + ); + + test( + 'T34c - an empty custom name is treated as a clear, not stored', + () async { + final settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + connector.setContactSettingsKeyForTest(_radioKey); + connector.contactsForTest.add(_contact(customName: _custom)); + + await connector.setContactCustomName(_contact().publicKeyHex, ' '); + + expect(connector.contactsForTest.single.name, _received); + expect(await settings.loadCustomName(_contact().publicKeyHex), isNull); + }, + ); + }); + + group('advert interaction, regression guards from 750.1 (#750)', () { + test('T16 - copyWith of a received name leaves the display name alone', () { + final c = _contact( + customName: _custom, + ).copyWith(receivedName: 'renamed-on-its-radio'); + + expect(c.name, _custom); + expect(c.receivedName, 'renamed-on-its-radio'); + }); + + test('T17 + clearing afterwards reveals the NEWEST received name', () { + final c = _contact(customName: _custom) + .copyWith(receivedName: 'renamed-on-its-radio') + .copyWith(clearCustomName: true); + + expect(c.name, 'renamed-on-its-radio'); + }); + + test('T19 - a received-name update never writes a custom name', () { + final c = _contact().copyWith(receivedName: 'new'); + + expect(c.customName, isNull); + }); + + test('T20 + a card-added contact is not advert-verified', () { + final carded = Contact( + publicKey: _key(0x55), + receivedName: 'Alice', + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + + expect(carded.isAdvertVerified, isFalse); + expect(carded.name, 'Alice'); + }); + + test('T21 - a contact that has adverted IS verified', () { + expect(_contact().isAdvertVerified, isTrue); + }); + + test('T22 + a rename that never propagated still shows the user label', () { + // The owner's case: an operator renames their radio, the advert does not + // come, so the received name stays stale. The user's own label is what + // they see, and the stale received name is still there to show beside it. + final c = _contact(customName: _custom); + + expect(c.name, _custom); + expect(c.receivedName, _received); + }); + }); +} diff --git a/test/connector/gps_mode_connector_test.dart b/test/connector/gps_mode_connector_test.dart new file mode 100644 index 00000000..7ce3f2e5 --- /dev/null +++ b/test/connector/gps_mode_connector_test.dart @@ -0,0 +1,184 @@ +// #969: the connector side of GPS mode over 0xC5 0x0D / 0x0E. Pins the gate +// (no 0x20, no frame), the bytes a write sends, that a mode change resends the +// radio's own interval rather than inventing one, that a refusal lands on the +// GPS surface, and that the legacy `gps` custom-var mirror follows the device. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// RESP_CODE_DEVICE_INFO from an Offband radio, caps byte 2 at offset 84. +/// +/// The population classifier honors caps bytes only on a fork-length frame +/// with the dual version form, so a stock-looking frame would (correctly) have +/// its caps ignored. This is the shape a real Offband radio sends. +List deviceInfo({required int caps2}) { + final v = ascii.encode('1.5.0-1.17.0'); + final f = Uint8List(85); + f[0] = 13; + f[1] = 22; + f.setRange(60, 60 + v.length, v); + f[84] = caps2; + return f; +} + +/// `[0xC5][sub][mode][stored][ps_ok][activity][interval:4 LE][wait:4 LE]` +List gpsReply({ + int sub = 0x0D, + int mode = 1, + int stored = 1, + int psOk = 1, + int activity = 1, + int interval = 3600, + int wait = 0, +}) { + final f = Uint8List(14); + f[0] = 0xC5; + f[1] = sub; + f[2] = mode; + f[3] = stored; + f[4] = psOk; + f[5] = activity; + final d = ByteData.sublistView(f); + d.setUint32(6, interval, Endian.little); + d.setUint32(10, wait, Endian.little); + return f; +} + +/// RESP_CODE_CUSTOM_VARS, `key:value` pairs comma-separated. +List customVars(String body) => [21, ...ascii.encode(body), 0]; + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List> sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + sent = []; + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (data) => sent.add(data.toList()); + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + bool sentGps(int sub) => sent.any( + (f) => f.length >= 2 && f[0] == cmdOffbandDeviceUi && f[1] == sub, + ); + + test('a radio advertising 0x20 is asked for its GPS state', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + await Future.delayed(Duration.zero); + + expect(connector.supportsGpsMode, isTrue); + expect(sentGps(offbandUiGpsGet), isTrue); + }); + + test('a radio without 0x20 never sees a GPS frame', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x01)); + await connector.requestGpsMode(); + await connector.setGpsMode(GpsMode.on, intervalSeconds: 0); + + expect(connector.supportsGpsMode, isFalse); + expect(sentGps(offbandUiGpsGet), isFalse); + expect(sentGps(offbandUiGpsSet), isFalse); + }); + + test('the reply becomes the state the screen reads', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest( + gpsReply(mode: 2, stored: 2, activity: 4, interval: 900, wait: 2880), + ); + + final g = connector.gpsModeState!; + expect(g.mode, GpsMode.powerSave); + expect(g.activity, GpsActivity.backedOff); + expect(g.intervalSeconds, equals(900)); + expect(g.waitSeconds, equals(2880)); + }); + + test('a mode change resends the radio\'s current interval', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest(gpsReply(mode: 1, interval: 3600)); + sent.clear(); + + await connector.setGpsMode(GpsMode.powerSave); + + expect(sent, equals([buildGpsModeSetFrame(GpsMode.powerSave, 3600)])); + }); + + test('an explicit interval is sent as given', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest(gpsReply(mode: 2, interval: 3600)); + sent.clear(); + + await connector.setGpsMode(GpsMode.powerSave, intervalSeconds: 120); + + expect(sent, equals([buildGpsModeSetFrame(GpsMode.powerSave, 120)])); + }); + + test('a write before any read is refused visibly, nothing sent', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + sent.clear(); + + await connector.setGpsMode(GpsMode.on); + + expect(sentGps(offbandUiGpsSet), isFalse); + expect(connector.deviceUiError, isNotNull); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.gpsMode); + }); + + test('a refusal after a GPS write is the GPS screen\'s, in its words', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest(gpsReply(mode: 1, psOk: 0)); + connector.setGpsMode(GpsMode.powerSave); + connector.handleFrameForTest([0xC5, 0x7F, 0x01]); + + expect(connector.deviceUiErrorSurface, DeviceUiSurface.gpsMode); + expect(connector.deviceUiError, 'This radio cannot run Power save'); + // The state is not touched by a refusal: the device did not change. + expect(connector.gpsModeState!.mode, GpsMode.on); + }); + + test('a refusal with no GPS write outstanding is not claimed by GPS', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest([0xC5, 0x7F, 0x04]); + + expect(connector.deviceUiError, isNotNull); + expect(connector.deviceUiErrorSurface, isNull); + }); + + test('a confirmed Off updates the gps custom-var mirror', () { + connector.handleFrameForTest(customVars('gps:1,gps_interval:900')); + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest(gpsReply(sub: 0x0E, mode: 0, stored: 2)); + + expect(connector.currentCustomVars!['gps'], equals('0')); + // Off kept the remembered Power-save byte. + expect(connector.gpsModeState!.storedMode, equals(2)); + }); + + test('a radio that reported no gps var does not get one invented', () { + connector.handleFrameForTest(customVars('gps_interval:900')); + connector.handleFrameForTest(deviceInfo(caps2: 0x20)); + connector.handleFrameForTest(gpsReply(mode: 1)); + + expect(connector.currentCustomVars!.containsKey('gps'), isFalse); + }); +} diff --git a/test/connector/inbound_cli_command_test.dart b/test/connector/inbound_cli_command_test.dart new file mode 100644 index 00000000..053ceee1 --- /dev/null +++ b/test/connector/inbound_cli_command_test.dart @@ -0,0 +1,137 @@ +// #890: an inbound remote-CLI command (TXT type 3) another contact sends to run +// on our radio reaches the app as a message. It must be accepted and flagged +// (isCliCommand), not warn-dropped as an unknown type. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// A companion-layout contact-message frame (non-V3): +/// [code][prefix x6][path_len][txt_type][timestamp x4][text][0]. +Uint8List _frame({ + required int txtType, + required Uint8List pubKey, + String text = 'get radio', +}) { + final b = BytesBuilder(); + b.addByte(respCodeContactMsgRecv); + b.add(pubKey.sublist(0, 6)); + b.addByte(0); // path_len + b.addByte(txtType); + b.add([0, 0, 0, 0]); // timestamp + b.add(ascii.encode(text)); + b.addByte(0); // null terminator + return b.toBytes(); +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late Uint8List pubKey; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + pubKey = Uint8List.fromList(List.generate(32, (i) => i + 1)); + connector.contactsForTest.add( + Contact( + publicKey: pubKey, + receivedName: 'Sender', + type: advTypeChat, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ), + ); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test('an inbound type-3 command is accepted and flagged (#890)', () { + final msg = connector.parseContactMessageForTest( + _frame(txtType: txtTypeCliCommand, pubKey: pubKey), + ); + expect(msg, isNotNull, reason: 'type 3 must not be dropped'); + expect(msg!.isCliCommand, isTrue); + expect(msg.isCli, isFalse); + expect(msg.text, 'get radio'); + }); + + test('a type-1 CLI_DATA reply is isCli, not isCliCommand', () { + final msg = connector.parseContactMessageForTest( + _frame(txtType: txtTypeCliData, pubKey: pubKey), + ); + expect(msg, isNotNull); + expect(msg!.isCli, isTrue); + expect(msg.isCliCommand, isFalse); + }); + + test('a plain message is neither isCli nor isCliCommand', () { + final msg = connector.parseContactMessageForTest( + _frame(txtType: txtTypePlain, pubKey: pubKey, text: 'hi'), + ); + expect(msg, isNotNull); + expect(msg!.isCli, isFalse); + expect(msg.isCliCommand, isFalse); + }); + + group('CLI traffic stays out of the chat thread (#999)', () { + // CLI and chat are separate surfaces: a CLI reply (type-1) or an inbound + // CLI command (type-3) is the CLI console's concern, correlated via the + // receivedFrames listener. It must never land in the contact's + // conversation. The console is tested in cli_console_transport_test. + setUp(() { + // The incoming-message path bails without a self identity; set one + // distinct from the sender so nothing is mistaken for an echo of self. + connector.setSelfPublicKeyForTest( + Uint8List.fromList(List.filled(32, 0xAA)), + ); + }); + + Iterable allMessages() => + connector.conversationsForTest.values.expand((m) => m); + + test('a type-1 CLI reply does not enter the conversation', () async { + connector.handleFrameForTest( + _frame(txtType: txtTypeCliData, pubKey: pubKey, text: 'A1|radio ok'), + ); + await Future.delayed(Duration.zero); + expect(allMessages(), isEmpty); + }); + + test( + 'an inbound type-3 CLI command does not enter the conversation', + () async { + connector.handleFrameForTest( + _frame(txtType: txtTypeCliCommand, pubKey: pubKey, text: 'reboot'), + ); + await Future.delayed(Duration.zero); + expect(allMessages(), isEmpty); + }, + ); + + test('a plain message does enter the conversation', () async { + connector.handleFrameForTest( + _frame(txtType: txtTypePlain, pubKey: pubKey, text: 'hi there'), + ); + await Future.delayed(Duration.zero); + expect(allMessages(), isNotEmpty); + }); + }); +} diff --git a/test/connector/offband_device_ui_test.dart b/test/connector/offband_device_ui_test.dart index 4d2ccb2e..61c0443f 100644 --- a/test/connector/offband_device_ui_test.dart +++ b/test/connector/offband_device_ui_test.dart @@ -199,6 +199,262 @@ void main() { }); }); + // #969: GPS mode and Power save over 0xC5 0x0D / 0x0E, per the contract on + // meshcore-firmware#1789. Reply is 14 bytes: + // [0xC5][sub][mode][stored][ps_ok][activity][interval_s:4 LE][wait_s:4 LE] + group('GPS mode capability (caps byte 2 0x20)', () { + test('requires the explicit bit', () { + expect(firmwareSupportsGpsMode(offbandCap2GpsMode), isTrue); + expect(firmwareSupportsGpsMode(offbandCap2NotifyScope), isFalse); + expect(firmwareSupportsGpsMode(null), isFalse); + }); + + test('the new bits collide with no allocated caps-byte-2 bit', () { + // Firmware allocates 0x01 scope, 0x02 matrix, 0x04 indicators, 0x08 + // packet hash (OffbandConfigProtocol.h on firmware-base), and + // f3d30a88 adds 0x10 TUNES, 0x20 GPS mode, 0x40 SCREEN_SETTINGS. + const allocated = 0x01 | 0x02 | 0x04 | 0x08; + const added = [ + offbandCap2Tunes, + offbandCap2GpsMode, + offbandCap2ScreenSettings, + ]; + for (final bit in added) { + expect(bit & allocated, equals(0)); + expect(added.where((b) => b & bit != 0).length, equals(1)); + } + expect(offbandCap2Tunes, equals(0x10)); + expect(offbandCap2GpsMode, equals(0x20)); + expect(offbandCap2ScreenSettings, equals(0x40)); + }); + }); + + group('GPS mode frames', () { + test('get encodes as documented', () { + expect(buildGpsModeGetFrame(), equals([0xC5, 0x0D])); + }); + + test('set carries the mode and a little-endian interval', () { + expect( + buildGpsModeSetFrame(GpsMode.powerSave, 3600), + equals([0xC5, 0x0E, 0x02, 0x10, 0x0E, 0x00, 0x00]), + ); + expect( + buildGpsModeSetFrame(GpsMode.off, 0), + equals([0xC5, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00]), + ); + }); + + test('mode wire values match the firmware enum', () { + expect(GpsMode.off.code, equals(0)); + expect(GpsMode.on.code, equals(1)); + expect(GpsMode.powerSave.code, equals(2)); + }); + }); + + group('GPS mode reply parse', () { + Uint8List reply( + int sub, { + int mode = 2, + int stored = 2, + int psOk = 1, + int activity = 4, + int interval = 3600, + int wait = 2880, + }) => Uint8List.fromList([ + 0xC5, + sub, + mode, + stored, + psOk, + activity, + interval & 0xFF, + (interval >> 8) & 0xFF, + (interval >> 16) & 0xFF, + (interval >> 24) & 0xFF, + wait & 0xFF, + (wait >> 8) & 0xFF, + (wait >> 16) & 0xFF, + (wait >> 24) & 0xFF, + ]); + + test('reads every field from a GET reply', () { + final r = parseGpsModeReply(reply(0x0D)); + expect(r, isNotNull); + expect(r!.isError, isFalse); + final g = r.gps!; + expect(g.mode, GpsMode.powerSave); + expect(g.storedMode, equals(2)); + expect(g.powerSaveAvailable, isTrue); + expect(g.activity, GpsActivity.backedOff); + expect(g.intervalSeconds, equals(3600)); + expect(g.waitSeconds, equals(2880)); + }); + + test('a SET reply has the same shape and is the stored state', () { + final r = parseGpsModeReply(reply(0x0E, interval: 300)); + expect(r!.sub, equals(0x0E)); + expect(r.gps!.intervalSeconds, equals(300)); + }); + + test('the raw 0xFF never-set byte is kept beside the resolved mode', () { + final g = parseGpsModeReply(reply(0x0D, mode: 1, stored: 0xFF))!.gps!; + expect(g.mode, GpsMode.on); + expect(g.storedMode, equals(0xFF)); + }); + + test('ps_ok 0 means Power save is not offered', () { + final g = parseGpsModeReply(reply(0x0D, mode: 1, psOk: 0))!.gps!; + expect(g.powerSaveAvailable, isFalse); + }); + + test('the full 32-bit interval and wait survive', () { + final g = parseGpsModeReply( + reply(0x0D, interval: 0xFFFFFFFF, wait: 0x01020304), + )!.gps!; + expect(g.intervalSeconds, equals(0xFFFFFFFF)); + expect(g.waitSeconds, equals(0x01020304)); + }); + + test('each activity byte maps to its state', () { + const expected = { + 0: GpsActivity.off, + 1: GpsActivity.on, + 2: GpsActivity.searching, + 3: GpsActivity.sleeping, + 4: GpsActivity.backedOff, + }; + expected.forEach((code, activity) { + final g = parseGpsModeReply(reply(0x0D, activity: code))!.gps!; + expect(g.activity, activity, reason: 'activity byte $code'); + }); + }); + + test('an unknown activity from newer firmware is not guessed at', () { + final g = parseGpsModeReply(reply(0x0D, activity: 0x33))!.gps!; + expect(g.activity, isNull); + expect(g.mode, GpsMode.powerSave); + }); + + test('an unknown resolved mode is a visible error, not a default', () { + final r = parseGpsModeReply(reply(0x0D, mode: 7)); + expect(r!.isError, isTrue); + expect(r.gps, isNull); + expect(r.errorMessage, contains('0x07')); + }); + + test('a truncated reply yields null rather than a partial state', () { + final full = reply(0x0D); + for (var n = 2; n < 14; n++) { + expect( + parseGpsModeReply(Uint8List.sublistView(full, 0, n)), + isNull, + reason: 'length $n', + ); + } + }); + + test('other 0xC5 sub-codes are not claimed', () { + expect(parseGpsModeReply(Uint8List.fromList([0xC5, 0x01, 0x00])), isNull); + expect(parseGpsModeReply(Uint8List.fromList([0xC5, 0x7F, 0x04])), isNull); + }); + }); + + // #971: per-channel tune over 0xC5 0x0B / 0x0C (meshcore-firmware#1789). + // Stored byte: 0 = inherit the global channel tune, else tune id + 1, and + // tune id 0 is Silent. Inherit and Silent must never collapse. + group('channel tune encoding', () { + test('inherit is stored as 0', () { + expect(const ChannelTune.inherit().stored, equals(0)); + expect(const ChannelTune.inherit().inherits, isTrue); + expect(const ChannelTune.inherit().tuneId, isNull); + }); + + test('Silent is tune id 0, stored as 1, and is not inherit', () { + final silent = ChannelTune.tune(0); + expect(silent.stored, equals(1)); + expect(silent.isSilent, isTrue); + expect(silent.inherits, isFalse); + expect(silent, isNot(equals(const ChannelTune.inherit()))); + }); + + test('a tune id round-trips through the stored byte', () { + for (final id in [0, 1, 7, 40, 254]) { + final t = ChannelTune.tune(id); + expect(t.stored, equals(id + 1)); + expect(ChannelTune.fromStored(t.stored).tuneId, equals(id)); + } + expect(ChannelTune.fromStored(0).inherits, isTrue); + }); + + test('a tune id that cannot fit the byte is refused', () { + expect(() => ChannelTune.tune(255), throwsArgumentError); + expect(() => ChannelTune.tune(-1), throwsArgumentError); + }); + }); + + group('channel tune frames', () { + test('get and set encode as documented', () { + expect(buildChannelTuneGetFrame(3), equals([0xC5, 0x0B, 0x03])); + expect( + buildChannelTuneSetFrame(3, const ChannelTune.inherit()), + equals([0xC5, 0x0C, 0x03, 0x00]), + ); + expect( + buildChannelTuneSetFrame(3, ChannelTune.tune(0)), + equals([0xC5, 0x0C, 0x03, 0x01]), + ); + }); + + test('a channel index outside a byte is refused', () { + expect(() => buildChannelTuneGetFrame(256), throwsArgumentError); + expect(() => buildChannelTuneGetFrame(-1), throwsArgumentError); + }); + }); + + group('channel tune reply parse', () { + test('a GET reply gives the channel and its tune', () { + final r = parseChannelTuneReply( + Uint8List.fromList([0xC5, 0x0B, 0x02, 0x05]), + ); + expect(r, isNotNull); + expect(r!.channelTune!.channel, equals(2)); + expect(r.channelTune!.tune.tuneId, equals(4)); + }); + + test('a SET reply is the re-read value, and keeps Silent distinct', () { + final silent = parseChannelTuneReply( + Uint8List.fromList([0xC5, 0x0C, 0x02, 0x01]), + )!; + final inherit = parseChannelTuneReply( + Uint8List.fromList([0xC5, 0x0C, 0x02, 0x00]), + )!; + expect(silent.sub, equals(0x0C)); + expect(silent.channelTune!.tune.isSilent, isTrue); + expect(inherit.channelTune!.tune.inherits, isTrue); + }); + + test('a truncated reply yields null', () { + for (final f in [ + [0xC5, 0x0B], + [0xC5, 0x0B, 0x02], + ]) { + expect(parseChannelTuneReply(Uint8List.fromList(f)), isNull); + } + }); + + test('GPS and scope sub-codes are not claimed', () { + expect( + parseChannelTuneReply(Uint8List.fromList([0xC5, 0x0D, 0, 0, 0, 0])), + isNull, + ); + expect( + parseChannelTuneReply(Uint8List.fromList([0xC5, 0x01, 0x00, 0x00])), + isNull, + ); + }); + }); + group('long press is not assignable', () { test('no sequence models a long press', () { // Firmware reserves long press for CLI rescue and power off. Exposing it diff --git a/test/connector/offband_screen_settings_test.dart b/test/connector/offband_screen_settings_test.dart new file mode 100644 index 00000000..fd1f97b6 --- /dev/null +++ b/test/connector/offband_screen_settings_test.dart @@ -0,0 +1,146 @@ +// #987: the badge's screen and battery settings over 0xC5 0x13 to 0x17, and +// the time zone table, against meshcore-firmware f3d30a88. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/offband_screen_settings.dart'; +import 'package:meshcore_open/models/badge_time_zones.dart'; + +void main() { + group('frames', () { + test('get and each set encode as documented', () { + expect(buildScreenSettingsGetFrame(), equals([0xC5, 0x13])); + expect( + buildTextSizeSetFrame(BadgeTextTarget.messages, BadgeTextSize.small), + equals([0xC5, 0x14, 1, 2]), + ); + expect(buildScreenOffSetFrame(300), equals([0xC5, 0x15, 0x2C, 0x01])); + expect(buildTimeZoneSetFrame(2), equals([0xC5, 0x16, 2])); + expect(buildBatteryFullSetFrame(pin: true), equals([0xC5, 0x17, 1])); + expect(buildBatteryFullSetFrame(pin: false), equals([0xC5, 0x17, 0])); + }); + }); + + group('reply', () { + test('all fourteen bytes, little-endian', () { + final r = parseScreenSettingsReply( + Uint8List.fromList([ + 0xC5, 0x15, // + 0, 1, // nav large, messages medium + 0x3C, 0x00, // stored 60 s + 0x3C, 0x00, // waits 60 s + 2, // Eastern + 0x36, 0x10, // 4150 mV stored + 0x36, 0x10, // 4150 mV in use + 0, // learned + ]), + )!; + final s = r.screen!; + expect(s.navText, BadgeTextSize.large); + expect(s.messageText, BadgeTextSize.medium); + expect(s.screenOffStored, 60); + expect(s.screenOffIsDefault, isFalse); + expect(s.timeZone, 2); + expect(s.batteryFullStored, 4150); + expect(s.batteryPinned, isFalse); + }); + + test('a short reply is never shown as the radio\'s state', () { + expect( + parseScreenSettingsReply(Uint8List.fromList([0xC5, 0x13, 0, 1])), + isNull, + ); + }); + + test('screen off labels', () { + expect(screenOffSteps.map(screenOffLabel), [ + '15 s', + '30 s', + '1 m', + '2 m', + '5 m', + ]); + }); + }); + + group('time zones', () { + test('the table matches firmware: 41 entries, indices pinned', () { + expect(badgeTimeZones.length, 41); + expect(badgeTimeZones[0].name, 'not set'); + expect(badgeTimeZones[2].name, 'Eastern'); + expect(badgeTimeZones[12].name, 'UTC-12'); + expect(badgeTimeZones.last.name, 'UTC+9:30'); + }); + + test('US daylight time, both edges', () { + // 2026: DST runs Mar 8 07:00 UTC to Nov 1 06:00 UTC for Eastern. + expect(timeZoneOffsetMinutes(2, DateTime.utc(2026, 3, 8, 6, 59)), -300); + expect(timeZoneOffsetMinutes(2, DateTime.utc(2026, 3, 8, 7)), -240); + expect(timeZoneOffsetMinutes(2, DateTime.utc(2026, 11, 1, 5, 59)), -240); + expect(timeZoneOffsetMinutes(2, DateTime.utc(2026, 11, 1, 6)), -300); + // Arizona keeps standard time all year. + expect(timeZoneOffsetMinutes(5, DateTime.utc(2026, 7, 1)), -420); + }); + + test('EU summer time, both edges', () { + // 2026: last Sundays are Mar 29 and Oct 25, at 01:00 UTC. + expect(timeZoneOffsetMinutes(10, DateTime.utc(2026, 3, 29, 0, 59)), 60); + expect(timeZoneOffsetMinutes(10, DateTime.utc(2026, 3, 29, 1)), 120); + expect(timeZoneOffsetMinutes(10, DateTime.utc(2026, 10, 25, 1)), 60); + }); + + test('not set and unknown indices have no offset', () { + expect(timeZoneOffsetMinutes(0, DateTime.utc(2026)), isNull); + expect(timeZoneOffsetMinutes(99, DateTime.utc(2026)), isNull); + expect(timeZoneName(99), 'Zone 99'); + }); + + test('offset labels', () { + expect(formatUtcOffset(-240), 'UTC-4'); + expect(formatUtcOffset(330), 'UTC+5:30'); + expect(formatUtcOffset(0), 'UTC+0'); + }); + + // A phone whose offset follows the US Eastern rule. + Duration eastern(DateTime local) => + Duration(minutes: timeZoneOffsetMinutes(2, local.toUtc())!); + + test('a phone on Eastern is offered Eastern, not UTC-4', () { + expect( + suggestTimeZone(now: DateTime(2026, 10, 25, 12), offsetAt: eastern), + 2, + ); + }); + + test('a phone with no daylight rule gets the fixed offset', () { + expect( + suggestTimeZone( + now: DateTime(2026, 10, 25, 12), + offsetAt: (_) => const Duration(minutes: 330), + ), + 39, + ); + }); + + test('a phone on UTC gets UTC, not the UK', () { + expect( + suggestTimeZone( + now: DateTime(2026, 10, 25, 12), + offsetAt: (_) => Duration.zero, + ), + 1, + ); + }); + + test('an offset with no zone suggests nothing', () { + expect( + suggestTimeZone( + now: DateTime(2026, 10, 25, 12), + offsetAt: (_) => const Duration(minutes: 345), + ), + isNull, + ); + }); + }); +} diff --git a/test/connector/offband_tones_test.dart b/test/connector/offband_tones_test.dart new file mode 100644 index 00000000..91946a39 --- /dev/null +++ b/test/connector/offband_tones_test.dart @@ -0,0 +1,170 @@ +// #970, #986: the tune codec over 0xC5, against the contract in +// meshcore-firmware f3d30a88 OffbandConfigProtocol.h, and the ports of its +// RTTTL validator and slot-name rule. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/offband_tones.dart'; + +void main() { + group('frames', () { + test('event tone get and set', () { + expect(buildEventToneGetFrame(ToneEvent.dm), equals([0xC5, 0x0F, 0])); + expect( + buildEventToneSetFrame(ToneEvent.sent, 9), + equals([0xC5, 0x10, 5, 9]), + ); + }); + + test('play, slot get and slot read', () { + expect(buildTunePlayFrame(8), equals([0xC5, 0x11, 8])); + expect(buildSlotGetFrame(7), equals([0xC5, 0x09, 7])); + expect(buildSlotReadFrame(2, 15), equals([0xC5, 0x12, 2, 15])); + }); + + test('slot set carries offset, more and the bytes', () { + expect( + buildSlotSetFrame(1, 15, true, [0x61, 0x62]), + equals([0xC5, 0x0A, 1, 15, 1, 0x61, 0x62]), + ); + // The empty final chunk at offset 0 is how a slot is cleared. + expect(buildSlotSetFrame(1, 0, false, []), equals([0xC5, 0x0A, 1, 0, 0])); + }); + + test('a slot past the eight is refused before it is sent', () { + expect(() => buildSlotGetFrame(8), throwsArgumentError); + expect(() => buildSlotReadFrame(-1, 0), throwsArgumentError); + }); + }); + + group('replies', () { + Uint8List f(List b) => Uint8List.fromList(b); + + test('event tone keeps stored and effective apart', () { + final r = parseTuneReply(f([0xC5, 0x0F, 0, 0xFF, 1]))!; + expect(r.eventTone!.event, ToneEvent.dm); + expect(r.eventTone!.state.isRadioDefault, isTrue); + expect(r.eventTone!.state.effective, 1); + }); + + test('an unknown event is an error, not a guess', () { + expect(parseTuneReply(f([0xC5, 0x10, 9, 1, 1]))!.isError, isTrue); + }); + + test('slot get: length and name, and an empty slot', () { + final full = parseTuneReply( + f([0xC5, 0x09, 0, 142, ...'Mario'.codeUnits]), + ); + expect(full!.tuneSlot!.info.length, 142); + expect(full.tuneSlot!.info.name, 'Mario'); + final empty = parseTuneReply(f([0xC5, 0x09, 3, 0])); + expect(empty!.tuneSlot!.info.isEmpty, isTrue); + }); + + test('slot read chunk and play result', () { + final c = parseTuneReply(f([0xC5, 0x12, 1, 15, 1, 0x61, 0x62]))!; + expect(c.slotChunk!.offset, 15); + expect(c.slotChunk!.more, isTrue); + expect(c.slotChunk!.bytes, equals([0x61, 0x62])); + final p = parseTuneReply(f([0xC5, 0x11, 8, 2]))!; + expect(p.tunePlay!.result, TunePlayResult.soundOff); + }); + + test('truncated replies are dropped', () { + expect(parseTuneReply(f([0xC5, 0x0F, 0, 1])), isNull); + expect(parseTuneReply(f([0xC5, 0x12, 1, 0])), isNull); + expect(parseTuneReply(f([0xC5, 0x11, 8])), isNull); + }); + }); + + group('the picker rule', () { + test('named built-ins plus filled slots, never id 7 or empty slots', () { + final slots = { + 0: const TuneSlotInfo(length: 142, name: 'Mario'), + 1: const TuneSlotInfo(length: 0, name: ''), + }; + expect(offeredTuneIds(slots), equals([0, 1, 2, 3, 4, 5, 6, 8])); + }); + + test('labels', () { + final slots = { + 0: const TuneSlotInfo(length: 142, name: 'Mario'), + 4: const TuneSlotInfo(length: 20, name: ''), + }; + expect(tuneLabel(2, slots), 'Kerplop'); + expect(tuneLabel(7, slots), isNull); + expect(tuneLabel(8, slots), 'Mario'); + expect(tuneLabel(12, slots), 'Slot 5'); + expect(tuneLabel(9, slots), isNull); + }); + }); + + group('rtttlProblem, ported from firmware', () { + final cases = { + 'Mario:d=4,o=5,b=100:16e6,16e6': RtttlProblem.ok, + 'MsgRcv3:d=4,o=6,b=200:32e,32g,32b,16c7': RtttlProblem.ok, + 'ack:d=32,o=8,b=120:c': RtttlProblem.ok, + '': RtttlProblem.empty, + 'no colon here': RtttlProblem.missingColon, + ':d=4:c': RtttlProblem.noName, + 'x:d=:c': RtttlProblem.badDefault, + 'x:o=55:c': RtttlProblem.badDefault, + 'Doorbell:d=4,o=5,b=0:8e6': RtttlProblem.zeroTempo, + 'x:b=:c': RtttlProblem.zeroTempo, + 'x:d=4:': RtttlProblem.noNotes, + 'x:b8,c': RtttlProblem.ambiguousNote, + 'x:c:d': RtttlProblem.strayColon, + 'x: d=4,o=5,b=100:c': RtttlProblem.strayColon, + }; + cases.forEach((tune, want) { + test('"$tune" is ${want.name}', () { + expect(rtttlProblem(tune), want); + }); + }); + + test('every problem has firmware\'s words', () { + expect(RtttlProblem.zeroTempo.text, 'b= must be 1 or more'); + expect(RtttlProblem.missingColon.text, 'Needs name:notes'); + }); + }); + + group('fixRtttlDefaultsOrder', () { + // The owner's tune, 2026-10-25: o= before d=, and b= twice. + const takeOnMe = 'Take On Me:o=5,d=8,b=160,b=160:f#,f#,f#,d,p,b4,p,e,p,e5'; + + test('the owner\'s tune is refused, and the fix plays', () { + expect(rtttlProblem(takeOnMe), RtttlProblem.strayColon); + final fixed = fixRtttlDefaultsOrder(takeOnMe); + expect(fixed, 'Take On Me:d=8,o=5,b=160:f#,f#,f#,d,p,b4,p,e,p,e5'); + expect(rtttlProblem(fixed!), RtttlProblem.ok); + }); + + test('a valid tune needs no fix', () { + expect(fixRtttlDefaultsOrder('x:d=4,o=5,b=100:c'), isNull); + }); + + test('two different tempos are not the app\'s to choose', () { + expect(fixRtttlDefaultsOrder('x:o=5,b=160,b=200:c'), isNull); + }); + + test('a header fix never hides a second problem', () { + // Reordered, b=0 still divides by zero in the player. + expect(fixRtttlDefaultsOrder('x:o=5,d=8,b=0:c'), isNull); + // A key the player does not know is not a reorder. + expect(fixRtttlDefaultsOrder('x:o=5,l=8:c'), isNull); + }); + + test('spaces around the defaults are dropped', () { + expect(fixRtttlDefaultsOrder('x: o=5 , d=8 :c'), 'x:d=8,o=5:c'); + }); + }); + + group('deriveSlotName', () { + test('the text before the first colon, trimmed and capped at 12', () { + expect(deriveSlotName(' Mario :d=4:c'), 'Mario'); + expect(deriveSlotName('ABCDEFGHIJKLMNOP:c'), 'ABCDEFGHIJKL'); + expect(deriveSlotName('no colon'), ''); + }); + }); +} diff --git a/test/connector/reconnect_policy_test.dart b/test/connector/reconnect_policy_test.dart new file mode 100644 index 00000000..d03288bb --- /dev/null +++ b/test/connector/reconnect_policy_test.dart @@ -0,0 +1,61 @@ +// Bounded auto-reconnect (#997, design on #995). +// +// On 2026-10-25 the client retried an unreachable T1000-E every ~1 s for 7.7 +// hours: connect() reset the attempt counter at the start of every automatic +// attempt, so the backoff never grew and nothing ever gave up. The policy owns +// the counter now, and only an explicit reset clears it. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/reconnect_policy.dart'; + +void main() { + final t0 = DateTime.utc(2026, 10, 26, 12); + + test('delays grow 1, 2, 4, 8, 16 s across the five allowed attempts', () { + final policy = ReconnectPolicy(); + final delays = [ + for (var i = 0; i < 5; i++) + policy.nextDelay(t0.add(Duration(seconds: i)))!.inSeconds, + ]; + expect(delays, [1, 2, 4, 8, 16]); + }); + + test('gives up after five attempts', () { + final policy = ReconnectPolicy(); + for (var i = 0; i < 5; i++) { + expect(policy.nextDelay(t0), isNotNull); + } + expect(policy.nextDelay(t0), isNull); + expect(policy.attempts, 5); + }); + + test('gives up after three minutes even with attempts left', () { + final policy = ReconnectPolicy(); + expect(policy.nextDelay(t0), isNotNull); + expect( + policy.nextDelay(t0.add(const Duration(minutes: 3))), + isNull, + reason: 'the window runs from the first scheduled attempt', + ); + }); + + test('a delay never carries the retry past the three minute window', () { + final policy = ReconnectPolicy(); + policy.nextDelay(t0); + final delay = policy.nextDelay( + t0.add(const Duration(minutes: 2, seconds: 59)), + ); + expect(delay, isNull, reason: 'the attempt would start after 3 min'); + }); + + test('reset starts a fresh budget', () { + final policy = ReconnectPolicy(); + for (var i = 0; i < 5; i++) { + policy.nextDelay(t0); + } + policy.reset(); + final later = t0.add(const Duration(minutes: 10)); + expect(policy.attempts, 0); + expect(policy.nextDelay(later)!.inSeconds, 1); + }); +} diff --git a/test/connector/region_connector_test.dart b/test/connector/region_connector_test.dart new file mode 100644 index 00000000..b565fc17 --- /dev/null +++ b/test/connector/region_connector_test.dart @@ -0,0 +1,246 @@ +// Epic #813 T3: connector wiring for region discovery + flood-scope. +// Exercises the real dispatch/correlation via the test seams +// (setConnectedForTest / sendFrameOverrideForTest / handleFrameForTest). +// No key material here is real. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List _u32le(int v) { + final b = Uint8List(4); + ByteData.sublistView(b).setUint32(0, v, Endian.little); + return b; +} + +Uint8List _padName(String name, int len) { + final b = Uint8List(len); + for (var i = 0; i < name.length && i < len - 1; i++) { + b[i] = name.codeUnitAt(i); + } + return b; +} + +// The firmware's send ack: [RESP_CODE_SENT][flood][tag:4 LE][est:4]. The tag is +// the firmware-chosen anon-req tag the repeater echoes in its 0x8C reply. +Uint8List _respSent(int tag) { + final b = BytesBuilder() + ..addByte(respCodeSent) + ..addByte(0) + ..add(_u32le(tag)) + ..add(_u32le(0)); + return b.toBytes(); +} + +// The repeater's 0x8C regions reply: [0x8C][0][tag:4][clock:4][CSV]. +Uint8List _regionsReply(int tag, {required int clock, required String csv}) { + final b = BytesBuilder() + ..addByte(pushCodeBinaryResponse) + ..addByte(0) + ..add(_u32le(tag)) + ..add(_u32le(clock)) + ..add(Uint8List.fromList([...csv.codeUnits, 0])); + return b.toBytes(); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late MeshCoreConnector connector; + final pub = Uint8List.fromList(List.generate(32, (i) => i + 1)); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + connector = MeshCoreConnector(); + connector.setConnectedForTest(); + connector.setFirmwareVerCodeForTest(22); + }); + + group('discoverRegions', () { + test( + 'sends the anon regions request and returns the parsed reply', + () async { + Uint8List? sent; + connector.sendFrameOverrideForTest = (data) { + sent = data; + // Firmware ack carries the tag; the repeater's 0x8C echoes it. + connector.handleFrameForTest(_respSent(0xAABBCCDD)); + connector.handleFrameForTest( + _regionsReply(0xAABBCCDD, clock: 0x01020304, csv: 'oki,test,*'), + ); + }; + final reply = await connector.discoverRegions(repeaterPubKey: pub); + expect(sent, isNotNull); + expect(sent![0], cmdSendAnonReq); + expect(sent![33], anonReqTypeRegions); // type right after the pubkey + expect(reply, isNotNull); + expect(reply!.regionNames, ['oki', 'test', '*']); + expect(reply.clock, 0x01020304); + }, + ); + + test('returns null on timeout when no reply arrives', () async { + connector.sendFrameOverrideForTest = (_) {}; + final reply = await connector.discoverRegions( + repeaterPubKey: pub, + timeout: const Duration(milliseconds: 50), + ); + expect(reply, isNull); + }); + + test( + 'a 0x8C with a non-matching tag never satisfies the request', + () async { + connector.sendFrameOverrideForTest = (_) { + // Ack says tag A, but the 0x8C carries a different tag -> no match. + connector.handleFrameForTest(_respSent(0x11111111)); + connector.handleFrameForTest( + _regionsReply(0x22222222, clock: 1, csv: 'zzz'), + ); + }; + final reply = await connector.discoverRegions( + repeaterPubKey: pub, + timeout: const Duration(milliseconds: 80), + ); + expect(reply, isNull); + }, + ); + + test('refuses when firmware does not support region scope', () async { + connector.setFirmwareVerCodeForTest(7); + expect(connector.supportsRegionScope, isFalse); + await expectLater( + connector.discoverRegions(repeaterPubKey: pub), + throwsStateError, + ); + }); + + test('uses the repeater contact path as the reply path', () async { + final pk = Uint8List.fromList(List.generate(32, (i) => 0x40 + i)); + connector.contactsForTest.add( + Contact( + publicKey: pk, + receivedName: 'rpt', + type: advTypeRepeater, + pathLength: 2, + pathHashWidth: 1, + path: Uint8List.fromList([0xAA, 0xBB]), + lastSeen: DateTime(2026), + ), + ); + Uint8List? sent; + connector.sendFrameOverrideForTest = (data) { + sent = data; + connector.handleFrameForTest(_respSent(0x55)); + connector.handleFrameForTest(_regionsReply(0x55, clock: 1, csv: 'oki')); + }; + final reply = await connector.discoverRegions(repeaterPubKey: pk); + expect(reply, isNotNull); + expect(sent![33], anonReqTypeRegions); + expect(sent![34], 2); // packed path-len byte: 2 hops, 1-byte hashes + expect(sent!.sublist(35), [0xAA, 0xBB]); + }); + + test( + 'auto-retries once: first attempt times out, second succeeds', + () async { + var sends = 0; + connector.sendFrameOverrideForTest = (_) { + sends++; + // First send injects nothing (that attempt times out); second answers. + if (sends >= 2) { + connector.handleFrameForTest(_respSent(0x77)); + connector.handleFrameForTest( + _regionsReply(0x77, clock: 1, csv: 'oki'), + ); + } + }; + final reply = await connector.discoverRegions( + repeaterPubKey: pub, + timeout: const Duration(milliseconds: 60), + ); + expect(reply, isNotNull); + expect(reply!.regionNames, ['oki']); + expect(sends, 2); + }, + ); + }); + + group('send-scope setters', () { + test('setChannelSendScope emits [54][0][key16]', () async { + Uint8List? sent; + connector.sendFrameOverrideForTest = (d) => sent = d; + final key = Uint8List.fromList(List.generate(16, (i) => 0xA0 + i)); + await connector.setChannelSendScope(key); + expect(sent, isNotNull); + expect(sent![0], cmdSetFloodScopeKey); + expect(sent![1], floodScopeSubSetKey); + expect(sent!.sublist(2), key); + }); + + test('clearSendScope emits [54][0]', () async { + Uint8List? sent; + connector.sendFrameOverrideForTest = (d) => sent = d; + await connector.clearSendScope(); + expect(sent, [cmdSetFloodScopeKey, floodScopeSubSetKey]); + }); + + test('setChannelSendScope refuses when unsupported', () async { + connector.setFirmwareVerCodeForTest(7); + await expectLater( + connector.setChannelSendScope(Uint8List(16)), + throwsStateError, + ); + }); + }); + + group('default flood scope', () { + test('getDefaultFloodScope returns the parsed RESP 28', () async { + connector.sendFrameOverrideForTest = (_) { + final b = BytesBuilder() + ..addByte(respCodeDefaultFloodScope) + ..add(_padName('oki', 31)) + ..add(Uint8List.fromList(List.generate(16, (i) => i))); + connector.handleFrameForTest(b.toBytes()); + }; + final scope = await connector.getDefaultFloodScope(); + expect(scope, isNotNull); + expect(scope!.name, 'oki'); + expect(scope.isSet, isTrue); + }); + + test('setDefaultFloodScope emits [63][name31][key16]', () async { + Uint8List? sent; + connector.sendFrameOverrideForTest = (d) => sent = d; + await connector.setDefaultFloodScope('oki', Uint8List(16)); + expect(sent, isNotNull); + expect(sent![0], cmdSetDefaultFloodScope); + expect(sent!.length, 1 + 31 + 16); + }); + + test('coalesces concurrent calls onto one in-flight query', () async { + var sends = 0; + connector.sendFrameOverrideForTest = (_) { + sends++; + final b = BytesBuilder() + ..addByte(respCodeDefaultFloodScope) + ..add(_padName('oki', 31)) + ..add(Uint8List(16)); + connector.handleFrameForTest(b.toBytes()); + }; + final f1 = connector.getDefaultFloodScope(); + final f2 = connector.getDefaultFloodScope(); + final r1 = await f1; + final r2 = await f2; + expect(sends, 1); // second caller did not emit a second frame + expect(r1!.name, 'oki'); + expect(r2!.name, 'oki'); + }); + }); +} diff --git a/test/connector/region_protocol_test.dart b/test/connector/region_protocol_test.dart new file mode 100644 index 00000000..3177bbeb --- /dev/null +++ b/test/connector/region_protocol_test.dart @@ -0,0 +1,160 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; + +// Wire contract verified against firmware source: +// - companion MyMesh.cpp:3114-3144 (CMD_SEND_ANON_REQ, non-contact 13+), +// 3512-3548 (CMD_SET_FLOOD_SCOPE_KEY 54, CMD_SET/GET_DEFAULT_FLOOD_SCOPE +// 63/64, RESP_CODE_DEFAULT_FLOOD_SCOPE 28), 1201-1211 (0x8C envelope). +// - simple_repeater MyMesh.cpp:586-607, 150-163 (anon regions req/reply). + +Uint8List _key16(int seed) => + Uint8List.fromList(List.generate(16, (i) => (seed + i) & 0xFF)); + +void main() { + group('buildAnonRegionsRequestFrame', () { + test( + '[57][pubkey32][0x01][reply_path_len=0] (firmware prepends the tag)', + () { + final pub = Uint8List.fromList(List.generate(32, (i) => i + 1)); + final frame = buildAnonRegionsRequestFrame(pub); + // No client timestamp: BaseChatMesh.sendAnonReq prepends the 4-byte tag, + // so the type byte must sit immediately after the 32-byte pubkey (#836). + expect(frame.length, 1 + 32 + 1 + 1); + expect(frame[0], cmdSendAnonReq); + expect(frame.sublist(1, 33), pub); + expect(frame[33], anonReqTypeRegions); + expect(frame[34], 0); // reply_path_len = 0 (zero-hop reply) + }, + ); + }); + + group('flood-scope key frames', () { + test('set: [54][0][key16]', () { + final frame = buildSetFloodScopeKeyFrame(_key16(0xA0)); + expect(frame.length, 2 + 16); + expect(frame[0], cmdSetFloodScopeKey); + expect(frame[1], 0); + expect(frame.sublist(2), _key16(0xA0)); + }); + + test('clear override to node default: [54][0]', () { + expect(buildClearFloodScopeFrame(), [cmdSetFloodScopeKey, 0]); + }); + + test('force unscoped (ver 12+): [54][1]', () { + expect(buildFloodScopeUnscopedFrame(), [cmdSetFloodScopeKey, 1]); + }); + }); + + group('default flood scope', () { + test('set: [63][name:31 NUL-padded][key:16]', () { + final frame = buildSetDefaultFloodScopeFrame('oki', _key16(0x10)); + expect(frame.length, 1 + 31 + 16); + expect(frame[0], cmdSetDefaultFloodScope); + expect(frame.sublist(1, 4), 'oki'.codeUnits); + expect(frame[4], 0); // NUL terminator + expect(frame.sublist(32, 48), _key16(0x10)); + }); + + test('clear: [63]', () { + expect(buildClearDefaultFloodScopeFrame(), [cmdSetDefaultFloodScope]); + }); + + test('get: [64]', () { + expect(buildGetDefaultFloodScopeFrame(), [cmdGetDefaultFloodScope]); + }); + + test('parse RESP 28 with a set scope', () { + final f = BytesBuilder() + ..addByte(respCodeDefaultFloodScope) + ..add(_padName('oki', 31)) + ..add(_key16(0x10)); + final scope = parseDefaultFloodScopeReply(f.toBytes()); + expect(scope, isNotNull); + expect(scope!.name, 'oki'); + expect(scope.key, _key16(0x10)); + expect(scope.isSet, isTrue); + }); + + test('parse bare RESP 28 as no-default', () { + final scope = parseDefaultFloodScopeReply( + Uint8List.fromList([respCodeDefaultFloodScope]), + ); + expect(scope, isNotNull); + expect(scope!.isSet, isFalse); + }); + + test('parse returns null for a non-28 frame', () { + expect( + parseDefaultFloodScopeReply(Uint8List.fromList([respCodeOk])), + isNull, + ); + }); + }); + + group('parseRegionsReply (0x8C envelope)', () { + Uint8List reply(int tag, int clock, String csv) { + final b = BytesBuilder() + ..addByte(pushCodeBinaryResponse) + ..addByte(0) // reserved + ..add(_u32le(tag)) + ..add(_u32le(clock)) + ..add(Uint8List.fromList([...csv.codeUnits, 0])); + return b.toBytes(); + } + + test('extracts tag, clock, and comma-split names', () { + final r = parseRegionsReply(reply(0xDEADBEEF, 0x01020304, 'oki,test,*')); + expect(r, isNotNull); + expect(r!.tag, 0xDEADBEEF); + expect(r.clock, 0x01020304); + expect(r.regionNames, ['oki', 'test', '*']); + }); + + test('empty CSV yields no names (not a parse error)', () { + final r = parseRegionsReply(reply(1, 2, '')); + expect(r, isNotNull); + expect(r!.regionNames, isEmpty); + }); + + test('null for a short or non-0x8C frame', () { + expect( + parseRegionsReply(Uint8List.fromList([pushCodeBinaryResponse, 0])), + isNull, + ); + expect( + parseRegionsReply( + Uint8List.fromList([respCodeOk, 0, 0, 0, 0, 0, 0, 0, 0, 0]), + ), + isNull, + ); + }); + }); + + group('firmwareSupportsRegionScope', () { + test('floor is FIRMWARE_VER_CODE 13', () { + expect(firmwareSupportsRegionScope(null), isFalse); + expect(firmwareSupportsRegionScope(7), isFalse); + expect(firmwareSupportsRegionScope(12), isFalse); + expect(firmwareSupportsRegionScope(13), isTrue); + expect(firmwareSupportsRegionScope(22), isTrue); + }); + }); +} + +Uint8List _u32le(int v) { + final b = Uint8List(4); + ByteData.sublistView(b).setUint32(0, v, Endian.little); + return b; +} + +Uint8List _padName(String name, int len) { + final b = Uint8List(len); + final bytes = name.codeUnits; + for (var i = 0; i < bytes.length && i < len - 1; i++) { + b[i] = bytes[i]; + } + return b; +} diff --git a/test/connector/scope_key_lifecycle_test.dart b/test/connector/scope_key_lifecycle_test.dart new file mode 100644 index 00000000..1123580f --- /dev/null +++ b/test/connector/scope_key_lifecycle_test.dart @@ -0,0 +1,169 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #939 Epic D: the scope-key lifecycle. +/// +/// A different defect class from Epic B's global keys. These stores ARE +/// correctly per-radio; they bled anyway, through timing. The scope key is set +/// on SELF_INFO, and an unexpected disconnect did not clear it, so connecting a +/// different radio left a window in which any read served the previous radio's +/// data (#158). +/// +/// Also carries D1's verdict on #190, as a test rather than an argument. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage msg(String text) => ChannelMessage( + senderName: 's', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + isOutgoing: false, + channelIndex: 0, + messageId: 'id-$text', + ); + + group('#158 the stale-read window after an unexpected drop', () { + test( + 'clearing the scope keys makes a read fail closed, not serve radio A', + () async { + // Radio A connects and stores history. + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [msg('radio A only')]); + expect((await store.loadChannelMessages(0)).length, 1); + + // The drop. Before this fix _handleDisconnection left the key in + // place, so this store still answered as radio A. + store.setPublicKeyHex = ''; + + expect( + await store.loadChannelMessages(0), + isEmpty, + reason: + 'with no radio identity a read must return nothing. ' + 'Serving radio A here is #158', + ); + }, + ); + + test('and a write in that window is refused, not misfiled', () async { + final store = ChannelMessageStore()..setPublicKeyHex = ''; + + await store.saveChannelMessages(0, [msg('arrived mid-reconnect')]); + + // Bring radio A back and confirm nothing was filed under it. + store.setPublicKeyHex = 'a' * 20; + expect( + await store.loadChannelMessages(0), + isEmpty, + reason: + 'a message arriving before SELF_INFO must not be written ' + 'under whichever radio connects next', + ); + }); + + test('the connector clears every store on an unexpected drop', () async { + // Exercises the real reset rather than a hand-cleared store, so the + // test fails if a store is added to the connector and left out of + // _clearStorageScopeKeys. + final connector = MeshCoreConnector(); + + connector.clearStorageScopeKeysForTest(); + + expect( + connector.selfPublicKeyHex, + isEmpty, + reason: + 'channels_screen builds its own store from this getter, so ' + 'clearing the connector-owned stores alone would leave that ' + 'path reading a stale prefix', + ); + }); + }); + + group('#190 verdict: a reused slot cannot surface the old occupant', () { + // #190's reproduction: scan a new channel's QR, and the new channel shows + // the previous occupant's history (#echo). Its named root cause was + // slot-index keying with no PSK binding. Two mechanisms landed since, and + // this proves the scenario rather than arguing it. + + test( + 'PSK identity, not slot index, decides which history is read', + () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + // The old occupant of slot 0. + store.channelPskResolver = (_) => 'psk_old'; + await store.saveChannelMessages(0, [msg('old #echo history')]); + + // The slot is reassigned: same index 0, different PSK. + store.channelPskResolver = (_) => 'psk_new'; + + expect( + await store.loadChannelMessages(0), + isEmpty, + reason: + '#190 exactly: the newly added channel must not see the ' + 'previous occupant\'s messages. Keyed by PSK (#194) it reads a ' + 'different key entirely', + ); + }, + ); + + test('and the old occupant\'s history is still its own', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + store.channelPskResolver = (_) => 'psk_old'; + await store.saveChannelMessages(0, [msg('old #echo history')]); + + store.channelPskResolver = (_) => 'psk_new'; + await store.saveChannelMessages(0, [msg('new channel')]); + store.channelPskResolver = (_) => 'psk_old'; + + expect( + (await store.loadChannelMessages(0)).single.text, + 'old #echo history', + reason: + 'isolation by identity, not deletion: if that channel comes ' + 'back to any slot it still has its own history', + ); + }); + + test('the index fallback is what remains, and it warns', () async { + // With no resolver the store falls back to the slot-index key. That is + // legitimate before the channel list has loaded and is the #333 race, + // which is a TIMING problem and therefore this Epic's subject rather + // than #190's. Pinned here so the remaining surface is explicit. + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + await store.saveChannelMessages(0, [msg('written without a PSK')]); + + expect( + (await store.loadChannelMessages(0)).single.text, + 'written without a PSK', + reason: + 'the fallback still works; what it cannot do is tell two ' + 'occupants of one slot apart, which is why _storageKey logs a ' + 'warning when it fires', + ); + }); + }); +} diff --git a/test/connector/tunes_connector_test.dart b/test/connector/tunes_connector_test.dart new file mode 100644 index 00000000..25e94578 --- /dev/null +++ b/test/connector/tunes_connector_test.dart @@ -0,0 +1,346 @@ +// #970, #986, #987: the connector side of tunes and screen settings over 0xC5. +// Pins the gates (no bit, no frame), that state follows only the radio's +// replies, the chunked slot read and save, the one restart a displaced save +// gets, and that refusals land on the right surface. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/connector/offband_tones.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// RESP_CODE_DEVICE_INFO from an Offband radio, caps byte 2 at offset 84. +List deviceInfo({required int caps2}) { + final v = ascii.encode('1.5.0-1.17.0'); + final f = Uint8List(85); + f[0] = 13; + f[1] = 22; + f.setRange(60, 60 + v.length, v); + f[84] = caps2; + return f; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List> sent; + + /// Replies the fake radio sends for each frame the client writes. + List> Function(List frame)? radio; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + sent = []; + radio = null; + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (data) { + final frame = data.toList(); + sent.add(frame); + final replies = radio?.call(frame) ?? const []; + // Replies arrive after the write returns, as they would over a link. + scheduleMicrotask(() { + for (final r in replies) { + connector.handleFrameForTest(r); + } + }); + }; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + bool sentSub(Set subs) => sent.any( + (f) => f.length >= 2 && f[0] == cmdOffbandDeviceUi && subs.contains(f[1]), + ); + + group('gates', () { + test('no 0x10: no tune frame of any kind', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x01)); + sent.clear(); + await connector.requestEventTones(); + await connector.setEventTone(ToneEvent.dm, 1); + await connector.requestTuneSlots(); + expect(await connector.playTune(1), isNull); + expect(await connector.readTuneSlot(0), isNull); + expect(await connector.saveTuneSlot(0, 'x:d=4:c'), isFalse); + expect(sentSub({0x09, 0x0A, 0x0F, 0x10, 0x11, 0x12}), isFalse); + }); + + test('no 0x40: no screen frame, and none on connect', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + await connector.setTimeZone(2); + await connector.setScreenOff(60); + expect(sentSub({0x13, 0x14, 0x15, 0x16, 0x17}), isFalse); + }); + + test('with 0x40 the settings are read on connect', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x40)); + expect(sent, contains(equals([0xC5, 0x13]))); + }); + }); + + group('event tones', () { + test('reads all six, and a write shows only once confirmed', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + sent.clear(); + await connector.requestEventTones(); + expect(sent, [ + for (var ev = 0; ev < 6; ev++) [0xC5, 0x0F, ev], + ]); + + await connector.setEventTone(ToneEvent.room, 8); + expect(connector.eventTone(ToneEvent.room), isNull); + connector.handleFrameForTest([0xC5, 0x10, 2, 8, 8]); + expect(connector.eventTone(ToneEvent.room)!.stored, 8); + }); + + test('a refused event tone is the event tone surface\'s', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + await connector.setEventTone(ToneEvent.dm, 9); + connector.handleFrameForTest([0xC5, 0x7F, 0x05]); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.eventTone); + expect(connector.eventTone(ToneEvent.dm), isNull); + }); + }); + + group('preview', () { + test('returns the radio\'s result', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => [ + [0xC5, 0x11, f[2], 2], + ]; + expect(await connector.playTune(3), TunePlayResult.soundOff); + }); + + test('a refused id comes back null and is shown', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => [ + [0xC5, 0x7F, 0x05], + ]; + expect(await connector.playTune(12), isNull); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.tunePlay); + }); + }); + + group('slot read', () { + test('follows more until the radio says done', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + final tune = ascii.encode('Mario:d=4,o=5,b=100:16e6,16e6,32p'); + radio = (f) { + final offset = f[3]; + final end = (offset + 10).clamp(0, tune.length); + return [ + [ + 0xC5, + 0x12, + f[2], + offset, + end < tune.length ? 1 : 0, + ...tune.sublist(offset, end), + ], + ]; + }; + final progress = []; + final text = await connector.readTuneSlot(1, onProgress: progress.add); + expect(text, ascii.decode(tune)); + expect(progress.last, tune.length); + expect(connector.tuneSlotTransferActive, isFalse); + }); + + test('an empty slot reads as empty text', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => [ + [0xC5, 0x12, f[2], 0, 0], + ]; + expect(await connector.readTuneSlot(4), ''); + }); + + test('a chunk that says more but carries nothing stops the read', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => [ + [0xC5, 0x12, f[2], f[3], 1], + ]; + expect(await connector.readTuneSlot(0), isNull); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.tuneSlot); + }); + }); + + group('slot save', () { + /// A radio that assembles pushes the way firmware does, optionally + /// displacing the first push after its first chunk. + List> Function(List) assembler({bool displaceOnce = false}) { + var held = []; + var displaced = !displaceOnce; + return (f) { + if (f[1] == 0x09) { + return [ + [0xC5, 0x09, f[2], held.length, ...ascii.encode('Mario')], + ]; + } + if (f[1] != 0x0A) return const []; + final offset = f[3]; + final more = f[4] != 0; + if (offset == 0) held = []; + if (offset != held.length) { + return [ + [0xC5, 0x7F, 0x07, held.length], + ]; + } + held.addAll(f.sublist(5)); + if (!displaced && more) { + displaced = true; + held = []; + return [ + [0xC5, 0x7F, 0x07, 0], + ]; + } + return [ + [0xC5, 0x0A, f[2], more ? held.length : 0], + ]; + }; + } + + test('sends chunks with running offsets and commits on the last', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = assembler(); + sent.clear(); + final tune = 'Mario:d=4,o=5,b=100:${List.filled(40, '8e6').join(',')}'; + final ok = await connector.saveTuneSlot(0, tune); + expect(ok, isTrue); + + final pushes = sent.where((f) => f[1] == 0x0A).toList(); + expect(pushes.length, greaterThan(1)); + var expectOffset = 0; + for (final p in pushes) { + expect(p[3], expectOffset); + expectOffset += p.length - 5; + } + expect(pushes.last[4], 0); + expect( + pushes.sublist(0, pushes.length - 1).every((p) => p[4] == 1), + isTrue, + ); + // Chunks respect the transport's frame budget. + expect( + pushes.every((p) => p.length <= connector.effectiveMaxFrameSize), + isTrue, + ); + // Re-read after the commit, and the list shows the radio's answer. + expect(sent.last, equals([0xC5, 0x09, 0])); + expect(connector.tuneSlots[0]!.length, tune.length); + }); + + test('a displaced push restarts from 0 once and succeeds', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = assembler(displaceOnce: true); + final tune = 'Mario:d=4,o=5,b=100:${List.filled(40, '8e6').join(',')}'; + expect(await connector.saveTuneSlot(0, tune), isTrue); + final restarts = sent.where((f) => f[1] == 0x0A && f[3] == 0).length; + expect(restarts, 2); + expect(connector.deviceUiError, isNull); + }); + + test('displaced twice: stops and says so', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => f[1] == 0x0A + ? [ + [0xC5, 0x7F, 0x07, 0], + ] + : const []; + final tune = 'Mario:d=4,o=5,b=100:${List.filled(40, '8e6').join(',')}'; + expect(await connector.saveTuneSlot(0, tune), isFalse); + expect(sent.where((f) => f[1] == 0x0A).length, 2); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.tuneSlot); + expect(connector.deviceUiError, ButtonConfigError.slotOffset.message); + }); + + test('clearing sends the one empty commit', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = assembler(); + sent.clear(); + expect(await connector.saveTuneSlot(3, ''), isTrue); + expect(sent.first, equals([0xC5, 0x0A, 3, 0, 0])); + }); + + test('a final reply that is not 0 is not a commit', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + radio = (f) => f[1] == 0x0A + ? [ + [0xC5, 0x0A, f[2], 5], + ] + : const []; + expect(await connector.saveTuneSlot(0, 'x:d=4:c'), isFalse); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.tuneSlot); + }); + + test('no preview is sent while a slot transfer is running', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + sent.clear(); + final read = connector.readTuneSlot(0); + await Future.delayed(Duration.zero); + expect(connector.tuneSlotTransferActive, isTrue); + expect(await connector.playTune(3), isNull); + expect(sentSub({0x11}), isFalse); + connector.handleFrameForTest([0xC5, 0x12, 0, 0, 0]); + expect(await read, ''); + }); + + test('a tune over 240 characters is never sent', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x10)); + sent.clear(); + expect(await connector.saveTuneSlot(0, 'x:${'c' * 240}'), isFalse); + expect(sent, isEmpty); + }); + }); + + group('screen settings', () { + List reply(int sub, {int tz = 2}) => [ + 0xC5, sub, 0, 1, 60, 0, 60, 0, tz, 0x36, 0x10, 0x36, 0x10, 0, // + ]; + + test('state follows the re-read reply', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x40)); + await connector.setTimeZone(9); + expect(sent.last, equals([0xC5, 0x16, 9])); + connector.handleFrameForTest(reply(0x16, tz: 9)); + expect(connector.screenSettings!.timeZone, 9); + }); + + test('a battery refusal keeps the radio\'s reason', () async { + connector.handleFrameForTest(deviceInfo(caps2: 0x40)); + connector.handleFrameForTest(reply(0x13)); + await connector.setBatteryFull(pin: true); + connector.handleFrameForTest([0xC5, 0x7F, 0x09]); + expect(connector.deviceUiErrorSurface, DeviceUiSurface.screenSettings); + expect( + connector.deviceUiError, + ButtonConfigError.batteryNotCharged.message, + ); + expect(connector.screenSettings!.batteryFullStored, 4150); + }); + + test('a new radio does not inherit the previous one\'s settings', () { + connector.handleFrameForTest(deviceInfo(caps2: 0x50)); + connector.handleFrameForTest(reply(0x13)); + connector.handleFrameForTest([0xC5, 0x0F, 0, 1, 1]); + connector.handleFrameForTest(deviceInfo(caps2: 0x50)); + expect(connector.screenSettings, isNull); + expect(connector.eventTone(ToneEvent.dm), isNull); + }); + }); +} diff --git a/test/device_population_test.dart b/test/device_population_test.dart new file mode 100644 index 00000000..1767b6c1 --- /dev/null +++ b/test/device_population_test.dart @@ -0,0 +1,318 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/device_population.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Builds a device-info reply frame of [length] bytes with [verCode] at +/// byte 1, mirroring RESP_CODE_DEVICE_INFO layouts: +/// stock ships exactly 82 bytes; the Offband fork appends offband_caps at +/// offset 82 (83 bytes) and caps byte 2 at offset 84 (85 bytes). +Uint8List deviceInfoFrame({required int length, required int verCode}) { + final frame = Uint8List(length); + if (length > 0) frame[0] = 13; // RESP_CODE_DEVICE_INFO + if (length > 1) frame[1] = verCode; + return frame; +} + +void main() { + group('classifyDevicePopulation', () { + test('stock 1.17.x: 82-byte frame, ver 13', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 13), + firmwareVersion: 'v1.17.0', + ); + expect(c.population, DevicePopulation.stockLegacy); + expect(c.allowsOffbandFrames, isFalse); + expect(c.allowsCliFrame, isFalse); + }); + + test('stock 1.18.0: 82-byte frame, ver 14', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 14), + firmwareVersion: 'v1.18.0', + ); + expect(c.population, DevicePopulation.stockModern); + expect(c.allowsOffbandFrames, isFalse); + expect(c.allowsCliFrame, isTrue); + }); + + test('Offband ver 22: 83-byte frame (caps byte 1 only)', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 83, verCode: 22), + firmwareVersion: '1.4.0-1.17.0', + ); + expect(c.population, DevicePopulation.offband); + expect(c.allowsOffbandFrames, isTrue); + // No frame-66 CLI on the 1.17.0-base fork; flips only post-absorb. + expect(c.allowsCliFrame, isFalse); + }); + + test('Offband ver 22: 85-byte frame (caps byte 2 present)', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 85, verCode: 22), + firmwareVersion: '1.4.0-1.17.0', + ); + expect(c.population, DevicePopulation.offband); + expect(c.allowsOffbandFrames, isTrue); + }); + + test( + 'Offband release image X-X version string (#691) still classifies', + () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 85, verCode: 22), + firmwareVersion: '1.4.0-1.4.0', + ); + expect(c.population, DevicePopulation.offband); + }, + ); + + test('ver >= 14 with a LONG frame but stock version string is a conflict:' + ' fails closed to stockLegacy', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 83, verCode: 14), + firmwareVersion: 'v1.18.0', + ); + expect(c.population, DevicePopulation.stockLegacy); + expect(c.allowsOffbandFrames, isFalse); + expect(c.allowsCliFrame, isFalse); + expect(c.conflict, isTrue); + }); + + test('malformed short frame fails closed', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 3, verCode: 0), + firmwareVersion: null, + ); + expect(c.population, DevicePopulation.stockLegacy); + expect(c.allowsOffbandFrames, isFalse); + expect(c.allowsCliFrame, isFalse); + }); + + test('fork-shape frame with NO readable version fails closed' + ' (uncorroborated shape never unlocks fork frames)', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 83, verCode: 22), + firmwareVersion: null, + ); + expect(c.population, DevicePopulation.stockLegacy); + expect(c.conflict, isTrue); + expect(c.allowsOffbandFrames, isFalse); + }); + + test('fork-shape frame with an unrecognizable version fails closed', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 83, verCode: 22), + firmwareVersion: 'my-custom-build', + ); + // #878: 'my-custom-build' is no semver, so it corroborates nothing - + // the fork shape stays uncorroborated and the device fails closed. + expect(c.population, DevicePopulation.stockLegacy); + expect(c.conflict, isTrue); + }); + + group('classifyVersionString (#878)', () { + test('stock forms', () { + expect(classifyVersionString('v1.18.0'), VersionStringShape.stock); + expect(classifyVersionString('1.18.0'), VersionStringShape.stock); + expect(classifyVersionString(' v1.17.1 '), VersionStringShape.stock); + }); + test('Offband dual forms', () { + expect( + classifyVersionString('1.4.0-1.17.0'), + VersionStringShape.offbandDual, + ); + expect( + classifyVersionString('1.4.0-1.4.0'), // release image X-X (#691) + VersionStringShape.offbandDual, + ); + expect( + classifyVersionString('1.1.0-4-g9f2e1c3-dirty'), // bench build + VersionStringShape.offbandDual, + ); + }); + test('unknown forms', () { + expect(classifyVersionString(null), VersionStringShape.unknown); + expect(classifyVersionString(''), VersionStringShape.unknown); + expect( + classifyVersionString('my-custom-build'), + VersionStringShape.unknown, + ); + expect(classifyVersionString('v1.18'), VersionStringShape.unknown); + // A stock pre-release / git-suffixed string reads as dual at the parser + // level; that is harmless now, because a stock-shape frame is classified + // by ver code regardless of the version string (#946). + expect( + classifyVersionString('v1.19.0-rc1'), + VersionStringShape.offbandDual, + ); + expect(classifyVersionString('-1.17.0'), VersionStringShape.unknown); + }); + }); + + test('real stock 1.18.0 with a git-suffixed version classifies' + ' stockModern (#946, hardware)', () { + // The field device reports "v1.18.0-81dbae5" (semver + git-describe + // hash), which classifyVersionString reads as the dual form. An 82-byte + // frame is definitively stock (Offband always appends caps bytes), so the + // version string must not override the shape: the console must be offered. + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 14), + firmwareVersion: 'v1.18.0-81dbae5', + ); + expect(c.population, DevicePopulation.stockModern); + expect(c.allowsCliFrame, isTrue); + expect(c.conflict, isFalse); + }); + + test('stock-shape frame with a dual-looking version is still stockModern:' + ' the 82-byte shape is definitive (#946)', () { + // Previously an inverse conflict (fail closed); the shape is definitive, + // so a stock-shape frame is never forced to a conflict by its version. + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 14), + firmwareVersion: '1.4.0-1.17.0', + ); + expect(c.population, DevicePopulation.stockModern); + expect(c.conflict, isFalse); + expect(c.allowsCliFrame, isTrue); + }); + + test('length 84 with a dual version string classifies offband', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 84, verCode: 22), + firmwareVersion: '1.4.0-1.17.0', + ); + expect(c.population, DevicePopulation.offband); + }); + + test('ver at maxKnownVerCode with stock shape and stock string stays' + ' stockModern; one above fails closed', () { + final at = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 32), + firmwareVersion: 'v9.9.9', + ); + expect(at.population, DevicePopulation.stockModern); + final above = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 33), + firmwareVersion: 'v9.9.9', + ); + expect(above.population, DevicePopulation.stockLegacy); + }); + + test('stock ver wildly out of range fails closed', () { + final c = classifyDevicePopulation( + deviceInfo: deviceInfoFrame(length: 82, verCode: 255), + firmwareVersion: 'v9.9.9', + ); + expect(c.population, DevicePopulation.stockLegacy); + }); + }); + + group('connector routes caps parsing through the classifier (#876)', () { + late OffbandDatabase db; + late MeshCoreConnector connector; + + /// Full RESP_CODE_DEVICE_INFO frame with the version string at its real + /// offset (60, 20 bytes NUL-padded) and optional fork tail bytes. + Uint8List deviceInfo({ + required int verCode, + required String version, + int length = 82, + int caps = 0x21, + int caps2 = 0x0F, + }) { + final frame = Uint8List(length); + frame[0] = 13; // RESP_CODE_DEVICE_INFO + frame[1] = verCode; + final v = ascii.encode(version); + frame.setRange(60, 60 + v.length, v); + if (length > 82) frame[82] = caps; + if (length > 84) frame[84] = caps2; + return frame; + } + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (_) {}; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test('Offband frame with dual version populates caps', () { + connector.handleFrameForTest( + deviceInfo(verCode: 22, version: '1.4.0-1.17.0', length: 85), + ); + expect(connector.classification?.population, DevicePopulation.offband); + expect(connector.offbandCaps, 0x21); + expect(connector.offbandCaps2, 0x0F); + // femLna byte at offset 83 defaults to 0 in the fixture = bypass. + expect(connector.femLnaEnabled, isFalse); + }); + + test('83-byte Offband frame: caps byte 1 present, byte 2 and FEM state' + ' absent', () { + connector.handleFrameForTest( + deviceInfo(verCode: 22, version: '1.4.0-1.17.0', length: 83), + ); + expect(connector.classification?.population, DevicePopulation.offband); + expect(connector.offbandCaps, 0x21); + expect(connector.offbandCaps2, isNull); + expect(connector.femLnaEnabled, isNull); + }); + + test('fork-length frame with a stock version string leaves every Offband' + ' field null', () { + connector.handleFrameForTest( + deviceInfo(verCode: 14, version: 'v1.18.0', length: 85), + ); + expect( + connector.classification?.population, + DevicePopulation.stockLegacy, + ); + expect(connector.classification?.conflict, isTrue); + expect(connector.offbandCaps, isNull); + expect(connector.offbandCaps2, isNull); + }); + + test('stock 1.18 frame classifies stockModern with null caps', () { + connector.handleFrameForTest(deviceInfo(verCode: 14, version: 'v1.18.0')); + expect( + connector.classification?.population, + DevicePopulation.stockModern, + ); + expect(connector.offbandCaps, isNull); + }); + + test('fork gates never open on a stock device, whatever its ver code' + ' (#877): stock reuses the fork range 14+ with other meanings', () { + // A hypothetical future stock device reporting ver 22 (the fork's + // current contract number) must not light any Offband capability. + connector.handleFrameForTest(deviceInfo(verCode: 22, version: 'v9.9.9')); + expect(connector.supportsOffbandGps, isFalse); + expect(connector.supportsOffbandBlock, isFalse); + expect(connector.supportsOffbandFemLna, isFalse); + expect(connector.supportsButtonMatrix, isFalse); + expect(connector.supportsNotifyScope, isFalse); + expect(connector.supportsPktHash, isFalse); + // Pre-split floors (same meaning on every population) stay available. + expect(connector.supportsCompanionRadioStats, isTrue); + }); + }); +} diff --git a/test/helpers/device_name_validator_test.dart b/test/helpers/device_name_validator_test.dart new file mode 100644 index 00000000..3bedffaf --- /dev/null +++ b/test/helpers/device_name_validator_test.dart @@ -0,0 +1,46 @@ +// #885: mirrors the firmware's `set name` character rejection. Pins exactly +// which characters are forbidden and that detection is order-stable. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/device_name_validator.dart'; + +void main() { + group('device name validator (#885)', () { + test('a clean name is valid', () { + expect(isValidDeviceName('MyNode-1'), isTrue); + expect(isValidDeviceName('base camp 2'), isTrue); + expect(forbiddenCharsIn('MyNode-1'), isEmpty); + }); + + test('an empty name carries no forbidden characters', () { + expect(isValidDeviceName(''), isTrue); + }); + + test('the forbidden set is exactly these seven characters', () { + expect(forbiddenDeviceNameChars, ['[', ']', '\\', ':', ',', '?', '*']); + }); + + test('each forbidden character is caught on its own', () { + for (final c in forbiddenDeviceNameChars) { + expect(isValidDeviceName('ab${c}cd'), isFalse, reason: c); + expect(forbiddenCharsIn('ab${c}cd'), [c], reason: c); + } + }); + + test( + 'a name with no forbidden characters passes, common punctuation ok', + () { + expect(isValidDeviceName('Node_42.a-b (home)!'), isTrue); + }, + ); + + test('reports the distinct forbidden characters in canonical order', () { + // Input order ? , [ ; canonical order is [ , ? . + expect(forbiddenCharsIn('a?b,c[d'), ['[', ',', '?']); + }); + + test('a repeated forbidden char is reported once', () { + expect(forbiddenCharsIn('a,,,b'), [',']); + }); + }); +} diff --git a/test/helpers/path_helper_test.dart b/test/helpers/path_helper_test.dart index 1329ef4f..8a3b291c 100644 --- a/test/helpers/path_helper_test.dart +++ b/test/helpers/path_helper_test.dart @@ -16,7 +16,7 @@ Contact _contact({ } return Contact( publicKey: key, - name: name, + receivedName: name, type: type, pathLength: 0, path: Uint8List(0), diff --git a/test/helpers/region_key_test.dart b/test/helpers/region_key_test.dart new file mode 100644 index 00000000..34d5f4ef --- /dev/null +++ b/test/helpers/region_key_test.dart @@ -0,0 +1,69 @@ +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/helpers/region_key.dart'; + +// Known-answer vectors computed with an independent implementation +// (Python hashlib). The firmware derives a region's transport key as the +// first 16 bytes of SHA256 of the hashtag name WITH exactly one leading '#' +// (firmware: RegionMap.getTransportKeysFor -> TransportKeyStore.getAutoKeyFor, +// which hashes the stored name; bare names get '#' prepended). Discovered +// region names arrive '#'-stripped, so the client re-adds the '#'. +String _hex(Uint8List b) => + b.map((x) => x.toRadixString(16).padLeft(2, '0')).join(); + +void main() { + group('transportKeyForName', () { + test('first 16 bytes of SHA256("#"+name) for a bare name', () { + expect( + _hex(transportKeyForName('oki')!), + '599fe2546002709fa493b15de58bdd0d', + ); + expect( + _hex(transportKeyForName('test')!), + '9cd8fcf22a47333b591d96a2b848b73f', + ); + }); + + test('idempotent on a leading # (auto-hashtag names hash as-is)', () { + expect( + _hex(transportKeyForName('#oki')!), + _hex(transportKeyForName('oki')!), + ); + }); + + test('key is 16 bytes', () { + expect(transportKeyForName('oki')!.length, 16); + }); + + test('private (\$-prefixed) regions are not name-derivable', () { + expect(isPrivateRegionName(r'$secret'), isTrue); + expect(transportKeyForName(r'$secret'), isNull); + }); + + test('empty or blank name yields no key', () { + expect(transportKeyForName(''), isNull); + expect(transportKeyForName(' '), isNull); + }); + }); + + group('onAirCode', () { + test('matches the firmware HMAC transport code (little-endian uint16)', () { + final key = transportKeyForName('oki')!; + final code = onAirCode( + key, + 0x00, + Uint8List.fromList([0xde, 0xad, 0xbe, 0xef]), + ); + expect(code, 0x959d); + }); + + test('reserves codes 0x0000 and 0xFFFF', () { + // Both reserved values are bumped by one, matching + // TransportKey::calcTransportCode in firmware. + expect(reserveTransportCode(0x0000), 0x0001); + expect(reserveTransportCode(0xFFFF), 0xFFFE); + expect(reserveTransportCode(0x1234), 0x1234); + }); + }); +} diff --git a/test/l10n/contact_localization_test.dart b/test/l10n/contact_localization_test.dart index 62f8b6c8..b00bc35e 100644 --- a/test/l10n/contact_localization_test.dart +++ b/test/l10n/contact_localization_test.dart @@ -14,7 +14,7 @@ Contact _contact({ }) { return Contact( publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), - name: 'Node', + receivedName: 'Node', type: type, pathLength: pathLength, path: Uint8List(0), diff --git a/test/models/contact_is_companion_test.dart b/test/models/contact_is_companion_test.dart new file mode 100644 index 00000000..04dbfa8c --- /dev/null +++ b/test/models/contact_is_companion_test.dart @@ -0,0 +1,31 @@ +// #999: remote CLI is a companion-only feature, and the chat-screen entry point +// gates on Contact.isCompanion. These pin that only a chat node reads as a +// companion - a repeater, room server or sensor must not, or the CLI-console +// action would appear where it does not belong. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; + +Contact _of(int type) => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i)), + receivedName: 'X', + type: type, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +void main() { + test('a chat node is a companion', () { + expect(_of(advTypeChat).isCompanion, isTrue); + }); + + test('a repeater, room server or sensor is not a companion', () { + expect(_of(advTypeRepeater).isCompanion, isFalse); + expect(_of(advTypeRoom).isCompanion, isFalse); + expect(_of(advTypeSensor).isCompanion, isFalse); + }); +} diff --git a/test/models/contact_naming_test.dart b/test/models/contact_naming_test.dart new file mode 100644 index 00000000..00ea63fa --- /dev/null +++ b/test/models/contact_naming_test.dart @@ -0,0 +1,101 @@ +// Custom Name override for contacts (#750), model half. +// +// `Contact.name` becomes a getter returning `customName ?? receivedName`, so +// the 85 existing display reads stay correct and untouched while every write +// site is forced to say which name it means. +// +// Tests T1 to T8 and T31 from the plan of record, +// docs/initiatives/standalone/750-contact-naming/PLAN.md. +// +// The negatives here are the ones that matter. A positive-only suite would keep +// passing while an advert quietly took the user's chosen name back. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; + +Contact _contact({required String receivedName, String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x11)), + receivedName: receivedName, + customName: customName, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + group('Contact.name resolution (#750)', () { + test('T1 + returns the custom name when one is set', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: 'Chuck'); + + expect(c.name, 'Chuck'); + }); + + test('T2 - falls back to the received name, and does not invent one', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater'); + + expect(c.name, 'KQ4EZN-Repeater'); + expect(c.customName, isNull); + }); + + test('T3 - an empty custom name counts as unset, not as a blank name', () { + // Otherwise a user who clears the field by deleting its text gets a blank + // display name with no way back. + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: ''); + + expect(c.name, 'KQ4EZN-Repeater'); + }); + + test('T4 - a whitespace-only custom name counts as unset', () { + final c = _contact(receivedName: 'KQ4EZN-Repeater', customName: ' '); + + expect(c.name, 'KQ4EZN-Repeater'); + }); + + test( + 'T5 + copyWith(receivedName:) updates it and keeps the custom name', + () { + final c = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name'); + + expect(c.receivedName, 'new-advert-name'); + expect(c.customName, 'Chuck'); + }, + ); + + test('T6 - copyWith(receivedName:) does not change the displayed name', () { + // This is the whole point of the epic: an advert updates what the node + // calls itself and never disturbs what the user calls it. + final c = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name'); + + expect(c.name, 'Chuck'); + }); + + test('T6b + clearing the custom name reveals the newest received name', () { + final renamed = _contact( + receivedName: 'old-advert-name', + customName: 'Chuck', + ).copyWith(receivedName: 'new-advert-name', clearCustomName: true); + + expect(renamed.customName, isNull); + expect(renamed.name, 'new-advert-name'); + }); + + test('T28 - a custom name keeps CJK, emoji and ZWJ sequences intact', () { + // A custom name never crosses the wire, so #636's grapheme truncation + // must not be applied to it. + const rich = 'ๆต‹่ฏ• ๐Ÿง™โ€โ™‚๏ธ Chuck'; + final c = _contact(receivedName: 'plain', customName: rich); + + expect(c.name, rich); + expect(c.customName, rich); + }); + }); +} diff --git a/test/models/contact_share_uri_test.dart b/test/models/contact_share_uri_test.dart index 8ed02f8c..c4e88f8d 100644 --- a/test/models/contact_share_uri_test.dart +++ b/test/models/contact_share_uri_test.dart @@ -165,7 +165,7 @@ void main() { group('Contact share URI emit (#626)', () { Contact stub(String name, int type) => Contact( publicKey: hex2Uint8List(_key), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), @@ -232,7 +232,7 @@ void main() { group('Compact channel contact share (#611)', () { Contact stub(String name, int type) => Contact( publicKey: hex2Uint8List(_key), - name: name, + receivedName: name, type: type, pathLength: -1, path: Uint8List(0), diff --git a/test/models/path_selection_test.dart b/test/models/path_selection_test.dart index b3ffbbc3..b4de0d48 100644 --- a/test/models/path_selection_test.dart +++ b/test/models/path_selection_test.dart @@ -14,7 +14,7 @@ Contact _contact({ }) { return Contact( publicKey: Uint8List(32), - name: 'R', + receivedName: 'R', type: advTypeRepeater, pathLength: pathLength, pathHashWidth: pathHashWidth, diff --git a/test/models/region_test.dart b/test/models/region_test.dart new file mode 100644 index 00000000..54614b87 --- /dev/null +++ b/test/models/region_test.dart @@ -0,0 +1,26 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/region.dart'; + +void main() { + test('value equality by name (lets discovery dedupe replies)', () { + expect(const Region('oki'), const Region('oki')); + expect(const Region('oki').hashCode, const Region('oki').hashCode); + expect(const Region('oki') == const Region('ked'), isFalse); + final duplicates = [const Region('oki'), const Region('oki')]; + expect(duplicates.toSet().length, 1); + }); + + test('derives its 16-byte transport key', () { + final key = const Region('oki').transportKey; + expect(key, isNotNull); + expect(key!.length, 16); + }); + + test('flags wildcard and private regions', () { + expect(const Region('*').isWildcard, isTrue); + expect(const Region(r'$secret').isPrivate, isTrue); + expect(const Region('oki').isWildcard, isFalse); + expect(const Region('oki').isPrivate, isFalse); + expect(const Region(r'$secret').transportKey, isNull); + }); +} diff --git a/test/population_conformance_test.dart b/test/population_conformance_test.dart new file mode 100644 index 00000000..b62ad493 --- /dev/null +++ b/test/population_conformance_test.dart @@ -0,0 +1,220 @@ +// E1.2 (#880): the conformance matrix -every capability gate against every +// population fixture (plan E1.2; INVESTIGATION.md ยงB3). This is the epic's +// verification: it proves the F1 pieces cohere, it is not a re-run of the +// unit tests. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/device_population.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/observer_config_client.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Uint8List frameOf({ + required int length, + required int verCode, + String? version, + int caps = 0, + int caps2 = 0, +}) { + final f = Uint8List(length); + if (length > 0) f[0] = 13; + if (length > 1) f[1] = verCode; + if (version != null && length >= 80) { + final v = ascii.encode(version); + f.setRange(60, 60 + v.length, v); + } + if (length > 82) f[82] = caps; + if (length > 84) f[84] = caps2; + return f; +} + +/// One population fixture: the frame a device of that population sends, and +/// the capability doors that must (not) open. +class Fixture { + const Fixture( + this.name, + this.frame, { + required this.population, + required this.offbandGps, + required this.offbandBlock, + required this.femLna, + required this.buttonMatrix, + required this.notifyScope, + required this.pktHash, + required this.observerConfig, + required this.companionStats, + }); + + final String name; + final Uint8List frame; + final DevicePopulation population; + final bool offbandGps; + final bool offbandBlock; + final bool femLna; + final bool buttonMatrix; + final bool notifyScope; + final bool pktHash; + final bool observerConfig; + final bool companionStats; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (_) {}; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + final fixtures = [ + Fixture( + 'stock 1.17.x (82B, ver 13)', + frameOf(length: 82, verCode: 13, version: 'v1.17.1'), + population: DevicePopulation.stockLegacy, + offbandGps: false, + offbandBlock: false, + femLna: false, + buttonMatrix: false, + notifyScope: false, + pktHash: false, + observerConfig: false, + companionStats: true, + ), + Fixture( + 'stock 1.18.0 (82B, ver 14)', + frameOf(length: 82, verCode: 14, version: 'v1.18.0'), + population: DevicePopulation.stockModern, + offbandGps: false, + offbandBlock: false, + femLna: false, + buttonMatrix: false, + notifyScope: false, + pktHash: false, + observerConfig: false, + companionStats: true, + ), + Fixture( + 'Offband observer, all caps lit (85B, ver 22)', + frameOf( + length: 85, + verCode: 22, + version: '1.4.0-1.17.0', + caps: 0x27, // observer 0x01 | block 0x02 | fem 0x04 | caplog 0x20 + caps2: 0x0F, + ), + population: DevicePopulation.offband, + offbandGps: true, + offbandBlock: true, + femLna: true, + buttonMatrix: true, + notifyScope: true, + pktHash: true, + observerConfig: true, + companionStats: true, + ), + Fixture( + 'Offband companion, no cap bits set (83B, ver 22)', + frameOf(length: 83, verCode: 22, version: '1.4.0-1.17.0'), + population: DevicePopulation.offband, + offbandGps: true, // presence-gate: caps byte exists + offbandBlock: false, + femLna: false, + buttonMatrix: false, + notifyScope: false, + pktHash: false, + observerConfig: false, + companionStats: true, + ), + Fixture( + 'conflict: fork shape, stock string (85B, ver 14)', + frameOf( + length: 85, + verCode: 14, + version: 'v1.18.0', + caps: 0xFF, + caps2: 0xFF, + ), + population: DevicePopulation.stockLegacy, + offbandGps: false, + offbandBlock: false, + femLna: false, + buttonMatrix: false, + notifyScope: false, + pktHash: false, + observerConfig: false, + companionStats: true, + ), + Fixture( + 'malformed (3B)', + frameOf(length: 3, verCode: 0), + population: DevicePopulation.stockLegacy, + offbandGps: false, + offbandBlock: false, + femLna: false, + buttonMatrix: false, + notifyScope: false, + pktHash: false, + observerConfig: false, + companionStats: false, // ver code never parsed from a 3-byte frame + ), + ]; + + for (final f in fixtures) { + test('matrix: ${f.name}', () { + connector.handleFrameForTest(f.frame); + if (f.frame.length >= 4) { + expect( + connector.classification?.population, + f.population, + reason: 'population', + ); + } + expect(connector.supportsOffbandGps, f.offbandGps, reason: 'gps 0xC1'); + expect(connector.supportsOffbandBlock, f.offbandBlock, reason: 'block'); + expect(connector.supportsOffbandFemLna, f.femLna, reason: 'fem 0xC3'); + expect( + connector.supportsButtonMatrix, + f.buttonMatrix, + reason: 'button matrix 0xC5', + ); + expect( + connector.supportsNotifyScope, + f.notifyScope, + reason: 'notify scope 0xC5', + ); + expect(connector.supportsPktHash, f.pktHash, reason: 'pkt hash 0xC6'); + expect( + ObserverConfigClient.supportsConfig( + firmwareVerCode: connector.firmwareVerCode ?? 0, + offbandCaps: connector.offbandCaps ?? 0, + ), + f.observerConfig, + reason: '0xC0 config', + ); + expect( + connector.supportsCompanionRadioStats, + f.companionStats, + reason: 'pre-split stats >=8', + ); + }); + } +} diff --git a/test/screens/blocked_view_test.dart b/test/screens/blocked_view_test.dart new file mode 100644 index 00000000..0f535319 --- /dev/null +++ b/test/screens/blocked_view_test.dart @@ -0,0 +1,149 @@ +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/settings/blocked_view.dart'; +import 'package:meshcore_open/services/block_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #938 (#507): the Blocked pane is per radio, and says so. +/// +/// The gap this closes: with no radio connected the pane rendered "No blocked +/// users", which is indistinguishable from a connected radio with an empty +/// list. Since #471 made blocks per radio, that wording invited the reader to +/// conclude their blocks had been lost. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + Widget harness(BlockService block) => MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: block), + ChangeNotifierProvider( + create: (_) => MeshCoreConnector(), + ), + ], + child: const MaterialApp( + localizationsDelegates: [ + AppLocalizations.delegate, + GlobalMaterialLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ], + home: Scaffold(body: BlockedView()), + ), + ); + + group('the two empty states read differently', () { + testWidgets('no radio connected says so, and explains why', (t) async { + final block = BlockService(); + await block.loadForDevice(null); + + await t.pumpWidget(harness(block)); + await t.pumpAndSettle(); + + expect(find.text('No radio connected'), findsOneWidget); + expect( + find.textContaining('Blocks belong to the radio that holds them'), + findsOneWidget, + reason: 'the reason matters: without it the pane looks like data loss', + ); + expect( + find.text('No blocked users'), + findsNothing, + reason: 'this was the bug: both states said the same thing', + ); + }); + + testWidgets('a connected radio with nothing blocked says THAT', (t) async { + final block = BlockService(); + await block.loadForDevice('aa' * 16); + + await t.pumpWidget(harness(block)); + await t.pumpAndSettle(); + + expect(find.text('No blocked users'), findsOneWidget); + expect(find.text('No radio connected'), findsNothing); + }); + }); + + group('per-radio isolation through the pane', () { + testWidgets('a block made on radio A is absent on radio B', (t) async { + final block = BlockService(); + await block.loadForDevice('aa' * 16); + await block.block('deadbeef'); + + await t.pumpWidget(harness(block)); + await t.pumpAndSettle(); + expect(find.textContaining('deadbeef'), findsOneWidget); + + // Switch radios, as the connector does on SELF_INFO. + await block.loadForDevice('bb' * 16); + await t.pumpAndSettle(); + + expect( + find.textContaining('deadbeef'), + findsNothing, + reason: 'radio A\'s block must not appear while radio B is connected', + ); + expect(find.text('No blocked users'), findsOneWidget); + }); + + testWidgets('switching back restores radio A\'s list', (t) async { + final block = BlockService(); + await block.loadForDevice('aa' * 16); + await block.block('deadbeef'); + await block.loadForDevice('bb' * 16); + await block.loadForDevice('aa' * 16); + + await t.pumpWidget(harness(block)); + await t.pumpAndSettle(); + + expect( + find.textContaining('deadbeef'), + findsOneWidget, + reason: 'isolation is not deletion: A keeps its own list', + ); + }); + }); + + group('unblock sticks', () { + testWidgets('an unblock survives a radio switch and back', (t) async { + final block = BlockService(); + await block.loadForDevice('aa' * 16); + await block.block('deadbeef'); + await block.unblock('deadbeef'); + + await block.loadForDevice('bb' * 16); + await block.loadForDevice('aa' * 16); + + await t.pumpWidget(harness(block)); + await t.pumpAndSettle(); + + expect( + find.textContaining('deadbeef'), + findsNothing, + reason: + 'the clear-sticks case from #507: the re-clear that kept ' + 'recurring was #471, and it must not come back', + ); + }); + }); +} diff --git a/test/screens/device_cli_screen_test.dart b/test/screens/device_cli_screen_test.dart new file mode 100644 index 00000000..a138c9b8 --- /dev/null +++ b/test/screens/device_cli_screen_test.dart @@ -0,0 +1,401 @@ +// Widget tests for the Device CLI console (#883, F2/E2.1). +// +// Pins the behaviors the owner-approved screen must hold: a correlated reply +// renders with a latency chip; a secret reply is MASKED (its cleartext never +// enters the widget tree); an error string gets the warning treatment; a reply +// at the device bound shows the truncation badge; a command with no answer +// renders a timeout row; and a blank command does nothing. Negative cases sit +// beside the positive ones so a regression in either direction fails CI. + +import 'dart:convert'; + +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/cli_command_codec.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/device_cli_screen.dart'; +import 'package:meshcore_open/services/cli_console_transport.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Always times out, so the console's timeout row can be tested without +/// driving a real mesh window (#891). +class _TimeoutTransport implements CliConsoleTransport { + @override + Future run(String command, {Duration? timeout}) async { + throw CliConsoleTimeout(command: command, secondsText: '28.7'); + } + + @override + void dispose() {} +} + +/// The connected radio refuses the send outright (pre-1.18 firmware). +class _UnsupportedTransport implements CliConsoleTransport { + @override + Future run(String command, {Duration? timeout}) async { + throw CliConsoleUnsupported(command: command); + } + + @override + void dispose() {} +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pumpScreen(WidgetTester tester, {Duration? timeout}) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DeviceCliScreen(commandTimeout: timeout), + ), + ), + ); + await tester.pumpAndSettle(); + } + + /// Builds the `[29][prefix][text]` reply the device would send for the most + /// recently captured request, mirroring its 3-char correlation reflection. + Uint8List replyFor(Uint8List request, String text) { + final prefix = ascii.decode(request.sublist(1, 4)); + return Uint8List.fromList([ + respCodeCliReply, + ...ascii.encode('$prefix$text'), + ]); + } + + Future send(WidgetTester tester, String command) async { + await tester.enterText(find.byType(TextField), command); + await tester.tap(find.byIcon(Icons.send)); + await tester.pump(); + } + + testWidgets('round trip: a correlated reply renders with a latency chip', ( + tester, + ) async { + await pumpScreen(tester); + await send(tester, 'get radio'); + expect(sent, hasLength(1)); + + connector.handleFrameForTest(replyFor(sent.single, '> 910.525,62.5,7,5')); + await tester.pumpAndSettle(); + + expect(find.text('> 910.525,62.5,7,5'), findsOneWidget); + expect(find.textContaining(RegExp(r'\d+ ms')), findsOneWidget); + }); + + testWidgets('a secret reply is masked: cleartext never enters the tree', ( + tester, + ) async { + await pumpScreen(tester); + await send(tester, 'get wifi.pwd'); + connector.handleFrameForTest(replyFor(sent.single, 'hunter2-secret')); + await tester.pumpAndSettle(); + + expect(find.text('hunter2-secret'), findsNothing); + expect(find.textContaining('long-press to copy'), findsOneWidget); + }); + + testWidgets('any command containing pwd is treated as secret', ( + tester, + ) async { + await pumpScreen(tester); + await send(tester, 'set wifi.pwd topsecret'); + connector.handleFrameForTest(replyFor(sent.single, 'topsecret')); + await tester.pumpAndSettle(); + + expect(find.text('topsecret'), findsNothing); + expect(find.textContaining('long-press to copy'), findsOneWidget); + }); + + testWidgets('an error-string reply gets the warning glyph', (tester) async { + await pumpScreen(tester); + await send(tester, 'badcmd'); + connector.handleFrameForTest(replyFor(sent.single, 'Unknown command')); + await tester.pumpAndSettle(); + + expect(find.text('Unknown command'), findsOneWidget); + expect(find.byIcon(Icons.warning_amber), findsOneWidget); + }); + + testWidgets('a non-error reply gets no warning glyph', (tester) async { + await pumpScreen(tester); + await send(tester, 'get radio'); + connector.handleFrameForTest(replyFor(sent.single, '> ok')); + await tester.pumpAndSettle(); + + expect(find.text('> ok'), findsOneWidget); + expect(find.byIcon(Icons.warning_amber), findsNothing); + }); + + testWidgets('a reply at the device bound shows the truncation badge', ( + tester, + ) async { + await pumpScreen(tester); + await send(tester, 'neighbors'); + // payloadLength (prefix + text) must reach maxCliReplyPayload (165). + final text = 'x' * (maxCliReplyPayload - 3); + connector.handleFrameForTest(replyFor(sent.single, text)); + await tester.pumpAndSettle(); + + expect(find.textContaining('truncated by the device'), findsOneWidget); + }); + + testWidgets('a short reply shows no truncation badge', (tester) async { + await pumpScreen(tester); + await send(tester, 'ver'); + connector.handleFrameForTest(replyFor(sent.single, 'v1.18.0')); + await tester.pumpAndSettle(); + + expect(find.textContaining('truncated by the device'), findsNothing); + }); + + testWidgets('a command with no answer renders a timeout row', (tester) async { + await pumpScreen(tester, timeout: const Duration(milliseconds: 120)); + await send(tester, 'get gps diag'); + // Let the window elapse without feeding a reply. + await tester.pump(const Duration(milliseconds: 200)); + await tester.pumpAndSettle(); + + expect(find.text('get gps diag: no reply in 0.1 s'), findsOneWidget); + expect(find.byIcon(Icons.timer_off_outlined), findsOneWidget); + // The local console never shows the remote permission hint (#891). + expect(find.textContaining('may not allow remote CLI'), findsNothing); + expect(find.textContaining('Not retried'), findsNothing); + }); + + testWidgets('a send failure renders the send-failed row', (tester) async { + connector.sendFrameOverrideForTest = (_) => throw StateError('tx down'); + await pumpScreen(tester); + await send(tester, 'get radio'); + await tester.pumpAndSettle(); + + expect(find.textContaining('Send failed'), findsOneWidget); + }); + + testWidgets('a secret reply can be copied via long-press', (tester) async { + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') copied.add(call); + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + + await pumpScreen(tester); + await send(tester, 'get wifi.pwd'); + connector.handleFrameForTest(replyFor(sent.single, 'topsecret')); + await tester.pumpAndSettle(); + + await tester.longPress(find.textContaining('long-press to copy')); + await tester.pumpAndSettle(); + + expect(copied, hasLength(1)); + expect(copied.single.arguments['text'], 'topsecret'); + }); + + testWidgets('set name with a forbidden char is rejected client-side, not ' + 'sent (#885)', (tester) async { + await pumpScreen(tester); + await tester.enterText(find.byType(TextField), 'set name My[Node]'); + await tester.tap(find.byIcon(Icons.send)); + await tester.pump(const Duration(milliseconds: 150)); // flush scroll timer + + expect(sent, isEmpty); // the frame never left the client + expect(find.text('set name My[Node]'), findsOneWidget); // echoed + expect(find.textContaining('Not sent'), findsOneWidget); // rejection row + expect(find.textContaining('['), findsWidgets); // names the offender + }); + + testWidgets('a rejected set name is still recallable from history (#885 ' + 'Gemini review)', (tester) async { + // History derives from the command entries in the transcript, and the + // rejection path adds the command entry, so up-arrow recalls it to fix. + await pumpScreen(tester); + await tester.enterText(find.byType(TextField), 'set name bad:name'); + await tester.tap(find.byIcon(Icons.send)); + await tester.pump(const Duration(milliseconds: 150)); + + await tester.tap(find.byIcon(Icons.arrow_upward)); + await tester.pumpAndSettle(); + final field = tester.widget(find.byType(TextField)); + expect(field.controller?.text, 'set name bad:name'); + }); + + testWidgets('a valid set name is sent normally (#885)', (tester) async { + await pumpScreen(tester); + await send(tester, 'set name MyNode'); + expect(sent, hasLength(1)); + connector.handleFrameForTest(replyFor(sent.single, '> ok')); + await tester.pumpAndSettle(); + expect(find.text('> ok'), findsOneWidget); + }); + + testWidgets('a blank command does nothing', (tester) async { + await pumpScreen(tester); + await tester.tap(find.byIcon(Icons.send)); + await tester.pump(); + + expect(sent, isEmpty); + // The empty-state hint is still the only thing on screen. + expect(find.byIcon(Icons.terminal), findsOneWidget); + }); + + testWidgets('history recall walks back through sent commands', ( + tester, + ) async { + await pumpScreen(tester); + await send(tester, 'get radio'); + connector.handleFrameForTest(replyFor(sent.single, '> ok')); + await tester.pumpAndSettle(); + + await tester.tap(find.byIcon(Icons.arrow_upward)); + await tester.pumpAndSettle(); + + final field = tester.widget(find.byType(TextField)); + expect(field.controller?.text, 'get radio'); + }); + + group('remote companion target (#999)', () { + Contact companion() => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + receivedName: 'Pocket Radio', + type: advTypeChat, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), + ); + + Future pumpRemote(WidgetTester tester, Contact target) async { + connector.contactsForTest.add(target); + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DeviceCliScreen(remoteContact: target), + ), + ), + ); + await tester.pumpAndSettle(); + } + + testWidgets('titles with the remote variant and the contact name', ( + tester, + ) async { + await pumpRemote(tester, companion()); + + // Remote mode titles "Remote CLI" with the contact as the subtitle, + // rather than the local "Device CLI" + self name/version. The send and + // reply correlation over the mesh are covered in + // cli_console_transport_test; the entry-point gating in + // contact_is_companion_test. + expect(find.text('Remote CLI'), findsOneWidget); + expect(find.text('Pocket Radio'), findsOneWidget); + expect(find.text('Device CLI'), findsNothing); + }); + + testWidgets('a remote timeout explains the silence and the no-retry (#891)', ( + tester, + ) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DeviceCliScreen( + remoteContact: companion(), + transportOverride: _TimeoutTransport(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await send(tester, 'get radio'); + await tester.pumpAndSettle(); + + // The remote row explains the silence, not the bare local "no reply" row, + // with the command and the armed window interpolated. + expect( + find.text( + 'get radio: no reply in 28.7 s. This radio may not allow remote CLI ' + 'from you, or is unreachable. Not retried.', + ), + findsOneWidget, + ); + }); + + testWidgets('a refused send says nothing went out, not a timeout (#999)', ( + tester, + ) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DeviceCliScreen( + remoteContact: companion(), + transportOverride: _UnsupportedTransport(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + await send(tester, 'get radio'); + await tester.pumpAndSettle(); + + expect( + find.text( + "get radio: not sent. Your radio's firmware doesn't support " + 'remote CLI.', + ), + findsOneWidget, + ); + // Not the #891 row, which would blame the target. + expect(find.textContaining('may not allow remote CLI'), findsNothing); + }); + }); +} diff --git a/test/screens/discover_regions_screen_test.dart b/test/screens/discover_regions_screen_test.dart new file mode 100644 index 00000000..e6031ef8 --- /dev/null +++ b/test/screens/discover_regions_screen_test.dart @@ -0,0 +1,65 @@ +// Epic #814 T B2: Discover Regions screen state rendering. +// Injects a fake discoverer service so each state renders without a radio. + +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/discover_regions_screen.dart'; +import 'package:meshcore_open/services/region_discovery_service.dart'; + +Contact _repeater() => Contact( + publicKey: Uint8List(32), + receivedName: 'rpt-01', + type: advTypeRepeater, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime(2026), +); + +Future _pump(WidgetTester tester, RegionDiscoveryService svc) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: DiscoverRegionsScreen(repeater: _repeater(), service: svc), + ), + ); + await tester.pumpAndSettle(); +} + +void main() { + RegionsReply reply(List names) => + RegionsReply(tag: 1, clock: 1, regionNames: names); + + testWidgets('success lists region names', (tester) async { + await _pump( + tester, + RegionDiscoveryService((_, _) async => reply(['oki', 'test'])), + ); + expect(find.text('oki'), findsOneWidget); + expect(find.text('test'), findsOneWidget); + }); + + testWidgets('empty reply shows the empty state', (tester) async { + await _pump(tester, RegionDiscoveryService((_, _) async => reply([]))); + expect(find.byKey(const Key('discoverRegionsEmpty')), findsOneWidget); + }); + + testWidgets('timeout shows the timeout state with a retry', (tester) async { + await _pump(tester, RegionDiscoveryService((_, _) async => null)); + expect(find.byKey(const Key('discoverRegionsTimeout')), findsOneWidget); + expect(find.byKey(const Key('discoverRegionsRetry')), findsOneWidget); + }); + + testWidgets('a thrown error shows the error state', (tester) async { + await _pump( + tester, + RegionDiscoveryService((_, _) async => throw StateError('boom')), + ); + expect(find.byKey(const Key('discoverRegionsError')), findsOneWidget); + }); +} diff --git a/test/screens/remote_console_gate_test.dart b/test/screens/remote_console_gate_test.dart new file mode 100644 index 00000000..5c6ba539 --- /dev/null +++ b/test/screens/remote_console_gate_test.dart @@ -0,0 +1,75 @@ +// #999 reopen: the companion "CLI console" entry is offered only when BOTH the +// target is a companion AND the connected radio speaks the 1.18 CLI. A +// pre-1.18 radio (stock 1.17, or Offband before the absorb) refuses a type-3 +// send, so offering the console there only produces failures. + +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/device_population.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/screens/device_cli_screen.dart'; + +Contact _contact(int type) => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i)), + receivedName: 'X', + type: type, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +Classification _radio(DevicePopulation population) => + Classification(population: population, conflict: false, evidence: 'test'); + +void main() { + test('a companion on a 1.18 radio is offered the console', () { + expect( + DeviceCliScreen.offersRemoteConsole( + contact: _contact(advTypeChat), + classification: _radio(DevicePopulation.stockModern), + ), + isTrue, + ); + }); + + test('no console when the connected radio is pre-1.18 or Offband', () { + for (final population in [ + DevicePopulation.stockLegacy, + DevicePopulation.offband, + ]) { + expect( + DeviceCliScreen.offersRemoteConsole( + contact: _contact(advTypeChat), + classification: _radio(population), + ), + isFalse, + reason: '$population cannot send a type-3 command', + ); + } + }); + + test('no console when the radio is not classified (disconnected)', () { + expect( + DeviceCliScreen.offersRemoteConsole( + contact: _contact(advTypeChat), + classification: null, + ), + isFalse, + ); + }); + + test('no console for a repeater or room server, even on a 1.18 radio', () { + for (final type in [advTypeRepeater, advTypeRoom, advTypeSensor]) { + expect( + DeviceCliScreen.offersRemoteConsole( + contact: _contact(type), + classification: _radio(DevicePopulation.stockModern), + ), + isFalse, + reason: 'type $type has its own CLI via the repeater hub', + ); + } + }); +} diff --git a/test/screens/settings_declutter_test.dart b/test/screens/settings_declutter_test.dart new file mode 100644 index 00000000..fad53b64 --- /dev/null +++ b/test/screens/settings_declutter_test.dart @@ -0,0 +1,123 @@ +// Pins the #902 Settings declutter: config import/export, the GPX exports, and +// "Sync queued messages now" live under the Actions pane (they are user +// operations); the Debug pane keeps only diagnostics, with App Debug Logging +// ahead of Companion Debug. Positive (present under Actions) and negative +// (absent from Debug) assertions sit together so a row drifting back to the +// wrong pane fails CI. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:drift/native.dart'; + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (_) {}; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pumpSettings(WidgetTester tester) async { + // Narrow layout: the category list renders and each detail pane builds + // lazily when its tile is tapped (so unrelated panes never construct). + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future openPane(WidgetTester tester, String categoryTitle) async { + // The category list is built lazily, so a category below the fold does not + // exist until scrolled to. #977 added Location, which pushed Debug past it. + await tester.scrollUntilVisible(find.text(categoryTitle), 200); + await tester.tap(find.text(categoryTitle)); + await tester.pumpAndSettle(); + } + + testWidgets('Actions holds the moved user-operations', (tester) async { + await pumpSettings(tester); + await openPane(tester, 'Actions'); + + // Sync queued messages now (moved from Debug). + expect(find.byIcon(Icons.sync_problem_outlined), findsOneWidget); + // Config export + import (moved from Debug). + expect(find.byIcon(Icons.save_alt), findsOneWidget); + expect(find.byIcon(Icons.upload_file), findsOneWidget); + // The three GPX exports (moved from Debug). + expect(find.byIcon(Icons.download_outlined), findsNWidgets(3)); + // The pre-existing Actions still here. + expect(find.byIcon(Icons.restart_alt), findsOneWidget); // reboot + }); + + testWidgets('Debug keeps only diagnostics, correctly ordered', ( + tester, + ) async { + await pumpSettings(tester); + await openPane(tester, 'Debug'); + + // The moved user-operations are gone from Debug. save_alt + upload_file + // are unique to the export card, so their absence proves the whole card + // (config export/import AND the GPX rows) left the pane. + expect(find.byIcon(Icons.sync_problem_outlined), findsNothing); + expect(find.byIcon(Icons.save_alt), findsNothing); + expect(find.byIcon(Icons.upload_file), findsNothing); + + // Serial capture stays (its leading icon is also download_outlined, which + // is why the GPX absence above is asserted via save_alt, not that icon). + expect(find.text('Serial capture'), findsOneWidget); + // Mesh topology stays (useful diagnosing with a user). + expect(find.byIcon(Icons.hub_outlined), findsOneWidget); + + // Full ordering per the owner's spec: App Debug Logging, then Companion + // Debug, then App Debug (view log). Pinning all three guards against any + // row drifting within the pane, not just the first pair. + final loggingDy = tester + .getTopLeft(find.byIcon(Icons.bug_report_outlined)) + .dy; // App Debug Logging toggle + final companionDy = tester + .getTopLeft(find.byIcon(Icons.bluetooth_outlined)) + .dy; // Companion Debug + final appDebugDy = tester + .getTopLeft(find.byIcon(Icons.code_outlined)) + .dy; // App Debug (view log) + expect(loggingDy, lessThan(companionDy)); + expect(companionDy, lessThan(appDebugDy)); + }); +} diff --git a/test/screens/settings_device_cli_entry_test.dart b/test/screens/settings_device_cli_entry_test.dart new file mode 100644 index 00000000..8d18df59 --- /dev/null +++ b/test/screens/settings_device_cli_entry_test.dart @@ -0,0 +1,145 @@ +// Pins the #884 Device CLI entry gate: a "Device CLI" row appears at the TOP of +// the Debug pane only when the classifier places the connected radio at stock +// v14+ (allowsCliFrame). It is absent when disconnected, on a stock-legacy +// radio, and on an Offband device (which gains the frame-66 CLI only at the +// upstream-1.18 absorb). Tapping it opens the console. + +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/device_cli_screen.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// A RESP_CODE_DEVICE_INFO frame with the version string at its real offset. +Uint8List deviceInfo({ + required int length, + required int verCode, + required String version, +}) { + final v = ascii.encode(version); + assert( + 60 + v.length <= length, + 'version string does not fit in a $length-byte frame', + ); + final f = Uint8List(length); + f[0] = 13; // RESP_CODE_DEVICE_INFO + f[1] = verCode; + f.setRange(60, 60 + v.length, v); + return f; +} + +void main() { + late OffbandDatabase db; + late MeshCoreConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + connector.sendFrameOverrideForTest = (_) {}; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pumpAndOpenDebug(WidgetTester tester) async { + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + // The category list is built lazily, so a category below the fold does not + // exist until scrolled to. #977 added Location, which pushed Debug past it. + await tester.scrollUntilVisible(find.text('Debug'), 200); + await tester.tap(find.text('Debug')); + await tester.pumpAndSettle(); + } + + testWidgets('stock 1.18 radio: Device CLI row shows at the top of Debug', ( + tester, + ) async { + connector.handleFrameForTest( + deviceInfo(length: 82, verCode: 14, version: 'v1.18.0'), + ); + await pumpAndOpenDebug(tester); + + expect(find.text('Device CLI'), findsOneWidget); + // Sits above App Debug Logging (the row that is otherwise first). + final cliDy = tester.getTopLeft(find.byIcon(Icons.terminal)).dy; + final loggingDy = tester + .getTopLeft(find.byIcon(Icons.bug_report_outlined)) + .dy; + expect(cliDy, lessThan(loggingDy)); + }); + + testWidgets('tapping the row opens the console', (tester) async { + connector.handleFrameForTest( + deviceInfo(length: 82, verCode: 14, version: 'v1.18.0'), + ); + await pumpAndOpenDebug(tester); + + await tester.tap(find.text('Device CLI')); + await tester.pumpAndSettle(); + expect(find.byType(DeviceCliScreen), findsOneWidget); + }); + + testWidgets('disconnected / no device info: no Device CLI row', ( + tester, + ) async { + // No device-info frame fed, so classification stays null. + await pumpAndOpenDebug(tester); + expect(find.text('Device CLI'), findsNothing); + expect(find.byIcon(Icons.terminal), findsNothing); + }); + + testWidgets('stock-legacy radio (ver 13): no Device CLI row', (tester) async { + connector.handleFrameForTest( + deviceInfo(length: 82, verCode: 13, version: 'v1.17.1'), + ); + await pumpAndOpenDebug(tester); + expect(find.text('Device CLI'), findsNothing); + }); + + testWidgets('Offband radio: no Device CLI row (CLI arrives at the absorb)', ( + tester, + ) async { + connector.handleFrameForTest( + deviceInfo(length: 85, verCode: 22, version: '1.4.0-1.17.0'), + ); + await pumpAndOpenDebug(tester); + expect(find.text('Device CLI'), findsNothing); + }); +} diff --git a/test/screens/settings_device_ui_split_test.dart b/test/screens/settings_device_ui_split_test.dart new file mode 100644 index 00000000..4b6127a8 --- /dev/null +++ b/test/screens/settings_device_ui_split_test.dart @@ -0,0 +1,161 @@ +// Pins #978: button actions live under Node Settings on caps byte 2 0x02, the +// buzzer under Message Settings on 0x01, and each opens only its own half. +// All four combinations are covered, because boards with a buzzer and no +// button exist (m5stack_unit_c6l, thinknode_m9, wio-tracker-l1-eink). + +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _Radio extends MeshCoreConnector { + _Radio({required this.button, required this.buzzer}); + final bool button; + final bool buzzer; + final List requests = []; + + @override + bool get supportsButtonMatrix => button; + + @override + bool get supportsNotifyScope => buzzer; + + // Values already read, so no screen sits on an animating spinner. + @override + ButtonMatrix? get buttonMatrix => + const ButtonMatrix(assignments: {}, supportedActions: 0); + + @override + DeviceNotifyScope? get deviceNotifyScope => DeviceNotifyScope.all; + + @override + Future requestButtonMatrix() async => requests.add('matrix'); + + @override + Future requestNotifyScope() async => requests.add('scope'); +} + +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pumpSettings(WidgetTester tester, _Radio radio) async { + radio.sendFrameOverrideForTest = (_) {}; + tester.view.physicalSize = const Size(400, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: radio), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future tapText(WidgetTester tester, String text) async { + await tester.scrollUntilVisible(find.text(text), 200); + await tester.tap(find.text(text)); + await tester.pumpAndSettle(); + } + + Future back(WidgetTester tester) async { + await tester.pageBack(); + await tester.pumpAndSettle(); + } + + /// What Node Settings and Message Settings each offer for this radio. + Future<(bool, bool)> entries(WidgetTester tester, _Radio radio) async { + await pumpSettings(tester, radio); + await tapText(tester, 'Node Settings'); + final hasButton = find.text('Button actions').evaluate().isNotEmpty; + await back(tester); + await tapText(tester, 'Message Settings'); + final hasBuzzer = find.text('Buzzer and tones').evaluate().isNotEmpty; + return (hasButton, hasBuzzer); + } + + testWidgets('button only: an entry in Node Settings, none for a buzzer', ( + tester, + ) async { + final r = await entries(tester, _Radio(button: true, buzzer: false)); + expect(r, equals((true, false))); + }); + + testWidgets('buzzer only: an entry in Message Settings, none for a button', ( + tester, + ) async { + final r = await entries(tester, _Radio(button: false, buzzer: true)); + expect(r, equals((false, true))); + }); + + testWidgets('both: each in its own place', (tester) async { + final r = await entries(tester, _Radio(button: true, buzzer: true)); + expect(r, equals((true, true))); + }); + + testWidgets('neither: no entry anywhere', (tester) async { + final r = await entries(tester, _Radio(button: false, buzzer: false)); + expect(r, equals((false, false))); + }); + + testWidgets('the combined Button and buzzer entry is gone', (tester) async { + await pumpSettings(tester, _Radio(button: true, buzzer: true)); + await tapText(tester, 'Node Settings'); + expect(find.text('Button and buzzer'), findsNothing); + }); + + testWidgets('Buzzer and tones opens only the buzzer half', (tester) async { + final radio = _Radio(button: true, buzzer: true); + await pumpSettings(tester, radio); + await tapText(tester, 'Message Settings'); + await tapText(tester, 'Buzzer and tones'); + + expect(find.text('Device notification scope'), findsOneWidget); + // A button row: present whenever the button half renders. + expect(find.text('Single press'), findsNothing); + expect(radio.requests, equals(['scope'])); + }); + + testWidgets('Button actions opens only the button half', (tester) async { + final radio = _Radio(button: true, buzzer: true); + await pumpSettings(tester, radio); + await tapText(tester, 'Node Settings'); + await tapText(tester, 'Button actions'); + + expect(find.text('Single press'), findsOneWidget); + expect(find.text('Device notification scope'), findsNothing); + expect(radio.requests, equals(['matrix'])); + }); +} diff --git a/test/screens/settings_gps_mode_test.dart b/test/screens/settings_gps_mode_test.dart new file mode 100644 index 00000000..191efac6 --- /dev/null +++ b/test/screens/settings_gps_mode_test.dart @@ -0,0 +1,301 @@ +// Pins #969 on the Location screen, against the approved mockups (cards 1 to +// 4, docs/initiatives/standalone/975-settings-restructure/): one Off / On / +// Power save control, Power save offered only where ps_ok says the build can +// run it, one status row naming backed off, and a sleep row that exists only +// in Power save and treats 0 as the firmware default. + +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/offband_gps_status.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// A radio that speaks the 0xC5 GPS sub-codes, with its state set directly. +class _GpsRadio extends MeshCoreConnector { + GpsModeState? gpsState; + String? error; + DeviceUiSurface? errorSurface; + final List<(GpsMode, int?)> writes = []; + + @override + bool get supportsGpsMode => true; + + @override + bool get supportsOffbandGps => false; + + @override + GpsModeState? get gpsModeState => gpsState; + + @override + String? get deviceUiError => error; + + @override + DeviceUiSurface? get deviceUiErrorSurface => errorSurface; + + @override + Map? get currentCustomVars => {'gps': '1'}; + + @override + Future requestGpsMode() async {} + + @override + Future requestOffbandGps({ + Duration timeout = const Duration(seconds: 5), + }) async => null; + + @override + Future setGpsMode(GpsMode mode, {int? intervalSeconds}) async { + writes.add((mode, intervalSeconds)); + } + + @override + void clearDeviceUiError() { + error = null; + errorSurface = null; + notifyListeners(); + } +} + +GpsModeState gps({ + GpsMode mode = GpsMode.on, + bool psOk = true, + GpsActivity? activity = GpsActivity.on, + int interval = 0, + int wait = 0, +}) => GpsModeState( + mode: mode, + storedMode: mode.code, + powerSaveAvailable: psOk, + activity: activity, + intervalSeconds: interval, + waitSeconds: wait, +); + +void main() { + late OffbandDatabase db; + late _GpsRadio radio; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + radio = _GpsRadio(); + radio.sendFrameOverrideForTest = (_) {}; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + /// [settle] false is for a pane showing an indeterminate spinner, which + /// animates forever and so never lets `pumpAndSettle` finish. + Future openLocation(WidgetTester tester, {bool settle = true}) async { + tester.view.physicalSize = const Size(400, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: radio), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Location')); + if (settle) { + await tester.pumpAndSettle(); + } else { + // One frame to push the route, then enough time for its transition. + await tester.pump(); + await tester.pump(const Duration(seconds: 1)); + } + } + + Finder segment(String label) => find.descendant( + of: find.byType(SegmentedButton), + matching: find.text(label), + ); + + testWidgets('one control with three states replaces the toggle', ( + tester, + ) async { + radio.gpsState = gps(); + await openLocation(tester); + + expect(segment('Off'), findsOneWidget); + expect(segment('On'), findsOneWidget); + expect(segment('Power save'), findsOneWidget); + // The legacy two-control layout is gone on a 0x20 radio. + expect(find.text('GPS Enable'), findsNothing); + expect(find.byType(SwitchListTile), findsNothing); + }); + + testWidgets('Power save is absent where the build cannot run it', ( + tester, + ) async { + radio.gpsState = gps(psOk: false); + await openLocation(tester); + + expect(segment('Off'), findsOneWidget); + expect(segment('On'), findsOneWidget); + expect(segment('Power save'), findsNothing); + }); + + testWidgets('each choice writes its mode and leaves the interval alone', ( + tester, + ) async { + radio.gpsState = gps(); + await openLocation(tester); + + await tester.tap(segment('Power save')); + await tester.pumpAndSettle(); + await tester.tap(segment('Off')); + await tester.pumpAndSettle(); + + // No explicit interval: the connector resends the radio's own. + expect( + radio.writes, + equals([(GpsMode.powerSave, null), (GpsMode.off, null)]), + ); + }); + + testWidgets('backed off is named, with the wait to the next try', ( + tester, + ) async { + radio.gpsState = gps( + mode: GpsMode.powerSave, + activity: GpsActivity.backedOff, + wait: 2880, + ); + await openLocation(tester); + + expect(find.text('Backed off'), findsOneWidget); + expect(find.text('Next try in 48 min'), findsOneWidget); + }); + + testWidgets('Off says what is shown instead of a fix', (tester) async { + radio.gpsState = gps(mode: GpsMode.off, activity: GpsActivity.off); + await openLocation(tester); + + expect(find.text('GPS is off'), findsOneWidget); + expect(find.text('Showing the last stored position'), findsOneWidget); + }); + + testWidgets('the sleep row exists only in Power save', (tester) async { + radio.gpsState = gps(mode: GpsMode.on); + await openLocation(tester); + expect(find.text('Sleep between fix attempts'), findsNothing); + }); + + testWidgets('a sleep of 0 reads as the firmware default, not a number', ( + tester, + ) async { + radio.gpsState = gps(mode: GpsMode.powerSave, interval: 0); + await openLocation(tester); + + expect(find.text('Sleep between fix attempts'), findsOneWidget); + expect(find.text('Firmware default, minimum 5 minutes'), findsOneWidget); + }); + + testWidgets('the stored sleep is shown, as the radio reported it', ( + tester, + ) async { + radio.gpsState = gps(mode: GpsMode.powerSave, interval: 300); + await openLocation(tester); + expect(find.text('Every 5 minutes'), findsOneWidget); + }); + + testWidgets('the sleep editor sends what was typed, including 0', ( + tester, + ) async { + radio.gpsState = gps(mode: GpsMode.powerSave, interval: 3600); + await openLocation(tester); + + await tester.tap(find.text('Sleep between fix attempts')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), '0'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(radio.writes, equals([(GpsMode.powerSave, 0)])); + }); + + testWidgets('a negative or non-numeric sleep is refused, nothing sent', ( + tester, + ) async { + radio.gpsState = gps(mode: GpsMode.powerSave, interval: 3600); + await openLocation(tester); + + for (final bad in ['-5', 'abc']) { + await tester.tap(find.text('Sleep between fix attempts')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), bad); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + final message = find.text('Enter a whole number of seconds, 0 or more.'); + expect(message, findsOneWidget, reason: 'input "$bad"'); + // Persistent: still there after the default 4-second toast would end. + await tester.pump(const Duration(seconds: 6)); + expect(message, findsOneWidget, reason: 'input "$bad" after 6 s'); + await tester.tap(message); + await tester.pumpAndSettle(); + } + expect(radio.writes, isEmpty); + }); + + testWidgets('a GPS refusal is held on the card until dismissed', ( + tester, + ) async { + radio.gpsState = gps(); + radio.error = 'This radio cannot run Power save'; + radio.errorSurface = DeviceUiSurface.gpsMode; + await openLocation(tester); + + expect(find.text('This radio cannot run Power save'), findsOneWidget); + await tester.tap(find.byTooltip('Close')); + await tester.pumpAndSettle(); + expect(find.text('This radio cannot run Power save'), findsNothing); + }); + + testWidgets('another screen\'s refusal is not shown on Location', ( + tester, + ) async { + radio.gpsState = gps(); + radio.error = 'This radio has no buzzer'; + radio.errorSurface = DeviceUiSurface.notifyScope; + await openLocation(tester); + + expect(find.text('This radio has no buzzer'), findsNothing); + }); + + testWidgets('before the first reply the card says it is reading', ( + tester, + ) async { + radio.gpsState = null; + await openLocation(tester, settle: false); + + expect(find.text('Reading GPS settingsโ€ฆ'), findsOneWidget); + expect(find.byType(SegmentedButton), findsNothing); + }); +} diff --git a/test/screens/settings_location_test.dart b/test/screens/settings_location_test.dart new file mode 100644 index 00000000..ed00913c --- /dev/null +++ b/test/screens/settings_location_test.dart @@ -0,0 +1,227 @@ +// Pins #977: Location is a top-level Settings category directly under Radio +// Settings, and the only place GPS lives. Each placement is asserted from both +// sides (present in Location, absent from Node Settings) so a control drifting +// back fails CI. The writes the radio sees are pinned too: this was a move, not +// a behavior change, apart from coordinates and interval saving independently. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:drift/native.dart'; + +/// Supplies custom vars and coordinates, and records every write so the +/// negative cases can prove nothing left the client. +class _SpyConnector extends MeshCoreConnector { + Map? vars; + double? lat; + double? lon; + final List customVarWrites = []; + final List<(double, double)> locationWrites = []; + + @override + Map? get currentCustomVars => vars; + + @override + double? get selfLatitude => lat; + + @override + double? get selfLongitude => lon; + + @override + Future setCustomVar(String value) async { + customVarWrites.add(value); + final sep = value.indexOf(':'); + if (sep > 0) { + (vars ??= {})[value.substring(0, sep)] = value.substring( + sep + 1, + ); + notifyListeners(); + } + } + + @override + Future setNodeLocation({ + required double lat, + required double lon, + }) async { + locationWrites.add((lat, lon)); + } + + @override + Future refreshDeviceInfo() async {} +} + +void main() { + late OffbandDatabase db; + late _SpyConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = _SpyConnector(); + connector.sendFrameOverrideForTest = (_) {}; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pumpSettings(WidgetTester tester) async { + // Narrow layout: the category list renders and each pane is pushed. + tester.view.physicalSize = const Size(400, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future openPane(WidgetTester tester, String title) async { + await tester.tap(find.text(title)); + await tester.pumpAndSettle(); + } + + testWidgets('Location sits directly under Radio Settings', (tester) async { + await pumpSettings(tester); + + final radio = tester.getTopLeft(find.text('Radio Settings')).dy; + final location = tester.getTopLeft(find.text('Location')).dy; + final stats = tester.getTopLeft(find.text('Radio stats')).dy; + expect(radio, lessThan(location)); + expect(location, lessThan(stats)); + expect(find.text('GPS, coordinates, and reporting'), findsOneWidget); + }); + + testWidgets('Node Settings no longer carries GPS or a Location row', ( + tester, + ) async { + // A GPS radio: before #977 this showed the toggle in Node Settings. + connector.vars = {'gps': '1', 'gps_interval': '900'}; + await pumpSettings(tester); + await openPane(tester, 'Node Settings'); + + expect(find.text('GPS Enable'), findsNothing); + expect(find.byType(SwitchListTile), findsNothing); + expect(find.text('GPS coordinates'), findsNothing); + }); + + testWidgets('a GPS radio shows the toggle and the interval in Location', ( + tester, + ) async { + connector.vars = {'gps': '1', 'gps_interval': '900'}; + connector.lat = 39.103118; + connector.lon = -84.51202; + await pumpSettings(tester); + await openPane(tester, 'Location'); + + expect(find.text('GPS Enable'), findsOneWidget); + final toggle = tester.widget(find.byType(SwitchListTile)); + expect(toggle.value, isTrue); + expect(find.text('39.103118, -84.512020'), findsOneWidget); + expect(find.text('Every 15 minutes'), findsOneWidget); + + // The toggle writes the same custom var it always did. + await tester.tap(find.byType(SwitchListTile)); + await tester.pumpAndSettle(); + expect(connector.customVarWrites, equals(['gps:0'])); + }); + + testWidgets('a radio without GPS shows coordinates only', (tester) async { + connector.vars = {}; + await pumpSettings(tester); + await openPane(tester, 'Location'); + + expect(find.text('Coordinates'), findsOneWidget); + expect(find.text('Not set'), findsOneWidget); + expect(find.text('GPS Enable'), findsNothing); + expect(find.text('Position reporting interval'), findsNothing); + }); + + testWidgets('coordinates save on their own, without touching the interval', ( + tester, + ) async { + // No interval reported. In the old combined dialog an empty interval + // returned early and skipped the coordinates; they must now save. + connector.vars = {'gps': '1'}; + await pumpSettings(tester); + await openPane(tester, 'Location'); + + await tester.tap(find.text('Coordinates')); + await tester.pumpAndSettle(); + final fields = find.byType(TextField); + await tester.enterText(fields.at(0), '39.5'); + await tester.enterText(fields.at(1), '-84.25'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(connector.locationWrites, equals([(39.5, -84.25)])); + expect(connector.customVarWrites, isEmpty); + }); + + testWidgets('an out-of-range interval is refused and nothing is sent', ( + tester, + ) async { + connector.vars = {'gps': '1', 'gps_interval': '900'}; + await pumpSettings(tester); + await openPane(tester, 'Location'); + + await tester.tap(find.text('Position reporting interval')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), '59'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(connector.customVarWrites, isEmpty); + expect( + find.text( + 'Interval must be at least 60 seconds, and less than 86400 seconds.', + ), + findsOneWidget, + ); + }); + + testWidgets('a valid interval writes the same custom var as before', ( + tester, + ) async { + connector.vars = {'gps': '1', 'gps_interval': '900'}; + await pumpSettings(tester); + await openPane(tester, 'Location'); + + await tester.tap(find.text('Position reporting interval')); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), '120'); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(connector.customVarWrites, equals(['gps_interval:120'])); + expect(connector.locationWrites, isEmpty); + expect(find.text('Every 2 minutes'), findsOneWidget); + }); +} diff --git a/test/screens/settings_node_name_validation_test.dart b/test/screens/settings_node_name_validation_test.dart new file mode 100644 index 00000000..a9e407d7 --- /dev/null +++ b/test/screens/settings_node_name_validation_test.dart @@ -0,0 +1,106 @@ +// #885: the Settings node-name dialog mirrors the firmware's `set name` +// character rejection. An invalid name shows an inline error and the dialog +// stays open (the name is not sent); a clean name saves and the dialog closes. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:drift/native.dart'; + +/// Records any setNodeName the dialog would send, so the negative case can +/// prove nothing left the client. +class _SpyConnector extends MeshCoreConnector { + final List names = []; + + @override + Future setNodeName(String name) async { + names.add(name); + } + + @override + Future refreshDeviceInfo() async {} +} + +void main() { + late OffbandDatabase db; + late _SpyConnector connector; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = _SpyConnector(); + connector.sendFrameOverrideForTest = (_) {}; + connector.setConnectedForTest(); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future openNameDialog(WidgetTester tester) async { + tester.view.physicalSize = const Size(400, 900); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: connector), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: const MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: SettingsScreen(), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Node Settings')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Node Name')); + await tester.pumpAndSettle(); + } + + testWidgets('a forbidden character blocks the save and shows an error', ( + tester, + ) async { + await openNameDialog(tester); + + await tester.enterText(find.byType(TextField), 'Base:Camp'); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(find.textContaining("can't contain"), findsOneWidget); + expect(find.text('Save'), findsOneWidget); // dialog still open + expect(connector.names, isEmpty); // nothing sent + }); + + testWidgets('a clean name saves and closes the dialog', (tester) async { + await openNameDialog(tester); + + await tester.enterText(find.byType(TextField), 'BaseCamp'); + await tester.pumpAndSettle(); + await tester.tap(find.text('Save')); + await tester.pumpAndSettle(); + + expect(find.text('Save'), findsNothing); // dialog closed + expect(connector.names, ['BaseCamp']); + }); +} diff --git a/test/screens/settings_tones_parity_test.dart b/test/screens/settings_tones_parity_test.dart new file mode 100644 index 00000000..968286ea --- /dev/null +++ b/test/screens/settings_tones_parity_test.dart @@ -0,0 +1,419 @@ +// #970, #971, #986, #987: the approved parity screens +// (docs/initiatives/standalone/975-settings-restructure/ +// tones-screen-parity-mockups.html). Pins the gates, that each list offers +// exactly what firmware accepts, that play never chooses, and that each +// control sends the documented request. + +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/offband_device_ui.dart'; +import 'package:meshcore_open/connector/offband_screen_settings.dart'; +import 'package:meshcore_open/connector/offband_tones.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/screens/settings_screen.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/widgets/radio_tone.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:typed_data'; + +class _Radio extends MeshCoreConnector { + _Radio({this.tunes = true, this.screen = true, this.playResult}); + final bool tunes; + final bool screen; + final TunePlayResult? playResult; + final List calls = []; + + ScreenSettingsState settings = const ScreenSettingsState( + navText: BadgeTextSize.large, + messageText: BadgeTextSize.medium, + screenOffStored: 60, + screenOffSeconds: 60, + timeZone: 2, + batteryFullStored: 0, + batteryFullMv: 4200, + batteryPinned: false, + ); + + @override + bool get supportsNotifyScope => true; + @override + bool get supportsButtonMatrix => false; + @override + bool get supportsTunes => tunes; + @override + bool get supportsScreenSettings => screen; + @override + DeviceNotifyScope? get deviceNotifyScope => DeviceNotifyScope.all; + + @override + EventToneState? eventTone(ToneEvent event) => switch (event) { + ToneEvent.dm => const EventToneState(stored: 0xFF, effective: 1), + ToneEvent.channel => const EventToneState(stored: 0xFF, effective: 2), + ToneEvent.room => const EventToneState(stored: 8, effective: 8), + _ => const EventToneState(stored: 0, effective: 0), + }; + + @override + Map get tuneSlots => { + 0: const TuneSlotInfo(length: 34, name: 'Mario'), + for (var s = 1; s < tuneSlotCount; s++) + s: const TuneSlotInfo(length: 0, name: ''), + }; + + @override + ScreenSettingsState? get screenSettings => screen ? settings : null; + + @override + ChannelTune? channelTuneFor(int channel) => const ChannelTune.inherit(); + + @override + Future requestNotifyScope() async => calls.add('scope'); + @override + Future requestEventTones() async => calls.add('evtones'); + @override + Future requestTuneSlots() async => calls.add('slots'); + @override + Future requestScreenSettings() async => calls.add('screen'); + @override + Future requestChannelTune(int channel) async => + calls.add('chtune $channel'); + @override + Future setEventTone(ToneEvent event, int tuneId) async => + calls.add('evtone ${event.name} $tuneId'); + @override + Future setChannelTune(int channel, ChannelTune tune) async => + calls.add('chtune set $channel ${tune.stored}'); + @override + Future playTune(int tuneId) async { + calls.add('play $tuneId'); + return playResult ?? TunePlayResult.played; + } + + @override + Future readTuneSlot( + int slot, { + void Function(int bytesRead)? onProgress, + }) async { + calls.add('read $slot'); + return 'Mario:d=4,o=5,b=100:16e6,16e6,32p'; + } + + @override + Future setTextSize(BadgeTextTarget target, BadgeTextSize size) async => + calls.add('text ${target.name} ${size.name}'); + @override + Future setScreenOff(int seconds) async => calls.add('scroff $seconds'); + @override + Future setTimeZone(int index) async => calls.add('tz $index'); + @override + Future setBatteryFull({required bool pin}) async => + calls.add('batt ${pin ? 'pin' : 'auto'}'); +} + +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + Future pump(WidgetTester tester, _Radio radio, Widget home) async { + radio.sendFrameOverrideForTest = (_) {}; + tester.view.physicalSize = const Size(400, 1000); + tester.view.devicePixelRatio = 1.0; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MultiProvider( + providers: [ + ChangeNotifierProvider.value(value: radio), + ChangeNotifierProvider( + create: (_) => AppSettingsService(), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: home, + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future tapText(WidgetTester tester, String text) async { + await tester.scrollUntilVisible( + find.text(text), + 200, + scrollable: find.byType(Scrollable).last, + ); + // scrollUntilVisible can stop with the row at the very edge, where a tap + // lands on whatever is drawn over it. + await tester.ensureVisible(find.text(text)); + await tester.pumpAndSettle(); + await tester.tap(find.text(text)); + await tester.pumpAndSettle(); + } + + Future openBuzzer(WidgetTester tester, _Radio radio) async { + await pump(tester, radio, const SettingsScreen()); + await tapText(tester, 'Message Settings'); + await tapText(tester, 'Buzzer and tones'); + } + + group('Buzzer and tones', () { + testWidgets('scope, the six tones and all eight slots', (tester) async { + final radio = _Radio(); + await openBuzzer(tester, radio); + expect(radio.calls, containsAll(['scope', 'evtones', 'slots'])); + for (final e in ToneEvent.values) { + await tester.scrollUntilVisible( + find.text(e.label), + 100, + scrollable: find.byType(Scrollable).last, + ); + expect(find.text(e.label), findsOneWidget); + } + await tester.scrollUntilVisible( + find.text('8 (empty)'), + 100, + scrollable: find.byType(Scrollable).last, + ); + expect(find.text('8 (empty)'), findsOneWidget); + }); + + testWidgets('a default and a choice never read alike', (tester) async { + await openBuzzer(tester, _Radio()); + expect(find.text('Chime (radio default)'), findsOneWidget); + expect(find.text('Mario'), findsOneWidget); + }); + + testWidgets('no 0x10: the scope alone, as before', (tester) async { + final radio = _Radio(tunes: false); + await openBuzzer(tester, radio); + expect(find.text('Device notification scope'), findsOneWidget); + expect(find.text('Tones'), findsNothing); + expect(find.text('Custom tunes'), findsNothing); + expect(radio.calls, isNot(contains('evtones'))); + }); + + testWidgets('the picker lists what firmware accepts; play never chooses', ( + tester, + ) async { + final radio = _Radio(); + await openBuzzer(tester, radio); + await tapText(tester, 'DM'); + + final dialog = find.byType(AlertDialog); + for (final name in [ + 'Silent', + 'Chime', + 'Kerplop', + 'Tick', + 'Bloop', + 'Drop', + 'Knock', + 'Mario', + ]) { + expect( + find.descendant(of: dialog, matching: find.text(name)), + findsOneWidget, + ); + } + // No Default row for an event (owner decision 3), no empty slot. + expect( + find.descendant(of: dialog, matching: find.text('Default')), + findsNothing, + ); + expect( + find.descendant(of: dialog, matching: find.textContaining('empty')), + findsNothing, + ); + + final kerplop = find.ancestor( + of: find.descendant(of: dialog, matching: find.text('Kerplop')), + matching: find.byType(ListTile), + ); + await tester.tap( + find.descendant( + of: kerplop, + matching: find.byIcon(Icons.play_circle_outline), + ), + ); + await tester.pumpAndSettle(); + expect(radio.calls, contains('play 2')); + expect(radio.calls.where((c) => c.startsWith('evtone ')), isEmpty); + + await tester.tap( + find.descendant(of: dialog, matching: find.text('Bloop')), + ); + await tester.pumpAndSettle(); + expect(radio.calls, contains('evtone dm 4')); + }); + + testWidgets('a silent preview says why', (tester) async { + final radio = _Radio(playResult: TunePlayResult.soundOff); + await openBuzzer(tester, radio); + await tapText(tester, 'DM'); + final dialog = find.byType(AlertDialog); + final chime = find.ancestor( + of: find.descendant(of: dialog, matching: find.text('Chime')), + matching: find.byType(ListTile), + ); + await tester.tap( + find.descendant( + of: chime, + matching: find.byIcon(Icons.play_circle_outline), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('Sound is off on this radio'), findsOneWidget); + }); + }); + + group('slot editor', () { + testWidgets('opens with the stored tune and checks typing', (tester) async { + final radio = _Radio(); + await openBuzzer(tester, radio); + await tapText(tester, '1 Mario'); + expect(radio.calls, contains('read 0')); + expect(find.text('Mario:d=4,o=5,b=100:16e6,16e6,32p'), findsOneWidget); + expect(find.text('Plays as "Mario"'), findsOneWidget); + + await tester.enterText( + find.byType(TextField), + 'Doorbell:d=4,o=5,b=0:8e6', + ); + await tester.pump(); + expect(find.text('b= must be 1 or more'), findsOneWidget); + final save = tester.widget( + find.widgetWithText(FilledButton, 'Save'), + ); + expect(save.onPressed, isNull); + }); + }); + + group('slot editor, defaults out of order', () { + testWidgets('says why and fixes it in one tap', (tester) async { + await openBuzzer(tester, _Radio()); + await tapText(tester, '1 Mario'); + await tester.enterText( + find.byType(TextField), + 'Take On Me:o=5,d=8,b=160,b=160:f#,f#,e5', + ); + await tester.pump(); + expect( + find.text('The badge reads d=, o=, b= in that order, each once'), + findsOneWidget, + ); + + await tester.tap(find.text('Fix order')); + await tester.pump(); + expect(find.text('Take On Me:d=8,o=5,b=160:f#,f#,e5'), findsOneWidget); + expect(find.text('Plays as "Take On Me"'), findsOneWidget); + expect(find.text('Fix order'), findsNothing); + }); + }); + + group('Node Settings', () { + testWidgets('Screen and Battery only with 0x40', (tester) async { + await pump(tester, _Radio(screen: false), const SettingsScreen()); + await tapText(tester, 'Node Settings'); + expect(find.text('Screen'), findsNothing); + expect(find.text('Battery'), findsNothing); + }); + + testWidgets('the Screen page sends each control\'s request', ( + tester, + ) async { + final radio = _Radio(); + await pump(tester, radio, const SettingsScreen()); + await tapText(tester, 'Node Settings'); + expect(find.text('100% at 4200 mV'), findsOneWidget); + await tapText(tester, 'Screen'); + + await tester.tap(find.text('Small').last); + await tester.pumpAndSettle(); + expect(radio.calls, contains('text messages small')); + + await tester.tap(find.text('5 m')); + await tester.pumpAndSettle(); + expect(radio.calls, contains('scroff 300')); + + await tapText(tester, 'Eastern'); + await tapText(tester, 'Central'); + expect(radio.calls, contains('tz 3')); + }); + + testWidgets('Battery: pin asks first; Back to auto only when set', ( + tester, + ) async { + final radio = _Radio(); + await pump(tester, radio, const SettingsScreen()); + await tapText(tester, 'Node Settings'); + await tapText(tester, 'Battery'); + expect(find.text('Default for this board'), findsOneWidget); + expect(find.text('Back to auto'), findsNothing); + + await tester.tap(find.text('Set 100% here')); + await tester.pumpAndSettle(); + expect(radio.calls, isNot(contains('batt pin'))); + await tester.tap(find.text('Set 100% here').last); + await tester.pumpAndSettle(); + expect(radio.calls, contains('batt pin')); + }); + }); + + group('channel Radio tone', () { + final channel = Channel(index: 3, name: '#okimesh', psk: Uint8List(16)); + + Widget tile() => Scaffold( + body: Builder( + builder: (context) => ChannelRadioToneTile( + channel: channel, + onTap: () => showChannelRadioToneDialog(context, channel), + ), + ), + ); + + testWidgets('absent without 0x10', (tester) async { + await pump(tester, _Radio(tunes: false), tile()); + expect(find.text('Radio tone'), findsNothing); + }); + + testWidgets('Default names what it plays, and is selectable', ( + tester, + ) async { + final radio = _Radio(); + await pump(tester, radio, tile()); + expect(radio.calls, contains('chtune 3')); + expect(find.text('Default'), findsOneWidget); + + await tester.tap(find.text('Radio tone')); + await tester.pumpAndSettle(); + expect(find.text('Kerplop, the radio\'s channel tone'), findsOneWidget); + + await tester.tap(find.text('Silent')); + await tester.pumpAndSettle(); + expect(radio.calls, contains('chtune set 3 1')); + // Let the refusal watcher's window close. + await tester.pump(const Duration(seconds: 6)); + }); + }); +} diff --git a/test/screens/usb_flow_test.dart b/test/screens/usb_flow_test.dart index 16e5a951..f05853e4 100644 --- a/test/screens/usb_flow_test.dart +++ b/test/screens/usb_flow_test.dart @@ -18,6 +18,12 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { final MeshCoreConnectionState initialState; final List _ports; + MeshCoreTransportType fakeTransport = MeshCoreTransportType.usb; + bool fakeAutoReconnecting = false; + bool fakeGaveUp = false; + int stopCalls = 0; + int retryCalls = 0; + String? requestPortLabel; String? fallbackDeviceName; int connectUsbCalls = 0; @@ -32,7 +38,25 @@ class _FakeMeshCoreConnector extends MeshCoreConnector { MeshCoreConnectionState get state => initialState; @override - MeshCoreTransportType get activeTransport => MeshCoreTransportType.usb; + MeshCoreTransportType get activeTransport => fakeTransport; + + @override + bool get isAutoReconnecting => fakeAutoReconnecting; + + @override + bool get autoReconnectGaveUp => fakeGaveUp; + + @override + int get autoReconnectAttempt => 2; + + @override + String? get autoReconnectTargetName => 'T1000-E'; + + @override + Future stopAutoReconnect() async => stopCalls += 1; + + @override + Future retryLastDevice() async => retryCalls += 1; @override String? get activeUsbPort => fakeActiveUsbPort; @@ -147,6 +171,78 @@ void main() { expect(connector.lastConnectPortName, 'COM6'); }); + testWidgets( + 'UsbScreen connects while a BLE auto-reconnect holds the state (#997)', + (tester) async { + // The 2026-10-25 log: a USB tap during the retry loop was dropped + // silently, for 74 minutes, until the app was restarted. + final connector = + _FakeMeshCoreConnector( + initialState: MeshCoreConnectionState.connecting, + ports: ['COM13 - USB Serial Device (COM13)'], + ) + ..fakeTransport = MeshCoreTransportType.bluetooth + ..fakeAutoReconnecting = true; + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: const UsbScreen()), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.byType(ListTile).first); + await tester.pump(); + + expect(connector.connectUsbCalls, 1); + expect(connector.lastConnectPortName, 'COM13'); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(milliseconds: 60)); + }, + ); + + testWidgets('ScannerScreen shows the retry and a Stop that ends it (#997)', ( + tester, + ) async { + final connector = + _FakeMeshCoreConnector(initialState: MeshCoreConnectionState.connecting) + ..fakeTransport = MeshCoreTransportType.bluetooth + ..fakeAutoReconnecting = true; + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: const ScannerScreen()), + ); + await tester.pump(); + + expect(find.textContaining('attempt 2 of 5'), findsOneWidget); + await tester.tap(find.widgetWithText(TextButton, 'Stop')); + await tester.pump(); + expect(connector.stopCalls, 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(milliseconds: 60)); + }); + + testWidgets('ScannerScreen offers Retry once the retry gave up (#997)', ( + tester, + ) async { + final connector = _FakeMeshCoreConnector() + ..fakeTransport = MeshCoreTransportType.bluetooth + ..fakeGaveUp = true; + + await tester.pumpWidget( + _buildTestApp(connector: connector, child: const ScannerScreen()), + ); + await tester.pump(); + + expect(find.textContaining("Couldn't reach T1000-E"), findsOneWidget); + await tester.tap(find.widgetWithText(TextButton, 'Retry')); + await tester.pump(); + expect(connector.retryCalls, 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(milliseconds: 60)); + }); + testWidgets('ScannerScreen USB action reflects platform support', ( tester, ) async { diff --git a/test/services/app_exit_info_service_test.dart b/test/services/app_exit_info_service_test.dart new file mode 100644 index 00000000..ac758fa4 --- /dev/null +++ b/test/services/app_exit_info_service_test.dart @@ -0,0 +1,551 @@ +// Exit-record capture (#906). Covers the selection, formatting, naming and +// pruning logic as pure functions, plus the channel layer behind a mock handler +// so the dedup contract and the never-throw contract are both checked. +// +// NOT covered here, and it cannot be: that Android actually produces a +// REASON_ANR record with a readable trace. No adb command induces an ANR +// (`am crash` is a crash; `kill -3` dumps traces without a REASON_ANR death), +// so that needs a real main-thread block on an API 30+ device and a relaunch. +// That is #911 part B, and it is the only way to prove the mechanism. + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/app_exit_info_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +ExitRecord _record({ + int reason = 6, + String reasonName = 'ANR', + required int timestampMs, + int pid = 1234, + String? description, + String? processName = 'app.offband.meshcore', + int importance = 100, + int pssKb = 0, + int rssKb = 0, + int status = 0, + Uint8List? traceBytes, + String? traceUnavailable, + bool traceTruncated = false, +}) => ExitRecord( + reason: reason, + reasonName: reasonName, + timestampMs: timestampMs, + pid: pid, + description: description, + processName: processName, + importance: importance, + pssKb: pssKb, + rssKb: rssKb, + status: status, + traceBytes: traceBytes, + traceUnavailable: traceUnavailable, + traceTruncated: traceTruncated, +); + +void main() { + group('selectExitRecords', () { + test('first run backfills everything and caps the trace budget', () { + final all = [ + _record(timestampMs: 500), + _record(timestampMs: 400), + _record(timestampMs: 300), + _record(timestampMs: 200), + _record(timestampMs: 100), + ]; + final s = selectExitRecords(all, null, backfillTraceCap: 3); + expect(s.backfill, isTrue); + expect(s.records.length, 5, reason: 'metadata for every record'); + expect(s.traceBudget, 3, reason: 'traces capped on a backfill'); + expect(s.newWatermarkMs, 500); + }); + + test('backfill budget never exceeds the number of records', () { + final s = selectExitRecords( + [_record(timestampMs: 10)], + null, + backfillTraceCap: 3, + ); + expect(s.traceBudget, 1); + }); + + test('with a watermark, only strictly newer records are selected', () { + final all = [ + _record(timestampMs: 300), + _record(timestampMs: 200), + _record(timestampMs: 100), + ]; + final s = selectExitRecords(all, 200); + expect(s.backfill, isFalse); + expect(s.records.map((r) => r.timestampMs), [300]); + expect(s.newWatermarkMs, 300); + expect(s.traceBudget, 1, reason: 'no cap outside a backfill'); + }); + + test('a record equal to the watermark is treated as already logged', () { + final s = selectExitRecords([_record(timestampMs: 200)], 200); + expect(s.records, isEmpty); + expect(s.newWatermarkMs, isNull, reason: 'watermark must not move'); + }); + + test('two records in the same millisecond are both kept', () { + final all = [ + _record(timestampMs: 400, pid: 2), + _record(timestampMs: 400, pid: 1), + _record(timestampMs: 100, pid: 0), + ]; + final s = selectExitRecords(all, 100); + expect(s.records.map((r) => r.pid), [2, 1]); + expect( + s.newWatermarkMs, + 400, + reason: 'both logged before the watermark advances past them', + ); + }); + + test('nothing new yields an empty, non-backfill selection', () { + final s = selectExitRecords([_record(timestampMs: 50)], 999); + expect(s.records, isEmpty); + expect(s.backfill, isFalse); + expect(s.traceBudget, 0); + expect(s.newWatermarkMs, isNull); + }); + + test('watermark takes the highest timestamp, not the first', () { + final all = [_record(timestampMs: 100), _record(timestampMs: 900)]; + expect(selectExitRecords(all, 50).newWatermarkMs, 900); + }); + }); + + group('formatExitLine', () { + final at = DateTime.utc(2026, 10, 19, 7, 30).millisecondsSinceEpoch; + final now = DateTime.utc(2026, 10, 19, 8); + + test('an ANR logs at WARN with reason, pid and the trace filename', () { + final line = formatExitLine( + _record(timestampMs: at, description: 'Input dispatching timed out'), + backfill: false, + writtenFileName: 'anr-20261019T073000Z-1234.txt', + now: now, + ); + expect(line, startsWith('2026-10-19T08:00:00.000Z [WARN/ExitInfo] ')); + expect(line, contains('reason=ANR(6)')); + expect(line, contains('desc="Input dispatching timed out"')); + expect(line, contains('pid=1234')); + expect(line, contains('proc=app.offband.meshcore')); + expect(line, contains('importance=FOREGROUND')); + expect(line, contains('trace=anr-20261019T073000Z-1234.txt')); + expect(line, isNot(contains('backfill=true'))); + }); + + test('a routine exit logs at INFO, not WARN', () { + final line = formatExitLine( + _record(timestampMs: at, reason: 1, reasonName: 'EXIT_SELF'), + backfill: false, + now: now, + ); + expect(line, contains('[INFO/ExitInfo]')); + expect(line, contains('reason=EXIT_SELF(1)')); + }); + + test('a resource kill logs at WARN', () { + for (final name in const [ + 'LOW_MEMORY', + 'FREEZER', + 'EXCESSIVE_RESOURCE_USAGE', + 'CRASH', + 'CRASH_NATIVE', + ]) { + final line = formatExitLine( + _record(timestampMs: at, reasonName: name), + backfill: false, + now: now, + ); + expect(line, contains('[WARN/ExitInfo]'), reason: name); + } + }); + + test('zero memory renders as unknown, never as a real measurement', () { + final line = formatExitLine( + _record(timestampMs: at, pssKb: 0, rssKb: 0), + backfill: false, + now: now, + ); + expect(line, contains('pss=unknown')); + expect(line, contains('rss=unknown')); + expect(line, isNot(contains('0kB'))); + }); + + test('real memory figures render in kB', () { + final line = formatExitLine( + _record(timestampMs: at, pssKb: 182340, rssKb: 241088), + backfill: false, + now: now, + ); + expect(line, contains('pss=182340kB')); + expect(line, contains('rss=241088kB')); + }); + + test('a null description is omitted rather than printed as null', () { + final line = formatExitLine( + _record(timestampMs: at), + backfill: false, + now: now, + ); + expect(line, isNot(contains('desc='))); + expect(line, isNot(contains('null'))); + }); + + test('an absent trace records why, which is a normal outcome', () { + final line = formatExitLine( + _record(timestampMs: at, traceUnavailable: 'evicted_or_absent'), + backfill: false, + now: now, + ); + expect(line, contains('trace=none(evicted_or_absent)')); + }); + + test('a truncated trace is marked as such', () { + final line = formatExitLine( + _record(timestampMs: at, traceTruncated: true), + backfill: false, + writtenFileName: 'anr-x.txt', + now: now, + ); + expect(line, contains('trace=anr-x.txt(truncated)')); + }); + + test('a backfilled record says so, so it is not read as fresh', () { + final line = formatExitLine( + _record(timestampMs: at), + backfill: true, + now: now, + ); + expect(line, contains('backfill=true')); + }); + + test('an ideal line carries none of the failure markers', () { + final line = formatExitLine( + _record( + timestampMs: at, + pssKb: 1000, + rssKb: 2000, + description: 'Input dispatching timed out', + ), + backfill: false, + writtenFileName: 'anr-ok.txt', + now: now, + ); + for (final marker in ExitInfoMessages.failureMarkers) { + expect(line, isNot(contains(marker)), reason: marker); + } + }); + }); + + group('importanceName', () { + test('names the values that matter for reading an ANR', () { + expect(importanceName(100), 'FOREGROUND'); + expect(importanceName(125), 'FOREGROUND_SERVICE'); + expect(importanceName(200), 'VISIBLE'); + expect(importanceName(230), 'PERCEPTIBLE'); + expect(importanceName(300), 'SERVICE'); + expect(importanceName(400), 'CACHED'); + expect(importanceName(1000), 'GONE'); + }); + + test('zero is unknown, and an unmapped value keeps its number', () { + expect(importanceName(0), 'unknown'); + expect(importanceName(275), 'IMPORTANCE_275'); + }); + }); + + group('traceFileName', () { + test('is UTC, zero-padded, and sorts chronologically by name', () { + final a = traceFileName( + DateTime.utc(2026, 9, 3, 4, 5, 6).millisecondsSinceEpoch, + 7, + ); + final b = traceFileName( + DateTime.utc(2026, 10, 19, 7, 30, 0).millisecondsSinceEpoch, + 1234, + ); + expect(a, 'anr-20260903T040506Z-7.txt'); + expect(b, 'anr-20261019T073000Z-1234.txt'); + expect(a.compareTo(b), lessThan(0), reason: 'name order is time order'); + }); + }); + + group('traceFilesToPrune', () { + test('keeps nothing to do when under both limits', () { + final doomed = traceFilesToPrune( + {'anr-1.txt': 10, 'anr-2.txt': 10}, + keep: 5, + ceilingBytes: 1000, + ); + expect(doomed, isEmpty); + }); + + test('drops the oldest beyond the keep count', () { + final doomed = traceFilesToPrune( + { + 'anr-20260101T000000Z-1.txt': 10, + 'anr-20260102T000000Z-1.txt': 10, + 'anr-20260103T000000Z-1.txt': 10, + }, + keep: 2, + ceilingBytes: 1000, + ); + expect(doomed, ['anr-20260101T000000Z-1.txt']); + }); + + test('drops oldest first until the byte ceiling is met', () { + final doomed = traceFilesToPrune( + { + 'anr-20260101T000000Z-1.txt': 600, + 'anr-20260102T000000Z-1.txt': 600, + 'anr-20260103T000000Z-1.txt': 600, + }, + keep: 5, + ceilingBytes: 1000, + ); + expect(doomed, [ + 'anr-20260101T000000Z-1.txt', + 'anr-20260102T000000Z-1.txt', + ]); + }); + + test( + 'never deletes the newest file, even if it alone busts the ceiling', + () { + final doomed = traceFilesToPrune( + {'anr-20260103T000000Z-1.txt': 5000}, + keep: 5, + ceilingBytes: 1000, + ); + expect( + doomed, + isEmpty, + reason: 'a trace too big to keep is still the only evidence we have', + ); + }, + ); + }); + + group('ExitInfoMessages', () { + test('each failure has a distinct, non-empty message', () { + final messages = [ + ExitInfoMessages.notAndroid, + ExitInfoMessages.nullResult, + ExitInfoMessages.unsupported('api_below_30', 29), + ExitInfoMessages.queryFailed('exit_info_query_failed', 'boom'), + ExitInfoMessages.captureFailed('boom'), + ExitInfoMessages.traceDirMissing(42), + ExitInfoMessages.traceWriteFailed('anr-x.txt', 'boom'), + ExitInfoMessages.pruneFailed('boom'), + ExitInfoMessages.listFailed('boom'), + ExitInfoMessages.watermarkReadFailed('boom'), + ExitInfoMessages.watermarkWriteFailed('boom'), + ExitInfoMessages.forceBlockFailed('boom'), + ExitInfoMessages.dartBlockSurvived(20000, 1234), + ]; + for (final m in messages) { + expect(m, isNotEmpty); + } + expect(messages.toSet().length, messages.length, reason: 'all distinct'); + }); + + test('the unsupported message names the API level and the reason', () { + final m = ExitInfoMessages.unsupported('api_below_30', 29); + expect(m, contains('api_below_30')); + expect(m, contains('sdkInt=29')); + expect(m, contains('API 30')); + }); + + test('a query failure names the code so it is traceable', () { + expect( + ExitInfoMessages.queryFailed('exit_info_query_failed', 'binder died'), + contains('exit_info_query_failed'), + ); + }); + + test('every failure message trips at least one failure marker', () { + final messages = [ + ExitInfoMessages.unsupported('api_below_30', 29), + ExitInfoMessages.queryFailed('c', 'm'), + ExitInfoMessages.captureFailed('e'), + ExitInfoMessages.traceDirMissing(1), + ExitInfoMessages.traceWriteFailed('n', 'e'), + ExitInfoMessages.pruneFailed('e'), + ExitInfoMessages.listFailed('e'), + ExitInfoMessages.watermarkReadFailed('e'), + ExitInfoMessages.watermarkWriteFailed('e'), + ExitInfoMessages.forceBlockFailed('e'), + ]; + for (final m in messages) { + expect( + ExitInfoMessages.failureMarkers.any(m.contains), + isTrue, + reason: 'not detectable as a failure: $m', + ); + } + }); + }); + + group('collect over the platform channel', () { + const channel = MethodChannel('meshcore_open/app_exit_info'); + late List calls; + + setUp(() { + TestWidgetsFlutterBinding.ensureInitialized(); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + calls = []; + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + }); + + tearDown(() { + debugDefaultTargetPlatformOverride = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + PrefsManager.reset(); + }); + + void handle(Future? Function(MethodCall) handler) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) { + calls.add(call); + return handler(call); + }); + } + + Map reply(List> records) => { + 'supported': true, + 'sdkInt': 34, + 'records': records, + }; + + Map rec(int ts, {int pid = 1}) => { + 'reason': 6, + 'reasonName': 'ANR', + 'timestampMs': ts, + 'pid': pid, + 'importance': 100, + 'pssKb': 0, + 'rssKb': 0, + 'status': 0, + 'traceUnavailable': 'evicted_or_absent', + }; + + test('advances the watermark so nothing is logged twice', () async { + await PrefsManager.initialize(); + handle((_) async => reply([rec(5000), rec(4000)])); + + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + + expect( + PrefsManager.instance.getInt(AppExitInfoService.watermarkKey), + 5000, + ); + + // Second launch, same records: nothing new, watermark unchanged. + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + expect( + PrefsManager.instance.getInt(AppExitInfoService.watermarkKey), + 5000, + ); + }); + + test('a query failure leaves the watermark alone so it retries', () async { + SharedPreferences.setMockInitialValues({ + AppExitInfoService.watermarkKey: 1234, + }); + await PrefsManager.initialize(); + handle( + (_) async => throw PlatformException(code: 'exit_info_query_failed'), + ); + + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + + expect( + PrefsManager.instance.getInt(AppExitInfoService.watermarkKey), + 1234, + reason: 'an untouched watermark is what makes the next launch retry', + ); + }); + + test( + 'an unsupported platform reply does not throw or move anything', + () async { + await PrefsManager.initialize(); + handle( + (_) async => { + 'supported': false, + 'unsupportedReason': 'api_below_30', + 'sdkInt': 29, + 'records': [], + }, + ); + + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + + expect( + PrefsManager.instance.getInt(AppExitInfoService.watermarkKey), + isNull, + ); + expect(calls.single.method, 'getExitRecords'); + }, + ); + + test('a null reply does not throw', () async { + await PrefsManager.initialize(); + handle((_) async => null); + AppExitInfoService.instance.resetForTest(); + await expectLater(AppExitInfoService.instance.collect(), completes); + }); + + test('collect runs once per launch', () async { + await PrefsManager.initialize(); + handle((_) async => reply([rec(10)])); + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + await AppExitInfoService.instance.collect(); + expect(calls.length, 1, reason: 'second call is a no-op'); + }); + + test('off Android the channel is never touched', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + await PrefsManager.initialize(); + handle((_) async => reply([rec(10)])); + AppExitInfoService.instance.resetForTest(); + await AppExitInfoService.instance.collect(); + expect(calls, isEmpty); + }); + + // #931: the Dart block is a 20 second spin by design, so a missing platform + // guard would hang a desktop build rather than fail visibly. This proves it + // returns immediately off Android; the block itself is hardware-tested. + test('the Dart isolate block is an immediate no-op off Android', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + final started = DateTime.now(); + await AppExitInfoService.instance.forceDartIsolateBlock(millis: 20000); + expect( + DateTime.now().difference(started).inSeconds, + lessThan(2), + reason: 'it must not spin on a platform with no exit records', + ); + }); + + test('the native block is an immediate no-op off Android', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + handle((_) async => 20000); + await AppExitInfoService.instance.forceMainThreadBlock(); + expect(calls, isEmpty); + }); + }); +} diff --git a/test/services/channel_notify_per_radio_test.dart b/test/services/channel_notify_per_radio_test.dart new file mode 100644 index 00000000..0c4ba545 --- /dev/null +++ b/test/services/channel_notify_per_radio_test.dart @@ -0,0 +1,218 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/app_settings.dart'; +import 'package:meshcore_open/services/app_settings_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #839: channel notify modes must be scoped per radio (connected device-key +// prefix), the bare slot-index fallback is gone, and setting All must truly +// reset. Positive AND negative cases per the owner acceptance. +void main() { + const prefixA = 'aaaaaaaaaa'; + const prefixB = 'bbbbbbbbbb'; + const pskX = '0123456789abcdef0123456789abcdef'; + const pskPublic = 'ffffffffffffffffffffffffffffffff'; + + AppSettingsService service() => AppSettingsService(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + test('a mode set on radio A does not bleed into radio B', () async { + final s = service(); + await s.loadSettings(); + + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.off, + ); + // Same channel PSK, different radio: independent, defaults to All. + expect( + s.channelNotifyMode(devicePrefix: prefixB, pskHex: pskX), + ChannelNotifyMode.all, + ); + }); + + test('set-and-back to All truly resets (no stale alias wins)', () async { + final s = service(); + await s.loadSettings(); + + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.all, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.all, + ); + // All is the default and is not stored. + expect( + s.settings.channelNotifyModesByRadio[prefixA]?.containsKey(pskX) ?? false, + isFalse, + ); + }); + + test( + 'unknown scope resolves All and persists nothing (no index fallback)', + () async { + final s = service(); + await s.loadSettings(); + + // PSK not yet known (pre-sync): resolve All, never key by slot index. + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: null), + ChannelNotifyMode.all, + ); + expect( + s.channelNotifyMode(devicePrefix: '', pskHex: pskX), + ChannelNotifyMode.all, + ); + + // Setting with no PSK is a no-op, not an index-keyed write. + await s.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: null, + channelName: 'Test', + mode: ChannelNotifyMode.off, + ); + expect( + s.settings.channelNotifyModesByRadio[prefixA] ?? const {}, + isEmpty, + ); + }, + ); + + test('the mode survives an app restart (reload from prefs)', () async { + final s1 = service(); + await s1.loadSettings(); + await s1.setChannelNotifyMode( + devicePrefix: prefixA, + pskHex: pskX, + channelName: 'Test', + mode: ChannelNotifyMode.mentionsOnly, + ); + + // New service instance, same backing prefs = an app restart. + final s2 = service(); + await s2.loadSettings(); + expect( + s2.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.mentionsOnly, + ); + }); + + test('nested notify map round-trips through JSON', () { + final original = AppSettings( + channelNotifyModesByRadio: { + prefixA: {pskX: ChannelNotifyMode.off}, + prefixB: {pskPublic: ChannelNotifyMode.mentionsOnly}, + }, + ); + final restored = AppSettings.fromJson( + jsonDecode(jsonEncode(original.toJson())) as Map, + ); + expect( + restored.channelNotifyModesByRadio[prefixA]?[pskX], + ChannelNotifyMode.off, + ); + expect( + restored.channelNotifyModesByRadio[prefixB]?[pskPublic], + ChannelNotifyMode.mentionsOnly, + ); + }); + + test( + 'legacy flat map (psk- and index-keyed) migrates into the first radio', + () async { + // Seed the pre-#839 shape: a global flat map with a psk-keyed and an + // index-keyed entry, no nested map, not yet migrated. + final legacy = AppSettings( + channelNotifyModes: { + 'psk_$pskX': ChannelNotifyMode.mentionsOnly, + '2': ChannelNotifyMode.off, // resolvable index entry + }, + ); + SharedPreferences.setMockInitialValues({ + 'app_settings': jsonEncode(legacy.toJson()), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final s = service(); + await s.loadSettings(); + + // First radio connects and its channels are known: migrate into prefixA. + await s.migrateLegacyChannelNotify( + devicePrefix: prefixA, + pskByChannelIndex: {2: pskPublic}, + pskByChannelName: const {}, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskX), + ChannelNotifyMode.mentionsOnly, // from the psk_ entry + ); + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskPublic), + ChannelNotifyMode.off, // index '2' resolved to pskPublic + ); + + // A second radio starts clean: the legacy state is not re-applied. + await s.migrateLegacyChannelNotify( + devicePrefix: prefixB, + pskByChannelIndex: {2: pskPublic}, + pskByChannelName: const {}, + ); + expect( + s.settings.channelNotifyModesByRadio[prefixB] ?? const {}, + isEmpty, + ); + }, + ); + + test( + 'legacy name-keyed mute set migrates to Off on its resolved PSK', + () async { + final legacy = AppSettings(mutedChannels: {'Public'}); + SharedPreferences.setMockInitialValues({ + 'app_settings': jsonEncode(legacy.toJson()), + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + + final s = service(); + await s.loadSettings(); + await s.migrateLegacyChannelNotify( + devicePrefix: prefixA, + pskByChannelIndex: const {}, + pskByChannelName: {'Public': pskPublic}, + ); + + expect( + s.channelNotifyMode(devicePrefix: prefixA, pskHex: pskPublic), + ChannelNotifyMode.off, + ); + }, + ); +} diff --git a/test/services/cli_console_transport_test.dart b/test/services/cli_console_transport_test.dart new file mode 100644 index 00000000..c7836d83 --- /dev/null +++ b/test/services/cli_console_transport_test.dart @@ -0,0 +1,402 @@ +// #999: the CLI console must drive a remote companion the same way it drives +// the local device - one run()->CliReply call, one timeout type. These pin the +// remote transport's wiring (send type-3, correlate the reflected-prefix +// reply), its sender filtering (another contact's reply must not complete our +// command), and that both transports map their service's timeout to the single +// CliConsoleTimeout the console catches. + +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/cli_command_codec.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/services/cli_console_transport.dart'; +import 'package:meshcore_open/services/local_cli_service.dart'; +import 'package:meshcore_open/services/repeater_command_service.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +Contact _companion() => Contact( + publicKey: Uint8List.fromList(List.generate(32, (i) => i + 1)), + receivedName: 'Companion', + type: advTypeChat, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(0), +); + +/// A contact-message reply frame carrying [text] from [senderPrefix]: +/// [respCodeContactMsgRecv][prefix x6][path_len][txt_type][ts x4][text][0]. +Uint8List _replyFrame({ + required Uint8List senderPrefix, + required String text, + int txtType = txtTypeCliData, +}) { + final b = BytesBuilder(); + b.addByte(respCodeContactMsgRecv); + b.add(senderPrefix.sublist(0, 6)); + b.addByte(0); // path_len + b.addByte(txtType); // CLI_DATA is the reply type a companion answers with + b.add([0, 0, 0, 0]); // timestamp + b.add(ascii.encode(text)); + b.addByte(0); + return b.toBytes(); +} + +/// Throws a timeout from sendCommand so the mapping can be tested without +/// waiting out a real mesh window. +class _TimingOutRemoteService extends RepeaterCommandService { + _TimingOutRemoteService(super.connector); + + @override + Future sendCommand( + Contact repeater, + String command, { + Function(String)? onResponse, + Function(int)? onAttempt, + int retries = RepeaterCommandService.maxRetries, + }) async { + throw RepeaterCommandTimeout(command: command, timeoutMs: 4300); + } +} + +/// Throws a local timeout from run() so LocalCliTransport's mapping can be +/// tested in isolation. +class _TimingOutLocalService extends LocalCliService { + _TimingOutLocalService(super.connector); + + @override + Future run(String command, {Duration? timeout}) async { + throw LocalCliTimeout( + command: command, + timeout: const Duration(seconds: 10), + ); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + group('RemoteCliTransport', () { + test( + 'sends a type-3 command and completes with the correlated reply', + () async { + final connector = MeshCoreConnector(); + final companion = _companion(); + final sent = []; + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + sent.add(f); + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + connector.contactsForTest.add(companion); + + final transport = RemoteCliTransport(connector, companion); + final future = transport.run('get radio'); + + final frame = await cliSent.future; + // Frame: [cmd][type][attempt][ts x4][pubKey x6][cc| prefix ...]. + expect(frame[1], txtTypeCliCommand, reason: 'a companion gets type 3'); + final prefix = ascii.decode(frame.sublist(13, 16)); + + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: '${prefix}radio ok', + ), + ); + + final reply = await future; + expect(reply.text, 'radio ok'); + // No auto-retry: exactly one CLI send frame went out (#999/#891). + expect( + sent.where((f) => f.isNotEmpty && f[0] == cmdSendTxtMsg), + hasLength(1), + ); + transport.dispose(); + }, + ); + + test( + 'a plain or type-3 message from the target does not complete the command', + () async { + final connector = MeshCoreConnector(); + final companion = _companion(); + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + connector.contactsForTest.add(companion); + + final transport = RemoteCliTransport(connector, companion); + final future = transport.run('get radio'); + final frame = await cliSent.future; + final prefix = ascii.decode(frame.sublist(13, 16)); + + // A companion is a human chat node. A plain chat message (no prefix) + // must NOT complete the command via the unprefixed sole-pending + // fallback, and neither must an inbound type-3 command from them. + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: 'hey, you there?', + txtType: txtTypePlain, + ), + ); + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: 'run this on me', + txtType: txtTypeCliCommand, + ), + ); + // Only the real CLI_DATA reply completes it. + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: '${prefix}radio ok', + ), + ); + + final reply = await future; + expect(reply.text, 'radio ok'); + transport.dispose(); + }, + ); + + test( + 'a reply from another contact does not complete our command', + () async { + final connector = MeshCoreConnector(); + final companion = _companion(); + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + connector.contactsForTest.add(companion); + + final transport = RemoteCliTransport(connector, companion); + final future = transport.run('get radio'); + final frame = await cliSent.future; + final prefix = ascii.decode(frame.sublist(13, 16)); + + // A different contact reflects the same prefix - must be ignored. + final otherKey = Uint8List.fromList(List.filled(32, 0xEE)); + connector.handleFrameForTest( + _replyFrame(senderPrefix: otherKey, text: '${prefix}WRONG'), + ); + // The real target's reply must be the one that completes it. + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: '${prefix}RIGHT', + ), + ); + + final reply = await future; + expect(reply.text, 'RIGHT'); + transport.dispose(); + }, + ); + + test('a timed-out send surfaces as CliConsoleTimeout', () async { + final connector = MeshCoreConnector(); + final transport = RemoteCliTransport( + connector, + _companion(), + service: _TimingOutRemoteService(connector), + ); + await expectLater( + transport.run('get radio'), + throwsA( + isA().having( + (e) => e.secondsText, + 'secondsText', + '4.3', + ), + ), + ); + transport.dispose(); + }); + }); + + group('fail fast when the connected radio refuses the send (#999)', () { + // A pre-1.18 companion answers CMD_SEND_TXT_MSG carrying type 3 with + // ERR_CODE_UNSUPPORTED_CMD (companion-v1.17.1 MyMesh.cpp). The command + // never went out, so waiting out the mesh timeout would end in a row that + // blames the target. + final errUnsupported = Uint8List.fromList([ + respCodeErr, + errCodeUnsupportedCmd, + ]); + // [RESP_CODE_SENT][is_flood][expected_ack x4][est timeout x4]. 1.18 sends a + // CLI command with no ack expected, so OUR send's SENT carries ack 0; a + // plain DM's SENT carries a real ack hash. + Uint8List sent(List ack) => + Uint8List.fromList([respCodeSent, 0, ...ack, 0x10, 0x27, 0, 0]); + final commandSent = sent([0, 0, 0, 0]); + final dmSent = sent([0xDE, 0xAD, 0xBE, 0xEF]); + + Future< + ({ + MeshCoreConnector connector, + Contact companion, + Future run, + String prefix, + RemoteCliTransport transport, + }) + > + startRun() async { + final connector = MeshCoreConnector(); + final companion = _companion(); + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + connector.contactsForTest.add(companion); + final transport = RemoteCliTransport(connector, companion); + final run = transport.run('get radio'); + final frame = await cliSent.future; + return ( + connector: connector, + companion: companion, + run: run, + prefix: ascii.decode(frame.sublist(13, 16)), + transport: transport, + ); + } + + test('an unsupported-command error fails the command at once', () async { + final s = await startRun(); + s.connector.handleFrameForTest(errUnsupported); + await expectLater( + s.run.timeout(const Duration(seconds: 1)), + throwsA(isA()), + ); + s.transport.dispose(); + }); + + test('a different error code does not fail the command', () async { + final s = await startRun(); + s.connector.handleFrameForTest( + Uint8List.fromList([respCodeErr, errCodeNotFound]), + ); + s.connector.handleFrameForTest( + _replyFrame( + senderPrefix: s.companion.publicKey, + text: '${s.prefix}radio ok', + ), + ); + expect((await s.run).text, 'radio ok'); + s.transport.dispose(); + }); + + test('an error after the radio accepted the send is not ours', () async { + final s = await startRun(); + s.connector.handleFrameForTest(commandSent); + s.connector.handleFrameForTest(errUnsupported); + s.connector.handleFrameForTest( + _replyFrame( + senderPrefix: s.companion.publicKey, + text: '${s.prefix}radio ok', + ), + ); + expect((await s.run).text, 'radio ok'); + s.transport.dispose(); + }); + + test('a DM\'s SENT does not close the window early', () async { + // An earlier in-flight DM's acknowledgement (real ack hash) must not be + // mistaken for ours, or a refusal after it would be missed. + final s = await startRun(); + s.connector.handleFrameForTest(dmSent); + s.connector.handleFrameForTest(errUnsupported); + await expectLater( + s.run.timeout(const Duration(seconds: 1)), + throwsA(isA()), + ); + s.transport.dispose(); + }); + + test('an error before the text frame is written is not ours', () async { + // The window arms only at the write. An unrelated refusal that lands + // while the path update is still in progress must not fail the command. + final connector = MeshCoreConnector(); + final companion = _companion(); + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + connector.contactsForTest.add(companion); + final transport = RemoteCliTransport(connector, companion); + final run = transport.run('get radio'); + // run() has yielded inside the path update; nothing is armed yet. + connector.handleFrameForTest(errUnsupported); + final frame = await cliSent.future; + final prefix = ascii.decode(frame.sublist(13, 16)); + connector.handleFrameForTest( + _replyFrame( + senderPrefix: companion.publicKey, + text: '${prefix}radio ok', + ), + ); + expect((await run).text, 'radio ok'); + transport.dispose(); + }); + + test('dispose with a command in flight does not hang its run()', () async { + final s = await startRun(); + s.transport.dispose(); + await expectLater( + s.run.timeout(const Duration(seconds: 1)), + throwsA(isA()), + ); + }); + }); + + group('LocalCliTransport', () { + test('a local timeout surfaces as CliConsoleTimeout', () async { + final connector = MeshCoreConnector(); + final transport = LocalCliTransport( + connector, + service: _TimingOutLocalService(connector), + ); + await expectLater( + transport.run('get radio'), + throwsA( + isA().having( + (e) => e.secondsText, + 'secondsText', + '10.0', + ), + ), + ); + transport.dispose(); + }); + }); +} diff --git a/test/services/local_cli_service_test.dart b/test/services/local_cli_service_test.dart new file mode 100644 index 00000000..ecaa85e7 --- /dev/null +++ b/test/services/local_cli_service_test.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/cli_command_codec.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/services/app_debug_log_service.dart'; +import 'package:meshcore_open/services/command_correlation.dart'; +import 'package:meshcore_open/services/local_cli_service.dart'; +import 'package:meshcore_open/utils/app_logger.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + group('PrefixAllocator / splitCorrelated', () { + test('allocates unique XX| tokens and skips in-flight ones', () { + final a = PrefixAllocator(); + expect(a.next({}), '00|'); + expect(a.next({}), '01|'); + expect(a.next({'02|'}), '03|'); + }); + + test('wraps after 256 tokens', () { + final a = PrefixAllocator(); + for (var i = 0; i < 256; i++) { + a.next({}); + } + expect(a.next({}), '00|'); + }); + + test('split honors the positional rule', () { + final c = splitCorrelated('0A| > ok'); + expect(c.prefix, '0A|'); + expect(c.payload, '> ok'); + final plain = splitCorrelated('Unknown command'); + expect(plain.prefix, isNull); + expect(plain.payload, 'Unknown command'); + }); + }); + + group('LocalCliService', () { + late OffbandDatabase db; + late MeshCoreConnector connector; + late LocalCliService service; + late List sent; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + connector = MeshCoreConnector(); + sent = []; + connector.sendFrameOverrideForTest = sent.add; + connector.setConnectedForTest(); + service = LocalCliService(connector); + }); + + tearDown(() async { + service.dispose(); + BlobStore.clearTestOverride(); + await db.close(); + }); + + Uint8List replyFor(Uint8List request, String text) { + final prefix = ascii.decode(request.sublist(1, 4)); + return Uint8List.fromList([ + respCodeCliReply, + ...ascii.encode('$prefix$text'), + ]); + } + + test('round trip: command out, correlated reply completes it', () async { + final future = service.run('get radio'); + expect(sent, hasLength(1)); + expect(sent.single[0], cmdRunCliCommand); + connector.handleFrameForTest(replyFor(sent.single, '> 910.525,62.5,7,5')); + final reply = await future; + expect(reply.text, '> 910.525,62.5,7,5'); + expect(reply.prefix, isNotNull); + }); + + test('a reply with a foreign prefix never completes a waiting command' + ' - the command times out instead', () async { + final future = service.run( + 'ver', + timeout: const Duration(milliseconds: 80), + ); + connector.handleFrameForTest( + Uint8List.fromList([respCodeCliReply, ...ascii.encode('ZZ|nope')]), + ); + await expectLater(future, throwsA(isA())); + }); + + test('timeout surfaces as LocalCliTimeout', () async { + final future = service.run( + 'ver', + timeout: const Duration(milliseconds: 50), + ); + await expectLater(future, throwsA(isA())); + }); + + test('two in-flight commands complete independently', () async { + final f1 = service.run('get af'); + final f2 = service.run('get cad'); + expect(sent, hasLength(2)); + // Answer the SECOND first; each reply must find its own command. + connector.handleFrameForTest(replyFor(sent[1], '> off')); + connector.handleFrameForTest(replyFor(sent[0], '> 1.0')); + expect((await f2).text, '> off'); + expect((await f1).text, '> 1.0'); + }); + + test('a late reply to a secret command never logs its cleartext' + ' (Gemini review #883)', () async { + final logService = AppDebugLogService(); + appLogger.initialize(logService, enabled: true); + addTearDown(() => appLogger.setEnabled(false)); + + // The command times out, so its pending entry is dropped. + final future = service.run( + 'get wifi.pwd', + timeout: const Duration(milliseconds: 40), + ); + await expectLater(future, throwsA(isA())); + + // The device answers late, carrying the secret in cleartext. + const secret = 'hunter2-cleartext'; + connector.handleFrameForTest(replyFor(sent.single, secret)); + + // The unmatched reply is logged for diagnostics, but its text is not. + expect(logService.entries, isNotEmpty); + for (final e in logService.entries) { + expect(e.message, isNot(contains(secret))); + } + expect( + logService.entries.any((e) => e.message.contains('text withheld')), + isTrue, + ); + }); + }); +} diff --git a/test/services/path_history_service_test.dart b/test/services/path_history_service_test.dart index cce2c6a2..4949b4d1 100644 --- a/test/services/path_history_service_test.dart +++ b/test/services/path_history_service_test.dart @@ -51,7 +51,7 @@ Contact _makeContact({ } return Contact( publicKey: bytes, - name: 'Test', + receivedName: 'Test', type: 1, pathLength: pathLength, path: Uint8List.fromList(path), diff --git a/test/services/radio_isolation_bleed_test.dart b/test/services/radio_isolation_bleed_test.dart new file mode 100644 index 00000000..5959b66b --- /dev/null +++ b/test/services/radio_isolation_bleed_test.dart @@ -0,0 +1,298 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/delivery_observation.dart'; +import 'package:meshcore_open/models/path_history.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/services/timeout_prediction_service.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #937 B2 and B3: the two bleeds, now isolated. +/// +/// These were written in Epic A (#936) asserting the BUG, so Epic B had +/// something concrete to invert rather than a prose description. This is that +/// inversion: every expectation that previously demanded the bleed now demands +/// isolation, and the before/after is in the git history of this one file. +/// +/// Still against the REAL `StorageService` rather than a fake, because the +/// defect was in the key and a fake would have hidden it. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + PathRecord record(int hops, int ms) => PathRecord( + hopCount: hops, + tripTimeMs: ms, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + wasFloodDiscovery: false, + pathBytes: const [1, 2, 3], + successCount: 1, + failureCount: 0, + ); + + StorageService radio(String key) => + StorageService()..setPublicKeyHex = key * 20; + + ContactPathHistory history(String contact, int hops, int ms) => + ContactPathHistory( + contactPubKeyHex: contact, + recentPaths: [record(hops, ms)], + ); + + group('#854 path history is per radio', () { + test('the key carries the radio, not just the contact', () async { + await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 500)); + + final keys = await BlobStore.instance.keysWithPrefix('path_history_'); + + expect(keys.length, 1); + expect( + keys.single, + 'path_history_aaaaaaaaaacafebabe', + reason: + 'prefix + radio + contact. Before #854 this was ' + 'path_history_cafebabe, with no radio in it', + ); + }); + + test('a route learned by radio A is NOT served to radio B', () async { + await radio( + 'a', + ).savePathHistory('cafebabe', history('cafebabe', 7, 9000)); + + final seenByB = await radio('b').loadPathHistory('cafebabe'); + + expect( + seenByB, + isNull, + reason: + 'the 7-hop route radio A measured must not reach radio B. ' + 'This asserted hopCount == 7 before Epic B', + ); + }); + + test('each radio keeps its own route to the same contact', () async { + await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 400)); + await radio( + 'b', + ).savePathHistory('cafebabe', history('cafebabe', 7, 9000)); + + expect( + (await radio( + 'a', + ).loadPathHistory('cafebabe'))!.recentPaths.single.hopCount, + 2, + ); + expect( + (await radio( + 'b', + ).loadPathHistory('cafebabe'))!.recentPaths.single.hopCount, + 7, + ); + }); + + test('an unset radio key loads nothing and writes nothing', () async { + final unset = StorageService(); + + await unset.savePathHistory('cafebabe', history('cafebabe', 2, 400)); + + expect(await unset.loadPathHistory('cafebabe'), isNull); + expect( + await BlobStore.instance.keysWithPrefix('path_history_'), + isEmpty, + reason: + 'the #754 precedent: with no radio connected it must not ' + 'write an unscoped key that a later radio could pick up', + ); + }); + + test('clearing one radio does not touch another', () async { + await radio('a').savePathHistory('cafebabe', history('cafebabe', 2, 400)); + await radio( + 'b', + ).savePathHistory('cafebabe', history('cafebabe', 7, 9000)); + + await radio('a').clearAllPathHistories(); + + expect(await radio('a').loadPathHistory('cafebabe'), isNull); + expect( + await radio('b').loadPathHistory('cafebabe'), + isNotNull, + reason: + 'clearAllPathHistories was global before #854 and would have ' + 'taken radio B\'s routes with it', + ); + }); + }); + + group('#856 delivery observations are per radio', () { + DeliveryObservation obs(int ms, int hops) => DeliveryObservation( + contactKey: 'cafebabe', + pathLength: hops, + messageBytes: 100, + secondsSinceLastRx: 10, + isFlood: false, + deliveryMs: ms, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ); + + test('the key carries the radio', () async { + await radio('a').saveDeliveryObservations([obs(2500, 3)]); + + final keys = PrefsManager.instance + .getKeys() + .where((k) => k.contains('delivery_observations')) + .toList(); + + expect(keys.length, 1); + expect( + keys.single.endsWith('delivery_observations${'a' * 10}'), + isTrue, + reason: 'before #856 this was the bare key, shared by every radio', + ); + }); + + test( + 'one radio\'s RF timing does NOT reach another radio\'s model', + () async { + // A repeater's slow 45-second delivery. + await radio('a').saveDeliveryObservations([obs(45000, 7)]); + + final otherRadio = TimeoutPredictionService(radio('b')); + await otherRadio.initialize(); + + expect( + otherRadio.observationCount, + 0, + reason: + 'radio B has sent nothing, so it must start with no training ' + 'data. This asserted 1 before Epic B', + ); + }, + ); + + test('each radio trains on its own observations', () async { + await radio('a').saveDeliveryObservations([obs(45000, 7)]); + await radio('b').saveDeliveryObservations([obs(800, 1), obs(900, 1)]); + + final a = TimeoutPredictionService(radio('a')); + final b = TimeoutPredictionService(radio('b')); + await a.initialize(); + await b.initialize(); + + expect(a.observationCount, 1); + expect(b.observationCount, 2); + }); + }); + + group('legacy purges (plan decision 1: delete, do not orphan)', () { + test( + 'untagged path-history keys are removed, scoped ones are not', + () async { + // Pre-#854 keys live in PREFS; the new scheme writes to drift, so the + // two cannot be confused and no shape heuristic is needed. + SharedPreferences.setMockInitialValues({ + 'flutter.path_history_aaaa': '{}', + 'flutter.path_history_bbbb': '{}', + 'flutter.unrelated_setting': 'keep me', + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + final storage = radio('a'); + await storage.savePathHistory('cafebabe', history('cafebabe', 2, 400)); + + final removed = await storage.purgeLegacyPathHistory(chunkSize: 1); + + expect(removed, 2); + expect( + PrefsManager.instance.getKeys().where( + (k) => k.contains('path_history_'), + ), + isEmpty, + ); + expect( + PrefsManager.instance.getString('unrelated_setting'), + 'keep me', + reason: 'the purge must touch only its own prefix', + ); + expect( + await storage.loadPathHistory('cafebabe'), + isNotNull, + reason: 'the drift-side scoped history survives the prefs purge', + ); + }, + ); + + test('purging twice is a no-op, not an error', () async { + SharedPreferences.setMockInitialValues({ + 'flutter.path_history_aaaa': '{}', + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + final storage = radio('a'); + + expect(await storage.purgeLegacyPathHistory(), 1); + expect( + await storage.purgeLegacyPathHistory(), + 0, + reason: + 'it runs on every connect, so it has to be idempotent and ' + 'do no writes when there is nothing left', + ); + }); + + test( + 'the global observation list is removed, the scoped one is not', + () async { + SharedPreferences.setMockInitialValues({ + 'flutter.delivery_observations': '[]', + }); + PrefsManager.reset(); + await PrefsManager.initialize(); + final storage = radio('a'); + await storage.saveDeliveryObservations([ + DeliveryObservation( + contactKey: 'cafebabe', + pathLength: 1, + messageBytes: 10, + secondsSinceLastRx: 1, + isFlood: false, + deliveryMs: 100, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ), + ]); + + expect(await storage.purgeLegacyDeliveryObservations(), isTrue); + + expect( + PrefsManager.instance.containsKey('delivery_observations'), + isFalse, + ); + expect( + (await storage.loadDeliveryObservations()).length, + 1, + reason: 'this radio\'s own observations are not collateral', + ); + expect( + await storage.purgeLegacyDeliveryObservations(), + isFalse, + reason: 'idempotent', + ); + }, + ); + }); +} diff --git a/test/services/region_discovery_service_test.dart b/test/services/region_discovery_service_test.dart new file mode 100644 index 00000000..ac60f5f0 --- /dev/null +++ b/test/services/region_discovery_service_test.dart @@ -0,0 +1,94 @@ +// Epic #814 T B1: region discovery lifecycle service. +// Uses an injected discoverer function as the seam, so no live connector or +// drift codegen is needed to exercise every state. + +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/models/region.dart'; +import 'package:meshcore_open/services/region_discovery_service.dart'; + +void main() { + final pub = Uint8List(32); + RegionsReply reply(List names) => + RegionsReply(tag: 1, clock: 42, regionNames: names); + + test('success exposes deduped regions in order', () async { + final svc = RegionDiscoveryService( + (_, _) async => reply(['oki', 'test', 'oki']), + ); + await svc.discover(pub); + expect(svc.status, RegionDiscoveryStatus.success); + expect(svc.regions, const [Region('oki'), Region('test')]); + expect(svc.clock, 42); + }); + + test('empty reply surfaces empty, never success', () async { + final svc = RegionDiscoveryService((_, _) async => reply([])); + await svc.discover(pub); + expect(svc.status, RegionDiscoveryStatus.empty); + expect(svc.regions, isEmpty); + }); + + test('null reply surfaces timeout', () async { + final svc = RegionDiscoveryService((_, _) async => null); + await svc.discover(pub); + expect(svc.status, RegionDiscoveryStatus.timeout); + }); + + test('a thrown error (e.g. unsupported firmware) surfaces error', () async { + final svc = RegionDiscoveryService( + (_, _) async => + throw StateError('firmware does not support region scoping'), + ); + await svc.discover(pub); + expect(svc.status, RegionDiscoveryStatus.error); + expect(svc.errorMessage, contains('region scoping')); + }); + + test( + 'status is loading synchronously and notifies on start + finish', + () async { + var notifications = 0; + final svc = RegionDiscoveryService((_, _) async => reply(['x'])); + svc.addListener(() => notifications++); + final future = svc.discover(pub); + expect(svc.status, RegionDiscoveryStatus.loading); + await future; + expect(svc.status, RegionDiscoveryStatus.success); + expect(notifications, greaterThanOrEqualTo(2)); + }, + ); + + test('a second discover while loading is ignored', () async { + var calls = 0; + final svc = RegionDiscoveryService((_, _) async { + calls++; + await Future.delayed(const Duration(milliseconds: 20)); + return reply(['a']); + }); + final first = svc.discover(pub); + await svc.discover(pub); // no-op while the first is in flight + await first; + expect(calls, 1); + }); + + test('reset returns to idle', () async { + final svc = RegionDiscoveryService((_, _) async => reply(['a'])); + await svc.discover(pub); + svc.reset(); + expect(svc.status, RegionDiscoveryStatus.idle); + expect(svc.regions, isEmpty); + }); + + test('does not notify after dispose (screen popped mid-discovery)', () async { + final gate = Completer(); + final svc = RegionDiscoveryService((_, _) => gate.future); + final future = svc.discover(pub); + svc.dispose(); + gate.complete(reply(['a'])); + await future; // must complete without notifying the disposed notifier + }); +} diff --git a/test/services/repeater_command_service_test.dart b/test/services/repeater_command_service_test.dart index c7913e3b..2f9ed817 100644 --- a/test/services/repeater_command_service_test.dart +++ b/test/services/repeater_command_service_test.dart @@ -8,24 +8,29 @@ // These tests pin the contract that no reply is ever dropped silently. import 'dart:async'; +import 'dart:convert'; import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; import 'package:meshcore_open/models/contact.dart'; import 'package:meshcore_open/services/repeater_command_service.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:shared_preferences/shared_preferences.dart'; -Contact _repeater() => Contact( +Contact _contact({required int type}) => Contact( publicKey: Uint8List.fromList(List.generate(32, (i) => i)), - name: 'Test Repeater', - type: 2, + receivedName: 'Test', + type: type, pathLength: 0, path: Uint8List(0), lastSeen: DateTime.fromMillisecondsSinceEpoch(0), ); +Contact _repeater() => _contact(type: advTypeRepeater); +Contact _companion() => _contact(type: advTypeChat); + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -274,4 +279,41 @@ void main() { expect(surfaced.single.command, isNull); }); }); + + group('target split: message type by role (#889)', () { + // Drives a real send and reads the TXT type byte off the captured frame. + // Frame: [cmd][type][attempt][ts x4][pubKey x6][command...]; the cc| prefix + // leads the command at offset 13. + Future sentTypeFor(Contact target) async { + final connector = MeshCoreConnector(); + // Fires the moment the CLI send frame goes out, so the test is + // deterministic rather than racing a fixed delay. The send path emits a + // contact-path-update frame first; the CLI command is the + // CMD_SEND_TXT_MSG frame. + final cliSent = Completer(); + connector.sendFrameOverrideForTest = (f) { + if (!cliSent.isCompleted && f.isNotEmpty && f[0] == cmdSendTxtMsg) { + cliSent.complete(f); + } + }; + connector.setConnectedForTest(); + final svc = RepeaterCommandService(connector); + final future = svc.sendCommand(target, 'get radio', retries: 1); + final frame = await cliSent.future; + // Complete the command so sendCommand resolves (feed the reflected prefix). + final prefix = ascii.decode(frame.sublist(13, 16)); + svc.handleResponse(target, '${prefix}ok'); + await future; + svc.dispose(); + return frame[1]; + } + + test('a companion target gets the 1.18 command type', () async { + expect(await sentTypeFor(_companion()), txtTypeCliCommand); + }); + + test('a repeater target keeps the universal CLI_DATA type', () async { + expect(await sentTypeFor(_repeater()), txtTypeCliData); + }); + }); } diff --git a/test/services/retry_and_protocol_test.dart b/test/services/retry_and_protocol_test.dart index 0860f2d6..d5f86c86 100644 --- a/test/services/retry_and_protocol_test.dart +++ b/test/services/retry_and_protocol_test.dart @@ -62,7 +62,7 @@ Contact _makeContact({ }) { return Contact( publicKey: publicKey, - name: 'Test', + receivedName: 'Test', type: 1, pathLength: pathLength, path: Uint8List.fromList(path), diff --git a/test/services/stock_config_export_service_test.dart b/test/services/stock_config_export_service_test.dart index 3ed8db8f..83435d9e 100644 --- a/test/services/stock_config_export_service_test.dart +++ b/test/services/stock_config_export_service_test.dart @@ -27,7 +27,7 @@ Contact makeContact({ }) { return Contact( publicKey: Uint8List(32), - name: name, + receivedName: name, type: type, flags: flags, pathLength: pathLength, diff --git a/test/storage/blob_delete_off_thread_test.dart b/test/storage/blob_delete_off_thread_test.dart new file mode 100644 index 00000000..337aabb5 --- /dev/null +++ b/test/storage/blob_delete_off_thread_test.dart @@ -0,0 +1,177 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #919: the explicit delete path rewrites the whole blob too, so it moved off +/// the UI isolate with the save path. These tests pin that it still removes +/// exactly one record, never writes when there is nothing to change, and never +/// replaces a blob it could not read. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage msg(int i) => ChannelMessage( + senderName: 's', + text: 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'id$i', + ); + + Message dm(int i) => Message( + senderKey: Uint8List.fromList(const [1, 2, 3, 4]), + text: 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + messageId: 'id$i', + ); + + // Fixtures go through the store's own encoder rather than a hand-written map, + // which silently rots the moment a non-null field is added to the schema. + // Saves write rows now (#920), so this calls the encoder directly. + Future encodeVia(List ms) async => + ChannelMessageStore.encodeHistoryForTest(ms); + + group('dropFromChannelHistoryJson', () { + test('drops only the target and keeps the rest', () async { + final blobs = BlobStore.instance; + await blobs.write('k', await encodeVia([msg(1), msg(2), msg(3)])); + + final wrote = await blobs.mergeOffThread( + 'k', + 'id:id2', + dropFromChannelHistoryJson, + ); + + expect(wrote, isTrue); + final out = jsonDecode((await blobs.read('k'))!) as List; + expect(out.map((e) => (e as Map)['messageId']), [ + 'id1', + 'id3', + ]); + }); + + test('a target that is not present writes nothing at all', () async { + final blobs = BlobStore.instance; + final original = await encodeVia([msg(1)]); + await blobs.write('k', original); + + final wrote = await blobs.mergeOffThread( + 'k', + 'id:nope', + dropFromChannelHistoryJson, + ); + + expect( + wrote, + isFalse, + reason: + 'rewriting megabytes to change nothing is the cost #919 exists ' + 'to remove', + ); + expect(await blobs.read('k'), original); + }); + + test('a corrupt blob survives a delete untouched', () async { + final blobs = BlobStore.instance; + const corrupt = '{not json at all'; + await blobs.write('k', corrupt); + + final wrote = await blobs.mergeOffThread( + 'k', + 'id:id1', + dropFromChannelHistoryJson, + ); + + expect(wrote, isFalse); + expect(await blobs.read('k'), corrupt); + }); + + test('an absent blob is a no-op, not an empty write', () async { + final blobs = BlobStore.instance; + + final wrote = await blobs.mergeOffThread( + 'missing', + 'id:id1', + dropFromChannelHistoryJson, + ); + + expect(wrote, isFalse); + expect(await blobs.read('missing'), isNull); + }); + + test('removeChannelMessage deletes through the store API', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'c' * 20; + await store.saveChannelMessages(0, [msg(1), msg(2), msg(3)]); + + await store.removeChannelMessage(0, msg(2)); + + final loaded = await store.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1', 'id3']); + }); + }); + + group('dropFromDmHistoryJson', () { + test('removeMessage deletes through the store API', () async { + final store = MessageStore()..setPublicKeyHex = 'c' * 20; + await store.saveMessages('cafe', [dm(1), dm(2), dm(3)]); + + await store.removeMessage('cafe', dm(2)); + + final loaded = await store.loadMessages('cafe'); + expect(loaded.map((m) => m.messageId), ['id1', 'id3']); + }); + + test( + 'a delete racing a save cannot resurrect the deleted message', + () async { + final store = MessageStore()..setPublicKeyHex = 'd' * 20; + await store.saveMessages('f00d', [dm(1), dm(2)]); + + // Both are read-modify-writes on one key. Before #919 the delete ran + // outside the per-key chain, so a save landing after it could bring + // the deleted message back. + await Future.wait([ + store.removeMessage('f00d', dm(2)), + store.saveMessages('f00d', [dm(3)]), + ]); + + final loaded = await store.loadMessages('f00d'); + expect(loaded.map((m) => m.messageId), ['id1', 'id3']); + }, + ); + + test('a corrupt DM blob survives a delete untouched', () async { + final store = MessageStore()..setPublicKeyHex = 'e' * 20; + const corrupt = '{not json at all'; + await BlobStore.instance.write('messages_eeeeeeeeeedead', corrupt); + + await store.removeMessage('dead', dm(1)); + + expect(await BlobStore.instance.read('messages_eeeeeeeeeedead'), corrupt); + }); + }); +} diff --git a/test/storage/blob_merge_off_thread_test.dart b/test/storage/blob_merge_off_thread_test.dart new file mode 100644 index 00000000..68172768 --- /dev/null +++ b/test/storage/blob_merge_off_thread_test.dart @@ -0,0 +1,311 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #919: the blob read-modify-write moved off the UI isolate. These tests pin +/// the two things that must not change with it: the merge is semantically what +/// it was, and a blob that cannot be decoded is never overwritten. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage msg(int i, {String? text}) => ChannelMessage( + senderName: 's', + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'id$i', + ); + + // Fixtures go through the store's OWN encoder rather than a hand-written map. + // A hand-rolled fixture silently rots the moment a non-null field is added to + // the schema, which is exactly how the first run of this test failed. + // + // This used to get there by calling saveChannelMessages and reading the blob + // back. Saves write rows now (#920), so it calls the encoder directly. + Future encodeVia(List ms) async => + ChannelMessageStore.encodeHistoryForTest(ms); + + group('mergeChannelHistoryJson', () { + test('adds incoming messages to the stored history', () async { + final stored = await encodeVia([msg(1), msg(2)]); + final incoming = await encodeVia([msg(3)]); + + final out = + jsonDecode(mergeChannelHistoryJson((stored, incoming))) + as List; + + expect(out.length, 3); + expect( + out.map((e) => (e as Map)['messageId']), + containsAll(['id1', 'id2', 'id3']), + ); + }); + + test('incoming wins on the same id, so edits are captured', () async { + final stored = await encodeVia([msg(1, text: 'original')]); + final incoming = await encodeVia([msg(1, text: 'edited')]); + + final out = + jsonDecode(mergeChannelHistoryJson((stored, incoming))) + as List; + + expect( + out.length, + 1, + reason: 'same messageId must upsert, not duplicate', + ); + expect((out.single as Map)['text'], 'edited'); + }); + + test('result is sorted by timestamp regardless of input order', () async { + final stored = await encodeVia([msg(9), msg(3)]); + final incoming = await encodeVia([msg(5)]); + + final out = + jsonDecode(mergeChannelHistoryJson((stored, incoming))) + as List; + final stamps = out + .map((e) => (e as Map)['timestamp'] as int) + .toList(); + + expect(stamps, [...stamps]..sort()); + }); + + test( + 'an empty or absent stored blob merges into just the incoming', + () async { + final incoming = await encodeVia([msg(1)]); + + for (final stored in [null, '']) { + final out = + jsonDecode(mergeChannelHistoryJson((stored, incoming))) + as List; + expect(out.length, 1, reason: 'stored=$stored'); + } + }, + ); + + test( + 'THROWS on an undecodable stored blob rather than truncating', + () async { + final incoming = await encodeVia([msg(1)]); + + // The whole point: swallowing this would merge into an empty base and + // silently replace real history with one message. + expect( + () => mergeChannelHistoryJson(('{not json at all', incoming)), + throwsA(anything), + ); + }, + ); + }); + + Message dm(int i, {String? text}) => Message( + senderKey: Uint8List.fromList(const [1, 2, 3, 4]), + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + messageId: 'id$i', + ); + + Future encodeDmVia(List ms) async => + MessageStore.encodeHistoryForTest(ms); + + group('mergeDmHistoryJson', () { + test('adds incoming messages to the stored history', () async { + final stored = await encodeDmVia([dm(1), dm(2)]); + final incoming = await encodeDmVia([dm(3)]); + + final out = + jsonDecode(mergeDmHistoryJson((stored, incoming))) as List; + + expect(out.length, 3); + expect( + out.map((e) => (e as Map)['messageId']), + containsAll(['id1', 'id2', 'id3']), + ); + }); + + test('incoming wins on the same id, so a status change lands', () async { + final stored = await encodeDmVia([dm(1, text: 'original')]); + final incoming = await encodeDmVia([dm(1, text: 'edited')]); + + final out = + jsonDecode(mergeDmHistoryJson((stored, incoming))) as List; + + expect( + out.length, + 1, + reason: 'same messageId must upsert, not duplicate', + ); + expect((out.single as Map)['text'], 'edited'); + }); + + test('result is sorted by timestamp regardless of input order', () async { + final stored = await encodeDmVia([dm(9), dm(3)]); + final incoming = await encodeDmVia([dm(5)]); + + final out = + jsonDecode(mergeDmHistoryJson((stored, incoming))) as List; + final stamps = out + .map((e) => (e as Map)['timestamp'] as int) + .toList(); + + expect(stamps, [...stamps]..sort()); + }); + + test( + 'an empty or absent stored blob merges into just the incoming', + () async { + final incoming = await encodeDmVia([dm(1)]); + + for (final stored in [null, '']) { + final out = + jsonDecode(mergeDmHistoryJson((stored, incoming))) + as List; + expect(out.length, 1, reason: 'stored=$stored'); + } + }, + ); + + test( + 'THROWS on an undecodable stored blob rather than truncating', + () async { + final incoming = await encodeDmVia([dm(1)]); + + expect( + () => mergeDmHistoryJson(('{not json at all', incoming)), + throwsA(anything), + ); + }, + ); + + test( + 'a full DM save round trip through mergeOffThread keeps both', + () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveMessages('beef', [dm(1)]); + await store.saveMessages('beef', [dm(2)]); + + final loaded = await store.loadMessages('beef'); + expect( + loaded.map((m) => m.messageId), + ['id1', 'id2'], + reason: 'the second save must merge, not overwrite (#343)', + ); + }, + ); + }); + + group('BlobStore.mergeOffThread', () { + test('writes the merged result', () async { + final blobs = BlobStore.instance; + await blobs.write('k', await encodeVia([msg(1)])); + + final wrote = await blobs.mergeOffThread( + 'k', + await encodeVia([msg(2)]), + mergeChannelHistoryJson, + ); + + expect(wrote, isTrue); + final out = jsonDecode((await blobs.read('k'))!) as List; + expect(out.length, 2); + }); + + test( + 'FAILS CLOSED on a corrupt stored blob: returns false and leaves it byte-identical', + () async { + final blobs = BlobStore.instance; + const corrupt = '{not json at all'; + await blobs.write('k', corrupt); + + final wrote = await blobs.mergeOffThread( + 'k', + await encodeVia([msg(1)]), + mergeChannelHistoryJson, + ); + + expect( + wrote, + isFalse, + reason: 'a failed merge must not report success', + ); + expect( + await blobs.read('k'), + corrupt, + reason: 'the unreadable blob must survive untouched, not be replaced', + ); + }, + ); + + test('a merge returning null leaves the key untouched', () async { + final blobs = BlobStore.instance; + await blobs.write('k', 'original'); + + final wrote = await blobs.mergeOffThread('k', 'x', _alwaysNull); + + expect(wrote, isFalse); + expect(await blobs.read('k'), 'original'); + }); + + test('concurrent merges on one key do not clobber each other', () async { + final blobs = BlobStore.instance; + await blobs.write('k', await encodeVia([msg(0)])); + + // Fired together: without the per-key serialisation one read-modify-write + // would overwrite the other and a message would vanish. + await Future.wait([ + blobs.mergeOffThread( + 'k', + await encodeVia([msg(1)]), + mergeChannelHistoryJson, + ), + blobs.mergeOffThread( + 'k', + await encodeVia([msg(2)]), + mergeChannelHistoryJson, + ), + blobs.mergeOffThread( + 'k', + await encodeVia([msg(3)]), + mergeChannelHistoryJson, + ), + ]); + + final out = jsonDecode((await blobs.read('k'))!) as List; + expect( + out.length, + 4, + reason: 'all three concurrent saves plus the original must survive', + ); + }); + }); +} + +/// Top-level so `compute` can send it. +String? _alwaysNull((String?, String) input) => null; diff --git a/test/storage/blob_merge_runs_off_main_isolate_test.dart b/test/storage/blob_merge_runs_off_main_isolate_test.dart new file mode 100644 index 00000000..897f3196 --- /dev/null +++ b/test/storage/blob_merge_runs_off_main_isolate_test.dart @@ -0,0 +1,72 @@ +import 'dart:isolate'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// The one property Epic A (#919) delivers: the decode / merge / re-encode does +/// not run on the isolate that draws the UI. +/// +/// Asserted structurally rather than by timing, because a wall-clock threshold +/// would be flaky on CI and would not say *why* it passed. If someone later +/// "simplifies" `mergeOffThread` back to an inline call, every other test in +/// this directory still passes and only this one fails. +void main() { + late OffbandDatabase db; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + test('the merge callback does not run on the main isolate', () async { + final mainName = Isolate.current.debugName; + expect( + mainName, + 'main', + reason: 'sanity check on the premise of this test', + ); + + await BlobStore.instance.write('k', 'ignored'); + final wrote = await BlobStore.instance.mergeOffThread( + 'k', + 'ignored', + _reportIsolateName, + ); + + expect(wrote, isTrue); + final ranOn = await BlobStore.instance.read('k'); + + // `compute` names the isolate it spawns after the callback it was handed, + // so the recorded name both proves this was not the main isolate and says + // which worker it was. Observed: "Closure: ((String?, String)) => String + // from Function '_reportIsolateName@...': static." + expect( + ranOn, + isNot('main'), + reason: 'the whole point of #919: this work must leave the UI isolate', + ); + expect( + ranOn, + contains('_reportIsolateName'), + reason: + 'a spawned compute worker is named after its callback; anything ' + 'else means the merge ran somewhere unexpected', + ); + }); +} + +/// Writes the name of the isolate it ran on, so the caller can check it. +String _reportIsolateName((String?, String) input) => + Isolate.current.debugName ?? 'unnamed'; diff --git a/test/storage/channel_region_scope_store_test.dart b/test/storage/channel_region_scope_store_test.dart new file mode 100644 index 00000000..9ca28c8a --- /dev/null +++ b/test/storage/channel_region_scope_store_test.dart @@ -0,0 +1,60 @@ +// Epic #815 T C1: per-channel region-scope store. +// Device-key scoped (first 10 hex chars of the device public key), channel -> region name. + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/channel_region_scope_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _devA = 'aabbccddee0011223344'; +const _devB = 'ffeeddccbb0011223344'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + ChannelRegionScopeStore storeFor(String deviceKeyHex) { + final s = ChannelRegionScopeStore(); + s.setPublicKeyHex = deviceKeyHex; + return s; + } + + test('set / get / clear round-trip', () async { + final store = storeFor(_devA); + expect(await store.scopeFor(0), isNull); + await store.setScope(0, 'oki'); + expect(await store.scopeFor(0), 'oki'); + await store.clearScope(0); + expect(await store.scopeFor(0), isNull); + }); + + test('scopes are isolated per device key', () async { + await storeFor(_devA).setScope(2, 'oki'); + expect(await storeFor(_devB).scopeFor(2), isNull); + expect(await storeFor(_devA).scopeFor(2), 'oki'); + }); + + test('scopes are isolated per channel index', () async { + final store = storeFor(_devA); + await store.setScope(1, 'oki'); + expect(await store.scopeFor(3), isNull); + expect(await store.scopeFor(1), 'oki'); + }); + + test('survives a fresh store instance (persisted to prefs)', () async { + await storeFor(_devA).setScope(5, 'test'); + final reopened = storeFor(_devA); + expect(await reopened.scopeFor(5), 'test'); + }); + + test('with no device key set, reads null and writes are refused', () async { + final store = ChannelRegionScopeStore(); + await store.setScope(0, 'oki'); + expect(await store.scopeFor(0), isNull); + }); +} diff --git a/test/storage/contact_discovery_per_radio_test.dart b/test/storage/contact_discovery_per_radio_test.dart new file mode 100644 index 00000000..a9f449b7 --- /dev/null +++ b/test/storage/contact_discovery_per_radio_test.dart @@ -0,0 +1,84 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_discovery_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +// #754: discovered contacts are what THIS radio heard, so they must be scoped +// per radio like every other store, not shared across radios on one host. +void main() { + // Full-length keys; the store scopes on the first 10 hex, like production. + final keyA = 'aa' * 32; + final keyB = 'bb' * 32; + + late OffbandDatabase db; + + Contact node(int keyByte, String name) => Contact( + publicKey: Uint8List.fromList(List.filled(32, keyByte)), + receivedName: name, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 1, 1), + ); + + ContactDiscoveryStore store(String deviceKey) { + final s = ContactDiscoveryStore(); + s.setPublicKeyHex = deviceKey; + return s; + } + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + test( + 'radio A discoveries are not visible while radio B is connected', + () async { + await store( + keyA, + ).saveContacts([node(0x11, 'Alpha'), node(0x22, 'Bravo')]); + + expect((await store(keyA).loadContacts()).map((c) => c.name).toSet(), { + 'Alpha', + 'Bravo', + }); + expect(await store(keyB).loadContacts(), isEmpty); + }, + ); + + test( + 'an unset device key loads nothing, never the legacy shared blob', + () async { + await store(keyA).saveContacts([node(0x11, 'Alpha')]); + + final unscoped = ContactDiscoveryStore(); // no radio connected + expect(await unscoped.loadContacts(), isEmpty); + // A save with no radio connected must not write a shared blob either. + await unscoped.saveContacts([node(0x99, 'Ghost')]); + expect(await store(keyB).loadContacts(), isEmpty); + }, + ); + + test('each radio keeps its own discovery list across a switch', () async { + await store(keyA).saveContacts([node(0x11, 'Alpha')]); + await store(keyB).saveContacts([node(0x22, 'Bravo')]); + + expect((await store(keyA).loadContacts()).single.name, 'Alpha'); + expect((await store(keyB).loadContacts()).single.name, 'Bravo'); + }); +} diff --git a/test/storage/contact_naming_storage_test.dart b/test/storage/contact_naming_storage_test.dart new file mode 100644 index 00000000..c697bd23 --- /dev/null +++ b/test/storage/contact_naming_storage_test.dart @@ -0,0 +1,172 @@ +// Custom Name override for contacts (#750), storage half. +// +// Tests T7, T8, T9, T31 and T32 from the plan of record, +// docs/initiatives/standalone/750-contact-naming/PLAN.md. +// +// T32 is the data-loss guard that the plan correction on #750 added. Persisting +// `contact.name` instead of `contact.receivedName` would write a user's private +// label into the `name` key, and the next load would read it back as what the +// node calls itself. The real name would be gone permanently, with no advert +// able to restore it because the contact would already appear to have it. + +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/storage/contact_settings_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +const _radioKey = 'd549bbfbd003e580'; +const _contactKey = '00112233445566778899aabbccddeeff'; + +Contact _contact({required String receivedName, String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x22)), + receivedName: receivedName, + customName: customName, + type: 1, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +void main() { + late OffbandDatabase db; + late BlobStore blobs; + late ContactStore store; + late ContactSettingsStore settings; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + store = ContactStore()..setPublicKeyHex = _radioKey; + settings = ContactSettingsStore()..setPublicKeyHex = _radioKey; + }); + + tearDown(() async { + BlobStore.clearTestOverride(); + await db.close(); + }); + + group('contact_store and the received name (#750)', () { + test('T7 + a stored contact round-trips its received name', () async { + await store.saveContacts([_contact(receivedName: 'KQ4EZN-Repeater')]); + final loaded = await store.loadContacts(); + + expect(loaded.single.receivedName, 'KQ4EZN-Repeater'); + expect(loaded.single.name, 'KQ4EZN-Repeater'); + }); + + test('T8 - loading never invents a custom name', () async { + // If the migration populated customName from the stored name, every + // existing contact would silently become "renamed" and adverts would + // stop updating any of them. That is the worst failure in this epic and + // a positive-only suite would never see it. + await store.saveContacts([_contact(receivedName: 'KQ4EZN-Repeater')]); + final loaded = await store.loadContacts(); + + expect(loaded.single.customName, isNull); + }); + + test( + 'T32 - saving a renamed contact keeps the received name on disk', + () async { + // The data-loss guard. `contact.name` would be 'Chuck' here. + await store.saveContacts([ + _contact(receivedName: 'KQ4EZN-Repeater', customName: 'Chuck'), + ]); + final loaded = await store.loadContacts(); + + expect( + loaded.single.receivedName, + 'KQ4EZN-Repeater', + reason: 'the custom name must not be persisted as the received name', + ); + expect( + loaded.single.customName, + isNull, + reason: + 'contact_store does not own the custom name; a radio sync ' + 'rebuilds this record and would wipe it', + ); + }, + ); + + test( + 'T31 - a legacy row with no name loads as Unknown, not a crash', + () async { + // `receivedName` is non-nullable, and the pre-#750 reader had + // `json['name'] as String? ?? 'Unknown'`. Dropping that fallback during + // the rename would crash the load for anyone holding such a row. + await BlobStore.instance.write( + store.keyFor, + '[{"publicKey":"${base64OfKey()}","type":1,"pathLength":-1,"lastSeen":0}]', + ); + + final loaded = await store.loadContacts(); + + expect(loaded.single.receivedName, 'Unknown'); + expect(loaded.single.name, 'Unknown'); + }, + ); + }); + + group('contact_settings_store owns the custom name (#750)', () { + test('T9 + a custom name round-trips', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + + expect(await settings.loadCustomName(_contactKey), 'Chuck'); + }); + + test( + 'T9b - an unknown contact returns null, not an empty string', + () async { + expect(await settings.loadCustomName('ffffffffffffffff'), isNull); + }, + ); + + test('T9c + clearing with null removes it', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, null); + + expect(await settings.loadCustomName(_contactKey), isNull); + }); + + test( + 'T9d - saving an empty name stores nothing, not an empty string', + () async { + // The store is the second enforcement point for "empty counts as unset", + // so a UI that passes '' cannot leave a contact with a blank name. + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, ''); + + expect(await settings.loadCustomName(_contactKey), isNull); + }, + ); + + test('T9e - saving a whitespace-only name stores nothing', () async { + await settings.saveCustomName(_contactKey, 'Chuck'); + await settings.saveCustomName(_contactKey, ' '); + + expect(await settings.loadCustomName(_contactKey), isNull); + }); + + test('T9f + a custom name with emoji and CJK survives storage', () async { + const rich = 'ๆต‹่ฏ• ๐Ÿง™โ€โ™‚๏ธ Chuck'; + await settings.saveCustomName(_contactKey, rich); + + expect(await settings.loadCustomName(_contactKey), rich); + }); + }); +} + +/// Base64 of the 32-byte key used by [_contact], for the legacy-row fixture. +String base64OfKey() => 'IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI='; diff --git a/test/storage/contact_store_test.dart b/test/storage/contact_store_test.dart index e892177e..f9b09ed0 100644 --- a/test/storage/contact_store_test.dart +++ b/test/storage/contact_store_test.dart @@ -14,7 +14,7 @@ import 'package:shared_preferences/shared_preferences.dart'; /// wrote whatever was in memory over the stored contacts. Contact _contact(int keyByte, String name) => Contact( publicKey: Uint8List.fromList(List.filled(32, keyByte)), - name: name, + receivedName: name, type: 1, pathLength: -1, path: Uint8List(0), diff --git a/test/storage/message_rows_migration_test.dart b/test/storage/message_rows_migration_test.dart new file mode 100644 index 00000000..7a87ff7f --- /dev/null +++ b/test/storage/message_rows_migration_test.dart @@ -0,0 +1,245 @@ +import 'dart:convert'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #920 B3: moving a history blob into rows. The gate matters more than the +/// move: every failure path here has to leave the blob as the source of truth, +/// because the blob is the only copy of someone's messages. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + String blobOf(List ids) => jsonEncode([ + for (final i in ids) {'messageId': 'id$i', 'timestamp': 1000 + i}, + ]); + + test('moves a blob into rows and marks the key migrated', () async { + await blobs.write('k', blobOf([1, 2, 3])); + + final ok = await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(ok, isTrue); + expect(await blobs.messageRowCount('k'), 3); + expect(await blobs.isOnMessageRows('k'), isTrue); + }); + + test('NEVER deletes the blob, even on a verified match', () async { + final original = blobOf([1, 2]); + await blobs.write('k', original); + + await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect( + await blobs.read('k'), + original, + reason: 'reclaiming the space is a separate owner-gated step (#920)', + ); + }); + + test('rows carry the payload through unchanged', () async { + await blobs.write('k', blobOf([7])); + + await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(await blobs.messagePayloads('k'), [ + '{"messageId":"id7","timestamp":1007}', + ]); + }); + + test('a second call is a no-op and does not re-import', () async { + await blobs.write('k', blobOf([1, 2])); + await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + // Something arrives and is saved as a row after the migration. + await blobs.upsertMessageRows('k', const [ + MessageRowInput(mergeKey: 'id:new', timestampMs: 9999, payload: '{}'), + ]); + final ok = await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(ok, isTrue); + expect( + await blobs.messageRowCount('k'), + 3, + reason: 'a repeat migration must not touch the rows that exist', + ); + }); + + test('an absent blob marks the key migrated with no rows', () async { + final ok = await blobs.ensureMessageRowsMigrated('fresh', rowsFromTestBlob); + + expect(ok, isTrue); + expect(await blobs.isOnMessageRows('fresh'), isTrue); + expect(await blobs.messageRowCount('fresh'), 0); + }); + + test('an empty blob marks the key migrated with no rows', () async { + await blobs.write('k', ''); + + final ok = await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(ok, isTrue); + expect(await blobs.isOnMessageRows('k'), isTrue); + }); + + group('failure paths all keep the blob authoritative', () { + test('an undecodable blob refuses the migration', () async { + const corrupt = '{not json at all'; + await blobs.write('k', corrupt); + + final ok = await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(ok, isFalse); + expect(await blobs.isOnMessageRows('k'), isFalse); + expect(await blobs.read('k'), corrupt); + expect(await blobs.messageRowCount('k'), 0); + }); + + test('a decoder that throws refuses the migration', () async { + await blobs.write('k', blobOf([1])); + + final ok = await blobs.ensureMessageRowsMigrated('k', _alwaysThrows); + + expect(ok, isFalse); + expect(await blobs.isOnMessageRows('k'), isFalse); + expect(await blobs.read('k'), blobOf([1])); + }); + + test('a decoder that drops records refuses on the count gate', () async { + // The case the readback gate exists for: the decode "succeeded" but + // produced fewer messages than the blob held. Marking this migrated + // would silently shorten someone's history. + await blobs.write('k', blobOf([1, 2, 3, 4, 5])); + + final ok = await blobs.ensureMessageRowsMigrated('k', _dropsOneRecord); + + expect( + ok, + isFalse, + reason: 'fewer rows than records must never be accepted', + ); + expect(await blobs.isOnMessageRows('k'), isFalse); + expect( + await blobs.read('k'), + blobOf([1, 2, 3, 4, 5]), + reason: 'the blob is the only copy of those messages', + ); + }); + + test('a refused key can still be read from its blob afterwards', () async { + await blobs.write('k', blobOf([1, 2])); + await blobs.ensureMessageRowsMigrated('k', _alwaysThrows); + + // The whole point of refusing rather than throwing: the app keeps + // working on the old path. + expect(await blobs.read('k'), blobOf([1, 2])); + expect(await blobs.isOnMessageRows('k'), isFalse); + }); + }); + + test('duplicate identities in a blob are deduped, not refused', () async { + // A blob built by the old merge should not contain duplicates, but the + // legacy-key adoption path could have produced them. Comparing against + // the DISTINCT count means that does not read as data loss. + await blobs.write( + 'k', + jsonEncode([ + {'messageId': 'id1', 'timestamp': 1001}, + {'messageId': 'id1', 'timestamp': 1001}, + {'messageId': 'id2', 'timestamp': 1002}, + ]), + ); + + final ok = await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + expect(ok, isTrue); + expect(await blobs.messageRowCount('k'), 2); + }); + + test('the marker survives a reopen of the same database', () async { + await blobs.write('k', blobOf([1])); + await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + + // Same database, fresh in-memory cache: the marker has to be on disk. + blobs.resetMigratedKeyCache(); + + expect(await blobs.isOnMessageRows('k'), isTrue); + }); + + test('an unreadable marker treats every key as unmigrated', () async { + await blobs.write('k', blobOf([1])); + await blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob); + await blobs.write(BlobStore.migratedMarkerKey, 'not json'); + blobs.resetMigratedKeyCache(); + + // Safe direction: the blobs are all still there, so re-reading them is + // correct, where trusting a corrupt marker would hide histories. + expect(await blobs.isOnMessageRows('k'), isFalse); + }); + + test('migrating one key does not mark or touch another', () async { + await blobs.write('a', blobOf([1, 2])); + await blobs.write('b', blobOf([3])); + + await blobs.ensureMessageRowsMigrated('a', rowsFromTestBlob); + + expect(await blobs.isOnMessageRows('b'), isFalse); + expect(await blobs.messageRowCount('b'), 0); + expect(await blobs.read('b'), blobOf([3])); + }); + + test('concurrent calls on one key import it exactly once', () async { + await blobs.write('k', blobOf([1, 2, 3])); + + final results = await Future.wait([ + blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob), + blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob), + blobs.ensureMessageRowsMigrated('k', rowsFromTestBlob), + ]); + + expect(results, everyElement(isTrue)); + expect(await blobs.messageRowCount('k'), 3); + }); +} + +/// Stands in for a store's real decoder. Top-level so `compute` can send it. +List rowsFromTestBlob(String blobJson) { + return (jsonDecode(blobJson) as List) + .map((e) => e as Map) + .map( + (m) => MessageRowInput( + mergeKey: 'id:${m['messageId']}', + timestampMs: m['timestamp'] as int, + payload: jsonEncode(m), + ), + ) + .toList(); +} + +List _alwaysThrows(String blobJson) => + throw StateError('decoder blew up'); + +/// Silently loses the last record, which is exactly what the readback gate is +/// there to catch. +List _dropsOneRecord(String blobJson) { + final all = rowsFromTestBlob(blobJson); + return all.sublist(0, all.length - 1); +} diff --git a/test/storage/message_rows_schema_migration_test.dart b/test/storage/message_rows_schema_migration_test.dart new file mode 100644 index 00000000..ff181b59 --- /dev/null +++ b/test/storage/message_rows_schema_migration_test.dart @@ -0,0 +1,129 @@ +import 'package:drift/drift.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #920: schema 1 -> 2 adds `message_records` and must not touch a single byte +/// of `stored_blobs`. Every existing install is on schema 1 with its whole +/// history in there, so this is the test that stands between a schema bump and +/// 41 MB of someone's messages. +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDown(BlobStore.clearTestOverride); + + /// A database that looks exactly like one an older build left behind: the v1 + /// table, real data in it, and `user_version` still 1 so drift runs the + /// upgrade rather than creating everything fresh. + QueryExecutor v1DatabaseWith(Map blobs) { + return NativeDatabase.memory( + setup: (raw) { + raw.execute( + 'CREATE TABLE stored_blobs (' + 'key TEXT NOT NULL, ' + 'value TEXT NOT NULL, ' + "updated_at INTEGER NOT NULL DEFAULT (CAST(strftime('%s', " + "CURRENT_TIMESTAMP) AS INTEGER)), " + 'PRIMARY KEY (key))', + ); + for (final entry in blobs.entries) { + final escaped = entry.value.replaceAll("'", "''"); + raw.execute( + "INSERT INTO stored_blobs (key, value) VALUES ('${entry.key}', " + "'$escaped')", + ); + } + raw.execute('PRAGMA user_version = 1'); + }, + ); + } + + test('upgrading from 1 to 2 keeps every blob byte-identical', () async { + const history = '[{"messageId":"id1","text":"don\'t lose me"}]'; + final db = OffbandDatabase( + v1DatabaseWith({ + 'channel_messages_abc0123456psk_dead': history, + 'contacts': '[{"name":"someone"}]', + }), + ); + final blobs = BlobStore(db); + + // Opening is lazy; the first query is what triggers the migration. + expect(await blobs.read('channel_messages_abc0123456psk_dead'), history); + expect(await blobs.read('contacts'), '[{"name":"someone"}]'); + + await db.close(); + }); + + test('upgrading from 1 to 2 creates a usable message_records', () async { + final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'})); + final blobs = BlobStore(db); + + await blobs.upsertMessageRows('k', const [ + MessageRowInput(mergeKey: 'id:a', timestampMs: 1, payload: '{"a":1}'), + ]); + + expect(await blobs.messagePayloads('k'), ['{"a":1}']); + await db.close(); + }); + + test('the upgraded database reports schema 2', () async { + final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'})); + + // Forces the open, and therefore the migration. + await BlobStore(db).read('contacts'); + final version = await db + .customSelect('PRAGMA user_version') + .getSingle() + .then((r) => r.data.values.first as int); + + expect(version, 2); + await db.close(); + }); + + test('the store-key index exists after an upgrade', () async { + final db = OffbandDatabase(v1DatabaseWith({'contacts': '[]'})); + await BlobStore(db).read('contacts'); + + final names = await db + .customSelect( + "SELECT name FROM sqlite_master WHERE type = 'index' " + "AND tbl_name = 'message_records'", + ) + .get(); + + expect( + names.map((r) => r.data['name']), + contains('idx_message_records_store_ts'), + reason: 'without it, ORDER BY timestamp_ms scans the whole table', + ); + await db.close(); + }); + + test('a database created fresh at schema 2 also gets the index', () async { + // onUpgrade does not run for a new database, so the index has to be + // created in beforeOpen as well or a fresh install silently loses it. + final db = OffbandDatabase(NativeDatabase.memory()); + await BlobStore(db).read('anything'); + + final names = await db + .customSelect( + "SELECT name FROM sqlite_master WHERE type = 'index' " + "AND tbl_name = 'message_records'", + ) + .get(); + + expect( + names.map((r) => r.data['name']), + contains('idx_message_records_store_ts'), + ); + await db.close(); + }); +} diff --git a/test/storage/message_rows_test.dart b/test/storage/message_rows_test.dart new file mode 100644 index 00000000..4931be5b --- /dev/null +++ b/test/storage/message_rows_test.dart @@ -0,0 +1,173 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #920 B1: one row per message. These pin the properties the stores and the +/// migration are about to rely on, in particular that an upsert is scoped to +/// its store key and deduped by merge key exactly as the blob merge was. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + MessageRowInput row(int i, {String? text, String? id}) => MessageRowInput( + mergeKey: 'id:${id ?? 'id$i'}', + timestampMs: 1000 + i, + payload: '{"messageId":"${id ?? 'id$i'}","text":"${text ?? 'm$i'}"}', + ); + + test('stores and reads back in timestamp order', () async { + // Inserted out of order on purpose: ordering must come from SQLite, not + // from insertion sequence. + await blobs.upsertMessageRows('k', [row(9), row(2), row(5)]); + + final out = await blobs.messagePayloads('k'); + + expect(out, [ + '{"messageId":"id2","text":"m2"}', + '{"messageId":"id5","text":"m5"}', + '{"messageId":"id9","text":"m9"}', + ]); + }); + + test('upsert on the same merge key updates, never duplicates', () async { + await blobs.upsertMessageRows('k', [row(1, text: 'original')]); + await blobs.upsertMessageRows('k', [row(1, text: 'edited')]); + + expect(await blobs.messageRowCount('k'), 1); + expect(await blobs.messagePayloads('k'), [ + '{"messageId":"id1","text":"edited"}', + ]); + }); + + test('rows are scoped to their store key', () async { + // The key carries all the per-radio and per-channel scoping (#194, #472), + // so a leak across keys here would be a history bleed between radios. + await blobs.upsertMessageRows('radio_a', [row(1), row(2)]); + await blobs.upsertMessageRows('radio_b', [row(1)]); + + expect(await blobs.messageRowCount('radio_a'), 2); + expect(await blobs.messageRowCount('radio_b'), 1); + expect(await blobs.messagePayloads('radio_b'), [ + '{"messageId":"id1","text":"m1"}', + ]); + }); + + test('the same merge key under two store keys is two messages', () async { + await blobs.upsertMessageRows('a', [row(1, text: 'in a')]); + await blobs.upsertMessageRows('b', [row(1, text: 'in b')]); + + expect(await blobs.messagePayloads('a'), [ + '{"messageId":"id1","text":"in a"}', + ]); + expect(await blobs.messagePayloads('b'), [ + '{"messageId":"id1","text":"in b"}', + ]); + }); + + test('limit returns the NEWEST n, still oldest-first', () async { + await blobs.upsertMessageRows('k', [for (var i = 1; i <= 10; i++) row(i)]); + + final out = await blobs.messagePayloads('k', limit: 3); + + expect(out, [ + '{"messageId":"id8","text":"m8"}', + '{"messageId":"id9","text":"m9"}', + '{"messageId":"id10","text":"m10"}', + ]); + }); + + test('limit with offset pages backwards through history', () async { + await blobs.upsertMessageRows('k', [for (var i = 1; i <= 10; i++) row(i)]); + + final page2 = await blobs.messagePayloads('k', limit: 3, offset: 3); + + expect(page2, [ + '{"messageId":"id5","text":"m5"}', + '{"messageId":"id6","text":"m6"}', + '{"messageId":"id7","text":"m7"}', + ]); + }); + + test('deleting one row leaves the rest alone', () async { + await blobs.upsertMessageRows('k', [row(1), row(2), row(3)]); + + await blobs.deleteMessageRow('k', 'id:id2'); + + expect(await blobs.messagePayloads('k'), [ + '{"messageId":"id1","text":"m1"}', + '{"messageId":"id3","text":"m3"}', + ]); + }); + + test('deleting one row does not touch another store key', () async { + await blobs.upsertMessageRows('a', [row(1)]); + await blobs.upsertMessageRows('b', [row(1)]); + + await blobs.deleteMessageRow('a', 'id:id1'); + + expect(await blobs.messageRowCount('a'), 0); + expect(await blobs.messageRowCount('b'), 1); + }); + + test('clearing a key removes only that key', () async { + await blobs.upsertMessageRows('a', [row(1), row(2)]); + await blobs.upsertMessageRows('b', [row(1)]); + + await blobs.deleteMessageRows('a'); + + expect(await blobs.messageRowCount('a'), 0); + expect(await blobs.messageRowCount('b'), 1); + }); + + test('messageStoreKeys lists keys that have rows, deduped', () async { + await blobs.upsertMessageRows('a', [row(1), row(2)]); + await blobs.upsertMessageRows('b', [row(1)]); + + expect(await blobs.messageStoreKeys(), {'a', 'b'}); + }); + + test('an empty upsert is a no-op, not an error', () async { + await blobs.upsertMessageRows('k', const []); + + expect(await blobs.messageRowCount('k'), 0); + }); + + test('count and payloads are empty for an unknown key', () async { + expect(await blobs.messageRowCount('never-seen'), 0); + expect(await blobs.messagePayloads('never-seen'), isEmpty); + }); + + test('message rows and the blob for the same key coexist', () async { + // The migration is additive: during and after it, the blob is still there + // and must not be disturbed by anything on the row path (#920). + await blobs.write('k', '[{"messageId":"old"}]'); + await blobs.upsertMessageRows('k', [row(1)]); + + expect(await blobs.read('k'), '[{"messageId":"old"}]'); + expect(await blobs.messageRowCount('k'), 1); + + await blobs.deleteMessageRows('k'); + expect( + await blobs.read('k'), + '[{"messageId":"old"}]', + reason: 'clearing rows must never touch the retained blob', + ); + }); +} diff --git a/test/storage/migration_readback_gate_test.dart b/test/storage/migration_readback_gate_test.dart new file mode 100644 index 00000000..93309954 --- /dev/null +++ b/test/storage/migration_readback_gate_test.dart @@ -0,0 +1,182 @@ +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #952: the migration's readback gate asserts a superset, not equality. +/// +/// Found on the owner's live database while working #943. Four of his store +/// keys held rows whose `merge_key` did not appear in their blob (1, 3, 7 and +/// 5 of them), so the old gate's comparison of TOTALS could never come level +/// again: nothing removes those rows and the frozen blob can never come to +/// contain them. Every attempt refused, forever, and his two largest channels +/// (6,313 and 5,648 messages) were among them, still re-encoding their whole +/// history on every save. +/// +/// The invariant that was actually wanted is "no record from the blob is +/// missing from rows". These tests pin that, and that it still catches the +/// short insert the step exists for. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + const key = 'channel_messages_aaaaaaaaaapsk_deadbeef'; + + /// A channel history blob. Only `messageId` matters here: both stores' merge + /// key is `id:` whenever it is non-empty. + String blobWith(List ids) => + '[${ids.map((id) => '{"messageId":"$id","text":"t-$id","timestamp":1}').join(',')}]'; + + List toRows(String json) { + final ids = RegExp( + r'"messageId":"([^"]+)"', + ).allMatches(json).map((m) => m.group(1)!).toList(); + return ids + .map( + (id) => MessageRowInput( + mergeKey: 'id:$id', + timestampMs: 1, + payload: '{"messageId":"$id"}', + ), + ) + .toList(); + } + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + test('a clean key migrates, so the fixture itself is sound', () async { + await blobs.write(key, blobWith(['a', 'b', 'c'])); + + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + expect(await blobs.isOnMessageRows(key), isTrue); + expect(await blobs.messageRowCount(key), 3); + }); + + group('rows the blob does not contain no longer block the migration', () { + test('one extra row still migrates', () async { + await blobs.write(key, blobWith(['a', 'b', 'c'])); + // The state the owner's four keys were in. Under the old gate this + // compared 4 stored rows against 3 blob records and refused. + await blobs.upsertMessageRows(key, const [ + MessageRowInput(mergeKey: 'id:newer', timestampMs: 2, payload: '{}'), + ]); + + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + expect(await blobs.isOnMessageRows(key), isTrue); + }); + + test('the extra row is kept, not discarded', () async { + await blobs.write(key, blobWith(['a', 'b', 'c'])); + await blobs.upsertMessageRows(key, const [ + MessageRowInput( + mergeKey: 'id:newer', + timestampMs: 2, + payload: '{"messageId":"newer"}', + ), + ]); + await blobs.ensureMessageRowsMigrated(key, toRows); + + // Accepting the migration must not lose the message that caused the + // mismatch: it is newer than the blob, not spurious. + expect(await blobs.messageMergeKeys(key), contains('id:newer')); + expect(await blobs.messageRowCount(key), 4); + }); + + test('his worst key in miniature: many records, a few extra', () async { + await blobs.write(key, blobWith(List.generate(60, (i) => 'm$i'))); + await blobs.upsertMessageRows(key, const [ + MessageRowInput(mergeKey: 'id:x1', timestampMs: 9, payload: '{}'), + MessageRowInput(mergeKey: 'id:x2', timestampMs: 9, payload: '{}'), + MessageRowInput(mergeKey: 'id:x3', timestampMs: 9, payload: '{}'), + MessageRowInput(mergeKey: 'id:x4', timestampMs: 9, payload: '{}'), + MessageRowInput(mergeKey: 'id:x5', timestampMs: 9, payload: '{}'), + ]); + + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + expect(await blobs.messageRowCount(key), 65); + }); + + test('a key stuck under the old gate recovers on next access', () async { + // The outcome that matters for his install: no healing migration is + // needed, the four keys migrate normally once the comparison is right. + await blobs.write(key, blobWith(['a', 'b', 'c'])); + await blobs.upsertMessageRows(key, const [ + MessageRowInput(mergeKey: 'id:newer', timestampMs: 2, payload: '{}'), + ]); + expect(await blobs.isOnMessageRows(key), isFalse); + + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + expect(await blobs.isOnMessageRows(key), isTrue); + }); + }); + + group('the gate can still fail', () { + test('a short insert is refused and the key stays on the blob', () async { + // Proving the step still does its job. A store whose insert silently + // drops a row is exactly what the readback exists to catch, and the + // superset check must not have traded that away. + final lossy = _DropsOneRow(db); + BlobStore.overrideForTest(lossy); + await lossy.write(key, blobWith(['a', 'b', 'c'])); + + expect( + await lossy.ensureMessageRowsMigrated(key, toRows), + isFalse, + reason: 'one of the three blob records never reached a row', + ); + expect(await lossy.isOnMessageRows(key), isFalse); + }); + + test('a lossy converter is refused before anything is written', () async { + // The other half of the loop (step 2), unchanged by #952: the blob's + // element count is measured independently of the converter. + await blobs.write(key, blobWith(['a', 'b', 'c'])); + + expect( + await blobs.ensureMessageRowsMigrated(key, (json) { + final all = toRows(json); + return all.take(all.length - 1).toList(); + }), + isFalse, + ); + expect(await blobs.messageRowCount(key), 0); + }); + }); + + test('no message is lost either way: the blob is retained', () async { + final history = blobWith(['a', 'b', 'c']); + await blobs.write(key, history); + await blobs.upsertMessageRows(key, const [ + MessageRowInput(mergeKey: 'id:newer', timestampMs: 2, payload: '{}'), + ]); + await blobs.ensureMessageRowsMigrated(key, toRows); + + expect(await blobs.read(key), history); + }); +} + +/// A [BlobStore] whose row insert silently drops the first row, standing in +/// for a short or partially failed write. +class _DropsOneRow extends BlobStore { + _DropsOneRow(super.db); + + @override + Future upsertMessageRows( + String storeKey, + Iterable rows, + ) => super.upsertMessageRows(storeKey, rows.skip(1)); +} diff --git a/test/storage/radio_isolation_matrix_test.dart b/test/storage/radio_isolation_matrix_test.dart new file mode 100644 index 00000000..f227726c --- /dev/null +++ b/test/storage/radio_isolation_matrix_test.dart @@ -0,0 +1,309 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/models/delivery_observation.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/models/path_history.dart'; +import 'package:meshcore_open/services/storage_service.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/channel_order_store.dart'; +import 'package:meshcore_open/storage/channel_store.dart'; +import 'package:meshcore_open/storage/contact_discovery_store.dart'; +import 'package:meshcore_open/storage/contact_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:meshcore_open/storage/scoping_inventory.dart'; +import 'package:meshcore_open/storage/unread_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #940, Feature #853's Integration Testing Epic. +/// +/// Epic A's inventory declares a verdict per surface. Epics B, C and D fixed +/// the holes. This proves the whole thing end to end against the bar #853 +/// actually set: +/// +/// "the datum is isolated per radio, and a second radio does not inherit +/// the first's copy, across a radio switch AND an app restart" +/// +/// A "restart" here is a fresh store object reading the same database, which +/// is what a restart does to storage. The hardware half, two real radios on +/// the owner's install, is E2 and only he can run it. +void main() { + late OffbandDatabase db; + + const radioA = 'aaaaaaaaaa'; + const radioB = 'bbbbbbbbbb'; + // The stores truncate to 10 hex, so pad past that to exercise the setter. + String key(String r) => r * 3; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + BlobStore.overrideForTest(BlobStore(db)); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + Contact contact(String name) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 7)), + receivedName: name, + type: 1, + pathLength: 0, + path: Uint8List(0), + lastSeen: DateTime.fromMillisecondsSinceEpoch(1700000000000), + ); + + ChannelMessage chanMsg(String text) => ChannelMessage( + senderName: 's', + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + isOutgoing: false, + channelIndex: 0, + messageId: 'id-$text', + ); + + Message dm(String text) => Message( + senderKey: Uint8List.fromList(const [1, 2, 3, 4]), + text: text, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + isOutgoing: false, + messageId: 'id-$text', + ); + + /// Writes radio A's datum, switches to radio B, asserts B sees nothing, then + /// switches back and asserts A still has it. That is the full bar: isolation + /// is not deletion. + /// + /// [readFresh] builds a NEW store each time, which is what an app restart + /// does to storage, so every case covers the switch and the restart at once. + Future expectIsolated({ + required String label, + required Future Function(String radio) write, + required Future Function(String radio) readFresh, + required bool Function(T) hasData, + }) async { + await write(key(radioA)); + + expect( + hasData(await readFresh(key(radioA))), + isTrue, + reason: '$label: radio A must see its own datum', + ); + expect( + hasData(await readFresh(key(radioB))), + isFalse, + reason: '$label: radio B MUST NOT inherit radio A\'s datum', + ); + expect( + hasData(await readFresh(key(radioA))), + isTrue, + reason: + '$label: switching back must restore A. Isolation is not ' + 'deletion', + ); + } + + group('every per-radio surface, across a switch and a restart', () { + test('channel messages', () async { + await expectIsolated>( + label: 'channel_messages_', + write: (r) async => (ChannelMessageStore()..setPublicKeyHex = r) + .saveChannelMessages(0, [chanMsg('A only')]), + readFresh: (r) => + (ChannelMessageStore()..setPublicKeyHex = r).loadChannelMessages(0), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('direct messages', () async { + await expectIsolated>( + label: 'messages_', + write: (r) async => (MessageStore()..setPublicKeyHex = r).saveMessages( + 'cafebabe', + [dm('A only')], + ), + readFresh: (r) => + (MessageStore()..setPublicKeyHex = r).loadMessages('cafebabe'), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('contacts', () async { + await expectIsolated>( + label: 'contacts', + write: (r) async => (ContactStore()..setPublicKeyHex = r).saveContacts([ + contact('A only'), + ]), + readFresh: (r) => (ContactStore()..setPublicKeyHex = r).loadContacts(), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('discovered contacts (#754)', () async { + await expectIsolated>( + label: 'discovered_contacts', + write: (r) async => (ContactDiscoveryStore()..setPublicKeyHex = r) + .saveContacts([contact('A heard this')]), + readFresh: (r) => + (ContactDiscoveryStore()..setPublicKeyHex = r).loadContacts(), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('channels', () async { + await expectIsolated>( + label: 'channels', + write: (r) async => (ChannelStore()..setPublicKeyHex = r).saveChannels([ + Channel(index: 0, name: 'A only', psk: Uint8List(16)), + ]), + readFresh: (r) => (ChannelStore()..setPublicKeyHex = r).loadChannels(), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('channel order', () async { + await expectIsolated>( + label: 'channel_order_', + write: (r) async => + (ChannelOrderStore()..setPublicKeyHex = r).saveChannelOrder([3, 1]), + readFresh: (r) => + (ChannelOrderStore()..setPublicKeyHex = r).loadChannelOrder(), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('unread counts', () async { + await expectIsolated>( + label: 'contact_unread_count', + write: (r) async { + // saveContactUnreadCount is debounced, so the flush is what makes + // it durable. Without it this would test the in-memory pending map. + final store = UnreadStore()..setPublicKeyHex = r; + store.saveContactUnreadCount({'c': 3}); + await store.flush(); + store.dispose(); + }, + readFresh: (r) => + (UnreadStore()..setPublicKeyHex = r).loadContactUnreadCount(), + hasData: (v) => v.isNotEmpty, + ); + }); + + test('path history (#854)', () async { + await expectIsolated( + label: 'path_history_', + write: (r) async => + (StorageService()..setPublicKeyHex = r).savePathHistory( + 'cafebabe', + ContactPathHistory( + contactPubKeyHex: 'cafebabe', + recentPaths: [ + PathRecord( + hopCount: 2, + tripTimeMs: 500, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000), + wasFloodDiscovery: false, + pathBytes: const [1], + successCount: 1, + failureCount: 0, + ), + ], + ), + ), + readFresh: (r) => + (StorageService()..setPublicKeyHex = r).loadPathHistory('cafebabe'), + hasData: (v) => v != null, + ); + }); + + test('delivery observations (#856)', () async { + await expectIsolated>( + label: 'delivery_observations', + write: (r) async => + (StorageService()..setPublicKeyHex = r).saveDeliveryObservations([ + DeliveryObservation( + contactKey: 'cafebabe', + pathLength: 3, + messageBytes: 100, + secondsSinceLastRx: 10, + isFlood: false, + deliveryMs: 2500, + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000), + ), + ]), + readFresh: (r) => + (StorageService()..setPublicKeyHex = r).loadDeliveryObservations(), + hasData: (v) => v.isNotEmpty, + ); + }); + }); + + group('no radio connected means no data, for every surface', () { + // Epic D's fail-closed property, across the board rather than one store. + test('an unset key reads nothing even with data stored', () async { + await (ChannelMessageStore()..setPublicKeyHex = key(radioA)) + .saveChannelMessages(0, [chanMsg('A only')]); + await (MessageStore()..setPublicKeyHex = key(radioA)).saveMessages( + 'cafebabe', + [dm('A only')], + ); + await (ContactStore()..setPublicKeyHex = key(radioA)).saveContacts([ + contact('A only'), + ]); + + expect( + await (ChannelMessageStore()..setPublicKeyHex = '').loadChannelMessages( + 0, + ), + isEmpty, + ); + expect( + await (MessageStore()..setPublicKeyHex = '').loadMessages('cafebabe'), + isEmpty, + ); + expect( + await (ContactStore()..setPublicKeyHex = '').loadContacts(), + isEmpty, + ); + }); + }); + + group('the Feature\'s own closure condition', () { + test('no surface is left unclassified and no hole remains', () async { + // #853: "the Feature closes when every store has a verified scoping + // verdict and no hole remains." Both halves, asserted. + final holes = storageSurfaces.where( + (s) => s.verdict == ScopingVerdict.knownHole, + ); + expect( + holes.map((s) => s.key), + isEmpty, + reason: 'a remaining hole means this Feature is not done', + ); + + for (final s in storageSurfaces) { + expect(s.reason.trim(), isNotEmpty, reason: '${s.key} has no reason'); + } + + // And the per-radio count is not quietly zero. + expect( + storageSurfaces + .where((s) => s.verdict == ScopingVerdict.perRadio) + .length, + greaterThanOrEqualTo(14), + reason: 'sanity: the per-radio surfaces are the point of the Feature', + ); + }); + }); +} diff --git a/test/storage/schema_downgrade_test.dart b/test/storage/schema_downgrade_test.dart new file mode 100644 index 00000000..e2c218bb --- /dev/null +++ b/test/storage/schema_downgrade_test.dart @@ -0,0 +1,257 @@ +import 'dart:io'; + +import 'package:drift/drift.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #943: what happens when a build opens a database left by a NEWER build. +/// +/// #917's plan claimed a downgrade still works because the blobs are retained. +/// The owner hit the opposite on 2026-10-20: his pre-#917 install would not +/// start against his migrated database. +/// +/// The issue's own explanation was wrong. drift has no "newer schema" refusal, +/// so the first group here pins what actually governs this. The owner's +/// decision on 2026-10-22 was that downgrades stay unsupported and must fail +/// loudly rather than silently, which the second group pins. +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + }); + + tearDown(BlobStore.clearTestOverride); + + /// This build's schema, and one past it. Derived rather than written as a + /// literal: hard-coding 3 here would turn these tests green-but-meaningless + /// the day the real schema becomes 3, which is exactly when they matter. + /// + /// Read in setUpAll and closed straight away, so the probe never overlaps + /// with the databases the tests build (drift warns about two live instances + /// of one class, and warnings in test output are how real ones get missed). + late final int current; + late final int future; + + setUpAll(() async { + final probe = OffbandDatabase(NativeDatabase.memory()); + current = probe.schemaVersion; + future = current + 1; + await probe.close(); + }); + + /// A database shaped like one a build at [userVersion] left behind, with + /// both of today's tables and real data in the blob table. + QueryExecutor databaseAtVersion( + int userVersion, + Map blobs, { + File? file, + }) { + void setup(dynamic raw) { + raw.execute( + 'CREATE TABLE stored_blobs (' + 'key TEXT NOT NULL, ' + 'value TEXT NOT NULL, ' + "updated_at INTEGER NOT NULL DEFAULT (CAST(strftime('%s', " + "CURRENT_TIMESTAMP) AS INTEGER)), " + 'PRIMARY KEY (key))', + ); + raw.execute( + 'CREATE TABLE message_records (' + 'store_key TEXT NOT NULL, ' + 'merge_key TEXT NOT NULL, ' + 'timestamp_ms INTEGER NOT NULL, ' + 'payload TEXT NOT NULL, ' + 'PRIMARY KEY (store_key, merge_key))', + ); + for (final entry in blobs.entries) { + final escaped = entry.value.replaceAll("'", "''"); + raw.execute( + "INSERT INTO stored_blobs (key, value) VALUES ('${entry.key}', " + "'$escaped')", + ); + } + raw.execute('PRAGMA user_version = $userVersion'); + } + + return file == null + ? NativeDatabase.memory(setup: setup) + : NativeDatabase(file, setup: setup); + } + + Future userVersionOf(OffbandDatabase db) => db + .customSelect('PRAGMA user_version') + .getSingle() + .then((r) => r.data.values.first as int); + + group('drift dispatches a downgrade through onUpgrade', () { + test('a newer user_version is reported as hadUpgrade, not refused', () { + // The fact the whole question rests on. drift has no "newer schema" + // refusal: it compares the two numbers for INEQUALITY and routes both + // directions into onUpgrade ("Schema version upgrades and downgrades + // will both be run here"). So whether a downgrade is caught is decided + // by OUR onUpgrade, not by drift. + final downgrade = OpeningDetails(future, current); + expect(downgrade.hadUpgrade, isTrue); + expect(downgrade.wasCreated, isFalse); + }); + + test('a strategy with no onUpgrade throws, which is what bit #943', () { + // The pre-#917 build declared schemaVersion 1 and NO migration getter, + // so it got exactly this default. That, and not a drift version check, + // is why the owner's old install would not open his schema-2 database. + final db = OffbandDatabase(NativeDatabase.memory()); + addTearDown(db.close); + + expect( + () => MigrationStrategy().onUpgrade(Migrator(db), 2, 1), + throwsA(isA()), + ); + }); + }); + + group('this build refuses a database from a future schema', () { + test('opening one throws OffbandSchemaDowngrade', () async { + final db = OffbandDatabase( + databaseAtVersion(future, {'contacts': '[{"name":"someone"}]'}), + ); + addTearDown(() async { + try { + await db.close(); + } catch (_) {} + }); + + await expectLater( + BlobStore(db).read('contacts'), + throwsA(isA()), + ); + }); + + test('and the message names both schemas and what to do', () { + // Deliberately not `current`/`future`: this checks the message renders + // whatever it is given, so fixed numbers unrelated to today's schema + // make a wrong substitution visible. + const e = OffbandSchemaDowngrade( + from: 7, + to: 6, + databasePath: r'C:\somewhere\offband_store.sqlite', + ); + final text = e.toString(); + + expect(text, contains('schema 7')); + expect(text, contains('only understands 6')); + expect(text, contains('one-way')); + expect(text, contains(r'C:\somewhere\offband_store.sqlite')); + }); + + test('a resolved path is optional, so web still gets a message', () { + const e = OffbandSchemaDowngrade(from: 9, to: 2); + expect(e.toString(), contains('schema 9')); + expect(e.toString(), isNot(contains('Database:'))); + }); + + test('and user_version is NOT rewritten backwards', () async { + // The point of refusing rather than falling through. drift writes its + // own schemaVersion only after migrations have run, so throwing keeps + // the database's record of having been on a newer build. Before #943 + // this came back 2 and that evidence was gone. + final dir = await Directory.systemTemp.createTemp('offband_downgrade'); + // Swallowed deliberately: if this test fails the database is left open, + // Windows keeps the file locked, and a throwing cleanup would replace + // the real failure with a PathAccessException. + addTearDown(() async { + try { + await dir.delete(recursive: true); + } catch (_) {} + }); + final file = File('${dir.path}/offband_store.sqlite'); + + final db = OffbandDatabase( + databaseAtVersion(future, {'contacts': '[]'}, file: file), + ); + await expectLater( + BlobStore(db).read('contacts'), + throwsA(isA()), + ); + try { + await db.close(); + } catch (_) {} + + // Read it back on a connection that declares no schema of its own. + final raw = NativeDatabase(file); + final probe = _Probe(raw, future); + addTearDown(probe.close); + expect( + await probe + .customSelect('PRAGMA user_version') + .getSingle() + .then((r) => r.data.values.first as int), + future, + reason: 'the refusal must leave the version alone', + ); + }); + }); + + group('a normal upgrade still behaves', () { + test('an equal version is neither a create nor an upgrade', () { + // Guards the group above: refusing a downgrade only means something if + // a matched version takes neither branch. + const same = OpeningDetails(2, 2); + expect(same.hadUpgrade, isFalse); + expect(same.wasCreated, isFalse); + }); + + test( + 'a fresh database lands on 2 and is not treated as a downgrade', + () async { + final db = OffbandDatabase(NativeDatabase.memory()); + addTearDown(db.close); + await BlobStore(db).read('anything'); + + expect(await userVersionOf(db), current); + }, + ); + + test('a real 1 to 2 upgrade is untouched by the new branch', () async { + // The regression that matters: every existing install arrives here. + final db = OffbandDatabase( + NativeDatabase.memory( + setup: (raw) { + raw.execute( + 'CREATE TABLE stored_blobs (key TEXT NOT NULL, ' + 'value TEXT NOT NULL, ' + "updated_at INTEGER NOT NULL DEFAULT (CAST(strftime('%s', " + "CURRENT_TIMESTAMP) AS INTEGER)), PRIMARY KEY (key))", + ); + raw.execute( + "INSERT INTO stored_blobs (key, value) VALUES ('contacts', " + "'[{\"name\":\"keep me\"}]')", + ); + raw.execute('PRAGMA user_version = 1'); + }, + ), + ); + addTearDown(db.close); + + expect(await BlobStore(db).read('contacts'), '[{"name":"keep me"}]'); + expect(await userVersionOf(db), current); + }); + }); +} + +/// A drift database with no tables and no migration, for reading a PRAGMA off +/// a file without declaring a schema that would itself trigger a migration. +class _Probe extends GeneratedDatabase { + _Probe(super.executor, this.schemaVersion); + + /// Matches the file's own version, so opening it runs no migration. + @override + final int schemaVersion; + + @override + Iterable> get allTables => const []; +} diff --git a/test/storage/scoping_inventory_test.dart b/test/storage/scoping_inventory_test.dart new file mode 100644 index 00000000..028c2496 --- /dev/null +++ b/test/storage/scoping_inventory_test.dart @@ -0,0 +1,228 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/storage/scoping_inventory.dart'; + +/// #936: the scoping verdict for every persistence surface, enforced. +/// +/// Feature #853's acceptance bar is that every store has a verified scoping +/// verdict and no hole remains. Before this test, "verified" meant a human +/// re-reading an audit in an issue body, which is how three separate bleeds +/// (#754, #854, #856) survived earlier rounds of bleed fixes. +/// +/// The scan deliberately covers one shape: a `const String` whose value is +/// lower snake_case, which is the shape every storage key in this repo uses. +/// What it would miss, stated plainly so nobody mistakes it for total: a key +/// built inline at the call site without a constant, and a key that is not +/// snake_case. Covering every string literal in `lib/` was tried and rejected: +/// it fires on asset paths and log tags, and a check that cries wolf gets +/// worked around, which is the #927 lesson. +void main() { + final declaredKeys = {for (final s in storageSurfaces) s.key}; + + group('inventory is internally coherent', () { + test('no surface is declared twice', () { + expect( + declaredKeys.length, + storageSurfaces.length, + reason: 'a duplicated key means two verdicts for one surface', + ); + }); + + test('every verdict carries a reason', () { + for (final s in storageSurfaces) { + expect( + s.reason.trim(), + isNotEmpty, + reason: + '${s.key} has no reason. An unexplained verdict is how a ' + 'surface gets re-opened as a hole later', + ); + expect(s.owner.trim(), isNotEmpty, reason: '${s.key} has no owner'); + } + }); + + test('every known hole names its issue', () { + final holes = storageSurfaces.where( + (s) => s.verdict == ScopingVerdict.knownHole, + ); + // No `isNotEmpty` sanity check any more. Epic A had one, reasoning that + // "the holes are the point", and Epic B closing the last hole made it + // fail. The invariant that actually matters is conditional: IF a hole + // is declared, it must name an issue. An empty set satisfies that and + // is the desired end state. + for (final s in holes) { + expect( + s.issue, + isNotNull, + reason: '${s.key} is a hole with no tracking issue', + ); + } + }); + + test('nothing is both a surface and a non-storage constant', () { + final overlap = declaredKeys.intersection( + nonStorageConstants.keys.toSet(), + ); + expect( + overlap, + isEmpty, + reason: 'a key cannot be both a storage surface and not one', + ); + }); + + test('no known holes remain', () { + // This expectation shrank as Epic B landed: {854, 855, 856} at the + // start, then {854, 856} once B1 deleted the dead pending_messages + // surface, now empty. #855 was deleted, #854 and #856 are scoped per + // radio. + // + // Empty is the state Epic B exists to reach, and the assertion stays so + // a future hole cannot be added quietly: adding one makes this fail + // until somebody deliberately changes the expectation. + final holes = { + for (final s in storageSurfaces) + if (s.verdict == ScopingVerdict.knownHole) s.issue, + }; + expect( + holes, + isEmpty, + reason: + 'every surface is now perRadio or globalOnPurpose with a ' + 'reason. A new hole here needs a deliberate decision, not a ' + 'silent label', + ); + }); + }); + + group('source scan', () { + test('every candidate key in lib/ is classified', () { + final found = _scanLibForCandidateKeys(); + + expect( + found, + isNotEmpty, + reason: 'the scan found nothing, so it is broken, not clean', + ); + + final unclassified = + found.keys + .where((k) => !declaredKeys.contains(k)) + .where((k) => !nonStorageConstants.containsKey(k)) + .toList() + ..sort(); + + expect( + unclassified, + isEmpty, + reason: + 'undeclared candidate keys:\n' + '${unclassified.map((k) => ' $k (${found[k]})').join('\n')}\n\n' + 'Add each to storageSurfaces with a verdict and a reason, or to ' + 'nonStorageConstants with why it is not a key. This is the gate ' + 'Feature #853 asked for: a new global key cannot land unnoticed.', + ); + }); + + test('nothing declared has vanished from the source', () { + // The other direction: a surface removed from the code but left in the + // inventory is a lie in the opposite direction. pending_messages will + // trip this the moment Epic B deletes it, which is intended. + final found = _scanLibForCandidateKeys().keys.toSet(); + final stale = declaredKeys.difference(found).toList()..sort(); + + expect( + stale, + isEmpty, + reason: + 'declared but not found in lib/:\n${stale.join('\n')}\n\n' + 'If the surface was deleted, remove its row. If it was renamed, ' + 'update it.', + ); + }); + }); + + group('the gate can fail', () { + // A check nobody has watched fail is not evidence. These run the scan + // logic over synthetic source instead of lib/, so the failure is provable + // without breaking the real tree. + + test('an undeclared snake_case key is caught', () { + final found = _extractCandidateKeys( + "class Foo { static const String _k = 'a_brand_new_global_key'; }", + 'synthetic.dart', + ); + + expect(found.keys, contains('a_brand_new_global_key')); + expect( + declaredKeys.contains('a_brand_new_global_key') || + nonStorageConstants.containsKey('a_brand_new_global_key'), + isFalse, + reason: 'so the real test would fail on it, which is the point', + ); + }); + + test('a declared key is not flagged', () { + final found = _extractCandidateKeys( + "const String _p = 'channel_messages_';", + 'synthetic.dart', + ); + + expect(found.keys, contains('channel_messages_')); + expect(declaredKeys, contains('channel_messages_')); + }); + + test('a non-key shape is ignored rather than demanding a verdict', () { + final found = _extractCandidateKeys( + "const String a = 'assets/radio_presets/';\n" + "const String b = 'com.meshcore.open';\n" + "const String c = 'linux connect stage failure';", + 'synthetic.dart', + ); + + expect( + found, + isEmpty, + reason: + 'paths, package ids and prose must not demand a verdict, or ' + 'the check gets worked around', + ); + }); + }); +} + +/// `const String = ''`, the shape every storage key in +/// this repo is declared with. +/// +/// Leading underscores are allowed in the VALUE because internal markers use +/// them (`__msgrows_migrated`). The first run of this test declared that key +/// and then reported it missing, because the pattern required a letter first. +final RegExp _candidate = RegExp( + r"const\s+String\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*'(_{0,2}[a-z][a-z0-9_]*)'", +); + +Map _extractCandidateKeys(String source, String path) { + final out = {}; + for (final m in _candidate.allMatches(source)) { + out[m.group(1)!] = path; + } + return out; +} + +/// Candidate key -> the file it was found in. +Map _scanLibForCandidateKeys() { + final lib = Directory('lib'); + expect( + lib.existsSync(), + isTrue, + reason: 'this test must run from the package root so lib/ is visible', + ); + + final out = {}; + for (final f in lib.listSync(recursive: true).whereType()) { + if (!f.path.endsWith('.dart')) continue; + if (f.path.endsWith('.g.dart')) continue; // generated, not authored + out.addAll(_extractCandidateKeys(f.readAsStringSync(), f.path)); + } + return out; +} diff --git a/test/storage/stale_history_sweep_test.dart b/test/storage/stale_history_sweep_test.dart new file mode 100644 index 00000000..712a5b91 --- /dev/null +++ b/test/storage/stale_history_sweep_test.dart @@ -0,0 +1,719 @@ +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/services/stale_history_sweep.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Epic A of #962, task A1: the diagnosis as failing tests, before anything is +/// built. +/// +/// The three reds assert the behaviour the Feature is for and have no +/// implementation yet. The fourth is a control: it asserts SQLite's actual +/// behaviour, passes today, and must keep passing, because it is the whole +/// reason a `VACUUM` step exists at all. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + const key = 'channel_messages_aaaaaaaaaapsk_deadbeef'; + + /// A history blob big enough to span many SQLite pages, so page counts move + /// measurably when it is deleted and the file is rebuilt. + /// + /// Built with the store's OWN encoder, deliberately. A hand-rolled JSON + /// fixture was the first version of this and it did not satisfy the real + /// parser, which requires `senderName`, `isOutgoing` and `status`. The sweep + /// then correctly refused the key as unverifiable, and the test looked like + /// a sweep bug. Using the production encoder means the fixture cannot drift + /// from what the production converter accepts. + String bigBlobWith(int count) => ChannelMessageStore.encodeHistoryForTest( + List.generate( + count, + (i) => ChannelMessage( + senderName: 'sender', + text: 'message $i ${'x' * 200}', + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'm$i', + ), + ), + ); + + /// The real converter, so migration and the sweep's re-verify agree. + final toRows = channelHistoryToRows; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + group('A1 ยท the diagnosis, red until Epic A is built', () { + test('migrating a key records WHEN it migrated', () async { + await blobs.write(key, bigBlobWith(50)); + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + + // Today the marker is a flat array of keys with no timestamps, so there + // is nothing to age a key against. + expect( + await blobs.messageRowsMigratedAt(key), + isNotNull, + reason: 'without a timestamp the sweep cannot know what is stale', + ); + }); + + test('a key migrated 31 days ago loses its blob to the sweep', () async { + await blobs.write(key, bigBlobWith(50)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.setMessageRowsMigratedAtForTest( + key, + DateTime.now().subtract(const Duration(days: 31)), + ); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [key]); + expect(outcome.refused, isEmpty); + expect( + await blobs.read(key), + isNull, + reason: 'the stale snapshot is the thing this Feature reclaims', + ); + // The history itself must survive: rows are the source of truth. + expect(await blobs.messageRowCount(key), 50); + }); + + test('a sweep that deleted something shrinks the database', () async { + await blobs.write(key, bigBlobWith(400)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.setMessageRowsMigratedAtForTest( + key, + DateTime.now().subtract(const Duration(days: 31)), + ); + + final before = await blobs.databaseSizeBytes(); + final outcome = await StaleHistorySweep(blobs).run(); + final after = await blobs.databaseSizeBytes(); + + expect(outcome.cleared, isNotEmpty); + expect( + after, + lessThan(before), + reason: + 'a sweep without VACUUM reclaims nothing the user can see, which ' + 'is the measured finding this step exists for', + ); + expect(outcome.bytesBefore, before); + expect(outcome.bytesAfter, after); + }); + }); + + group('A1 ยท the control: why a VACUUM step exists', () { + test('DELETE alone does not shrink the database', () async { + // Measured on the owner's real database: 74,350,592 bytes before + // deleting all 40 migrated blobs and 74,350,592 after. This pins that + // behaviour in a test so nobody "simplifies" the VACUUM away. + await blobs.write(key, bigBlobWith(400)); + final before = await blobs.databaseSizeBytes(); + + await blobs.delete(key); + final afterDelete = await blobs.databaseSizeBytes(); + + expect( + afterDelete, + before, + reason: 'SQLite frees pages for reuse; it does not return them', + ); + + await blobs.vacuum(); + expect( + await blobs.databaseSizeBytes(), + lessThan(before), + reason: 'VACUUM is what actually returns the space', + ); + }); + }); + + /// Migrates [k] and backdates its migration by [days]. + Future migratedDaysAgo(String k, int days, {int messages = 20}) async { + await blobs.write(k, bigBlobWith(messages)); + expect(await blobs.ensureMessageRowsMigrated(k, toRows), isTrue); + await blobs.setMessageRowsMigratedAtForTest( + k, + DateTime.now().subtract(Duration(days: days)), + ); + } + + group('what the sweep refuses to touch', () { + test( + 'a key with ONE blob record missing from rows keeps its blob', + () async { + await migratedDaysAgo(key, 31); + // Remove one row so the blob is no longer fully represented. The blob is + // now the only copy of that message, which is exactly when deleting it + // would be data loss. + final victim = (await blobs.messageMergeKeys(key)).first; + await blobs.deleteMessageRow(key, victim); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.refused, [key]); + expect(outcome.cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + }, + ); + + test('the same key IS cleared once its rows are complete again', () async { + // The negative half: this proves the refusal above discriminates rather + // than the sweep simply never deleting anything. + await migratedDaysAgo(key, 31); + final victim = (await blobs.messageMergeKeys(key)).first; + await blobs.deleteMessageRow(key, victim); + expect((await StaleHistorySweep(blobs).run()).refused, [key]); + + // Put it back, verbatim, and sweep again. + final stillThere = await blobs.read(key); + await blobs.upsertMessageRows(key, toRows(stillThere!)); + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [key]); + expect(await blobs.read(key), isNull); + }); + + test('a converter that silently drops a record is refused', () async { + // The hole Gemini found, closed. A converter can fail without throwing: + // it returns fewer rows than the blob holds. Comparing only the records + // it DID produce would find them all present and delete the blob that + // holds the only copy of the dropped one. The verify path therefore + // cross-checks against an independent count, as the migration gate does. + await migratedDaysAgo(key, 31); + + final result = await blobs.reclaimVerifiedHistoryBlob(key, (json) { + final all = toRows(json); + return all.take(all.length - 1).toList(); + }); + + expect(result.deleted, isFalse); + expect( + result.missing, + isNull, + reason: 'a lossy converter is UNVERIFIABLE, not verified-empty', + ); + expect(await blobs.read(key), isNotNull); + }); + + test('an undecodable blob is refused, not treated as empty', () async { + await migratedDaysAgo(key, 31); + await blobs.write(key, 'this is not json'); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect( + outcome.refused, + [key], + reason: + 'unverifiable and verified-empty must not collapse into the same ' + 'answer: that is how the only copy of an unreadable history gets ' + 'deleted', + ); + expect(await blobs.read(key), 'this is not json'); + }); + + test('a key inside the window keeps its blob, tested at 29 days', () async { + await migratedDaysAgo(key, 29); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + }); + + test('30 days exactly is eligible, so the boundary is pinned', () async { + await migratedDaysAgo(key, 30); + expect((await StaleHistorySweep(blobs).run()).cleared, [key]); + }); + + test('a migrated key with no timestamp is stamped, not deleted', () async { + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + // Simulate an install that migrated before #962: marked, never stamped. + await blobs.write(BlobStore.migratedAtKey, '{}'); + blobs.resetMigratedKeyCache(); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + expect( + await blobs.messageRowsMigratedAt(key), + isNotNull, + reason: 'it must start its window now, not be deleted on sight', + ); + }); + + test('a migrated key with no blob is neither cleared nor refused', () async { + // The empty-blob migration path marks a key without there ever being a + // blob, and a second sweep sees a key it already reclaimed. Both must be + // silent: counting them as cleared would overstate what was reclaimed, + // and as refused would raise a false alarm. On the owner's database 7 of + // 47 aged keys are in exactly this state. + await migratedDaysAgo(key, 31); + expect((await StaleHistorySweep(blobs).run()).cleared, [key]); + + final second = await StaleHistorySweep(blobs).run(); + + expect(second.cleared, isEmpty); + expect(second.refused, isEmpty); + expect(second.bytesReclaimed, 0); + }); + + test( + 'reclaim is atomic: verify and delete hold the same key lock', + () async { + // Checking through one call and deleting through another leaves a window + // where the answer can go stale, and a delete decided on a stale answer + // cannot be taken back. BlobStore.reclaimVerifiedHistoryBlob exists to + // close that, so assert the sweep goes through it rather than doing its + // own read-then-delete. + await migratedDaysAgo(key, 31); + + final result = await blobs.reclaimVerifiedHistoryBlob(key, toRows); + + expect(result.deleted, isTrue); + expect(result.missing, isEmpty); + expect(await blobs.read(key), isNull); + + // Called again on the now-blobless key it reports no delete and no + // problem, which is what makes a second sweep silent. + final again = await blobs.reclaimVerifiedHistoryBlob(key, toRows); + expect(again.deleted, isFalse); + expect(again.missing, isEmpty); + }, + ); + + test('an unmigrated history key keeps its blob', () async { + await blobs.write(key, bigBlobWith(20)); + // Never migrated: the blob is authoritative. + expect(await blobs.isOnMessageRows(key), isFalse); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + }); + + test('non-history keys are never candidates, by name', () async { + // The blob IS the storage for these: there is no row equivalent, so a + // sweep that considered them would delete the only copy. + const others = [ + 'contacts', + 'contactsaaaaaaaaaa', + 'discovered_contacts', + 'discovered_contactsaaaaaaaaaa', + 'path_history_aaaaaaaaaacafebabe', + ]; + for (final k in others) { + await blobs.write(k, '[{"name":"keep me"}]'); + expect( + StaleHistorySweep.isHistoryKey(k), + isFalse, + reason: '$k must never be considered a history key', + ); + // Asserting the helper alone would pass even if `run` stopped calling + // it, because the loop only visits keys that HAVE rows and these + // normally have none (Gemini review). So give them rows and a stale + // timestamp: now the only thing standing between them and a delete is + // the prefix guard inside `run`. + await blobs.upsertMessageRows(k, const [ + MessageRowInput( + mergeKey: 'id:planted', + timestampMs: 1, + payload: '{}', + ), + ]); + await blobs.setMessageRowsMigratedAtForTest( + k, + DateTime.now().subtract(const Duration(days: 99)), + ); + } + await migratedDaysAgo(key, 31); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [key]); + expect( + outcome.refused, + isEmpty, + reason: 'they must be skipped outright, not refused', + ); + for (final k in others) { + expect(await blobs.read(k), '[{"name":"keep me"}]', reason: k); + } + }); + }); + + group('the audit trail', () { + test('a sweep records WHICH keys it deleted, durably', () async { + // The app log is gated on a setting that is off by default, so without + // this an irreversible delete leaves no trail on a normal install. And + // a count is not an audit trail. + await migratedDaysAgo(key, 31); + + final outcome = await StaleHistorySweep(blobs).run(); + expect(outcome.cleared, [key]); + + final audit = await blobs.reclaimAudit(); + expect(audit, hasLength(1)); + expect(audit.single['cleared'], [key]); + expect(audit.single['refused'], isEmpty); + expect(audit.single['bytesBefore'], outcome.bytesBefore); + expect(audit.single['bytesAfter'], outcome.bytesAfter); + expect(audit.single['at'], isA()); + }); + + test('it survives a fresh store object, so it is really on disk', () async { + await migratedDaysAgo(key, 31); + await StaleHistorySweep(blobs).run(); + + // A new BlobStore over the same database is what a restart looks like + // to storage. The audit has to come back. + final reopened = BlobStore(db); + expect((await reopened.reclaimAudit()).single['cleared'], [key]); + }); + + test('refusals are recorded too, not only deletions', () async { + await migratedDaysAgo(key, 31); + await blobs.deleteMessageRow( + key, + (await blobs.messageMergeKeys(key)).first, + ); + + await StaleHistorySweep(blobs).run(); + + final audit = await blobs.reclaimAudit(); + expect(audit.single['cleared'], isEmpty); + expect(audit.single['refused'], [key]); + }); + + test('a sweep that did nothing writes no entry', () async { + await migratedDaysAgo(key, 1); // inside the window + await StaleHistorySweep(blobs).run(); + expect(await blobs.reclaimAudit(), isEmpty); + }); + + test('it is capped, so it cannot grow without bound', () async { + for (var i = 0; i < BlobStore.reclaimAuditEntries + 3; i++) { + final k = 'channel_messages_aaaaaaaaaapsk_run$i'; + await migratedDaysAgo(k, 31, messages: 2); + await StaleHistorySweep(blobs).run(); + } + + final audit = await blobs.reclaimAudit(); + expect(audit, hasLength(BlobStore.reclaimAuditEntries)); + // Oldest dropped, newest kept. + expect( + audit.last['cleared'], + contains( + 'channel_messages_aaaaaaaaaapsk_run' + '${BlobStore.reclaimAuditEntries + 2}', + ), + ); + }); + + test('an unreadable audit does not stop a sweep', () async { + await blobs.write(BlobStore.reclaimAuditKey, 'not json'); + await migratedDaysAgo(key, 31); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [key], reason: 'the sweep still has to work'); + expect((await blobs.reclaimAudit()).single['cleared'], [key]); + }); + }); + + group('the age rule, shared by preview and run', () { + final at = DateTime(2026, 10, 23, 12); + + test('an unstamped key is NOT eligible for the automatic sweep', () { + expect( + StaleHistorySweep.eligibleByAge( + migratedAt: null, + freshlyStamped: false, + window: staleHistoryWindow, + at: at, + includeNewlyStamped: false, + ), + isFalse, + reason: 'the stamp exists so an app update never deletes on sight', + ); + }); + + test('an unstamped key IS eligible for an explicit press', () { + expect( + StaleHistorySweep.eligibleByAge( + migratedAt: null, + freshlyStamped: true, + window: Duration.zero, + at: at, + includeNewlyStamped: true, + ), + isTrue, + reason: 'a user asking to clear now is not an app update', + ); + }); + + test('29 days out, 30 days in', () { + bool eligible(int days) => StaleHistorySweep.eligibleByAge( + migratedAt: at.subtract(Duration(days: days)), + freshlyStamped: false, + window: staleHistoryWindow, + at: at, + includeNewlyStamped: false, + ); + expect(eligible(29), isFalse); + expect(eligible(30), isTrue); + }); + }); + + group('the bug the preview exposed', () { + test('an install with NO stamps clears on the first press', () async { + // Every install that migrated before #962 has an empty + // __msgrows_migrated_at. The sweep stamps them all, and the old + // "skip anything stamped this pass" rule then skipped every one, so the + // button reported nothing to clear against real reclaimable blobs. That + // was the owner's install exactly: 47 migrated keys, none stamped. + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.write(BlobStore.migratedAtKey, '{}'); // nothing stamped + blobs.resetMigratedKeyCache(); + + // The automatic sweep still refuses, which is correct. + expect((await StaleHistorySweep(blobs).run()).cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + + // The explicit press does not. + final outcome = await StaleHistorySweep( + blobs, + ).run(olderThan: Duration.zero, includeNewlyStamped: true); + expect(outcome.cleared, [key]); + expect(await blobs.read(key), isNull); + expect(await blobs.messageRowCount(key), 20); + }); + }); + + group('preview', () { + test('it reports what a press would clear, and writes nothing', () async { + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.write(BlobStore.migratedAtKey, '{}'); + blobs.resetMigratedKeyCache(); + + final p = await StaleHistorySweep( + blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + expect(p.eligible, [key]); + expect(p.refused, isEmpty); + expect(p.hasWork, isTrue); + expect(p.approximateBytes, greaterThan(0)); + expect(p.messagesKept, 20); + + // Nothing was deleted and nothing was stamped, so a later run behaves + // exactly as if the preview had never happened. + expect(await blobs.read(key), isNotNull); + expect(await blobs.read(BlobStore.migratedAtKey), '{}'); + }); + + test('it forecasts a refusal instead of discovering it later', () async { + await migratedDaysAgo(key, 31); + await blobs.deleteMessageRow( + key, + (await blobs.messageMergeKeys(key)).first, + ); + + final p = await StaleHistorySweep(blobs).preview(); + + expect(p.eligible, isEmpty); + expect(p.refused, [key]); + expect( + p.hasWork, + isFalse, + reason: 'nothing to confirm, so the card reports without a dialog', + ); + }); + + test('preview and run agree on eligibility', () async { + // The dialog must not promise what the sweep will not do. Same inputs, + // same answer. + await migratedDaysAgo(key, 31); + const young = 'channel_messages_aaaaaaaaaapsk_young'; + await migratedDaysAgo(young, 2); + + final p = await StaleHistorySweep(blobs).preview(); + final outcome = await StaleHistorySweep(blobs).run(); + + expect(p.eligible, [key]); + expect(outcome.cleared, [key]); + expect(await blobs.read(young), isNotNull); + }); + + test('non-history and unmigrated keys never appear', () async { + await blobs.write('contacts', '[{"name":"a"}]'); + await blobs.upsertMessageRows('contacts', const [ + MessageRowInput(mergeKey: 'id:x', timestampMs: 1, payload: '{}'), + ]); + await blobs.write('channel_messages_bbbbbbbbbbpsk_un', bigBlobWith(5)); + + final p = await StaleHistorySweep( + blobs, + ).preview(olderThan: Duration.zero, includeNewlyStamped: true); + + expect(p.eligible, isEmpty); + expect(p.refused, isEmpty); + }); + }); + + group('what the manual action relies on (#966)', () { + test('olderThan zero makes a key migrated seconds ago eligible', () async { + // The button passes Duration.zero, which is the whole point of it: no + // waiting 30 days. Proven here under plain `test()` rather than in the + // widget test, because the sweep uses `compute` and an isolate + // deadlocks pumpAndSettle in flutter_test's fake-async zone. The widget + // test injects the sweep for that reason, so this is what keeps the + // semantic it injects honest. + await blobs.write(key, bigBlobWith(20)); + expect(await blobs.ensureMessageRowsMigrated(key, toRows), isTrue); + + // The default window leaves it alone. + expect((await StaleHistorySweep(blobs).run()).cleared, isEmpty); + expect(await blobs.read(key), isNotNull); + + // Duration.zero does not. + final outcome = await StaleHistorySweep( + blobs, + ).run(olderThan: Duration.zero); + + expect(outcome.cleared, [key]); + expect(await blobs.read(key), isNull); + expect(await blobs.messageRowCount(key), 20); + }); + + test('olderThan zero still refuses an unverifiable key', () async { + // Skipping the wait must not skip the safety. + await blobs.write(key, bigBlobWith(20)); + await blobs.ensureMessageRowsMigrated(key, toRows); + await blobs.deleteMessageRow( + key, + (await blobs.messageMergeKeys(key)).first, + ); + + final outcome = await StaleHistorySweep( + blobs, + ).run(olderThan: Duration.zero); + + expect(outcome.cleared, isEmpty); + expect(outcome.refused, [key]); + expect(await blobs.read(key), isNotNull); + }); + }); + + group('a direct-message key sweeps too', () { + test('messages_ uses the DM converter and is cleared', () async { + const dmKey = 'messages_aaaaaaaaaacafebabe'; + final history = MessageStore.encodeHistoryForTest([ + Message( + senderKey: Uint8List.fromList(const [1, 2, 3, 4]), + text: 'hello', + timestamp: DateTime.fromMillisecondsSinceEpoch(1700000000000), + isOutgoing: false, + messageId: 'dm-1', + ), + ]); + await blobs.write(dmKey, history); + expect( + await blobs.ensureMessageRowsMigrated(dmKey, dmHistoryToRows), + isTrue, + ); + await blobs.setMessageRowsMigratedAtForTest( + dmKey, + DateTime.now().subtract(const Duration(days: 31)), + ); + + final outcome = await StaleHistorySweep(blobs).run(); + + expect(outcome.cleared, [dmKey]); + expect(await blobs.read(dmKey), isNull); + expect(await blobs.messagePayloads(dmKey), hasLength(1)); + }); + + test('converterFor picks by shape', () { + expect( + StaleHistorySweep.converterFor('channel_messages_x'), + same(channelHistoryToRows), + ); + expect( + StaleHistorySweep.converterFor('messages_x'), + same(dmHistoryToRows), + ); + }); + }); + + group('VACUUM leaves everything it kept untouched', () { + test('every kept blob is byte-identical and rows are unchanged', () async { + // The owner's question, as a test. Measured on his real database: 291 + // kept keys including all 98 unmigrated history blobs came through + // hash-identical. This is the same assertion in miniature. + await migratedDaysAgo(key, 31, messages: 200); + const unmigrated = 'channel_messages_bbbbbbbbbbpsk_feedface'; + await blobs.write(unmigrated, bigBlobWith(50)); + await blobs.write('contacts', '[{"name":"a"}]'); + await blobs.write('path_history_ccccccccccdeadbeef', '{"paths":[]}'); + + final before = {}; + for (final k in await blobs.keysWithPrefix('')) { + if (k == key) continue; // the one we expect to go + before[k] = (await blobs.read(k))!; + } + final rowsBefore = await blobs.messageRowCount(key); + + final outcome = await StaleHistorySweep(blobs).run(); + expect(outcome.cleared, [key]); + + for (final entry in before.entries) { + expect( + await blobs.read(entry.key), + entry.value, + reason: '${entry.key} changed across the sweep and VACUUM', + ); + } + expect( + await blobs.read(unmigrated), + isNotNull, + reason: 'the unmigrated history blob is the only copy of its history', + ); + expect( + await blobs.messageRowCount(key), + rowsBefore, + reason: 'the history itself must survive losing its stale snapshot', + ); + expect(outcome.bytesReclaimed, greaterThan(0)); + }); + }); +} diff --git a/test/storage/stores_on_rows_test.dart b/test/storage/stores_on_rows_test.dart new file mode 100644 index 00000000..8bf14856 --- /dev/null +++ b/test/storage/stores_on_rows_test.dart @@ -0,0 +1,372 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/models/channel_message.dart'; +import 'package:meshcore_open/models/message.dart'; +import 'package:meshcore_open/storage/channel_message_store.dart'; +import 'package:meshcore_open/storage/drift/blob_store.dart'; +import 'package:meshcore_open/storage/drift/offband_database.dart'; +import 'package:meshcore_open/storage/message_store.dart'; +import 'package:meshcore_open/storage/prefs_manager.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// #920 B2: both stores read and write rows. These go through the public store +/// API only, because that is what the app calls and what an existing install +/// will hit on its first launch after this ships. +void main() { + late OffbandDatabase db; + late BlobStore blobs; + + setUp(() async { + SharedPreferences.setMockInitialValues({}); + PrefsManager.reset(); + await PrefsManager.initialize(); + db = OffbandDatabase(NativeDatabase.memory()); + blobs = BlobStore(db); + BlobStore.overrideForTest(blobs); + }); + + tearDown(() async { + await db.close(); + BlobStore.clearTestOverride(); + }); + + ChannelMessage chan(int i, {String? text}) => ChannelMessage( + senderName: 's', + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + channelIndex: 0, + messageId: 'id$i', + ); + + Message dm(int i, {String? text}) => Message( + senderKey: Uint8List.fromList(const [1, 2, 3, 4]), + text: text ?? 'm$i', + timestamp: DateTime.fromMillisecondsSinceEpoch(1000 + i), + isOutgoing: false, + messageId: 'id$i', + ); + + group('channel store on rows', () { + test('a save writes rows, not a blob', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + await store.saveChannelMessages(0, [chan(1), chan(2)]); + + expect(await blobs.messageRowCount('channel_messages_aaaaaaaaaa0'), 2); + expect( + await blobs.read('channel_messages_aaaaaaaaaa0'), + isNull, + reason: 'the blob path is the fallback now, not the write path', + ); + }); + + test('round-trips through load', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]); + + final loaded = await store.loadChannelMessages(0); + + expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3']); + expect(loaded.map((m) => m.text), ['m1', 'm2', 'm3']); + }); + + test('a windowed save does not truncate stored history (#343)', () async { + // The in-memory list is windowed, so this is the case that made saves a + // merge in the first place. On rows it has to stay true. + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]); + + await store.saveChannelMessages(0, [chan(4)]); + + final loaded = await store.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3', 'id4']); + }); + + test('re-saving a message updates it instead of duplicating', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1, text: 'first')]); + + await store.saveChannelMessages(0, [chan(1, text: 'edited')]); + + final loaded = await store.loadChannelMessages(0); + expect(loaded.single.text, 'edited'); + }); + + test('an existing blob history is adopted on first load', () async { + // What every current install looks like: the whole history in a blob and + // no rows at all. + const key = 'channel_messages_aaaaaaaaaa0'; + await blobs.write( + key, + ChannelMessageStore.encodeHistoryForTest([chan(1), chan(2), chan(3)]), + ); + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + final loaded = await store.loadChannelMessages(0); + + expect(loaded.map((m) => m.messageId), ['id1', 'id2', 'id3']); + expect(await blobs.messageRowCount(key), 3, reason: 'migrated on read'); + expect(await blobs.isOnMessageRows(key), isTrue); + }); + + test('an existing blob history is adopted on first save', () async { + const key = 'channel_messages_aaaaaaaaaa0'; + await blobs.write( + key, + ChannelMessageStore.encodeHistoryForTest([chan(1), chan(2)]), + ); + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + await store.saveChannelMessages(0, [chan(3)]); + + final loaded = await store.loadChannelMessages(0); + expect( + loaded.map((m) => m.messageId), + ['id1', 'id2', 'id3'], + reason: 'the blob history must not be lost by the first row save', + ); + }); + + test('the adopted blob is left in place', () async { + const key = 'channel_messages_aaaaaaaaaa0'; + final original = ChannelMessageStore.encodeHistoryForTest([chan(1)]); + await blobs.write(key, original); + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + await store.loadChannelMessages(0); + + expect(await blobs.read(key), original); + }); + + test('delete removes one message and keeps the rest', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2), chan(3)]); + + await store.removeChannelMessage(0, chan(2)); + + final loaded = await store.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1', 'id3']); + }); + + test('a deleted message is not resurrected by the next save', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2)]); + await store.removeChannelMessage(0, chan(2)); + + // The in-memory list the app saves next may still be stale, but a save + // that re-sends the deleted message legitimately re-adds it. What must + // not happen is a save of OTHER messages bringing it back. + await store.saveChannelMessages(0, [chan(1)]); + + final loaded = await store.loadChannelMessages(0); + expect(loaded.map((m) => m.messageId), ['id1']); + }); + + test('clear removes the rows, not just the blob', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2)]); + + await store.clearChannelMessages(0); + + expect(await store.loadChannelMessages(0), isEmpty); + expect(await blobs.messageRowCount('channel_messages_aaaaaaaaaa0'), 0); + }); + + test('clearAll removes row-only histories too', () async { + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1)]); + await store.saveChannelMessages(1, [chan(2)]); + + await store.clearAllChannelMessages(); + + expect(await store.loadChannelMessages(0), isEmpty); + expect(await store.loadChannelMessages(1), isEmpty); + }); + + test('history stays scoped per radio', () async { + // A bleed here is #472, which shipped once already. + final radioA = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + final radioB = ChannelMessageStore()..setPublicKeyHex = 'b' * 20; + + await radioA.saveChannelMessages(0, [chan(1)]); + await radioB.saveChannelMessages(0, [chan(2)]); + + expect((await radioA.loadChannelMessages(0)).single.messageId, 'id1'); + expect((await radioB.loadChannelMessages(0)).single.messageId, 'id2'); + }); + + test('one unreadable row costs one message, not the channel', () async { + // On the blob, a single bad byte took the whole history with it. + const key = 'channel_messages_aaaaaaaaaa0'; + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1), chan(2)]); + await blobs.upsertMessageRows(key, const [ + MessageRowInput( + mergeKey: 'id:broken', + timestampMs: 1500, + payload: '{not json', + ), + ]); + + final loaded = await store.loadChannelMessages(0); + + expect(loaded.map((m) => m.messageId), ['id1', 'id2']); + }); + }); + + group('DM store on rows', () { + test('a save writes rows, not a blob', () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + + await store.saveMessages('beef', [dm(1), dm(2)]); + + expect(await blobs.messageRowCount('messages_aaaaaaaaaabeef'), 2); + expect(await blobs.read('messages_aaaaaaaaaabeef'), isNull); + }); + + test('round-trips through load', () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveMessages('beef', [dm(1), dm(2)]); + + final loaded = await store.loadMessages('beef'); + + expect(loaded.map((m) => m.messageId), ['id1', 'id2']); + }); + + test('a windowed save does not truncate stored history (#343)', () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveMessages('beef', [dm(1), dm(2)]); + + await store.saveMessages('beef', [dm(3)]); + + expect((await store.loadMessages('beef')).map((m) => m.messageId), [ + 'id1', + 'id2', + 'id3', + ]); + }); + + test('an existing blob history is adopted on first load', () async { + const key = 'messages_aaaaaaaaaabeef'; + await blobs.write(key, MessageStore.encodeHistoryForTest([dm(1), dm(2)])); + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + + final loaded = await store.loadMessages('beef'); + + expect(loaded.map((m) => m.messageId), ['id1', 'id2']); + expect(await blobs.messageRowCount(key), 2); + }); + + test('an existing blob history is adopted on first save', () async { + const key = 'messages_aaaaaaaaaabeef'; + await blobs.write(key, MessageStore.encodeHistoryForTest([dm(1)])); + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + + await store.saveMessages('beef', [dm(2)]); + + expect((await store.loadMessages('beef')).map((m) => m.messageId), [ + 'id1', + 'id2', + ]); + }); + + test('delete removes one message', () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveMessages('beef', [dm(1), dm(2), dm(3)]); + + await store.removeMessage('beef', dm(2)); + + expect((await store.loadMessages('beef')).map((m) => m.messageId), [ + 'id1', + 'id3', + ]); + }); + + test('clear removes the rows', () async { + final store = MessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveMessages('beef', [dm(1)]); + + await store.clearMessages('beef'); + + expect(await store.loadMessages('beef'), isEmpty); + }); + + test('conversations stay scoped per contact and per radio', () async { + final radioA = MessageStore()..setPublicKeyHex = 'a' * 20; + final radioB = MessageStore()..setPublicKeyHex = 'b' * 20; + + await radioA.saveMessages('beef', [dm(1)]); + await radioA.saveMessages('cafe', [dm(2)]); + await radioB.saveMessages('beef', [dm(3)]); + + expect((await radioA.loadMessages('beef')).single.messageId, 'id1'); + expect((await radioA.loadMessages('cafe')).single.messageId, 'id2'); + expect((await radioB.loadMessages('beef')).single.messageId, 'id3'); + }); + }); + + group('refused migration keeps the store working on the blob', () { + test('channel: a corrupt blob still reads and saves', () async { + const key = 'channel_messages_aaaaaaaaaa0'; + // Valid JSON that the converter cannot turn into messages: the record + // decode throws, so the migration must refuse and the blob path stays. + await blobs.write(key, '[{"not":"a message"}]'); + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + + final loaded = await store.loadChannelMessages(0); + + expect( + await blobs.isOnMessageRows(key), + isFalse, + reason: 'a converter that throws must not mark the key migrated', + ); + expect(loaded, isEmpty, reason: 'the blob itself does not decode either'); + expect(await blobs.read(key), '[{"not":"a message"}]'); + + // And a save still lands, on the blob path. + await store.saveChannelMessages(0, [chan(1)]); + expect(await blobs.read(key), isNotNull); + }); + + test( + 'channel: the blob fallback still merges rather than overwriting', + () async { + const key = 'channel_messages_aaaaaaaaaa0'; + await blobs.write(key, '[{"not":"a message"}]'); + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.loadChannelMessages(0); + + // mergeOffThread fails closed on an undecodable blob, so the refused + // key keeps its bytes rather than being replaced by the incoming save. + await store.saveChannelMessages(0, [chan(1)]); + + expect(await blobs.read(key), '[{"not":"a message"}]'); + expect( + await blobs.messageRowCount(key), + 0, + reason: 'a refused key must not accumulate half a history in rows', + ); + }, + ); + }); + + test('the payload a row stores is the stores own encoding', () async { + // Guards the migration contract: rows hold exactly what the blob held, so + // a payload is decodable by the same _messageFromJson. + final store = ChannelMessageStore()..setPublicKeyHex = 'a' * 20; + await store.saveChannelMessages(0, [chan(1)]); + + final payload = (await blobs.messagePayloads( + 'channel_messages_aaaaaaaaaa0', + )).single; + final decoded = jsonDecode(payload) as Map; + + expect(decoded['messageId'], 'id1'); + expect(decoded['text'], 'm1'); + expect(decoded.containsKey('status'), isTrue); + }); +} diff --git a/test/utils/file_log_writer_test.dart b/test/utils/file_log_writer_test.dart index 3e9c21cc..36b0bb9f 100644 --- a/test/utils/file_log_writer_test.dart +++ b/test/utils/file_log_writer_test.dart @@ -75,5 +75,135 @@ void main() { expect(File('${dir.path}/t.log').existsSync(), isTrue); expect(File('${dir.path}/t.1.log').existsSync(), isTrue); }); + + // #906: the export used to ship only the active file, so a line written + // once at startup was lost as soon as the log rotated. These pin the + // accessor the export now relies on. + group('existingFiles (#906)', () { + test('is empty before anything is written', () async { + final w = FileLogWriter(dir: dir, baseName: 't', maxBytes: 1 << 20); + expect(await w.existingFiles(), isEmpty); + }); + + test('returns just the active file before any rotation', () async { + final w = FileLogWriter(dir: dir, baseName: 't', maxBytes: 1 << 20); + await w.writeLine('only'); + final files = await w.existingFiles(); + expect(files.map((f) => f.uri.pathSegments.last), ['t.log']); + }); + + test('returns the rotated files too, newest first', () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 100, + maxFiles: 3, + ); + for (var i = 0; i < 60; i++) { + await w.writeLine('line $i ${'x' * 20}'); + } + final names = (await w.existingFiles()) + .map((f) => f.uri.pathSegments.last) + .toList(); + expect(names, ['t.log', 't.1.log', 't.2.log']); + }); + + test('never reports more than maxFiles', () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 60, + maxFiles: 2, + ); + for (var i = 0; i < 80; i++) { + await w.writeLine('line $i ${'y' * 20}'); + } + final files = await w.existingFiles(); + expect(files.length, lessThanOrEqualTo(2)); + expect( + files.map((f) => f.uri.pathSegments.last), + isNot(contains('t.2.log')), + ); + }); + }); + + // #906: exit-record capture puts a pointer line in offband.log and the + // trace itself in a sibling file, partly because a trace is tens of KB. + // These pin down what a large entry actually does to rotation, so the + // Epic's "rotation still behaves with a large trace present" criterion is + // measured rather than assumed. + group('with an oversized entry present (#906)', () { + test( + 'an entry larger than maxBytes rotates and is written whole', + () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 2048, + maxFiles: 3, + ); + await w.writeLine('small line to make the active file non-empty'); + final big = 'T' * 40000; + await w.writeLine(big); + + // Rotation fired, and the oversized entry is intact rather than cut. + expect(File('${dir.path}/t.1.log').existsSync(), isTrue); + expect(await w.activeFile.readAsString(), '$big\n'); + }, + ); + + test('a single entry over maxBytes leaves the active file above the cap, ' + 'by design: it rotates once then appends regardless', () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 2048, + maxFiles: 3, + ); + await w.writeLine('seed'); + await w.writeLine('T' * 40000); + expect( + await w.activeFile.length(), + greaterThan(2048), + reason: 'maxBytes gates when to rotate, it is not a hard truncation', + ); + }); + + test('normal rotation still works after an oversized entry', () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 2048, + maxFiles: 3, + ); + await w.writeLine('T' * 40000); + for (var i = 0; i < 40; i++) { + await w.writeLine('line $i ${'z' * 100}'); + } + expect(File('${dir.path}/t.log').existsSync(), isTrue); + expect(File('${dir.path}/t.1.log').existsSync(), isTrue); + expect(File('${dir.path}/t.2.log').existsSync(), isTrue); + expect( + File('${dir.path}/t.3.log').existsSync(), + isFalse, + reason: 'maxFiles still holds, so the log cannot grow without bound', + ); + }); + + test('an oversized batch rotates once and is not dropped', () async { + final w = FileLogWriter( + dir: dir, + baseName: 't', + maxBytes: 2048, + maxFiles: 3, + ); + await w.writeLine('seed'); + final lines = List.generate(500, (i) => 'trace frame $i ${'f' * 60}'); + await w.writeLines(lines); + final active = await w.activeFile.readAsString(); + expect(active, contains('trace frame 0 ')); + expect(active, contains('trace frame 499 ')); + }); + }); }); } diff --git a/test/widgets/channel_region_scope_dialog_test.dart b/test/widgets/channel_region_scope_dialog_test.dart new file mode 100644 index 00000000..79dd3dce --- /dev/null +++ b/test/widgets/channel_region_scope_dialog_test.dart @@ -0,0 +1,158 @@ +// Epic #815 T C2: channel Set Region Scope picker dialog. +// Decoupled from the connector (plain data + callbacks + injected service), +// so it widget-tests without a radio. + +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/services/region_discovery_service.dart'; +import 'package:meshcore_open/widgets/channel_region_scope_dialog.dart'; + +void main() { + final repeaters = [RepeaterChoice(name: 'rpt-01', pubKey: Uint8List(32))]; + RegionsReply reply(List names) => + RegionsReply(tag: 1, clock: 1, regionNames: names); + + Future pump( + WidgetTester tester, { + String? current, + required RegionDiscoveryService service, + required void Function(String?) onSave, + }) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: ChannelRegionScopeDialog( + channelName: 'general', + currentScope: current, + repeaters: repeaters, + service: service, + onSave: (r) async => onSave(r), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + testWidgets('discover, pick a region, save returns it', (tester) async { + String? result; + var called = false; + await pump( + tester, + service: RegionDiscoveryService((_, _) async => reply(['oki', 'test'])), + onSave: (r) { + called = true; + result = r; + }, + ); + await tester.tap(find.byKey(const Key('regionScopeDiscover'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('oki')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('regionScopeSave'))); + await tester.pumpAndSettle(); + expect(called, isTrue); + expect(result, 'oki'); + }); + + testWidgets('selecting None saves null (clears the scope)', (tester) async { + String? result = 'sentinel'; + await pump( + tester, + current: 'oki', + service: RegionDiscoveryService((_, _) async => reply(['oki'])), + onSave: (r) => result = r, + ); + await tester.tap(find.byKey(const Key('regionScopeNone'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('regionScopeSave'))); + await tester.pumpAndSettle(); + expect(result, isNull); + }); + + testWidgets('repeaters are alpha-sorted and searchable', (tester) async { + final many = [ + RepeaterChoice(name: 'Zephyr', pubKey: Uint8List(32)), + RepeaterChoice(name: 'alpha-rptr', pubKey: Uint8List(32)), + RepeaterChoice(name: 'Mike', pubKey: Uint8List(32)), + ]; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: ChannelRegionScopeDialog( + channelName: 'general', + currentScope: null, + repeaters: many, + service: RegionDiscoveryService((_, _) async => reply([])), + onSave: (_) async {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + // Case-insensitive alpha order: alpha-rptr, Mike, Zephyr. + final yAlpha = tester.getTopLeft(find.text('alpha-rptr')).dy; + final yMike = tester.getTopLeft(find.text('Mike')).dy; + final yZephyr = tester.getTopLeft(find.text('Zephyr')).dy; + expect(yAlpha < yMike && yMike < yZephyr, isTrue); + // The search box filters the list. + await tester.enterText( + find.byKey(const Key('regionScopeRepeaterSearch')), + 'mik', + ); + await tester.pumpAndSettle(); + expect(find.text('Mike'), findsOneWidget); + expect(find.text('Zephyr'), findsNothing); + expect(find.text('alpha-rptr'), findsNothing); + }); + + testWidgets( + 'pathless repeaters are hidden by default, greyed + non-selectable on search', + (tester) async { + final repeaters = [ + RepeaterChoice(name: 'HasPath', pubKey: Uint8List(32)), + RepeaterChoice(name: 'NoPath', pubKey: Uint8List(32), hasPath: false), + ]; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: ChannelRegionScopeDialog( + channelName: 'general', + currentScope: null, + repeaters: repeaters, + service: RegionDiscoveryService((_, _) async => reply([])), + onSave: (_) async {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + // Default: only the path-having repeater is listed (scope to ListTile, + // since the search field can also hold the typed text). + expect(find.widgetWithText(ListTile, 'HasPath'), findsOneWidget); + expect(find.widgetWithText(ListTile, 'NoPath'), findsNothing); + // Search surfaces the pathless one, labeled and disabled. + await tester.enterText( + find.byKey(const Key('regionScopeRepeaterSearch')), + 'NoPath', + ); + await tester.pumpAndSettle(); + expect(find.widgetWithText(ListTile, 'NoPath'), findsOneWidget); + expect(find.text('No stored path'), findsOneWidget); + final tile = tester.widget( + find.widgetWithText(ListTile, 'NoPath'), + ); + expect(tile.enabled, isFalse); + }, + ); +} diff --git a/test/widgets/contact_rename_dialog_test.dart b/test/widgets/contact_rename_dialog_test.dart new file mode 100644 index 00000000..eadd901f --- /dev/null +++ b/test/widgets/contact_rename_dialog_test.dart @@ -0,0 +1,208 @@ +// Custom Name override for contacts (#750), task 750.4: the rename UI. +// +// Tests T23, T24, T27, T28, T29 and T30 from the plan of record. +// +// T29 and T30 came out of the pre-PR adversarial review on the plan. T3 and T4 +// prove the model's getter tolerates an empty custom name, but nothing proved +// the UI never writes one, and a working Clear button (T24) would have masked +// a broken Save path. They assert what reaches the connector, not what the +// screen shows, because that is where the wrong value would be stored. + +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/meshcore_connector.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/models/contact.dart'; +import 'package:meshcore_open/widgets/contact_rename_dialog.dart'; +import 'package:provider/provider.dart'; + +const _received = 'KQ4EZN-Repeater'; + +Contact _contact({String? customName}) => Contact( + publicKey: Uint8List.fromList(List.filled(32, 0x66)), + receivedName: _received, + customName: customName, + type: advTypeChat, + pathLength: -1, + path: Uint8List(0), + lastSeen: DateTime.utc(2026, 7, 1), +); + +/// Records what the dialog asked the connector to store, which is the thing +/// that matters: a wrong value here is persisted. +class _RecordingConnector extends MeshCoreConnector { + final calls = <(String, String?)>[]; + + @override + Future setContactCustomName(String contactKeyHex, String? name) async { + calls.add((contactKeyHex, name)); + } +} + +Future _open( + WidgetTester tester, + _RecordingConnector connector, + Contact contact, +) async { + await tester.pumpWidget( + ChangeNotifierProvider.value( + value: connector, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Scaffold( + body: ElevatedButton( + onPressed: () => showContactRenameDialog(context, contact), + child: const Text('open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pumpAndSettle(); +} + +void main() { + late _RecordingConnector connector; + + setUp(() => connector = _RecordingConnector()); + + testWidgets('T23 + saving a name sends it to the connector', (tester) async { + await _open(tester, connector, _contact()); + + await tester.enterText(find.byType(TextField), 'Chuck'); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + + expect(connector.calls.single.$2, 'Chuck'); + }); + + testWidgets('T23b + the field opens pre-filled with the current name', ( + tester, + ) async { + await _open(tester, connector, _contact(customName: 'Chuck')); + + expect(find.text('Chuck'), findsOneWidget); + }); + + testWidgets('T24 + Clear sends null, reverting to the received name', ( + tester, + ) async { + await _open(tester, connector, _contact(customName: 'Chuck')); + + await tester.tap(find.widgetWithText(TextButton, 'Clear')); + await tester.pumpAndSettle(); + + expect(connector.calls.single.$2, isNull); + }); + + testWidgets('T29 - saving an EMPTY field never stores an empty string', ( + tester, + ) async { + // The review's finding. A plausible implementation saves '' here, the + // display still looks right because the getter falls back, and the dialog + // can never truly unset the name through its primary action. + await _open(tester, connector, _contact(customName: 'Chuck')); + + await tester.enterText(find.byType(TextField), ''); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + + expect( + connector.calls.single.$2, + isNull, + reason: + 'an empty field must clear. Asserting null strictly rather than ' + 'accepting an empty string, because an empty string IS the defect ' + 'the review found: the display would look right while the stored ' + 'value was wrong.', + ); + }); + + testWidgets('T30 - saving a WHITESPACE-ONLY field does the same', ( + tester, + ) async { + await _open(tester, connector, _contact(customName: 'Chuck')); + + await tester.enterText(find.byType(TextField), ' '); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + + expect(connector.calls.single.$2, isNull); + }); + + group('T25 and T26 the node name shows only when it differs', () { + testWidgets('+ shown while the typed name differs from the node name', ( + tester, + ) async { + await _open(tester, connector, _contact(customName: 'Chuck')); + + expect(find.textContaining(_received), findsOneWidget); + }); + + testWidgets('- not shown when the typed name IS the node name', ( + tester, + ) async { + // Otherwise the same string appears twice for no reason. + await _open(tester, connector, _contact(customName: _received)); + + expect(find.textContaining('Node name:'), findsNothing); + }); + }); + + group('T27 the length message appears only when it should', () { + testWidgets('- absent while the input is valid', (tester) async { + await _open(tester, connector, _contact()); + + await tester.enterText(find.byType(TextField), 'Chuck'); + await tester.pump(); + + expect(find.textContaining('Keep it under'), findsNothing); + }); + + testWidgets('+ present once the input is too long', (tester) async { + await _open(tester, connector, _contact()); + + await tester.enterText( + find.byType(TextField), + 'x' * (maxCustomNameLength + 1), + ); + await tester.pump(); + + expect(find.textContaining('Keep it under'), findsOneWidget); + }); + + testWidgets('- an over-length name cannot be saved at all', (tester) async { + await _open(tester, connector, _contact()); + + await tester.enterText( + find.byType(TextField), + 'x' * (maxCustomNameLength + 1), + ); + await tester.pump(); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + + expect(connector.calls, isEmpty); + }); + }); + + testWidgets('T28 + a name of CJK and ZWJ emoji saves intact', (tester) async { + // It never crosses the wire, so #636's grapheme truncation must not be + // applied to it. Counted in characters, so this is well within the cap. + const rich = 'ๆต‹่ฏ• ๐Ÿง™โ€โ™‚๏ธ Chuck'; + await _open(tester, connector, _contact()); + + await tester.enterText(find.byType(TextField), rich); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + + expect(connector.calls.single.$2, rich); + }); +} diff --git a/test/widgets/contact_verification_badge_test.dart b/test/widgets/contact_verification_badge_test.dart index 3eea4ace..27501733 100644 --- a/test/widgets/contact_verification_badge_test.dart +++ b/test/widgets/contact_verification_badge_test.dart @@ -22,7 +22,7 @@ const _key = '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'; Contact _contact({required DateTime lastSeen}) => Contact( publicKey: hex2Uint8List(_key), - name: 'Bob', + receivedName: 'Bob', type: advTypeChat, pathLength: -1, path: Uint8List(0), diff --git a/test/widgets/storage_reclaim_card_test.dart b/test/widgets/storage_reclaim_card_test.dart new file mode 100644 index 00000000..5a046d3f --- /dev/null +++ b/test/widgets/storage_reclaim_card_test.dart @@ -0,0 +1,363 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/l10n/app_localizations.dart'; +import 'package:meshcore_open/services/stale_history_sweep.dart'; +import 'package:meshcore_open/widgets/storage_reclaim_card.dart'; + +/// Epic B of #962, task B2. +/// +/// Tests the CARD, not the sweep. The sweep's behaviour is pinned by Epic A's +/// 18 unit tests, which run under plain `test()`. It cannot be re-run here: +/// it uses `compute`, and an isolate deadlocks `pumpAndSettle` inside +/// `flutter_test`'s fake-async zone, which is what made the first version of +/// this file hang past ten minutes rather than fail. So the sweep is injected +/// and each outcome is fed in directly. +/// +/// The case this task exists for is the third one: a key held back because its +/// rows could not be verified must be REPORTED, not merely logged. Owner +/// decision 2026-10-22. +void main() { + StaleHistoryOutcome outcome({ + List cleared = const [], + List refused = const [], + int before = 70 * 1024 * 1024, + int after = 70 * 1024 * 1024, + }) => StaleHistoryOutcome( + cleared: cleared, + refused: refused, + bytesBefore: before, + bytesAfter: after, + ); + + StaleHistoryPreview preview({ + List eligible = const ['a'], + List refused = const [], + int bytes = 16 * 1024 * 1024, + int messagesKept = 29975, + }) => StaleHistoryPreview( + eligible: eligible, + refused: refused, + approximateBytes: bytes, + messagesKept: messagesKept, + ); + + Future pump( + WidgetTester tester, { + required Future Function() runSweep, + Future Function()? runPreview, + Future Function()? readSize, + }) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: StorageReclaimCard( + runPreview: runPreview ?? () async => preview(), + runSweep: runSweep, + readSize: readSize ?? () async => 70 * 1024 * 1024, + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + Future confirm(WidgetTester tester) async { + await tester.tap(find.textContaining('Clear 1 copies')); + await tester.pumpAndSettle(); + } + + Future tapClear(WidgetTester tester) async { + await tester.tap(find.text('Clear Stale History Now')); + await tester.pumpAndSettle(); + } + + testWidgets('it shows the database size before anything is clicked', ( + tester, + ) async { + await pump(tester, runSweep: () async => outcome()); + + expect(find.textContaining('Message database:'), findsOneWidget); + expect(find.textContaining('70.0 MB'), findsOneWidget); + }); + + group('the confirmation (variants 8 to 10)', () { + testWidgets('it states the scope before anything is deleted', ( + tester, + ) async { + await pump(tester, runSweep: () async => outcome(cleared: const ['a'])); + + await tapClear(tester); + + expect(find.text('Clear stale history?'), findsOneWidget); + expect(find.textContaining('1 old copies'), findsOneWidget); + expect(find.textContaining('16.0 MB'), findsOneWidget); + expect(find.textContaining('All 29975 stay'), findsOneWidget); + expect(find.text('This cannot be undone.'), findsOneWidget); + // The action carries the count, so the scope is the last thing read. + expect(find.textContaining('Clear 1 copies'), findsOneWidget); + }); + + testWidgets('Cancel deletes nothing and re-enables the button', ( + tester, + ) async { + var swept = false; + await pump( + tester, + runSweep: () async { + swept = true; + return outcome(cleared: const ['a']); + }, + ); + + await tapClear(tester); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(swept, isFalse, reason: 'Cancel must not run the sweep'); + expect(find.text('Clear stale history?'), findsNothing); + expect(find.textContaining('Cleared'), findsNothing); + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + reason: 'cancelling must not leave the action dead for the session', + ); + }); + + testWidgets('a forecast refusal is shown BEFORE the press', (tester) async { + await pump( + tester, + runPreview: () async => preview(refused: const ['b']), + runSweep: () async => outcome(cleared: const ['a']), + ); + + await tapClear(tester); + + expect( + find.textContaining('1 will be kept back'), + findsOneWidget, + reason: 'knowing beforehand beats discovering it afterwards', + ); + expect(find.textContaining('cannot be undone'), findsOneWidget); + }); + + testWidgets('no eligible keys means no dialog at all', (tester) async { + await pump( + tester, + runPreview: () async => preview(eligible: const []), + runSweep: () async => outcome(), + ); + + await tapClear(tester); + + expect( + find.text('Clear stale history?'), + findsNothing, + reason: 'a dialog that only says zero is not worth opening', + ); + expect(find.text('Nothing to clear.'), findsOneWidget); + }); + + testWidgets('a refusal with nothing eligible still reports, no dialog', ( + tester, + ) async { + await pump( + tester, + runPreview: () async => + preview(eligible: const [], refused: const ['b']), + runSweep: () async => outcome(), + ); + + await tapClear(tester); + + expect(find.text('Clear stale history?'), findsNothing); + expect( + find.textContaining('Kept 1 that could not be verified'), + findsOneWidget, + ); + }); + + testWidgets('a preview failure reports and does not open a dialog', ( + tester, + ) async { + await pump( + tester, + runPreview: () async => throw StateError('no preview'), + runSweep: () async => outcome(cleared: const ['a']), + ); + + await tapClear(tester); + + expect(find.text('Clear stale history?'), findsNothing); + expect(find.textContaining('Could not finish'), findsOneWidget); + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + ); + }); + }); + + testWidgets('cleared keys report the count and the size returned', ( + tester, + ) async { + await pump( + tester, + runSweep: () async => outcome( + cleared: const ['a', 'b', 'c'], + before: 70 * 1024 * 1024, + after: 54 * 1024 * 1024, + ), + ); + + await tapClear(tester); + await confirm(tester); + + expect(find.textContaining('Cleared 3 old copies'), findsOneWidget); + expect(find.textContaining('16.0 MB returned'), findsOneWidget); + // And the size row updates to what the sweep actually left behind, rather + // than still showing the pre-sweep number. + expect(find.textContaining('Message database: 54.0 MB'), findsOneWidget); + }); + + testWidgets('a refused key is REPORTED, not just logged', (tester) async { + await pump( + tester, + runSweep: () async => outcome(cleared: const ['a'], refused: const ['b']), + ); + + await tapClear(tester); + await confirm(tester); + + expect( + find.textContaining('Kept 1 that could not be verified'), + findsOneWidget, + reason: 'silence here is how #952 went unnoticed for days', + ); + expect( + find.textContaining('messages are intact'), + findsOneWidget, + reason: + 'it has to say the history is safe, not only that something was ' + 'held back', + ); + // Both halves are shown: what went and what did not. + expect(find.textContaining('Cleared 1 old copies'), findsOneWidget); + }); + + testWidgets('refusals show even when nothing at all was cleared', ( + tester, + ) async { + await pump(tester, runSweep: () async => outcome(refused: const ['b'])); + + await tapClear(tester); + await confirm(tester); + + expect(find.text('Nothing to clear.'), findsOneWidget); + expect( + find.textContaining('Kept 1 that could not be verified'), + findsOneWidget, + reason: + 'a run that cleared nothing BECAUSE of a refusal is the most ' + 'important case to surface, not the least', + ); + }); + + testWidgets('a failure says the messages are intact', (tester) async { + // "Could not finish" on a delete action otherwise reads as "something was + // half-deleted". + await pump(tester, runSweep: () async => throw StateError('boom')); + + await tapClear(tester); + await confirm(tester); + + expect(find.textContaining('Could not finish'), findsOneWidget); + expect(find.textContaining('messages are intact'), findsOneWidget); + expect( + find.textContaining('may already have been cleared'), + findsOneWidget, + reason: + 'the sweep deletes per key, so a throw can follow real deletes and ' + 'the message must not claim nothing happened (Gemini review)', + ); + }); + + testWidgets('a second tap in the same frame cannot start a second sweep', ( + tester, + ) async { + // The disabled button is not enough: setState only SCHEDULES a rebuild, + // so two taps inside one frame both see a live onPressed. _clear guards + // on _running for that. + // + // A tap now starts the PREVIEW, not the sweep, so that is what has to be + // counted. Two previews would also mean two dialogs stacked on each other. + var previews = 0; + final gate = Completer(); + await pump( + tester, + runPreview: () { + previews++; + return gate.future; + }, + runSweep: () async => outcome(cleared: const ['a']), + ); + + final button = find.text('Clear Stale History Now'); + await tester.tap(button, warnIfMissed: false); + await tester.tap(button, warnIfMissed: false); + + expect( + previews, + 1, + reason: 'the second tap in the same frame must be ignored', + ); + + gate.complete(preview(eligible: const [])); + await tester.pumpAndSettle(); + }); + + testWidgets('the button is disabled while it runs', (tester) async { + final gate = Completer(); + await pump(tester, runSweep: () => gate.future); + + await tapClear(tester); + await confirm(tester); + await tester.pump(); + + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNull, + reason: 'a second tap mid-sweep would run two VACUUMs at once', + ); + expect(find.text('Clearing...'), findsOneWidget); + + gate.complete(outcome(cleared: const ['a'])); + await tester.pumpAndSettle(); + + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + reason: 'and it must come back, or the action works exactly once', + ); + }); + + testWidgets('an unreadable size leaves the row out rather than erroring', ( + tester, + ) async { + await pump( + tester, + runSweep: () async => outcome(), + readSize: () async => throw StateError('no size'), + ); + + expect(find.textContaining('Message database:'), findsNothing); + // The action is still usable: a size we cannot read is not a reason to + // block clearing. + expect( + tester.widget(find.byType(FilledButton)).onPressed, + isNotNull, + ); + }); +} diff --git a/untranslated.json b/untranslated.json index 33eda239..15068b60 100644 --- a/untranslated.json +++ b/untranslated.json @@ -1,12 +1,34 @@ { "bg": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -17,6 +39,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -56,6 +114,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -153,6 +221,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -231,17 +301,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "de": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -252,6 +375,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -291,6 +450,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -388,6 +557,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -466,17 +637,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "es": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -487,6 +711,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -526,6 +786,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -623,6 +893,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -701,17 +973,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "fr": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -722,6 +1047,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -761,6 +1122,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -858,6 +1229,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -936,17 +1309,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "hu": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -957,6 +1383,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -996,6 +1458,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1093,6 +1565,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -1171,17 +1645,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "it": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -1192,6 +1719,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -1231,6 +1794,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1328,6 +1901,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -1406,17 +1981,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "ja": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -1427,6 +2055,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -1466,6 +2130,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1563,6 +2237,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -1641,17 +2317,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "ko": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -1662,6 +2391,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -1701,6 +2466,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -1798,6 +2573,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -1876,17 +2653,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "nl": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -1897,6 +2727,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -1936,6 +2802,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2033,6 +2909,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -2111,17 +2989,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "pl": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -2132,6 +3063,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -2171,6 +3138,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2268,6 +3245,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -2346,17 +3325,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "pt": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -2367,6 +3399,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -2406,6 +3474,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2503,6 +3581,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -2581,17 +3661,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "ru": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -2602,6 +3735,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -2641,6 +3810,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2738,6 +3917,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -2816,17 +3997,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "sk": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -2837,6 +4071,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -2876,6 +4146,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -2973,6 +4253,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -3051,17 +4333,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "sl": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -3072,6 +4407,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -3111,6 +4482,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3208,6 +4589,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -3286,17 +4669,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "sv": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -3307,6 +4743,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -3346,6 +4818,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3443,6 +4925,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -3521,17 +5005,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "uk": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -3542,6 +5079,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -3581,6 +5154,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3678,6 +5261,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -3756,17 +5341,70 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ], "zh": [ + "common_stop", + "scanner_reconnecting", + "scanner_reconnectGaveUp", + "connectBusy", "scanner_connectFailedTransient", "scanner_connectFailedTimeout", "scanner_connectFailedGeneric", "scanner_bleReleaseWarning", "scanner_bleReleaseWarningMessage", + "deviceCli_title", + "deviceCli_remoteTitle", + "deviceCli_entrySubtitle", + "deviceCli_nameRejected", + "deviceCli_commandHint", + "deviceCli_emptyHint", + "deviceCli_noReply", + "deviceCli_remoteNoReply", + "deviceCli_remoteUnsupported", + "deviceCli_sendFailed", + "deviceCli_truncatedByDevice", + "deviceCli_secretLongPressToCopy", + "deviceCli_secretCopied", + "deviceCli_latencyMs", "settings_messageSettings", "settings_messageSettingsSubtitle", + "settings_nodeNameInvalidChars", + "settings_syncQueuedMessages", + "settings_syncQueuedMessagesSubtitle", + "settings_syncQueuedMessagesRequested", "settings_gpsStatusTitle", "settings_gpsStatusRefresh", "settings_gpsStatusLiveFix", @@ -3777,6 +5415,42 @@ "settings_gpsStatusTime", "settings_gpsStatusTapRefresh", "settings_gpsStatusNoResponse", + "settings_locationCategorySubtitle", + "settings_locationCoordinates", + "settings_locationNotSet", + "settings_locationReportInterval", + "settings_locationEveryMinutes", + "settings_locationEverySeconds", + "settings_gpsModeLabel", + "settings_gpsModeOff", + "settings_gpsModeOn", + "settings_gpsModePowerSave", + "settings_gpsActivityOff", + "settings_gpsActivityOn", + "settings_gpsActivitySearching", + "settings_gpsActivitySleeping", + "settings_gpsActivityBackedOff", + "settings_gpsOffDetail", + "settings_gpsNextTryMinutes", + "settings_gpsNextTrySeconds", + "settings_gpsLastFixMinutes", + "settings_gpsSatellites", + "settings_gpsQuery", + "settings_gpsReading", + "settings_gpsSleepTitle", + "settings_gpsSleepDefault", + "settings_gpsSleepFieldLabel", + "settings_gpsSleepFieldHint", + "settings_gpsSleepInvalid", + "settings_buttonActions", + "settings_buttonActionsSubtitle", + "settings_badgeScreen", + "settings_badgeScreenSubtitle", + "settings_badgeBattery", + "settings_badgeBatterySubtitle", + "settings_badgeBatteryReading", + "settings_buzzerTones", + "settings_buzzerTonesSubtitle", "settings_experimental", "settings_experimentalSubtitle", "settings_experimentalDescription", @@ -3816,6 +5490,16 @@ "appSettings_clock24h", "contacts_searchSensors", "contacts_manageSensor", + "contact_rename", + "contact_renameTitle", + "contact_renameHint", + "contact_renameExplain", + "contact_renameClear", + "contact_renameTooLong", + "contact_nodeCallsItself", + "contact_remoteCli", + "contact_remoteCliSubtitle", + "contact_cliConsole", "channels_notifications", "channels_notifyAll", "channels_notifyMentionsOnly", @@ -3913,6 +5597,8 @@ "block_settingsTitle", "block_settingsSubtitle", "block_none", + "block_noRadio", + "block_noRadioHint", "block_keysSection", "block_namesSection", "block_namesHint", @@ -3991,6 +5677,37 @@ "contactSyncDecisionBody", "contactSyncKeep", "contactSyncUseRadio", - "contactSyncConfirmedGone" + "contactSyncConfirmedGone", + "discoverRegions_title", + "discoverRegions_subtitle", + "discoverRegions_loading", + "discoverRegions_source", + "discoverRegions_empty", + "discoverRegions_timeout", + "discoverRegions_error", + "discoverRegions_retry", + "setRegionScope_menu", + "setRegionScope_title", + "setRegionScope_discover", + "setRegionScope_none", + "setRegionScope_save", + "setRegionScope_searchRepeaters", + "setRegionScope_pathNote", + "setRegionScope_noPath", + "storage_title", + "storage_databaseSize", + "storage_staleHint", + "storage_clearStaleNow", + "storage_working", + "storage_resultNothing", + "storage_resultCleared", + "storage_resultRefused", + "storage_confirmTitle", + "storage_confirmBody", + "storage_confirmSafe", + "storage_confirmIrreversible", + "storage_confirmKeptBack", + "storage_confirmAction", + "storage_resultFailed" ] } diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp index 9eda059a..5560cc16 100644 --- a/windows/runner/flutter_window.cpp +++ b/windows/runner/flutter_window.cpp @@ -11,7 +11,27 @@ FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} -FlutterWindow::~FlutterWindow() {} +FlutterWindow::~FlutterWindow() { + // Destroy the controller with the member ALREADY null. (#984) + // + // This destructor is reached without OnDestroy() having run whenever the + // message loop ends before the window is destroyed. windowManager.destroy() + // does exactly that: in window_manager 0.5.2, Destroy() is only + // PostQuitMessage(0), so WM_DESTROY is never sent and OnDestroy()'s safe + // reset never happens. + // + // Left to the member destructor, the controller was deleted by + // ~unique_ptr, which in MSVC does NOT null the pointer first (reset() does). + // While the engine tore down, the still-live top-level window received a + // message, MessageHandler saw a non-null flutter_controller_, and forwarded + // into the half-destroyed view: FlutterWindowsView::GetEngine read freed + // memory and the app crashed on close. + // + // Moving it out leaves flutter_controller_ null for the whole teardown, so + // MessageHandler's guard holds no matter which path ended the loop. + auto controller = std::move(flutter_controller_); + controller.reset(); +} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp index baf81c41..ad06e597 100644 --- a/windows/runner/main.cpp +++ b/windows/runner/main.cpp @@ -24,18 +24,26 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); - FlutterWindow window(project); - Win32Window::Point origin(10, 10); - Win32Window::Size size(1280, 720); - if (!window.Create(L"Offband Meshcore", origin, size)) { - return EXIT_FAILURE; - } - window.SetQuitOnClose(true); - - ::MSG msg; - while (::GetMessage(&msg, nullptr, 0, 0)) { - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); + // Scoped so the window, and the engine inside it, is destroyed BEFORE + // CoUninitialize below. Accessibility (UIAutomationCore) and text input + // (msctf) are COM-based and both sit on the #984 crash stack: tearing them + // down after COM has been uninitialized is undefined behaviour. Previously + // `window` was a plain local, destroyed by the return statement, i.e. after + // CoUninitialize had already run. (#984) + { + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"Offband Meshcore", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } } ::CoUninitialize();