@davoodmehraban89 / LifeMate / commits / deb27ce
Fork 0

LifeMate — Personal, Family & Learning Companion

feat(android): isolate opt-in device planner reminders from online identity

Quinn White committed Oct 19, 2026 at 13:16 UTC deb27cea41e6fbab3551c5b0248592bfab2d935a
7 files changed +866 -14
apps/lifemate/android/app/build.gradle.kts
+27 -1
@@ -10,6 +10,27 @@ plugins {
10 }
11
12 val releaseRequested = gradle.startParameter.taskNames.any { it.contains("release", ignoreCase = true) }
13 +// A separate, debug-only device edition. The published online identity stays fixed.
14 +val devicePlannerOnly = providers.gradleProperty("lifeguideDevicePlanner").orNull == "true"
15 +val requestedTasks = gradle.startParameter.taskNames.map { it.substringAfterLast(':').lowercase() }
16 +val assembling = requestedTasks.any { it.startsWith("assemble") || it.startsWith("bundle") }
17 +val decodedDefines = providers.gradleProperty("dart-defines").orNull.orEmpty()
18 + .split(',').filter { it.isNotBlank() }.map { String(Base64.getDecoder().decode(it)) }
19 +val standaloneDefine = decodedDefines.contains("LIFEGUIDE_STANDALONE=true")
20 +if (devicePlannerOnly) {
21 + if (requestedTasks.any { it.contains("release") || it.contains("profile") || it == "assemble" || it == "bundle" }) {
22 + throw GradleException("The independent device planner is a debug-only initial edition.")
23 + }
24 + if (assembling && !standaloneDefine) {
25 + throw GradleException("Device planner builds require the matching LIFEGUIDE_STANDALONE define.")
26 + }
27 + val target = providers.gradleProperty("target").orNull.orEmpty().replace('\\', '/')
28 + if (assembling && !(target.endsWith("lib/standalone_main.dart") || target.endsWith("tool/standalone_acceptance_fixture.dart"))) {
29 + throw GradleException("The device edition requires its isolated Dart entry point.")
30 + }
31 +} else if (assembling && standaloneDefine) {
32 + throw GradleException("Standalone Dart cannot be packaged as the online application.")
33 +}
34 val releaseEnvironment = listOf("LIFEGUIDE_KEYSTORE_PATH", "LIFEGUIDE_KEYSTORE_PASSWORD", "LIFEGUIDE_KEY_ALIAS", "LIFEGUIDE_KEY_PASSWORD")
35 val signingValues = releaseEnvironment.associateWith { System.getenv(it) }
36 if (releaseRequested) {
@@ -42,6 +63,10 @@ android {
63 namespace = "ir.lifeguide.app"
64 compileSdk = flutter.compileSdkVersion
65 ndkVersion = flutter.ndkVersion
66 + buildFeatures { buildConfig = true }
67 + if (devicePlannerOnly) {
68 + sourceSets.getByName("debug").manifest.srcFile("src/devicePlanner/AndroidManifest.xml")
69 + }
70
71 compileOptions {
72 sourceCompatibility = JavaVersion.VERSION_17
@@ -50,7 +75,8 @@ android {
75
76 defaultConfig {
77 // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
53 - applicationId = "ir.lifeguide.app"
78 + applicationId = if (devicePlannerOnly) "ir.lifeguide.app.device" else "ir.lifeguide.app"
79 + buildConfigField("boolean", "DEVICE_PLANNER_ONLY", devicePlannerOnly.toString())
80 // You can update the following values to match your application needs.
81 // For more information, see: https://flutter.dev/to/review-gradle-config.
82 minSdk = flutter.minSdkVersion
apps/lifemate/android/app/src/devicePlanner/AndroidManifest.xml new
+6
@@ -0,0 +1,6 @@
1 +<manifest xmlns:android="http://schemas.android.com/apk/res/android"
2 + xmlns:tools="http://schemas.android.com/tools">
3 + <!-- Highest-priority debug overlay: even dependency manifests cannot grant network access. -->
4 + <uses-permission android:name="android.permission.INTERNET" tools:node="remove"/>
5 + <application android:label="لایف‌گاید شخصی" tools:replace="android:label"/>
6 +</manifest>
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/DevicePlannerReminders.kt new
+144
@@ -0,0 +1,144 @@
1 +package ir.lifeguide.app
2 +
3 +import android.Manifest
4 +import android.app.Activity
5 +import android.content.Context
6 +import android.content.Intent
7 +import android.content.pm.PackageManager
8 +import android.net.Uri
9 +import android.os.Build
10 +import android.provider.Settings
11 +import io.flutter.plugin.common.MethodCall
12 +import io.flutter.plugin.common.MethodChannel
13 +import java.util.Locale
14 +
15 +/** Native authority for reminders belonging only to the separate device-planner APK. */
16 +internal object DevicePlannerReminders {
17 + const val LEASE_KIND = "device-planner-v1"
18 + const val MAX_LEASE = 31L * 24 * 60 * 60 * 1000
19 + private val scope = Regex("^device-planner:v1:[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}$")
20 + private val controls = Regex("[\\p{Cc}\\u202a-\\u202e\\u2066-\\u2069]")
21 + private const val PREFS = "lifeguide_device_planner_reminders_v1"
22 + private const val ENABLED = "enabled"
23 + @Volatile private var choiceFailedClosed = false
24 +
25 + fun supported(c: Context) = BuildConfig.DEVICE_PLANNER_ONLY && c.packageName == "ir.lifeguide.app.device"
26 + fun enabled(c: Context): Boolean {
27 + if (!supported(c) || choiceFailedClosed) return false
28 + return try { c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(ENABLED, false) }
29 + catch (_: Exception) { choiceFailedClosed = true; false }
30 + }
31 + @Synchronized fun setEnabled(c: Context, value: Boolean) {
32 + require(supported(c))
33 + val stored = try { c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(ENABLED, value).commit() }
34 + catch (_: Exception) { false }
35 + choiceFailedClosed = !stored
36 + // Cancellation still runs when persisting OFF fails. Deactivate preserves the choice.
37 + if (!value) LocalReminders.deactivate(c)
38 + if (!stored) throw IllegalStateException("Device reminder choice storage unavailable")
39 + }
40 + fun status(c: Context): Map<String, Any?> = LocalReminders.status(c) + ("enabled" to enabled(c))
41 + fun validScope(value: String) = scope.matches(value)
42 + fun unsupportedStatus(): Map<String, Any?> = mapOf(
43 + "supported" to false, "enabled" to false, "permissionGranted" to false, "active" to false,
44 + "scheduledCount" to 0, "timing" to "approximate", "activeScope" to null,
45 + "validUntilEpochMs" to null, "exactAlarmSupported" to false, "canScheduleExactAlarms" to false)
46 +
47 + fun validateArguments(args: Map<*, *>, keys: Set<String>) {
48 + require(args.keys.all { it in keys })
49 + require(validScope(args["scope"] as? String ?: throw IllegalArgumentException()))
50 + }
51 +
52 + fun validateNames(args: Map<*, *>) {
53 + val rows = args["reminders"] as? List<*> ?: throw IllegalArgumentException()
54 + require(rows.size <= 128)
55 + for (raw in rows) {
56 + val row = raw as? Map<*, *> ?: throw IllegalArgumentException()
57 + val name = (row["companionName"] as? String)?.trim() ?: throw IllegalArgumentException()
58 + require(name.isNotEmpty() && name.length <= 4096 && !controls.containsMatchIn(name))
59 + // Android's ICU handles combining marks and emoji clusters at the native boundary.
60 + val boundaries = if (Build.VERSION.SDK_INT >= 24) {
61 + android.icu.text.BreakIterator.getCharacterInstance(Locale.ROOT).apply { setText(name) }
62 + } else null
63 + var count = 0
64 + if (boundaries != null) {
65 + boundaries.first()
66 + while (boundaries.next() != android.icu.text.BreakIterator.DONE) {
67 + require(++count <= 40)
68 + }
69 + } else {
70 + val legacy = java.text.BreakIterator.getCharacterInstance(Locale.ROOT).apply { setText(name) }
71 + legacy.first()
72 + while (legacy.next() != java.text.BreakIterator.DONE) {
73 + require(++count <= 40)
74 + }
75 + }
76 + }
77 + }
78 +}
79 +
80 +internal class DevicePlannerReminderChannel(private val activity: Activity) : MethodChannel.MethodCallHandler {
81 + companion object { const val REQUEST = 8248 }
82 + private var permissionResult: MethodChannel.Result? = null
83 +
84 + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
85 + if (!DevicePlannerReminders.supported(activity)) {
86 + result.success(DevicePlannerReminders.unsupportedStatus())
87 + return
88 + }
89 + try {
90 + when (call.method) {
91 + "setEnabled" -> {
92 + val args = call.arguments as? Map<*, *> ?: throw IllegalArgumentException()
93 + require(args.keys == setOf("enabled"))
94 + DevicePlannerReminders.setEnabled(activity, args["enabled"] as? Boolean ?: throw IllegalArgumentException())
95 + result.success(true)
96 + }
97 + "activate" -> {
98 + val args = call.arguments as? Map<*, *> ?: throw IllegalArgumentException()
99 + DevicePlannerReminders.validateArguments(args, setOf("scope", "validUntilEpochMs"))
100 + LocalReminders.activateDevicePlanner(activity, args)
101 + result.success(true)
102 + }
103 + "replace" -> {
104 + val args = call.arguments as? Map<*, *> ?: throw IllegalArgumentException()
105 + DevicePlannerReminders.validateArguments(args, setOf("scope", "reminders"))
106 + DevicePlannerReminders.validateNames(args)
107 + LocalReminders.replace(activity, args)
108 + result.success(true)
109 + }
110 + "suppressPlanItems" -> {
111 + val args = call.arguments as? Map<*, *> ?: throw IllegalArgumentException()
112 + DevicePlannerReminders.validateArguments(args, setOf("scope", "planItemIds"))
113 + LocalReminders.suppress(activity, args)
114 + result.success(true)
115 + }
116 + "deactivate" -> { LocalReminders.deactivate(activity); result.success(true) }
117 + "status" -> result.success(DevicePlannerReminders.status(activity))
118 + "requestPermission" -> {
119 + if (Build.VERSION.SDK_INT >= 33 && activity.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
120 + if (permissionResult != null) { result.error("permission_request_pending", null, null); return }
121 + permissionResult = result
122 + activity.requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST)
123 + } else result.success(DevicePlannerReminders.status(activity))
124 + }
125 + "requestExactAlarmAccess" -> {
126 + if (Build.VERSION.SDK_INT >= 31 && !LocalReminders.exact(activity)) {
127 + activity.startActivity(Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM, Uri.parse("package:${activity.packageName}")))
128 + }
129 + result.success(DevicePlannerReminders.status(activity))
130 + }
131 + else -> result.notImplemented()
132 + }
133 + } catch (_: IllegalArgumentException) { result.error("invalid_device_planner_reminder", null, null) }
134 + catch (_: Exception) { result.error("device_planner_reminder_unavailable", null, null) }
135 + }
136 +
137 + fun onPermissionResult(requestCode: Int) {
138 + if (requestCode != REQUEST) return
139 + val result = permissionResult ?: return
140 + permissionResult = null
141 + try { result.success(DevicePlannerReminders.status(activity)) }
142 + catch (_: Exception) { result.error("device_planner_reminder_unavailable", null, null) }
143 + }
144 +}
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/LocalReminders.kt
+30 -10
@@ -45,10 +45,16 @@ internal object LocalReminders {
45 }
46 failedClosed = false
47 }
48 - private fun leased(s: JSONObject, now: Long = System.currentTimeMillis()) =
49 - s.optString("scope").isNotEmpty() && s.optString("generation").isNotEmpty() &&
48 + private fun leased(c: Context, s: JSONObject, now: Long = System.currentTimeMillis()): Boolean {
49 + val maxLease = when (s.optString("leaseKind")) {
50 + "" -> MAX_LEASE
51 + DevicePlannerReminders.LEASE_KIND -> if (DevicePlannerReminders.enabled(c) && DevicePlannerReminders.validScope(s.optString("scope"))) DevicePlannerReminders.MAX_LEASE else 0L
52 + else -> 0L
53 + }
54 + return s.optString("scope").isNotEmpty() && s.optString("generation").isNotEmpty() &&
55 s.optLong("issuedAtEpochMs") <= now && s.optLong("validUntilEpochMs") > now &&
51 - s.optLong("validUntilEpochMs") - s.optLong("issuedAtEpochMs") in 1..MAX_LEASE
56 + s.optLong("validUntilEpochMs") - s.optLong("issuedAtEpochMs") in 1..maxLease
57 + }
58 fun permission(c: Context) =
59 (Build.VERSION.SDK_INT < 33 || c.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED) &&
60 notifications(c).areNotificationsEnabled() &&
@@ -95,21 +101,31 @@ internal object LocalReminders {
101 store(c, JSONObject(s.toString()).put("generation", UUID.randomUUID().toString()).put("deliveryExpired", true).put("reminders", JSONArray()))
102 }
103 @Synchronized fun activate(c: Context, args: Map<*, *>) {
104 + activate(c, args, false)
105 + }
106 + @Synchronized fun activateDevicePlanner(c: Context, args: Map<*, *>) {
107 + require(DevicePlannerReminders.enabled(c))
108 + activate(c, args, true)
109 + }
110 + private fun activate(c: Context, args: Map<*, *>, devicePlanner: Boolean) {
111 val scope = args["scope"] as? String ?: throw IllegalArgumentException()
112 val until = (args["validUntilEpochMs"] as? Number)?.toLong() ?: throw IllegalArgumentException()
113 val now = System.currentTimeMillis()
114 require(scope.isNotEmpty() && scope.length <= 1024 && !controls.containsMatchIn(scope))
102 - require(until > now && until - now <= MAX_LEASE)
115 + require(!devicePlanner || DevicePlannerReminders.validScope(scope))
116 + require(until > now && until - now <= if (devicePlanner) DevicePlannerReminders.MAX_LEASE else MAX_LEASE)
117 val old = read(c)
104 - val rows = if (old != null && old.optString("scope") == scope && leased(old, now)) old.optJSONArray("reminders") ?: JSONArray() else JSONArray()
118 + val kind = if (devicePlanner) DevicePlannerReminders.LEASE_KIND else ""
119 + val rows = if (old != null && old.optString("scope") == scope && old.optString("leaseKind") == kind && leased(c, old, now)) old.optJSONArray("reminders") ?: JSONArray() else JSONArray()
120 val next = JSONObject().put("scope", scope).put("generation", UUID.randomUUID().toString()).put("issuedAtEpochMs", now)
121 .put("validUntilEpochMs", until).put("reminders", rows)
122 + if (devicePlanner) next.put("leaseKind", kind)
123 cancel(c, old)
124 try { store(c, next); schedule(c, next) } catch (error: Exception) { deactivate(c); throw error }
125 }
126 @Synchronized fun replace(c: Context, args: Map<*, *>) {
127 val old = read(c) ?: throw IllegalStateException("No reminder scope")
112 - require(old.optString("scope") == args["scope"] && leased(old))
128 + require(old.optString("scope") == args["scope"] && leased(c, old))
129 val raw = args["reminders"] as? List<*> ?: throw IllegalArgumentException()
130 require(raw.size <= 128)
131 val ids = mutableSetOf<String>()
@@ -156,7 +172,7 @@ internal object LocalReminders {
172 alarms(c).setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, alarm)
173 }
174 private fun schedule(c: Context, s: JSONObject) {
159 - if (!leased(s) || !permission(c)) return
175 + if (!leased(c, s) || !permission(c)) return
176 channel(c)
177 val rows = s.optJSONArray("reminders") ?: JSONArray()
178 val now = System.currentTimeMillis()
@@ -170,12 +186,12 @@ internal object LocalReminders {
186 }
187 @Synchronized fun restore(c: Context) {
188 val state = read(c) ?: return
173 - if (!leased(state) || !permission(c)) { expire(c, state); return }
189 + if (!leased(c, state) || !permission(c)) { expire(c, state); return }
190 schedule(c, state)
191 }
192 @Synchronized fun status(c: Context): Map<String, Any?> {
193 var state = read(c)
178 - if (state != null && (!leased(state) || !permission(c))) { expire(c, state); state = read(c) }
194 + if (state != null && (!leased(c, state) || !permission(c))) { expire(c, state); state = read(c) }
195 val rows = state?.optJSONArray("reminders") ?: JSONArray()
196 val now = System.currentTimeMillis()
197 var count = 0
@@ -190,7 +206,7 @@ internal object LocalReminders {
206 if (parts.size != 2) return
207 val state = read(c) ?: return
208 if (parts[0] != state.optString("generation")) return
193 - if (!leased(state) || !permission(c) || parts[1] == "expiry") { expire(c, state); return }
209 + if (!leased(c, state) || !permission(c) || parts[1] == "expiry") { expire(c, state); return }
210 val rows = state.optJSONArray("reminders") ?: return
211 val now = System.currentTimeMillis()
212 for (i in 0 until rows.length()) {
@@ -225,6 +241,10 @@ internal object LocalReminders {
241 class LocalReminderReceiver : BroadcastReceiver() {
242 override fun onReceive(context: Context, intent: Intent) {
243 try {
244 + if (BuildConfig.DEVICE_PLANNER_ONLY && !DevicePlannerReminders.enabled(context)) {
245 + LocalReminders.deactivate(context)
246 + return
247 + }
248 when (intent.action) {
249 Intent.ACTION_BOOT_COMPLETED, Intent.ACTION_MY_PACKAGE_REPLACED, Intent.ACTION_TIME_CHANGED,
250 Intent.ACTION_TIMEZONE_CHANGED, AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED -> LocalReminders.restore(context)
apps/lifemate/android/app/src/main/kotlin/ir/lifeguide/app/MainActivity.kt
+10 -3
@@ -6,16 +6,23 @@ import io.flutter.plugin.common.MethodChannel
6
7 class MainActivity : FlutterActivity() {
8 private var localReminderChannel: LocalReminderChannel? = null
9 + private var devicePlannerReminderChannel: DevicePlannerReminderChannel? = null
10 override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
11 super.onRequestPermissionsResult(requestCode, permissions, grantResults)
12 localReminderChannel?.onPermissionResult(requestCode)
13 + devicePlannerReminderChannel?.onPermissionResult(requestCode)
14 }
15
16 override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
17 super.configureFlutterEngine(flutterEngine)
16 - localReminderChannel = LocalReminderChannel(this)
17 - MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_reminders")
18 - .setMethodCallHandler(localReminderChannel)
18 + if (!BuildConfig.DEVICE_PLANNER_ONLY) {
19 + localReminderChannel = LocalReminderChannel(this)
20 + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_reminders")
21 + .setMethodCallHandler(localReminderChannel)
22 + }
23 + devicePlannerReminderChannel = DevicePlannerReminderChannel(this)
24 + MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/device_planner_reminders")
25 + .setMethodCallHandler(devicePlannerReminderChannel)
26 MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "lifeguide/local_write_guard")
27 .setMethodCallHandler { call, result ->
28 when (call.method) {
apps/lifemate/lib/standalone/reminders.dart new
+365
@@ -0,0 +1,365 @@
1 +import 'dart:async';
2 +
3 +import 'package:flutter/foundation.dart';
4 +import 'package:flutter/services.dart';
5 +import 'package:flutter/widgets.dart' show StringCharacters;
6 +import 'package:shared_preferences/shared_preferences.dart';
7 +
8 +/// A committed record from this device's personal planner, never a server ACK.
9 +final class LocalPersonalReminder {
10 + const LocalPersonalReminder(
11 + {required this.id,
12 + required this.planItemId,
13 + required this.profileId,
14 + required this.scheduledAt,
15 + this.completed = false,
16 + this.archived = false});
17 + final String id, planItemId, profileId;
18 + final DateTime scheduledAt;
19 + final bool completed, archived;
20 +}
21 +
22 +final class StandaloneReminderStatus {
23 + const StandaloneReminderStatus(
24 + {required this.supported,
25 + required this.permissionGranted,
26 + required this.active,
27 + required this.scheduledCount,
28 + this.enabled = false,
29 + this.timing = 'approximate',
30 + this.activeScope,
31 + this.validUntil,
32 + this.exactAlarmSupported = false,
33 + this.canScheduleExactAlarms = false,
34 + this.eligibleCount = 0,
35 + this.selectedCount = 0});
36 + final bool supported, permissionGranted, active, enabled;
37 + final bool exactAlarmSupported, canScheduleExactAlarms;
38 + final int scheduledCount, eligibleCount, selectedCount;
39 + final String timing;
40 + final String? activeScope;
41 + final DateTime? validUntil;
42 + static const coverageDays = 28;
43 + static const maximumReminders = 128;
44 +}
45 +
46 +/// Dedicated device edition port. Opening/reconciling never grants consent or
47 +/// requests permission. Only [enable] can turn the two persisted choices ON.
48 +final class StandaloneReminderPort {
49 + StandaloneReminderPort(
50 + {MethodChannel? channel,
51 + SharedPreferencesAsync? preferences,
52 + DateTime Function()? now})
53 + : _channel = channel ??
54 + const MethodChannel('lifeguide/device_planner_reminders'),
55 + _preferences = preferences ?? SharedPreferencesAsync(),
56 + _now = now ?? DateTime.now;
57 +
58 + final MethodChannel _channel;
59 + final SharedPreferencesAsync _preferences;
60 + final DateTime Function() _now;
61 + Future<void>? _tail;
62 + int _generation = 0;
63 + String? _profileId;
64 + int _eligibleCount = 0, _selectedCount = 0;
65 + static final _uuid = RegExp(
66 + 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}$');
67 + static final _controls =
68 + RegExp(r'[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]');
69 + static const _unsupported = StandaloneReminderStatus(
70 + supported: false,
71 + permissionGranted: false,
72 + active: false,
73 + scheduledCount: 0);
74 + bool get _native =>
75 + !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
76 + String _scope(String id) {
77 + if (!_uuid.hasMatch(id)) throw ArgumentError('Invalid local profile ID.');
78 + return 'device-planner:v1:$id';
79 + }
80 +
81 + String _key(String id) {
82 + _scope(id);
83 + return 'lifeguide.device_planner.reminders_enabled.v1.$id';
84 + }
85 +
86 + Future<T> _serial<T>(Future<T> Function() work) async {
87 + final previous = _tail;
88 + final release = Completer<void>();
89 + _tail = release.future;
90 + if (previous != null) await previous;
91 + try {
92 + return await work();
93 + } finally {
94 + if (identical(_tail, release.future)) _tail = null;
95 + release.complete();
96 + }
97 + }
98 +
99 + Future<void> _write(String method, [Map<String, Object>? args]) async {
100 + if (!_native) return;
101 + final result = await _channel
102 + .invokeMethod<dynamic>(method, args)
103 + .timeout(const Duration(seconds: 5));
104 + if (result is Map && result['supported'] == false) {
105 + throw UnsupportedError('Device planner reminders are unavailable.');
106 + }
107 + if (result != true) throw StateError('Device reminder operation failed.');
108 + }
109 +
110 + Future<void> _deactivate() async {
111 + try {
112 + await _write('deactivate');
113 + } on MissingPluginException {
114 + /* No native alarms exist in older builds. */
115 + } on UnsupportedError {/* The online edition cannot own these alarms. */}
116 + }
117 +
118 + Future<StandaloneReminderStatus> _nativeStatus(
119 + [String method = 'status']) async {
120 + if (!_native) return _unsupported;
121 + try {
122 + final raw = await _channel
123 + .invokeMapMethod<String, dynamic>(method)
124 + .timeout(Duration(seconds: method == 'requestPermission' ? 90 : 5));
125 + if (raw == null || raw['supported'] == false) return _unsupported;
126 + if (raw['supported'] != true ||
127 + raw['enabled'] is! bool ||
128 + raw['permissionGranted'] is! bool ||
129 + raw['active'] is! bool ||
130 + raw['scheduledCount'] is! int ||
131 + (raw['scheduledCount'] as int) < 0 ||
132 + (raw['scheduledCount'] as int) > 128 ||
133 + !['exact', 'approximate'].contains(raw['timing'])) {
134 + throw StateError('Invalid device reminder status.');
135 + }
136 + return StandaloneReminderStatus(
137 + supported: true,
138 + enabled: raw['enabled'] == true,
139 + permissionGranted: raw['permissionGranted'] == true,
140 + active: raw['active'] == true,
141 + scheduledCount: raw['scheduledCount'] as int,
142 + timing: raw['timing'] as String,
143 + activeScope: raw['activeScope'] is String
144 + ? raw['activeScope'] as String
145 + : null,
146 + validUntil: raw['validUntilEpochMs'] is int
147 + ? DateTime.fromMillisecondsSinceEpoch(
148 + raw['validUntilEpochMs'] as int,
149 + isUtc: true)
150 + : null,
151 + exactAlarmSupported: raw['exactAlarmSupported'] == true,
152 + canScheduleExactAlarms: raw['canScheduleExactAlarms'] == true);
153 + } on MissingPluginException {
154 + return _unsupported;
155 + }
156 + }
157 +
158 + StandaloneReminderStatus _view(StandaloneReminderStatus raw, bool enabled) =>
159 + StandaloneReminderStatus(
160 + supported: raw.supported,
161 + enabled: enabled && raw.enabled,
162 + permissionGranted: raw.permissionGranted,
163 + active: raw.active,
164 + scheduledCount: raw.scheduledCount,
165 + timing: raw.timing,
166 + activeScope: raw.activeScope,
167 + validUntil: raw.validUntil,
168 + exactAlarmSupported: raw.exactAlarmSupported,
169 + canScheduleExactAlarms: raw.canScheduleExactAlarms,
170 + eligibleCount: _eligibleCount,
171 + selectedCount: _selectedCount);
172 + Future<StandaloneReminderStatus> _readStatus(String? id,
173 + [String method = 'status']) async {
174 + final raw = await _nativeStatus(method);
175 + final enabled = id != null && await _preferences.getBool(_key(id)) == true;
176 + return _view(raw, enabled);
177 + }
178 +
179 + Future<StandaloneReminderStatus> status({String? profileId}) {
180 + if (profileId != null) {
181 + _scope(profileId);
182 + _profileId = profileId;
183 + }
184 + return _serial(() => _readStatus(profileId ?? _profileId));
185 + }
186 +
187 + Future<StandaloneReminderStatus> requestPermission() =>
188 + _serial(() => _readStatus(_profileId, 'requestPermission'));
189 + Future<StandaloneReminderStatus> requestExactAlarmAccess() =>
190 + _serial(() => _readStatus(_profileId, 'requestExactAlarmAccess'));
191 +
192 + List<Map<String, Object>> _select(
193 + List<LocalPersonalReminder> rows, String name, String profileId) {
194 + _scope(profileId);
195 + final trimmed = name.trim();
196 + if (trimmed.isEmpty ||
197 + name.length > 4096 ||
198 + name.characters.length > 40 ||
199 + _controls.hasMatch(name)) {
200 + throw ArgumentError('Invalid companion name.');
201 + }
202 + final now = _now().toUtc();
203 + final through = now.add(const Duration(days: 28));
204 + final ids = <String>{}, eligible = <LocalPersonalReminder>[];
205 + for (final row in rows) {
206 + if (!_uuid.hasMatch(row.id) ||
207 + !_uuid.hasMatch(row.planItemId) ||
208 + !ids.add(row.id) ||
209 + row.profileId != profileId ||
210 + !row.scheduledAt.isUtc) {
211 + throw ArgumentError(
212 + 'Only committed records of this local profile may schedule.');
213 + }
214 + if (!row.completed &&
215 + !row.archived &&
216 + row.scheduledAt.isAfter(now) &&
217 + !row.scheduledAt.isAfter(through)) {
218 + eligible.add(row);
219 + }
220 + }
221 + eligible.sort((a, b) {
222 + final time = a.scheduledAt.compareTo(b.scheduledAt);
223 + return time != 0 ? time : a.id.compareTo(b.id);
224 + });
225 + _eligibleCount = eligible.length;
226 + final selected = eligible.take(128).toList();
227 + _selectedCount = selected.length;
228 + return selected
229 + .map((row) => <String, Object>{
230 + 'id': row.id,
231 + 'planItemId': row.planItemId,
232 + 'scheduledAtEpochMs': row.scheduledAt.millisecondsSinceEpoch,
233 + 'companionName': trimmed
234 + })
235 + .toList();
236 + }
237 +
238 + Future<void> _schedule(List<Map<String, Object>> payload, String profileId,
239 + int generation) async {
240 + if (generation != _generation) return;
241 + await _deactivate();
242 + if (generation != _generation) return;
243 + await _write('activate', {
244 + 'scope': _scope(profileId),
245 + 'validUntilEpochMs':
246 + _now().toUtc().add(const Duration(days: 31)).millisecondsSinceEpoch
247 + });
248 + if (generation != _generation) return;
249 + await _write('replace', {'scope': _scope(profileId), 'reminders': payload});
250 + }
251 +
252 + Future<StandaloneReminderStatus> enable(List<LocalPersonalReminder> rows,
253 + {required String companionName, required String profileId}) {
254 + final payload = _select(rows, companionName, profileId);
255 + _profileId = profileId;
256 + final generation = ++_generation;
257 + return _serial(() async {
258 + if (generation != _generation) return _readStatus(profileId);
259 + final initial = await _nativeStatus('requestPermission');
260 + if (!initial.supported ||
261 + !initial.permissionGranted ||
262 + generation != _generation) {
263 + return _view(initial, false);
264 + }
265 + try {
266 + await _write('setEnabled', {'enabled': true});
267 + if (generation != _generation) return await _readStatus(profileId);
268 + await _preferences.setBool(_key(profileId), true);
269 + await _schedule(payload, profileId, generation);
270 + } catch (error, stack) {
271 + try {
272 + await _write('setEnabled', {'enabled': false});
273 + } catch (_) {
274 + await _deactivate();
275 + }
276 + try {
277 + await _preferences.setBool(_key(profileId), false);
278 + } catch (_) {/* Surface the original failure. */}
279 + Error.throwWithStackTrace(error, stack);
280 + }
281 + return _readStatus(profileId);
282 + });
283 + }
284 +
285 + /// Call only with a fresh, successful read of the committed local store.
286 + Future<StandaloneReminderStatus> reconcile(List<LocalPersonalReminder> rows,
287 + {required String companionName, required String profileId}) {
288 + _scope(profileId);
289 + _profileId = profileId;
290 + final generation = ++_generation;
291 + return _serial(() async {
292 + final raw = await _nativeStatus();
293 + final optedIn = await _preferences.getBool(_key(profileId)) == true;
294 + if (generation != _generation) return _view(raw, optedIn);
295 + if (!raw.supported) return _unsupported;
296 + if (!optedIn || !raw.enabled) {
297 + _eligibleCount = 0;
298 + _selectedCount = 0;
299 + if (!optedIn && raw.enabled) {
300 + await _write('setEnabled', {'enabled': false});
301 + } else {
302 + await _deactivate();
303 + }
304 + return _readStatus(profileId);
305 + }
306 + try {
307 + final payload = _select(rows, companionName, profileId);
308 + await _schedule(payload, profileId, generation);
309 + } catch (error, stack) {
310 + await _deactivate();
311 + Error.throwWithStackTrace(error, stack);
312 + }
313 + return _readStatus(profileId);
314 + });
315 + }
316 +
317 + /// Invalidate queued work before a store write. Consent survives suspension;
318 + /// only a fresh committed-store reconciliation can install alarms again.
319 + Future<void> suspendUntilReconcile({String? profileId}) {
320 + if (profileId != null) {
321 + _scope(profileId);
322 + _profileId = profileId;
323 + }
324 + ++_generation;
325 + _selectedCount = 0;
326 + return _serial(_deactivate);
327 + }
328 +
329 + Future<void> cancelOnStorageFailure({String? profileId}) =>
330 + suspendUntilReconcile(profileId: profileId);
331 +
332 + Future<void> disable({required String profileId}) {
333 + _scope(profileId);
334 + _profileId = profileId;
335 + ++_generation;
336 + _eligibleCount = 0;
337 + _selectedCount = 0;
338 + return _serial(() async {
339 + Object? failure;
340 + StackTrace? trace;
341 + try {
342 + await _write('setEnabled', {'enabled': false});
343 + } on MissingPluginException {
344 + /* Unsupported older build. */
345 + } on UnsupportedError {/* Online edition. */} catch (error, stack) {
346 + failure = error;
347 + trace = stack;
348 + }
349 + // Cancellation is attempted independently of either preference write.
350 + try {
351 + await _deactivate();
352 + } catch (error, stack) {
353 + failure ??= error;
354 + trace ??= stack;
355 + }
356 + try {
357 + await _preferences.setBool(_key(profileId), false);
358 + } catch (error, stack) {
359 + failure ??= error;
360 + trace ??= stack;
361 + }
362 + if (failure != null) Error.throwWithStackTrace(failure, trace!);
363 + });
364 + }
365 +}
apps/lifemate/test/standalone_reminders_test.dart new
+284
@@ -0,0 +1,284 @@
1 +import 'dart:async';
2 +import 'package:flutter/foundation.dart';
3 +import 'package:flutter/services.dart';
4 +import 'package:flutter_test/flutter_test.dart';
5 +import 'package:lifemate/standalone/reminders.dart';
6 +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
7 +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
8 +import 'package:shared_preferences_platform_interface/types.dart';
9 +
10 +final class FailingOffPreferences extends InMemorySharedPreferencesAsync {
11 + FailingOffPreferences() : super.empty();
12 + bool failOff = false;
13 + @override
14 + Future<bool> setBool(
15 + String key, bool value, SharedPreferencesOptions options) {
16 + if (!value && failOff) throw StateError('Preference disk unavailable');
17 + return super.setBool(key, value, options);
18 + }
19 +}
20 +
21 +void main() {
22 + TestWidgetsFlutterBinding.ensureInitialized();
23 + const channel = MethodChannel('lifeguide/device_planner_reminders');
24 + const profile = '11111111-1111-4111-8111-111111111111';
25 + const item = '22222222-2222-4222-8222-222222222222';
26 + final now = DateTime.utc(2026, 10, 19, 8);
27 + final calls = <MethodCall>[];
28 + late StandaloneReminderPort port;
29 + late FailingOffPreferences preferences;
30 + bool nativeEnabled = false, active = false, supported = true;
31 + int scheduled = 0;
32 + List<dynamic> payload = [];
33 + Future<void> Function(MethodCall)? intercept;
34 + LocalPersonalReminder row(
35 + {String id = item,
36 + String profileId = profile,
37 + DateTime? at,
38 + bool completed = false,
39 + bool archived = false}) =>
40 + LocalPersonalReminder(
41 + id: id,
42 + planItemId: id,
43 + profileId: profileId,
44 + scheduledAt: at ?? now.add(const Duration(hours: 1)),
45 + completed: completed,
46 + archived: archived);
47 + String idAt(int index) =>
48 + '${index.toRadixString(16).padLeft(8, '0')}-2222-4222-8222-222222222222';
49 +
50 + setUp(() {
51 + debugDefaultTargetPlatformOverride = TargetPlatform.android;
52 + preferences = FailingOffPreferences();
53 + SharedPreferencesAsyncPlatform.instance = preferences;
54 + port = StandaloneReminderPort(now: () => now);
55 + nativeEnabled = false;
56 + active = false;
57 + supported = true;
58 + scheduled = 0;
59 + payload = [];
60 + calls.clear();
61 + intercept = null;
62 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
63 + .setMockMethodCallHandler(channel, (call) async {
64 + calls.add(call);
65 + if (intercept != null) await intercept!(call);
66 + if (!supported) {
67 + return {
68 + 'supported': false,
69 + 'enabled': false,
70 + 'permissionGranted': false,
71 + 'active': false,
72 + 'scheduledCount': 0,
73 + 'timing': 'approximate'
74 + };
75 + }
76 + if (call.method == 'setEnabled') {
77 + nativeEnabled = (call.arguments as Map)['enabled'] == true;
78 + if (!nativeEnabled) {
79 + active = false;
80 + scheduled = 0;
81 + payload = [];
82 + }
83 + }
84 + if (call.method == 'activate') active = true;
85 + if (call.method == 'replace') {
86 + payload = (call.arguments as Map)['reminders'] as List;
87 + scheduled = payload.length;
88 + }
89 + if (call.method == 'deactivate') {
90 + active = false;
91 + scheduled = 0;
92 + payload = [];
93 + }
94 + if (['status', 'requestPermission', 'requestExactAlarmAccess']
95 + .contains(call.method)) {
96 + return {
97 + 'supported': true,
98 + 'enabled': nativeEnabled,
99 + 'permissionGranted': true,
100 + 'active': active,
101 + 'scheduledCount': scheduled,
102 + 'timing': 'approximate',
103 + 'activeScope': active ? 'device-planner:v1:$profile' : null,
104 + 'validUntilEpochMs': active
105 + ? now.add(const Duration(days: 31)).millisecondsSinceEpoch
106 + : null,
107 + 'exactAlarmSupported': true,
108 + 'canScheduleExactAlarms': false
109 + };
110 + }
111 + return true;
112 + });
113 + });
114 + tearDown(() {
115 + debugDefaultTargetPlatformOverride = null;
116 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
117 + .setMockMethodCallHandler(channel, null);
118 + });
119 +
120 + test('opening and reconciliation remain OFF without permission prompts',
121 + () async {
122 + expect((await port.status(profileId: profile)).enabled, isFalse);
123 + final result = await port
124 + .reconcile([row()], companionName: 'همراه من', profileId: profile);
125 + expect(result.enabled, isFalse);
126 + expect(result.active, isFalse);
127 + expect(calls.map((call) => call.method), isNot(contains('activate')));
128 + expect(
129 + calls.map((call) => call.method), isNot(contains('requestPermission')));
130 + });
131 + test(
132 + 'explicit enable selects next 28 days and soonest 128 with opaque payload',
133 + () async {
134 + final rows = List.generate(
135 + 130, (i) => row(id: idAt(i), at: now.add(Duration(minutes: 130 - i))));
136 + rows.addAll([
137 + row(id: idAt(131), at: now.subtract(const Duration(seconds: 1))),
138 + row(id: idAt(132), at: now.add(const Duration(days: 29))),
139 + row(id: idAt(133), completed: true),
140 + row(id: idAt(134), archived: true)
141 + ]);
142 + final result =
143 + await port.enable(rows, companionName: 'همراه من', profileId: profile);
144 + expect(result.enabled, isTrue);
145 + expect(result.active, isTrue);
146 + expect(result.eligibleCount, 130);
147 + expect(result.selectedCount, 128);
148 + expect(result.scheduledCount, 128);
149 + expect(calls.where((call) => call.method == 'requestPermission'),
150 + hasLength(1));
151 + final activation = calls.singleWhere((call) => call.method == 'activate');
152 + expect((activation.arguments as Map)['validUntilEpochMs'],
153 + now.add(const Duration(days: 31)).millisecondsSinceEpoch);
154 + expect((payload.first as Map)['id'], idAt(129));
155 + expect((payload.last as Map)['id'], idAt(2));
156 + expect(
157 + (payload.first as Map).keys,
158 + unorderedEquals(
159 + ['id', 'planItemId', 'scheduledAtEpochMs', 'companionName']));
160 + });
161 + test('completed and archived stay cancelled after restored choice', () async {
162 + await port.enable([row()], companionName: 'همراه من', profileId: profile);
163 + await port.suspendUntilReconcile(profileId: profile);
164 + expect(nativeEnabled, isTrue);
165 + expect(active, isFalse);
166 + calls.clear();
167 + final reopened = StandaloneReminderPort(now: () => now);
168 + final result = await reopened.reconcile(
169 + [row(completed: true), row(id: idAt(3), archived: true)],
170 + companionName: 'همراه من', profileId: profile);
171 + expect(result.enabled, isTrue);
172 + expect(result.scheduledCount, 0);
173 + expect(payload, isEmpty);
174 + expect(
175 + calls.map((call) => call.method), isNot(contains('requestPermission')));
176 + });
177 + test('suspension invalidates in-flight scheduling and fresh DB read restores',
178 + () async {
179 + await port.enable([row()], companionName: 'همراه من', profileId: profile);
180 + final entered = Completer<void>(), release = Completer<void>();
181 + intercept = (call) async {
182 + if (call.method == 'activate' && !entered.isCompleted) {
183 + entered.complete();
184 + await release.future;
185 + }
186 + };
187 + calls.clear();
188 + final updating =
189 + port.reconcile([row()], companionName: 'همراه من', profileId: profile);
190 + await entered.future;
191 + final suspending = port.suspendUntilReconcile(profileId: profile);
192 + release.complete();
193 + await Future.wait([updating, suspending]);
194 + expect(active, isFalse);
195 + expect(nativeEnabled, isTrue);
196 + expect(calls.map((call) => call.method), isNot(contains('replace')));
197 + intercept = null;
198 + await StandaloneReminderPort(now: () => now)
199 + .reconcile([row()], companionName: 'همراه من', profileId: profile);
200 + expect(active, isTrue);
201 + expect(scheduled, 1);
202 + });
203 + test('OFF invalidates an activation already in flight', () async {
204 + final entered = Completer<void>(), release = Completer<void>();
205 + intercept = (call) async {
206 + if (call.method == 'activate') {
207 + entered.complete();
208 + await release.future;
209 + }
210 + };
211 + final enabling =
212 + port.enable([row()], companionName: 'همراه من', profileId: profile);
213 + await entered.future;
214 + final disabling = port.disable(profileId: profile);
215 + release.complete();
216 + await Future.wait([enabling, disabling]);
217 + expect(nativeEnabled, isFalse);
218 + expect(active, isFalse);
219 + expect(calls.map((call) => call.method), isNot(contains('replace')));
220 + await StandaloneReminderPort(now: () => now)
221 + .reconcile([row()], companionName: 'همراه من', profileId: profile);
222 + expect(active, isFalse);
223 + });
224 + test('failed Dart OFF write cancels native; stale ON cannot resurrect',
225 + () async {
226 + await port.enable([row()], companionName: 'همراه من', profileId: profile);
227 + preferences.failOff = true;
228 + await expectLater(port.disable(profileId: profile), throwsStateError);
229 + expect(nativeEnabled, isFalse);
230 + expect(active, isFalse);
231 + final result = await StandaloneReminderPort(now: () => now)
232 + .reconcile([row()], companionName: 'همراه من', profileId: profile);
233 + expect(result.enabled, isFalse);
234 + expect(result.active, isFalse);
235 + expect(scheduled, 0);
236 + });
237 + test('invalid profiles, IDs, timestamps and names never schedule', () async {
238 + for (final invalid in [
239 + row(profileId: idAt(5)),
240 + row(id: 'not-a-uuid'),
241 + row(at: DateTime(2026, 10, 19, 9))
242 + ]) {
243 + expect(
244 + () => port
245 + .enable([invalid], companionName: 'همراه من', profileId: profile),
246 + throwsArgumentError);
247 + }
248 + expect(
249 + () => port
250 + .enable([row()], companionName: 'bad\nname', profileId: profile),
251 + throwsArgumentError);
252 + expect(
253 + () => port.enable([row()],
254 + companionName: List.filled(41, '👩‍🔬').join(), profileId: profile),
255 + throwsArgumentError);
256 + expect(calls, isEmpty);
257 + });
258 + test('unsupported native build and missing plugin are honest', () async {
259 + supported = false;
260 + final unavailable = await port
261 + .enable([row()], companionName: 'همراه من', profileId: profile);
262 + expect(unavailable.supported, isFalse);
263 + expect(unavailable.enabled, isFalse);
264 + await port.disable(profileId: profile);
265 + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
266 + .setMockMethodCallHandler(channel, null);
267 + expect(
268 + (await StandaloneReminderPort().status(profileId: profile)).supported,
269 + isFalse);
270 + });
271 + test('non-Android never reaches native or claims background support',
272 + () async {
273 + debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
274 + expect(
275 + (await port
276 + .enable([row()], companionName: 'همراه من', profileId: profile))
277 + .supported,
278 + isFalse);
279 + await port
280 + .reconcile([row()], companionName: 'همراه من', profileId: profile);
281 + await port.disable(profileId: profile);
282 + expect(calls, isEmpty);
283 + });
284 +}