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 041d63d924..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) { @@ -1540,6 +1610,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/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/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..feaceab6c8 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'; @@ -13,6 +14,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 +156,9 @@ class SearchDialog extends StatefulWidget { /// האם מותרת התצוגה המקדימה של פיתוח; ברירת המחדל [kDebugMode]. final bool semanticDebugPreview; + /// בחיפוש בתוך ספר: הספר, שבו מוצע החיפוש החכם כשיש לו וקטורים. + final Book? semanticBook; + const SearchDialog({ super.key, this.existingTab, @@ -166,6 +172,7 @@ class SearchDialog extends StatefulWidget { this.semanticRepository, this.semanticConsent, this.semanticDebugPreview = kDebugMode, + this.semanticBook, }); @override @@ -238,17 +245,21 @@ class _SearchDialogState extends State { bool _semanticGroupIdentical = SearchDefaults.initialSemanticGroupIdenticalForNewSearch(); bool _semanticSubmitted = false; + + String? _pendingCoverageQuery; + int _semanticSubmitRevision = 0; SemanticSearchBloc? _semanticBloc; TabsBloc? _tabsBloc; /// החיפוש נשלח לכרטיסייה חדשה, ולכן [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 +274,19 @@ 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 && + _hasOwnBookFacet(book) && + covered != null && + covered.contains(BookIdentity.indexedFilePath(book)); + } bool get _isSemanticActive => _semanticSelected && _semanticVisible(_semanticBloc?.state.availability); @@ -328,11 +351,16 @@ class _SearchDialogState extends State { repository: widget.semanticRepository ?? SemanticSearchRepository.instance, )..add(const SemanticSearchStarted()); + final book = widget.semanticBook; + if (book != null && _hasOwnBookFacet(book)) { + _semanticBloc!.add(const SemanticCoveredBooksRequested()); + } // מצב מבוקש במפורש (קיצור חיפוש מתקדם, איתור) וכרטיסייה בעריכה // גוברים על זיכרון הסשן. _semanticSelected = _editedSemanticTab != null || (SearchDefaults.initialSemanticForNewSearch() && + widget.semanticBook == null && widget.initialSearchMode == null && widget.existingTab == null && widget.editTab == null); @@ -385,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); @@ -1054,8 +1092,8 @@ class _SearchDialogState extends State { UiSnack.showError(LibraryMessages.searchIndexMissing); return; } - if (_isSemanticActive) { - _performSemanticSearch(); + if (_isSemanticActive || _editedSemanticTab?.lockedBookFacet != null) { + unawaited(_performSemanticSearch()); return; } @@ -1249,9 +1287,10 @@ class _SearchDialogState extends State { /// בלי הסכמה או בלי נתונים אין חיפוש; הדיאלוג עצמו אינו רושם דבר. Library? get _library => context.read().state.library; - void _performSemanticSearch() { + Future _performSemanticSearch() async { final availability = _semanticBloc?.state.availability; if (_semanticSubmitted || + _pendingCoverageQuery != null || availability == null || !canRunSemanticSearch( availability, @@ -1259,45 +1298,120 @@ class _SearchDialogState extends State { )) { return; } - final library = _library; - final parsedCategory = parseCategoryQuery( - _searchTab.queryController.text, - library, - ); - if (parsedCategory.hasCategoryToken && !parsedCategory.categoryFound) { + final book = widget.semanticBook; + 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 selection = parsedCategory.categoryFound - ? [ - ...parsedCategory.facets!, - ...FacetHelper.dimensionFacetsOf(_scopeSelection), - ] - : _scopeSelection; - if (!selection.every( - (facet) => isSemanticScopeFacetSupported( - facet, - includeLexical: _semanticIncludeLexical, - isOfficialCategory: isOfficialCategory, - ), - )) { + 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; } + 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; + } + } + _submitSemanticSearch( + query, + semanticScopeFacets(selection), + lockedBookFacet: bookFacet, + ); + } + + void _cancelPendingSemanticSubmit() { + if (_pendingCoverageQuery == null) return; + _semanticSubmitRevision++; + setState(() => _pendingCoverageQuery = null); + } + + // PDF שה-id שלו שאול מספר הטקסט המקביל חולק איתו את ה-facet באינדקס, + // ולכן אי אפשר לצמצם את החיפוש אליו בלבד. + static bool _hasOwnBookFacet(Book book) => + book is! PdfBook || + book.id == null || + BookIdentity.indexedFilePath(book) == BookIdentity.keyOf(book); + + void _submitSemanticSearch( + String query, + List facets, { + String? lockedBookFacet, + }) { _semanticSubmitted = true; - _existingTabHandedOff = true; - SearchDefaults.rememberSessionSemantic(true); + _existingTabHandedOff = !widget.returnResultOnSubmit; + if (lockedBookFacet == null) SearchDefaults.rememberSessionSemantic(true); final options = SemanticQueryOptions( query: query, - facets: semanticScopeFacets(selection), + facets: facets, includeLexical: _semanticIncludeLexical, groupIdenticalText: _semanticGroupIdentical, ); @@ -1307,7 +1421,11 @@ class _SearchDialogState extends State { edited.submit(options); return; } - final tab = SemanticSearchTab(runOnFirstShow: true, options: options); + final tab = SemanticSearchTab( + runOnFirstShow: true, + options: options, + lockedBookFacet: lockedBookFacet, + ); final tabsBloc = context.read(); final navigationBloc = context.read(); Navigator.of(context).pop(); @@ -1349,9 +1467,20 @@ class _SearchDialogState extends State { queryController: _searchTab.queryController, queryFocusNode: _searchTab.searchFieldFocusNode, scopeSelection: _scopeSelection, - onScopeChanged: _onScopeChanged, + 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) { @@ -1360,6 +1489,7 @@ class _SearchDialogState extends State { }, groupIdenticalText: _semanticGroupIdentical, onGroupIdenticalTextChanged: (value) { + _cancelPendingSemanticSubmit(); setState(() => _semanticGroupIdentical = value); if (widget.editTab == null) { SearchDefaults.saveSemanticGroupIdenticalDefault(value); @@ -1490,6 +1620,7 @@ class _SearchDialogState extends State { } void _onScopeChanged(Set selection) { + _cancelPendingSemanticSubmit(); setState(() { _scopeSelection = selection; _historyResultFilter = null; @@ -1562,9 +1693,15 @@ class _SearchDialogState extends State { } void _onModeChoice(_ModeChoice choice) { + _cancelPendingSemanticSubmit(); final mode = choice.mode; - SearchDefaults.rememberSessionSemantic(mode == null); + if (widget.semanticBook == null) { + SearchDefaults.rememberSessionSemantic(mode == null); + } if (mode == null) { + if (!_semanticIncludeLexical && widget.semanticBook == null) { + _semanticBloc?.add(const SemanticCoveredBooksRequested()); + } setState(() => _semanticSelected = true); } else { _semanticSelected = false; @@ -1976,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, + ), ), ); }, @@ -2008,6 +2150,7 @@ class _SearchDialogState extends State { ? context.settingsText('עדכן חיפוש') : context.settingsText('חפש'), icon: FluentIcons.search_24_regular, + isLoading: _pendingCoverageQuery != null, onPressed: blocked || semanticBlocked ? null : _performSearch, ), ); @@ -2105,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 926604af78..4f81790d5d 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; @@ -168,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 9e055a52d9..de16234c33 100644 --- a/lib/semantic_search/bloc/semantic_search_bloc.dart +++ b/lib/semantic_search/bloc/semantic_search_bloc.dart @@ -16,6 +16,8 @@ class SemanticSearchBloc extends Bloc { final SemanticSearchRepository repository; StreamSubscription? _subscription; + bool _coverageWanted = false; + int _coverageRequest = 0; SemanticSearchBloc({required this.repository}) : super( @@ -49,15 +51,33 @@ 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 { + 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)); } Future _onStarted( @@ -69,6 +89,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..882b6c29fa 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,16 @@ class SemanticSearchState extends Equatable { SemanticModelChoice? modelChoice, SemanticModelChoice? activeModelChoice, bool? isRemoving, + 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 != null + ? coveredBookFilePaths() + : this.coveredBookFilePaths, ); @override @@ -39,5 +47,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..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,35 @@ 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, { + 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, + recoveredFromPrevious: covered.recoveredFromPrevious, + ); + }); + @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..88b27310bc 100644 --- a/lib/semantic_search/engine/semantic_engine_backend.dart +++ b/lib/semantic_search/engine/semantic_engine_backend.dart @@ -41,6 +41,15 @@ abstract interface class SemanticEngineBackend { required SemanticCancelHandle cancel, }); + /// מזהה זול של דור וקטורים תקין; null כשאי אפשר לאמת מטמון קודם. + Future coveredBooksStamp(String vectorsDir); + + /// הספרים באינדקס הפתוח שיש להם וקטורים בסט; מעבר על כל האינדקס. + Future coveredBooks( + String vectorsDir, { + required SemanticCancelHandle cancel, + }); + /// פותח את הסט והמודל לקריאה ומחזיר את המצב שאחרי הפתיחה. Future open(SemanticOpenRequest request); @@ -108,6 +117,15 @@ class UnavailableSemanticEngineBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) => Future.error(_unavailable); + @override + Future coveredBooksStamp(String vectorsDir) async => null; + + @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..ff5a583091 100644 --- a/lib/semantic_search/models/semantic_engine_models.dart +++ b/lib/semantic_search/models/semantic_engine_models.dart @@ -223,6 +223,24 @@ class SemanticCoverageSummary extends Equatable { ]; } +/// הספרים שהסט מכסה (`semanticCoveredBooks`), לפי ה-filePath שלהם באינדקס. +class SemanticCoveredBooksSummary extends Equatable { + final List filePaths; + + /// משתנה בכל שינוי במה שהסט מגיש; להשוואה בלבד. + final String setKey; + final bool recoveredFromPrevious; + + const SemanticCoveredBooksSummary({ + required this.filePaths, + required this.setKey, + this.recoveredFromPrevious = false, + }); + + @override + List get props => [filePaths, setKey, recoveredFromPrevious]; +} + /// בקשת פתיחה של סט הוקטורים והמודל (`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..3cdc9d2a94 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'; @@ -51,15 +52,22 @@ List semanticScopeFacets(Iterable selection) { return facets..sort(); } +/// האם יש בבחירה ספר או קטגוריה שדורשים בדיקת כיסוי. +bool needsSemanticScopeCoverage(Iterable selection) => selection.any( + (facet) => facet != '/' && !FacetHelper.isDimensionFacet(facet), +); + /// האם facet של ספר או קטגוריה נתמך, לפני נרמול של בחירת כל הספרייה. 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 +100,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..14c0b7ca0c 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; @@ -175,6 +179,7 @@ class SemanticSearchRepository { _jobCancel.cancel(); await _job; await _settings.setModelChoice(value); + _invalidateCoveredBooks(); await _settings.setSkippedVectorsRelease(null); _lastFailure = null; _unpublishedVersion = null; @@ -250,6 +255,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 +552,80 @@ 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 { + final current = _availability.isUsable ? _availability : await refresh(); + if (!current.isUsable || _moveInProgress || !_isConsentGranted()) { + return null; + } + for (var attempt = 0; attempt < 2 && !cancel.isCancelled; attempt++) { + final epoch = _coveredEpoch; + 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 && + stamp.vectors != null && + previous?.cacheable == true && + previous?.stamp == stamp) { + return previous!.filePaths; + } + _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, + ); + _coveredValid = true; + return paths; + } + return null; + } catch (error, stackTrace) { + _coveredValid = false; + if (error is! SemanticFailure || + error.kind != SemanticFailureKind.cancelled) { + _log('coveredBooks', error, stackTrace); + } + return null; + } finally { + _activeSearches.remove(cancel); + } + } + + Future<_CoverageStamp> _coverageStamp(String directory) async => ( + directory: directory, + index: await _indexStamp(), + vectors: await _backend.coveredBooksStamp(directory), + ); + + void _invalidateCoveredBooks() { + _coveredEpoch++; + _coveredValid = false; + } + /// תמונת המנוע לטלמטריה: מצב, זהות המודל, החבילה והוקטורים המותקנים. Future engineSnapshot() async { final status = await _safeStatus(); @@ -778,7 +861,11 @@ class SemanticSearchRepository { bool waitForOpening = true, bool invalidateOpening = true, }) async { - if (invalidateOpening) _lifecycleEpoch++; + // הסגירה שבתוך פתיחה אינה משנה את הסט; סגירה מבחוץ (מחיקה, העברה) כן. + if (invalidateOpening) { + _lifecycleEpoch++; + _invalidateCoveredBooks(); + } final wasOpen = _openQuantization != null; _openQuantization = null; _passageModelVerification = null; @@ -1429,6 +1516,7 @@ class SemanticSearchRepository { } _needsRepair = false; if (repair) _lastFailure = null; + _invalidateCoveredBooks(); _vectors = await _backend.vectorsInfo(paths.vectorsDirectory); return true; } @@ -1450,6 +1538,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 +2030,10 @@ class SemanticSearchRepository { ); } + /// משתנה בכל שינוי בתוכן האינדקס הלקסיקלי, שגם בו תלוי הכיסוי. + static Future _defaultIndexStamp() async => + (await TantivyDataProvider.instance.engine).searchSnapshot(); + static Future _defaultLibraryVersion() async => int.tryParse(await DataCollectionService().readLibraryVersion()); @@ -1949,6 +2042,23 @@ class SemanticSearchRepository { } } +/// תשובת הכיסוי האחרונה, והמצב של הסט והאינדקס שהיא נכונה להם. +class _CoveredBooks { + const _CoveredBooks({ + required this.setKey, + required this.stamp, + required this.cacheable, + required this.filePaths, + }); + + final String setKey; + 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_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..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'; @@ -31,6 +32,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'; @@ -72,11 +74,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(); @@ -99,6 +105,9 @@ class _SemanticSearchResultsScreenState int _freshnessResultCount = 0; int _previewRequestId = 0; + /// צמצום שממתין לספרים המכוסים מוחלף בצמצום שאחריו. + int _narrowRequestId = 0; + /// התוצאה שבתצוגה המקדימה; קובע אם להדגיש מילים בספר. SemanticResultItem? _previewItem; @@ -147,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), @@ -161,45 +172,71 @@ class _SemanticSearchResultsScreenState List get _currentFacets => _bloc.state.options?.facets ?? widget.tab.options.facets; - void _narrow(List categories, List dimensions) { - final scope = FacetHelper.categoryFacetsOf(widget.tab.options.facets); + Future _narrow(List categories, List dimensions) async { + 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 isOfficialCategory = officialCategoryFilter( - context.read().state.library, - ); - if (!selection.every( - (facet) => isSemanticScopeFacetSupported( - facet, - includeLexical: widget.tab.options.includeLexical, - isOfficialCategory: isOfficialCategory, - ), - )) { - UiSnack.showError(SemanticSearchMessages.unsupportedScope); - return; + final request = ++_narrowRequestId; + 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) { 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()), + ); } /// ספירה לפי קטגוריה של התוצאות שמוצגות כעת. @@ -546,7 +583,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/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/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/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/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/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..96157f86c4 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; @@ -101,6 +122,7 @@ class _FakeEngine implements SearchEngine { required bool matchNikud, required bool matchTaamim, SemanticRankingOptions? ranking, + List? votes, required SemanticCancellationToken cancellation, }) async { this.ranking = ranking; @@ -202,6 +224,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 new file mode 100644 index 0000000000..435e03a4ab --- /dev/null +++ b/test/semantic_search/in_book_semantic_search_dialog_test.dart @@ -0,0 +1,415 @@ +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(), + ); + + Set? covered; + + /// כשמוגדר, התשובה מגיעה רק כשהוא מושלם. + Completer? answerGate; + 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 { + await answerGate?.future; + return 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, + _CoveredRepository repository, + List results, + }) + > + pumpInBookDialog( + WidgetTester tester, + Set? covered, { + bool inBook = true, + Completer? answerGate, + Book? openBook, + }) 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)..answerGate = answerGate; + + 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: (openBook ?? book).title, + returnResultOnSubmit: true, + semanticBook: openBook ?? 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, + repository: repository, + results: results, + ); + } + + testWidgets('ספר עם וקטורים: המצב החכם מוצע, אבל לא נבחר מעצמו', ( + tester, + ) async { + SearchDefaults.rememberSessionSemantic(true); + await pumpInBookDialog(tester, coveredBook); + expect(_semanticSegment, findsOneWidget); + 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 { + 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]); + expect(tab.lockedBookFacet, bookFacet); + verify( + () => harness.navigation.add(const NavigateToScreen(Screen.search)), + ).called(1); + expect(harness.results, [null]); + 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, + 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]); + }); + }); + + 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 new file mode 100644 index 0000000000..b1e2a35d8f --- /dev/null +++ b/test/semantic_search/semantic_covered_books_test.dart @@ -0,0 +1,310 @@ +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/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'; + +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, isNot(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('שינוי דור וקטורים מכלי חיצוני מחשב מחדש גם באותו אינדקס', () 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() + ..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); + }); + + 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'}); + }); + + 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'}); + }); + + 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_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_results_screen_test.dart b/test/semantic_search/semantic_results_screen_test.dart index 843c57c8fe..425c9934e0 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 @@ -173,11 +177,13 @@ void main() { utils.HolyNameStyle? holyNameStyle, FakeResultsSource? injectedSource, SemanticQueryOptions? initialOptions, + String? lockedBookFacet, Library? library, Stream libraryStates = const Stream.empty(), double? paneWidth, bool platformSupported = true, IndexingBloc? indexingBloc, + SemanticSearchRepository? semanticRepository, }) async { if (library != null) { DataRepository.instance.library = Future.value(library); @@ -193,6 +199,7 @@ void main() { final tab = SemanticSearchTab( runOnFirstShow: runOnFirstShow, options: initialOptions ?? SemanticQueryOptions(query: query), + lockedBookFacet: lockedBookFacet, createResultsBloc: (_) => buildResultsBloc( source: source, recorder: recorder, @@ -248,6 +255,7 @@ void main() { child: SemanticSearchResultsScreen( tab: tab, platformSupported: platformSupported, + semanticRepository: semanticRepository, ), ), ), @@ -1122,6 +1130,106 @@ 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 repository = _LateCoverageRepository({'uid:4'}); + final harness = await pumpScreen( + tester, + library: library, + initialOptions: const SemanticQueryOptions( + query: 'כבוד אב', + includeLexical: false, + ), + semanticRepository: repository, + ); + 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)]); + + 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); + + 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)', ( tester, ) async { @@ -1199,3 +1307,25 @@ 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; + Completer? gate; + + @override + Set? get coveredBookFilePaths => null; + + @override + Future?> loadCoveredBookFilePaths() async { + await gate?.future; + return covered; + } +} diff --git a/test/semantic_search/semantic_search_dialog_test.dart b/test/semantic_search/semantic_search_dialog_test.dart index 8dc13ccc29..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; @@ -104,6 +105,12 @@ class _FakeRepository extends SemanticSearchRepository { @override Future cancelDownload() async => cancels++; + + @override + Future?> loadCoveredBookFilePaths() async { + await coverageGate?.future; + return null; + } } SemanticAvailability _availability( @@ -679,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 39b000bdef..c59117e484 100644 --- a/test/semantic_search/semantic_test_support.dart +++ b/test/semantic_search/semantic_test_support.dart @@ -221,6 +221,32 @@ class FakeBackend implements SemanticEngineBackend { required SemanticCancelHandle cancel, }) async => throw UnimplementedError(); + /// מה [coveredBooks] מחזיר; `null` = כשל. + 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 answer ?? + (throw const SemanticFailure(SemanticFailureKind.artifactMissing)); + } + @override Future open(SemanticOpenRequest request) async { calls.add('open'); @@ -419,6 +445,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 +465,7 @@ SemanticSearchRepository buildRepository({ (_) async => DiskSpaceInfo(volumeId: 'C', freeBytes: freeBytes), modelReleases: modelReleases ?? testModelReleases, busyRetryDelay: busyRetryDelay, + indexStamp: indexStamp ?? () async => 'index', ); }