diff --git a/lib/services/translation_service.dart b/lib/services/translation_service.dart index 1688203b..cb8b0958 100644 --- a/lib/services/translation_service.dart +++ b/lib/services/translation_service.dart @@ -39,11 +39,14 @@ class TranslationDownloadCancelled implements Exception { class TranslationService extends ChangeNotifier { final AppSettingsService _appSettingsService; final TranslationFileStore _fileStore; + final http.Client Function() _newClient; TranslationService( this._appSettingsService, { TranslationFileStore? fileStore, - }) : _fileStore = fileStore ?? TranslationFileStore() { + http.Client Function()? clientFactory, + }) : _fileStore = fileStore ?? TranslationFileStore(), + _newClient = clientFactory ?? http.Client.new { // Initialize langdetect once at service construction. _langDetectInit = initLangDetect(); } @@ -64,6 +67,10 @@ class TranslationService extends ChangeNotifier { String? _downloadTargetFileName; String? _downloadSourceUrl; String? _downloadModelId; + String? _failedDownloadError; + String? _failedDownloadSourceUrl; + String? _failedDownloadFileName; + String? _failedDownloadModelId; bool get isBusy => _isBusy; bool get isDownloading => _isDownloading; @@ -82,6 +89,18 @@ class TranslationService extends ChangeNotifier { /// Preset id when the download was started as a preset, otherwise null. String? get downloadModelId => _downloadModelId; + + /// Error message from the most recent failed download, if any. + String? get failedDownloadError => _failedDownloadError; + + /// URL of the most recent failed download, if any. + String? get failedDownloadSourceUrl => _failedDownloadSourceUrl; + + /// Resolved filename of the most recent failed download, if any. + String? get failedDownloadFileName => _failedDownloadFileName; + + /// Preset id of the most recent failed download, if it was a preset. + String? get failedDownloadModelId => _failedDownloadModelId; double? get downloadProgress { final total = _downloadTotalBytes; if (!_isDownloading || total == null || total <= 0) { @@ -210,6 +229,7 @@ class TranslationService extends ChangeNotifier { return _runExclusive(() async { _setBusy(true); _lastError = null; + _clearFailedDownload(); final resolvedFileName = fileName ?? _sanitizeFileName( @@ -227,7 +247,7 @@ class TranslationService extends ChangeNotifier { _setDownloading(true); try { // HEAD request to check size and range support. - final headClient = http.Client(); + final headClient = _newClient(); int? totalSize; bool supportsRange = false; try { @@ -240,6 +260,10 @@ class TranslationService extends ChangeNotifier { headClient.close(); } + if (_cancelDownloadRequested) { + throw const TranslationDownloadCancelled(); + } + _downloadTotalBytes = totalSize; _notify(); @@ -277,6 +301,15 @@ class TranslationService extends ChangeNotifier { await _appSettingsService.setTranslationModelSourceUrl(sourceUrl); _failedModelPath = null; return record; + } on TranslationDownloadCancelled { + rethrow; + } catch (error) { + _lastError = '$error'; + _failedDownloadError = '$error'; + _failedDownloadSourceUrl = sourceUrl; + _failedDownloadFileName = resolvedFileName; + _failedDownloadModelId = id; + rethrow; } finally { _setDownloading(false); } @@ -287,7 +320,7 @@ class TranslationService extends ChangeNotifier { required Uri uri, required String fileName, }) async { - final client = http.Client(); + final client = _newClient(); try { final response = await client.send(http.Request('GET', uri)); if (response.statusCode < 200 || response.statusCode >= 300) { @@ -331,7 +364,7 @@ class TranslationService extends ChangeNotifier { if (start >= totalSize) break; final chunkPath = await _fileStore.chunkFilePath(fileName, i); chunkPaths.add(chunkPath); - final client = http.Client(); + final client = _newClient(); clients.add(client); futures.add( _downloadRange( @@ -718,6 +751,13 @@ class TranslationService extends ChangeNotifier { _notify(); } + void _clearFailedDownload() { + _failedDownloadError = null; + _failedDownloadSourceUrl = null; + _failedDownloadFileName = null; + _failedDownloadModelId = null; + } + /// Puts the service in the same state [downloadModel] publishes while a /// fetch is running, so settings can be rebuilt without a network call. @visibleForTesting @@ -729,12 +769,15 @@ class TranslationService extends ChangeNotifier { int downloadedBytes = 0, int? totalBytes, }) { + _lastError = null; + _clearFailedDownload(); _downloadSourceUrl = sourceUrl; _downloadModelId = modelId; _downloadTargetFileName = fileName; _downloadFileName = displayedFileName ?? fileName; _downloadedBytes = downloadedBytes; _downloadTotalBytes = totalBytes; + _isBusy = true; _isDownloading = true; _notify(); } diff --git a/lib/widgets/translation_settings_section.dart b/lib/widgets/translation_settings_section.dart index fc0ac2cb..8f2de947 100644 --- a/lib/widgets/translation_settings_section.dart +++ b/lib/widgets/translation_settings_section.dart @@ -171,6 +171,7 @@ class _TranslationModelsState extends State<_TranslationModels> { lastError != null && lastError.isNotEmpty && lastError != 'Download stopped.' && + lastError != translationService.failedDownloadError && lastError != _failedDetail; return Column( @@ -219,6 +220,8 @@ class _TranslationModelsState extends State<_TranslationModels> { final items = []; var pendingShown = false; + final serviceFailedError = service.failedDownloadError; + bool targets(String id, String sourceUrl, String name) { if (pending == null) return false; if (pending.id == id || pending.modelId == id) return true; @@ -227,6 +230,27 @@ class _TranslationModelsState extends State<_TranslationModels> { return false; } + bool matchesServiceFailure( + String id, + String sourceUrl, + String? fileName, + String? installedName, + ) { + if (serviceFailedError == null) return false; + if (service.failedDownloadModelId == id) return true; + if (sourceUrl.isNotEmpty && + service.failedDownloadSourceUrl == sourceUrl) { + return true; + } + final failedFile = service.failedDownloadFileName; + if (failedFile != null && + failedFile.isNotEmpty && + (failedFile == fileName || failedFile == installedName)) { + return true; + } + return false; + } + ModelDownloadItem buildItem({ required String id, required String name, @@ -240,11 +264,25 @@ class _TranslationModelsState extends State<_TranslationModels> { service.isDownloading && (targets(id, sourceUrl, name) || _fileNamesThisDownload(service, fileName, installed?.name)); - final failed = !downloading && _failedId == id; + final failed = + !downloading && + (_failedId == id || + (_failedId == null && + matchesServiceFailure( + id, + sourceUrl, + fileName, + installed?.name, + ))); if (downloading || failed) pendingShown = true; final merging = downloading && _isMerging(service); final busy = service.isBusy; final installedModel = installed; + final failureDetail = _failedId == id + ? _failedDetail + : (serviceFailedError != null + ? l10n.translation_downloadFailed(serviceFailedError) + : null); return ModelDownloadItem( id: id, @@ -266,7 +304,7 @@ class _TranslationModelsState extends State<_TranslationModels> { detail: merging ? l10n.translation_mergingChunks : failed - ? _failedDetail + ? failureDetail : null, progress: downloading && !merging ? service.downloadProgress : null, downloadedBytes: downloading ? service.downloadedBytes : 0, @@ -349,6 +387,33 @@ class _TranslationModelsState extends State<_TranslationModels> { ), ), ); + } else if (!pendingShown && + !service.isDownloading && + serviceFailedError != null && + service.failedDownloadSourceUrl != null) { + final failedUrl = service.failedDownloadSourceUrl!; + final failedFile = service.failedDownloadFileName; + final failedModelId = service.failedDownloadModelId; + final id = (failedModelId != null && failedModelId.isNotEmpty) + ? failedModelId + : failedUrl.isNotEmpty + ? failedUrl + : (failedFile ?? 'download'); + items.add( + ModelDownloadItem( + id: id, + name: _displayName(failedUrl, failedFile, failedModelId), + status: ModelDownloadStatus.error, + detail: l10n.translation_downloadFailed(serviceFailedError), + onDownload: service.isBusy + ? null + : () => _download( + sourceUrl: failedUrl, + fileName: failedFile, + id: failedModelId, + ), + ), + ); } return items; diff --git a/test/widgets/model_download_list_test.dart b/test/widgets/model_download_list_test.dart index 4734bcad..d5653aa8 100644 --- a/test/widgets/model_download_list_test.dart +++ b/test/widgets/model_download_list_test.dart @@ -1,11 +1,16 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import 'package:meshcore_open/l10n/app_localizations.dart'; import 'package:meshcore_open/models/image_codec_support.dart'; import 'package:meshcore_open/models/translation_support.dart'; import 'package:meshcore_open/services/app_settings_service.dart'; import 'package:meshcore_open/services/image_codec_service.dart'; import 'package:meshcore_open/services/image_codec_settings_store.dart'; +import 'package:meshcore_open/services/translation_file_store.dart'; import 'package:meshcore_open/services/translation_service.dart'; import 'package:meshcore_open/storage/prefs_manager.dart'; import 'package:meshcore_open/theme/mesh_theme.dart'; @@ -16,6 +21,40 @@ import 'package:provider/provider.dart'; import 'package:provider/single_child_widget.dart'; import 'package:shared_preferences/shared_preferences.dart'; +class _MemoryTranslationFileStore extends TranslationFileStore { + final Map _files = {}; + + @override + Future modelDirectoryPath() async => '/memory/translation_models'; + + @override + Future> scanDownloadedModels() async => const []; + + @override + Future deleteModel(TranslationModelRecord model) async { + _files.remove(model.localPath); + } + + @override + Future deleteFile(String path) async { + _files.remove(path); + } + + @override + Future writeModelBytes({ + required String fileName, + required Stream> chunks, + }) async { + var total = 0; + await for (final chunk in chunks) { + total += chunk.length; + } + final path = '/memory/translation_models/$fileName'; + _files[path] = total; + return DownloadedModelFile(localPath: path, fileSizeBytes: total); + } +} + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -274,6 +313,156 @@ void main() { expect(find.byTooltip('Cancel'), findsOneWidget); }); + testWidgets( + 'reopening settings during a custom download supports cancel, completion, and failure', + (tester) async { + StreamController>? getStream; + final settings = AppSettingsService(); + await settings.loadSettings(); + final translation = TranslationService( + settings, + fileStore: _MemoryTranslationFileStore(), + clientFactory: () => MockClient.streaming((request, _) async { + if (request.method == 'HEAD') { + return http.StreamedResponse( + const Stream>.empty(), + 200, + contentLength: 1024, + ); + } + final controller = StreamController>(); + getStream = controller; + return http.StreamedResponse( + controller.stream, + 200, + contentLength: 1024, + ); + }), + ); + addTearDown(translation.dispose); + + final providers = [ + ChangeNotifierProvider.value(value: settings), + ChangeNotifierProvider.value(value: translation), + ]; + + Future startCustomDownload(String url) async { + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + await tester.ensureVisible(find.byType(TextField)); + await tester.enterText(find.byType(TextField), url); + await tester.pump(); + final urlFieldDownload = find.descendant( + of: find.byType(TextField), + matching: find.byTooltip('Download'), + ); + await tester.ensureVisible(urlFieldDownload); + await tester.tap(urlFieldDownload); + await tester.pump(); + await tester.pump(); + } + + Future leaveAndReopen() async { + await pump(tester, const SizedBox.shrink(), providers: providers); + await pump( + tester, + const TranslationSettingsSection(), + providers: providers, + ); + } + + // 1. Cancel after reopen. + await startCustomDownload('https://example.com/Custom-Cancel.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(512, 1)); + await tester.pump(Duration.zero); + expect(translation.downloadedBytes, 512); + await leaveAndReopen(); + expect(find.text('Custom-Cancel'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + expect(find.byTooltip('Cancel'), findsOneWidget); + expect( + find.byKey( + ValueKey('model-download-${translationPresetModels.first.id}'), + ), + findsNothing, + ); + expect( + tester + .widget( + find.descendant( + of: find.byType(TextField), + matching: find.byType(IconButton), + ), + ) + .onPressed, + isNull, + ); + + await tester.ensureVisible(find.byTooltip('Cancel')); + await tester.tap(find.byTooltip('Cancel')); + await tester.pump(); + expect(translation.lastError, 'Download stopped.'); + getStream!.add(List.filled(16, 1)); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(translation.isDownloading, isFalse); + expect(find.text('Custom-Cancel'), findsNothing); + expect(find.text('Download stopped.'), findsNothing); + + // 2. Complete after reopen. + await startCustomDownload('https://example.com/Custom-Complete.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(512, 2)); + await tester.pump(Duration.zero); + await leaveAndReopen(); + expect(find.text('Custom-Complete'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + + getStream!.add(List.filled(512, 2)); + unawaited(getStream!.close()); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(find.text('Custom-Complete'), findsOneWidget); + expect(find.textContaining('Ready'), findsOneWidget); + expect(find.textContaining('Active'), findsOneWidget); + + // 3. Failure after reopen. + await startCustomDownload('https://example.com/Custom-Fail.gguf'); + await tester.pump(Duration.zero); + getStream!.add(List.filled(256, 3)); + await tester.pump(Duration.zero); + await leaveAndReopen(); + expect(find.text('Custom-Fail'), findsOneWidget); + expect(find.textContaining('Downloading'), findsOneWidget); + + getStream!.addError(http.ClientException('Connection reset')); + unawaited(getStream!.close()); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pump(); + expect(find.text('Custom-Fail'), findsOneWidget); + expect(find.textContaining("Couldn't download"), findsOneWidget); + expect(find.textContaining('Connection reset'), findsOneWidget); + // Error is shown in the model row detail, not duplicated below the URL field. + expect(find.text('ClientException: Connection reset'), findsNothing); + expect( + find.byKey( + const ValueKey('model-download-https://example.com/Custom-Fail.gguf'), + ), + findsOneWidget, + ); + }, + ); + testWidgets('an installed image bundle is one ready row', (tester) async { final spec = imageCodecPresetModels.single; final settings = AppSettingsService();