From 11dcb5f13e3f3ad55f40de630268b64f4e9197d2 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Mon, 16 Nov 2026 22:25:08 +0200 Subject: [PATCH 1/6] =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=97?= =?UTF-8?q?=D7=9B=D7=9D=20=D7=92=D7=9D=20=D7=91=D7=AA=D7=95=D7=9A=20=D7=A1?= =?UTF-8?q?=D7=A4=D7=A8,=20=D7=9C=D7=A4=D7=99=20=D7=94=D7=A1=D7=A4=D7=A8?= =?UTF-8?q?=D7=99=D7=9D=20=D7=A9=D7=99=D7=A9=20=D7=9C=D7=94=D7=9D=20=D7=95?= =?UTF-8?q?=D7=A7=D7=98=D7=95=D7=A8=D7=99=D7=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit החיפוש החכם הוצע עד כה רק לספרי הספרייה הרשמית, ובחיפוש בתוך ספר לא הוצע כלל (#1963). המנוע מחזיר עכשיו את רשימת הספרים שסט הווקטורים מכסה (semanticCoveredBooks), וההחלטה עוברת ממקור הספר לשאלה אם יש לו וקטורים. SemanticSearchRepository מחשב את הרשימה לפי בקשה, אחרי פתיחת ה-session, וקוראים במקביל חולקים חישוב אחד. התשובה נשמרת עד התקנה, איחוד, פתיחה או סגירה של ה-session, או שינוי באינדקס (searchSnapshot). כשה-setKey והאינדקס לא השתנו נשמר אותו סט. כשל או ביטול מחזירים null. בדיקת ההיקף, בורר ההיקף וצמצום התוצאות מקבלים ספר מכוסה וקטגוריה שיש בה ספר מכוסה. כל עוד הרשימה לא ידועה, הם בודקים לפי מקור הספר כמו קודם. בחיפוש המתקדם בתוך ספר טקסט או PDF המצב החכם מוצע כשיש לספר וקטורים. שליחה פותחת כרטיסיית תוצאות בהיקף של הספר בלבד, בלי ההיקף השמור ובלי תחביר @, והדיאלוג מחזיר null. בחירה בתוך ספר אינה משנה את זיכרון המצב החכם בסשן. התלות במנוע עולה ל-^7.3.0, שעוד לא פורסמה. pubspec.lock יעודכן כשהגרסה תפורסם. --- lib/pdf_book/view/pdf_search_screen.dart | 4 + lib/search/utils/scope_tree.dart | 16 + .../view/in_book_advanced_search_dialog.dart | 4 + lib/search/view/search_dialog.dart | 77 +++- lib/search/view/search_scope_menu.dart | 10 +- .../bloc/semantic_search_bloc.dart | 21 +- .../bloc/semantic_search_event.dart | 5 + .../bloc/semantic_search_state.dart | 7 + .../engine/onnx_semantic_engine_adapter.dart | 15 + .../engine/semantic_engine_backend.dart | 12 + .../models/semantic_engine_models.dart | 16 + .../models/semantic_mode_gate.dart | 46 +++ .../semantic_search_repository.dart | 90 ++++- .../view/semantic_mode_panel.dart | 20 +- .../view/semantic_search_results_screen.dart | 9 +- .../view/text_book_search_screen.dart | 7 +- test/search/scope_tree_test.dart | 34 ++ .../in_book_semantic_search_dialog_test.dart | 344 ++++++++++++++++++ .../semantic_covered_books_test.dart | 141 +++++++ .../semantic_mode_gate_test.dart | 69 ++++ .../semantic_search_dialog_test.dart | 3 + .../semantic_test_support.dart | 21 ++ 22 files changed, 945 insertions(+), 26 deletions(-) create mode 100644 test/semantic_search/in_book_semantic_search_dialog_test.dart create mode 100644 test/semantic_search/semantic_covered_books_test.dart diff --git a/lib/pdf_book/view/pdf_search_screen.dart b/lib/pdf_book/view/pdf_search_screen.dart index 041d63d924..4248ae6ac1 100644 --- a/lib/pdf_book/view/pdf_search_screen.dart +++ b/lib/pdf_book/view/pdf_search_screen.dart @@ -1540,6 +1540,10 @@ class PdfBookSearchViewState extends State final result = await showInBookAdvancedSearchDialog( context, bookTitle: widget.bookTitle, + book: switch (pdfBookBloc.state) { + PdfBookLoaded(:final book) => book, + _ => null, + }, query: widget.searchController.text, settings: _settings, ); diff --git a/lib/search/utils/scope_tree.dart b/lib/search/utils/scope_tree.dart index 26860209c4..57f88e8a1a 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'; @@ -177,6 +178,21 @@ class ScopeTree { ScopeTree withoutUserBooks() => _withoutUserBooksCache[this] ??= _pruned((book) => !book.source.isUser); + static final Expando<(Set, ScopeTree)> _coveredOnlyCache = Expando( + 'coveredOnlyScopeTree', + ); + + /// העץ רק עם הספרים שה-filePath שלהם באינדקס ב-[filePaths]. + ScopeTree coveredOnly(Set filePaths) { + final cached = _coveredOnlyCache[this]; + if (cached != null && identical(cached.$1, filePaths)) return cached.$2; + final tree = _pruned( + (book) => filePaths.contains(BookIdentity.indexedFilePath(book)), + ); + _coveredOnlyCache[this] = (filePaths, tree); + return tree; + } + ScopeTree _pruned(bool Function(Book book) keep) { final nodesByFacet = {}; ScopeNode? prune(ScopeNode node) { diff --git a/lib/search/view/in_book_advanced_search_dialog.dart b/lib/search/view/in_book_advanced_search_dialog.dart index 0776c5c290..ead5ff16e5 100644 --- a/lib/search/view/in_book_advanced_search_dialog.dart +++ b/lib/search/view/in_book_advanced_search_dialog.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:otzaria/models/books.dart'; import 'package:otzaria/search/in_book_search_settings.dart'; import 'package:otzaria/search/models/search_configuration.dart'; import 'package:otzaria/search/search_query_builder.dart'; @@ -54,9 +55,11 @@ SearchingTab createInBookSearchDialogTab({ /// פותח חיפוש מתקדם בתוך ספר עם [settings] ומחזיר את ההגדרות שאושרו, או /// null בביטול. הדיאלוג מציג את המדיניות שנבחרה, לא את זו שהותאמה לשאילתה. +/// חיפוש חכם ב-[book] פותח כרטיסיית תוצאות ומחזיר null. Future showInBookAdvancedSearchDialog( BuildContext context, { required String? bookTitle, + Book? book, required String query, required InBookSearchSettings settings, }) async { @@ -77,6 +80,7 @@ Future showInBookAdvancedSearchDialog( existingTab: tab, bookTitle: bookTitle, returnResultOnSubmit: true, + semanticBook: book, ), ); diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index 96033c486e..17a0c4f9e3 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -13,6 +13,8 @@ import 'package:otzaria/widgets/dialogs/app_dialog_frame.dart'; import 'package:otzaria_icons/otzaria_icons.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/core/focus_repository.dart'; +import 'package:otzaria/data/book_identity.dart'; +import 'package:otzaria/models/books.dart'; import 'package:otzaria/core/messages/library_messages.dart'; import 'package:otzaria/core/messages/semantic_search_messages.dart'; import 'package:otzaria/history/bloc/history_bloc.dart'; @@ -153,6 +155,9 @@ class SearchDialog extends StatefulWidget { /// האם מותרת התצוגה המקדימה של פיתוח; ברירת המחדל [kDebugMode]. final bool semanticDebugPreview; + /// בחיפוש בתוך ספר: הספר, שבו מוצע החיפוש החכם כשיש לו וקטורים. + final Book? semanticBook; + const SearchDialog({ super.key, this.existingTab, @@ -166,6 +171,7 @@ class SearchDialog extends StatefulWidget { this.semanticRepository, this.semanticConsent, this.semanticDebugPreview = kDebugMode, + this.semanticBook, }); @override @@ -244,11 +250,12 @@ class _SearchDialogState extends State { /// החיפוש נשלח לכרטיסייה חדשה, ולכן [SearchDialog.existingTab] זמני ומיותר. bool _existingTabHandedOff = false; - /// חיפוש בספרייה, חדש או בעריכה; לא בתוך ספר (issue #1892). + /// חיפוש בספרייה, חדש או בעריכה, או בתוך ספר שנמסר כ-[SearchDialog.semanticBook]. bool get _supportsSemanticMode => - widget.bookTitle == null && - widget.onSearch == null && - !widget.returnResultOnSubmit; + widget.semanticBook != null || + (widget.bookTitle == null && + widget.onSearch == null && + !widget.returnResultOnSubmit); SemanticSearchTab? get _editedSemanticTab => switch (widget.editTab) { final SemanticSearchTab tab => tab, @@ -263,7 +270,18 @@ class _SearchDialogState extends State { isSemanticModeVisible( availability, debug: widget.semanticDebugPreview, - )); + ) && + _semanticBookCovered(availability)); + + /// בתוך ספר המצב מוצע רק כשהחיפוש שמיש ולספר יש וקטורים. + bool _semanticBookCovered(SemanticAvailability availability) { + final book = widget.semanticBook; + if (book == null) return true; + final covered = _semanticBloc?.state.coveredBookFilePaths; + return availability.isUsable && + covered != null && + covered.contains(BookIdentity.indexedFilePath(book)); + } bool get _isSemanticActive => _semanticSelected && _semanticVisible(_semanticBloc?.state.availability); @@ -328,6 +346,9 @@ class _SearchDialogState extends State { repository: widget.semanticRepository ?? SemanticSearchRepository.instance, )..add(const SemanticSearchStarted()); + if (widget.semanticBook != null) { + _semanticBloc!.add(const SemanticCoveredBooksRequested()); + } // מצב מבוקש במפורש (קיצור חיפוש מתקדם, איתור) וכרטיסייה בעריכה // גוברים על זיכרון הסשן. _semanticSelected = @@ -337,6 +358,7 @@ class _SearchDialogState extends State { widget.existingTab == null && widget.editTab == null); if (_semanticSelected) { + _semanticBloc!.add(const SemanticCoveredBooksRequested()); // autofocus אינו בוחר טקסט; מכינים את הבחירה לפני הרכבת השדה, // כדי שבדיקת הזמינות לא תדרוס בחירת סמן מאוחרת יותר. _searchTab.queryController.selection = TextSelection( @@ -1259,6 +1281,11 @@ class _SearchDialogState extends State { )) { return; } + final book = widget.semanticBook; + if (book != null) { + _performInBookSemanticSearch(book); + return; + } final library = _library; final parsedCategory = parseCategoryQuery( _searchTab.queryController.text, @@ -1276,6 +1303,10 @@ class _SearchDialogState extends State { return; } final isOfficialCategory = officialCategoryFilter(library); + final isCoveredFacet = coveredFacetFilter( + library, + _semanticBloc?.state.coveredBookFilePaths, + ); final selection = parsedCategory.categoryFound ? [ ...parsedCategory.facets!, @@ -1287,6 +1318,7 @@ class _SearchDialogState extends State { facet, includeLexical: _semanticIncludeLexical, isOfficialCategory: isOfficialCategory, + isCoveredFacet: isCoveredFacet, ), )) { UiSnack.showError(SemanticSearchMessages.unsupportedScope); @@ -1307,6 +1339,33 @@ class _SearchDialogState extends State { edited.submit(options); return; } + _openSemanticTab(options); + } + + /// ההיקף הוא הספר בלבד: לא ההיקף השמור ולא תחביר @, שהיו מרחיבים אותו. + void _performInBookSemanticSearch(Book book) { + final query = _searchTab.queryController.text.trim(); + if (query.isEmpty) { + UiSnack.show(LibraryMessages.emptySearchQuery); + return; + } + _semanticSubmitted = true; + _openSemanticTab( + SemanticQueryOptions( + query: query, + facets: [ + FacetHelper.buildBookFacet( + FacetHelper.resolveCategoryPath(book), + book, + ), + ], + includeLexical: _semanticIncludeLexical, + groupIdenticalText: _semanticGroupIdentical, + ), + ); + } + + void _openSemanticTab(SemanticQueryOptions options) { final tab = SemanticSearchTab(runOnFirstShow: true, options: options); final tabsBloc = context.read(); final navigationBloc = context.read(); @@ -1349,7 +1408,8 @@ class _SearchDialogState extends State { queryController: _searchTab.queryController, queryFocusNode: _searchTab.searchFieldFocusNode, scopeSelection: _scopeSelection, - onScopeChanged: _onScopeChanged, + onScopeChanged: widget.semanticBook == null ? _onScopeChanged : null, + coveredBookFilePaths: _semanticBloc?.state.coveredBookFilePaths, includeLexical: _semanticIncludeLexical, onIncludeLexicalChanged: (value) { setState(() => _semanticIncludeLexical = value); @@ -1563,8 +1623,11 @@ class _SearchDialogState extends State { void _onModeChoice(_ModeChoice choice) { final mode = choice.mode; - SearchDefaults.rememberSessionSemantic(mode == null); + if (widget.semanticBook == null) { + SearchDefaults.rememberSessionSemantic(mode == null); + } if (mode == null) { + _semanticBloc?.add(const SemanticCoveredBooksRequested()); setState(() => _semanticSelected = true); } else { _semanticSelected = false; diff --git a/lib/search/view/search_scope_menu.dart b/lib/search/view/search_scope_menu.dart index 926604af78..1427b013ef 100644 --- a/lib/search/view/search_scope_menu.dart +++ b/lib/search/view/search_scope_menu.dart @@ -46,8 +46,10 @@ class SearchScopeMenuButton extends StatefulWidget { final Set selected; final ValueChanged> onChanged; - /// מציג רק ספרים מהספרייה הרשמית (בחיפוש החכם — רק להם יש וקטורים). + /// בחיפוש החכם: רק ספרים עם וקטורים ([coveredFilePaths]), ועד שהם ידועים + /// רק ספרים מהספרייה הרשמית. final bool officialBooksOnly; + final Set? coveredFilePaths; /// מסתיר ספרים אישיים כשאינם באינדקס ("בלי ספרים אישיים"). final bool excludeUserBooks; @@ -57,6 +59,7 @@ class SearchScopeMenuButton extends StatefulWidget { required this.selected, required this.onChanged, this.officialBooksOnly = false, + this.coveredFilePaths, this.excludeUserBooks = false, }); @@ -84,7 +87,10 @@ class _SearchScopeMenuButtonState extends State { int _baseBookGeneration = 0; ScopeTree _visibleTree(ScopeTree tree) => widget.officialBooksOnly - ? tree.officialOnly() + ? switch (widget.coveredFilePaths) { + final covered? => tree.coveredOnly(covered), + null => tree.officialOnly(), + } : widget.excludeUserBooks ? tree.withoutUserBooks() : tree; diff --git a/lib/semantic_search/bloc/semantic_search_bloc.dart b/lib/semantic_search/bloc/semantic_search_bloc.dart index 9e055a52d9..38de31b10b 100644 --- a/lib/semantic_search/bloc/semantic_search_bloc.dart +++ b/lib/semantic_search/bloc/semantic_search_bloc.dart @@ -16,6 +16,7 @@ class SemanticSearchBloc extends Bloc { final SemanticSearchRepository repository; StreamSubscription? _subscription; + bool _coverageWanted = false; SemanticSearchBloc({required this.repository}) : super( @@ -49,15 +50,26 @@ 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 _loadCoverageIfWanted(emit); + }); + on((event, emit) async { + _coverageWanted = true; + await _loadCoverageIfWanted(emit); + }); + } + + Future _loadCoverageIfWanted(Emitter emit) async { + if (!_coverageWanted || !state.availability.isUsable) return; + final covered = await repository.loadCoveredBookFilePaths(); + if (covered != null) emit(state.copyWith(coveredBookFilePaths: covered)); } Future _onStarted( @@ -69,6 +81,7 @@ class SemanticSearchBloc ); final availability = await repository.refresh(); emit(state.copyWith(availability: availability)); + await _loadCoverageIfWanted(emit); } Future _onQuantizationChanged( diff --git a/lib/semantic_search/bloc/semantic_search_event.dart b/lib/semantic_search/bloc/semantic_search_event.dart index 77c7346670..b132404f0e 100644 --- a/lib/semantic_search/bloc/semantic_search_event.dart +++ b/lib/semantic_search/bloc/semantic_search_event.dart @@ -68,3 +68,8 @@ class SemanticModelChoiceChanged extends SemanticSearchEvent { @override List get props => [modelChoice]; } + +/// הממשק צריך את הספרים שיש להם וקטורים; נטענים כשהחיפוש החכם שמיש. +class SemanticCoveredBooksRequested extends SemanticSearchEvent { + const SemanticCoveredBooksRequested(); +} diff --git a/lib/semantic_search/bloc/semantic_search_state.dart b/lib/semantic_search/bloc/semantic_search_state.dart index 109da3b371..8053d6f900 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; + /// ה-filePath באינדקס של הספרים שיש להם וקטורים; `null` = לא ידוע. + final Set? coveredBookFilePaths; + const SemanticSearchState({ this.availability = SemanticAvailability.initial, this.quantization = SemanticQuantization.int8, this.modelChoice = SemanticModelChoice.meivin, this.activeModelChoice = SemanticModelChoice.meivin, this.isRemoving = false, + this.coveredBookFilePaths, }); SemanticSearchState copyWith({ @@ -24,12 +28,14 @@ class SemanticSearchState extends Equatable { SemanticModelChoice? modelChoice, SemanticModelChoice? activeModelChoice, bool? isRemoving, + Set? coveredBookFilePaths, }) => SemanticSearchState( availability: availability ?? this.availability, quantization: quantization ?? this.quantization, modelChoice: modelChoice ?? this.modelChoice, activeModelChoice: activeModelChoice ?? this.activeModelChoice, isRemoving: isRemoving ?? this.isRemoving, + coveredBookFilePaths: coveredBookFilePaths ?? this.coveredBookFilePaths, ); @override @@ -39,5 +45,6 @@ class SemanticSearchState extends Equatable { modelChoice, activeModelChoice, isRemoving, + coveredBookFilePaths, ]; } diff --git a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart index 970332633a..598df2ea02 100644 --- a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart +++ b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart @@ -87,6 +87,21 @@ 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 SemanticCoveredBooksSummary( + filePaths: covered.filePaths, + setKey: covered.setKey, + ); + }); + @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..fe610d0747 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, }); + /// הספרים באינדקס הפתוח שיש להם וקטורים בסט; מעבר על כל האינדקס. + 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_engine_models.dart b/lib/semantic_search/models/semantic_engine_models.dart index f51e9c214c..7050fcec94 100644 --- a/lib/semantic_search/models/semantic_engine_models.dart +++ b/lib/semantic_search/models/semantic_engine_models.dart @@ -223,6 +223,22 @@ class SemanticCoverageSummary extends Equatable { ]; } +/// הספרים שהסט מכסה (`semanticCoveredBooks`), לפי ה-filePath שלהם באינדקס. +class SemanticCoveredBooksSummary extends Equatable { + final List filePaths; + + /// משתנה בכל שינוי במה שהסט מגיש; להשוואה בלבד. + final String setKey; + + const SemanticCoveredBooksSummary({ + required this.filePaths, + required this.setKey, + }); + + @override + List get props => [filePaths, setKey]; +} + /// בקשת פתיחה של סט הוקטורים והמודל (`openSemanticArtifact`). class SemanticOpenRequest extends Equatable { final String vectorsDir; diff --git a/lib/semantic_search/models/semantic_mode_gate.dart b/lib/semantic_search/models/semantic_mode_gate.dart index f8b23fcffa..da0c3ee397 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'; @@ -56,10 +57,12 @@ bool isSemanticScopeFacetSupported( String facet, { bool includeLexical = false, bool Function(String facet)? isOfficialCategory, + bool Function(String facet)? isCoveredFacet, }) { if (includeLexical || facet == '/' || FacetHelper.isDimensionFacet(facet)) { return true; } + if (isCoveredFacet != null) return isCoveredFacet(facet); if (BookDatabaseResolver.likelySource(categoryPath: facet) != BookSource.official) { return false; @@ -92,3 +95,46 @@ bool Function(String facet)? officialCategoryFilter(Library? library) { bool _hasOfficialBook(Category category) => category.books.any((book) => book.source.isOfficial) || category.subCategories.any(_hasOfficialBook); + +final Expando<(Set, Set)> _coveredFacetsCache = Expando(); + +/// האם ל-facet של ספר יש וקטורים, או שבקטגוריה יש ספר כזה; `null` כשהספרייה +/// או הספרים המכוסים ([coveredFilePaths], לפי filePath באינדקס) לא ידועים. +bool Function(String facet)? coveredFacetFilter( + Library? library, + Set? coveredFilePaths, +) { + if (library == null || coveredFilePaths == null) return null; + final cached = _coveredFacetsCache[library]; + final facets = cached != null && identical(cached.$1, coveredFilePaths) + ? cached.$2 + : _coveredFacets(library, coveredFilePaths); + _coveredFacetsCache[library] = (coveredFilePaths, facets); + return facets.contains; +} + +Set _coveredFacets(Library library, Set coveredFilePaths) { + final facets = {}; + bool visit(Category category) { + var covered = false; + for (final book in category.books) { + if (coveredFilePaths.contains(BookIdentity.indexedFilePath(book))) { + facets.add( + FacetHelper.buildBookFacet( + FacetHelper.resolveCategoryPath(book), + book, + ), + ); + covered = true; + } + } + for (final child in category.subCategories) { + if (visit(child)) covered = true; + } + if (covered) facets.add(FacetHelper.categoryFacet(category)); + return covered; + } + + visit(library); + return facets; +} diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index 9e0790bd07..23f5534982 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -9,6 +9,7 @@ import 'package:flutter/services.dart' show rootBundle; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:http/http.dart' as http; import 'package:otzaria/data/constants/database_constants.dart'; +import 'package:otzaria/data/data_providers/tantivy_data_provider.dart'; import 'package:otzaria/library_update/services/companion_assets_service.dart'; import 'package:otzaria/library_update/services/github_rate_limit.dart'; import 'package:otzaria/search/search_engine_gateway.dart' @@ -86,8 +87,10 @@ class SemanticSearchRepository { bool Function()? isPlatformSupported, Future Function(String path)? diskSpace, Map? modelReleases, + Future Function()? indexStamp, this._busyRetryDelay = const Duration(minutes: 2), - }) : _backend = backend ?? createSemanticEngineBackend(), + }) : _indexStamp = indexStamp ?? _defaultIndexStamp, + _backend = backend ?? createSemanticEngineBackend(), _consentFactory = consent ?? (() => SearchFeedbackService.instance), _settings = settings ?? const SettingsSemanticSettingsStore(), _basePaths = paths ?? _defaultPaths, @@ -131,6 +134,7 @@ class SemanticSearchRepository { final String? Function() _onnxRuntimePath; final bool Function() _isPlatformSupported; final Future Function(String path) _diskSpace; + final Future Function() _indexStamp; final Map? _modelReleaseOverrides; @@ -250,6 +254,10 @@ class SemanticSearchRepository { SemanticQuantization? _openQuantization; final SemanticSearchSession _defaultSession = SemanticSearchSession(); final Set _activeSearches = {}; + _CoveredBooks? _covered; + bool _coveredValid = false; + int _coveredEpoch = 0; + Future?>? _coveredJob; /// המצב האחרון שחושב. SemanticAvailability get availability => _availability; @@ -543,6 +551,65 @@ class SemanticSearchRepository { cancel: cancel ?? SemanticCancelHandle(), ); + /// ה-filePath באינדקס של הספרים שיש להם וקטורים, כפי שחושב לאחרונה; + /// `null` כשעוד לא חושב או כשהסט או האינדקס השתנו מאז. + Set? get coveredBookFilePaths => + _coveredValid ? _covered?.filePaths : null; + + /// מחשב את [coveredBookFilePaths] כשצריך, אחרי פתיחת ה-session; קוראים + /// במקביל חולקים חישוב אחד. כשל או ביטול מחזירים `null`. + Future?> loadCoveredBookFilePaths() => + _coveredJob ??= _loadCovered().whenComplete(() => _coveredJob = null); + + Future?> _loadCovered() async { + final cancel = SemanticCancelHandle(); + _activeSearches.add(cancel); + try { + await ensureOpen(); + // סט או אינדקס שהשתנו באמצע החישוב מחייבים חישוב נוסף. + for (var attempt = 0; attempt < 2 && !cancel.isCancelled; attempt++) { + final epoch = _coveredEpoch; + final stamp = await _indexStamp(); + final previous = _covered; + if (_coveredValid && previous?.indexStamp == stamp) { + return previous!.filePaths; + } + final answer = await _backend.coveredBooks( + (await _paths()).vectorsDirectory, + cancel: cancel, + ); + if (epoch != _coveredEpoch) continue; + final unchanged = + previous != null && + previous.setKey == answer.setKey && + previous.indexStamp == stamp; + _covered = unchanged + ? previous + : _CoveredBooks( + setKey: answer.setKey, + indexStamp: stamp, + filePaths: Set.unmodifiable(answer.filePaths), + ); + _coveredValid = true; + return _covered!.filePaths; + } + return null; + } catch (error, stackTrace) { + if (error is! SemanticFailure || + error.kind != SemanticFailureKind.cancelled) { + _log('coveredBooks', error, stackTrace); + } + return null; + } finally { + _activeSearches.remove(cancel); + } + } + + void _invalidateCoveredBooks() { + _coveredEpoch++; + _coveredValid = false; + } + /// תמונת המנוע לטלמטריה: מצב, זהות המודל, החבילה והוקטורים המותקנים. Future engineSnapshot() async { final status = await _safeStatus(); @@ -751,6 +818,7 @@ class SemanticSearchRepository { throw const SemanticFailure(SemanticFailureKind.cancelled); } _openQuantization = quantization; + _invalidateCoveredBooks(); unawaited(_warmUp()); } @@ -779,6 +847,7 @@ class SemanticSearchRepository { bool invalidateOpening = true, }) async { if (invalidateOpening) _lifecycleEpoch++; + _invalidateCoveredBooks(); final wasOpen = _openQuantization != null; _openQuantization = null; _passageModelVerification = null; @@ -1429,6 +1498,7 @@ class SemanticSearchRepository { } _needsRepair = false; if (repair) _lastFailure = null; + _invalidateCoveredBooks(); _vectors = await _backend.vectorsInfo(paths.vectorsDirectory); return true; } @@ -1450,6 +1520,7 @@ class SemanticSearchRepository { // גרסת המסד אינה מוכיחה שהאינדקס מלא ועדכני; בלי גרסת אינדקס מאומתת // מאחדים בלי לנפות רשומות מול האינדקס, שעשוי להיות חלקי. await _backend.compactVectors(dir, cancel: cancel); + _invalidateCoveredBooks(); if (!cancel.isCancelled) _vectors = await _backend.vectorsInfo(dir); } on SemanticFailure catch (failure) { if (failure.kind == SemanticFailureKind.vectorsBusy) { @@ -1941,6 +2012,10 @@ class SemanticSearchRepository { ); } + /// משתנה בכל שינוי בתוכן האינדקס הלקסיקלי, שגם בו תלוי הכיסוי. + static Future _defaultIndexStamp() async => + (await TantivyDataProvider.instance.engine).searchSnapshot(); + static Future _defaultLibraryVersion() async => int.tryParse(await DataCollectionService().readLibraryVersion()); @@ -1949,6 +2024,19 @@ class SemanticSearchRepository { } } +/// תשובת הכיסוי האחרונה, והמצב של הסט והאינדקס שהיא נכונה להם. +class _CoveredBooks { + const _CoveredBooks({ + required this.setKey, + required this.indexStamp, + required this.filePaths, + }); + + final String setKey; + final String indexStamp; + final Set filePaths; +} + /// release של רכיב החיפוש והקבצים ממנו שחסרים במכשיר. typedef _ModelPlan = ({ SemanticModelRelease release, diff --git a/lib/semantic_search/view/semantic_mode_panel.dart b/lib/semantic_search/view/semantic_mode_panel.dart index b0d6040262..65db61f0f8 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.coveredBookFilePaths, required this.includeLexical, required this.onIncludeLexicalChanged, required this.groupIdenticalText, @@ -45,7 +46,10 @@ class SemanticModePanel extends StatelessWidget { /// פעולה בסוף שדה השאילתה (היסטוריית החיפושים). final Widget? queryTrailingAction; final Set scopeSelection; - final ValueChanged> onScopeChanged; + + /// `null` בחיפוש בתוך ספר, שבו ההיקף הוא הספר ואין בורר. + final ValueChanged>? onScopeChanged; + final Set? coveredBookFilePaths; final bool includeLexical; final ValueChanged onIncludeLexicalChanged; final bool groupIdenticalText; @@ -328,12 +332,14 @@ class SemanticModePanel extends StatelessWidget { runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: [ - SearchScopeMenuButton( - key: ValueKey(includeLexical), - selected: scopeSelection, - officialBooksOnly: !includeLexical, - onChanged: onScopeChanged, - ), + if (onScopeChanged case final onScopeChanged?) + SearchScopeMenuButton( + key: ValueKey((includeLexical, coveredBookFilePaths)), + selected: scopeSelection, + officialBooksOnly: !includeLexical, + coveredFilePaths: coveredBookFilePaths, + onChanged: onScopeChanged, + ), FilterChip( key: const ValueKey('semantic-include-lexical'), label: Text(context.settingsText('שלב גם התאמה מילולית')), diff --git a/lib/semantic_search/view/semantic_search_results_screen.dart b/lib/semantic_search/view/semantic_search_results_screen.dart index 78a6afcf17..0c719fa064 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,18 @@ class _SemanticSearchResultsScreenState ...(categories.isEmpty ? scope : categories), ...dimensions, ]; - final isOfficialCategory = officialCategoryFilter( - context.read().state.library, + final library = context.read().state.library; + final isOfficialCategory = officialCategoryFilter(library); + final isCoveredFacet = coveredFacetFilter( + library, + SemanticSearchRepository.instance.coveredBookFilePaths, ); if (!selection.every( (facet) => isSemanticScopeFacetSupported( facet, includeLexical: widget.tab.options.includeLexical, isOfficialCategory: isOfficialCategory, + isCoveredFacet: isCoveredFacet, ), )) { UiSnack.showError(SemanticSearchMessages.unsupportedScope); diff --git a/lib/text_book/view/text_book_search_screen.dart b/lib/text_book/view/text_book_search_screen.dart index a7f8c15839..5077e3c467 100644 --- a/lib/text_book/view/text_book_search_screen.dart +++ b/lib/text_book/view/text_book_search_screen.dart @@ -1280,12 +1280,13 @@ class TextBookSearchViewState extends State onArrowDown: () => _moveBetweenResults(1), onArrowUp: () => _moveBetweenResults(-1), onAdvancedSearch: () async { - final bookTitle = - (context.read().state as TextBookLoaded).book.title; + final book = + (context.read().state as TextBookLoaded).book; final result = await showInBookAdvancedSearchDialog( context, - bookTitle: bookTitle, + bookTitle: book.title, + book: book, query: searchTextController.text, settings: _settings, ); diff --git a/test/search/scope_tree_test.dart b/test/search/scope_tree_test.dart index c1168c640d..5b6c16f99c 100644 --- a/test/search/scope_tree_test.dart +++ b/test/search/scope_tree_test.dart @@ -701,4 +701,38 @@ void main() { expect(noPersonal.allBookNodes().map((n) => n.title), ['בראשית', 'זר']); expect(noPersonal.nodesByFacet.containsKey('/אישי'), isFalse); }); + + test('coveredOnly משאיר רק ספרים עם וקטורים, מכל מקור (issue #1963)', () { + Category cat(String title, List books) => Category( + title: title, + description: '', + shortDescription: '', + order: 10, + subCategories: [], + books: books, + parent: null, + ); + final library = Library( + categories: [ + cat('תנ״ך', [ + TextBook(id: 1, title: 'בראשית'), + TextBook(id: 2, title: 'שמות'), + ]), + cat('אישי', [TextBook(id: 3, title: 'עוד', source: BookSource.user)]), + ], + ); + final covered = {'id:1', 'uid:3'}; + final tree = ScopeTree.fromLibrary(library).coveredOnly(covered); + expect(tree.allBookNodes().map((n) => n.title), ['בראשית', 'עוד']); + expect( + identical(tree, ScopeTree.fromLibrary(library).coveredOnly(covered)), + isTrue, + ); + expect( + ScopeTree.fromLibrary( + library, + ).coveredOnly({'id:2'}).allBookNodes().map((n) => n.title), + ['שמות'], + ); + }); } diff --git a/test/semantic_search/in_book_semantic_search_dialog_test.dart b/test/semantic_search/in_book_semantic_search_dialog_test.dart new file mode 100644 index 0000000000..108a417387 --- /dev/null +++ b/test/semantic_search/in_book_semantic_search_dialog_test.dart @@ -0,0 +1,344 @@ +import 'dart:async'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:mocktail/mocktail.dart'; +import 'package:otzaria/core/ui_snack.dart'; +import 'package:otzaria/data/book_identity.dart'; +import 'package:otzaria/history/bloc/history_bloc.dart'; +import 'package:otzaria/history/bloc/history_event.dart'; +import 'package:otzaria/history/bloc/history_state.dart'; +import 'package:otzaria/indexing/bloc/indexing_bloc.dart'; +import 'package:otzaria/indexing/bloc/indexing_event.dart'; +import 'package:otzaria/indexing/bloc/indexing_state.dart'; +import 'package:otzaria/library/bloc/library_bloc.dart'; +import 'package:otzaria/library/bloc/library_event.dart'; +import 'package:otzaria/library/bloc/library_state.dart'; +import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/navigation/bloc/navigation_bloc.dart'; +import 'package:otzaria/navigation/bloc/navigation_event.dart'; +import 'package:otzaria/navigation/bloc/navigation_state.dart'; +import 'package:otzaria/search/in_book_search_settings.dart'; +import 'package:otzaria/search/search_defaults.dart'; +import 'package:otzaria/search/search_scope_preferences.dart'; +import 'package:otzaria/search/utils/facet_helper.dart'; +import 'package:otzaria/search/view/in_book_advanced_search_dialog.dart'; +import 'package:otzaria/search/view/search_dialog.dart'; +import 'package:otzaria/search/view/search_scope_menu.dart'; +import 'package:otzaria/semantic_search/models/semantic_availability.dart'; +import 'package:otzaria/semantic_search/repository/semantic_search_repository.dart'; +import 'package:otzaria/settings/engine/app_settings_store.dart'; +import 'package:otzaria/tabs/bloc/tabs_bloc.dart'; +import 'package:otzaria/tabs/bloc/tabs_event.dart'; +import 'package:otzaria/tabs/bloc/tabs_state.dart'; +import 'package:otzaria/tabs/models/semantic_search_tab.dart'; + +import '../test_helpers/memory_cache_provider.dart'; +import 'semantic_test_support.dart'; + +class _MockHistoryBloc extends MockBloc + implements HistoryBloc {} + +class _MockIndexingBloc extends MockBloc + implements IndexingBloc {} + +class _MockNavigationBloc extends MockBloc + implements NavigationBloc {} + +class _MockLibraryBloc extends MockBloc + implements LibraryBloc {} + +class _MockTabsBloc extends MockBloc + implements TabsBloc {} + +class _FakeTabsEvent extends Fake implements TabsEvent {} + +class _FakeNavigationEvent extends Fake implements NavigationEvent {} + +/// מאגר מוכן לחיפוש, שהספרים המכוסים שלו נקבעים בבדיקה. +class _CoveredRepository extends SemanticSearchRepository { + _CoveredRepository(this.covered) + : super( + backend: FakeBackend(), + consent: () => FakeConsentStore(), + settings: FakeSettingsStore(), + ); + + final Set? covered; + static const _ready = SemanticAvailability( + phase: SemanticAvailabilityPhase.ready, + consentGranted: true, + ); + + @override + SemanticAvailability get availability => _ready; + + @override + Stream get availabilityChanges => const Stream.empty(); + + @override + Future refresh() async => _ready; + + @override + Future?> loadCoveredBookFilePaths() async => covered; +} + +final _semanticSegment = find.byKey( + const ValueKey('search-dialog-semantic-mode'), +); +final _queryField = find.byKey(const ValueKey('semantic-query-field')); + +void main() { + final book = TextBook(title: 'בראשית', id: 1); + final library = Library( + categories: [ + Category( + title: 'תנ״ך', + description: '', + shortDescription: '', + order: 1, + subCategories: [], + books: [ + book, + TextBook(title: 'שמות', id: 2), + ], + parent: null, + ), + ], + ); + final bookFacet = FacetHelper.buildBookFacet( + FacetHelper.resolveCategoryPath(book), + book, + ); + final coveredBook = {BookIdentity.indexedFilePath(book)}; + + setUpAll(() { + registerFallbackValue(_FakeTabsEvent()); + registerFallbackValue(_FakeNavigationEvent()); + }); + + setUp(() async { + await Settings.init(cacheProvider: MemoryCacheProvider()); + SearchDefaults.rememberSessionSemantic(false); + }); + + tearDown(UiSnack.hide); + + Future< + ({ + _MockTabsBloc tabs, + _MockNavigationBloc navigation, + List results, + }) + > + pumpInBookDialog( + WidgetTester tester, + Set? covered, { + bool inBook = true, + }) async { + final history = _MockHistoryBloc(); + final indexing = _MockIndexingBloc(); + final navigation = _MockNavigationBloc(); + final libraryBloc = _MockLibraryBloc(); + final tabs = _MockTabsBloc(); + whenListen( + history, + const Stream.empty(), + initialState: HistoryLoaded([]), + ); + whenListen( + indexing, + const Stream.empty(), + initialState: IndexingInitial(), + ); + whenListen( + navigation, + const Stream.empty(), + initialState: const NavigationState(currentScreen: Screen.reading), + ); + whenListen( + libraryBloc, + const Stream.empty(), + initialState: LibraryState(library: library), + ); + whenListen( + tabs, + const Stream.empty(), + initialState: const TabsState(tabs: [], currentTabIndex: 0), + ); + addTearDown(() async { + await history.close(); + await indexing.close(); + await navigation.close(); + await libraryBloc.close(); + await tabs.close(); + }); + + const settings = InBookSearchSettings(); + final tab = createInBookSearchDialogTab( + query: '', + searchMode: settings.searchMode, + distance: settings.distance, + matchPolicy: settings.requestedMatchPolicy, + searchOptions: settings.searchOptions, + alternativeWords: settings.alternativeWords, + spacingValues: settings.spacingValues, + ); + addTearDown(tab.dispose); + final results = []; + final repository = _CoveredRepository(covered); + + await tester.pumpWidget( + MultiBlocProvider( + providers: [ + BlocProvider.value(value: history), + BlocProvider.value(value: indexing), + BlocProvider.value(value: navigation), + BlocProvider.value(value: libraryBloc), + BlocProvider.value(value: tabs), + ], + child: MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => GestureDetector( + key: const ValueKey('launch'), + behavior: HitTestBehavior.opaque, + onTap: () async => results.add( + await showDialog( + context: context, + builder: (_) => MediaQuery( + data: const MediaQueryData(size: Size(1280, 900)), + child: inBook + ? SearchDialog( + existingTab: tab, + bookTitle: book.title, + returnResultOnSubmit: true, + semanticBook: book, + semanticRepository: repository, + semanticDebugPreview: false, + ) + : SearchDialog( + semanticRepository: repository, + semanticDebugPreview: false, + ), + ), + ), + ), + child: const SizedBox(width: 40, height: 40), + ), + ), + ), + ), + ), + ); + await tester.tap(find.byKey(const ValueKey('launch'))); + await tester.pumpAndSettle(); + return (tabs: tabs, navigation: navigation, results: results); + } + + testWidgets('ספר עם וקטורים: המצב החכם מוצע, אבל לא נבחר מעצמו', ( + tester, + ) async { + SearchDefaults.rememberSessionSemantic(true); + await pumpInBookDialog(tester, coveredBook); + expect(_semanticSegment, findsOneWidget); + expect(_queryField, findsNothing); + }); + + testWidgets('ספר בלי וקטורים: אין מצב חכם, גם כשהסשן זוכר חכם', ( + tester, + ) async { + SearchDefaults.rememberSessionSemantic(true); + await pumpInBookDialog(tester, {'id:2'}); + expect(_semanticSegment, findsNothing); + expect(_queryField, findsNothing); + }); + + testWidgets('כיסוי לא ידוע: אין מצב חכם', (tester) async { + await pumpInBookDialog(tester, null); + expect(_semanticSegment, findsNothing); + }); + + testWidgets('שליחה פותחת כרטיסייה בספר בלבד, גם כשנשמר היקף רחב', ( + tester, + ) async { + await SearchScopePreferences.save( + searchAllCategories: true, + manualFacets: const {}, + ); + await SearchScopePreferences.saveDimensionFacets({'/base'}); + final harness = await pumpInBookDialog(tester, coveredBook); + + await tester.tap(_semanticSegment); + await tester.pumpAndSettle(); + expect(find.byType(SearchScopeMenuButton), findsNothing); + await tester.enterText(_queryField, 'בריאת העולם'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pumpAndSettle(); + + final added = verify( + () => harness.tabs.add(captureAny()), + ).captured.whereType().single; + final tab = added.tab as SemanticSearchTab; + addTearDown(tab.dispose); + expect(tab.options.query, 'בריאת העולם'); + expect(tab.options.facets, [bookFacet]); + verify( + () => harness.navigation.add(const NavigateToScreen(Screen.search)), + ).called(1); + expect(harness.results, [null]); + expect(SearchDefaults.initialSemanticForNewSearch(), isFalse); + }); + + group('חיפוש בספרייה לפי ספרים עם וקטורים', () { + Future<_MockTabsBloc> submitScope( + WidgetTester tester, + Set scope, + ) async { + SearchDefaults.rememberSessionSemantic(true); + final harness = await pumpInBookDialog(tester, { + ...coveredBook, + 'id:9', + }, inBook: false); + final picker = tester.widget( + find.byType(SearchScopeMenuButton), + ); + if (picker.officialBooksOnly == false) { + await tester.tap( + find.byKey(const ValueKey('semantic-include-lexical')), + ); + await tester.pumpAndSettle(); + } + final narrowed = tester.widget( + find.byType(SearchScopeMenuButton), + ); + expect(narrowed.officialBooksOnly, isTrue); + expect(narrowed.coveredFilePaths, {...coveredBook, 'id:9'}); + narrowed.onChanged(scope); + await tester.pumpAndSettle(); + await tester.enterText(_queryField, 'שאלה'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pumpAndSettle(); + return harness.tabs; + } + + testWidgets('ספר רשמי בלי וקטורים אינו נשלח', (tester) async { + final tabs = await submitScope(tester, {'/תנ״ך/id:2'}); + verifyNever(() => tabs.add(any())); + }); + + testWidgets('ספר מכוסה נשלח', (tester) async { + final tabs = await submitScope(tester, {bookFacet}); + final tab = + verify( + () => tabs.add(captureAny()), + ).captured.whereType().single.tab + as SemanticSearchTab; + addTearDown(tab.dispose); + expect(tab.options.facets, [bookFacet]); + }); + }); +} diff --git a/test/semantic_search/semantic_covered_books_test.dart b/test/semantic_search/semantic_covered_books_test.dart new file mode 100644 index 0000000000..872b510a78 --- /dev/null +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -0,0 +1,141 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; + +import 'semantic_test_support.dart'; + +void main() { + late Directory root; + setUp(() => root = Directory.systemTemp.createTempSync('semantic_covered_')); + tearDown(() async { + if (root.existsSync()) await root.delete(recursive: true); + }); + + SemanticCoveredBooksSummary answer(String setKey, List paths) => + SemanticCoveredBooksSummary(filePaths: paths, setKey: setKey); + + int computations(FakeBackend backend) => + backend.calls.where((call) => call == 'coveredBooks').length; + + test('חישוב אחד לקוראים במקביל, ונשמר עד שמשהו משתנה', () async { + installModelFiles(root); + final gate = Completer(); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1', 'id:2']) + ..coveredBooksGate = gate; + final repo = buildRepository(root: root, backend: backend); + + expect(repo.coveredBookFilePaths, isNull); + final first = repo.loadCoveredBookFilePaths(); + final second = repo.loadCoveredBookFilePaths(); + await waitFor(() => computations(backend) == 1); + gate.complete(); + backend.coveredBooksGate = null; + + expect(await first, {'id:1', 'id:2'}); + expect(identical(await first, await second), isTrue); + expect(await repo.loadCoveredBookFilePaths(), {'id:1', 'id:2'}); + expect(computations(backend), 1); + expect(repo.coveredBookFilePaths, {'id:1', 'id:2'}); + expect(backend.calls, contains('open')); + }); + + test('שינוי באינדקס הלקסיקלי מחשב מחדש', () async { + installModelFiles(root); + var stamp = 'index-1'; + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository( + root: root, + backend: backend, + indexStamp: () async => stamp, + ); + + expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); + stamp = 'index-2'; + backend.coveredBooksValue = answer('set-1', ['id:1', 'uid:7']); + + expect(await repo.loadCoveredBookFilePaths(), {'id:1', 'uid:7'}); + expect(computations(backend), 2); + }); + + test('התקנת וקטורים מבטלת את התשובה; אותו setKey שומר על אותו סט', () async { + installModelFiles(root); + final backend = FakeBackend() + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository( + root: root, + backend: backend, + locator: FakeLocator(releaseV30()), + ); + await repo.enableAndDownload(); + final before = await repo.loadCoveredBookFilePaths(); + expect(before, {'id:1'}); + + backend.vectors = SemanticVectorsSummary.absent; + await repo.enableAndDownload(); + expect(repo.coveredBookFilePaths, isNull); + + final same = await repo.loadCoveredBookFilePaths(); + expect(computations(backend), 2); + expect(identical(same, before), isTrue); + + backend.vectors = SemanticVectorsSummary.absent; + await repo.enableAndDownload(); + backend.coveredBooksValue = answer('set-2', ['id:1', 'id:3']); + expect(await repo.loadCoveredBookFilePaths(), {'id:1', 'id:3'}); + }); + + test('סגירת ה-session (העברת ספרייה) מבטלת את התשובה', () async { + installModelFiles(root); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository(root: root, backend: backend); + await repo.loadCoveredBookFilePaths(); + + await repo.releaseForLibraryMove(); + expect(repo.coveredBookFilePaths, isNull); + expect(await repo.loadCoveredBookFilePaths(), isNull); + repo.finishLibraryMove(); + + expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); + expect(computations(backend), 2); + }); + + test('כשל במנוע או בלי וקטורים — null', () async { + installModelFiles(root); + final backend = FakeBackend()..vectors = installedV30; + final repo = buildRepository(root: root, backend: backend); + expect(await repo.loadCoveredBookFilePaths(), isNull); + expect(repo.coveredBookFilePaths, isNull); + + final empty = buildRepository( + root: Directory('${root.path}/empty')..createSync(), + backend: FakeBackend(), + ); + expect(await empty.loadCoveredBookFilePaths(), isNull); + }); + + test('ביטול באמצע (העברת ספרייה) מחזיר null ולא שומר תשובה', () async { + installModelFiles(root); + final gate = Completer(); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']) + ..coveredBooksGate = gate; + final repo = buildRepository(root: root, backend: backend); + final loading = repo.loadCoveredBookFilePaths(); + await waitFor(() => computations(backend) == 1); + final moving = repo.releaseForLibraryMove(); + await Future.delayed(const Duration(milliseconds: 50)); + gate.complete(); + await moving; + expect(await loading, isNull); + expect(repo.coveredBookFilePaths, isNull); + }); +} diff --git a/test/semantic_search/semantic_mode_gate_test.dart b/test/semantic_search/semantic_mode_gate_test.dart index 9e305f9a7b..555222a937 100644 --- a/test/semantic_search/semantic_mode_gate_test.dart +++ b/test/semantic_search/semantic_mode_gate_test.dart @@ -1,5 +1,7 @@ import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/data/book_identity.dart'; import 'package:otzaria/library/models/library.dart'; +import 'package:otzaria/search/utils/facet_helper.dart'; import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/models/books.dart'; import 'package:otzaria/search_feedback/search_feedback_api.dart'; @@ -275,4 +277,71 @@ void main() { expect(officialCategoryFilter(null), isNull); }); }); + + group('היקף לפי ספרים עם וקטורים (issue #1963)', () { + final official = TextBook(title: 'בראשית', id: 1); + final uncovered = TextBook(title: 'שמות', id: 2); + final personal = TextBook(title: 'חידושים', source: BookSource.user, id: 3); + late Library library; + + setUp(() { + library = Library( + categories: [ + Category( + title: 'תנ״ך', + description: '', + shortDescription: '', + order: 1, + subCategories: [], + books: [official, uncovered], + parent: null, + ), + Category( + title: 'אישי', + description: '', + shortDescription: '', + order: 2, + subCategories: [], + books: [personal], + parent: null, + ), + ], + ); + }); + + String facetOf(Book book) => + FacetHelper.buildBookFacet(FacetHelper.resolveCategoryPath(book), book); + + bool supported(String facet, Set? covered) => + isSemanticScopeFacetSupported( + facet, + isOfficialCategory: officialCategoryFilter(library), + isCoveredFacet: coveredFacetFilter(library, covered), + ); + + test('ספר מכוסה נתמך גם כשאינו רשמי; ספר רשמי בלי וקטורים לא', () { + final covered = { + BookIdentity.indexedFilePath(official), + BookIdentity.indexedFilePath(personal), + }; + expect(supported(facetOf(official), covered), isTrue); + expect(supported(facetOf(personal), covered), isTrue); + expect(supported(facetOf(uncovered), covered), isFalse); + }); + + test('קטגוריה נתמכת רק כשיש בה ספר מכוסה', () { + final covered = {BookIdentity.indexedFilePath(personal)}; + expect(supported('/אישי', covered), isTrue); + expect(supported('/תנ״ך', covered), isFalse); + expect(supported('/', covered), isTrue); + }); + + test('כשהכיסוי לא ידוע — לפי מקור הספר כמו קודם', () { + expect(coveredFacetFilter(library, null), isNull); + expect(coveredFacetFilter(null, const {}), isNull); + expect(supported(facetOf(uncovered), null), isTrue); + expect(supported(facetOf(personal), null), isFalse); + expect(supported('/אישי', null), isFalse); + }); + }); } diff --git a/test/semantic_search/semantic_search_dialog_test.dart b/test/semantic_search/semantic_search_dialog_test.dart index 8dc13ccc29..ebd65f9550 100644 --- a/test/semantic_search/semantic_search_dialog_test.dart +++ b/test/semantic_search/semantic_search_dialog_test.dart @@ -104,6 +104,9 @@ class _FakeRepository extends SemanticSearchRepository { @override Future cancelDownload() async => cancels++; + + @override + Future?> loadCoveredBookFilePaths() async => null; } SemanticAvailability _availability( diff --git a/test/semantic_search/semantic_test_support.dart b/test/semantic_search/semantic_test_support.dart index 39b000bdef..6a66addc5d 100644 --- a/test/semantic_search/semantic_test_support.dart +++ b/test/semantic_search/semantic_test_support.dart @@ -221,6 +221,25 @@ class FakeBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) async => throw UnimplementedError(); + /// מה [coveredBooks] מחזיר; `null` = כשל. + SemanticCoveredBooksSummary? coveredBooksValue; + Completer? coveredBooksGate; + + @override + Future coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }) async { + calls.add('coveredBooks'); + final gate = coveredBooksGate; + if (gate != null) await gate.future; + if (cancel.isCancelled) { + throw const SemanticFailure(SemanticFailureKind.cancelled); + } + return coveredBooksValue ?? + (throw const SemanticFailure(SemanticFailureKind.artifactMissing)); + } + @override Future open(SemanticOpenRequest request) async { calls.add('open'); @@ -419,6 +438,7 @@ SemanticSearchRepository buildRepository({ Duration busyRetryDelay = const Duration(milliseconds: 20), Future Function(SemanticVectorsFamily family)? identityLoader, String? Function()? onnxRuntimePath, + Future Function()? indexStamp, }) { return SemanticSearchRepository( backend: backend ?? FakeBackend(), @@ -438,6 +458,7 @@ SemanticSearchRepository buildRepository({ (_) async => DiskSpaceInfo(volumeId: 'C', freeBytes: freeBytes), modelReleases: modelReleases ?? testModelReleases, busyRetryDelay: busyRetryDelay, + indexStamp: indexStamp ?? () async => 'index', ); } From 75bd92e37295f5a7c4c7b901affc6e520c0d83a2 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Mon, 16 Nov 2026 22:35:04 +0200 Subject: [PATCH 2/6] =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=97?= =?UTF-8?q?=D7=9B=D7=9D:=20=D7=A8=D7=A9=D7=99=D7=9E=D7=AA=20=D7=94=D7=A1?= =?UTF-8?q?=D7=A4=D7=A8=D7=99=D7=9D=20=D7=94=D7=9E=D7=9B=D7=95=D7=A1=D7=99?= =?UTF-8?q?=D7=9D=20=D7=91=D7=9C=D7=99=20=D7=9C=D7=A4=D7=AA=D7=95=D7=97=20?= =?UTF-8?q?session?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit החישוב של הספרים שיש להם וקטורים כבר לא קורא ל-ensureOpen ולא טוען את המודל. המנוע צריך לשם כך רק את תיקיית הווקטורים ואת האינדקס הלקסיקלי. החישוב רץ רק כשהחיפוש החכם שמיש, כלומר הווקטורים מותקנים ויש הסכמה, ולא בזמן העברת ספרייה. הוא עובד גם כשה-session פתוח. נוספו בדיקות: אין חישוב בלי הסכמה, החישוב עובד עם session פתוח, והמצב החכם מופיע בדיאלוג שכבר פתוח כשהתשובה מגיעה. --- .../semantic_search_repository.dart | 7 ++--- .../in_book_semantic_search_dialog_test.dart | 20 ++++++++++++-- .../semantic_covered_books_test.dart | 27 ++++++++++++++++++- 3 files changed, 48 insertions(+), 6 deletions(-) diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index 23f5534982..6cefcee713 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -556,8 +556,8 @@ class SemanticSearchRepository { Set? get coveredBookFilePaths => _coveredValid ? _covered?.filePaths : null; - /// מחשב את [coveredBookFilePaths] כשצריך, אחרי פתיחת ה-session; קוראים - /// במקביל חולקים חישוב אחד. כשל או ביטול מחזירים `null`. + /// מחשב את [coveredBookFilePaths] כשצריך, בלי לפתוח session; קוראים + /// במקביל חולקים חישוב אחד. בלי חיפוש שמיש, בכשל או בביטול: `null`. Future?> loadCoveredBookFilePaths() => _coveredJob ??= _loadCovered().whenComplete(() => _coveredJob = null); @@ -565,7 +565,8 @@ class SemanticSearchRepository { final cancel = SemanticCancelHandle(); _activeSearches.add(cancel); try { - await ensureOpen(); + final current = _availability.isUsable ? _availability : await refresh(); + if (!current.isUsable || _moveInProgress) return null; // סט או אינדקס שהשתנו באמצע החישוב מחייבים חישוב נוסף. for (var attempt = 0; attempt < 2 && !cancel.isCancelled; attempt++) { final epoch = _coveredEpoch; diff --git a/test/semantic_search/in_book_semantic_search_dialog_test.dart b/test/semantic_search/in_book_semantic_search_dialog_test.dart index 108a417387..556c3ecf67 100644 --- a/test/semantic_search/in_book_semantic_search_dialog_test.dart +++ b/test/semantic_search/in_book_semantic_search_dialog_test.dart @@ -68,6 +68,9 @@ class _CoveredRepository extends SemanticSearchRepository { ); final Set? covered; + + /// כשמוגדר, התשובה מגיעה רק כשהוא מושלם. + Completer? answerGate; static const _ready = SemanticAvailability( phase: SemanticAvailabilityPhase.ready, consentGranted: true, @@ -83,7 +86,10 @@ class _CoveredRepository extends SemanticSearchRepository { Future refresh() async => _ready; @override - Future?> loadCoveredBookFilePaths() async => covered; + Future?> loadCoveredBookFilePaths() async { + await answerGate?.future; + return covered; + } } final _semanticSegment = find.byKey( @@ -138,6 +144,7 @@ void main() { WidgetTester tester, Set? covered, { bool inBook = true, + Completer? answerGate, }) async { final history = _MockHistoryBloc(); final indexing = _MockIndexingBloc(); @@ -189,7 +196,7 @@ void main() { ); addTearDown(tab.dispose); final results = []; - final repository = _CoveredRepository(covered); + final repository = _CoveredRepository(covered)..answerGate = answerGate; await tester.pumpWidget( MultiBlocProvider( @@ -248,6 +255,15 @@ void main() { expect(_queryField, findsNothing); }); + testWidgets('המצב החכם מופיע בדיאלוג הפתוח כשהתשובה מגיעה', (tester) async { + final gate = Completer(); + await pumpInBookDialog(tester, coveredBook, answerGate: gate); + expect(_semanticSegment, findsNothing); + gate.complete(); + await tester.pumpAndSettle(); + expect(_semanticSegment, findsOneWidget); + }); + testWidgets('ספר בלי וקטורים: אין מצב חכם, גם כשהסשן זוכר חכם', ( tester, ) async { diff --git a/test/semantic_search/semantic_covered_books_test.dart b/test/semantic_search/semantic_covered_books_test.dart index 872b510a78..8e0d104aa1 100644 --- a/test/semantic_search/semantic_covered_books_test.dart +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/search_feedback/search_feedback_api.dart'; import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; import 'semantic_test_support.dart'; @@ -40,7 +41,7 @@ void main() { expect(await repo.loadCoveredBookFilePaths(), {'id:1', 'id:2'}); expect(computations(backend), 1); expect(repo.coveredBookFilePaths, {'id:1', 'id:2'}); - expect(backend.calls, contains('open')); + expect(backend.calls, isNot(contains('open'))); }); test('שינוי באינדקס הלקסיקלי מחשב מחדש', () async { @@ -138,4 +139,28 @@ void main() { expect(await loading, isNull); expect(repo.coveredBookFilePaths, isNull); }); + + test('בלי הסכמה אין חישוב', () async { + installModelFiles(root); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository( + root: root, + backend: backend, + consent: FakeConsentStore(SearchFeedbackConsent.declined), + ); + expect(await repo.loadCoveredBookFilePaths(), isNull); + expect(computations(backend), 0); + }); + + test('עובד גם כשה-session פתוח', () async { + installModelFiles(root); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository(root: root, backend: backend); + await repo.ensureOpen(); + expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); + }); } From fd4f0a7566918b95aba6f13857672d6e16bb8314 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Mon, 16 Nov 2026 22:52:09 +0200 Subject: [PATCH 3/6] =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=97?= =?UTF-8?q?=D7=9B=D7=9D:=20=D7=AA=D7=99=D7=A7=D7=95=D7=A0=D7=99=20QA=20?= =?UTF-8?q?=D7=9C=D7=A8=D7=A9=D7=99=D7=9E=D7=AA=20=D7=94=D7=A1=D7=A4=D7=A8?= =?UTF-8?q?=D7=99=D7=9D=20=D7=94=D7=9E=D7=9B=D7=95=D7=A1=D7=99=D7=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit פתיחת ה-session כבר לא מבטלת את הרשימה, וגם לא הסגירה שבתוך הפתיחה. הרשימה מתבטלת בהתקנה, באיחוד, בסגירה מבחוץ (מחיקת נתונים, העברת ספרייה) ובהחלפת מודל. מסך התוצאות ודיאלוג החיפוש, גם בעריכת כרטיסייה, ממתינים לרשימה כשהיא עוד לא ידועה, במקום לחזור לבדיקה לפי מקור הספר. כך ספר אישי מכוסה כבר לא נדחה בצמצום אחרי החיפוש הראשון. מפתח האינדקס לוקח מ-searchSnapshot רק את מצב המקטעים ואת מקורות הטקסט. שינוי בסדר הספרים או במילונים כבר לא גורם למעבר מחדש על כל האינדקס. ב-state של ה-bloc אפשר לאפס את הרשימה. היא מתאפסת כשהחיפוש החכם אינו שמיש וכשהטעינה נכשלת, כדי שלא תוצג רשימה ישנה. PDF שה-id שלו שאול מספר הטקסט המקביל נכתב לאינדקס עם אותו facet כמו ספר הטקסט, ולכן אי אפשר לצמצם את החיפוש אליו בלבד. בספר כזה המצב החכם לא מוצע. בדיקות חדשות: פתיחת session אינה מבטלת את הרשימה, התקנה באמצע חישוב, חותמת האינדקס, איפוס ב-bloc, צמצום במסך התוצאות כשהרשימה עוד לא נטענה, ו-PDF עם id שאול ובלעדיו. --- lib/search/view/search_dialog.dart | 40 +++++- .../bloc/semantic_search_bloc.dart | 9 +- .../bloc/semantic_search_state.dart | 6 +- .../semantic_search_repository.dart | 23 +++- .../view/semantic_search_results_screen.dart | 33 +++-- .../in_book_semantic_search_dialog_test.dart | 35 +++++- .../semantic_covered_books_test.dart | 117 ++++++++++++++++++ .../semantic_results_screen_test.dart | 72 +++++++++++ 8 files changed, 308 insertions(+), 27 deletions(-) diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index 17a0c4f9e3..8ab152cf1c 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:math' show max; import 'package:flutter/foundation.dart'; @@ -279,6 +280,7 @@ class _SearchDialogState extends State { if (book == null) return true; final covered = _semanticBloc?.state.coveredBookFilePaths; return availability.isUsable && + _hasOwnBookFacet(book) && covered != null && covered.contains(BookIdentity.indexedFilePath(book)); } @@ -1077,7 +1079,7 @@ class _SearchDialogState extends State { return; } if (_isSemanticActive) { - _performSemanticSearch(); + unawaited(_performSemanticSearch()); return; } @@ -1271,7 +1273,7 @@ class _SearchDialogState extends State { /// בלי הסכמה או בלי נתונים אין חיפוש; הדיאלוג עצמו אינו רושם דבר. Library? get _library => context.read().state.library; - void _performSemanticSearch() { + Future _performSemanticSearch() async { final availability = _semanticBloc?.state.availability; if (_semanticSubmitted || availability == null || @@ -1286,6 +1288,9 @@ class _SearchDialogState extends State { _performInBookSemanticSearch(book); return; } + if (_loadingCoverage) return; + final covered = await _coveredForSubmit(availability); + if (!mounted || _semanticSubmitted) return; final library = _library; final parsedCategory = parseCategoryQuery( _searchTab.queryController.text, @@ -1303,10 +1308,7 @@ class _SearchDialogState extends State { return; } final isOfficialCategory = officialCategoryFilter(library); - final isCoveredFacet = coveredFacetFilter( - library, - _semanticBloc?.state.coveredBookFilePaths, - ); + final isCoveredFacet = coveredFacetFilter(library, covered); final selection = parsedCategory.categoryFound ? [ ...parsedCategory.facets!, @@ -1342,7 +1344,33 @@ class _SearchDialogState extends State { _openSemanticTab(options); } + bool _loadingCoverage = false; + + /// הספרים המכוסים לבדיקת ההיקף; כשעוד לא נטענו, ממתינים להם. + Future?> _coveredForSubmit( + SemanticAvailability availability, + ) async { + final bloc = _semanticBloc!; + final known = bloc.state.coveredBookFilePaths; + if (known != null || _semanticIncludeLexical || !availability.isUsable) { + return known; + } + _loadingCoverage = true; + try { + return await bloc.repository.loadCoveredBookFilePaths(); + } finally { + _loadingCoverage = false; + } + } + /// ההיקף הוא הספר בלבד: לא ההיקף השמור ולא תחביר @, שהיו מרחיבים אותו. + // PDF שה-id שלו שאול מספר הטקסט המקביל חולק איתו את ה-facet באינדקס, + // ולכן אי אפשר לצמצם את החיפוש אליו בלבד. + static bool _hasOwnBookFacet(Book book) => + book is! PdfBook || + book.id == null || + BookIdentity.indexedFilePath(book) == BookIdentity.keyOf(book); + void _performInBookSemanticSearch(Book book) { final query = _searchTab.queryController.text.trim(); if (query.isEmpty) { diff --git a/lib/semantic_search/bloc/semantic_search_bloc.dart b/lib/semantic_search/bloc/semantic_search_bloc.dart index 38de31b10b..f64e071a69 100644 --- a/lib/semantic_search/bloc/semantic_search_bloc.dart +++ b/lib/semantic_search/bloc/semantic_search_bloc.dart @@ -66,10 +66,15 @@ class SemanticSearchBloc }); } + /// בלי חיפוש שמיש, או כשהטעינה נכשלה, הרשימה הקודמת כבר אינה נכונה. Future _loadCoverageIfWanted(Emitter emit) async { - if (!_coverageWanted || !state.availability.isUsable) return; + if (!state.availability.isUsable) { + emit(state.copyWith(coveredBookFilePaths: () => null)); + return; + } + if (!_coverageWanted) return; final covered = await repository.loadCoveredBookFilePaths(); - if (covered != null) emit(state.copyWith(coveredBookFilePaths: covered)); + emit(state.copyWith(coveredBookFilePaths: () => covered)); } Future _onStarted( diff --git a/lib/semantic_search/bloc/semantic_search_state.dart b/lib/semantic_search/bloc/semantic_search_state.dart index 8053d6f900..882b6c29fa 100644 --- a/lib/semantic_search/bloc/semantic_search_state.dart +++ b/lib/semantic_search/bloc/semantic_search_state.dart @@ -28,14 +28,16 @@ class SemanticSearchState extends Equatable { SemanticModelChoice? modelChoice, SemanticModelChoice? activeModelChoice, bool? isRemoving, - Set? coveredBookFilePaths, + Set? Function()? coveredBookFilePaths, }) => SemanticSearchState( availability: availability ?? this.availability, quantization: quantization ?? this.quantization, modelChoice: modelChoice ?? this.modelChoice, activeModelChoice: activeModelChoice ?? this.activeModelChoice, isRemoving: isRemoving ?? this.isRemoving, - coveredBookFilePaths: coveredBookFilePaths ?? this.coveredBookFilePaths, + coveredBookFilePaths: coveredBookFilePaths != null + ? coveredBookFilePaths() + : this.coveredBookFilePaths, ); @override diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index 6cefcee713..8d58e8d024 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -179,6 +179,7 @@ class SemanticSearchRepository { _jobCancel.cancel(); await _job; await _settings.setModelChoice(value); + _invalidateCoveredBooks(); await _settings.setSkippedVectorsRelease(null); _lastFailure = null; _unpublishedVersion = null; @@ -819,7 +820,6 @@ class SemanticSearchRepository { throw const SemanticFailure(SemanticFailureKind.cancelled); } _openQuantization = quantization; - _invalidateCoveredBooks(); unawaited(_warmUp()); } @@ -847,8 +847,11 @@ class SemanticSearchRepository { bool waitForOpening = true, bool invalidateOpening = true, }) async { - if (invalidateOpening) _lifecycleEpoch++; - _invalidateCoveredBooks(); + // הסגירה שבתוך פתיחה אינה משנה את הסט; סגירה מבחוץ (מחיקה, העברה) כן. + if (invalidateOpening) { + _lifecycleEpoch++; + _invalidateCoveredBooks(); + } final wasOpen = _openQuantization != null; _openQuantization = null; _passageModelVerification = null; @@ -2014,8 +2017,18 @@ class SemanticSearchRepository { } /// משתנה בכל שינוי בתוכן האינדקס הלקסיקלי, שגם בו תלוי הכיסוי. - static Future _defaultIndexStamp() async => - (await TantivyDataProvider.instance.engine).searchSnapshot(); + static Future _defaultIndexStamp() async => coverageIndexStamp( + await (await TantivyDataProvider.instance.engine).searchSnapshot(), + ); + + /// מ-searchSnapshot רק המקטעים ומקורות הטקסט; סדר הספרים והמילונים אינם + /// משנים את הכיסוי. פורמט לא מוכר נשאר כמו שהוא. + @visibleForTesting + static String coverageIndexStamp(String snapshot) { + final parts = snapshot.split(':'); + if (parts.length < 4) return snapshot; + return '${parts.first}:${parts.sublist(3).join(':')}'; + } static Future _defaultLibraryVersion() async => int.tryParse(await DataCollectionService().readLibraryVersion()); diff --git a/lib/semantic_search/view/semantic_search_results_screen.dart b/lib/semantic_search/view/semantic_search_results_screen.dart index 0c719fa064..e78c0992ba 100644 --- a/lib/semantic_search/view/semantic_search_results_screen.dart +++ b/lib/semantic_search/view/semantic_search_results_screen.dart @@ -73,11 +73,15 @@ class SemanticSearchResultsScreen extends StatefulWidget { super.key, required this.tab, this.platformSupported, + this.semanticRepository, }); final SemanticSearchTab tab; final bool? platformSupported; + /// ברירת המחדל: [SemanticSearchRepository.instance] (לבדיקות). + final SemanticSearchRepository? semanticRepository; + @override State createState() => _SemanticSearchResultsScreenState(); @@ -162,22 +166,27 @@ class _SemanticSearchResultsScreenState List get _currentFacets => _bloc.state.options?.facets ?? widget.tab.options.facets; - void _narrow(List categories, List dimensions) { + Future _narrow(List categories, List dimensions) async { final scope = FacetHelper.categoryFacetsOf(widget.tab.options.facets); final selection = [ ...(categories.isEmpty ? scope : categories), ...dimensions, ]; + final includeLexical = widget.tab.options.includeLexical; + final repository = + widget.semanticRepository ?? SemanticSearchRepository.instance; + final covered = includeLexical + ? null + : repository.coveredBookFilePaths ?? + await repository.loadCoveredBookFilePaths(); + if (!mounted) return; final library = context.read().state.library; final isOfficialCategory = officialCategoryFilter(library); - final isCoveredFacet = coveredFacetFilter( - library, - SemanticSearchRepository.instance.coveredBookFilePaths, - ); + final isCoveredFacet = coveredFacetFilter(library, covered); if (!selection.every( (facet) => isSemanticScopeFacetSupported( facet, - includeLexical: widget.tab.options.includeLexical, + includeLexical: includeLexical, isOfficialCategory: isOfficialCategory, isCoveredFacet: isCoveredFacet, ), @@ -191,20 +200,24 @@ class _SemanticSearchResultsScreenState void _setFacet(String facet) { final dimensions = FacetHelper.dimensionFacetsOf(_currentFacets); - _narrow(facet == '/' ? const [] : [facet], dimensions); + unawaited(_narrow(facet == '/' ? const [] : [facet], dimensions)); } void _toggleFacet(String facet) { final categories = FacetHelper.categoryFacetsOf(_currentFacets) ..remove('/'); if (!categories.remove(facet)) categories.add(facet); - _narrow(categories, FacetHelper.dimensionFacetsOf(_currentFacets)); + unawaited( + _narrow(categories, FacetHelper.dimensionFacetsOf(_currentFacets)), + ); } void _toggleDimension(String facet) { final dimensions = FacetHelper.dimensionFacetsOf(_currentFacets); if (!dimensions.remove(facet)) dimensions.add(facet); - _narrow(FacetHelper.categoryFacetsOf(_currentFacets), dimensions..sort()); + unawaited( + _narrow(FacetHelper.categoryFacetsOf(_currentFacets), dimensions..sort()), + ); } /// ספירה לפי קטגוריה של התוצאות שמוצגות כעת. @@ -551,7 +564,7 @@ class _SemanticSearchResultsScreenState hasResults: state.items.isNotEmpty, onSetFacet: _setFacet, onToggleFacet: _toggleFacet, - onClearAll: () => _narrow(const [], const []), + onClearAll: () => unawaited(_narrow(const [], const [])), onToggleDimension: _toggleDimension, ), ); diff --git a/test/semantic_search/in_book_semantic_search_dialog_test.dart b/test/semantic_search/in_book_semantic_search_dialog_test.dart index 556c3ecf67..388d3b4811 100644 --- a/test/semantic_search/in_book_semantic_search_dialog_test.dart +++ b/test/semantic_search/in_book_semantic_search_dialog_test.dart @@ -145,6 +145,7 @@ void main() { Set? covered, { bool inBook = true, Completer? answerGate, + Book? openBook, }) async { final history = _MockHistoryBloc(); final indexing = _MockIndexingBloc(); @@ -221,9 +222,9 @@ void main() { child: inBook ? SearchDialog( existingTab: tab, - bookTitle: book.title, + bookTitle: (openBook ?? book).title, returnResultOnSubmit: true, - semanticBook: book, + semanticBook: openBook ?? book, semanticRepository: repository, semanticDebugPreview: false, ) @@ -357,4 +358,34 @@ void main() { expect(tab.options.facets, [bookFacet]); }); }); + + group('PDF', () { + testWidgets('PDF עם id שאול מספר הטקסט: אין מצב חכם', (tester) async { + final pdf = PdfBook(id: 1, title: 'בראשית', path: '/pdf/a.pdf'); + await pumpInBookDialog(tester, { + BookIdentity.indexedFilePath(pdf), + BookIdentity.indexedFilePath(book), + }, openBook: pdf); + expect(_semanticSegment, findsNothing); + }); + + testWidgets('PDF בלי id: ההיקף הוא ה-PDF עצמו', (tester) async { + final pdf = PdfBook(title: 'בראשית', path: '/pdf/a.pdf'); + final harness = await pumpInBookDialog(tester, { + BookIdentity.indexedFilePath(pdf), + }, openBook: pdf); + await tester.tap(_semanticSegment); + await tester.pumpAndSettle(); + await tester.enterText(_queryField, 'שאלה'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pumpAndSettle(); + final tab = + verify( + () => harness.tabs.add(captureAny()), + ).captured.whereType().single.tab + as SemanticSearchTab; + addTearDown(tab.dispose); + expect(tab.options.facets.single, endsWith('/pdf/a.pdf')); + }); + }); } diff --git a/test/semantic_search/semantic_covered_books_test.dart b/test/semantic_search/semantic_covered_books_test.dart index 8e0d104aa1..3fd69ee1bd 100644 --- a/test/semantic_search/semantic_covered_books_test.dart +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -3,7 +3,10 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/search_feedback/search_feedback_api.dart'; +import 'package:otzaria/semantic_search/bloc/semantic_search_bloc.dart'; +import 'package:otzaria/semantic_search/models/semantic_availability.dart'; import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; +import 'package:otzaria/semantic_search/repository/semantic_search_repository.dart'; import 'semantic_test_support.dart'; @@ -163,4 +166,118 @@ void main() { await repo.ensureOpen(); expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); }); + + test('פתיחת ה-session אינה מבטלת את התשובה', () async { + installModelFiles(root); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository(root: root, backend: backend); + await repo.loadCoveredBookFilePaths(); + await repo.ensureOpen(); + expect(repo.coveredBookFilePaths, {'id:1'}); + expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); + expect(computations(backend), 1); + }); + + test('התקנה באמצע החישוב: התשובה הישנה לא נשמרת ומחושבת מחדש', () async { + installModelFiles(root); + final backend = FakeBackend() + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository( + root: root, + backend: backend, + locator: FakeLocator(releaseV30()), + ); + await repo.enableAndDownload(); + final gate = Completer(); + backend.coveredBooksGate = gate; + final loading = repo.loadCoveredBookFilePaths(); + await waitFor(() => computations(backend) == 1); + backend.coveredBooksGate = null; + + backend.vectors = SemanticVectorsSummary.absent; + await repo.enableAndDownload(); + backend.coveredBooksValue = answer('set-2', ['id:3']); + gate.complete(); + + expect(await loading, {'id:3'}); + expect(computations(backend), 2); + expect(repo.coveredBookFilePaths, {'id:3'}); + }); + + test('חותמת האינדקס מתעלמת מסדר הספרים ומהמילונים', () { + String stamp(String s) => SemanticSearchRepository.coverageIndexStamp(s); + expect( + stamp('00000000000000aa:0000000000000001:0000000000000002:Some(3)'), + stamp('00000000000000aa:0000000000000009:0000000000000008:Some(3)'), + ); + expect( + stamp('00000000000000aa:1:2:Some(3)'), + isNot(stamp('00000000000000bb:1:2:Some(3)')), + ); + expect(stamp('aa:1:2:Some(3)'), isNot(stamp('aa:1:2:Some(4)'))); + expect(stamp('opaque'), 'opaque'); + }); + + group('SemanticSearchBloc', () { + test('הרשימה מתאפסת כשהחיפוש אינו שמיש וכשהטעינה נכשלת', () async { + final repo = _ScriptedRepository(); + final bloc = SemanticSearchBloc(repository: repo) + ..add(const SemanticSearchStarted()) + ..add(const SemanticCoveredBooksRequested()); + addTearDown(bloc.close); + await waitFor(() => bloc.state.coveredBookFilePaths != null); + expect(bloc.state.coveredBookFilePaths, {'id:1'}); + + repo.next = null; + repo.emit(_availability(SemanticAvailabilityPhase.ready)); + await waitFor(() => bloc.state.coveredBookFilePaths == null); + expect(bloc.state.coveredBookFilePaths, isNull); + + repo.next = {'id:2'}; + repo.emit(_availability(SemanticAvailabilityPhase.ready)); + await waitFor(() => bloc.state.coveredBookFilePaths != null); + expect(bloc.state.coveredBookFilePaths, {'id:2'}); + + repo.emit(_availability(SemanticAvailabilityPhase.installing)); + await waitFor(() => bloc.state.coveredBookFilePaths == null); + expect(bloc.state.coveredBookFilePaths, isNull); + }); + }); +} + +SemanticAvailability _availability(SemanticAvailabilityPhase phase) => + SemanticAvailability(phase: phase, consentGranted: true); + +class _ScriptedRepository extends SemanticSearchRepository { + _ScriptedRepository() + : super( + backend: FakeBackend(), + consent: () => FakeConsentStore(), + settings: FakeSettingsStore(), + ); + + SemanticAvailability current = _availability( + SemanticAvailabilityPhase.ready, + ); + final _controller = StreamController.broadcast(); + Set? next = {'id:1'}; + + void emit(SemanticAvailability value) { + current = value; + _controller.add(value); + } + + @override + SemanticAvailability get availability => current; + + @override + Stream get availabilityChanges => _controller.stream; + + @override + Future refresh() async => current; + + @override + Future?> loadCoveredBookFilePaths() async => next; } diff --git a/test/semantic_search/semantic_results_screen_test.dart b/test/semantic_search/semantic_results_screen_test.dart index 843c57c8fe..040c8b81c6 100644 --- a/test/semantic_search/semantic_results_screen_test.dart +++ b/test/semantic_search/semantic_results_screen_test.dart @@ -18,6 +18,9 @@ import 'package:otzaria/library/bloc/library_state.dart'; import 'package:otzaria/library/models/library.dart'; import 'package:otzaria/library/view/book_preview_panel.dart'; import 'package:otzaria/models/books.dart'; +import 'package:otzaria/semantic_search/repository/semantic_search_repository.dart'; +import 'package:otzaria/search/utils/facet_helper.dart'; +import 'package:otzaria/models/book_source.dart'; import 'package:otzaria/navigation/bloc/navigation_bloc.dart'; import 'package:otzaria/navigation/bloc/navigation_event.dart'; import 'package:otzaria/navigation/bloc/navigation_state.dart'; @@ -55,6 +58,7 @@ import 'package:otzaria_search_engine/otzaria_search_engine.dart' SearchEngine; import '../test_helpers/memory_cache_provider.dart'; +import 'semantic_test_support.dart' show FakeBackend, FakeSettingsStore; import 'semantic_ui_test_support.dart'; class _MockSettingsBloc extends MockBloc @@ -178,6 +182,7 @@ void main() { double? paneWidth, bool platformSupported = true, IndexingBloc? indexingBloc, + SemanticSearchRepository? semanticRepository, }) async { if (library != null) { DataRepository.instance.library = Future.value(library); @@ -248,6 +253,7 @@ void main() { child: SemanticSearchResultsScreen( tab: tab, platformSupported: platformSupported, + semanticRepository: semanticRepository, ), ), ), @@ -1122,6 +1128,54 @@ void main() { ]); }); + testWidgets('צמצום בחיפוש חכם בלבד ממתין לספרים המכוסים (issue #1963)', ( + tester, + ) async { + final personal = TextBook( + id: 4, + title: 'חידושים', + source: BookSource.user, + ); + final uncovered = TextBook(id: 1, title: 'ספר 1'); + Category category(String title, Book book) => Category( + title: title, + description: '', + shortDescription: '', + order: 0, + subCategories: const [], + books: [book], + parent: null, + ); + final library = Library( + categories: [ + category('ספרים אישיים', personal), + category('הלכה', uncovered), + ], + ); + String facetOf(Book book) => + FacetHelper.buildBookFacet(FacetHelper.resolveCategoryPath(book), book); + final harness = await pumpScreen( + tester, + library: library, + initialOptions: const SemanticQueryOptions( + query: 'כבוד אב', + includeLexical: false, + ), + semanticRepository: _LateCoverageRepository({'uid:4'}), + ); + SemanticFacetFiltering tree() => tester.widget( + find.byType(SemanticFacetFiltering, skipOffstage: false), + ); + + tree().onSetFacet(facetOf(personal)); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, [facetOf(personal)]); + + tree().onSetFacet(facetOf(uncovered)); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, [facetOf(personal)]); + }); + testWidgets('עץ חכם מסתיר חברי היקף בלי תוצאות (issue #2702)', ( tester, ) async { @@ -1199,3 +1253,21 @@ Future settle(WidgetTester tester) async { await tester.pump(const Duration(milliseconds: 100)); } } + +/// מאגר שהספרים המכוסים בו לא חושבו עדיין, ונטענים רק לפי בקשה. +class _LateCoverageRepository extends SemanticSearchRepository { + _LateCoverageRepository(this.covered) + : super( + backend: FakeBackend(), + consent: () => FakeConsentStore(), + settings: FakeSettingsStore(), + ); + + final Set covered; + + @override + Set? get coveredBookFilePaths => null; + + @override + Future?> loadCoveredBookFilePaths() async => covered; +} From b43fbfdf4efe538d67f03f1a18ae2d7a974b8390 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Mon, 16 Nov 2026 23:00:55 +0200 Subject: [PATCH 4/6] =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=97?= =?UTF-8?q?=D7=9B=D7=9D:=20=D7=AA=D7=99=D7=A7=D7=95=D7=A0=D7=99=D7=9D=20?= =?UTF-8?q?=D7=A7=D7=98=D7=A0=D7=99=D7=9D=20=D7=9E-QA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit מפתח האינדקס הוא שוב searchSnapshot כולו, כמחרוזת אטומה. פירוק לפי מיקום של פורמט פנימי היה מגיש רשימה ישנה בלי שום סימן אם סדר השדות ישתנה. חישוב מחדש כשסדר הספרים או המילונים משתנים נדיר. בשליחה חכמה שממתינה לספרים המכוסים, כפתור החיפוש מציג המתנה. במסך התוצאות רק הצמצום האחרון מוחל, ולא כמה צמצומים שהמתינו לרשימה. הערת התיעוד והשדה _loadingCoverage הוחזרו למקומם. --- lib/search/view/search_dialog.dart | 12 +++++++----- .../repository/semantic_search_repository.dart | 14 ++------------ .../view/semantic_search_results_screen.dart | 6 +++++- .../semantic_covered_books_test.dart | 14 -------------- .../semantic_results_screen_test.dart | 18 ++++++++++++++++-- 5 files changed, 30 insertions(+), 34 deletions(-) diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index 8ab152cf1c..c3631f5d7a 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -245,6 +245,9 @@ class _SearchDialogState extends State { bool _semanticGroupIdentical = SearchDefaults.initialSemanticGroupIdenticalForNewSearch(); bool _semanticSubmitted = false; + + /// בשליחה חכמה ממתינים לספרים המכוסים; הכפתור מציג המתנה. + bool _loadingCoverage = false; SemanticSearchBloc? _semanticBloc; TabsBloc? _tabsBloc; @@ -1344,8 +1347,6 @@ class _SearchDialogState extends State { _openSemanticTab(options); } - bool _loadingCoverage = false; - /// הספרים המכוסים לבדיקת ההיקף; כשעוד לא נטענו, ממתינים להם. Future?> _coveredForSubmit( SemanticAvailability availability, @@ -1355,15 +1356,14 @@ class _SearchDialogState extends State { if (known != null || _semanticIncludeLexical || !availability.isUsable) { return known; } - _loadingCoverage = true; + setState(() => _loadingCoverage = true); try { return await bloc.repository.loadCoveredBookFilePaths(); } finally { - _loadingCoverage = false; + if (mounted) setState(() => _loadingCoverage = false); } } - /// ההיקף הוא הספר בלבד: לא ההיקף השמור ולא תחביר @, שהיו מרחיבים אותו. // PDF שה-id שלו שאול מספר הטקסט המקביל חולק איתו את ה-facet באינדקס, // ולכן אי אפשר לצמצם את החיפוש אליו בלבד. static bool _hasOwnBookFacet(Book book) => @@ -1371,6 +1371,7 @@ class _SearchDialogState extends State { book.id == null || BookIdentity.indexedFilePath(book) == BookIdentity.keyOf(book); + /// ההיקף הוא הספר בלבד: לא ההיקף השמור ולא תחביר @, שהיו מרחיבים אותו. void _performInBookSemanticSearch(Book book) { final query = _searchTab.queryController.text.trim(); if (query.isEmpty) { @@ -2099,6 +2100,7 @@ class _SearchDialogState extends State { ? context.settingsText('עדכן חיפוש') : context.settingsText('חפש'), icon: FluentIcons.search_24_regular, + isLoading: _loadingCoverage, onPressed: blocked || semanticBlocked ? null : _performSearch, ), ); diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index 8d58e8d024..b3df3de86f 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -2017,18 +2017,8 @@ class SemanticSearchRepository { } /// משתנה בכל שינוי בתוכן האינדקס הלקסיקלי, שגם בו תלוי הכיסוי. - static Future _defaultIndexStamp() async => coverageIndexStamp( - await (await TantivyDataProvider.instance.engine).searchSnapshot(), - ); - - /// מ-searchSnapshot רק המקטעים ומקורות הטקסט; סדר הספרים והמילונים אינם - /// משנים את הכיסוי. פורמט לא מוכר נשאר כמו שהוא. - @visibleForTesting - static String coverageIndexStamp(String snapshot) { - final parts = snapshot.split(':'); - if (parts.length < 4) return snapshot; - return '${parts.first}:${parts.sublist(3).join(':')}'; - } + static Future _defaultIndexStamp() async => + (await TantivyDataProvider.instance.engine).searchSnapshot(); static Future _defaultLibraryVersion() async => int.tryParse(await DataCollectionService().readLibraryVersion()); diff --git a/lib/semantic_search/view/semantic_search_results_screen.dart b/lib/semantic_search/view/semantic_search_results_screen.dart index e78c0992ba..a8074cdf6c 100644 --- a/lib/semantic_search/view/semantic_search_results_screen.dart +++ b/lib/semantic_search/view/semantic_search_results_screen.dart @@ -104,6 +104,9 @@ class _SemanticSearchResultsScreenState int _freshnessResultCount = 0; int _previewRequestId = 0; + /// צמצום שממתין לספרים המכוסים מוחלף בצמצום שאחריו. + int _narrowRequestId = 0; + /// התוצאה שבתצוגה המקדימה; קובע אם להדגיש מילים בספר. SemanticResultItem? _previewItem; @@ -172,6 +175,7 @@ class _SemanticSearchResultsScreenState ...(categories.isEmpty ? scope : categories), ...dimensions, ]; + final request = ++_narrowRequestId; final includeLexical = widget.tab.options.includeLexical; final repository = widget.semanticRepository ?? SemanticSearchRepository.instance; @@ -179,7 +183,7 @@ class _SemanticSearchResultsScreenState ? null : repository.coveredBookFilePaths ?? await repository.loadCoveredBookFilePaths(); - if (!mounted) return; + if (!mounted || request != _narrowRequestId) return; final library = context.read().state.library; final isOfficialCategory = officialCategoryFilter(library); final isCoveredFacet = coveredFacetFilter(library, covered); diff --git a/test/semantic_search/semantic_covered_books_test.dart b/test/semantic_search/semantic_covered_books_test.dart index 3fd69ee1bd..e82afe920b 100644 --- a/test/semantic_search/semantic_covered_books_test.dart +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -206,20 +206,6 @@ void main() { expect(repo.coveredBookFilePaths, {'id:3'}); }); - test('חותמת האינדקס מתעלמת מסדר הספרים ומהמילונים', () { - String stamp(String s) => SemanticSearchRepository.coverageIndexStamp(s); - expect( - stamp('00000000000000aa:0000000000000001:0000000000000002:Some(3)'), - stamp('00000000000000aa:0000000000000009:0000000000000008:Some(3)'), - ); - expect( - stamp('00000000000000aa:1:2:Some(3)'), - isNot(stamp('00000000000000bb:1:2:Some(3)')), - ); - expect(stamp('aa:1:2:Some(3)'), isNot(stamp('aa:1:2:Some(4)'))); - expect(stamp('opaque'), 'opaque'); - }); - group('SemanticSearchBloc', () { test('הרשימה מתאפסת כשהחיפוש אינו שמיש וכשהטעינה נכשלת', () async { final repo = _ScriptedRepository(); diff --git a/test/semantic_search/semantic_results_screen_test.dart b/test/semantic_search/semantic_results_screen_test.dart index 040c8b81c6..fc2506c2a5 100644 --- a/test/semantic_search/semantic_results_screen_test.dart +++ b/test/semantic_search/semantic_results_screen_test.dart @@ -1154,6 +1154,7 @@ void main() { ); String facetOf(Book book) => FacetHelper.buildBookFacet(FacetHelper.resolveCategoryPath(book), book); + final repository = _LateCoverageRepository({'uid:4'}); final harness = await pumpScreen( tester, library: library, @@ -1161,7 +1162,7 @@ void main() { query: 'כבוד אב', includeLexical: false, ), - semanticRepository: _LateCoverageRepository({'uid:4'}), + semanticRepository: repository, ); SemanticFacetFiltering tree() => tester.widget( find.byType(SemanticFacetFiltering, skipOffstage: false), @@ -1174,6 +1175,15 @@ void main() { tree().onSetFacet(facetOf(uncovered)); await settle(tester); expect(harness.tab.resultsBloc.state.options!.facets, [facetOf(personal)]); + + final searchId = harness.tab.resultsBloc.state.searchId; + repository.gate = Completer(); + tree().onSetFacet('/'); + tree().onSetFacet('/ספרים אישיים'); + repository.gate!.complete(); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, ['/ספרים אישיים']); + expect(harness.tab.resultsBloc.state.searchId, searchId + 1); }); testWidgets('עץ חכם מסתיר חברי היקף בלי תוצאות (issue #2702)', ( @@ -1264,10 +1274,14 @@ class _LateCoverageRepository extends SemanticSearchRepository { ); final Set covered; + Completer? gate; @override Set? get coveredBookFilePaths => null; @override - Future?> loadCoveredBookFilePaths() async => covered; + Future?> loadCoveredBookFilePaths() async { + await gate?.future; + return covered; + } } From 1c517b9fda1e1f910e1d70f6553640fb2a480667 Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Wed, 18 Nov 2026 22:58:19 +0200 Subject: [PATCH 5/6] =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=97?= =?UTF-8?q?=D7=9B=D7=9D:=20=D7=90=D7=99=D7=9E=D7=95=D7=AA=20=D7=9B=D7=99?= =?UTF-8?q?=D7=A1=D7=95=D7=99=20=D7=95=D7=A0=D7=A2=D7=99=D7=9C=D7=AA=20?= =?UTF-8?q?=D7=A1=D7=A4=D7=A8=20=D7=91=D7=A2=D7=A8=D7=99=D7=9B=D7=94=20?= =?UTF-8?q?=D7=95=D7=91=D7=A1=D7=99=D7=A0=D7=95=D7=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/search/view/search_dialog.dart | 260 +++++++++++------- lib/search/view/search_scope_menu.dart | 15 + .../bloc/semantic_search_bloc.dart | 3 + .../engine/onnx_semantic_engine_adapter.dart | 17 ++ .../engine/semantic_engine_backend.dart | 6 + .../models/semantic_engine_models.dart | 4 +- .../models/semantic_mode_gate.dart | 5 + .../semantic_search_repository.dart | 64 +++-- .../view/semantic_search_results_screen.dart | 63 +++-- lib/tabs/models/semantic_search_tab.dart | 33 ++- ...search_scope_menu_search_actions_test.dart | 43 ++- .../onnx_semantic_engine_adapter_test.dart | 38 +++ .../in_book_semantic_search_dialog_test.dart | 28 +- .../semantic_covered_books_test.dart | 41 +++ .../semantic_results_screen_test.dart | 46 +++- .../semantic_search_dialog_test.dart | 104 ++++++- .../semantic_search_tab_test.dart | 15 + .../semantic_test_support.dart | 9 +- 18 files changed, 627 insertions(+), 167 deletions(-) diff --git a/lib/search/view/search_dialog.dart b/lib/search/view/search_dialog.dart index c3631f5d7a..feaceab6c8 100644 --- a/lib/search/view/search_dialog.dart +++ b/lib/search/view/search_dialog.dart @@ -246,8 +246,8 @@ class _SearchDialogState extends State { SearchDefaults.initialSemanticGroupIdenticalForNewSearch(); bool _semanticSubmitted = false; - /// בשליחה חכמה ממתינים לספרים המכוסים; הכפתור מציג המתנה. - bool _loadingCoverage = false; + String? _pendingCoverageQuery; + int _semanticSubmitRevision = 0; SemanticSearchBloc? _semanticBloc; TabsBloc? _tabsBloc; @@ -351,7 +351,8 @@ class _SearchDialogState extends State { repository: widget.semanticRepository ?? SemanticSearchRepository.instance, )..add(const SemanticSearchStarted()); - if (widget.semanticBook != null) { + final book = widget.semanticBook; + if (book != null && _hasOwnBookFacet(book)) { _semanticBloc!.add(const SemanticCoveredBooksRequested()); } // מצב מבוקש במפורש (קיצור חיפוש מתקדם, איתור) וכרטיסייה בעריכה @@ -359,11 +360,11 @@ class _SearchDialogState extends State { _semanticSelected = _editedSemanticTab != null || (SearchDefaults.initialSemanticForNewSearch() && + widget.semanticBook == null && widget.initialSearchMode == null && widget.existingTab == null && widget.editTab == null); if (_semanticSelected) { - _semanticBloc!.add(const SemanticCoveredBooksRequested()); // autofocus אינו בוחר טקסט; מכינים את הבחירה לפני הרכבת השדה, // כדי שבדיקת הזמינות לא תדרוס בחירת סמן מאוחרת יותר. _searchTab.queryController.selection = TextSelection( @@ -412,10 +413,20 @@ class _SearchDialogState extends State { _semanticIncludeLexical = editedOptions.includeLexical; _semanticGroupIdentical = editedOptions.groupIdenticalText; } + if (_semanticSelected && + !_semanticIncludeLexical && + _editedSemanticTab?.lockedBookFacet == null && + widget.semanticBook == null) { + _semanticBloc?.add(const SemanticCoveredBooksRequested()); + } // מאזין לשינויים בתיבת החיפוש כדי לעדכן את האפשרויות ולשמור את ההקלדה _queryListener = () { if (!mounted) return; + final pending = _pendingCoverageQuery; + if (pending != null && pending != _searchTab.queryController.text) { + _cancelPendingSemanticSubmit(); + } // שמירת ההקלדה הנוכחית (לא בעריכה — כדי לא לדרוס את ההקלדה האחרונה) if (widget.editTab != null) return; SearchDialogQuery.saveLastTyping(_searchTab.queryController.text); @@ -1081,7 +1092,7 @@ class _SearchDialogState extends State { UiSnack.showError(LibraryMessages.searchIndexMissing); return; } - if (_isSemanticActive) { + if (_isSemanticActive || _editedSemanticTab?.lockedBookFacet != null) { unawaited(_performSemanticSearch()); return; } @@ -1279,6 +1290,7 @@ class _SearchDialogState extends State { Future _performSemanticSearch() async { final availability = _semanticBloc?.state.availability; if (_semanticSubmitted || + _pendingCoverageQuery != null || availability == null || !canRunSemanticSearch( availability, @@ -1287,81 +1299,99 @@ class _SearchDialogState extends State { return; } final book = widget.semanticBook; - if (book != null) { - _performInBookSemanticSearch(book); - return; - } - if (_loadingCoverage) return; - final covered = await _coveredForSubmit(availability); - if (!mounted || _semanticSubmitted) return; - final library = _library; - final parsedCategory = parseCategoryQuery( - _searchTab.queryController.text, - library, - ); - if (parsedCategory.hasCategoryToken && !parsedCategory.categoryFound) { + final bookFacet = + _editedSemanticTab?.lockedBookFacet ?? + (book == null + ? null + : FacetHelper.buildBookFacet( + FacetHelper.resolveCategoryPath(book), + book, + )); + final input = _searchTab.queryController.text; + final parsedCategory = bookFacet == null + ? parseCategoryQuery(input, _library) + : null; + if (parsedCategory != null && + parsedCategory.hasCategoryToken && + !parsedCategory.categoryFound) { UiSnack.showError( LibraryMessages.categoryOrBookNotFound(parsedCategory.notFoundNames), ); return; } - final query = parsedCategory.query; + final query = parsedCategory?.query ?? input.trim(); if (query.trim().isEmpty) { UiSnack.show(LibraryMessages.emptySearchQuery); return; } - final isOfficialCategory = officialCategoryFilter(library); - final isCoveredFacet = coveredFacetFilter(library, covered); - final selection = parsedCategory.categoryFound - ? [ - ...parsedCategory.facets!, - ...FacetHelper.dimensionFacetsOf(_scopeSelection), - ] - : _scopeSelection; - if (!selection.every( - (facet) => isSemanticScopeFacetSupported( - facet, - includeLexical: _semanticIncludeLexical, - isOfficialCategory: isOfficialCategory, - isCoveredFacet: isCoveredFacet, - ), - )) { + final selection = switch ((bookFacet, parsedCategory?.facets)) { + (final facet?, _) => [facet], + (null, final facets?) => [ + ...facets, + ...FacetHelper.dimensionFacetsOf(_scopeSelection), + ], + (null, null) => _scopeSelection, + }; + final includeLexical = _semanticIncludeLexical; + Set? covered; + if (book != null || + (bookFacet == null && + !includeLexical && + availability.isUsable && + needsSemanticScopeCoverage(selection))) { + final revision = ++_semanticSubmitRevision; + setState(() => _pendingCoverageQuery = input); + try { + covered = await _semanticBloc!.repository.loadCoveredBookFilePaths(); + } finally { + if (mounted && revision == _semanticSubmitRevision) { + setState(() => _pendingCoverageQuery = null); + } + } + if (!mounted || + revision != _semanticSubmitRevision || + !_isSemanticActive || + !canRunSemanticSearch( + _semanticBloc!.state.availability, + debug: widget.semanticDebugPreview, + ) || + ModalRoute.of(context)?.isCurrent == false) { + return; + } + } + if (book != null && + covered?.contains(BookIdentity.indexedFilePath(book)) != true) { + _semanticBloc!.add(const SemanticCoveredBooksRequested()); UiSnack.showError(SemanticSearchMessages.unsupportedScope); return; } - _semanticSubmitted = true; - _existingTabHandedOff = true; - SearchDefaults.rememberSessionSemantic(true); - final options = SemanticQueryOptions( - query: query, - facets: semanticScopeFacets(selection), - includeLexical: _semanticIncludeLexical, - groupIdenticalText: _semanticGroupIdentical, - ); - final edited = _editedSemanticTab; - if (edited != null) { - Navigator.of(context).pop(); - edited.submit(options); - return; + if (bookFacet == null) { + final library = _library; + final isOfficialCategory = officialCategoryFilter(library); + final isCoveredFacet = coveredFacetFilter(library, covered); + if (!selection.every( + (facet) => isSemanticScopeFacetSupported( + facet, + includeLexical: includeLexical, + isOfficialCategory: isOfficialCategory, + isCoveredFacet: isCoveredFacet, + ), + )) { + UiSnack.showError(SemanticSearchMessages.unsupportedScope); + return; + } } - _openSemanticTab(options); + _submitSemanticSearch( + query, + semanticScopeFacets(selection), + lockedBookFacet: bookFacet, + ); } - /// הספרים המכוסים לבדיקת ההיקף; כשעוד לא נטענו, ממתינים להם. - Future?> _coveredForSubmit( - SemanticAvailability availability, - ) async { - final bloc = _semanticBloc!; - final known = bloc.state.coveredBookFilePaths; - if (known != null || _semanticIncludeLexical || !availability.isUsable) { - return known; - } - setState(() => _loadingCoverage = true); - try { - return await bloc.repository.loadCoveredBookFilePaths(); - } finally { - if (mounted) setState(() => _loadingCoverage = false); - } + void _cancelPendingSemanticSubmit() { + if (_pendingCoverageQuery == null) return; + _semanticSubmitRevision++; + setState(() => _pendingCoverageQuery = null); } // PDF שה-id שלו שאול מספר הטקסט המקביל חולק איתו את ה-facet באינדקס, @@ -1371,31 +1401,31 @@ class _SearchDialogState extends State { book.id == null || BookIdentity.indexedFilePath(book) == BookIdentity.keyOf(book); - /// ההיקף הוא הספר בלבד: לא ההיקף השמור ולא תחביר @, שהיו מרחיבים אותו. - void _performInBookSemanticSearch(Book book) { - final query = _searchTab.queryController.text.trim(); - if (query.isEmpty) { - UiSnack.show(LibraryMessages.emptySearchQuery); + void _submitSemanticSearch( + String query, + List facets, { + String? lockedBookFacet, + }) { + _semanticSubmitted = true; + _existingTabHandedOff = !widget.returnResultOnSubmit; + if (lockedBookFacet == null) SearchDefaults.rememberSessionSemantic(true); + final options = SemanticQueryOptions( + query: query, + facets: facets, + includeLexical: _semanticIncludeLexical, + groupIdenticalText: _semanticGroupIdentical, + ); + final edited = _editedSemanticTab; + if (edited != null) { + Navigator.of(context).pop(); + edited.submit(options); return; } - _semanticSubmitted = true; - _openSemanticTab( - SemanticQueryOptions( - query: query, - facets: [ - FacetHelper.buildBookFacet( - FacetHelper.resolveCategoryPath(book), - book, - ), - ], - includeLexical: _semanticIncludeLexical, - groupIdenticalText: _semanticGroupIdentical, - ), + final tab = SemanticSearchTab( + runOnFirstShow: true, + options: options, + lockedBookFacet: lockedBookFacet, ); - } - - void _openSemanticTab(SemanticQueryOptions options) { - final tab = SemanticSearchTab(runOnFirstShow: true, options: options); final tabsBloc = context.read(); final navigationBloc = context.read(); Navigator.of(context).pop(); @@ -1437,10 +1467,20 @@ class _SearchDialogState extends State { queryController: _searchTab.queryController, queryFocusNode: _searchTab.searchFieldFocusNode, scopeSelection: _scopeSelection, - onScopeChanged: widget.semanticBook == null ? _onScopeChanged : null, + onScopeChanged: + widget.semanticBook != null || + _editedSemanticTab?.lockedBookFacet != null + ? null + : _onScopeChanged, coveredBookFilePaths: _semanticBloc?.state.coveredBookFilePaths, includeLexical: _semanticIncludeLexical, onIncludeLexicalChanged: (value) { + _cancelPendingSemanticSubmit(); + if (!value && + widget.semanticBook == null && + _editedSemanticTab?.lockedBookFacet == null) { + _semanticBloc?.add(const SemanticCoveredBooksRequested()); + } setState(() => _semanticIncludeLexical = value); // עריכת כרטיסייה קיימת אינה משנה את ברירת המחדל לחיפוש חדש. if (widget.editTab == null) { @@ -1449,6 +1489,7 @@ class _SearchDialogState extends State { }, groupIdenticalText: _semanticGroupIdentical, onGroupIdenticalTextChanged: (value) { + _cancelPendingSemanticSubmit(); setState(() => _semanticGroupIdentical = value); if (widget.editTab == null) { SearchDefaults.saveSemanticGroupIdenticalDefault(value); @@ -1579,6 +1620,7 @@ class _SearchDialogState extends State { } void _onScopeChanged(Set selection) { + _cancelPendingSemanticSubmit(); setState(() { _scopeSelection = selection; _historyResultFilter = null; @@ -1651,12 +1693,15 @@ class _SearchDialogState extends State { } void _onModeChoice(_ModeChoice choice) { + _cancelPendingSemanticSubmit(); final mode = choice.mode; if (widget.semanticBook == null) { SearchDefaults.rememberSessionSemantic(mode == null); } if (mode == null) { - _semanticBloc?.add(const SemanticCoveredBooksRequested()); + if (!_semanticIncludeLexical && widget.semanticBook == null) { + _semanticBloc?.add(const SemanticCoveredBooksRequested()); + } setState(() => _semanticSelected = true); } else { _semanticSelected = false; @@ -2068,13 +2113,18 @@ class _SearchDialogState extends State { return _withSemanticAvailability( (semanticAvailability) => _buildSearchButton( blocked: blocked, - semanticBlocked: - _semanticSelected && - _semanticVisible(semanticAvailability) && - !canRunSemanticSearch( - semanticAvailability!, - debug: widget.semanticDebugPreview, - ), + semanticBlocked: _editedSemanticTab?.lockedBookFacet != null + ? semanticAvailability == null || + !canRunSemanticSearch( + semanticAvailability, + debug: widget.semanticDebugPreview, + ) + : _semanticSelected && + _semanticVisible(semanticAvailability) && + !canRunSemanticSearch( + semanticAvailability!, + debug: widget.semanticDebugPreview, + ), ), ); }, @@ -2100,7 +2150,7 @@ class _SearchDialogState extends State { ? context.settingsText('עדכן חיפוש') : context.settingsText('חפש'), icon: FluentIcons.search_24_regular, - isLoading: _loadingCoverage, + isLoading: _pendingCoverageQuery != null, onPressed: blocked || semanticBlocked ? null : _performSearch, ), ); @@ -2198,12 +2248,16 @@ class _SearchDialogState extends State { CrossAxisAlignment.stretch, children: [ _buildIndexWarning(), - _buildModeSelector( - context, - state, - semanticAvailability, - ), - const SizedBox(height: 12), + if (_editedSemanticTab + ?.lockedBookFacet == + null) ...[ + _buildModeSelector( + context, + state, + semanticAvailability, + ), + const SizedBox(height: 12), + ], if (semanticActive) _buildSemanticPanel( semanticAvailability!, diff --git a/lib/search/view/search_scope_menu.dart b/lib/search/view/search_scope_menu.dart index 1427b013ef..4f81790d5d 100644 --- a/lib/search/view/search_scope_menu.dart +++ b/lib/search/view/search_scope_menu.dart @@ -174,6 +174,21 @@ class _SearchScopeMenuButtonState extends State { _searchController.addListener(_onTextChanged); } + @override + void didUpdateWidget(covariant SearchScopeMenuButton oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.officialBooksOnly == widget.officialBooksOnly && + identical(oldWidget.coveredFilePaths, widget.coveredFilePaths) && + oldWidget.excludeUserBooks == widget.excludeUserBooks) { + return; + } + final library = _library; + final fullTree = library == null ? null : ScopeTree.cachedFor(library); + _treeCache = fullTree == null ? null : _visibleTree(fullTree); + _baseBookGeneration++; + _baseBookNodesCache = null; + } + @override void dispose() { _fieldFocus.removeListener(_onFocusChanged); diff --git a/lib/semantic_search/bloc/semantic_search_bloc.dart b/lib/semantic_search/bloc/semantic_search_bloc.dart index f64e071a69..de16234c33 100644 --- a/lib/semantic_search/bloc/semantic_search_bloc.dart +++ b/lib/semantic_search/bloc/semantic_search_bloc.dart @@ -17,6 +17,7 @@ class SemanticSearchBloc final SemanticSearchRepository repository; StreamSubscription? _subscription; bool _coverageWanted = false; + int _coverageRequest = 0; SemanticSearchBloc({required this.repository}) : super( @@ -68,12 +69,14 @@ class SemanticSearchBloc /// בלי חיפוש שמיש, או כשהטעינה נכשלה, הרשימה הקודמת כבר אינה נכונה. Future _loadCoverageIfWanted(Emitter emit) async { + final request = ++_coverageRequest; if (!state.availability.isUsable) { emit(state.copyWith(coveredBookFilePaths: () => null)); return; } if (!_coverageWanted) return; final covered = await repository.loadCoveredBookFilePaths(); + if (request != _coverageRequest || emit.isDone) return; emit(state.copyWith(coveredBookFilePaths: () => covered)); } diff --git a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart index 598df2ea02..16ca461977 100644 --- a/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart +++ b/lib/semantic_search/engine/onnx_semantic_engine_adapter.dart @@ -1,3 +1,5 @@ +import 'dart:io'; + import 'package:otzaria/data/data_providers/tantivy_data_provider.dart'; import 'package:otzaria/search/search_engine_gateway.dart' show SemanticSearchRequest; @@ -5,6 +7,7 @@ import 'package:otzaria/semantic_search/engine/semantic_engine_backend.dart'; import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; import 'package:otzaria/semantic_search/models/semantic_failure.dart'; import 'package:otzaria_search_engine/otzaria_search_engine.dart'; +import 'package:path/path.dart' as p; /// מממש את [SemanticEngineBackend] מעל ה-API של המנוע: התקנה, פתיחה וחיפוש /// של סט וקטורים מוכן, עם ביטול דרך [SemanticCancellationToken]. @@ -87,6 +90,19 @@ class OnnxSemanticEngineAdapter implements SemanticEngineBackend { ); }); + @override + Future coveredBooksStamp(String vectorsDir) => _guard(() async { + final engine = await _engine(); + final info = await engine.semanticVectorsInfo(vectorsDir: vectorsDir); + if (!info.present || info.recoveredFromPrevious) return null; + // CURRENT מכיל את ה-SHA של תיאור הדור, גם אם הותקן שוב באותו מספר. + try { + return await File(p.join(vectorsDir, 'CURRENT')).readAsString(); + } on PathNotFoundException { + return null; + } + }); + @override Future coveredBooks( String vectorsDir, { @@ -99,6 +115,7 @@ class OnnxSemanticEngineAdapter implements SemanticEngineBackend { return SemanticCoveredBooksSummary( filePaths: covered.filePaths, setKey: covered.setKey, + recoveredFromPrevious: covered.recoveredFromPrevious, ); }); diff --git a/lib/semantic_search/engine/semantic_engine_backend.dart b/lib/semantic_search/engine/semantic_engine_backend.dart index fe610d0747..88b27310bc 100644 --- a/lib/semantic_search/engine/semantic_engine_backend.dart +++ b/lib/semantic_search/engine/semantic_engine_backend.dart @@ -41,6 +41,9 @@ abstract interface class SemanticEngineBackend { required SemanticCancelHandle cancel, }); + /// מזהה זול של דור וקטורים תקין; null כשאי אפשר לאמת מטמון קודם. + Future coveredBooksStamp(String vectorsDir); + /// הספרים באינדקס הפתוח שיש להם וקטורים בסט; מעבר על כל האינדקס. Future coveredBooks( String vectorsDir, { @@ -114,6 +117,9 @@ class UnavailableSemanticEngineBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) => Future.error(_unavailable); + @override + Future coveredBooksStamp(String vectorsDir) async => null; + @override Future coveredBooks( String vectorsDir, { diff --git a/lib/semantic_search/models/semantic_engine_models.dart b/lib/semantic_search/models/semantic_engine_models.dart index 7050fcec94..ff5a583091 100644 --- a/lib/semantic_search/models/semantic_engine_models.dart +++ b/lib/semantic_search/models/semantic_engine_models.dart @@ -229,14 +229,16 @@ class SemanticCoveredBooksSummary extends Equatable { /// משתנה בכל שינוי במה שהסט מגיש; להשוואה בלבד. final String setKey; + final bool recoveredFromPrevious; const SemanticCoveredBooksSummary({ required this.filePaths, required this.setKey, + this.recoveredFromPrevious = false, }); @override - List get props => [filePaths, setKey]; + List get props => [filePaths, setKey, recoveredFromPrevious]; } /// בקשת פתיחה של סט הוקטורים והמודל (`openSemanticArtifact`). diff --git a/lib/semantic_search/models/semantic_mode_gate.dart b/lib/semantic_search/models/semantic_mode_gate.dart index da0c3ee397..3cdc9d2a94 100644 --- a/lib/semantic_search/models/semantic_mode_gate.dart +++ b/lib/semantic_search/models/semantic_mode_gate.dart @@ -52,6 +52,11 @@ List semanticScopeFacets(Iterable selection) { return facets..sort(); } +/// האם יש בבחירה ספר או קטגוריה שדורשים בדיקת כיסוי. +bool needsSemanticScopeCoverage(Iterable selection) => selection.any( + (facet) => facet != '/' && !FacetHelper.isDimensionFacet(facet), +); + /// האם facet של ספר או קטגוריה נתמך, לפני נרמול של בחירת כל הספרייה. bool isSemanticScopeFacetSupported( String facet, { diff --git a/lib/semantic_search/repository/semantic_search_repository.dart b/lib/semantic_search/repository/semantic_search_repository.dart index b3df3de86f..14c0b7ca0c 100644 --- a/lib/semantic_search/repository/semantic_search_repository.dart +++ b/lib/semantic_search/repository/semantic_search_repository.dart @@ -553,7 +553,7 @@ class SemanticSearchRepository { ); /// ה-filePath באינדקס של הספרים שיש להם וקטורים, כפי שחושב לאחרונה; - /// `null` כשעוד לא חושב או כשהסט או האינדקס השתנו מאז. + /// `null` לפני חישוב או אחרי ביטול. יש לטעון מחדש כדי לאמת עדכניות. Set? get coveredBookFilePaths => _coveredValid ? _covered?.filePaths : null; @@ -567,36 +567,44 @@ class SemanticSearchRepository { _activeSearches.add(cancel); try { final current = _availability.isUsable ? _availability : await refresh(); - if (!current.isUsable || _moveInProgress) return null; - // סט או אינדקס שהשתנו באמצע החישוב מחייבים חישוב נוסף. + if (!current.isUsable || _moveInProgress || !_isConsentGranted()) { + return null; + } for (var attempt = 0; attempt < 2 && !cancel.isCancelled; attempt++) { final epoch = _coveredEpoch; - final stamp = await _indexStamp(); + final directory = (await _paths()).vectorsDirectory; + final stamp = await _coverageStamp(directory); + if (cancel.isCancelled || !_isConsentGranted()) return null; + if (epoch != _coveredEpoch) continue; final previous = _covered; - if (_coveredValid && previous?.indexStamp == stamp) { + if (_coveredValid && + stamp.vectors != null && + previous?.cacheable == true && + previous?.stamp == stamp) { return previous!.filePaths; } - final answer = await _backend.coveredBooks( - (await _paths()).vectorsDirectory, - cancel: cancel, + _coveredValid = false; + final answer = await _backend.coveredBooks(directory, cancel: cancel); + final after = await _coverageStamp(directory); + if (cancel.isCancelled || !_isConsentGranted()) return null; + if (epoch != _coveredEpoch || stamp != after) continue; + final paths = + previous?.setKey == answer.setKey && + setEquals(previous?.filePaths, answer.filePaths.toSet()) + ? previous!.filePaths + : Set.unmodifiable(answer.filePaths); + _covered = _CoveredBooks( + setKey: answer.setKey, + stamp: stamp, + cacheable: !answer.recoveredFromPrevious, + filePaths: paths, ); - if (epoch != _coveredEpoch) continue; - final unchanged = - previous != null && - previous.setKey == answer.setKey && - previous.indexStamp == stamp; - _covered = unchanged - ? previous - : _CoveredBooks( - setKey: answer.setKey, - indexStamp: stamp, - filePaths: Set.unmodifiable(answer.filePaths), - ); _coveredValid = true; - return _covered!.filePaths; + return paths; } return null; } catch (error, stackTrace) { + _coveredValid = false; if (error is! SemanticFailure || error.kind != SemanticFailureKind.cancelled) { _log('coveredBooks', error, stackTrace); @@ -607,6 +615,12 @@ class SemanticSearchRepository { } } + Future<_CoverageStamp> _coverageStamp(String directory) async => ( + directory: directory, + index: await _indexStamp(), + vectors: await _backend.coveredBooksStamp(directory), + ); + void _invalidateCoveredBooks() { _coveredEpoch++; _coveredValid = false; @@ -2032,15 +2046,19 @@ class SemanticSearchRepository { class _CoveredBooks { const _CoveredBooks({ required this.setKey, - required this.indexStamp, + required this.stamp, + required this.cacheable, required this.filePaths, }); final String setKey; - final String indexStamp; + final _CoverageStamp stamp; + final bool cacheable; final Set filePaths; } +typedef _CoverageStamp = ({String directory, String index, String? vectors}); + /// release של רכיב החיפוש והקבצים ממנו שחסרים במכשיר. typedef _ModelPlan = ({ SemanticModelRelease release, diff --git a/lib/semantic_search/view/semantic_search_results_screen.dart b/lib/semantic_search/view/semantic_search_results_screen.dart index a8074cdf6c..166ac102b8 100644 --- a/lib/semantic_search/view/semantic_search_results_screen.dart +++ b/lib/semantic_search/view/semantic_search_results_screen.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:otzaria/theme/app_fonts.dart'; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; +import 'package:flutter/foundation.dart' show listEquals; import 'package:flutter/material.dart'; import 'package:otzaria/theme/app_tokens.dart'; import 'package:otzaria/widgets/feedback/app_info_banner.dart'; @@ -155,11 +156,13 @@ class _SemanticSearchResultsScreenState UiSnack.show(LibraryMessages.emptySearchQuery); return; } + _narrowRequestId++; _clearPreview(); _bloc.add(SemanticSearchSubmitted(options)); } void _openEditDialog() { + _narrowRequestId++; showDialog( context: context, builder: (_) => SearchDialog(editTab: widget.tab), @@ -170,36 +173,48 @@ class _SemanticSearchResultsScreenState _bloc.state.options?.facets ?? widget.tab.options.facets; Future _narrow(List categories, List dimensions) async { - final scope = FacetHelper.categoryFacetsOf(widget.tab.options.facets); + final tab = widget.tab; + final original = tab.options; + final bookFacet = tab.lockedBookFacet; + final scope = FacetHelper.categoryFacetsOf(original.facets); final selection = [ - ...(categories.isEmpty ? scope : categories), + if (bookFacet != null) + bookFacet + else + ...(categories.isEmpty ? scope : categories), ...dimensions, ]; final request = ++_narrowRequestId; - final includeLexical = widget.tab.options.includeLexical; - final repository = - widget.semanticRepository ?? SemanticSearchRepository.instance; - final covered = includeLexical - ? null - : repository.coveredBookFilePaths ?? - await repository.loadCoveredBookFilePaths(); - if (!mounted || request != _narrowRequestId) return; - final library = context.read().state.library; - final isOfficialCategory = officialCategoryFilter(library); - final isCoveredFacet = coveredFacetFilter(library, covered); - if (!selection.every( - (facet) => isSemanticScopeFacetSupported( - facet, - includeLexical: includeLexical, - isOfficialCategory: isOfficialCategory, - isCoveredFacet: isCoveredFacet, - ), - )) { - UiSnack.showError(SemanticSearchMessages.unsupportedScope); - return; + if (bookFacet == null && + !original.includeLexical && + needsSemanticScopeCoverage(selection)) { + final repository = + widget.semanticRepository ?? SemanticSearchRepository.instance; + final covered = await repository.loadCoveredBookFilePaths(); + if (!mounted || + request != _narrowRequestId || + !identical(widget.tab, tab) || + !identical(tab.options, original)) { + return; + } + final library = context.read().state.library; + final isOfficialCategory = officialCategoryFilter(library); + final isCoveredFacet = coveredFacetFilter(library, covered); + if (!selection.every( + (facet) => isSemanticScopeFacetSupported( + facet, + isOfficialCategory: isOfficialCategory, + isCoveredFacet: isCoveredFacet, + ), + )) { + UiSnack.showError(SemanticSearchMessages.unsupportedScope); + return; + } } + final facets = semanticScopeFacets(selection); + if (listEquals(_currentFacets, facets)) return; _clearPreview(); - widget.tab.narrow(semanticScopeFacets(selection)); + tab.narrow(facets); } void _setFacet(String facet) { diff --git a/lib/tabs/models/semantic_search_tab.dart b/lib/tabs/models/semantic_search_tab.dart index 495fe1fec9..5b187d1501 100644 --- a/lib/tabs/models/semantic_search_tab.dart +++ b/lib/tabs/models/semantic_search_tab.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; +import 'package:otzaria/search/utils/facet_helper.dart'; import 'package:otzaria/search_feedback/semantic_search_strings.dart'; import 'package:otzaria/semantic_search/bloc/semantic_results_bloc.dart'; import 'package:otzaria/semantic_search/models/semantic_result_item.dart'; @@ -14,16 +15,22 @@ class SemanticSearchTab extends SearchingTab { required SemanticQueryOptions options, super.isPinned, this.runOnFirstShow = false, + this.lockedBookFacet, String? resultsId, this._createResultsBloc, }) : _options = options, resultsId = resultsId ?? _newResultsId(), - super(titleFor(options.query), options.query); + super(titleFor(options.query), options.query) { + _options = _withinBook(options); + } /// הוגש עכשיו מהדיאלוג. כרטיסייה משוחזרת או משוכפלת אינה מריצה חיפוש /// מעצמה (אין רישום בלי פעולת משתמש), אלא מציעה "חפש מחדש". final bool runOnFirstShow; + /// ה-facet הקבוע בחיפוש שנפתח מתוך ספר. + final String? lockedBookFacet; + /// זהות יציבה של כרטיסיית התוצאות, נשמרת בשכפול (למעקב העיון). final String resultsId; @@ -66,18 +73,29 @@ class SemanticSearchTab extends SearchingTab { /// מריץ חיפוש חדש בכרטיסייה ומעדכן את הכותרת. void submit(SemanticQueryOptions options) { - _options = options; - queryController.text = options.query; - title = titleFor(options.query); + _options = _withinBook(options); + queryController.text = _options.query; + title = titleFor(_options.query); titleNotifier.value = title; - resultsBloc.add(SemanticSearchSubmitted(options)); + resultsBloc.add(SemanticSearchSubmitted(_options)); } /// מצמצם את התוצאות ל-[facets] בתוך ההיקף, בלי לשנות את ההיקף השמור. void narrow(List facets) => resultsBloc.add( - SemanticSearchSubmitted(_options.copyWith(facets: facets)), + SemanticSearchSubmitted(_withinBook(_options.copyWith(facets: facets))), ); + SemanticQueryOptions _withinBook(SemanticQueryOptions options) { + final bookFacet = lockedBookFacet; + if (bookFacet == null) return options; + return options.copyWith( + facets: [ + bookFacet, + ...FacetHelper.dimensionFacetsOf(options.facets), + ]..sort(), + ); + } + static SemanticResultsBloc _defaultResultsBloc(SemanticSearchTab tab) => SemanticResultsBloc( isUserBook: (item) async { @@ -92,6 +110,7 @@ class SemanticSearchTab extends SearchingTab { @override SemanticSearchTab clone() => SemanticSearchTab( options: _options, + lockedBookFacet: lockedBookFacet, isPinned: isPinned, resultsId: resultsId, createResultsBloc: _createResultsBloc, @@ -108,6 +127,7 @@ class SemanticSearchTab extends SearchingTab { factory SemanticSearchTab.fromJson(Map json) => SemanticSearchTab( options: SemanticQueryOptions.fromJson(json), + lockedBookFacet: json['lockedBookFacet'] as String?, isPinned: json['isPinned'] == true, ); @@ -116,6 +136,7 @@ class SemanticSearchTab extends SearchingTab { 'type': 'SemanticSearchTab', 'title': title, 'isPinned': isPinned, + if (lockedBookFacet != null) 'lockedBookFacet': lockedBookFacet, ..._options.toJson(), }; } diff --git a/test/search/search_scope_menu_search_actions_test.dart b/test/search/search_scope_menu_search_actions_test.dart index 35ece903a8..f14ae771c7 100644 --- a/test/search/search_scope_menu_search_actions_test.dart +++ b/test/search/search_scope_menu_search_actions_test.dart @@ -6,6 +6,7 @@ import 'package:positioned_sliver_list/positioned_sliver_list.dart' import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/data/book_identity.dart'; import 'package:otzaria/library/bloc/library_bloc.dart'; import 'package:otzaria/library/bloc/library_event.dart'; import 'package:otzaria/library/bloc/library_state.dart'; @@ -58,7 +59,11 @@ Future main() async { /// הבחירה החיה של הרכיב הנשלט — מוזנת חזרה דרך onChanged כמו בדיאלוג. late Set selection; - Future pumpMenu(WidgetTester tester, Set selected) async { + Future pumpMenu( + WidgetTester tester, + Set selected, { + ValueNotifier?>? coverage, + }) async { final libraryBloc = _MockLibraryBloc(); whenListen( libraryBloc, @@ -79,10 +84,20 @@ Future main() async { value: libraryBloc, child: Scaffold( body: StatefulBuilder( - builder: (context, setState) => SearchScopeMenuButton( - selected: selection, - onChanged: (next) => setState(() => selection = next), - ), + builder: (context, setState) { + Widget menu(Set? covered) => SearchScopeMenuButton( + selected: selection, + onChanged: (next) => setState(() => selection = next), + officialBooksOnly: coverage != null, + coveredFilePaths: covered, + ); + return coverage == null + ? menu(null) + : ValueListenableBuilder( + valueListenable: coverage, + builder: (_, covered, _) => menu(covered), + ); + }, ), ), ), @@ -129,6 +144,24 @@ Future main() async { group( 'פעולות בתוצאות סינון ההיקף (issue #933)', () { + testWidgets('עץ שכבר נפתח מתעדכן כשמגיעה רשימת הכיסוי', (tester) async { + final coverage = ValueNotifier?>(null); + addTearDown(coverage.dispose); + await pumpMenu(tester, {'/'}, coverage: coverage); + await typeQuery(tester, 'בראשית'); + expect(textInList('בראשית'), findsOneWidget); + + final book = _buildLibrary().getAllBooks().singleWhere( + (book) => book.title == 'שמות', + ); + coverage.value = {BookIdentity.indexedFilePath(book)}; + await tester.pumpAndSettle(); + + expect(textInList('בראשית'), findsNothing); + await typeQuery(tester, 'שמות'); + expect(textInList('שמות'), findsOneWidget); + }); + testWidgets('"נקה הכל" מוצג בתוצאות ומנקה גם היקף ברירת מחדל', ( tester, ) async { 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..a8bc4cac7a 100644 --- a/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart +++ b/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/search/search_engine_gateway.dart'; @@ -8,6 +9,7 @@ import 'package:otzaria/semantic_search/repository/semantic_platform_support.dar import 'package:otzaria/semantic_search/models/semantic_engine_models.dart'; import 'package:otzaria/semantic_search/models/semantic_failure.dart'; import 'package:otzaria_search_engine/otzaria_search_engine.dart'; +import 'package:path/path.dart' as p; const onnxStatus = SemanticStatus( state: SemanticState.ready, @@ -53,6 +55,25 @@ class _FakeEngine implements SearchEngine { Object? failure; Completer? searchPause; SemanticStatus status = onnxStatus; + bool vectorsRecovered = false; + + @override + Future semanticVectorsInfo({ + required String vectorsDir, + }) async => SemanticVectorsInfo( + present: true, + identityDigest: 'ab' * 32, + modelFamilyId: 'model-family', + libraryVersion: 30, + libraryReleaseTag: 'v30-test', + generation: BigInt.one, + segments: const [], + slotsLive: BigInt.one, + slotsDead: BigInt.zero, + bytesOnDisk: BigInt.one, + needsCompaction: false, + recoveredFromPrevious: vectorsRecovered, + ); @override Future semanticStatus() async => status; @@ -202,6 +223,23 @@ void main() { } }); + test('מטמון הכיסוי מזהה התקנה מחדש עם אותו מספר דור', () async { + final directory = await Directory.systemTemp.createTemp('vectors-stamp'); + addTearDown(() => directory.delete(recursive: true)); + final pointer = File(p.join(directory.path, 'CURRENT')); + final first = '{"generation":1,"set_sha256":"digest-one"}'; + final second = '{"generation":1,"set_sha256":"digest-two"}'; + + await pointer.writeAsString(first); + expect(await adapter.coveredBooksStamp(directory.path), first); + + await pointer.writeAsString(second); + expect(await adapter.coveredBooksStamp(directory.path), second); + + engine.vectorsRecovered = true; + expect(await adapter.coveredBooksStamp(directory.path), isNull); + }); + test('installVectors מעביר את כל השדות ומחזיר את הדוח', () async { final summary = await adapter.installVectors( const SemanticInstallRequest( diff --git a/test/semantic_search/in_book_semantic_search_dialog_test.dart b/test/semantic_search/in_book_semantic_search_dialog_test.dart index 388d3b4811..435e03a4ab 100644 --- a/test/semantic_search/in_book_semantic_search_dialog_test.dart +++ b/test/semantic_search/in_book_semantic_search_dialog_test.dart @@ -67,7 +67,7 @@ class _CoveredRepository extends SemanticSearchRepository { settings: FakeSettingsStore(), ); - final Set? covered; + Set? covered; /// כשמוגדר, התשובה מגיעה רק כשהוא מושלם. Completer? answerGate; @@ -137,6 +137,7 @@ void main() { ({ _MockTabsBloc tabs, _MockNavigationBloc navigation, + _CoveredRepository repository, List results, }) > @@ -244,7 +245,12 @@ void main() { ); await tester.tap(find.byKey(const ValueKey('launch'))); await tester.pumpAndSettle(); - return (tabs: tabs, navigation: navigation, results: results); + return ( + tabs: tabs, + navigation: navigation, + repository: repository, + results: results, + ); } testWidgets('ספר עם וקטורים: המצב החכם מוצע, אבל לא נבחר מעצמו', ( @@ -303,6 +309,7 @@ void main() { addTearDown(tab.dispose); expect(tab.options.query, 'בריאת העולם'); expect(tab.options.facets, [bookFacet]); + expect(tab.lockedBookFacet, bookFacet); verify( () => harness.navigation.add(const NavigateToScreen(Screen.search)), ).called(1); @@ -310,6 +317,23 @@ void main() { expect(SearchDefaults.initialSemanticForNewSearch(), isFalse); }); + testWidgets('שליחה מתוך ספר בודקת מחדש כיסוי שהשתנה אחרי פתיחת הדיאלוג', ( + tester, + ) async { + final harness = await pumpInBookDialog(tester, coveredBook); + await tester.tap(_semanticSegment); + await tester.pumpAndSettle(); + await tester.enterText(_queryField, 'בריאת העולם'); + + harness.repository.covered = {'id:2'}; + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pumpAndSettle(); + + verifyNever(() => harness.tabs.add(any())); + expect(find.byType(SearchDialog), findsOneWidget); + expect(_semanticSegment, findsNothing); + }); + group('חיפוש בספרייה לפי ספרים עם וקטורים', () { Future<_MockTabsBloc> submitScope( WidgetTester tester, diff --git a/test/semantic_search/semantic_covered_books_test.dart b/test/semantic_search/semantic_covered_books_test.dart index e82afe920b..b1e2a35d8f 100644 --- a/test/semantic_search/semantic_covered_books_test.dart +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -67,6 +67,47 @@ void main() { expect(computations(backend), 2); }); + test('שינוי דור וקטורים מכלי חיצוני מחשב מחדש גם באותו אינדקס', () async { + installModelFiles(root); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']); + final repo = buildRepository(root: root, backend: backend); + expect(await repo.loadCoveredBookFilePaths(), {'id:1'}); + + backend + ..coveredBooksStampValue = 'new generation' + ..coveredBooksValue = answer('set-2', ['uid:7']); + expect(await repo.loadCoveredBookFilePaths(), {'uid:7'}); + expect(computations(backend), 2); + }); + + test('שינוי באינדקס באמצע הסריקה פוסל את התשובה הישנה', () async { + installModelFiles(root); + var stamp = 'index-1'; + final gate = Completer(); + final backend = FakeBackend() + ..vectors = installedV30 + ..coveredBooksValue = answer('set-1', ['id:1']) + ..coveredBooksGate = gate; + final repo = buildRepository( + root: root, + backend: backend, + indexStamp: () async => stamp, + ); + final loading = repo.loadCoveredBookFilePaths(); + await waitFor(() => computations(backend) == 1); + + stamp = 'index-2'; + backend + ..coveredBooksValue = answer('set-1', ['uid:7']) + ..coveredBooksGate = null; + gate.complete(); + + expect(await loading, {'uid:7'}); + expect(computations(backend), 2); + }); + test('התקנת וקטורים מבטלת את התשובה; אותו setKey שומר על אותו סט', () async { installModelFiles(root); final backend = FakeBackend() diff --git a/test/semantic_search/semantic_results_screen_test.dart b/test/semantic_search/semantic_results_screen_test.dart index fc2506c2a5..425c9934e0 100644 --- a/test/semantic_search/semantic_results_screen_test.dart +++ b/test/semantic_search/semantic_results_screen_test.dart @@ -177,6 +177,7 @@ void main() { utils.HolyNameStyle? holyNameStyle, FakeResultsSource? injectedSource, SemanticQueryOptions? initialOptions, + String? lockedBookFacet, Library? library, Stream libraryStates = const Stream.empty(), double? paneWidth, @@ -198,6 +199,7 @@ void main() { final tab = SemanticSearchTab( runOnFirstShow: runOnFirstShow, options: initialOptions ?? SemanticQueryOptions(query: query), + lockedBookFacet: lockedBookFacet, createResultsBloc: (_) => buildResultsBloc( source: source, recorder: recorder, @@ -1178,12 +1180,54 @@ void main() { final searchId = harness.tab.resultsBloc.state.searchId; repository.gate = Completer(); - tree().onSetFacet('/'); + tree().onSetFacet('/הלכה'); tree().onSetFacet('/ספרים אישיים'); repository.gate!.complete(); await settle(tester); expect(harness.tab.resultsBloc.state.options!.facets, ['/ספרים אישיים']); expect(harness.tab.resultsBloc.state.searchId, searchId + 1); + + repository.gate = Completer(); + tree().onSetFacet(facetOf(personal)); + tree().onSetFacet('/'); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, ['/']); + repository.gate!.complete(); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, ['/']); + }); + + testWidgets('קטגוריית אב וספר אחר אינם מרחיבים חיפוש מתוך ספר', ( + tester, + ) async { + const bookFacet = '/הלכה/id:1'; + final harness = await pumpScreen( + tester, + initialOptions: const SemanticQueryOptions( + query: 'כבוד אב', + facets: [bookFacet], + ), + lockedBookFacet: bookFacet, + ); + SemanticFacetFiltering tree() => tester.widget( + find.byType(SemanticFacetFiltering, skipOffstage: false), + ); + + tree().onSetFacet('/הלכה'); + tree().onToggleFacet('/הלכה/id:2'); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, [bookFacet]); + + tree().onToggleDimension('/era/ראשונים'); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, [ + '/era/ראשונים', + bookFacet, + ]); + + tree().onClearAll(); + await settle(tester); + expect(harness.tab.resultsBloc.state.options!.facets, [bookFacet]); }); testWidgets('עץ חכם מסתיר חברי היקף בלי תוצאות (issue #2702)', ( diff --git a/test/semantic_search/semantic_search_dialog_test.dart b/test/semantic_search/semantic_search_dialog_test.dart index ebd65f9550..84d0be8759 100644 --- a/test/semantic_search/semantic_search_dialog_test.dart +++ b/test/semantic_search/semantic_search_dialog_test.dart @@ -83,6 +83,7 @@ class _FakeRepository extends SemanticSearchRepository { final _controller = StreamController.broadcast(); int downloads = 0; int cancels = 0; + Completer? coverageGate; @override SemanticAvailability get availability => current; @@ -106,7 +107,10 @@ class _FakeRepository extends SemanticSearchRepository { Future cancelDownload() async => cancels++; @override - Future?> loadCoveredBookFilePaths() async => null; + Future?> loadCoveredBookFilePaths() async { + await coverageGate?.future; + return null; + } } SemanticAvailability _availability( @@ -682,6 +686,104 @@ void main() { await completionCheck; expect(tester.takeException(), isNull); }); + testWidgets('חיפוש חכם בכל הספרייה נשלח בזמן שסריקת הכיסוי ממתינה', ( + tester, + ) async { + final harness = await pumpDialog( + tester, + _availability(SemanticAvailabilityPhase.ready), + ); + final gate = harness.repository.coverageGate = Completer(); + addTearDown(() { + if (!gate.isCompleted) gate.complete(); + }); + await tester.tap(_semanticSegment); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('semantic-include-lexical'))); + await tester.pumpAndSettle(); + + await tester.enterText(_queryField, 'בריאת העולם'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pump(const Duration(milliseconds: 300)); + + final tab = + harness.addedEvents.whereType().single.tab as SemanticSearchTab; + addTearDown(tab.dispose); + expect(tab.options.facets, ['/']); + expect(tab.options.includeLexical, isFalse); + gate.complete(); + await tester.pumpAndSettle(); + }); + + for (final changeMode in [false, true]) { + testWidgets( + 'שינוי ${changeMode ? "מצב" : "שאילתה"} מבטל שליחה שממתינה לכיסוי', + (tester) async { + final harness = await pumpDialog( + tester, + _availability(SemanticAvailabilityPhase.ready), + ); + final gate = harness.repository.coverageGate = Completer(); + addTearDown(() { + if (!gate.isCompleted) gate.complete(); + }); + await tester.tap(_semanticSegment); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('semantic-include-lexical')), + ); + await tester.pumpAndSettle(); + tester + .widget(find.byType(SearchScopeMenuButton)) + .onChanged({'/הלכה'}); + await tester.enterText(_queryField, 'שאילתה ראשונה'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pump(); + expect(submitButton(tester).isLoading, isTrue); + + if (changeMode) { + await tester.tap(find.text('מדויק')); + await tester.pump(); + await tester.tap(_semanticSegment); + } else { + await tester.enterText(_queryField, 'שאילתה אחרת'); + } + gate.complete(); + await tester.pumpAndSettle(); + + expect(harness.addedEvents.whereType(), isEmpty); + expect(submitButton(tester).isLoading, isFalse); + }, + ); + } + + testWidgets('עריכת חיפוש מתוך ספר שומרת את ההיקף ואת השאילתה עם @', ( + tester, + ) async { + const bookFacet = '/תנ״ך/id:1'; + final tab = SemanticSearchTab( + options: const SemanticQueryOptions(query: 'בריאה', facets: [bookFacet]), + lockedBookFacet: bookFacet, + createResultsBloc: (_) => + buildResultsBloc(source: null, recorder: RecordingRecorder()), + ); + addTearDown(tab.dispose); + await pumpDialog( + tester, + _availability(SemanticAvailabilityPhase.ready), + editTab: tab, + ); + + expect(find.byType(SearchScopeMenuButton), findsNothing); + expect(find.text('מדויק'), findsNothing); + await tester.enterText(_queryField, 'בריאת העולם@הלכה'); + await tester.tap(find.byKey(const ValueKey('search-dialog-submit'))); + await tester.pumpAndSettle(); + + expect(tab.options.query, 'בריאת העולם@הלכה'); + expect(tab.options.facets, [bookFacet]); + }); + testWidgets('ספר יחיד, ספר אישי וממד נשלחים כמו שהם בחיפוש משולב', ( tester, ) async { diff --git a/test/semantic_search/semantic_search_tab_test.dart b/test/semantic_search/semantic_search_tab_test.dart index b6aa3babcb..e35112d8d7 100644 --- a/test/semantic_search/semantic_search_tab_test.dart +++ b/test/semantic_search/semantic_search_tab_test.dart @@ -33,6 +33,21 @@ void main() { expect(restored.title, '$kSemanticSearchModeName: צדקה'); }); + test('שחזור ושכפול של חיפוש מתוך ספר שומרים את הספר והממדים', () { + const bookFacet = '/הלכה/id:1'; + final tab = SemanticSearchTab( + options: options.copyWith(facets: ['/הלכה', '/base']), + lockedBookFacet: bookFacet, + ); + final restored = OpenedTab.fromJson(tab.toJson()) as SemanticSearchTab; + final clone = tab.clone(); + for (final candidate in [tab, restored, clone]) { + addTearDown(candidate.dispose); + expect(candidate.lockedBookFacet, bookFacet); + expect(candidate.options.facets, ['/base', bookFacet]); + } + }); + test('שכפול נשאר כרטיסייה סמנטית עצמאית', () { final tab = SemanticSearchTab(options: options); addTearDown(tab.dispose); diff --git a/test/semantic_search/semantic_test_support.dart b/test/semantic_search/semantic_test_support.dart index 6a66addc5d..c59117e484 100644 --- a/test/semantic_search/semantic_test_support.dart +++ b/test/semantic_search/semantic_test_support.dart @@ -225,18 +225,25 @@ class FakeBackend implements SemanticEngineBackend { SemanticCoveredBooksSummary? coveredBooksValue; Completer? coveredBooksGate; + String? coveredBooksStampValue = 'vectors'; + + @override + Future coveredBooksStamp(String vectorsDir) async => + coveredBooksStampValue; + @override Future coveredBooks( String vectorsDir, { required SemanticCancelHandle cancel, }) async { calls.add('coveredBooks'); + final answer = coveredBooksValue; final gate = coveredBooksGate; if (gate != null) await gate.future; if (cancel.isCancelled) { throw const SemanticFailure(SemanticFailureKind.cancelled); } - return coveredBooksValue ?? + return answer ?? (throw const SemanticFailure(SemanticFailureKind.artifactMissing)); } From 914992b59055c4578103fae15adbc6c55a6cb48f Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Wed, 25 Nov 2026 23:32:28 +0200 Subject: [PATCH 6/6] =?UTF-8?q?=D7=94=D7=AA=D7=90=D7=9D=20=D7=90=D7=AA=20?= =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=94=D6=BEPDF=20=D7=95=D7=9E?= =?UTF-8?q?=D7=99=D7=92=D7=A8=D7=A6=D7=99=D7=99=D7=AA=20=D7=94=D7=90=D7=99?= =?UTF-8?q?=D7=A0=D7=93=D7=A7=D7=A1=20=D7=9C=D7=9E=D7=A0=D7=95=D7=A2=207.5?= =?UTF-8?q?.1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../repository/indexing_repository.dart | 10 +- .../utils/pdf_user_regex_pattern.dart | 4 +- .../utils/pdf_word_highlight_pattern.dart | 37 ++++++ .../utils/result_lines_highlight_pattern.dart | 3 +- lib/pdf_book/view/pdf_search_screen.dart | 84 +++++++++++- lib/search/in_book_search_settings.dart | 48 ++++--- lib/search/search_engine_gateway.dart | 53 +++++--- lib/search/search_repository.dart | 19 +++ pubspec.lock | 4 +- pubspec.yaml | 3 +- .../repository/indexing_repository_test.dart | 10 +- ...pdf_search_line_scoped_highlight_test.dart | 121 ++++++++++++++++-- .../pdf_book/pdf_user_regex_pattern_test.dart | 19 ++- .../onnx_semantic_engine_adapter_test.dart | 1 + 14 files changed, 343 insertions(+), 73 deletions(-) create mode 100644 lib/pdf_book/utils/pdf_word_highlight_pattern.dart diff --git a/lib/indexing/repository/indexing_repository.dart b/lib/indexing/repository/indexing_repository.dart index 8e31baa53b..65fadd5af3 100644 --- a/lib/indexing/repository/indexing_repository.dart +++ b/lib/indexing/repository/indexing_repository.dart @@ -1642,9 +1642,7 @@ class IndexingRepository { extraFacets: _bookExtraFacets(book), sourceHash: _dbSourceHash(book, sourceHashes), // טביעת הטקסט הריק: כך ספר שנשאר ריק נמצא תואם בבדיקה הבאה. - textHash: book is PdfBook - ? null - : await contentFingerprint(text: const []), + textHash: await contentFingerprint(text: const []), ), ], ); @@ -3014,7 +3012,11 @@ class StampChangeDetector implements IndexChangeDetector { topics: _repository._bookTopics(book), extraFacets: _repository._bookExtraFacets(book), ); - if (stamp.metadataHash == BigInt.zero || stamp.metadataHash != metadata) { + // חותם אפס מזהה PDF שאונדקס בשורות וצריך להיכתב מחדש בעמודים. + if (book is PdfBook && stamp.textHash == BigInt.zero) { + changed.add(book); + } else if (stamp.metadataHash == BigInt.zero || + stamp.metadataHash != metadata) { changed.add(book); final sourceHash = IndexingRepository._dbSourceHash(book, sourceHashes); if (sourceHash == null || diff --git a/lib/pdf_book/utils/pdf_user_regex_pattern.dart b/lib/pdf_book/utils/pdf_user_regex_pattern.dart index 3522119b41..472f78e990 100644 --- a/lib/pdf_book/utils/pdf_user_regex_pattern.dart +++ b/lib/pdf_book/utils/pdf_user_regex_pattern.dart @@ -25,8 +25,8 @@ class PdfUserRegexPattern implements RegExp { final UserRegexMatcher _matcher; - /// An edge `^`/`$` (`\A`/`\z` in the engine's pattern) means a text line, as - /// in the index where each PDF line is a document: such a pattern runs per line. + /// An edge `^`/`$` (`\A`/`\z` in the engine's pattern) belongs to a layout + /// line, even when the index stores the whole page as one document. final bool _lineAnchored; /// The query as typed, which also tells pdfrx whether a search repeats. diff --git a/lib/pdf_book/utils/pdf_word_highlight_pattern.dart b/lib/pdf_book/utils/pdf_word_highlight_pattern.dart new file mode 100644 index 0000000000..895349e7f6 --- /dev/null +++ b/lib/pdf_book/utils/pdf_word_highlight_pattern.dart @@ -0,0 +1,37 @@ +import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart'; +import 'package:otzaria_search_engine/otzaria_search_engine.dart'; + +class PdfWordHighlightPattern implements Pattern { + const PdfWordHighlightPattern( + this.matcher, + this.boundaries, + this.wordMatchMode, + this.wordMatchCount, + ); + + final HighlightMatcher matcher; + final List boundaries; + final WordMatchMode wordMatchMode; + final int wordMatchCount; + + @override + Iterable allMatches(String string, [int start = 0]) sync* { + RangeError.checkValueInInterval(start, 0, string.length, 'start'); + for (final match in matcher.findPdfWordMatches( + data: string, + requireTokenBoundaries: boundaries, + wordMatchMode: wordMatchMode, + wordMatchCount: wordMatchCount, + )) { + if (match.start >= start) { + yield PdfSpanMatch(this, string, match.start, match.end); + } + } + } + + @override + Match? matchAsPrefix(String string, [int start = 0]) { + final match = allMatches(string, start).firstOrNull; + return match?.start == start ? match : null; + } +} diff --git a/lib/pdf_book/utils/result_lines_highlight_pattern.dart b/lib/pdf_book/utils/result_lines_highlight_pattern.dart index b27df0721c..8cd42d0e06 100644 --- a/lib/pdf_book/utils/result_lines_highlight_pattern.dart +++ b/lib/pdf_book/utils/result_lines_highlight_pattern.dart @@ -2,8 +2,7 @@ import 'dart:convert'; import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart'; -/// המונחים שהמנוע סימן, רק בשורות העמוד שמכילות את כל המונחים של קטע תוצאה -/// אחד: כל שורת PDF היא מסמך באינדקס, וכשההתאמה אינה רצף היא השורה כולה. +/// הדגשה מתקצירים של אינדקס לפי שורות, כשאין מתאם לעמוד שלם. class ResultLinesHighlightPattern implements Pattern { ResultLinesHighlightPattern._(this._terms, this._termSets, this.key); diff --git a/lib/pdf_book/view/pdf_search_screen.dart b/lib/pdf_book/view/pdf_search_screen.dart index 4248ae6ac1..24363fb957 100644 --- a/lib/pdf_book/view/pdf_search_screen.dart +++ b/lib/pdf_book/view/pdf_search_screen.dart @@ -25,6 +25,7 @@ import 'package:otzaria/search/book_facet.dart'; import 'package:otzaria/search/in_book_search_preferences.dart'; import 'package:otzaria/search/view/whole_word_search_action.dart'; import 'package:otzaria/search/models/search_configuration.dart'; +import 'package:otzaria/search/search_query_builder.dart'; import 'package:otzaria/search/search_repository.dart'; import 'package:otzaria/search/utils/literal_search_pattern.dart'; import 'package:otzaria/search/utils/user_regex_query.dart'; @@ -32,6 +33,7 @@ import 'package:otzaria/pdf_book/utils/centered_text_search_session.dart'; import 'package:otzaria/pdf_book/utils/pdf_engine_result_ordinals.dart'; import 'package:otzaria/pdf_book/utils/pdf_search_result_list.dart'; import 'package:otzaria/pdf_book/utils/pdf_user_regex_pattern.dart'; +import 'package:otzaria/pdf_book/utils/pdf_word_highlight_pattern.dart'; import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart'; import 'package:otzaria/pdf_book/utils/result_lines_highlight_pattern.dart'; import 'package:otzaria/search/utils/snippet_builder.dart'; @@ -231,14 +233,25 @@ class PdfBookSearchView extends StatefulWidget { /// תקרת מונחים ייחודיים לתבנית ההדגשה, כדי שהרגקס לא יתנפח. static const int _maxHighlightTerms = 50; - /// תבנית הדגשה לעמודים: המתאם של הקורא הטקסטואלי כשהוא מוצא את [resultHtmls], - /// ואחרת המונחים שהמנוע סימן, בשורות שהוא התאים. null כשאין מה להדגיש. + /// תבנית הדגשה מהמתאם לעמוד, מהתאמת המרווח או מהסימונים ב-[resultHtmls]. @visibleForTesting static Pattern? buildAdvancedHighlightPattern( Iterable resultHtmls, { String query = '', InBookSearchSettings settings = const InBookSearchSettings(), + HighlightPattern? indexPattern, }) { + if (indexPattern?.matcher case final matcher?) { + final policy = settings.matchPolicy; + return PdfWordHighlightPattern( + matcher, + indexPattern!.wordBoundaryEligible, + settings.searchMode == SearchMode.fuzzy + ? WordMatchMode.all + : policy.wordMatchMode, + policy.wordMatchCount, + ); + } final proximity = _proximityPattern(resultHtmls, query, settings); if (proximity != null) return proximity; @@ -286,7 +299,7 @@ class PdfBookSearchView extends StatefulWidget { String query, InBookSearchSettings settings, ) { - // במקורב, בטווח פסקה/כותרת וב"לפחות N מילים" המנוע מתאים שורה ולא רצף. + // במקורב, בטווח פסקה/כותרת וב"לפחות N מילים" אין דרישה לרצף. if (query.isEmpty || settings.searchMode == SearchMode.fuzzy) return null; final policy = settings.matchPolicy; if (policy.proximityScope != SearchScope.wordDistance || @@ -397,7 +410,7 @@ class PdfBookSearchViewState extends State int get _searchDistance => _settings.distance; SearchMatchPolicy get _matchPolicy => _settings.matchPolicy; - String _lastPdfHighlightSource = ''; + Object _lastPdfHighlightSource = ''; int _searchGeneration = 0; late final _engineSearch = InBookEngineSearchCancellation( widget.searchRepository, @@ -475,6 +488,7 @@ class PdfBookSearchViewState extends State RegExp regExp => regExp.pattern, ProximityHighlightPattern proximity => proximity.key, ResultLinesHighlightPattern lines => lines.key, + PdfWordHighlightPattern words => words, _ => '', }; final searcher = widget.textSearcher; @@ -715,16 +729,67 @@ class PdfBookSearchViewState extends State } /// מדגיש על העמוד את מה שהמנוע מצא בפועל (כולל fuzzy/מילים חלופיות). - void _updateAdvancedHighlight(List results, String query) { + void _updateAdvancedHighlight( + List results, + String query, { + HighlightPattern? indexPattern, + }) { final pattern = PdfBookSearchView.buildAdvancedHighlightPattern( results.map((r) => r.text), query: query, settings: _settings, + indexPattern: indexPattern, ); _lastAdvancedHighlightPattern = pattern; _schedulePdfHighlight(pattern); } + static final _phraseQuotes = RegExp(r'(? _preparePageWordHighlights( + String query, + int requestId, + ) async { + final policy = _settings.matchPolicy; + final needsWordMatcher = switch (_settings.searchMode) { + SearchMode.exact => false, + SearchMode.fuzzy => + policy.querySemantics == SearchQuerySemantics.regular && + !_hasQuotedFuzzyPhrase(query), + SearchMode.advanced => + policy.proximityScope != SearchScope.wordDistance || + policy.wordMatchMode != WordMatchMode.all, + }; + final options = _settings.searchOptions; + if (!needsWordMatcher || + SearchQueryBuilder.optionsRequestVocalized(options) || + options.values.any((word) => word['תרגום ארמי'] == true)) { + return null; + } + try { + return await widget.searchRepository.preparePdfWordHighlightPattern( + inBookSearchRequest( + query: query, + bookPath: _bookPath!, + settings: _settings, + cancelRequestId: requestId, + ), + indexedFilePath: _indexedFilePath, + ); + } catch (error) { + debugPrint('[PdfSearch] page word highlights unavailable: $error'); + return null; + } + } + @override void initState() { super.initState(); @@ -1304,13 +1369,14 @@ class PdfBookSearchViewState extends State } try { + final requestId = _engineSearch.next(); final rawResults = await searchBookWithEngine( widget.searchRepository, query: query, bookPath: _bookPath!, limit: kInBookEngineFetchLimit, settings: _settings, - cancelRequestId: _engineSearch.next(), + cancelRequestId: requestId, ); final indexedFilePath = _indexedFilePath; @@ -1347,7 +1413,11 @@ class PdfBookSearchViewState extends State ); } }); - _updateAdvancedHighlight(results, query); + final indexPattern = results.isEmpty + ? null + : await _preparePageWordHighlights(query, requestId); + if (!mounted || generation != _searchGeneration) return; + _updateAdvancedHighlight(results, query, indexPattern: indexPattern); _centerOpenTargetMatch(); _scheduleScrollToCurrentPage(); } catch (e, st) { diff --git a/lib/search/in_book_search_settings.dart b/lib/search/in_book_search_settings.dart index 6248dda6bc..b0f9aef261 100644 --- a/lib/search/in_book_search_settings.dart +++ b/lib/search/in_book_search_settings.dart @@ -215,30 +215,46 @@ Future> searchBookWithEngine( ), ); } - final parameters = settings.activeParameters; - final policy = settings.requestedMatchPolicy.forQuery(query); return repository.searchTexts( - SearchEngineRequest( + inBookSearchRequest( query: query, - facets: [bookPath], + bookPath: bookPath, limit: limit, - searchOptions: parameters.searchOptions, - alternativeWords: parameters.alternativeWords, - customSpacing: parameters.customSpacing, - distance: settings.distance, - negativeDistance: settings.distance, - searchMode: settings.searchMode, - scope: policy.proximityScope, - negativeScope: policy.proximityScope, - wordMatchMode: policy.wordMatchMode, - wordMatchCount: policy.wordMatchCount, - anyOrder: policy.anyOrder, - order: ResultsOrder.catalogue, + settings: settings, cancelRequestId: cancelRequestId, ), ); } +SearchEngineRequest inBookSearchRequest({ + required String query, + required String bookPath, + int limit = 0, + required InBookSearchSettings settings, + int? cancelRequestId, +}) { + final parameters = settings.activeParameters; + final policy = settings.requestedMatchPolicy.forQuery(query); + return SearchEngineRequest( + query: query, + facets: [bookPath], + limit: limit, + searchOptions: parameters.searchOptions, + alternativeWords: parameters.alternativeWords, + customSpacing: parameters.customSpacing, + distance: settings.distance, + negativeDistance: settings.distance, + searchMode: settings.searchMode, + scope: policy.proximityScope, + negativeScope: policy.proximityScope, + wordMatchMode: policy.wordMatchMode, + wordMatchCount: policy.wordMatchCount, + anyOrder: policy.anyOrder, + order: ResultsOrder.catalogue, + cancelRequestId: cancelRequestId, + ); +} + /// מזהה הביטול של חיפוש המנוע האחרון בחלונית חיפוש בתוך ספר. /// חיפוש חדש או סגירת החלונית עוצרים במנוע את הקודם, שאחרת ממשיך לרוץ ברקע. class InBookEngineSearchCancellation { diff --git a/lib/search/search_engine_gateway.dart b/lib/search/search_engine_gateway.dart index 28aa203091..a1bc2dd652 100644 --- a/lib/search/search_engine_gateway.dart +++ b/lib/search/search_engine_gateway.dart @@ -1118,6 +1118,43 @@ class RustSearchEngineOperations void primeSmartHighlightPattern(SearchEngineRequest request) => _primeHighlightPattern(request, SearchQuerySemantics.smart); + Future preparePdfWordHighlightPattern( + SearchEngineRequest request, { + required String indexedFilePath, + }) async { + final indexed = indexHighlightRequest(request); + if (indexed == null || + await _engine.getBookTextFingerprint(filePath: indexedFilePath) == + BigInt.zero) { + return null; + } + return _generateIndexHighlightPattern( + indexed, + cancelRequestId: indexed.cancelRequestId, + ); + } + + Future _generateIndexHighlightPattern( + SearchEngineRequest request, { + int? cancelRequestId, + }) => switch (request.searchMode) { + SearchMode.advanced => _engine.generateIndexHighlightPattern( + query: request.query, + distance: request.distance < 0 ? 0 : request.distance, + customSpacing: request.customSpacing, + alternativeWords: request.alternativeWords, + searchOptions: request.searchOptions, + anyOrder: request.anyOrder, + cancelRequestId: cancelRequestId, + ), + SearchMode.fuzzy => _engine.generateIndexFuzzyHighlightPattern( + query: request.query, + maxDistance: _fuzzyDistance(request.distance), + cancelRequestId: cancelRequestId, + ), + SearchMode.exact => Future.value(null), + }; + void _primeHighlightPattern( SearchEngineRequest request, SearchQuerySemantics semantics, @@ -1146,21 +1183,7 @@ class RustSearchEngineOperations : SemanticLexicalMode.fuzzy, maxDistance: _fuzzyDistance(request.distance), ) - : switch (request.searchMode) { - SearchMode.advanced => _engine.generateIndexHighlightPattern( - query: request.query, - distance: request.distance < 0 ? 0 : request.distance, - customSpacing: request.customSpacing, - alternativeWords: request.alternativeWords, - searchOptions: request.searchOptions, - anyOrder: request.anyOrder, - ), - SearchMode.fuzzy => _engine.generateIndexFuzzyHighlightPattern( - query: request.query, - maxDistance: _fuzzyDistance(request.distance), - ), - SearchMode.exact => Future.value(null), - }, + : _generateIndexHighlightPattern(request), ), ); } diff --git a/lib/search/search_repository.dart b/lib/search/search_repository.dart index eda49ebf54..110c9881e0 100644 --- a/lib/search/search_repository.dart +++ b/lib/search/search_repository.dart @@ -135,6 +135,25 @@ class SearchRepository { return results; } + /// תבנית לקורא PDF, אם הספר נכתב כמסמכי עמוד. + Future preparePdfWordHighlightPattern( + SearchEngineRequest request, { + required String indexedFilePath, + }) async { + if (indexedFilePath.isEmpty || + (_engineProvider == null && + !TantivyDataProvider.instance.isInitialized.value)) { + return null; + } + final engine = await _engine(); + return engine is RustSearchEngineOperations + ? engine.preparePdfWordHighlightPattern( + request, + indexedFilePath: indexedFilePath, + ) + : null; + } + Future _verifySnapshot( SearchEngineOperations engine, String expected, diff --git a/pubspec.lock b/pubspec.lock index 74032bfb61..4c0ed78b61 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1246,10 +1246,10 @@ packages: dependency: "direct main" description: name: otzaria_search_engine - sha256: "6a71c5bf3ce9ef84317c516f9994e31f20b495e8523f16bc0932828ea5d713bf" + sha256: "8ecc30eb57059c92747f0bca487aaadee7c1b0064a337ef451bb46ca7479300e" url: "https://pub.dev" source: hosted - version: "7.2.1" + version: "7.5.1" package_config: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 0e84e566c2..34b8f3c4bc 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -123,8 +123,7 @@ dependencies: googleapis_auth: ^2.3.7 characters: ^1.4.1 collection: ^1.19.1 - # קו התאימות שומר על הדגשת PDF לפי שורות ועל חיפוש רג׳קס חוצה שורה. - otzaria_search_engine: 7.2.1 + otzaria_search_engine: 7.5.1 # חוזה הדיווחים מול השרת, משותף עם "עדכוני אוצריא" (Dart טהור). otzaria_report_contract: path: packages/otzaria_report_contract diff --git a/test/indexing/repository/indexing_repository_test.dart b/test/indexing/repository/indexing_repository_test.dart index 651a989c29..a178ac5f83 100644 --- a/test/indexing/repository/indexing_repository_test.dart +++ b/test/indexing/repository/indexing_repository_test.dart @@ -1909,16 +1909,18 @@ void main() { expect(changed, ['מצורף']); }); - test('ספר אישי ו-PDF — רק metadata, בלי קריאת טקסט', () async { + test('PDF ישן מסומן לאינדוקס מחדש בלי קריאת טקסט', () async { final personal = TextBook(id: 9, title: 'אישי', source: BookSource.user); final pdf = PdfBook(title: 'סרוק', path: r'C:\pdfs\a.pdf'); + final current = PdfBook(title: 'חדש', path: r'C:\pdfs\b.pdf'); final engine = _RecordingSearchEngine() ..fingerprints = { BookIdentity.indexedFilePath(personal): BigInt.one, BookIdentity.indexedFilePath(pdf): BigInt.zero, + BookIdentity.indexedFilePath(current): BigInt.one, }; - expect(await detect(engine, [personal, pdf]), isEmpty); + expect(await detect(engine, [personal, pdf, current]), [pdf.title]); }); test('ספר שאינו באינדקס אינו נבדק', () async { @@ -3546,6 +3548,10 @@ void main() { expect(result.failures.single.kind, IndexingFailureKind.pdfUnsupported); expect(result.failures.single.isRetryable, isFalse); expect(provider.indexedFilePaths, contains(pdf.path)); + expect( + engine.addedDocuments.single.textHash, + await _fakeContentFingerprint(text: const []), + ); }); test('PDF חלקי מאונדקס אך מוחזר כאזהרה מפורטת', () async { diff --git a/test/pdf_book/pdf_search_line_scoped_highlight_test.dart b/test/pdf_book/pdf_search_line_scoped_highlight_test.dart index 89a5641afa..84a99427ac 100644 --- a/test/pdf_book/pdf_search_line_scoped_highlight_test.dart +++ b/test/pdf_book/pdf_search_line_scoped_highlight_test.dart @@ -4,6 +4,8 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:otzaria/pdf_book/view/pdf_search_screen.dart'; import 'package:otzaria/search/in_book_search_settings.dart'; import 'package:otzaria/search/models/search_configuration.dart'; +import 'package:otzaria/search/search_engine_gateway.dart'; +import 'package:otzaria/search/search_repository.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:otzaria_search_engine/otzaria_search_engine.dart'; @@ -247,33 +249,65 @@ Future main() async { await directory.delete(recursive: true); }); const page = 'Hello world\nhello word\nhello לבד'; + const splitPage = '😀 hello לבד\nword נמצא בשורה אחרת'; await engine.addPdfBook( title: 'בדיקת כתיבים', topics: '/test', filePath: 'case.pdf', pages: [ const PdfPageInput(reference: 'עמוד א', text: page, pageIndex: 0), + const PdfPageInput( + reference: 'עמוד ב', + text: splitPage, + pageIndex: 1, + ), + ], + ); + await engine.addDocumentsBatch( + docs: [ + for (final (index, line) in [ + 'hello world', + ...splitPage.split('\n'), + ].indexed) + DocumentInput( + ordinal: index, + title: 'PDF ישן', + reference: 'עמוד ${index == 0 ? 1 : 2}', + topics: '/legacy', + text: line, + segment: index == 0 ? BigInt.zero : BigInt.one, + isPdf: true, + filePath: 'legacy.pdf', + ), ], ); await engine.commit(); - final hits = await engine.searchFuzzy( - query: 'hello world', - facets: [], + const query = 'hello world'; + final settings = const InBookSearchSettings( + searchMode: SearchMode.fuzzy, + distance: 1, + ).forQuery(query); + final repository = SearchRepository( + engineProvider: () async => RustSearchEngineOperations(engine), + ); + final request = inBookSearchRequest( + query: query, + bookPath: '/test', limit: 20, - offset: 0, - maxDistance: 1, - order: ResultsOrder.catalogue, - matchNikud: false, - matchTaamim: false, + settings: settings, + ); + final hits = await repository.searchTexts(request); + expect(hits.map((hit) => hit.segment), [BigInt.zero, BigInt.one]); + final indexPattern = await repository.preparePdfWordHighlightPattern( + request, + indexedFilePath: 'case.pdf', ); - expect(hits, hasLength(2)); + expect(indexPattern?.matcher, isNotNull); final pattern = PdfBookSearchView.buildAdvancedHighlightPattern( hits.map((hit) => hit.text), - query: 'hello world', - settings: const InBookSearchSettings( - searchMode: SearchMode.fuzzy, - distance: 1, - ).forQuery('hello world'), + query: query, + settings: settings, + indexPattern: indexPattern, )!; expect(_highlighted(pattern, page), [ @@ -282,6 +316,65 @@ Future main() async { (1, 'hello'), (1, 'word'), ]); + expect(_highlighted(pattern, splitPage), [(0, 'hello'), (1, 'word')]); + expect(_highlighted(pattern, 'hello בלבד\nhello שוב'), isEmpty); + + final legacyRequest = request.copyWith(facets: ['/legacy']); + final legacyHits = await repository.searchTexts(legacyRequest); + expect(legacyHits.map((hit) => hit.segment), [BigInt.zero]); + expect( + await repository.preparePdfWordHighlightPattern( + legacyRequest, + indexedFilePath: 'legacy.pdf', + ), + isNull, + ); + final legacyPattern = PdfBookSearchView.buildAdvancedHighlightPattern( + legacyHits.map((hit) => hit.text), + query: query, + settings: settings, + )!; + expect(_highlighted(legacyPattern, splitPage), isEmpty); + + for (final (query, policy) in [ + ( + 'hello word', + const SearchMatchPolicy(proximityScope: SearchScope.sameParagraph), + ), + ( + 'hello hello word missing', + const SearchMatchPolicy( + wordMatchMode: WordMatchMode.atLeast, + wordMatchCount: 2, + ), + ), + ]) { + final settings = InBookSearchSettings( + searchMode: SearchMode.advanced, + matchPolicy: policy, + ).forQuery(query); + final request = inBookSearchRequest( + query: query, + bookPath: '/test', + limit: 20, + settings: settings, + ); + final hits = await repository.searchTexts(request); + expect(hits.map((hit) => hit.segment), [BigInt.zero, BigInt.one]); + final indexPattern = await repository.preparePdfWordHighlightPattern( + request, + indexedFilePath: 'case.pdf', + ); + expect(indexPattern?.matcher, isNotNull); + final pattern = PdfBookSearchView.buildAdvancedHighlightPattern( + hits.map((hit) => hit.text), + query: query, + settings: settings, + indexPattern: indexPattern, + )!; + expect(_highlighted(pattern, page), [(1, 'hello'), (1, 'word')]); + expect(_highlighted(pattern, splitPage), [(0, 'hello'), (1, 'word')]); + } }); test('קטע שחוצה שורה: כל צד נבדק מול שורה משלו', () { diff --git a/test/pdf_book/pdf_user_regex_pattern_test.dart b/test/pdf_book/pdf_user_regex_pattern_test.dart index 0d8466d902..24943234b8 100644 --- a/test/pdf_book/pdf_user_regex_pattern_test.dart +++ b/test/pdf_book/pdf_user_regex_pattern_test.dart @@ -70,10 +70,9 @@ Future main() async { test('^ ו-\$ מעוגנים לשורת הטקסט, לא לעמוד', () { const text = 'ויאמר משה\nויאמר אהרן\r\nאמר משה'; List found(String raw, [int start = 0]) => - PdfUserRegexPattern.tryParse(raw)! - .allMatches(text, start) - .map((m) => m.group(0)) - .toList(); + PdfUserRegexPattern.tryParse( + raw, + )!.allMatches(text, start).map((m) => m.group(0)).toList(); expect(found('/^ויאמר/'), ['ויאמר', 'ויאמר']); expect(found(r'/משה$/'), ['משה', 'משה']); expect(found(r'/^ויאמר \S+$/'), ['ויאמר משה', 'ויאמר אהרן']); @@ -86,6 +85,12 @@ Future main() async { ); }); + test('רגקס ללא עוגן שורה יכול להתאים על פני שתי שורות', () { + const text = '😀 ויאמר מֹשֶׁה אל העם\r\nאל תיראו התיצבו'; + final pattern = PdfUserRegexPattern.tryParse('/משה .* תיראו/')!; + expect(pattern.stringMatch(text), 'מֹשֶׁה אל העם\r\nאל תיראו'); + }); + test('allMatches עצל ועוצר בשורה המתאימה הראשונה', () { final text = List.filled(1000, 'ויאמר משה').join('\n'); final pattern = PdfUserRegexPattern.tryParse('/^ויאמר/')!; @@ -147,9 +152,9 @@ Future main() async { test('pdfrx מקבל את התבנית ומחזיר טווחים בעמוד', () async { const text = 'אמר שמע בני ישראל'; - final ranges = await page(text) - .allMatches(PdfUserRegexPattern.tryParse(r'/שמע \S+ ישראל/')!) - .toList(); + final ranges = await page( + text, + ).allMatches(PdfUserRegexPattern.tryParse(r'/שמע \S+ ישראל/')!).toList(); expect(ranges.map((r) => (r.start, r.end)), [(4, text.length)]); }); }, skip: ready ? false : searchEngineSkipReason); 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 a8bc4cac7a..96157f86c4 100644 --- a/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart +++ b/test/semantic_search/engine/onnx_semantic_engine_adapter_test.dart @@ -122,6 +122,7 @@ class _FakeEngine implements SearchEngine { required bool matchNikud, required bool matchTaamim, SemanticRankingOptions? ranking, + List? votes, required SemanticCancellationToken cancellation, }) async { this.ranking = ranking;