feat(#406): observer config-profile preview/diff sub-screen

- config_profile_diff.dart: pure current->new diff builder (add/change,
  drops no-ops, flags danger + secret rows). 4 tests.
- splitProfileWrites: partitions writes into safe vs credential/identity for
  the two-tier apply; a mixed broker splits, enabled rides the safe half only.
- ConfigProfilePreviewScreen: full sub-screen — reads current state, renders
  the diff (amber overwrites, red danger section), normal Apply for plain
  config + a separate red gate (with confirm dialog listing exactly which
  credential/identity values change) for the danger set. Secrets masked.
  Re-diffs after apply for partial-save recovery.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
pull/455/head
Strycher 4 months ago
parent ef7629fd64
commit 239954644a

@ -0,0 +1,125 @@
import '../models/config_profile.dart';
import 'config_profile_writes.dart';
/// Builds the human-facing diff for a profile apply (#406): current → new, per
/// field, categorized so the preview can render its two-tier confirm.
///
/// Pure — the screen fetches current device values and passes them in, so this
/// is unit-testable without a device.
enum DiffKind {
/// Device has no value; the profile sets one.
add,
/// Device has a value; the profile sets a different one.
change,
}
class DiffRow {
const DiffRow({
required this.label,
required this.oldValue,
required this.newValue,
required this.kind,
required this.danger,
required this.secret,
});
/// Firmware key (flat) or `broker N.<field>` — never a value, safe to show.
final String label;
/// Current on-device value, or null if unknown/unreadable (e.g. write-only
/// `wifi.pwd`) or absent.
final String? oldValue;
final String newValue;
final DiffKind kind;
/// In the credential/identity danger set — routed to the red gate.
final bool danger;
/// A true secret (password / wifi.pwd) — the UI must mask both values.
final bool secret;
}
class ProfileDiff {
const ProfileDiff(this.rows);
final List<DiffRow> rows;
bool get isEmpty => rows.isEmpty;
List<DiffRow> get dangerRows => rows.where((r) => r.danger).toList();
List<DiffRow> get safeRows => rows.where((r) => !r.danger).toList();
bool get hasDanger => rows.any((r) => r.danger);
}
/// Broker sub-keys + flat keys that hold true secrets (mask both values).
const Set<String> _secretBrokerFields = {ConfigKeys.brokerPassword};
const Set<String> _secretFlatKeys = {ConfigKeys.wifiPassword};
/// Build the diff. [currentFlat] maps a flat key → current value (null =
/// unknown/absent). [currentBroker] maps slot → (subkey → current value).
/// Rows where the new value equals the current value are dropped (no-op).
ProfileDiff buildProfileDiff(
ProfileWrites writes, {
required Map<String, String?> currentFlat,
required Map<int, Map<String, String?>> currentBroker,
}) {
final rows = <DiffRow>[];
for (final f in writes.flats) {
final current = currentFlat[f.key];
if (current == f.value) continue; // unchanged
rows.add(
DiffRow(
label: f.key,
oldValue: current,
newValue: f.value,
kind: (current == null || current.isEmpty)
? DiffKind.add
: DiffKind.change,
danger: f.danger,
secret: _secretFlatKeys.contains(f.key),
),
);
}
for (final b in writes.brokers) {
final cur = currentBroker[b.slot] ?? const {};
for (final entry in b.fields.entries) {
final current = cur[entry.key];
if (current == entry.value) continue; // unchanged
rows.add(
DiffRow(
label: 'broker ${b.slot}.${entry.key}',
oldValue: current,
newValue: entry.value,
kind: (current == null || current.isEmpty)
? DiffKind.add
: DiffKind.change,
danger: b.dangerFields.contains(entry.key),
secret: _secretBrokerFields.contains(entry.key),
),
);
}
// enabled change (add/change), never danger/secret
if (b.enabled != null) {
final current = cur[ConfigKeys.brokerEnabled];
final newVal = b.enabled! ? '1' : '0';
if (current != newVal) {
rows.add(
DiffRow(
label: 'broker ${b.slot}.${ConfigKeys.brokerEnabled}',
oldValue: current,
newValue: newVal,
kind: (current == null || current.isEmpty)
? DiffKind.add
: DiffKind.change,
danger: false,
secret: false,
),
);
}
}
}
return ProfileDiff(rows);
}

@ -63,6 +63,55 @@ class ProfileWrites {
brokers.any((b) => b.dangerFields.isNotEmpty);
}
/// Partition writes into (safe, danger) so the preview's two buttons each apply
/// their own set: the normal Apply writes safe changes; the red gate writes the
/// credential/identity ones. A broker with both is split across both — its
/// `enabled` toggle rides with the safe half only.
({ProfileWrites safe, ProfileWrites danger}) splitProfileWrites(
ProfileWrites w,
) {
final safeFlats = w.flats.where((f) => !f.danger).toList();
final dangerFlats = w.flats.where((f) => f.danger).toList();
final safeBrokers = <BrokerWrites>[];
final dangerBrokers = <BrokerWrites>[];
for (final b in w.brokers) {
final safeFields = <String, String>{
for (final e in b.fields.entries)
if (!b.dangerFields.contains(e.key)) e.key: e.value,
};
final dangerFields = <String, String>{
for (final e in b.fields.entries)
if (b.dangerFields.contains(e.key)) e.key: e.value,
};
if (safeFields.isNotEmpty || b.enabled != null) {
safeBrokers.add(
BrokerWrites(
slot: b.slot,
fields: safeFields,
enabled: b.enabled,
dangerFields: const {},
),
);
}
if (dangerFields.isNotEmpty) {
dangerBrokers.add(
BrokerWrites(
slot: b.slot,
fields: dangerFields,
enabled: null, // never toggle activation from the credential pass
dangerFields: dangerFields.keys.toSet(),
),
);
}
}
return (
safe: ProfileWrites(flats: safeFlats, brokers: safeBrokers),
danger: ProfileWrites(flats: dangerFlats, brokers: dangerBrokers),
);
}
bool _blank(String? v) => v == null || v.isEmpty;
ProfileWrites enumerateProfileWrites(ConfigProfile p) {

@ -0,0 +1,323 @@
import 'package:flutter/material.dart';
import '../../helpers/config_profile_diff.dart';
import '../../helpers/config_profile_writes.dart';
import '../../models/config_profile.dart';
import '../../services/observer_apply_service.dart';
import '../../services/observer_config_service.dart';
/// Full sub-screen preview of a config-profile apply (#406): shows the current
/// -> new diff, then a two-tier confirm — a normal Apply for plain config, and a
/// separate red gate for credential/identity changes.
class ConfigProfilePreviewScreen extends StatefulWidget {
const ConfigProfilePreviewScreen({
super.key,
required this.profile,
required this.service,
});
final ConfigProfile profile;
final ObserverConfigService service;
@override
State<ConfigProfilePreviewScreen> createState() =>
_ConfigProfilePreviewScreenState();
}
class _ConfigProfilePreviewScreenState
extends State<ConfigProfilePreviewScreen> {
late ProfileWrites _writes;
ProfileDiff? _diff;
String? _error;
bool _loading = true;
bool _applying = false;
@override
void initState() {
super.initState();
_writes = enumerateProfileWrites(widget.profile);
_load();
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
try {
final currentFlat = <String, String?>{};
for (final f in _writes.flats) {
currentFlat[f.key] = await widget.service.getFlat(f.key);
}
final currentBroker = <int, Map<String, String?>>{};
for (final b in _writes.brokers) {
final m = <String, String?>{};
for (final key in [...b.fields.keys, ConfigKeys.brokerEnabled]) {
m[key] = await widget.service.getFlat(ConfigKeys.broker(b.slot, key));
}
currentBroker[b.slot] = m;
}
final diff = buildProfileDiff(
_writes,
currentFlat: currentFlat,
currentBroker: currentBroker,
);
if (mounted) setState(() => _diff = diff);
} catch (e) {
if (mounted) setState(() => _error = 'Could not read current config: $e');
} finally {
if (mounted) setState(() => _loading = false);
}
}
Future<void> _apply(ProfileWrites writes, String what) async {
setState(() => _applying = true);
try {
final result = await ObserverApplyService(widget.service).apply(writes);
if (!mounted) return;
final msg = result.allOk
? '$what applied.'
: '$what: ${result.failures.length} of ${result.items.length} failed '
'(${result.failures.first.error ?? 'error'}).';
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(msg),
backgroundColor: result.allOk
? null
: Theme.of(context).colorScheme.error,
),
);
await _load(); // re-diff against true state (partial-save recovery)
} finally {
if (mounted) setState(() => _applying = false);
}
}
@override
Widget build(BuildContext context) {
final diff = _diff;
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text('Review config profile'),
),
body: _loading
? const Center(child: CircularProgressIndicator())
: _error != null
? _ErrorView(message: _error!, onRetry: _load)
: diff == null
? const SizedBox.shrink()
: _buildBody(context, diff),
);
}
Widget _buildBody(BuildContext context, ProfileDiff diff) {
if (diff.isEmpty) {
return const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Text(
'No changes — the device already matches this profile.',
textAlign: TextAlign.center,
),
),
);
}
final theme = Theme.of(context);
final split = splitProfileWrites(_writes);
return Column(
children: [
if (widget.profile.name != null)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
widget.profile.name!,
style: theme.textTheme.titleMedium,
),
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.all(16),
children: [
for (final r in diff.safeRows) _DiffTile(row: r),
if (diff.hasDanger) ...[
const SizedBox(height: 16),
_DangerHeader(count: diff.dangerRows.length),
for (final r in diff.dangerRows)
_DiffTile(row: r, danger: true),
],
],
),
),
SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
FilledButton(
onPressed: _applying || diff.safeRows.isEmpty
? null
: () => _apply(split.safe, 'Config changes'),
child: Text(
diff.safeRows.isEmpty
? 'No plain-config changes'
: 'Apply ${diff.safeRows.length} config change'
'${diff.safeRows.length == 1 ? '' : 's'}',
),
),
if (diff.hasDanger) ...[
const SizedBox(height: 8),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: theme.colorScheme.error,
foregroundColor: theme.colorScheme.onError,
),
onPressed: _applying
? null
: () => _confirmDanger(context, split.danger, diff),
child: Text(
'Danger: change ${diff.dangerRows.length} '
'credential/identity value'
'${diff.dangerRows.length == 1 ? '' : 's'}',
),
),
],
],
),
),
),
],
);
}
Future<void> _confirmDanger(
BuildContext context,
ProfileWrites dangerWrites,
ProfileDiff diff,
) async {
final theme = Theme.of(context);
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Change credential / identity values?'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'These bind this device to an identity or credentials. Only proceed '
'if you trust this profile:',
),
const SizedBox(height: 12),
for (final r in diff.dangerRows)
Text('• ${r.label}', style: theme.textTheme.bodySmall),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('Cancel'),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: theme.colorScheme.error,
foregroundColor: theme.colorScheme.onError,
),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('Change them'),
),
],
),
);
if (ok == true) await _apply(dangerWrites, 'Credential changes');
}
}
class _DiffTile extends StatelessWidget {
const _DiffTile({required this.row, this.danger = false});
final DiffRow row;
final bool danger;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final isChange = row.kind == DiffKind.change;
final newText = row.secret ? '••••••' : row.newValue;
final oldText = row.secret
? '—'
: (row.oldValue == null || row.oldValue!.isEmpty ? '—' : row.oldValue!);
final accent = danger
? theme.colorScheme.error
: isChange
? Colors.amber.shade800
: theme.colorScheme.primary;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: ListTile(
leading: Icon(
isChange ? Icons.edit_outlined : Icons.add_circle_outline,
color: accent,
),
title: Text(row.label, style: theme.textTheme.bodyMedium),
subtitle: Text(
isChange ? '$oldText → $newText' : 'set to $newText',
style: theme.textTheme.bodySmall,
),
),
);
}
}
class _DangerHeader extends StatelessWidget {
const _DangerHeader({required this.count});
final int count;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Padding(
padding: const EdgeInsets.only(bottom: 8, top: 4),
child: Row(
children: [
Icon(Icons.warning_amber_rounded, color: theme.colorScheme.error),
const SizedBox(width: 8),
Expanded(
child: Text(
'Credential / identity changes ($count) — require the red button',
style: theme.textTheme.titleSmall?.copyWith(
color: theme.colorScheme.error,
),
),
),
],
),
);
}
}
class _ErrorView extends StatelessWidget {
const _ErrorView({required this.message, required this.onRetry});
final String message;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 16),
FilledButton(onPressed: onRetry, child: const Text('Retry')),
],
),
),
);
}
}

@ -0,0 +1,96 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:meshcore_open/helpers/config_profile_diff.dart';
import 'package:meshcore_open/helpers/config_profile_writes.dart';
import 'package:meshcore_open/models/config_profile.dart';
ProfileWrites _writes(ConfigProfile p) => enumerateProfileWrites(p);
void main() {
group('buildProfileDiff', () {
test('categorizes add vs change and drops unchanged', () {
final w = _writes(
const ConfigProfile(
schemaVersion: 1,
regionIata: 'IAD',
statusInterval: 60,
),
);
final d = buildProfileDiff(
w,
currentFlat: {
ConfigKeys.mqttIata: 'LHR', // change
ConfigKeys.mqttStatusInterval: '60', // unchanged -> dropped
},
currentBroker: const {},
);
expect(d.rows.length, 1);
expect(d.rows.single.label, ConfigKeys.mqttIata);
expect(d.rows.single.kind, DiffKind.change);
expect(d.rows.single.oldValue, 'LHR');
expect(d.rows.single.newValue, 'IAD');
});
test('add when device has no current value', () {
final w = _writes(
const ConfigProfile(schemaVersion: 1, regionIata: 'IAD'),
);
final d = buildProfileDiff(
w,
currentFlat: const {},
currentBroker: const {},
);
expect(d.rows.single.kind, DiffKind.add);
expect(d.rows.single.oldValue, isNull);
});
test('flags danger + secret rows', () {
final w = _writes(
const ConfigProfile(
schemaVersion: 1,
wifi: WifiConfig(password: 'pw'),
brokers: [
BrokerConfig(slot: 0, username: 'u', password: 'p', url: 'h'),
],
),
);
final d = buildProfileDiff(
w,
currentFlat: const {},
currentBroker: const {},
);
expect(d.hasDanger, isTrue);
// wifi.pwd + broker password + username are danger; url is not
final danger = d.dangerRows.map((r) => r.label).toSet();
expect(danger, contains(ConfigKeys.wifiPassword));
expect(danger, contains('broker 0.${ConfigKeys.brokerPassword}'));
expect(danger, contains('broker 0.${ConfigKeys.brokerUsername}'));
expect(danger.contains('broker 0.${ConfigKeys.brokerUrl}'), isFalse);
// secrets: password + wifi.pwd; username is danger but not secret
final secrets = d.rows.where((r) => r.secret).map((r) => r.label).toSet();
expect(secrets, {
ConfigKeys.wifiPassword,
'broker 0.${ConfigKeys.brokerPassword}',
});
});
test('broker enabled change is a plain (non-danger) row', () {
final w = _writes(
const ConfigProfile(
schemaVersion: 1,
brokers: [BrokerConfig(slot: 2, enabled: true, url: 'h')],
),
);
final d = buildProfileDiff(
w,
currentFlat: const {},
currentBroker: {
2: {ConfigKeys.brokerEnabled: '0', ConfigKeys.brokerUrl: 'h'},
},
);
// url unchanged (h==h) dropped; enabled 0->1 present, not danger
final labels = d.rows.map((r) => r.label).toList();
expect(labels, ['broker 2.${ConfigKeys.brokerEnabled}']);
expect(d.rows.single.danger, isFalse);
});
});
}

@ -127,4 +127,43 @@ void main() {
expect(w.brokers, isEmpty);
});
});
group('splitProfileWrites', () {
test('splits a mixed broker; enabled rides with safe half only', () {
final w = enumerateProfileWrites(
const ConfigProfile(
schemaVersion: 1,
wifi: WifiConfig(ssid: 'net', password: 'pw', enabled: true),
brokers: [
BrokerConfig(
slot: 0,
url: 'h',
username: 'u',
password: 'p',
enabled: true,
),
],
),
);
final s = splitProfileWrites(w);
// safe: wifi.ssid + wifi.enabled flats; broker url + enabled
final safeFlatKeys = s.safe.flats.map((f) => f.key).toSet();
expect(safeFlatKeys, contains(ConfigKeys.wifiSsid));
expect(safeFlatKeys, contains(ConfigKeys.wifiEnabled));
expect(safeFlatKeys.contains(ConfigKeys.wifiPassword), isFalse);
expect(s.safe.brokers.single.fields.keys, contains(ConfigKeys.brokerUrl));
expect(s.safe.brokers.single.enabled, true);
// danger: wifi.pwd flat; broker username + password, enabled NOT toggled
final dangerFlatKeys = s.danger.flats.map((f) => f.key).toSet();
expect(dangerFlatKeys, {ConfigKeys.wifiPassword});
final db = s.danger.brokers.single;
expect(db.fields.keys.toSet(), {
ConfigKeys.brokerUsername,
ConfigKeys.brokerPassword,
});
expect(db.enabled, isNull);
});
});
}

Loading…
Cancel
Save

Powered by TurnKey Linux.