diff --git a/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart b/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart index 0f9924629..192e6d580 100644 --- a/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart +++ b/mobile/lib/services/machine_learning/semantic_search/semantic_search_service.dart @@ -133,6 +133,39 @@ class SemanticSearchService { _isSyncing = false; } + Future<(String, List)>? _searchScreenRequest; + String? _lastQuery; + + // searchScreenQuery should only be used for the user initiate query on the search screen. + // If there are multiple call tho this method, then for all the calls, the result will be the same as the last query. + Future<(String, List)> searchScreenQuery(String query) async { + if (!LocalSettings.instance.hasEnabledMagicSearch() || + !_frameworkInitialization.isCompleted) { + return (query, []); + } + // If there's an ongoing request, just update the last query and return its future. + if (_searchScreenRequest != null) { + _lastQuery = query; + return _searchScreenRequest!; + } else { + // No ongoing request, start a new search. + _searchScreenRequest = _getMatchingFiles(query).then((result) { + // Search completed, reset the ongoing request. + _searchScreenRequest = null; + // If there was a new query during the last search, start a new search with the last query. + if (_lastQuery != null) { + final String newQuery = _lastQuery!; + _lastQuery = null; // Reset last query. + return searchScreenQuery( + newQuery, + ); // Recursively call search with the latest query. + } + return (query, result); + }); + return _searchScreenRequest!; + } + } + Future> search(String query) async { if (!LocalSettings.instance.hasEnabledMagicSearch() || !_frameworkInitialization.isCompleted) { diff --git a/mobile/lib/services/search_service.dart b/mobile/lib/services/search_service.dart index fa2317836..65aebf097 100644 --- a/mobile/lib/services/search_service.dart +++ b/mobile/lib/services/search_service.dart @@ -1,6 +1,7 @@ import "dart:math"; import "package:flutter/cupertino.dart"; +import "package:flutter/foundation.dart"; import "package:intl/intl.dart"; import 'package:logging/logging.dart'; import "package:photos/core/constants.dart"; @@ -830,8 +831,21 @@ class SearchService { String query, ) async { final List searchResults = []; - final files = await SemanticSearchService.instance.search(query); + late List files; + late String resultForQuery; + try { + (resultForQuery, files) = + await SemanticSearchService.instance.searchScreenQuery(query); + } catch (e, s) { + _logger.severe("Error occurred during magic search", e, s); + return searchResults; + } if (files.isNotEmpty) { + if (kDebugMode) { + debugPrint( + "getMagicSearchResults ($query) results: ${files.length} for $resultForQuery ", + ); + } searchResults.add(GenericSearchResult(ResultType.magic, query, files)); } return searchResults;