Merge branch 'main' into claude/trusting-shannon-ff64dd

# Conflicts:
#	apps/app_seeds/lib/i18n/strings.g.dart
This commit is contained in:
vjrj 2026-07-09 23:56:45 +02:00
commit 6eb1517ffb
37 changed files with 2998 additions and 258 deletions

View file

@ -0,0 +1,54 @@
import 'package:commons_core/commons_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/variety_repository.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';
import '../support/test_support.dart';
/// A real seed bank can hold thousands of accessions. This guards that the
/// list query stays a handful of batched queries (not N+1) and returns in a
/// human blink even at that scale the pre-beta performance check.
void main() {
late AppDatabase db;
late VarietyRepository repo;
setUp(() {
db = newTestDatabase();
repo = newTestRepository(db);
});
tearDown(() => db.close());
test('the inventory view loads 3000 varieties quickly', () async {
const count = 3000;
for (var i = 0; i < count; i++) {
final id = await repo.addQuickVariety(
label: 'Variety $i',
category: i.isEven ? 'Poaceae' : 'Fabaceae',
);
// Every few varieties, add a lot so the batched lot/type/share queries
// do real work.
if (i % 5 == 0) {
await repo.addLot(
varietyId: id,
harvestYear: 2020 + (i % 5),
quantity: const Quantity(kind: QuantityKind.handful),
offerStatus: i % 25 == 0 ? OfferStatus.shared : OfferStatus.private,
);
}
}
final sw = Stopwatch()..start();
final view = await repo.watchInventoryView().first;
sw.stop();
expect(view.items, hasLength(count));
// Generous ceiling for CI; typical local runs are well under 500ms. The
// point is to catch an accidental N+1 regression, not to micro-benchmark.
expect(
sw.elapsedMilliseconds,
lessThan(3000),
reason: 'inventory view took ${sw.elapsedMilliseconds}ms for $count rows',
);
});
}

View file

@ -0,0 +1,158 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:commons_core/commons_core.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/export_import/inventory_json_codec.dart';
import 'package:tane/db/database.dart';
import 'package:tane/security/secure_key_store.dart';
import 'package:tane/services/export_import_service.dart';
import 'package:tane/services/file_service.dart';
import '../support/test_support.dart';
class _FakeFiles implements FileService {
Uint8List? saved;
String? savedName;
Uint8List? toPick;
@override
Future<String?> saveFile({
required String suggestedName,
required Uint8List bytes,
}) async {
saved = bytes;
savedName = suggestedName;
return '/picked/$suggestedName';
}
@override
Future<Uint8List?> pickFileBytes({List<String>? allowedExtensions}) async =>
toPick;
}
void main() {
late AppDatabase dbA;
late AppDatabase dbB;
setUp(() {
dbA = newTestDatabase();
dbB = newTestDatabase();
});
tearDown(() async {
await dbA.close();
await dbB.close();
});
(ExportImportService, _FakeFiles, SecureKeyStore) newService(
AppDatabase db, {
String nodeId = 'node',
}) {
final files = _FakeFiles();
final keys = SecureKeyStore(store: InMemorySecretStore());
final service = ExportImportService(
repository: newTestRepository(db, nodeId: nodeId),
files: files,
keys: keys,
);
return (service, files, keys);
}
test('a saved backup is sealed — no plaintext leaves the app', () async {
final (service, files, _) = newService(dbA);
final repo = newTestRepository(dbA);
await repo.addQuickVariety(label: 'Secret heirloom');
await service.exportBackup();
expect(files.savedName, endsWith('.tanemaki'));
expect(BackupBox.looksSealed(files.saved!), isTrue);
expect(String.fromCharCodes(files.saved!).contains('Secret'), isFalse);
});
test('restore with the local seed needs no code (same identity)', () async {
final (serviceA, filesA, keysA) = newService(dbA);
final repoA = newTestRepository(dbA);
await repoA.addQuickVariety(label: 'Maize');
await serviceA.exportBackup();
// A fresh DB but the SAME keystore = your device after a reinstall.
final filesB = _FakeFiles()..toPick = filesA.saved;
final serviceB = ExportImportService(
repository: newTestRepository(dbB),
files: filesB,
keys: keysA,
);
final summary = await serviceB.restoreBackup(
(await serviceB.pickBackup())!,
);
expect(summary.inserted, 1);
final restored = await dbB.select(dbB.varieties).get();
expect(restored.single.label, 'Maize');
});
test(
'restore on a new device needs the recovery code and adopts the seed',
() async {
final (serviceA, filesA, keysA) = newService(dbA, nodeId: 'device-a');
final repoA = newTestRepository(dbA, nodeId: 'device-a');
await repoA.addQuickVariety(label: 'Grandma tomato');
await serviceA.exportBackup();
final code = await serviceA.recoveryCode();
final (serviceB, filesB, keysB) = newService(dbB, nodeId: 'device-b');
// Force device B to have its own (different) identity first.
final seedB = await keysB.rootSeedHex();
expect(seedB, isNot(await keysA.rootSeedHex()));
filesB.toPick = filesA.saved;
final pending = (await serviceB.pickBackup())!;
// Without the code: authentication fails, nothing imported.
await expectLater(
serviceB.restoreBackup(pending),
throwsA(isA<BackupAuthException>()),
);
expect(await dbB.select(dbB.varieties).get(), isEmpty);
// With the printed code: data restored AND identity recovered.
final summary = await serviceB.restoreBackup(pending, recoveryCode: code);
expect(summary.inserted, 1);
final restored = await dbB.select(dbB.varieties).get();
expect(restored.single.label, 'Grandma tomato');
expect(await keysB.rootSeedHex(), await keysA.rootSeedHex());
},
);
test('a sloppy typed code (lowercase, spaces) still opens', () async {
final (serviceA, filesA, _) = newService(dbA);
final repoA = newTestRepository(dbA);
await repoA.addQuickVariety(label: 'Bean');
await serviceA.exportBackup();
final code = await serviceA.recoveryCode();
final (serviceB, filesB, _) = newService(dbB);
filesB.toPick = filesA.saved;
final pending = (await serviceB.pickBackup())!;
final summary = await serviceB.restoreBackup(
pending,
recoveryCode: code.toLowerCase().replaceAll('-', ' '),
);
expect(summary.inserted, 1);
});
test('legacy plain exports still restore (no seal, direct parse)', () async {
final repoA = newTestRepository(dbA);
await repoA.addQuickVariety(label: 'Old export');
final legacy = utf8.encode(
const InventoryJsonCodec().encode(await repoA.exportInventory()),
);
final (serviceB, filesB, _) = newService(dbB);
filesB.toPick = Uint8List.fromList(legacy);
final summary = await serviceB.restoreBackup(
(await serviceB.pickBackup())!,
);
expect(summary.inserted, 1);
});
}

View file

@ -60,6 +60,7 @@ Widget wrapScreen({
required VarietyRepository repository,
required Widget child,
AppLocale locale = AppLocale.en,
TextDirection? textDirection,
}) {
LocaleSettings.setLocaleSync(locale);
return TranslationProvider(
@ -75,7 +76,9 @@ Widget wrapScreen({
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: child,
home: textDirection == null
? child
: Directionality(textDirection: textDirection, child: child),
),
),
),
@ -88,6 +91,7 @@ Widget wrapDetail({
required String varietyId,
SpeciesRepository? species,
AppLocale locale = AppLocale.en,
TextDirection? textDirection,
}) {
LocaleSettings.setLocaleSync(locale);
return TranslationProvider(
@ -106,7 +110,12 @@ Widget wrapDetail({
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: const VarietyDetailScreen(),
home: textDirection == null
? const VarietyDetailScreen()
: Directionality(
textDirection: textDirection,
child: const VarietyDetailScreen(),
),
),
),
),

View file

@ -1,15 +1,17 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:commons_core/commons_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/data/export_import/inventory_json_codec.dart';
import 'package:tane/data/export_import/inventory_snapshot.dart';
import 'package:tane/db/database.dart';
import 'package:tane/i18n/strings.g.dart';
import 'package:tane/security/secure_key_store.dart';
import 'package:tane/services/export_import_service.dart';
import 'package:tane/services/file_service.dart';
import 'package:tane/services/recovery_sheet_service.dart';
import 'package:tane/ui/backup_section.dart';
import 'package:tane/ui/settings_screen.dart';
@ -39,15 +41,20 @@ class FakeFileService implements FileService {
void main() {
late AppDatabase db;
late FakeFileService files;
late SecureKeyStore keys;
late ExportImportService service;
late RecoverySheetService sheet;
setUp(() {
db = newTestDatabase();
files = FakeFileService();
keys = SecureKeyStore(store: InMemorySecretStore());
service = ExportImportService(
repository: newTestRepository(db),
files: files,
keys: keys,
);
sheet = RecoverySheetService(files: files);
});
tearDown(() => db.close());
@ -66,6 +73,12 @@ void main() {
);
}
Widget section() => wrap(
Scaffold(
body: BackupSection(service: service, sheet: sheet),
),
);
testWidgets('settings shows the backup section with its actions', (
tester,
) async {
@ -76,6 +89,7 @@ void main() {
expect(find.text('Backup & restore'), findsOneWidget);
expect(find.text('Save a backup'), findsOneWidget);
expect(find.text('Restore a backup'), findsOneWidget);
expect(find.text('Your recovery code'), findsOneWidget);
expect(find.text('Export to a spreadsheet'), findsOneWidget);
expect(find.text('Import a list'), findsOneWidget);
});
@ -83,9 +97,7 @@ void main() {
testWidgets('spreadsheet export saves a .csv file and confirms', (
tester,
) async {
await tester.pumpWidget(
wrap(Scaffold(body: BackupSection(service: service))),
);
await tester.pumpWidget(section());
await tester.tap(find.text('Export to a spreadsheet'));
await tester.pumpAndSettle();
@ -94,35 +106,31 @@ void main() {
expect(find.text('Copy saved'), findsOneWidget);
});
testWidgets('saving a backup writes a versioned .json file', (tester) async {
await tester.pumpWidget(
wrap(Scaffold(body: BackupSection(service: service))),
);
testWidgets('saving a backup writes a sealed .tanemaki file', (tester) async {
await tester.pumpWidget(section());
await tester.tap(find.text('Save a backup'));
await tester.pumpAndSettle();
expect(files.savedName, endsWith('.json'));
final root =
jsonDecode(utf8.decode(files.savedBytes!)) as Map<String, dynamic>;
expect(root['formatVersion'], inventoryFormatVersion);
expect(files.savedName, endsWith('.tanemaki'));
expect(BackupBox.looksSealed(files.savedBytes!), isTrue);
expect(find.text('Copy saved'), findsOneWidget);
});
testWidgets('import asks for confirmation, imports and reports counts', (
tester,
) async {
// A valid one-variety export produced by another repository.
testWidgets('restoring my own sealed copy needs no code', (tester) async {
final otherDb = newTestDatabase();
addTearDown(otherDb.close);
final other = newTestRepository(otherDb, nodeId: 'node-other');
final otherFiles = FakeFileService();
final mine = ExportImportService(
repository: newTestRepository(otherDb, nodeId: 'other'),
files: otherFiles,
keys: keys, // same identity
);
final other = newTestRepository(otherDb, nodeId: 'other');
await other.addQuickVariety(label: 'Imported bean');
files.bytesToPick = utf8.encode(
const InventoryJsonCodec().encode(await other.exportInventory()),
);
await mine.exportBackup();
files.bytesToPick = otherFiles.savedBytes;
await tester.pumpWidget(
wrap(Scaffold(body: BackupSection(service: service))),
);
await tester.pumpWidget(section());
await tester.tap(find.text('Restore a backup'));
await tester.pumpAndSettle();
expect(find.text('Restore a backup?'), findsOneWidget);
@ -135,11 +143,64 @@ void main() {
expect(varieties.single.label, 'Imported bean');
});
testWidgets('a copy from another identity asks for the recovery code', (
tester,
) async {
final otherDb = newTestDatabase();
addTearDown(otherDb.close);
final otherFiles = FakeFileService();
final otherKeys = SecureKeyStore(store: InMemorySecretStore());
final theirs = ExportImportService(
repository: newTestRepository(otherDb, nodeId: 'other'),
files: otherFiles,
keys: otherKeys,
);
final other = newTestRepository(otherDb, nodeId: 'other');
await other.addQuickVariety(label: 'Recovered bean');
await theirs.exportBackup();
final code = await theirs.recoveryCode();
files.bytesToPick = otherFiles.savedBytes;
await tester.pumpWidget(section());
await tester.tap(find.text('Restore a backup'));
await tester.pumpAndSettle();
await tester.tap(find.text('Import'));
await tester.pumpAndSettle();
// Wrong seed the code prompt appears; type the printed code.
expect(find.text('Enter your recovery code'), findsOneWidget);
await tester.enterText(find.byKey(const Key('backup.recoveryField')), code);
await tester.tap(find.byKey(const Key('backup.recoveryConfirm')));
await tester.pumpAndSettle();
expect(find.text('Imported: 1 new, 0 updated'), findsOneWidget);
final varieties = await db.select(db.varieties).get();
expect(varieties.single.label, 'Recovered bean');
// The identity travelled with the code.
expect(await keys.rootSeedHex(), await otherKeys.rootSeedHex());
});
testWidgets('legacy plain exports still restore', (tester) async {
final otherDb = newTestDatabase();
addTearDown(otherDb.close);
final other = newTestRepository(otherDb, nodeId: 'node-other');
await other.addQuickVariety(label: 'Old bean');
files.bytesToPick = utf8.encode(
const InventoryJsonCodec().encode(await other.exportInventory()),
);
await tester.pumpWidget(section());
await tester.tap(find.text('Restore a backup'));
await tester.pumpAndSettle();
await tester.tap(find.text('Import'));
await tester.pumpAndSettle();
expect(find.text('Imported: 1 new, 0 updated'), findsOneWidget);
});
testWidgets('an unreadable file reports a friendly error', (tester) async {
files.bytesToPick = utf8.encode('this is not json');
await tester.pumpWidget(
wrap(Scaffold(body: BackupSection(service: service))),
);
await tester.pumpWidget(section());
await tester.tap(find.text('Restore a backup'));
await tester.pumpAndSettle();
await tester.tap(find.text('Import'));
@ -150,4 +211,25 @@ void main() {
findsOneWidget,
);
});
testWidgets('the recovery dialog shows the code and saves the sheet', (
tester,
) async {
await tester.pumpWidget(section());
await tester.tap(find.byKey(const Key('backup.recovery')));
await tester.pumpAndSettle();
final code = await service.recoveryCode();
expect(find.text(code), findsOneWidget);
await tester.tap(find.byKey(const Key('backup.recoverySave')));
await tester.pumpAndSettle();
expect(files.savedName, 'tanemaki-recovery.pdf');
expect(String.fromCharCodes(files.savedBytes!.take(5)), '%PDF-');
// The seed itself never appears in the clear in the PDF stream metadata;
// the QR encodes the human code, which IS the secret that's the point
// of the sheet. Just assert it saved and confirmed.
expect(find.text('Copy saved'), findsOneWidget);
});
}

View file

@ -0,0 +1,99 @@
import 'package:commons_core/commons_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:tane/db/database.dart';
import 'package:tane/db/enums.dart';
import 'package:tane/ui/inventory_list_screen.dart';
import 'package:tane/ui/settings_screen.dart';
import '../support/test_support.dart';
/// RTL is a first-class requirement (CLAUDE.md): the main screens must build
/// and lay out under right-to-left without overflowing or misplacing
/// directional affordances. Overflow errors fail these tests automatically.
void main() {
late AppDatabase db;
setUp(() => db = newTestDatabase());
tearDown(() => db.close());
testWidgets('the inventory list renders under RTL', (tester) async {
final repo = newTestRepository(db);
final id = await repo.addQuickVariety(
label: 'طماطم بلدية', // an Arabic label, as a keeper would write it
category: 'Solanaceae',
);
await repo.addLot(
varietyId: id,
harvestYear: 2024,
quantity: const Quantity(kind: QuantityKind.handful),
offerStatus: OfferStatus.shared,
);
await repo.addQuickVariety(label: 'Maize', category: 'Poaceae');
await tester.pumpWidget(
wrapScreen(
repository: repo,
textDirection: TextDirection.rtl,
child: const InventoryListScreen(),
),
);
await tester.pumpAndSettle();
expect(find.text('طماطم بلدية'), findsOneWidget);
expect(find.byKey(const Key('inventory.filter.sharing')), findsOneWidget);
await disposeTree(tester);
});
testWidgets('the variety detail (lots, calendar, names) renders under RTL', (
tester,
) async {
final repo = newTestRepository(db);
final id = await repo.addQuickVariety(
label: 'Grandma tomato',
category: 'Solanaceae',
);
await repo.addVernacularName(id, 'طماطم');
await repo.addLot(
varietyId: id,
harvestYear: 2023,
quantity: const Quantity(kind: QuantityKind.packet, count: 3),
abundance: Abundance.plentyToShare,
offerStatus: OfferStatus.exchange,
);
await tester.pumpWidget(
wrapDetail(
repository: repo,
varietyId: id,
species: newTestSpeciesRepository(db),
textDirection: TextDirection.rtl,
),
);
await tester.pumpAndSettle();
expect(find.text('Grandma tomato'), findsOneWidget);
expect(find.text('طماطم'), findsOneWidget);
// The lot sheet (the busiest form) must also lay out under RTL.
await tester.tap(find.byKey(const Key('detail.addLot')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('addLot.save')), findsOneWidget);
await disposeTree(tester);
});
testWidgets('settings renders under RTL', (tester) async {
final repo = newTestRepository(db);
await tester.pumpWidget(
wrapScreen(
repository: repo,
textDirection: TextDirection.rtl,
child: const SettingsScreen(),
),
);
await tester.pumpAndSettle();
expect(find.text('Português'), findsOneWidget);
await disposeTree(tester);
});
}