LifeMate — Personal, Family & Learning Companion

feat/flutter-mobile-navigation
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
dart 428 lines 16 KB
Raw
1 import 'dart:async';
2 import 'dart:convert';
3
4 import 'package:flutter/services.dart';
5 import 'package:flutter_test/flutter_test.dart';
6 import 'package:http/http.dart' as http;
7 import 'package:http/testing.dart';
8 import 'package:lifemate/api.dart';
9 import 'package:lifemate/learning_sync.dart';
10 import 'package:lifemate/offline_store.dart';
11 import 'package:lifemate/session_store.dart';
12 import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart';
13 import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart';
14
15 const _unit = '00000000-0000-4000-8000-000000000101';
16 const _otherUnit = '00000000-0000-4000-8000-000000000102';
17 const _course = '00000000-0000-4000-8000-000000000200';
18 const _time = '2026-10-09T10:00:00Z';
19
20 class _Session implements SessionStore {
21 @override
22 Future<String?> read() async => null;
23 @override
24 Future<void> write(String value) async {}
25 @override
26 Future<void> clear() async {}
27 }
28
29 class _Fixture {
30 _Fixture({String endpoint = 'https://api.test', String? user}) {
31 api = HttpIdentityApi(
32 baseUrl: endpoint,
33 client: MockClient(handle),
34 sessionStore: _Session(),
35 )
36 ..accessToken = 'synthetic-test-token'
37 ..currentUserId = user ?? 'learner-${next++}';
38 store = OfflineStore.forNamespace(api.cacheNamespace!, session: session);
39 sync = LearningSync(api, store: store);
40 }
41 static var next = 0;
42 final session = OfflineSession();
43 late HttpIdentityApi api;
44 late OfflineStore store;
45 late LearningSync sync;
46 bool offline = false;
47 int? errorStatus;
48 bool appliedThenDisconnect = false;
49 Future<void>? delay;
50 final requests = <http.Request>[];
51 final applied = <String, Map<String, dynamic>>{};
52 final progress = <String, Map<String, dynamic>>{};
53 Map<String, dynamic> Function(Map<String, dynamic>)? alterAck;
54 Map<String, dynamic> Function(Map<String, dynamic>)? alterCourse;
55
56 Map<String, dynamic> get course => {
57 'id': _course,
58 'titleFa': 'ریاضی آزمایشی',
59 'units': [
60 for (final id in [_unit, _otherUnit])
61 {
62 'id': id,
63 'titleFa': 'درس آزمایشی',
64 'progress': progress[id] ??
65 {
66 'unitId': id,
67 'status': 'not_started',
68 'source': 'self_reported',
69 'version': 0,
70 'updatedAt': null
71 }
72 }
73 ]
74 };
75
76 Future<http.Response> handle(http.Request request) async {
77 requests.add(request);
78 expect(request.headers['authorization'], 'Bearer synthetic-test-token');
79 if (delay != null) await delay;
80 if (offline) throw http.ClientException('offline substitute');
81 if (errorStatus != null) {
82 return http.Response(
83 jsonEncode({'error': 'synthetic_failure'}), errorStatus!);
84 }
85 if (request.method == 'GET' && request.url.path.contains('/courses/')) {
86 final value = alterCourse == null ? course : alterCourse!(course);
87 return http.Response(jsonEncode({'course': value}), 200,
88 headers: {'content-type': 'application/json; charset=utf-8'});
89 }
90 if (request.method == 'GET' &&
91 request.url.path == '/v1/me/learning-progress') {
92 return http.Response(
93 jsonEncode({'progress': progress.values.toList()}), 200);
94 }
95 final body = jsonDecode(request.body) as Map<String, dynamic>;
96 final id = request.url.path.split('/').last;
97 final mutationId = body['mutationId'] as String;
98 if (!applied.containsKey(mutationId)) {
99 final row = progress[id];
100 if ((row?['version'] ?? 0) != body['expectedVersion']) {
101 return http.Response(jsonEncode({'error': 'version_conflict'}), 409);
102 }
103 final ack = <String, dynamic>{
104 'mutationId': mutationId,
105 'unitId': id,
106 'status': body['status'],
107 'source': body['source'],
108 'version': (body['expectedVersion'] as int) + 1,
109 'updatedAt': _time,
110 'acceptedAt': _time
111 };
112 applied[mutationId] = ack;
113 progress[id] = {...ack}..remove('mutationId');
114 }
115 if (appliedThenDisconnect) {
116 appliedThenDisconnect = false;
117 throw http.ClientException('acknowledgement lost after synthetic commit');
118 }
119 var ack = {...applied[mutationId]!};
120 if (alterAck != null) ack = alterAck!(ack);
121 return http.Response(jsonEncode(ack), 200);
122 }
123
124 LearningSync reopen() => LearningSync(api,
125 store: OfflineStore.forNamespace(store.scope, session: session));
126 }
127
128 Matcher _code(String code) =>
129 throwsA(isA<ApiException>().having((e) => e.code, 'code', code));
130
131 void main() {
132 TestWidgetsFlutterBinding.ensureInitialized();
133 setUp(() {
134 SharedPreferencesAsyncPlatform.instance =
135 InMemorySharedPreferencesAsync.withData({});
136 String? pending;
137 TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
138 .setMockMethodCallHandler(
139 const MethodChannel('lifeguide/local_write_guard'), (call) async {
140 if (call.method == 'getBlocked') return pending != null;
141 if (call.method == 'beginWrite') return pending = 'synthetic-owned-write';
142 if (call.method == 'completeWrite' && call.arguments == pending) {
143 pending = null;
144 return true;
145 }
146 throw PlatformException(code: 'local_storage_restart_required');
147 });
148 });
149
150 test('reading a lesson never completes it and cache survives a fresh handle',
151 () async {
152 final f = _Fixture();
153 final course = await f.sync.readCourse(_course);
154 expect(course['offline'], false);
155 expect(
156 (course['units'] as List).first['progress']['status'], 'not_started');
157 expect(f.requests.where((r) => r.method == 'PUT'), isEmpty);
158 f.offline = true;
159 final cached = await f.reopen().readCourse(_course);
160 expect(cached['offline'], true);
161 expect(cached['titleFa'], 'ریاضی آزمایشی');
162 expect(
163 (cached['units'] as List).first['progress']['status'], 'not_started');
164 });
165
166 test('enqueue precedes PUT and acknowledgement updates only progress cache',
167 () async {
168 final f = _Fixture();
169 final original = f.api;
170 f.api = HttpIdentityApi(
171 baseUrl: original.baseUrl,
172 sessionStore: _Session(),
173 client: MockClient((request) async {
174 expect(await f.store.readQueue(), hasLength(1));
175 return f.handle(request);
176 }))
177 ..accessToken = 'synthetic-test-token'
178 ..currentUserId = original.currentUserId;
179 final result = await LearningSync(f.api, store: f.store)
180 .setProgress(_unit, 'in_progress', 0);
181 expect(result['queued'], false);
182 expect(result['progress']['version'], 1);
183 expect(await f.store.readQueue(), isEmpty);
184 expect(await f.store.readPlanner(), isEmpty);
185 expect(await f.store.readToday(), isEmpty);
186 expect(
187 (await f.store.readList('learning_progress')).single['unitId'], _unit);
188 });
189
190 test('offline report survives reopening and stable retry has no duplicate',
191 () async {
192 final f = _Fixture()..offline = true;
193 await f.sync.readCourse(_course).catchError((_) => <String, dynamic>{});
194 final result = await f.sync.setProgress(_unit, 'completed', 0);
195 expect(result['queued'], true);
196 expect(result['progress']['pending_sync'], true);
197 expect(result['progress']['version'], 0);
198 final queue = await f.store.readQueue();
199 final payload = Map<String, dynamic>.from(queue.single['payload'] as Map);
200 f.offline = false;
201 await f.reopen().flush();
202 await f.reopen().flush();
203 expect(f.applied, hasLength(1));
204 expect(f.applied.keys.single, payload['mutationId']);
205 final sent = f.requests.where((r) => r.method == 'PUT').last;
206 expect(jsonDecode(sent.body), payload);
207 expect(await f.store.readQueue(), isEmpty);
208 });
209
210 test('lost acknowledgement retries exact body after synthetic server commit',
211 () async {
212 final f = _Fixture()..appliedThenDisconnect = true;
213 final queued = await f.sync.setProgress(_unit, 'completed', 0);
214 expect(queued['queued'], true);
215 final firstBody = f.requests.single.body;
216 await f.reopen().flush();
217 expect(f.requests.last.body, firstBody);
218 expect(f.applied, hasLength(1));
219 expect((await f.store.readList('learning_progress')).single['version'], 1);
220 });
221
222 test('one unresolved mutation per unit, including concurrent handles',
223 () async {
224 final f = _Fixture()..offline = true;
225 final first = f.sync.setProgress(_unit, 'in_progress', 0);
226 final second = f.reopen().setProgress(_unit, 'completed', 0);
227 expect((await first)['queued'], true);
228 await expectLater(second, _code('sync_pending'));
229 expect(await f.sync.pendingFor(_unit), hasLength(1));
230 await f.sync.setProgress(_otherUnit, 'in_progress', 0);
231 expect(await f.store.readQueue(), hasLength(2));
232 });
233
234 test('malformed acknowledgements retain exact durable mutation', () async {
235 final mutations = <Map<String, dynamic> Function(Map<String, dynamic>)>[
236 (a) => a..['mutationId'] = 'wrong',
237 (a) => a..['unitId'] = _otherUnit,
238 (a) => a..['status'] = 'completed',
239 (a) => a..['source'] = 'timer',
240 (a) => a..['version'] = 0,
241 (a) => a..['version'] = 2,
242 (a) => a..['version'] = '1',
243 (a) => a..['acceptedAt'] = 'not-a-date',
244 (a) => a..['updatedAt'] = null,
245 ];
246 for (final corrupt in mutations) {
247 final f = _Fixture()..alterAck = corrupt;
248 await expectLater(f.sync.setProgress(_unit, 'in_progress', 0),
249 _code('invalid_sync_acknowledgement'));
250 expect(await f.store.readQueue(), hasLength(1));
251 expect(await f.store.readList('learning_progress'), isEmpty);
252 final body = (await f.store.readQueue()).single['payload'];
253 f.alterAck = null;
254 await f.reopen().flush();
255 expect(jsonDecode(f.requests.last.body), body);
256 }
257 });
258
259 test('refresh overlays pending report without calling it acknowledged',
260 () async {
261 final f = _Fixture();
262 await f.sync.readCourse(_course);
263 f.offline = true;
264 await f.sync.setProgress(_unit, 'completed', 0);
265 f.offline = false;
266 final live = await f.reopen().readCourse(_course);
267 final row = (live['units'] as List).first['progress'];
268 expect(row['status'], 'completed');
269 expect(row['pending_sync'], true);
270 expect(row['acknowledged'], false);
271 expect(row['version'], 0);
272 expect(await f.store.readQueue(), hasLength(1));
273 });
274
275 test('409 retains conflict; explicit server choice journals before removing',
276 () async {
277 final f = _Fixture()..offline = true;
278 await f.sync.setProgress(_unit, 'completed', 0);
279 final original = (await f.store.readQueue()).single;
280 f.progress[_unit] = {
281 'unitId': _unit,
282 'status': 'in_progress',
283 'source': 'self_reported',
284 'version': 2,
285 'updatedAt': _time,
286 };
287 f.offline = false;
288 await expectLater(f.sync.flush(), _code('version_conflict'));
289 expect((await f.store.readQueue()).single['queueStatus'], 'conflict');
290 await expectLater(f.sync.flush(), _code('sync_conflict'));
291 await f.sync.resolveUsingServer(_unit);
292 expect(await f.store.readQueue(), isEmpty);
293 final journal = await f.store.readDiscardedChanges();
294 expect(journal.single['payload'], original['payload']);
295 expect(journal.single['discardedAt'], isNotNull);
296 expect((await f.store.readList('learning_progress')).single['status'],
297 'in_progress');
298 expect(await f.store.readPlanner(), isEmpty);
299 });
300
301 test('permission/server failures are not offline success or stale live reads',
302 () async {
303 for (final status in [403, 422, 500, 503]) {
304 final f = _Fixture();
305 await f.sync.readCourse(_course);
306 f.errorStatus = status;
307 await expectLater(f.sync.readCourse(_course), _code('synthetic_failure'));
308 await expectLater(f.sync.setProgress(_unit, 'completed', 0),
309 _code('synthetic_failure'));
310 expect(await f.store.readQueue(), hasLength(1));
311 }
312 });
313
314 test('account and API namespace never share metadata or unsent progress',
315 () async {
316 final child = _Fixture(user: 'child');
317 await child.sync.readCourse(_course);
318 child.offline = true;
319 await child.sync.setProgress(_unit, 'completed', 0);
320 final parent = _Fixture(user: 'parent')..offline = true;
321 final other = _Fixture(user: 'child', endpoint: 'https://other.test')
322 ..offline = true;
323 for (final outsider in [parent, other]) {
324 expect(await outsider.sync.pendingFor(_unit), isEmpty);
325 await expectLater(
326 outsider.sync.readCourse(_course), _code('network_unavailable'));
327 expect(await outsider.store.readList('learning_progress'), isEmpty);
328 }
329 });
330
331 test(
332 'closed scope cannot acknowledge late response or erase quarantined work',
333 () async {
334 final f = _Fixture()..offline = true;
335 await f.sync.setProgress(_unit, 'completed', 0);
336 final original = (await f.store.readQueue()).single['payload'];
337 f.offline = false;
338 final delayed = Completer<void>();
339 f.delay = delayed.future;
340 final request = f.sync.flush();
341 await Future<void>.delayed(Duration.zero);
342 await OfflineStore.invalidateNamespace(f.store.scope);
343 delayed.complete();
344 await expectLater(request, _code('cache_scope_closed'));
345 final reopened =
346 OfflineStore.forNamespace(f.store.scope, session: f.session);
347 expect((await reopened.readQueue()).single['payload'], original);
348 expect(await reopened.readList('learning_progress'), isEmpty);
349 });
350
351 test('API identity change rejects old store without deleting its queue',
352 () async {
353 final f = _Fixture()..offline = true;
354 await f.sync.setProgress(_unit, 'in_progress', 0);
355 f.api.currentUserId = 'different-user';
356 await expectLater(f.sync.flush(), _code('cache_scope_closed'));
357 expect(await f.store.readQueue(), hasLength(1));
358 });
359
360 test('identity changed during offline response cannot return old progress',
361 () async {
362 final f = _Fixture();
363 final delayed = Completer<void>();
364 f.delay = delayed.future;
365 f.offline = true;
366 final request = f.sync.setProgress(_unit, 'completed', 0);
367 while (f.requests.isEmpty) {
368 await Future<void>.delayed(Duration.zero);
369 }
370 f.api.currentUserId = 'replacement-user';
371 delayed.complete();
372 await expectLater(request, _code('cache_scope_closed'));
373 expect(await f.store.readQueue(), hasLength(1));
374 });
375
376 test('malformed course response cannot replace last valid cached metadata',
377 () async {
378 final f = _Fixture();
379 await f.sync.readCourse(_course);
380 f.alterCourse = (value) => value
381 ..['units'] = [
382 {'id': 'wrong'}
383 ];
384 await expectLater(
385 f.sync.readCourse(_course), _code('invalid_learning_course'));
386 f.offline = true;
387 final cached = await f.sync.readCourse(_course);
388 expect(cached['offline'], true);
389 expect((cached['units'] as List).first['id'], _unit);
390 });
391
392 test('missing server progress never silently discards unresolved report',
393 () async {
394 final f = _Fixture()..offline = true;
395 await f.sync.setProgress(_unit, 'completed', 0);
396 final payload = (await f.store.readQueue()).single['payload'];
397 f.offline = false;
398 await expectLater(
399 f.sync.resolveUsingServer(_unit), _code('invalid_learning_progress'));
400 expect((await f.store.readQueue()).single['payload'], payload);
401 expect(await f.store.readDiscardedChanges(), isEmpty);
402 });
403
404 test('server choice does not discard an independent entity with same UUID',
405 () async {
406 final f = _Fixture()..offline = true;
407 await f.sync.setProgress(_unit, 'completed', 0);
408 await f.store.enqueue({
409 'id': '00000000-0000-4000-8000-000000000300',
410 'entityId': _unit,
411 'entityType': 'plan_item',
412 'operation': 'update',
413 'payload': {'title': 'synthetic independent planner change'},
414 });
415 f.progress[_unit] = {
416 'unitId': _unit,
417 'status': 'in_progress',
418 'source': 'self_reported',
419 'version': 1,
420 'updatedAt': _time,
421 };
422 f.offline = false;
423 await expectLater(
424 f.sync.resolveUsingServer(_unit), _code('sync_entity_collision'));
425 expect(await f.store.readQueue(), hasLength(2));
426 expect(await f.store.readDiscardedChanges(), isEmpty);
427 });
428 }