LifeMate — Personal, Family & Learning Companion
feat(reminders): reconcile owner alarms with device consent and private settings
Quinn White committed
Oct 18, 2026 at 21:50 UTC
0be1c67a710e69b57733f5b831d38ce9ef0b7e58
11 files changed
+972
-9
apps/lifemate/lib/api.dart
+24
-2
@@ -6,6 +6,7 @@ import 'runtime_config.dart';
6
import 'runtime_http_client.dart';
7
import 'session_store.dart';
8
import 'web_instance.dart';
9
+import 'local_reminders.dart';
10
11
abstract class IdentityApi {
12
String? get accessToken;
@@ -147,6 +148,7 @@ class HttpIdentityApi implements IdentityApi {
148
this.onSessionChanged,
149
this.onScopeDiscarded,
150
this.onScopeQuarantined,
151
+ this.onSessionDeactivating,
152
}) : baseUrl = normalizeApiUrl(
153
baseUrl ?? (throw ArgumentError('API configuration is required.'))),
154
_client = client ?? createRuntimeHttpClient(),
@@ -162,9 +164,13 @@ class HttpIdentityApi implements IdentityApi {
164
void Function()? onSessionChanged;
165
Future<void> Function(String)? onScopeDiscarded;
166
Future<void> Function(String)? onScopeQuarantined;
167
+ Future<void> Function()? onSessionDeactivating;
168
bool hasQuarantinedSession = false;
169
Future<void>? _refreshing;
170
int _sessionGeneration = 0;
171
+
172
+ /// Changes on logout, expiry and endpoint disposal, not ordinary refresh.
173
+ int get sessionRevision => _sessionGeneration;
174
String? currentUserId;
175
String get endpointIdentity => baseUrl;
176
String? get cacheNamespace => accessToken == null || currentUserId == null
@@ -291,11 +297,21 @@ class HttpIdentityApi implements IdentityApi {
297
{bool quarantine = false, String? scopeOverride}) async {
298
final scope = scopeOverride ??
299
(currentUserId == null ? null : '$endpointIdentity|$currentUserId');
300
+ Object? failure;
301
+ StackTrace? failureStack;
302
+ Future<void>? reminderCancellation;
303
+ try {
304
+ // Invalidate queued native scheduling synchronously before identity/cache
305
+ // changes; native cancellation completes before credential storage clears.
306
+ reminderCancellation =
307
+ (onSessionDeactivating ?? androidLocalReminders.deactivate)();
308
+ } catch (error, stack) {
309
+ failure = error;
310
+ failureStack = stack;
311
+ }
312
accessToken = null;
313
_refreshToken = null;
314
currentUserId = null;
297
- Object? failure;
298
- StackTrace? failureStack;
315
Future<void>? quarantinePending;
316
// Invalidate old cache handles synchronously, before notifying the signed
317
// out UI or awaiting credential storage. Quarantine performs no disk writes.
@@ -308,6 +324,12 @@ class HttpIdentityApi implements IdentityApi {
324
failureStack = stack;
325
}
326
onSessionChanged?.call();
327
+ try {
328
+ await reminderCancellation;
329
+ } catch (error, stack) {
330
+ failure ??= error;
331
+ failureStack ??= stack;
332
+ }
333
try {
334
await _sessionStore.clear();
335
} catch (error, stack) {
apps/lifemate/lib/device_reminder_coordinator.dart
new
+136
@@ -0,0 +1,136 @@
1
+import 'api.dart';
2
+import 'local_reminders.dart';
3
+import 'offline_store.dart';
4
+import 'plan_sync.dart';
5
+import 'device_reminder_preferences.dart';
6
+
7
+/// Online owner-only reminder reconciliation. Cached data never renews a lease.
8
+final class DeviceReminderCoordinator {
9
+ DeviceReminderCoordinator(this.api,
10
+ {LocalReminderPort? port, DateTime Function()? now, OfflineStore? store})
11
+ : port = port ?? androidLocalReminders,
12
+ _now = now ?? DateTime.now,
13
+ _store = store;
14
+ final HttpIdentityApi api;
15
+ final LocalReminderPort port;
16
+ final DateTime Function() _now;
17
+ final OfflineStore? _store;
18
+ static int _intentEpoch = 0;
19
+ static final _uuid = RegExp(
20
+ r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$');
21
+
22
+ @override
23
+ String toString() =>
24
+ 'DeviceReminderCoordinator'; // Never include scope or credentials.
25
+
26
+ Future<LocalReminderStatus> status() => port.status();
27
+ Future<LocalReminderStatus> disable() async {
28
+ ++_intentEpoch;
29
+ await port.deactivate();
30
+ return port.status();
31
+ }
32
+
33
+ Future<LocalReminderStatus> requestExactAlarmAccess() =>
34
+ port.requestExactAlarmAccess();
35
+
36
+ Future<LocalReminderStatus> enable({String? companionName}) async {
37
+ final intent = ++_intentEpoch;
38
+ final allowed = await port.requestPermission();
39
+ if (!allowed.supported || !allowed.permissionGranted) {
40
+ throw const ApiException(0, 'device_notifications_not_allowed');
41
+ }
42
+ return _load(companionName, intent);
43
+ }
44
+
45
+ Future<LocalReminderStatus> reconcile({String? companionName}) async {
46
+ final intent = _intentEpoch;
47
+ final current = await port.status();
48
+ if (!current.active || current.activeScope != api.cacheNamespace) {
49
+ return current;
50
+ }
51
+ return _load(companionName, intent);
52
+ }
53
+
54
+ Future<LocalReminderStatus> _load(String? companionName, int intent) async {
55
+ final scope = api.cacheNamespace;
56
+ final owner = api.currentUserId;
57
+ final token = api.accessToken;
58
+ final revision = api.sessionRevision;
59
+ if (scope == null || owner == null || token == null) {
60
+ throw const ApiException(401, 'authenticated_cache_required');
61
+ }
62
+ void requireSameSession() {
63
+ if (intent != _intentEpoch) {
64
+ throw const ApiException(409, 'device_notification_intent_changed');
65
+ }
66
+ if (api.cacheNamespace != scope ||
67
+ api.currentUserId != owner ||
68
+ api.sessionRevision != revision ||
69
+ api.accessToken == null) {
70
+ throw const ApiException(401, 'session_expired');
71
+ }
72
+ }
73
+
74
+ final nickname =
75
+ companionName ?? await DeviceReminderPreferences().read(scope);
76
+ requireSameSession();
77
+ final from = _now().toUtc();
78
+ final path = Uri(path: '/v1/planner-reminders', queryParameters: {
79
+ 'from': from.toIso8601String(),
80
+ 'to': from.add(const Duration(hours: 24)).toIso8601String(),
81
+ }).toString();
82
+ final result = await api.requestJson('GET', path);
83
+ requireSameSession();
84
+ final received = _now().toUtc();
85
+ final asOf = result['asOf'] is String
86
+ ? DateTime.tryParse(result['asOf'] as String)
87
+ : null;
88
+ final raw = result['reminders'];
89
+ if (asOf == null ||
90
+ asOf.isBefore(received.subtract(const Duration(minutes: 2))) ||
91
+ asOf.isAfter(received.add(const Duration(minutes: 1))) ||
92
+ raw is! List ||
93
+ raw.length > 128) {
94
+ throw const ApiException(502, 'invalid_api_response');
95
+ }
96
+ final rows = <LocalReminder>[];
97
+ final ids = <String>{};
98
+ for (final entry in raw) {
99
+ if (entry is! Map ||
100
+ entry['id'] is! String ||
101
+ entry['plan_item_id'] is! String ||
102
+ !_uuid.hasMatch(entry['id'] as String) ||
103
+ !_uuid.hasMatch(entry['plan_item_id'] as String) ||
104
+ !ids.add(entry['id'] as String) ||
105
+ entry['owner_user_id'] != owner ||
106
+ entry['scheduled_for'] is! String) {
107
+ throw const ApiException(502, 'invalid_api_response');
108
+ }
109
+ final at = DateTime.tryParse(entry['scheduled_for'] as String);
110
+ if (at == null) throw const ApiException(502, 'invalid_api_response');
111
+ rows.add(LocalReminder(
112
+ id: entry['id'] as String,
113
+ planItemId: entry['plan_item_id'] as String,
114
+ scheduledAt: at.toUtc(),
115
+ companionName: nickname,
116
+ ownerUserId: owner,
117
+ serverAcknowledged: true));
118
+ }
119
+ final store = _store ?? OfflineStore.forApi(api);
120
+ await PlanSync(api, store: store, reminders: port)
121
+ .withLocalMutationLock(() async {
122
+ requireSameSession();
123
+ final pending =
124
+ (await store.readQueue()).map((entry) => entry['entityId']).toSet();
125
+ requireSameSession();
126
+ final until = _now().toUtc().add(const Duration(hours: 24));
127
+ await port.activate(scope, validUntil: until);
128
+ requireSameSession();
129
+ await port.replace(scope,
130
+ rows.where((row) => !pending.contains(row.planItemId)).toList(),
131
+ currentUserId: owner);
132
+ });
133
+ requireSameSession();
134
+ return port.status();
135
+ }
136
+}
apps/lifemate/lib/device_reminder_preferences.dart
new
+33
@@ -0,0 +1,33 @@
1
+import 'dart:convert';
2
+import 'package:flutter/widgets.dart' show StringCharacters;
3
+import 'package:shared_preferences/shared_preferences.dart';
4
+
5
+/// Harmless display preferences; never an identity, permission or task cache.
6
+final class DeviceReminderPreferences {
7
+ final SharedPreferencesAsync _preferences = SharedPreferencesAsync();
8
+ static final _controls =
9
+ RegExp(r'[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]');
10
+ String _key(String scope) {
11
+ if (scope.isEmpty || scope.length > 4096) {
12
+ throw ArgumentError('Invalid preference scope.');
13
+ }
14
+ return 'lifeguide.reminder_companion.v1.${base64Url.encode(utf8.encode(scope))}';
15
+ }
16
+
17
+ static bool valid(String value) =>
18
+ value.length <= 4096 &&
19
+ value.characters.length <= 40 &&
20
+ !_controls.hasMatch(value);
21
+ Future<String> read(String scope) async {
22
+ final value = await _preferences.getString(_key(scope));
23
+ if (value == null || !valid(value) || value.trim().isEmpty) {
24
+ return 'LifeGuide';
25
+ }
26
+ return value.trim();
27
+ }
28
+
29
+ Future<void> write(String scope, String nickname) async {
30
+ if (!valid(nickname)) throw ArgumentError('Invalid companion nickname.');
31
+ await _preferences.setString(_key(scope), nickname.trim());
32
+ }
33
+}
apps/lifemate/lib/device_reminder_settings.dart
new
+198
@@ -0,0 +1,198 @@
1
+import 'package:flutter/material.dart';
2
+import 'api.dart';
3
+import 'device_reminder_coordinator.dart';
4
+import 'device_reminder_preferences.dart';
5
+import 'local_reminders.dart';
6
+
7
+class DeviceReminderSettingsPage extends StatefulWidget {
8
+ const DeviceReminderSettingsPage(
9
+ {super.key, required this.api, this.coordinator});
10
+ final HttpIdentityApi api;
11
+ final DeviceReminderCoordinator? coordinator;
12
+ @override
13
+ State<DeviceReminderSettingsPage> createState() =>
14
+ _DeviceReminderSettingsPageState();
15
+}
16
+
17
+class _DeviceReminderSettingsPageState extends State<DeviceReminderSettingsPage>
18
+ with WidgetsBindingObserver {
19
+ final _nickname = TextEditingController();
20
+ final _preferences = DeviceReminderPreferences();
21
+ LocalReminderStatus? _status;
22
+ String? _error;
23
+ bool _busy = true;
24
+ DeviceReminderCoordinator get _coordinator =>
25
+ widget.coordinator ?? DeviceReminderCoordinator(widget.api);
26
+ @override
27
+ void initState() {
28
+ super.initState();
29
+ WidgetsBinding.instance.addObserver(this);
30
+ _run(_load);
31
+ }
32
+
33
+ @override
34
+ void dispose() {
35
+ WidgetsBinding.instance.removeObserver(this);
36
+ _nickname.dispose();
37
+ super.dispose();
38
+ }
39
+
40
+ @override
41
+ void didChangeAppLifecycleState(AppLifecycleState state) {
42
+ if (state == AppLifecycleState.resumed && !_busy) _run(_refresh);
43
+ }
44
+
45
+ Future<void> _load() async {
46
+ final scope = widget.api.cacheNamespace;
47
+ if (scope == null) throw const ApiException(401, 'session_expired');
48
+ final name = await _preferences.read(scope);
49
+ final status = await _coordinator.status();
50
+ if (!mounted || widget.api.cacheNamespace != scope) return;
51
+ _nickname.text = name;
52
+ _status = status;
53
+ }
54
+
55
+ Future<void> _refresh() async {
56
+ _status = await _coordinator.reconcile();
57
+ }
58
+
59
+ Future<void> _run(Future<void> Function() work) async {
60
+ if (mounted) {
61
+ setState(() {
62
+ _busy = true;
63
+ _error = null;
64
+ });
65
+ }
66
+ try {
67
+ await work();
68
+ } catch (error) {
69
+ if (mounted) {
70
+ _error = error is ArgumentError
71
+ ? 'نام همراه باید حداکثر ۴۰ نویسه باشد و کاراکتر کنترلی نداشته باشد.'
72
+ : error is ApiException && error.statusCode == 429
73
+ ? 'درخواستها زیاد است؛ کمی بعد دوباره تلاش کنید.'
74
+ : error is ApiException && error.statusCode == 401
75
+ ? 'نشست پایان یافته؛ دوباره وارد شوید.'
76
+ : 'یادآوری آماده نشد. اتصال، مجوز اعلان و تنظیمات دستگاه را بررسی کنید؛ مهلت قبلی تمدید نشد.';
77
+ }
78
+ } finally {
79
+ if (mounted) {
80
+ setState(() {
81
+ _busy = false;
82
+ });
83
+ }
84
+ }
85
+ }
86
+
87
+ Future<void> _saveNickname() async {
88
+ final scope = widget.api.cacheNamespace;
89
+ if (scope == null) throw const ApiException(401, 'session_expired');
90
+ await _preferences.write(scope, _nickname.text);
91
+ _status = await _coordinator.reconcile();
92
+ }
93
+
94
+ String _localTime(DateTime value) {
95
+ final local = value.toLocal();
96
+ String two(int n) => '$n'.padLeft(2, '0');
97
+ return '${local.year}/${two(local.month)}/${two(local.day)}، ${two(local.hour)}:${two(local.minute)}';
98
+ }
99
+
100
+ @override
101
+ Widget build(BuildContext context) {
102
+ final status = _status;
103
+ final owned = status?.activeScope == widget.api.cacheNamespace;
104
+ final enabled = status?.active == true && owned;
105
+ final supported = status?.supported == true;
106
+ return Directionality(
107
+ textDirection: TextDirection.rtl,
108
+ child: Scaffold(
109
+ appBar: AppBar(title: const Text('یادآوری و نام همراه')),
110
+ body: ListView(padding: const EdgeInsets.all(16), children: [
111
+ const Text('همراهِ خودت',
112
+ style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20)),
113
+ const SizedBox(height: 12),
114
+ TextField(
115
+ key: const ValueKey('companion-nickname'),
116
+ controller: _nickname,
117
+ maxLength: 40,
118
+ enabled: !_busy,
119
+ decoration: const InputDecoration(
120
+ labelText: 'نام همراه',
121
+ hintText: 'LifeGuide',
122
+ helperText:
123
+ 'این نام بالای یادآوری میآید؛ نام رسمی برنامه لایفگاید میماند.')),
124
+ Align(
125
+ alignment: Alignment.centerRight,
126
+ child: FilledButton(
127
+ onPressed: _busy ? null : () => _run(_saveNickname),
128
+ child: const Text('ذخیرهٔ نام همراه'))),
129
+ const Divider(height: 32),
130
+ SwitchListTile(
131
+ contentPadding: EdgeInsets.zero,
132
+ title: const Text('یادآوری روی همین دستگاه'),
133
+ subtitle: const Text(
134
+ 'فعالسازی با اجازهٔ شما؛ عنوان و یادداشت خصوصی در اعلان نمایش داده نمیشود.'),
135
+ value: enabled,
136
+ onChanged: _busy || !supported
137
+ ? null
138
+ : (value) => _run(() async {
139
+ _status = value
140
+ ? await _coordinator.enable(
141
+ companionName: _nickname.text.trim().isEmpty
142
+ ? 'LifeGuide'
143
+ : _nickname.text.trim())
144
+ : await _coordinator.disable();
145
+ })),
146
+ if (status != null && !supported)
147
+ const Text('اعلان پسزمینه در این دستگاه پشتیبانی نمیشود.'),
148
+ if (supported && !status!.permissionGranted)
149
+ const Text(
150
+ 'مجوز اعلان یا کانال یادآوری در تنظیمات دستگاه بسته است.'),
151
+ if (supported)
152
+ Text(enabled
153
+ ? '${status!.scheduledCount} یادآوری برای این دستگاه آماده است.'
154
+ : 'یادآوری این حساب روی این دستگاه خاموش است.'),
155
+ if (enabled && status?.validUntil != null)
156
+ Padding(
157
+ padding: const EdgeInsets.only(top: 12),
158
+ child: Text(
159
+ 'مهلت یادآوری: ${_localTime(status!.validUntil!)}\nتمدید فقط با اتصال و دریافت تازه از سرور؛ دادهٔ آفلاین مهلت را تمدید نمیکند.')),
160
+ if (supported)
161
+ Padding(
162
+ padding: const EdgeInsets.only(top: 12),
163
+ child: Text(status!.timing == 'exact'
164
+ ? 'مجوز زمانبندی دقیق برقرار است. تنظیمات باتری، بیصدا و مزاحم نشوید همچنان اثر دارند.'
165
+ : 'زمانبندی تقریبی است و ممکن است اعلان دیر برسد.')),
166
+ if (supported &&
167
+ status!.exactAlarmSupported &&
168
+ !status.canScheduleExactAlarms)
169
+ OutlinedButton(
170
+ onPressed: _busy
171
+ ? null
172
+ : () => _run(() async {
173
+ _status =
174
+ await _coordinator.requestExactAlarmAccess();
175
+ }),
176
+ child: const Text('اجازهٔ زمانبندی دقیق')),
177
+ if (supported)
178
+ OutlinedButton.icon(
179
+ onPressed: _busy ? null : () => _run(_refresh),
180
+ icon: const Icon(Icons.refresh),
181
+ label: const Text('دریافت تازه و آمادهسازی یادآوری')),
182
+ const SizedBox(height: 16),
183
+ const Text(
184
+ 'بستن اجباری برنامه (Force stop)، خاموشی گوشی یا محدودیت باتری میتواند اعلان را متوقف کند. صدا و نمایش روی قفل در کنترل تنظیمات گوشی است. لمس اعلان، خانهٔ برنامه را باز میکند؛ برای تیک انجام، برنامه را باز کنید.'),
185
+ if (_busy)
186
+ const Padding(
187
+ padding: EdgeInsets.all(16),
188
+ child: Center(child: CircularProgressIndicator())),
189
+ if (_error != null)
190
+ Padding(
191
+ padding: const EdgeInsets.only(top: 16),
192
+ child: Text(_error!,
193
+ style: TextStyle(
194
+ color: Theme.of(context).colorScheme.error))),
195
+ ]),
196
+ ));
197
+ }
198
+}
apps/lifemate/lib/local_reminders.dart
+12
-5
@@ -60,7 +60,7 @@ final class AndroidLocalReminderPort implements LocalReminderPort {
60
_now = now ?? DateTime.now;
61
final MethodChannel _channel;
62
final DateTime Function() _now;
63
- Future<void> _tail = Future.value();
63
+ Future<void>? _tail;
64
int _generation = 0;
65
String? _scope;
66
DateTime? _validUntil;
@@ -75,10 +75,17 @@ final class AndroidLocalReminderPort implements LocalReminderPort {
75
permissionGranted: false,
76
active: false,
77
scheduledCount: 0);
78
- Future<void> _serial(Future<void> Function() work) {
79
- final result = _tail.then((_) => work());
80
- _tail = result.then((_) {}, onError: (Object _, StackTrace __) {});
81
- return result;
78
+ Future<void> _serial(Future<void> Function() work) async {
79
+ final previous = _tail;
80
+ final release = Completer<void>();
81
+ _tail = release.future;
82
+ if (previous != null) await previous;
83
+ try {
84
+ await work();
85
+ } finally {
86
+ if (identical(_tail, release.future)) _tail = null;
87
+ release.complete();
88
+ }
89
}
90
91
Future<void> _write(String method, [Map<String, Object>? arguments]) async {
apps/lifemate/lib/plan_sync.dart
+15
-2
@@ -2,6 +2,7 @@ import 'dart:async';
2
import 'dart:math';
3
import 'api.dart';
4
import 'offline_store.dart';
5
+import 'local_reminders.dart';
6
7
String newMutationId() {
8
final random = Random.secure();
@@ -19,10 +20,14 @@ class MutationOutcome {
20
}
21
22
class PlanSync {
22
- PlanSync(this.api, {OfflineStore? store})
23
- : store = store ?? OfflineStore.forApi(api);
23
+ PlanSync(this.api, {OfflineStore? store, LocalReminderPort? reminders})
24
+ : store = store ?? OfflineStore.forApi(api),
25
+ reminders = reminders ?? androidLocalReminders;
26
final IdentityApi api;
27
final OfflineStore store;
28
+ final LocalReminderPort reminders;
29
+ Future<T> withLocalMutationLock<T>(Future<T> Function() work) =>
30
+ _serial(work);
31
static final _tails = <String, Future<void>>{};
32
Future<T> _serial<T>(Future<T> Function() operation) {
33
final previous = _tails[store.scope];
@@ -79,6 +84,14 @@ class PlanSync {
84
};
85
final optimistic = optimisticPlanItem(item, mutation);
86
await store.enqueue(mutation, optimisticItem: optimistic);
87
+ try {
88
+ await reminders
89
+ .suppressPlanItems(store.scope, {item['id'] as String});
90
+ } catch (_) {
91
+ // Do not leave a stale alarm after a durable offline edit. If targeted
92
+ // cancellation fails, remove this device's full reminder opt-in.
93
+ await reminders.deactivate();
94
+ }
95
try {
96
await _flushQueue();
97
final pending =
apps/lifemate/test/device_reminder_coordinator_test.dart
new
+272
@@ -0,0 +1,272 @@
1
+import 'dart:async';
2
+import 'dart:convert';
3
+import 'package:flutter/services.dart';
4
+import 'package:flutter_test/flutter_test.dart';
5
+import 'package:http/http.dart' as http;
6
+import 'package:http/testing.dart';
7
+import 'package:lifemate/api.dart';
8
+import 'package:lifemate/device_reminder_coordinator.dart';
9
+import 'package:lifemate/local_reminders.dart';
10
+import 'package:lifemate/offline_store.dart';
11
+import 'package:lifemate/plan_sync.dart';
12
+import 'package:lifemate/device_reminder_preferences.dart';
13
+import 'package:lifemate/session_store.dart';
14
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
15
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
16
+
17
+class MemoryReminderSession implements SessionStore {
18
+ @override
19
+ Future<String?> read() async => null;
20
+ @override
21
+ Future<void> write(String value) async {}
22
+ @override
23
+ Future<void> clear() async {}
24
+}
25
+
26
+class RecordingReminders implements LocalReminderPort {
27
+ String? scope;
28
+ DateTime? until;
29
+ bool granted = true;
30
+ final calls = <String>[];
31
+ List<LocalReminder> rows = [];
32
+ Completer<void>? replaceEntered, replaceRelease;
33
+ @override
34
+ Future<LocalReminderStatus> status() async => LocalReminderStatus(
35
+ supported: true,
36
+ permissionGranted: granted,
37
+ active: scope != null,
38
+ activeScope: scope,
39
+ validUntil: until,
40
+ scheduledCount: rows.length);
41
+ @override
42
+ Future<LocalReminderStatus> requestPermission() async {
43
+ calls.add('permission');
44
+ return status();
45
+ }
46
+
47
+ @override
48
+ Future<LocalReminderStatus> requestExactAlarmAccess() async {
49
+ calls.add('exact');
50
+ return status();
51
+ }
52
+
53
+ @override
54
+ Future<void> activate(String value, {required DateTime validUntil}) async {
55
+ calls.add('activate');
56
+ scope = value;
57
+ until = validUntil;
58
+ }
59
+
60
+ @override
61
+ Future<void> replace(String scope, List<LocalReminder> reminders,
62
+ {required String currentUserId}) async {
63
+ calls.add('replace');
64
+ replaceEntered?.complete();
65
+ await replaceRelease?.future;
66
+ rows = reminders;
67
+ }
68
+
69
+ @override
70
+ Future<void> suppressPlanItems(String scope, Set<String> ids) async {
71
+ calls.add('suppress');
72
+ rows = rows.where((r) => !ids.contains(r.planItemId)).toList();
73
+ }
74
+
75
+ @override
76
+ Future<void> deactivate() async {
77
+ calls.add('deactivate');
78
+ scope = null;
79
+ until = null;
80
+ rows = [];
81
+ }
82
+}
83
+
84
+class _OfflineMutationApi implements IdentityApi {
85
+ @override
86
+ Future<Map<String, dynamic>> submitSyncMutations(
87
+ List<Map<String, dynamic>> mutations) async =>
88
+ throw const ApiException(0, 'network_unavailable');
89
+ @override
90
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
91
+}
92
+
93
+void main() {
94
+ TestWidgetsFlutterBinding.ensureInitialized();
95
+ const owner = '11111111-1111-4111-8111-111111111111',
96
+ item = '22222222-2222-4222-8222-222222222222',
97
+ reminder = '33333333-3333-4333-8333-333333333333';
98
+ final now = DateTime.utc(2026, 10, 18, 8);
99
+ late RecordingReminders port;
100
+ late HttpIdentityApi api;
101
+ late OfflineStore store;
102
+ late DeviceReminderCoordinator coordinator;
103
+ var requests = 0;
104
+ Object? networkFailure;
105
+ Completer<void>? responseGate;
106
+ late Map<String, dynamic> response;
107
+ setUp(() {
108
+ SharedPreferencesAsyncPlatform.instance =
109
+ InMemorySharedPreferencesAsync.withData({});
110
+ String? pending;
111
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
112
+ .setMockMethodCallHandler(
113
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
114
+ if (call.method == 'getBlocked') return pending != null;
115
+ if (call.method == 'beginWrite') return pending = 'synthetic-write';
116
+ if (call.method == 'completeWrite' && call.arguments == pending) {
117
+ pending = null;
118
+ return true;
119
+ }
120
+ throw PlatformException(code: 'local_storage_restart_required');
121
+ });
122
+ port = RecordingReminders();
123
+ requests = 0;
124
+ networkFailure = null;
125
+ responseGate = null;
126
+ response = {
127
+ 'asOf': now.toIso8601String(),
128
+ 'reminders': [
129
+ {
130
+ 'id': reminder,
131
+ 'plan_item_id': item,
132
+ 'scheduled_for': now.add(const Duration(hours: 1)).toIso8601String(),
133
+ 'owner_user_id': owner
134
+ }
135
+ ]
136
+ };
137
+ api = HttpIdentityApi(
138
+ baseUrl: 'https://fixture.invalid/api',
139
+ sessionStore: MemoryReminderSession(),
140
+ client: MockClient((req) async {
141
+ requests++;
142
+ expect(req.url.path, '/api/v1/planner-reminders');
143
+ expect(req.headers['authorization'], 'Bearer synthetic-access');
144
+ expect(
145
+ DateTime.parse(req.url.queryParameters['to']!)
146
+ .difference(DateTime.parse(req.url.queryParameters['from']!)),
147
+ const Duration(hours: 24));
148
+ await responseGate?.future;
149
+ if (networkFailure != null) throw networkFailure!;
150
+ return http.Response(jsonEncode(response), 200,
151
+ headers: {'content-type': 'application/json; charset=utf-8'});
152
+ }))
153
+ ..accessToken = 'synthetic-access'
154
+ ..currentUserId = owner;
155
+ store = OfflineStore.forApi(api);
156
+ coordinator = DeviceReminderCoordinator(api,
157
+ port: port, store: store, now: () => now);
158
+ });
159
+ test('freshness reconciliation never opts a new account into alarms',
160
+ () async {
161
+ final status = await coordinator.reconcile();
162
+ expect(status.active, isFalse);
163
+ expect(requests, 0);
164
+ expect(port.calls, isEmpty);
165
+ });
166
+ test('explicit enable schedules only fresh owner API records', () async {
167
+ final result = await coordinator.enable(companionName: 'همراه من');
168
+ expect(requests, 1);
169
+ expect(port.calls, ['permission', 'activate', 'replace']);
170
+ expect(result.scheduledCount, 1);
171
+ expect(port.rows.single.companionName, 'همراه من');
172
+ expect(port.rows.single.serverAcknowledged, isTrue);
173
+ expect(result.validUntil, now.add(const Duration(hours: 24)));
174
+ });
175
+ test('default reconciliation reads only this scope companion nickname',
176
+ () async {
177
+ await DeviceReminderPreferences().write(api.cacheNamespace!, 'همراه من');
178
+ await coordinator.enable();
179
+ expect(port.rows.single.companionName, 'همراه من');
180
+ });
181
+
182
+ test('offline edit waits for native replacement then cancels its alarm',
183
+ () async {
184
+ port.replaceEntered = Completer<void>();
185
+ port.replaceRelease = Completer<void>();
186
+ final enabling = coordinator.enable();
187
+ await port.replaceEntered!.future;
188
+ final changing =
189
+ PlanSync(_OfflineMutationApi(), store: store, reminders: port)
190
+ .complete({
191
+ 'id': item,
192
+ 'title': 'برنامهٔ ساختگی',
193
+ 'status': 'planned',
194
+ 'version': 1,
195
+ });
196
+ await Future<void>.delayed(Duration.zero);
197
+ expect(await store.pendingCount(), 0);
198
+ port.replaceRelease!.complete();
199
+ await enabling;
200
+ await changing;
201
+ expect(port.calls, ['permission', 'activate', 'replace', 'suppress']);
202
+ expect(port.rows, isEmpty);
203
+ expect(await store.pendingCount(), 1);
204
+ });
205
+
206
+ test('pending offline edits cannot recreate the old native alarm', () async {
207
+ await store.enqueue({
208
+ 'id': '44444444-4444-4444-8444-444444444444',
209
+ 'entityType': 'plan_item',
210
+ 'entityId': item,
211
+ 'operation': 'complete',
212
+ 'expectedVersion': 1,
213
+ 'clientUpdatedAt': now.toIso8601String(),
214
+ 'payload': {'status': 'completed'}
215
+ });
216
+ await coordinator.enable();
217
+ expect(port.rows, isEmpty);
218
+ });
219
+ test('foreign owner and stale server timestamps never extend lease',
220
+ () async {
221
+ (response['reminders'] as List).single['owner_user_id'] =
222
+ '55555555-5555-4555-8555-555555555555';
223
+ await expectLater(coordinator.enable(), throwsA(isA<ApiException>()));
224
+ expect(port.calls, ['permission']);
225
+ response['reminders'] = [];
226
+ response['asOf'] =
227
+ now.subtract(const Duration(minutes: 10)).toIso8601String();
228
+ await expectLater(coordinator.enable(), throwsA(isA<ApiException>()));
229
+ expect(port.calls, ['permission', 'permission']);
230
+ });
231
+ test('offline refresh leaves the previous lease unchanged', () async {
232
+ await coordinator.enable();
233
+ final before = port.until;
234
+ port.calls.clear();
235
+ networkFailure = http.ClientException('synthetic offline');
236
+ await expectLater(coordinator.reconcile(), throwsA(isA<ApiException>()));
237
+ expect(port.until, before);
238
+ expect(port.calls, isEmpty);
239
+ });
240
+ test('logout while reminder read is pending cannot reactivate alarms',
241
+ () async {
242
+ await coordinator.enable();
243
+ port.calls.clear();
244
+ responseGate = Completer<void>();
245
+ final pending = coordinator.reconcile();
246
+ await Future<void>.delayed(Duration.zero);
247
+ api.accessToken = null;
248
+ api.currentUserId = null;
249
+ await port.deactivate();
250
+ responseGate!.complete();
251
+ await expectLater(pending, throwsA(isA<ApiException>()));
252
+ expect(port.calls, ['deactivate']);
253
+ });
254
+ test('disable from another coordinator defeats a delayed refresh', () async {
255
+ await coordinator.enable();
256
+ port.calls.clear();
257
+ responseGate = Completer<void>();
258
+ final pending = coordinator.reconcile();
259
+ await Future<void>.delayed(Duration.zero);
260
+ await DeviceReminderCoordinator(api,
261
+ port: port, now: () => now, store: store)
262
+ .disable();
263
+ responseGate!.complete();
264
+ await expectLater(
265
+ pending,
266
+ throwsA(isA<ApiException>().having(
267
+ (e) => e.code, 'code', 'device_notification_intent_changed')));
268
+ expect(port.calls, ['deactivate']);
269
+ expect(port.rows, isEmpty);
270
+ expect(port.scope, isNull);
271
+ });
272
+}
apps/lifemate/test/device_reminder_preferences_test.dart
new
+37
@@ -0,0 +1,37 @@
1
+import 'package:flutter_test/flutter_test.dart';
2
+import 'package:lifemate/device_reminder_preferences.dart';
3
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
4
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
5
+
6
+void main() {
7
+ TestWidgetsFlutterBinding.ensureInitialized();
8
+ setUp(() {
9
+ SharedPreferencesAsyncPlatform.instance =
10
+ InMemorySharedPreferencesAsync.withData({});
11
+ });
12
+ test('nickname persists in its user and API scope only', () async {
13
+ final store = DeviceReminderPreferences();
14
+ await store.write('https://one.invalid|synthetic-user-a', 'همراه من');
15
+ expect(
16
+ await DeviceReminderPreferences()
17
+ .read('https://one.invalid|synthetic-user-a'),
18
+ 'همراه من');
19
+ expect(
20
+ await store.read('https://one.invalid|synthetic-user-b'), 'LifeGuide');
21
+ expect(
22
+ await store.read('https://two.invalid|synthetic-user-a'), 'LifeGuide');
23
+ });
24
+ test(
25
+ 'nickname validation retains joined emoji and rejects controls or excess',
26
+ () async {
27
+ final store = DeviceReminderPreferences();
28
+ final joined = List.filled(40, '👩🔬').join();
29
+ await store.write('synthetic-scope', joined);
30
+ expect(await store.read('synthetic-scope'), joined);
31
+ for (final invalid in ['$joined!', 'bad\nname']) {
32
+ await expectLater(
33
+ store.write('synthetic-scope', invalid), throwsArgumentError);
34
+ }
35
+ expect(await store.read('synthetic-scope'), joined);
36
+ });
37
+}
apps/lifemate/test/device_reminder_settings_test.dart
new
+81
@@ -0,0 +1,81 @@
1
+import 'package:flutter/material.dart';
2
+import 'package:flutter_test/flutter_test.dart';
3
+import 'package:http/testing.dart';
4
+import 'package:lifemate/api.dart';
5
+import 'package:lifemate/device_reminder_coordinator.dart';
6
+import 'package:lifemate/device_reminder_preferences.dart';
7
+import 'package:lifemate/device_reminder_settings.dart';
8
+import 'package:lifemate/local_reminders.dart';
9
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
10
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
11
+
12
+class _Port implements LocalReminderPort {
13
+ _Port({this.supported = true});
14
+ final bool supported;
15
+ int exactRequests = 0;
16
+ @override
17
+ Future<LocalReminderStatus> status() async => LocalReminderStatus(
18
+ supported: supported,
19
+ permissionGranted: supported,
20
+ active: false,
21
+ scheduledCount: 0,
22
+ exactAlarmSupported: supported);
23
+ @override
24
+ Future<LocalReminderStatus> requestExactAlarmAccess() async {
25
+ exactRequests++;
26
+ return status();
27
+ }
28
+
29
+ @override
30
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
31
+}
32
+
33
+void main() {
34
+ TestWidgetsFlutterBinding.ensureInitialized();
35
+ setUp(() {
36
+ SharedPreferencesAsyncPlatform.instance =
37
+ InMemorySharedPreferencesAsync.withData({});
38
+ });
39
+ HttpIdentityApi api() => HttpIdentityApi(
40
+ baseUrl: 'https://fixture.invalid/api',
41
+ client: MockClient((_) async => throw StateError('Unexpected network')))
42
+ ..accessToken = 'synthetic-access'
43
+ ..currentUserId = '11111111-1111-4111-8111-111111111111';
44
+ testWidgets(
45
+ 'unsupported device shows honest background state and disabled opt-in',
46
+ (tester) async {
47
+ final client = api(), port = _Port(supported: false);
48
+ await tester.pumpWidget(MaterialApp(
49
+ home: DeviceReminderSettingsPage(
50
+ api: client,
51
+ coordinator: DeviceReminderCoordinator(client, port: port))));
52
+ await tester.pumpAndSettle();
53
+ expect(find.text('اعلان پسزمینه در این دستگاه پشتیبانی نمیشود.'),
54
+ findsOneWidget);
55
+ expect(tester.widget<Switch>(find.byType(Switch)).onChanged, isNull);
56
+ });
57
+ testWidgets(
58
+ 'nickname save remains scoped and exact permission is user initiated',
59
+ (tester) async {
60
+ final client = api(), port = _Port();
61
+ await tester.pumpWidget(MaterialApp(
62
+ home: DeviceReminderSettingsPage(
63
+ api: client,
64
+ coordinator: DeviceReminderCoordinator(client, port: port))));
65
+ await tester.pumpAndSettle();
66
+ expect(port.exactRequests, 0);
67
+ await tester.enterText(
68
+ find.byKey(const ValueKey('companion-nickname')), 'همراه من');
69
+ await tester.tap(find.text('ذخیرهٔ نام همراه'));
70
+ await tester.pumpAndSettle();
71
+ expect(await DeviceReminderPreferences().read(client.cacheNamespace!),
72
+ 'همراه من');
73
+ expect(
74
+ await DeviceReminderPreferences().read('https://other.invalid|other'),
75
+ 'LifeGuide');
76
+ await tester.ensureVisible(find.text('اجازهٔ زمانبندی دقیق'));
77
+ await tester.tap(find.text('اجازهٔ زمانبندی دقیق'));
78
+ await tester.pumpAndSettle();
79
+ expect(port.exactRequests, 1);
80
+ });
81
+}
apps/lifemate/test/flutter_test_config.dart
new
+27
@@ -0,0 +1,27 @@
1
+import 'dart:async';
2
+import 'package:flutter/services.dart';
3
+import 'package:flutter_test/flutter_test.dart';
4
+
5
+/// Widget tests have no Android alarm service. Keep its default inactive and
6
+/// deterministic; local_reminders_test overrides this boundary explicitly.
7
+Future<void> testExecutable(FutureOr<void> Function() testMain) async {
8
+ TestWidgetsFlutterBinding.ensureInitialized();
9
+ setUp(() {
10
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
11
+ .setMockMethodCallHandler(
12
+ const MethodChannel('lifeguide/local_reminders'), (call) async {
13
+ if (const {'status', 'requestPermission', 'requestExactAlarmAccess'}
14
+ .contains(call.method)) {
15
+ return <String, Object?>{
16
+ 'supported': true,
17
+ 'permissionGranted': false,
18
+ 'active': false,
19
+ 'scheduledCount': 0,
20
+ 'timing': 'approximate',
21
+ };
22
+ }
23
+ return true;
24
+ });
25
+ });
26
+ await testMain();
27
+}
apps/lifemate/test/reminder_lifecycle_test.dart
new
+137
@@ -0,0 +1,137 @@
1
+import 'dart:async';
2
+import 'package:flutter/services.dart';
3
+import 'package:flutter_test/flutter_test.dart';
4
+import 'package:http/testing.dart';
5
+import 'package:lifemate/api.dart';
6
+import 'package:lifemate/local_reminders.dart';
7
+import 'package:lifemate/offline_store.dart';
8
+import 'package:lifemate/plan_sync.dart';
9
+import 'package:lifemate/session_store.dart';
10
+import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
11
+import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
12
+
13
+class _Session implements SessionStore {
14
+ final List<String> events;
15
+ _Session(this.events);
16
+ @override
17
+ Future<String?> read() async => null;
18
+ @override
19
+ Future<void> write(String value) async {}
20
+ @override
21
+ Future<void> clear() async {
22
+ events.add('credential-clear');
23
+ }
24
+}
25
+
26
+class _Port implements LocalReminderPort {
27
+ final List<String> events;
28
+ final OfflineStore store;
29
+ _Port(this.events, this.store);
30
+ @override
31
+ Future<void> suppressPlanItems(String scope, Set<String> ids) async {
32
+ expect(scope, store.scope);
33
+ expect(ids, {'22222222-2222-4222-8222-222222222222'});
34
+ expect(await store.pendingCount(), 1);
35
+ events.add('suppress');
36
+ }
37
+
38
+ @override
39
+ Future<void> deactivate() async {
40
+ events.add('deactivate');
41
+ }
42
+
43
+ @override
44
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
45
+}
46
+
47
+class _OfflineApi implements IdentityApi {
48
+ final List<String> events;
49
+ _OfflineApi(this.events);
50
+ @override
51
+ Future<Map<String, dynamic>> submitSyncMutations(
52
+ List<Map<String, dynamic>> values) async {
53
+ events.add('send');
54
+ throw const ApiException(0, 'network_unavailable');
55
+ }
56
+
57
+ @override
58
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
59
+}
60
+
61
+void main() {
62
+ TestWidgetsFlutterBinding.ensureInitialized();
63
+ setUp(() {
64
+ SharedPreferencesAsyncPlatform.instance =
65
+ InMemorySharedPreferencesAsync.withData({});
66
+ String? pending;
67
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
68
+ .setMockMethodCallHandler(
69
+ const MethodChannel('lifeguide/local_write_guard'), (call) async {
70
+ if (call.method == 'getBlocked') return pending != null;
71
+ if (call.method == 'beginWrite') return pending = 'synthetic';
72
+ if (call.method == 'completeWrite' && call.arguments == pending) {
73
+ pending = null;
74
+ return true;
75
+ }
76
+ throw PlatformException(code: 'local_storage_restart_required');
77
+ });
78
+ });
79
+ test(
80
+ 'offline completion suppresses old alarm after durable enqueue before send',
81
+ () async {
82
+ final events = <String>[],
83
+ store = OfflineStore.forNamespace('synthetic-reminder-scope');
84
+ final result = await PlanSync(_OfflineApi(events),
85
+ store: store, reminders: _Port(events, store))
86
+ .complete({
87
+ 'id': '22222222-2222-4222-8222-222222222222',
88
+ 'title': 'برنامهٔ ساختگی',
89
+ 'status': 'planned',
90
+ 'version': 1
91
+ });
92
+ expect(result.queued, isTrue);
93
+ expect(events, ['suppress', 'send']);
94
+ });
95
+ test('logout starts alarm cancellation before clearing credentials',
96
+ () async {
97
+ final events = <String>[];
98
+ final gate = Completer<void>();
99
+ final api = HttpIdentityApi(
100
+ baseUrl: 'https://fixture.invalid/api',
101
+ client: MockClient((_) async => throw StateError('Unexpected network')),
102
+ sessionStore: _Session(events),
103
+ onSessionDeactivating: () async {
104
+ events.add('cancel-start');
105
+ await gate.future;
106
+ events.add('cancel-finish');
107
+ })
108
+ ..accessToken = 'synthetic-access'
109
+ ..currentUserId = '11111111-1111-4111-8111-111111111111';
110
+ final signingOut = api.logout(revoke: false);
111
+ await Future<void>.delayed(Duration.zero);
112
+ expect(events.first, 'cancel-start');
113
+ expect(api.accessToken, isNull);
114
+ gate.complete();
115
+ await signingOut;
116
+ expect(events.indexOf('cancel-finish'),
117
+ lessThan(events.indexOf('credential-clear')));
118
+ });
119
+ test(
120
+ 'alarm cancellation failure still clears credentials and reports failure',
121
+ () async {
122
+ final events = <String>[];
123
+ final api = HttpIdentityApi(
124
+ baseUrl: 'https://fixture.invalid/api',
125
+ client: MockClient((_) async => throw StateError('Unexpected network')),
126
+ sessionStore: _Session(events),
127
+ onSessionDeactivating: () async {
128
+ throw StateError('synthetic device failure');
129
+ })
130
+ ..accessToken = 'synthetic-access'
131
+ ..currentUserId = '11111111-1111-4111-8111-111111111111';
132
+ await expectLater(api.logout(revoke: false), throwsStateError);
133
+ expect(api.accessToken, isNull);
134
+ expect(api.currentUserId, isNull);
135
+ expect(events, ['credential-clear']);
136
+ });
137
+}