diff --git a/lib/search/utils/scope_tree.dart b/lib/search/utils/scope_tree.dart index a0d85ab732..3a8e75a0f1 100644 --- a/lib/search/utils/scope_tree.dart +++ b/lib/search/utils/scope_tree.dart @@ -1,4 +1,5 @@ import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:otzaria/data/book_identity.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/books.dart'; import 'package:otzaria/search/utils/facet_helper.dart'; @@ -144,9 +145,15 @@ class ScopeTree { 'withoutUserBooksScopeTree', ); - /// העץ בלי ספרים אישיים ומצורפים, ובלי קטגוריות שנותרו ריקות. - ScopeTree officialOnly() => - _officialOnlyCache[this] ??= _pruned((book) => book.source.isOfficial); + /// העץ בלי ספרים אישיים ומצורפים, מלבד אלה שמפתחם ב-[alsoKeep], + /// ובלי קטגוריות שנותרו ריקות. + ScopeTree officialOnly({Set alsoKeep = const {}}) => alsoKeep.isEmpty + ? _officialOnlyCache[this] ??= _pruned((book) => book.source.isOfficial) + : _pruned( + (book) => + book.source.isOfficial || + alsoKeep.contains(BookIdentity.keyOf(book)), + ); /// העץ בלי ספרים אישיים, ובלי קטגוריות שנותרו ריקות. ScopeTree withoutUserBooks() => diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index 2aaf4c781d..c17a883c26 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -322,6 +322,7 @@ class _SearchDialogState extends State { _semanticBloc = SemanticSearchBloc( repository: widget.semanticRepository ?? SemanticSearchRepository.instance, + loadCoveredBooks: true, )..add(const SemanticSearchStarted()); // מצב מבוקש במפורש (קיצור חיפוש מתקדם, איתור) וכרטיסייה בעריכה // גוברים על זיכרון הסשן. @@ -1152,7 +1153,11 @@ class _SearchDialogState extends State { UiSnack.show(LibraryMessages.emptySearchQuery); return; } - final isOfficialCategory = officialCategoryFilter(library); + final coveredBooks = _semanticBloc?.state.coveredBooks ?? const {}; + final isOfficialCategory = officialCategoryFilter( + library, + coveredBooks: coveredBooks, + ); final selection = parsedCategory.categoryFound ? [ ...parsedCategory.facets!, @@ -1164,6 +1169,7 @@ class _SearchDialogState extends State { facet, includeLexical: _semanticIncludeLexical, isOfficialCategory: isOfficialCategory, + coveredBooks: coveredBooks, ), )) { UiSnack.showError(SemanticSearchMessages.unsupportedScope); @@ -1222,6 +1228,7 @@ class _SearchDialogState extends State { Widget _buildSemanticPanel(SemanticAvailability availability) { return SemanticModePanel( availability: availability, + coveredBooks: _semanticBloc?.state.coveredBooks ?? const {}, debug: widget.semanticDebugPreview, queryController: _searchTab.queryController, queryFocusNode: _searchTab.searchFieldFocusNode, diff --git a/lib/search/view/search_scope_menu.dart b/lib/search/view/search_scope_menu.dart index 74945fb503..71831dcd2d 100644 --- a/lib/search/view/search_scope_menu.dart +++ b/lib/search/view/search_scope_menu.dart @@ -44,9 +44,13 @@ class SearchScopeMenuButton extends StatefulWidget { final Set selected; final ValueChanged> onChanged; - /// מציג רק ספרים מהספרייה הרשמית (בחיפוש החכם — רק להם יש וקטורים). + /// מציג רק ספרים מהספרייה הרשמית ואת [coveredBooks] — בחיפוש החכם, + /// הספרים שיש להם וקטורים. final bool officialBooksOnly; + /// מפתחות ספרים לא רשמיים שמוצגים גם עם [officialBooksOnly]. + final Set coveredBooks; + /// מסתיר ספרים אישיים כשאינם באינדקס ("בלי ספרים אישיים"). final bool excludeUserBooks; @@ -55,6 +59,7 @@ class SearchScopeMenuButton extends StatefulWidget { required this.selected, required this.onChanged, this.officialBooksOnly = false, + this.coveredBooks = const {}, this.excludeUserBooks = false, }); @@ -82,7 +87,7 @@ class _SearchScopeMenuButtonState extends State { int _baseBookGeneration = 0; ScopeTree _visibleTree(ScopeTree tree) => widget.officialBooksOnly - ? tree.officialOnly() + ? tree.officialOnly(alsoKeep: widget.coveredBooks) : widget.excludeUserBooks ? tree.withoutUserBooks() : tree; @@ -166,6 +171,20 @@ class _SearchScopeMenuButtonState extends State { _searchController.addListener(_onTextChanged); } + @override + void didUpdateWidget(covariant SearchScopeMenuButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (!setEquals(oldWidget.coveredBooks, widget.coveredBooks)) _resetTree(); + } + + void _resetTree() { + _treeCache = null; + _treeFuture = null; + _baseBookGeneration++; + _baseBookNodesCache = null; + _baseBookNodesFuture = null; + } + @override void dispose() { _fieldFocus.removeListener(_onFocusChanged); @@ -324,11 +343,7 @@ class _SearchScopeMenuButtonState extends State { final enabled = library != null; if (!identical(library, _library)) { _library = library; - _treeCache = null; - _treeFuture = null; - _baseBookGeneration++; - _baseBookNodesCache = null; - _baseBookNodesFuture = null; + _resetTree(); } return OverlayPortal( diff --git a/lib/semantic_search/bloc/semantic_search_bloc.dart b/lib/semantic_search/bloc/semantic_search_bloc.dart index 9e055a52d9..87afbf908b 100644 --- a/lib/semantic_search/bloc/semantic_search_bloc.dart +++ b/lib/semantic_search/bloc/semantic_search_bloc.dart @@ -15,9 +15,12 @@ export 'semantic_search_state.dart'; class SemanticSearchBloc extends Bloc { final SemanticSearchRepository repository; + + /// טוען את [SemanticSearchState.coveredBooks]; החישוב קורא את כל הסט. + final bool loadCoveredBooks; StreamSubscription? _subscription; - SemanticSearchBloc({required this.repository}) + SemanticSearchBloc({required this.repository, this.loadCoveredBooks = false}) : super( SemanticSearchState( availability: repository.availability, @@ -49,15 +52,16 @@ class SemanticSearchBloc ); }); on(_onRemovalRequested); - on( - (event, emit) => emit( + on((event, emit) async { + emit( state.copyWith( availability: event.availability, modelChoice: repository.modelChoice, activeModelChoice: repository.activeModelChoice, ), - ), - ); + ); + await _loadCoveredBooks(emit); + }); } Future _onStarted( @@ -69,6 +73,12 @@ class SemanticSearchBloc ); final availability = await repository.refresh(); emit(state.copyWith(availability: availability)); + await _loadCoveredBooks(emit); + } + + Future _loadCoveredBooks(Emitter emit) async { + if (!loadCoveredBooks || !state.availability.isUsable) return; + emit(state.copyWith(coveredBooks: await repository.coveredBooks())); } Future _onQuantizationChanged( diff --git a/lib/semantic_search/bloc/semantic_search_state.dart b/lib/semantic_search/bloc/semantic_search_state.dart index 109da3b371..300a0707f7 100644 --- a/lib/semantic_search/bloc/semantic_search_state.dart +++ b/lib/semantic_search/bloc/semantic_search_state.dart @@ -10,12 +10,16 @@ class SemanticSearchState extends Equatable { final SemanticModelChoice activeModelChoice; final bool isRemoving; + /// מפתחות האינדקס של הספרים שיש להם וקטורים, מכל המקורות. + final Set coveredBooks; + const SemanticSearchState({ this.availability = SemanticAvailability.initial, this.quantization = SemanticQuantization.int8, this.modelChoice = SemanticModelChoice.meivin, this.activeModelChoice = SemanticModelChoice.meivin, this.isRemoving = false, + this.coveredBooks = const {}, }); SemanticSearchState copyWith({ @@ -24,12 +28,14 @@ class SemanticSearchState extends Equatable { SemanticModelChoice? modelChoice, SemanticModelChoice? activeModelChoice, bool? isRemoving, + Set? coveredBooks, }) => SemanticSearchState( availability: availability ?? this.availability, quantization: quantization ?? this.quantization, modelChoice: modelChoice ?? this.modelChoice, activeModelChoice: activeModelChoice ?? this.activeModelChoice, isRemoving: isRemoving ?? this.isRemoving, + coveredBooks: coveredBooks ?? this.coveredBooks, ); @override @@ -39,5 +45,6 @@ class SemanticSearchState extends Equatable { modelChoice, activeModelChoice, isRemoving, + coveredBooks, ]; } diff --git a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart index 970332633a..70609be279 100644 --- a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart +++ b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart @@ -87,6 +87,18 @@ class OnnxSemanticEngineAdapter implements SemanticEngineBackend { ); }); + @override + Future> coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }) => _withToken(cancel, (token) async { + final covered = await (await _engine()).semanticCoveredBooks( + vectorsDir: vectorsDir, + cancellation: token, + ); + return covered.filePaths.toSet(); + }); + @override Future open(SemanticOpenRequest request) => _guard( () async => mapStatus( diff --git a/lib/semantic_search/engine/semantic_engine_backend.dart b/lib/semantic_search/engine/semantic_engine_backend.dart index 17b339c409..8a000d012f 100644 --- a/lib/semantic_search/engine/semantic_engine_backend.dart +++ b/lib/semantic_search/engine/semantic_engine_backend.dart @@ -41,6 +41,12 @@ abstract interface class SemanticEngineBackend { required SemanticCancelHandle cancel, }); + /// מפתחות האינדקס (`id:`/`uid:`/`db:`...) של הספרים שהסט מכסה, מכל המקורות. + Future> coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }); + /// פותח את הסט והמודל לקריאה ומחזיר את המצב שאחרי הפתיחה. Future open(SemanticOpenRequest request); @@ -108,6 +114,12 @@ class UnavailableSemanticEngineBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) => Future.error(_unavailable); + @override + Future> coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }) => Future.error(_unavailable); + @override Future open(SemanticOpenRequest request) => Future.error(_unavailable); diff --git a/lib/semantic_search/models/semantic_mode_gate.dart b/lib/semantic_search/models/semantic_mode_gate.dart index f8b23fcffa..0dd8cd7973 100644 --- a/lib/semantic_search/models/semantic_mode_gate.dart +++ b/lib/semantic_search/models/semantic_mode_gate.dart @@ -1,4 +1,5 @@ import 'package:flutter/foundation.dart' show kDebugMode; +import 'package:otzaria/data/book_identity.dart'; import 'package:otzaria/data/data_providers/book_database_resolver.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/models/book_source.dart'; @@ -36,7 +37,7 @@ bool isWholeLibraryScope(Iterable selection) { return categories.isEmpty || categories.contains('/'); } -/// מפתחות של ספרים אישיים ושל מסדים מצורפים — אין להם וקטורים. +/// מפתחות של ספרים אישיים ושל מסדים מצורפים — וקטורים רק כשהסט מכסה אותם. final RegExp _nonOfficialBookKey = RegExp(r'^(uid|db):'); final RegExp _bookKeySegment = RegExp(r'^(id|uid|ext|db):|\|'); @@ -52,29 +53,38 @@ List semanticScopeFacets(Iterable selection) { } /// האם facet של ספר או קטגוריה נתמך, לפני נרמול של בחירת כל הספרייה. +/// [coveredBooks] — מפתחות הספרים שהסט מכסה (ראו [officialCategoryFilter]). bool isSemanticScopeFacetSupported( String facet, { bool includeLexical = false, bool Function(String facet)? isOfficialCategory, + Set coveredBooks = const {}, }) { if (includeLexical || facet == '/' || FacetHelper.isDimensionFacet(facet)) { return true; } - if (BookDatabaseResolver.likelySource(categoryPath: facet) != - BookSource.official) { - return false; - } final segments = facet.split('/'); + final isBook = _bookKeySegment.hasMatch(segments.last); + if (isBook && coveredBooks.contains(segments.last)) return true; if (segments.any(_nonOfficialBookKey.hasMatch)) return false; - final categoryPath = _bookKeySegment.hasMatch(segments.last) + final categoryPath = isBook ? segments.sublist(0, segments.length - 1).join('/') : facet; - return categoryPath.isEmpty || - (isOfficialCategory?.call(categoryPath) ?? true); + final searchableCategory = isOfficialCategory?.call(categoryPath); + if (searchableCategory != true && + BookDatabaseResolver.likelySource(categoryPath: facet) != + BookSource.official) { + return false; + } + return categoryPath.isEmpty || (searchableCategory ?? true); } -/// האם בקטגוריה של [facet] יש ספר מהספרייה הרשמית; `null` כשהספרייה לא נטענה. -bool Function(String facet)? officialCategoryFilter(Library? library) { +/// האם בקטגוריה של [facet] יש ספר רשמי או ספר שמפתחו ב-[coveredBooks]; +/// `null` כשהספרייה לא נטענה. +bool Function(String facet)? officialCategoryFilter( + Library? library, { + Set coveredBooks = const {}, +}) { if (library == null) return null; return (facet) { // פסיק בשם תיקייה הוא מפריד ב-facet, ולכן משווים לנתיב ה-facet של התיקייה. @@ -85,10 +95,16 @@ bool Function(String facet)? officialCategoryFilter(Library? library) { return facet == path || facet.startsWith('$path/'); }).firstOrNull; } - return category != null && _hasOfficialBook(category); + return category != null && _hasSearchableBook(category, coveredBooks); }; } -bool _hasOfficialBook(Category category) => - category.books.any((book) => book.source.isOfficial) || - category.subCategories.any(_hasOfficialBook); +bool _hasSearchableBook(Category category, Set coveredBooks) => + category.books.any( + (book) => + book.source.isOfficial || + coveredBooks.contains(BookIdentity.keyOf(book)), + ) || + category.subCategories.any( + (child) => _hasSearchableBook(child, coveredBooks), + ); diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index 9e0790bd07..7688f56b05 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -543,6 +543,37 @@ class SemanticSearchRepository { cancel: cancel ?? SemanticCancelHandle(), ); + ({SemanticVectorsSummary vectors, Future> books})? _covered; + + /// מפתחות האינדקס של הספרים שהסט המותקן מכסה — גם אישיים ומצורפים. + /// החישוב קורא את כל הסט, ולכן נשמר עד שהסט משתנה; בכשל — קבוצה ריקה. + Future> coveredBooks() async { + try { + final directory = (await _paths()).vectorsDirectory; + final vectors = await vectorsInfo(); + if (!vectors.present) return const {}; + var cached = _covered; + if (cached == null || cached.vectors != vectors) { + cached = _covered = ( + vectors: vectors, + books: _backend.coveredBooks( + directory, + cancel: SemanticCancelHandle(), + ), + ); + } + return _lastCoveredBooks = await cached.books; + } catch (error, stackTrace) { + _covered = null; + _log('coveredBooks', error, stackTrace); + return const {}; + } + } + + /// התשובה האחרונה של [coveredBooks] שכבר הושלמה, בלי לחשב. + Set get lastCoveredBooks => _lastCoveredBooks; + Set _lastCoveredBooks = const {}; + /// תמונת המנוע לטלמטריה: מצב, זהות המודל, החבילה והוקטורים המותקנים. Future engineSnapshot() async { final status = await _safeStatus(); diff --git a/lib/semantic_search/view/semantic_mode_panel.dart b/lib/semantic_search/view/semantic_mode_panel.dart index b0d6040262..7a0e535303 100644 --- a/lib/semantic_search/view/semantic_mode_panel.dart +++ b/lib/semantic_search/view/semantic_mode_panel.dart @@ -26,6 +26,7 @@ class SemanticModePanel extends StatelessWidget { this.queryTrailingAction, required this.scopeSelection, required this.onScopeChanged, + this.coveredBooks = const {}, required this.includeLexical, required this.onIncludeLexicalChanged, required this.groupIdenticalText, @@ -46,6 +47,9 @@ class SemanticModePanel extends StatelessWidget { final Widget? queryTrailingAction; final Set scopeSelection; final ValueChanged> onScopeChanged; + + /// ספרים לא רשמיים שיש להם וקטורים, ולכן מוצעים בהיקף גם בלי התאמה מילולית. + final Set coveredBooks; final bool includeLexical; final ValueChanged onIncludeLexicalChanged; final bool groupIdenticalText; @@ -332,6 +336,7 @@ class SemanticModePanel extends StatelessWidget { key: ValueKey(includeLexical), selected: scopeSelection, officialBooksOnly: !includeLexical, + coveredBooks: coveredBooks, onChanged: onScopeChanged, ), FilterChip( diff --git a/lib/semantic_search/view/semantic_search_results_screen.dart b/lib/semantic_search/view/semantic_search_results_screen.dart index 78a6afcf17..206acf3461 100644 --- a/lib/semantic_search/view/semantic_search_results_screen.dart +++ b/lib/semantic_search/view/semantic_search_results_screen.dart @@ -31,6 +31,7 @@ import 'package:otzaria/semantic_search/bloc/semantic_results_bloc.dart'; import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; import 'package:otzaria/semantic_search/models/semantic_mode_gate.dart'; import 'package:otzaria/semantic_search/repository/semantic_platform_support.dart'; +import 'package:otzaria/semantic_search/repository/semantic_search_repository.dart'; import 'package:otzaria/semantic_search/models/semantic_result_item.dart'; import 'package:otzaria/semantic_search/services/semantic_dwell_binding.dart'; import 'package:otzaria/semantic_search/view/semantic_mode_panel.dart'; @@ -167,14 +168,17 @@ class _SemanticSearchResultsScreenState ...(categories.isEmpty ? scope : categories), ...dimensions, ]; + final coveredBooks = SemanticSearchRepository.instance.lastCoveredBooks; final isOfficialCategory = officialCategoryFilter( context.read().state.library, + coveredBooks: coveredBooks, ); if (!selection.every( (facet) => isSemanticScopeFacetSupported( facet, includeLexical: widget.tab.options.includeLexical, isOfficialCategory: isOfficialCategory, + coveredBooks: coveredBooks, ), )) { UiSnack.showError(SemanticSearchMessages.unsupportedScope); diff --git a/pubspec.yaml b/pubspec.yaml index a09e01169d..ce4270848b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -120,7 +120,7 @@ dependencies: googleapis_auth: ^2.3.7 characters: ^1.4.1 collection: ^1.19.1 - otzaria_search_engine: ^7.2.0 + otzaria_search_engine: ^7.3.0 # חוזה הדיווחים מול השרת, משותף עם "עדכוני אוצריא" (Dart טהור). otzaria_report_contract: path: packages/otzaria_report_contract diff --git a/test/search/scope_tree_test.dart b/test/search/scope_tree_test.dart index c1168c640d..0d7dbf8d9c 100644 --- a/test/search/scope_tree_test.dart +++ b/test/search/scope_tree_test.dart @@ -696,6 +696,16 @@ void main() { isTrue, ); + final covered = ScopeTree.fromLibrary( + library, + ).officialOnly(alsoKeep: {'uid:3', 'db:lib:4'}); + expect(covered.rootNodes.map((n) => n.title), ['תנ״ך', 'אישי', 'מצורף']); + expect(covered.allBookNodes().map((n) => n.title), [ + 'בראשית', + 'עוד', + 'זר', + ]); + final noPersonal = ScopeTree.fromLibrary(library).withoutUserBooks(); expect(noPersonal.rootNodes.map((n) => n.title), ['תנ״ך', 'מצורף']); expect(noPersonal.allBookNodes().map((n) => n.title), ['בראשית', 'זר']); diff --git a/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart b/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart index dba84fd00c..6c13d825ef 100644 --- a/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart +++ b/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart @@ -80,6 +80,18 @@ class _FakeEngine implements SearchEngine { ); } + @override + Future semanticCoveredBooks({ + required String vectorsDir, + required SemanticCancellationToken cancellation, + }) async => SemanticCoveredBooks( + filePaths: ['id:1', 'uid:4774', 'db:zmanenu:12'], + setKey: vectorsDir, + generation: BigInt.from(10), + vectorsLibraryVersion: 39, + recoveredFromPrevious: false, + ); + @override Future openSemanticArtifact({ required SemanticArtifactInput config, @@ -221,6 +233,16 @@ void main() { expect(tokens.single.isDisposed, isTrue); }); + test('coveredBooks מחזיר את מפתחות הספרים מכל המקורות', () async { + final covered = await adapter.coveredBooks( + '/root/vectors', + cancel: SemanticCancelHandle(), + ); + + expect(covered, {'id:1', 'uid:4774', 'db:zmanenu:12'}); + expect(tokens.single.isDisposed, isTrue); + }); + test('SemanticError ממופה לפי סוג', () async { engine.failure = const SemanticError( kind: SemanticErrorKind.insufficientDiskSpace, diff --git a/test/semantic_search/semantic_mode_gate_test.dart b/test/semantic_search/semantic_mode_gate_test.dart index 9e305f9a7b..f13ced5887 100644 --- a/test/semantic_search/semantic_mode_gate_test.dart +++ b/test/semantic_search/semantic_mode_gate_test.dart @@ -274,5 +274,43 @@ void main() { ); expect(officialCategoryFilter(null), isNull); }); + + test('ספרים אישיים ומצורפים שהסט מכסה נתמכים גם בלי התאמה מילולית', () { + final library = Library( + categories: [ + category('תנ״ך', [TextBook(title: 'בראשית')]), + category('אוסף מצורף', [ + TextBook(id: 3, title: 'ספר', source: BookSource.attached('lib')), + ]), + category('ספרים אישיים', [ + TextBook(id: 4, title: 'שלי', source: BookSource.user), + TextBook(id: 5, title: 'אחר', source: BookSource.user), + ]), + ], + ); + const covered = {'db:lib:3', 'uid:4'}; + final filter = officialCategoryFilter(library, coveredBooks: covered); + bool supported(String facet) => isSemanticScopeFacetSupported( + facet, + isOfficialCategory: filter, + coveredBooks: covered, + ); + + expect(supported('/אוסף מצורף'), isTrue); + expect(supported('/אוסף מצורף/db:lib:3'), isTrue); + expect(supported('/ספרים אישיים'), isTrue); + expect(supported('/ספרים אישיים/uid:4'), isTrue); + expect(supported('/ספרים אישיים/uid:5'), isFalse); + expect(supported('/uid:5'), isFalse); + expect(supported('/לא קיים'), isFalse); + expect( + isSemanticScopeFacetSupported( + '/ספרים אישיים', + isOfficialCategory: filter, + ), + isTrue, + ); + expect(isSemanticScopeFacetSupported('/ספרים אישיים'), isFalse); + }); }); } diff --git a/test/semantic_search/semantic_search_bloc_test.dart b/test/semantic_search/semantic_search_bloc_test.dart index af9db10d23..21c0108a34 100644 --- a/test/semantic_search/semantic_search_bloc_test.dart +++ b/test/semantic_search/semantic_search_bloc_test.dart @@ -47,6 +47,35 @@ void main() { expect(bloc.state.availability.phase, SemanticAvailabilityPhase.ready); }); + test('הספרים המכוסים נטענים כשהחיפוש מוכן, ורק כשביקשו אותם', () async { + final backend = FakeBackend()..covered = {'id:1', 'uid:4'}; + final repository = buildRepository( + root: root, + backend: backend, + locator: FakeLocator(releaseV30()), + ); + final settings = SemanticSearchBloc(repository: repository) + ..add(const SemanticSearchStarted()); + addTearDown(settings.close); + final dialog = SemanticSearchBloc( + repository: repository, + loadCoveredBooks: true, + )..add(const SemanticSearchStarted()); + addTearDown(dialog.close); + await waitFor( + () => + dialog.state.availability.phase == + SemanticAvailabilityPhase.needsDownload, + ); + expect(dialog.state.coveredBooks, isEmpty); + + dialog.add(const SemanticDownloadRequested()); + await waitFor(() => dialog.state.coveredBooks.isNotEmpty); + expect(dialog.state.coveredBooks, {'id:1', 'uid:4'}); + expect(settings.state.coveredBooks, isEmpty); + expect(backend.calls.where((c) => c == 'coveredBooks'), hasLength(1)); + }); + test('סגירת הדיאלוג אינה עוצרת הורדה, ופתיחה מחדש מציגה את מצבה', () async { installModelFiles(root); final gate = Completer(); diff --git a/test/semantic_search/semantic_search_dialog_test.dart b/test/semantic_search/semantic_search_dialog_test.dart index 6384f4130e..38b612ba63 100644 --- a/test/semantic_search/semantic_search_dialog_test.dart +++ b/test/semantic_search/semantic_search_dialog_test.dart @@ -93,6 +93,11 @@ class _FakeRepository extends SemanticSearchRepository { @override Future refresh() async => current; + Set covered = const {}; + + @override + Future> coveredBooks() async => covered; + /// הבדיקה הראשונה הסתיימה: המאגר משדר מצב חדש. void emit(SemanticAvailability next) { current = next; diff --git a/test/semantic_search/semantic_search_repository_test.dart b/test/semantic_search/semantic_search_repository_test.dart index 7e181c5b7c..a2b091a389 100644 --- a/test/semantic_search/semantic_search_repository_test.dart +++ b/test/semantic_search/semantic_search_repository_test.dart @@ -1652,4 +1652,47 @@ void main() { expect(repository.availability.pausedByUser, isFalse); }); }); + + group('ספרים מכוסים', () { + test('נשמרים עד שהסט משתנה', () async { + final backend = FakeBackend() + ..vectors = const SemanticVectorsSummary( + present: true, + identityDigest: 'a', + libraryVersion: 39, + ) + ..covered = {'id:1', 'uid:4774'}; + final repository = buildRepository(root: root, backend: backend); + int computed() => backend.calls.where((c) => c == 'coveredBooks').length; + + expect(await repository.coveredBooks(), {'id:1', 'uid:4774'}); + expect(await repository.coveredBooks(), {'id:1', 'uid:4774'}); + expect(computed(), 1); + expect(repository.lastCoveredBooks, {'id:1', 'uid:4774'}); + + backend + ..vectors = const SemanticVectorsSummary( + present: true, + identityDigest: 'a', + libraryVersion: 40, + ) + ..covered = {'id:1'}; + expect(await repository.coveredBooks(), {'id:1'}); + expect(computed(), 2); + }); + + test('בלי סט מותקן או בכשל — ריק', () async { + final backend = FakeBackend()..covered = {'id:1'}; + final repository = buildRepository(root: root, backend: backend); + + expect(await repository.coveredBooks(), isEmpty); + expect(backend.calls, isNot(contains('coveredBooks'))); + + backend.vectorsInfoFailure = const SemanticFailure( + SemanticFailureKind.artifactCorrupt, + 'damaged', + ); + expect(await repository.coveredBooks(), isEmpty); + }); + }); } diff --git a/test/semantic_search/semantic_test_support.dart b/test/semantic_search/semantic_test_support.dart index 39b000bdef..ef7a6364c6 100644 --- a/test/semantic_search/semantic_test_support.dart +++ b/test/semantic_search/semantic_test_support.dart @@ -221,6 +221,18 @@ class FakeBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) async => throw UnimplementedError(); + /// מה ש-[coveredBooks] מחזיר; כל קריאה נרשמת ב-[calls]. + Set covered = const {}; + + @override + Future> coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }) async { + calls.add('coveredBooks'); + return covered; + } + @override Future open(SemanticOpenRequest request) async { calls.add('open');