diff --git a/apps/app_macos/assets/translations/fr.json b/apps/app_macos/assets/translations/fr.json index 8f205b9c..452c0f75 100644 --- a/apps/app_macos/assets/translations/fr.json +++ b/apps/app_macos/assets/translations/fr.json @@ -85,6 +85,27 @@ }, "coach": { "empty": "Vos retours d'anglais, réunion par réunion, s'afficheront ici. En attendant, ouvrez une note et choisissez « Coach anglais ».", + "unanalyzed": "Une partie de la réunion n'a pas été analysée.", + "corrections": { + "one": "{} correction", + "other": "{} corrections" + }, + "no_correction": "Aucune correction", + "nothing_to_analyse": "Rien en anglais à analyser", + "recurring": { + "title": "Erreurs récurrentes", + "notes": { + "one": "dans {} note", + "other": "dans {} notes" + } + }, + "live": { + "option": "Coach en direct", + "description": "Corrige votre anglais pendant la réunion, par le service en ligne choisi.", + "unavailable": "Nécessite un service en ligne autorisé : en local, la transcription ralentirait.", + "state_unavailable": "Coach en direct indisponible", + "waiting": "Vos corrections s'afficheront ici." + }, "category": { "grammar": "Grammaire", "conjugation": "Conjugaison", diff --git a/apps/app_macos/lib/application/services/live_coach/live_coach.service.dart b/apps/app_macos/lib/application/services/live_coach/live_coach.service.dart new file mode 100644 index 00000000..1eeab56d --- /dev/null +++ b/apps/app_macos/lib/application/services/live_coach/live_coach.service.dart @@ -0,0 +1,187 @@ +import 'dart:async'; + +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_foundation/logging/logger.dart'; +import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart' + show LiveAnswerModel; +import 'package:ici_transcript/application/services/llm/meeting_ai.dart'; +import 'package:rxdart/rxdart.dart'; + +/// Écart minimal entre deux requêtes du coach en direct. +const Duration kLiveCoachInterval = Duration(seconds: 20); + +/// Ce que le coach en direct a trouvé pendant la note [sessionId]. +class LiveCoachSnapshot { + /// Crée un instantané. + const LiveCoachSnapshot({ + this.sessionId, + this.corrections = const [], + this.unavailable = false, + }); + + /// Note concernée ; null avant le premier démarrage. + final String? sessionId; + + /// Corrections, dans l'ordre où elles ont été trouvées. + final List corrections; + + /// Dernier lot non envoyé (pas de fournisseur en ligne) ou en échec. + final bool unavailable; +} + +/// Coach anglais EN DIRECT : les phrases anglaises finales de l'utilisateur +/// partent par lots, au plus une requête par [interval] (la première sans +/// attendre), et seulement vers un fournisseur en ligne : une génération +/// locale ralentit la transcription (1,8 s → 6–24 s mesurés). +/// +/// Ne bloque jamais la transcription : [onSegmentFinalized] est synchrone, +/// un échec ne fait que poser `unavailable`, ses phrases restent pour la +/// passe d'après l'appel (pas dans [coachedSegmentIds]). +class LiveCoachService { + /// Crée le service ; le modèle est relu à chaque lot. + LiveCoachService({ + required Future Function() resolveModel, + this.interval = kLiveCoachInterval, + }) : _resolveModel = resolveModel; + + final Future Function() _resolveModel; + + /// Écart minimal entre deux requêtes. + final Duration interval; + + final Log _log = Log.named('LiveCoachService'); + final BehaviorSubject _subject = + BehaviorSubject.seeded(const LiveCoachSnapshot()); + final List _pending = []; + final Set _coached = {}; + + bool _running = false; + bool _busy = false; + Timer? _cooldown; + StreamSubscription? _request; + int _run = 0; + + /// Dernier état publié. + LiveCoachSnapshot get snapshot => _subject.value; + + /// [snapshot] à chaque changement. + Stream get snapshots => _subject.stream; + + /// Phrases déjà corrigées en direct (la passe d'après l'appel les saute). + Set get coachedSegmentIds => Set.unmodifiable(_coached); + + /// Ouvre la note [sessionId] : l'état précédent est oublié. + void start(String sessionId) { + _halt(); + _coached.clear(); + _running = true; + _subject.add(LiveCoachSnapshot(sessionId: sessionId)); + } + + /// Ferme la note : la requête en vol est abandonnée, ce qui a été trouvé + /// reste lisible jusqu'au prochain [start]. + Future stop() async => _halt(); + + /// Libère le service (fin de l'app). + Future dispose() async { + _halt(); + await _subject.close(); + } + + /// Phrase finale d'une des deux sources ; seules les phrases anglaises de + /// l'utilisateur sont gardées. + void onSegmentFinalized(TranscriptSegmentEntity segment) { + if (!_running || !isCoachable(segment)) return; + _pending.add(segment); + _flush(); + } + + void _halt() { + _running = false; + _run++; + _cooldown?.cancel(); + _cooldown = null; + unawaited(_request?.cancel()); + _request = null; + _busy = false; + _pending.clear(); + } + + void _flush() { + if (!_running || _busy || _cooldown != null || _pending.isEmpty) return; + final List batch = coachBatches(_pending).first; + final Set ids = batch.map((CoachLine l) => l.id).toSet(); + _pending.removeWhere((TranscriptSegmentEntity s) => ids.contains(s.id)); + _busy = true; + _cooldown = Timer(interval, () { + _cooldown = null; + _flush(); + }); + unawaited(_send(batch, ++_run)); + } + + Future _send(List batch, int run) async { + final LiveAnswerModel? model; + try { + model = await _resolveModel(); + } on Object catch (e) { + return _done(run, error: e); + } + if (run != _run) return; + if (model == null || model.isLocal) { + // Rien ne part : le modèle local ralentirait la transcription. + return _done(run, error: 'aucun fournisseur en ligne'); + } + final StringBuffer raw = StringBuffer(); + _request = model.provider + .streamChat(coachRequest(batch, preferLowLatency: true)) + .listen( + raw.write, + onError: (Object e) => _done(run, error: e), + onDone: () { + try { + final EnglishFeedbackEntity found = parseFeedback('$raw'); + _done(run, batch: batch, found: found); + } on Object catch (e) { + _done(run, error: e); + } + }, + cancelOnError: true, + ); + } + + void _done( + int run, { + List? batch, + EnglishFeedbackEntity? found, + Object? error, + }) { + if (run != _run) return; + _request = null; + _busy = false; + final LiveCoachSnapshot s = snapshot; + if (error != null) { + _log.warning('Coach en direct indisponible : $error'); + _subject.add( + LiveCoachSnapshot( + sessionId: s.sessionId, + corrections: s.corrections, + unavailable: true, + ), + ); + } else { + _coached.addAll(batch!.map((CoachLine l) => l.id)); + _subject.add( + LiveCoachSnapshot( + sessionId: s.sessionId, + corrections: [ + ...s.corrections, + ...timedCorrections(found!, batch), + ], + ), + ); + } + _flush(); + } +} diff --git a/apps/app_macos/lib/application/services/llm/meeting_ai.dart b/apps/app_macos/lib/application/services/llm/meeting_ai.dart index cde40969..fcd52898 100644 --- a/apps/app_macos/lib/application/services/llm/meeting_ai.dart +++ b/apps/app_macos/lib/application/services/llm/meeting_ai.dart @@ -1,7 +1,11 @@ import 'dart:convert'; import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/transcript_grouping.dart' + show isTranscriptMarker; /// Borne d'une requête : consignes + messages, en caractères (le modèle /// local tourne avec un contexte borné). @@ -125,25 +129,254 @@ Future coachEnglish( return parseFeedback(answer); } -/// Lit le retour du coach dans [answer]. +/// Lit le retour du coach dans [answer] : seul lecteur, pour tous les +/// fournisseurs. +/// +/// Objet JSON (entouré de texte ou d'un bloc ```json) ou liste de +/// corrections : lu. Pas de JSON mais une phrase « rien à corriger » (un +/// petit modèle respecte rarement le contrat) : retour vide. Sinon (vide, +/// texte sans rapport, JSON coupé, objet d'une autre forme) : +/// [LlmMalformedAnswerException]. EnglishFeedbackEntity parseFeedback(String answer) { - final int start = answer.indexOf('{'); - final int end = answer.lastIndexOf('}'); - if (start < 0 || end <= start) throw const LlmMalformedAnswerException(); + final Object? json = _firstJson(answer); try { - final Object? json = jsonDecode(answer.substring(start, end + 1)); - // Un objet sans les champs attendus (`{}`, autre forme) n'est pas un - // retour vide valable. - if (json is! Map || - (json['overall'] is! String && json['corrections'] is! List) || - (json['overall'] != null && json['overall'] is! String) || - (json['corrections'] != null && json['corrections'] is! List)) { - throw const LlmMalformedAnswerException(); + if (json is List) { + return EnglishFeedbackEntity( + corrections: [ + for (final Object? c in json) + EnglishCorrectionEntity.fromJson(c! as Map), + ], + ); + } + if (json is Map) { + // Un objet sans les champs attendus (`{}`, autre forme) n'est pas un + // retour vide valable. + if ((json['overall'] is! String && json['corrections'] is! List) || + (json['overall'] != null && json['overall'] is! String) || + (json['corrections'] != null && json['corrections'] is! List)) { + throw const LlmMalformedAnswerException(); + } + return EnglishFeedbackEntity.fromJson(json); } - return EnglishFeedbackEntity.fromJson(json); } on Object { throw const LlmMalformedAnswerException(); } + if (_nothingToCorrect.hasMatch(answer)) return const EnglishFeedbackEntity(); + throw const LlmMalformedAnswerException(); +} + +/// JSON de [answer] : la liste si elle s'ouvre avant l'objet et se lit +/// (« [] », liste de corrections), sinon l'objet ; null si aucun. Un objet +/// illisible (coupé) rend un objet vide, donc une réponse illisible. +Object? _firstJson(String answer) { + final int brace = answer.indexOf('{'); + final int bracket = answer.indexOf('['); + if (bracket >= 0 && (brace < 0 || bracket < brace)) { + final Object? list = _decode(answer, bracket, answer.lastIndexOf(']')); + if (list is List) return list; + } + final int end = answer.lastIndexOf('}'); + if (brace < 0 || end <= brace) return null; + return _decode(answer, brace, end) ?? const {}; +} + +Object? _decode(String text, int start, int end) { + if (end <= start) return null; + try { + return jsonDecode(text.substring(start, end + 1)); + } on FormatException { + return null; + } +} + +final RegExp _nothingToCorrect = RegExp( + r"rien à corriger|aucune (correction|erreur|faute)|pas d'erreur|" + r'no (corrections?|mistakes?|errors?)\b|nothing to correct|' + r'\bis (perfectly |already |entirely )?correct\b', + caseSensitive: false, +); + +/// Une phrase à corriger : segment (ou morceau d'un segment trop long), +/// texte, heure dans la note. +typedef CoachLine = ({String id, String text, int atMs}); + +/// Phrase que le coach peut corriger : dite au micro par l'utilisateur, pas +/// un repère, en anglais (règle de [isSpokenEnglish]). +bool isCoachable(TranscriptSegmentEntity s) => + s.source == AudioSource.input && + !isTranscriptMarker(s.text) && + isSpokenEnglish(s.text); + +/// Anglais : au moins un mot-outil anglais et au plus UN mot-outil +/// français. Un seul ne suffit pas à écarter une phrase : sigles (« EST », +/// « LE »), noms et marques (« La Poste », « du Pont », « Le Monde »), +/// homographes (« pour me a coffee », « Des will… ») ; le franglais en a +/// deux (« On fait le call… »). « on », « a » ne comptent pas comme +/// français. Pas de veto par `questionLanguage` : un accent (« Hélène ») +/// le fait pencher vers le français. « OK », « yes », « exactly » sont des +/// interjections, pas des mots-outils. +// ponytail: listes de mots fréquents ; un vrai détecteur si une 3e langue +// arrive. +bool isSpokenEnglish(String text) { + final List words = text + .toLowerCase() + .split(RegExp(r"[^\p{L}']+", unicode: true)) + .expand((String w) => w.split("'")) + .where((String w) => w.isNotEmpty) + .toList(); + return words.any(_englishFunctionWords.contains) && + words.where(_frenchFunctionWords.contains).length < 2; +} + +const Set _englishFunctionWords = { + 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her', 'us', // + 'them', 'my', 'your', 'his', 'its', 'our', 'their', 'this', 'that', // + 'these', 'those', 'the', 'a', 'an', 'am', 'is', 'are', 'was', 'were', // + 'be', 'been', 'do', 'does', 'did', 'have', 'has', 'had', 'will', // + 'would', 'can', 'could', 'should', 'shall', 'may', 'might', 'must', // + 'of', 'to', 'in', 'on', 'at', 'for', 'with', 'from', 'by', 'about', // + 'so', 'but', 'and', 'or', 'if', 'not', 'there', 'what', 'how', 'why', // + 'when', 'where', 'who', 'which', // +}; + +// Sans les homographes anglais (« on », « a », « as », « son », « car », +// « ai »…). +const Set _frenchFunctionWords = { + 'le', 'la', 'les', 'de', 'des', 'du', 'un', 'une', 'est', 'et', 'que', // + 'qui', 'quel', 'quelle', 'quels', 'quelles', 'combien', 'comment', // + 'pourquoi', 'quand', 'je', 'tu', 'il', 'elle', 'ils', 'elles', 'nous', // + 'vous', 'ce', 'ça', 'pour', 'sur', 'avec', 'dans', 'en', 'pas', 'ne', // + 'mais', 'ou', 'donc', 'au', 'aux', 'se', 'sa', 'ses', 'mon', 'ma', // + 'mes', 'ton', 'ta', 'notre', 'votre', 'leur', 'qu', 'fait', 'faire', // + 'suis', 'sont', 'va', 'vais', 'très', 'oui', 'voilà', // +}; + +/// Phrases corrigeables de [segments], hors [skip] (déjà corrigées en +/// direct). +List coachableLines( + List segments, { + Set skip = const {}, +}) => [ + for (final TranscriptSegmentEntity s in segments) + if (!skip.contains(s.id) && isCoachable(s)) s, +]; + +/// Lots de [lines] : chaque requête tient dans [kLlmMaxRequestChars] +/// (consignes comprises), chaque phrase dans exactement un lot ; une phrase +/// plus longue que la place est coupée en morceaux. +List> coachBatches(List lines) { + final int room = _room(_coachSystem, _coachPrefix); + final List> batches = >[]; + List current = []; + int used = 0; + for (final TranscriptSegmentEntity s in lines) { + final String text = s.text.trim(); + for (int i = 0; i < text.length; i += room) { + final String part = text.substring(i, (i + room).clamp(0, text.length)); + final int cost = part.length + (current.isEmpty ? 0 : 1); + if (used + cost > room) { + batches.add(current); + current = []; + used = 0; + } + used += part.length + (current.isEmpty ? 0 : 1); + current.add((id: s.id, text: part, atMs: s.timestampMs)); + } + } + if (current.isNotEmpty) batches.add(current); + return batches; +} + +/// Requête du coach pour [batch] ; [preferLowLatency] seulement en direct. +LlmChatRequest coachRequest( + List batch, { + bool preferLowLatency = false, +}) => LlmChatRequest( + systemPrompt: _coachSystem, + messages: [ + LlmMessage( + role: LlmRole.user, + content: '$_coachPrefix${batch.map((CoachLine l) => l.text).join('\n')}', + ), + ], + maxTokens: kLlmAnswerMaxTokens, + preferLowLatency: preferLowLatency, +); + +/// Corrections de [feedback], chacune à l'heure de la phrase de [batch] qui +/// contient son `original` (sinon sans heure). +List timedCorrections( + EnglishFeedbackEntity feedback, + List batch, +) => [ + for (final EnglishCorrectionEntity c in feedback.corrections) + c.copyWith(timestampMs: _timeOf(c.original, batch)), +]; + +int? _timeOf(String original, List batch) { + final String needle = original.trim().toLowerCase(); + if (needle.isEmpty) return null; + for (final CoachLine l in batch) { + if (l.text.toLowerCase().contains(needle)) return l.atMs; + } + return null; +} + +/// Coach anglais d'une note : phrases corrigeables de [segments] (hors +/// [skipSegmentIds]), par lots bornés, l'un après l'autre (le modèle local +/// ne sert qu'une requête à la fois). +/// +/// Un lot en échec ne fait pas tout échouer : ses phrases vont dans +/// `unanalyzedSegmentIds`. Tous en échec : l'erreur du dernier remonte. +/// Rien à corriger : retour vide, aucune requête. +/// +/// [shouldStop] est lu avant chaque lot : vrai (un enregistrement démarre, +/// une génération locale retarderait sa transcription), le lot en cours a +/// fini et compte, le reste est noté non analysé, sans erreur. +Future coachMeeting( + LlmProvider llm, + List segments, { + Set skipSegmentIds = const {}, + bool Function()? shouldStop, +}) async { + if (coachableLines(segments).isEmpty) { + return const EnglishFeedbackEntity(nothingToAnalyse: true); + } + final List> batches = coachBatches( + coachableLines(segments, skip: skipSegmentIds), + ); + final List corrections = []; + final Set unanalyzed = {}; + String? overall; + Object? lastError; + int failed = 0; + int sent = 0; + for (final List batch in batches) { + if (shouldStop?.call() ?? false) { + unanalyzed.addAll(batch.map((CoachLine l) => l.id)); + continue; + } + sent++; + try { + final EnglishFeedbackEntity part = parseFeedback( + await llm.streamChat(coachRequest(batch)).join(), + ); + corrections.addAll(timedCorrections(part, batch)); + if (overall == null && (part.overall ?? '').isNotEmpty) { + overall = part.overall; + } + } on Object catch (e) { + lastError = e; + failed++; + unanalyzed.addAll(batch.map((CoachLine l) => l.id)); + } + } + if (sent > 0 && failed == sent) throw lastError!; + return EnglishFeedbackEntity( + corrections: corrections, + overall: overall, + unanalyzedSegmentIds: unanalyzed.toList(), + ); } /// Réponse probablement coupée (limite de jetons, refus) : vide, ou @@ -206,3 +439,19 @@ List _split(String text, int room, {String separator = '\n'}) { if (current.isNotEmpty) pieces.add(current); return pieces; } + +/// [kept] puis les corrections de [added] qui n'y sont pas déjà (même +/// original et même correction, casse et blancs ignorés). +List mergeCorrections( + List kept, + List added, +) { + String key(EnglishCorrectionEntity c) => + '${c.original.trim().toLowerCase()}→${c.corrected.trim().toLowerCase()}'; + final Set seen = kept.map(key).toSet(); + return [ + ...kept, + for (final EnglishCorrectionEntity c in added) + if (seen.add(key(c))) c, + ]; +} diff --git a/apps/app_macos/lib/core/providers/services/live_coach.service.provider.dart b/apps/app_macos/lib/core/providers/services/live_coach.service.provider.dart new file mode 100644 index 00000000..5b7f45d4 --- /dev/null +++ b/apps/app_macos/lib/core/providers/services/live_coach.service.provider.dart @@ -0,0 +1,36 @@ +import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart' + show LiveAnswerModel; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/core/providers/services/live_answer_model.provider.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'live_coach.service.provider.g.dart'; + +/// Coach anglais en direct ; démarré et arrêté avec chaque enregistrement +/// (interrupteur activé) par le view model du direct. Même modèle que les +/// réponses en direct ; seul un fournisseur en ligne reçoit les phrases. +@Riverpod(keepAlive: true) +LiveCoachService liveCoachService(Ref ref) { + final LiveCoachService service = LiveCoachService( + resolveModel: () => resolveLiveAnswerModel(ref), + ); + ref.onDispose(service.dispose); + return service; +} + +/// Ce que le coach en direct a trouvé, à chaque changement. +@riverpod +Stream liveCoachSnapshot(Ref ref) => + ref.watch(liveCoachServiceProvider).snapshots; + +/// Le coach en direct peut-il partir ? Seulement vers un fournisseur en +/// ligne configuré et autorisé (même règle que le service). +@riverpod +Future liveCoachAvailable(Ref ref) async { + try { + final LiveAnswerModel? model = await resolveLiveAnswerModel(ref); + return model != null && !model.isLocal; + } on Object { + return false; + } +} diff --git a/apps/app_macos/lib/core/providers/services/live_coach.service.provider.g.dart b/apps/app_macos/lib/core/providers/services/live_coach.service.provider.g.dart new file mode 100644 index 00000000..391b60f8 --- /dev/null +++ b/apps/app_macos/lib/core/providers/services/live_coach.service.provider.g.dart @@ -0,0 +1,154 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'live_coach.service.provider.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Coach anglais en direct ; démarré et arrêté avec chaque enregistrement +/// (interrupteur activé) par le view model du direct. Même modèle que les +/// réponses en direct ; seul un fournisseur en ligne reçoit les phrases. + +@ProviderFor(liveCoachService) +const liveCoachServiceProvider = LiveCoachServiceProvider._(); + +/// Coach anglais en direct ; démarré et arrêté avec chaque enregistrement +/// (interrupteur activé) par le view model du direct. Même modèle que les +/// réponses en direct ; seul un fournisseur en ligne reçoit les phrases. + +final class LiveCoachServiceProvider + extends + $FunctionalProvider< + LiveCoachService, + LiveCoachService, + LiveCoachService + > + with $Provider { + /// Coach anglais en direct ; démarré et arrêté avec chaque enregistrement + /// (interrupteur activé) par le view model du direct. Même modèle que les + /// réponses en direct ; seul un fournisseur en ligne reçoit les phrases. + const LiveCoachServiceProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'liveCoachServiceProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$liveCoachServiceHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + LiveCoachService create(Ref ref) { + return liveCoachService(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(LiveCoachService value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$liveCoachServiceHash() => r'522ac1272d6e0e7b863ba44b874ea4fc5c6dfee8'; + +/// Ce que le coach en direct a trouvé, à chaque changement. + +@ProviderFor(liveCoachSnapshot) +const liveCoachSnapshotProvider = LiveCoachSnapshotProvider._(); + +/// Ce que le coach en direct a trouvé, à chaque changement. + +final class LiveCoachSnapshotProvider + extends + $FunctionalProvider< + AsyncValue, + LiveCoachSnapshot, + Stream + > + with + $FutureModifier, + $StreamProvider { + /// Ce que le coach en direct a trouvé, à chaque changement. + const LiveCoachSnapshotProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'liveCoachSnapshotProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$liveCoachSnapshotHash(); + + @$internal + @override + $StreamProviderElement $createElement( + $ProviderPointer pointer, + ) => $StreamProviderElement(pointer); + + @override + Stream create(Ref ref) { + return liveCoachSnapshot(ref); + } +} + +String _$liveCoachSnapshotHash() => r'c7506664042b627ebc52d14b2bddc6bdb3403e58'; + +/// Le coach en direct peut-il partir ? Seulement vers un fournisseur en +/// ligne configuré et autorisé (même règle que le service). + +@ProviderFor(liveCoachAvailable) +const liveCoachAvailableProvider = LiveCoachAvailableProvider._(); + +/// Le coach en direct peut-il partir ? Seulement vers un fournisseur en +/// ligne configuré et autorisé (même règle que le service). + +final class LiveCoachAvailableProvider + extends $FunctionalProvider, bool, FutureOr> + with $FutureModifier, $FutureProvider { + /// Le coach en direct peut-il partir ? Seulement vers un fournisseur en + /// ligne configuré et autorisé (même règle que le service). + const LiveCoachAvailableProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'liveCoachAvailableProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$liveCoachAvailableHash(); + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return liveCoachAvailable(ref); + } +} + +String _$liveCoachAvailableHash() => + r'9459e164b184a78c186f84225bb53d6720f7d615'; diff --git a/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.dart b/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.dart new file mode 100644 index 00000000..a356434d --- /dev/null +++ b/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.dart @@ -0,0 +1,87 @@ +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/session.entity.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; +import 'package:ici_transcript/application/services/summary.service.dart'; +import 'package:ici_transcript/core/providers/core/repositories/session.repository.provider.dart'; +import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; +import 'package:ici_transcript/features/shared/presentation/widgets/coach_feedback.widget.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'coach_overview.provider.g.dart'; + +/// Une note passée au coach et son retour. +typedef CoachNote = ({SessionEntity session, EnglishFeedbackEntity feedback}); + +/// Une catégorie de correction (telle que rangée) vue dans [notes] notes. +typedef RecurringMistake = ({String category, int notes}); + +/// Page « Coach anglais » : notes passées au coach, erreurs récurrentes. +typedef CoachOverview = ({ + List notes, + List recurring, +}); + +/// Une catégorie est récurrente à partir de ce nombre de notes. +const int kRecurringMinNotes = 3; + +/// Lu à l'ouverture de la page, dans `summaries.content` (pas de +/// migration). Une erreur de lecture se relance à la main (Réessayer). +@Riverpod(retry: _noRetry) +Future coachOverview(Ref ref) async { + final List sessions = await ref + .read(sessionRepositoryProvider) + .getAll(); + final SummaryService summaries = ref.read(summaryServiceProvider); + final List notes = []; + for (final SessionEntity s in sessions) { + final EnglishFeedbackEntity? feedback = SessionAnalysis.fromStored( + await summaries.getSummaryForSession(s.id), + ).feedback; + if (feedback != null) notes.add((session: s, feedback: feedback)); + } + return buildCoachOverview(notes); +} + +Duration? _noRetry(int retryCount, Object error) => null; + +/// Ordre de la page et erreurs récurrentes (règle pure). +/// +/// Jours du plus récent au plus ancien ; dans un jour, les notes avec des +/// corrections d'abord, puis la plus récente. Récurrente : une même +/// catégorie (« grammar » = « Grammaire ») dans [kRecurringMinNotes] notes +/// ou plus, une note comptant une fois. +CoachOverview buildCoachOverview(List notes) { + DateTime dayOf(DateTime t) => DateTime(t.year, t.month, t.day); + final List sorted = [...notes] + ..sort((CoachNote a, CoachNote b) { + final int byDay = dayOf( + b.session.createdAt, + ).compareTo(dayOf(a.session.createdAt)); + if (byDay != 0) return byDay; + final bool aHas = a.feedback.corrections.isNotEmpty; + final bool bHas = b.feedback.corrections.isNotEmpty; + if (aHas != bHas) return aHas ? -1 : 1; + return b.session.createdAt.compareTo(a.session.createdAt); + }); + // Clé commune (« grammar » = « Grammaire ») → nombre de notes, et une + // catégorie telle que rangée, pour l'afficher. + final Map count = {}; + final Map shown = {}; + for (final CoachNote n in notes) { + final Map categories = { + for (final EnglishCorrectionEntity c in n.feedback.corrections) + coachCategoryKey(c.category) ?? c.category.trim().toLowerCase(): + c.category, + }; + categories.forEach((String key, String category) { + count[key] = (count[key] ?? 0) + 1; + shown.putIfAbsent(key, () => category); + }); + } + final List recurring = [ + for (final MapEntry e in count.entries) + if (e.value >= kRecurringMinNotes) + (category: shown[e.key]!, notes: e.value), + ]..sort((RecurringMistake a, RecurringMistake b) => b.notes - a.notes); + return (notes: sorted, recurring: recurring); +} diff --git a/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.g.dart b/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.g.dart new file mode 100644 index 00000000..81d76a0e --- /dev/null +++ b/apps/app_macos/lib/features/coach/presentation/coach_overview.provider.g.dart @@ -0,0 +1,56 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'coach_overview.provider.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Lu à l'ouverture de la page, dans `summaries.content` (pas de +/// migration). Une erreur de lecture se relance à la main (Réessayer). + +@ProviderFor(coachOverview) +const coachOverviewProvider = CoachOverviewProvider._(); + +/// Lu à l'ouverture de la page, dans `summaries.content` (pas de +/// migration). Une erreur de lecture se relance à la main (Réessayer). + +final class CoachOverviewProvider + extends + $FunctionalProvider< + AsyncValue, + CoachOverview, + FutureOr + > + with $FutureModifier, $FutureProvider { + /// Lu à l'ouverture de la page, dans `summaries.content` (pas de + /// migration). Une erreur de lecture se relance à la main (Réessayer). + const CoachOverviewProvider._() + : super( + from: null, + argument: null, + retry: _noRetry, + name: r'coachOverviewProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$coachOverviewHash(); + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return coachOverview(ref); + } +} + +String _$coachOverviewHash() => r'8c6076747f4910fa15713a1418deb5314662efe9'; diff --git a/apps/app_macos/lib/features/coach/presentation/coach_overview.screen.dart b/apps/app_macos/lib/features/coach/presentation/coach_overview.screen.dart new file mode 100644 index 00000000..39ea68ab --- /dev/null +++ b/apps/app_macos/lib/features/coach/presentation/coach_overview.screen.dart @@ -0,0 +1,176 @@ +import 'package:core_presentation/core_presentation.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:ici_transcript/core/providers/platform/now.provider.dart'; +import 'package:ici_transcript/features/coach/presentation/coach_overview.provider.dart'; +import 'package:ici_transcript/features/home/presentation/agenda.dart'; +import 'package:ici_transcript/features/home/presentation/screens/home/home.screen.dart' + show kContentMaxWidth; +import 'package:ici_transcript/features/shared/presentation/widgets/coach_feedback.widget.dart'; +import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; + +/// Page « Coach anglais » : les notes passées au coach (jour par jour, avec +/// leur nombre de corrections), puis les erreurs récurrentes. +class CoachOverviewScreen extends ConsumerWidget { + /// Crée la page ; [onOpen] ouvre une note (sur sa section coach). + const CoachOverviewScreen({required this.onOpen, super.key}); + + /// Ouvre la note d'id donné. + final ValueChanged onOpen; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final AsyncValue async = ref.watch(coachOverviewProvider); + final Widget header = _Column( + child: OatsPageHeader(title: LocaleKeys.nav_coach.tr()), + ); + final CoachOverview? data = async.hasError ? null : async.value; + if (data == null || data.notes.isEmpty) { + return Padding( + padding: const EdgeInsets.symmetric( + horizontal: OatsSpace.xxxl, + vertical: OatsSpace.xl, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + header, + Expanded( + child: async.hasError + ? OatsEmptyState( + icon: Icons.error_outline, + message: LocaleKeys.common_error_generic.tr(), + action: OatsButton( + label: LocaleKeys.common_action_retry.tr(), + onPressed: () => ref.invalidate(coachOverviewProvider), + ), + ) + : data == null + ? const Center(child: CircularProgressIndicator()) + : OatsEmptyState( + icon: Icons.school_outlined, + message: LocaleKeys.coach_empty.tr(), + ), + ), + ], + ), + ); + } + + final Oats o = context.oats; + final DateTime now = ref.watch(nowProvider)(); + final List days = []; + DateTime? day; + for (final CoachNote n in data.notes) { + final DateTime d = DateTime( + n.session.createdAt.year, + n.session.createdAt.month, + n.session.createdAt.day, + ); + if (d != day) { + day = d; + days.add( + Padding( + padding: EdgeInsets.only( + left: OatsSpace.sm, + top: days.isEmpty ? 0 : OatsSpace.xl, + bottom: OatsSpace.xs, + ), + child: Semantics( + header: true, + child: Text(formatDayHeader(d, now: now), style: o.label), + ), + ), + ); + } + final int count = n.feedback.corrections.length; + days.add( + OatsListRow( + title: n.session.title, + trailing: count > 0 + ? LocaleKeys.coach_corrections.plural(count) + : n.feedback.unanalyzedSegmentIds.isNotEmpty + ? LocaleKeys.coach_unanalyzed.tr() + : n.feedback.nothingToAnalyse + ? LocaleKeys.coach_nothing_to_analyse.tr() + : LocaleKeys.coach_no_correction.tr(), + onTap: () => onOpen(n.session.id), + ), + ); + } + + return ListView( + padding: const EdgeInsets.symmetric( + horizontal: OatsSpace.xxxl, + vertical: OatsSpace.xl, + ), + children: [ + header, + const SizedBox(height: OatsSpace.xxl), + _Column( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: days, + ), + ), + if (data.recurring.isNotEmpty) ...[ + const SizedBox(height: OatsSpace.xxl), + _Column( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(left: OatsSpace.sm), + child: OatsSectionHeader( + LocaleKeys.coach_recurring_title.tr(), + ), + ), + for (final RecurringMistake r in data.recurring) + Container( + constraints: const BoxConstraints(minHeight: 44), + padding: const EdgeInsets.symmetric( + horizontal: OatsSpace.sm, + vertical: OatsSpace.sm, + ), + decoration: BoxDecoration( + border: Border(bottom: BorderSide(color: o.line)), + ), + child: Row( + children: [ + Expanded( + child: Text( + coachCategoryLabel(r.category), + style: o.bodyStrong, + ), + ), + Text( + LocaleKeys.coach_recurring_notes.plural(r.notes), + style: o.meta, + ), + ], + ), + ), + ], + ), + ), + ], + ], + ); + } +} + +/// Colonne centrée de largeur de lecture. +class _Column extends StatelessWidget { + const _Column({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) => Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: kContentMaxWidth), + child: child, + ), + ); +} diff --git a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.screen.dart b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.screen.dart index b6c501e7..bca8381a 100644 --- a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.screen.dart +++ b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.screen.dart @@ -31,9 +31,13 @@ class SessionDetailScreen extends ConsumerStatefulWidget { const SessionDetailScreen({ required this.sessionId, required this.onClose, + this.focusCoach = false, super.key, }); + /// Ouvre la note sur sa section « Coach anglais » (page du coach). + final bool focusCoach; + /// Identifiant de la note. final String sessionId; @@ -47,6 +51,20 @@ class SessionDetailScreen extends ConsumerStatefulWidget { class _SessionDetailScreenState extends ConsumerState { final TextEditingController _titleController = TextEditingController(); + final GlobalKey _coachSection = GlobalKey(); + bool _coachFocused = false; + + /// Une fois, dès que la section coach est construite : la faire défiler + /// en haut de la vue. + void _focusCoach() { + if (!widget.focusCoach || _coachFocused) return; + WidgetsBinding.instance.addPostFrameCallback((_) { + final BuildContext? section = _coachSection.currentContext; + if (section == null || _coachFocused || !mounted) return; + _coachFocused = true; + Scrollable.ensureVisible(section); + }); + } SessionDetailViewModel get _vm => ref.read( sessionDetailViewModelProvider(sessionId: widget.sessionId).notifier, @@ -80,12 +98,16 @@ class _SessionDetailScreenState extends ConsumerState { icon: Icons.error_outline, message: LocaleKeys.common_error_generic.tr(), ), - data: (SessionDetailState s) => s.session == null - ? OatsEmptyState( - icon: Icons.description_outlined, - message: LocaleKeys.history_detail_no_session.tr(), - ) - : _content(s, s.session!), + data: (SessionDetailState s) { + if (s.session == null) { + return OatsEmptyState( + icon: Icons.description_outlined, + message: LocaleKeys.history_detail_no_session.tr(), + ); + } + _focusCoach(); + return _content(s, s.session!); + }, ), ), ], @@ -217,6 +239,7 @@ class _SessionDetailScreenState extends ConsumerState { state.feedback != null || state.feedbackError != null) _section( + key: _coachSection, title: LocaleKeys.history_detail_english_coach.tr(), onDelete: state.feedback == null ? null @@ -227,7 +250,12 @@ class _SessionDetailScreenState extends ConsumerState { loadingLabel: LocaleKeys.history_detail_coach_loading.tr(), content: state.feedback == null ? null - : CoachFeedbackView(feedback: state.feedback!), + : CoachFeedbackView( + feedback: state.feedback!, + onRetry: state.isFeedbackLoading + ? null + : _vm.retryUnanalyzed, + ), errorKey: state.feedbackError, ), ), @@ -332,6 +360,7 @@ class _SessionDetailScreenState extends ConsumerState { } Widget _section({ + Key? key, required String title, required Widget child, VoidCallback? onDelete, @@ -339,6 +368,7 @@ class _SessionDetailScreenState extends ConsumerState { }) { final Oats o = context.oats; return Padding( + key: key, padding: const EdgeInsets.only(top: OatsSpace.xxl), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, diff --git a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.dart b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.dart index 8dc0511f..29e4837f 100644 --- a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.dart +++ b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.dart @@ -1,7 +1,6 @@ import 'package:core_domain/domain/entities/english_feedback.entity.dart'; import 'package:core_domain/domain/entities/session.entity.dart'; import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; -import 'package:core_domain/domain/enum/audio_source.enum.dart'; import 'package:core_domain/domain/services/session_history.service.dart'; import 'package:core_domain/domain/usecases/get_session_detail.use_case.dart'; import 'package:core_foundation/logging/logger.dart'; @@ -220,15 +219,67 @@ class SessionDetailViewModel extends _$SessionDetailViewModel { } /// Analyse (a la demande) l'anglais parle de la session, par le - /// fournisseur actif. - Future analyzeEnglish() async { + /// fournisseur actif : phrases anglaises du micro, par lots ; un lot en + /// échec est rangé « non analysé » (la note propose de réessayer). + Future analyzeEnglish() => _coach( + (SessionDetailState s) => s.segments, + (EnglishFeedbackEntity? old, EnglishFeedbackEntity found) => found, + ); + + /// « Réessayer » : seules les phrases non analysées repartent ; leurs + /// corrections s'ajoutent à celles déjà là. + Future retryUnanalyzed() => _coach( + (SessionDetailState s) { + final Set ids = + s.feedback?.unanalyzedSegmentIds.toSet() ?? const {}; + return [ + for (final TranscriptSegmentEntity x in s.segments) + if (ids.contains(x.id)) x, + ]; + }, + (EnglishFeedbackEntity? old, EnglishFeedbackEntity found) => + found.copyWith( + overall: old?.overall ?? found.overall, + corrections: mergeCorrections( + old?.corrections ?? const [], + found.corrections, + ), + ), + ); + + /// Coach sur les segments choisis par [pick] ; le résultat, combiné à + /// l'ancien retour par [combine], est rangé puis affiché. Tout en échec : + /// l'erreur est affichée, rien n'est rangé. + Future _coach( + List Function(SessionDetailState s) pick, + EnglishFeedbackEntity Function( + EnglishFeedbackEntity? old, + EnglishFeedbackEntity found, + ) + combine, + ) async { final SessionDetailState? current = state.value; final SessionEntity? session = current?.session; if (current == null || session == null || current.isFeedbackLoading) return; - // Coach = micro de l'utilisateur UNIQUEMENT (pas l'audio du meeting). - final String transcript = _micTranscript(current); - if (transcript.trim().isEmpty) return; + // Coach = phrases anglaises du micro UNIQUEMENT (pas l'audio du meeting). + final List segments = pick(current); + if (coachableLines(segments).isEmpty) { + // Réessayer sans phrase : rien à faire. Coach sur une note sans + // anglais de l'utilisateur : la note le dit, rien n'est envoyé. + if (current.feedback?.unanalyzedSegmentIds.isNotEmpty ?? false) return; + const EnglishFeedbackEntity nothing = EnglishFeedbackEntity( + nothingToAnalyse: true, + ); + await _store( + session.id, + (SessionAnalysis a) => a.copyWith(feedback: nothing), + ); + return _set( + (SessionDetailState s) => + s.copyWith(feedback: nothing, feedbackError: null), + ); + } _set( (SessionDetailState s) => @@ -242,11 +293,12 @@ class SessionDetailViewModel extends _$SessionDetailViewModel { s.copyWith(isFeedbackLoading: false, llmAvailable: false), ); } - final EnglishFeedbackEntity feedback = await coachEnglish( + final EnglishFeedbackEntity found = await coachMeeting( ready.llm, - transcript, + segments, ); if (!ref.mounted) return; + final EnglishFeedbackEntity feedback = combine(current.feedback, found); // Le coach garde le modele du resume deja range (pas de `model`). await _store( session.id, @@ -318,13 +370,6 @@ class SessionDetailViewModel extends _$SessionDetailViewModel { .map(TranscriptFormatter.plainLine) .join('\n'); - /// Transcript du micro de l'utilisateur uniquement (source input), pour le - /// coach d'anglais : on ne corrige que ce que l'utilisateur a dit. - String _micTranscript(SessionDetailState s) => s.segments - .where((TranscriptSegmentEntity seg) => seg.source == AudioSource.input) - .map((TranscriptSegmentEntity seg) => seg.text) - .join('\n'); - /// Range l'enveloppe stockee modifiee par [change] : on part de la base, /// pas de l'etat affiche (qui peut porter un resume coupe), et on garde /// transcription propre et interlocuteurs. diff --git a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.g.dart b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.g.dart index f8b1b9b8..3432907d 100644 --- a/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.g.dart +++ b/apps/app_macos/lib/features/history/presentation/screens/detail/session_detail.view_model.g.dart @@ -67,7 +67,7 @@ final class SessionDetailViewModelProvider } String _$sessionDetailViewModelHash() => - r'6164f8a69015ca0c952e7dd2e654e566a2cb2ffd'; + r'f5e7a20300e6add9665b84da00b197cdc07da67e'; /// ViewModel de l'ecran de detail d'une session. /// diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.screen.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.screen.dart index fb2c0c05..9628777f 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.screen.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.screen.dart @@ -13,6 +13,8 @@ import 'package:ici_transcript/features/live_transcription/presentation/screens/ import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/server_status.widget.dart'; import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/finalising.widget.dart'; import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/live_answers_panel.widget.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/live_coach_block.widget.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/session_controls.widget.dart'; import 'package:ici_transcript/features/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart'; import 'package:ici_transcript/features/shared/presentation/widgets/coach_feedback.widget.dart'; @@ -120,6 +122,7 @@ class _LiveTranscriptionScreenState children: [ _buildToolbar(state), _buildOptionsBar(state), + ?_liveCoachReason(state), for (final Widget n in notices) Padding( padding: const EdgeInsets.fromLTRB( @@ -193,19 +196,26 @@ class _LiveTranscriptionScreenState Widget _buildOptionsBar(LiveTranscriptionState state) { final Oats o = context.oats; final bool idle = !state.isRecording && !state.isPaused; + Widget group(List children) => + Row(mainAxisSize: MainAxisSize.min, children: children); + // Options groupées : à l'étroit, elles passent à la ligne au lieu de + // sortir de l'écran. return Container( - padding: const EdgeInsets.symmetric(horizontal: OatsSpace.xl), - height: 40, + constraints: const BoxConstraints(minHeight: 40), + padding: const EdgeInsets.symmetric( + horizontal: OatsSpace.xl, + vertical: OatsSpace.xxs, + ), decoration: BoxDecoration( border: Border(bottom: BorderSide(color: o.line)), ), - child: SingleChildScrollView( - scrollDirection: Axis.horizontal, - reverse: true, - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (idle) ...[ + child: Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: OatsSpace.lg, + children: [ + if (idle) ...[ + group([ _optionLabel( Icons.school_outlined, LocaleKeys.transcription_live_coach_option.tr(), @@ -214,7 +224,9 @@ class _LiveTranscriptionScreenState value: state.isCoachEnabled, onChanged: (_) => _vm.toggleCoach(), ), - const SizedBox(width: OatsSpace.lg), + ]), + _liveCoachOption(state), + group([ Tooltip( message: LocaleKeys.transcription_live_speakers_tooltip.tr(), child: _optionLabel( @@ -226,8 +238,9 @@ class _LiveTranscriptionScreenState value: state.isLiveSpeakersEnabled, onChanged: (_) => _vm.toggleLiveSpeakers(), ), - const SizedBox(width: OatsSpace.lg), - ], + ]), + ], + group([ _optionLabel( Icons.translate, LocaleKeys.transcription_live_translation_option.tr(), @@ -249,8 +262,51 @@ class _LiveTranscriptionScreenState value: state.isTranslationEnabled, onChanged: (_) => _vm.toggleTranslation(), ), - ], - ), + ]), + ], + ), + ); + } + + /// « Coach en direct » : disponible seulement avec un fournisseur en + /// ligne configuré et autorisé ; sinon désactivé, et la raison est dite + /// sous les options. + Widget _liveCoachOption(LiveTranscriptionState state) { + final bool available = + ref.watch(liveCoachAvailableProvider).value ?? false; + return MergeSemantics( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + _optionLabel(Icons.bolt_outlined, LocaleKeys.coach_live_option.tr()), + OatsSwitch( + value: available && state.isLiveCoachEnabled, + onChanged: available ? (_) => _vm.toggleLiveCoach() : null, + ), + ], + ), + ); + } + + /// Sous les options, avant de démarrer : pourquoi « Coach en direct » est + /// désactivé (une ligne discrète, alignée comme les options). + Widget? _liveCoachReason(LiveTranscriptionState state) { + final AsyncValue available = ref.watch(liveCoachAvailableProvider); + if (state.isRecording || state.isPaused || available.value != false) { + return null; + } + final Oats o = context.oats; + return Padding( + padding: const EdgeInsets.fromLTRB( + OatsSpace.xl, + OatsSpace.xs + 2, + OatsSpace.xl, + 0, + ), + child: Text( + LocaleKeys.coach_live_unavailable.tr(), + textAlign: TextAlign.right, + style: o.meta.copyWith(color: o.faint), ), ); } @@ -375,7 +431,18 @@ class _LiveTranscriptionScreenState VerticalDivider(width: 1, thickness: 1, color: o.line), SizedBox( width: (c.maxWidth * 0.4).clamp(280, 400), - child: const LiveAnswersPanel(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Expanded(child: LiveAnswersPanel()), + if (ref.watch( + liveTranscriptionViewModelProvider.select( + (LiveTranscriptionState s) => s.isLiveCoachEnabled, + ), + )) + const LiveCoachBlock(), + ], + ), ), ], ), diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.dart index 724b8905..9c54427d 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.dart @@ -53,6 +53,10 @@ abstract class LiveTranscriptionState with _$LiveTranscriptionState { /// Indique si l'option coach d'anglais est activée. @Default(false) bool isCoachEnabled, + /// Indique si le coach anglais en direct est activé (fournisseur en + /// ligne seulement). + @Default(false) bool isLiveCoachEnabled, + /// Indique si la traduction temps réel est activée. @Default(false) bool isTranslationEnabled, diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.freezed.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.freezed.dart index 871122c3..5f571223 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.freezed.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.state.freezed.dart @@ -30,7 +30,9 @@ mixin _$LiveTranscriptionState { String get screenRecordingPermission;/// Raison pour laquelle le son du Mac n'est pas capté (null si capté). String? get systemAudioError;/// Dernière ligne du serveur de transcription pendant son démarrage. String? get serverStartupLine;/// Indique si l'option coach d'anglais est activée. - bool get isCoachEnabled;/// Indique si la traduction temps réel est activée. + bool get isCoachEnabled;/// Indique si le coach anglais en direct est activé (fournisseur en +/// ligne seulement). + bool get isLiveCoachEnabled;/// Indique si la traduction temps réel est activée. bool get isTranslationEnabled;/// Langue source de la traduction (code ISO, ex: "en"). String get translationFrom;/// Langue cible de la traduction (code ISO, ex: "fr"). String get translationTo;/// Traductions par segment (id segment → texte traduit). @@ -52,16 +54,16 @@ $LiveTranscriptionStateCopyWith get copyWith => _$LiveTr @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is LiveTranscriptionState&&const DeepCollectionEquality().equals(other.segments, segments)&&(identical(other.isRecording, isRecording) || other.isRecording == isRecording)&&(identical(other.isPaused, isPaused) || other.isPaused == isPaused)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.finalisingRemaining, finalisingRemaining) || other.finalisingRemaining == finalisingRemaining)&&(identical(other.serverState, serverState) || other.serverState == serverState)&&(identical(other.serverPortInUse, serverPortInUse) || other.serverPortInUse == serverPortInUse)&&(identical(other.sessionTitle, sessionTitle) || other.sessionTitle == sessionTitle)&&(identical(other.micPermission, micPermission) || other.micPermission == micPermission)&&(identical(other.screenRecordingPermission, screenRecordingPermission) || other.screenRecordingPermission == screenRecordingPermission)&&(identical(other.systemAudioError, systemAudioError) || other.systemAudioError == systemAudioError)&&(identical(other.serverStartupLine, serverStartupLine) || other.serverStartupLine == serverStartupLine)&&(identical(other.isCoachEnabled, isCoachEnabled) || other.isCoachEnabled == isCoachEnabled)&&(identical(other.isTranslationEnabled, isTranslationEnabled) || other.isTranslationEnabled == isTranslationEnabled)&&(identical(other.translationFrom, translationFrom) || other.translationFrom == translationFrom)&&(identical(other.translationTo, translationTo) || other.translationTo == translationTo)&&const DeepCollectionEquality().equals(other.translations, translations)&&(identical(other.isLiveSpeakersEnabled, isLiveSpeakersEnabled) || other.isLiveSpeakersEnabled == isLiveSpeakersEnabled)&&const DeepCollectionEquality().equals(other.speakerLabels, speakerLabels)&&(identical(other.feedback, feedback) || other.feedback == feedback)&&(identical(other.isFeedbackLoading, isFeedbackLoading) || other.isFeedbackLoading == isFeedbackLoading)&&(identical(other.ollamaSetupStage, ollamaSetupStage) || other.ollamaSetupStage == ollamaSetupStage)&&(identical(other.ollamaSetupProgress, ollamaSetupProgress) || other.ollamaSetupProgress == ollamaSetupProgress)&&(identical(other.ollamaSetupError, ollamaSetupError) || other.ollamaSetupError == ollamaSetupError)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is LiveTranscriptionState&&const DeepCollectionEquality().equals(other.segments, segments)&&(identical(other.isRecording, isRecording) || other.isRecording == isRecording)&&(identical(other.isPaused, isPaused) || other.isPaused == isPaused)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.finalisingRemaining, finalisingRemaining) || other.finalisingRemaining == finalisingRemaining)&&(identical(other.serverState, serverState) || other.serverState == serverState)&&(identical(other.serverPortInUse, serverPortInUse) || other.serverPortInUse == serverPortInUse)&&(identical(other.sessionTitle, sessionTitle) || other.sessionTitle == sessionTitle)&&(identical(other.micPermission, micPermission) || other.micPermission == micPermission)&&(identical(other.screenRecordingPermission, screenRecordingPermission) || other.screenRecordingPermission == screenRecordingPermission)&&(identical(other.systemAudioError, systemAudioError) || other.systemAudioError == systemAudioError)&&(identical(other.serverStartupLine, serverStartupLine) || other.serverStartupLine == serverStartupLine)&&(identical(other.isCoachEnabled, isCoachEnabled) || other.isCoachEnabled == isCoachEnabled)&&(identical(other.isLiveCoachEnabled, isLiveCoachEnabled) || other.isLiveCoachEnabled == isLiveCoachEnabled)&&(identical(other.isTranslationEnabled, isTranslationEnabled) || other.isTranslationEnabled == isTranslationEnabled)&&(identical(other.translationFrom, translationFrom) || other.translationFrom == translationFrom)&&(identical(other.translationTo, translationTo) || other.translationTo == translationTo)&&const DeepCollectionEquality().equals(other.translations, translations)&&(identical(other.isLiveSpeakersEnabled, isLiveSpeakersEnabled) || other.isLiveSpeakersEnabled == isLiveSpeakersEnabled)&&const DeepCollectionEquality().equals(other.speakerLabels, speakerLabels)&&(identical(other.feedback, feedback) || other.feedback == feedback)&&(identical(other.isFeedbackLoading, isFeedbackLoading) || other.isFeedbackLoading == isFeedbackLoading)&&(identical(other.ollamaSetupStage, ollamaSetupStage) || other.ollamaSetupStage == ollamaSetupStage)&&(identical(other.ollamaSetupProgress, ollamaSetupProgress) || other.ollamaSetupProgress == ollamaSetupProgress)&&(identical(other.ollamaSetupError, ollamaSetupError) || other.ollamaSetupError == ollamaSetupError)); } @override -int get hashCode => Object.hashAll([runtimeType,const DeepCollectionEquality().hash(segments),isRecording,isPaused,duration,finalisingRemaining,serverState,serverPortInUse,sessionTitle,micPermission,screenRecordingPermission,systemAudioError,serverStartupLine,isCoachEnabled,isTranslationEnabled,translationFrom,translationTo,const DeepCollectionEquality().hash(translations),isLiveSpeakersEnabled,const DeepCollectionEquality().hash(speakerLabels),feedback,isFeedbackLoading,ollamaSetupStage,ollamaSetupProgress,ollamaSetupError]); +int get hashCode => Object.hashAll([runtimeType,const DeepCollectionEquality().hash(segments),isRecording,isPaused,duration,finalisingRemaining,serverState,serverPortInUse,sessionTitle,micPermission,screenRecordingPermission,systemAudioError,serverStartupLine,isCoachEnabled,isLiveCoachEnabled,isTranslationEnabled,translationFrom,translationTo,const DeepCollectionEquality().hash(translations),isLiveSpeakersEnabled,const DeepCollectionEquality().hash(speakerLabels),feedback,isFeedbackLoading,ollamaSetupStage,ollamaSetupProgress,ollamaSetupError]); @override String toString() { - return 'LiveTranscriptionState(segments: $segments, isRecording: $isRecording, isPaused: $isPaused, duration: $duration, finalisingRemaining: $finalisingRemaining, serverState: $serverState, serverPortInUse: $serverPortInUse, sessionTitle: $sessionTitle, micPermission: $micPermission, screenRecordingPermission: $screenRecordingPermission, systemAudioError: $systemAudioError, serverStartupLine: $serverStartupLine, isCoachEnabled: $isCoachEnabled, isTranslationEnabled: $isTranslationEnabled, translationFrom: $translationFrom, translationTo: $translationTo, translations: $translations, isLiveSpeakersEnabled: $isLiveSpeakersEnabled, speakerLabels: $speakerLabels, feedback: $feedback, isFeedbackLoading: $isFeedbackLoading, ollamaSetupStage: $ollamaSetupStage, ollamaSetupProgress: $ollamaSetupProgress, ollamaSetupError: $ollamaSetupError)'; + return 'LiveTranscriptionState(segments: $segments, isRecording: $isRecording, isPaused: $isPaused, duration: $duration, finalisingRemaining: $finalisingRemaining, serverState: $serverState, serverPortInUse: $serverPortInUse, sessionTitle: $sessionTitle, micPermission: $micPermission, screenRecordingPermission: $screenRecordingPermission, systemAudioError: $systemAudioError, serverStartupLine: $serverStartupLine, isCoachEnabled: $isCoachEnabled, isLiveCoachEnabled: $isLiveCoachEnabled, isTranslationEnabled: $isTranslationEnabled, translationFrom: $translationFrom, translationTo: $translationTo, translations: $translations, isLiveSpeakersEnabled: $isLiveSpeakersEnabled, speakerLabels: $speakerLabels, feedback: $feedback, isFeedbackLoading: $isFeedbackLoading, ollamaSetupStage: $ollamaSetupStage, ollamaSetupProgress: $ollamaSetupProgress, ollamaSetupError: $ollamaSetupError)'; } @@ -72,7 +74,7 @@ abstract mixin class $LiveTranscriptionStateCopyWith<$Res> { factory $LiveTranscriptionStateCopyWith(LiveTranscriptionState value, $Res Function(LiveTranscriptionState) _then) = _$LiveTranscriptionStateCopyWithImpl; @useResult $Res call({ - List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError + List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isLiveCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError }); @@ -89,7 +91,7 @@ class _$LiveTranscriptionStateCopyWithImpl<$Res> /// Create a copy of LiveTranscriptionState /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? segments = null,Object? isRecording = null,Object? isPaused = null,Object? duration = null,Object? finalisingRemaining = freezed,Object? serverState = null,Object? serverPortInUse = freezed,Object? sessionTitle = freezed,Object? micPermission = null,Object? screenRecordingPermission = null,Object? systemAudioError = freezed,Object? serverStartupLine = freezed,Object? isCoachEnabled = null,Object? isTranslationEnabled = null,Object? translationFrom = null,Object? translationTo = null,Object? translations = null,Object? isLiveSpeakersEnabled = null,Object? speakerLabels = null,Object? feedback = freezed,Object? isFeedbackLoading = null,Object? ollamaSetupStage = null,Object? ollamaSetupProgress = null,Object? ollamaSetupError = freezed,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? segments = null,Object? isRecording = null,Object? isPaused = null,Object? duration = null,Object? finalisingRemaining = freezed,Object? serverState = null,Object? serverPortInUse = freezed,Object? sessionTitle = freezed,Object? micPermission = null,Object? screenRecordingPermission = null,Object? systemAudioError = freezed,Object? serverStartupLine = freezed,Object? isCoachEnabled = null,Object? isLiveCoachEnabled = null,Object? isTranslationEnabled = null,Object? translationFrom = null,Object? translationTo = null,Object? translations = null,Object? isLiveSpeakersEnabled = null,Object? speakerLabels = null,Object? feedback = freezed,Object? isFeedbackLoading = null,Object? ollamaSetupStage = null,Object? ollamaSetupProgress = null,Object? ollamaSetupError = freezed,}) { return _then(_self.copyWith( segments: null == segments ? _self.segments : segments // ignore: cast_nullable_to_non_nullable as List,isRecording: null == isRecording ? _self.isRecording : isRecording // ignore: cast_nullable_to_non_nullable @@ -104,6 +106,7 @@ as String,screenRecordingPermission: null == screenRecordingPermission ? _self.s as String,systemAudioError: freezed == systemAudioError ? _self.systemAudioError : systemAudioError // ignore: cast_nullable_to_non_nullable as String?,serverStartupLine: freezed == serverStartupLine ? _self.serverStartupLine : serverStartupLine // ignore: cast_nullable_to_non_nullable as String?,isCoachEnabled: null == isCoachEnabled ? _self.isCoachEnabled : isCoachEnabled // ignore: cast_nullable_to_non_nullable +as bool,isLiveCoachEnabled: null == isLiveCoachEnabled ? _self.isLiveCoachEnabled : isLiveCoachEnabled // ignore: cast_nullable_to_non_nullable as bool,isTranslationEnabled: null == isTranslationEnabled ? _self.isTranslationEnabled : isTranslationEnabled // ignore: cast_nullable_to_non_nullable as bool,translationFrom: null == translationFrom ? _self.translationFrom : translationFrom // ignore: cast_nullable_to_non_nullable as String,translationTo: null == translationTo ? _self.translationTo : translationTo // ignore: cast_nullable_to_non_nullable @@ -212,10 +215,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isLiveCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _LiveTranscriptionState() when $default != null: -return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: +return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isLiveCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: return orElse(); } @@ -233,10 +236,10 @@ return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_ /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isLiveCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError) $default,) {final _that = this; switch (_that) { case _LiveTranscriptionState(): -return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: +return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isLiveCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: throw StateError('Unexpected subclass'); } @@ -253,10 +256,10 @@ return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_ /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isLiveCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError)? $default,) {final _that = this; switch (_that) { case _LiveTranscriptionState() when $default != null: -return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: +return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_that.finalisingRemaining,_that.serverState,_that.serverPortInUse,_that.sessionTitle,_that.micPermission,_that.screenRecordingPermission,_that.systemAudioError,_that.serverStartupLine,_that.isCoachEnabled,_that.isLiveCoachEnabled,_that.isTranslationEnabled,_that.translationFrom,_that.translationTo,_that.translations,_that.isLiveSpeakersEnabled,_that.speakerLabels,_that.feedback,_that.isFeedbackLoading,_that.ollamaSetupStage,_that.ollamaSetupProgress,_that.ollamaSetupError);case _: return null; } @@ -268,7 +271,7 @@ return $default(_that.segments,_that.isRecording,_that.isPaused,_that.duration,_ class _LiveTranscriptionState implements LiveTranscriptionState { - const _LiveTranscriptionState({required final List segments, this.isRecording = false, this.isPaused = false, this.duration = Duration.zero, this.finalisingRemaining, this.serverState = ServerState.stopped, this.serverPortInUse, this.sessionTitle, this.micPermission = 'unknown', this.screenRecordingPermission = 'unknown', this.systemAudioError, this.serverStartupLine, this.isCoachEnabled = false, this.isTranslationEnabled = false, this.translationFrom = 'en', this.translationTo = 'fr', final Map translations = const {}, this.isLiveSpeakersEnabled = true, final Map speakerLabels = const {}, this.feedback, this.isFeedbackLoading = false, this.ollamaSetupStage = OllamaSetupStage.idle, this.ollamaSetupProgress = 0.0, this.ollamaSetupError}): _segments = segments,_translations = translations,_speakerLabels = speakerLabels; + const _LiveTranscriptionState({required final List segments, this.isRecording = false, this.isPaused = false, this.duration = Duration.zero, this.finalisingRemaining, this.serverState = ServerState.stopped, this.serverPortInUse, this.sessionTitle, this.micPermission = 'unknown', this.screenRecordingPermission = 'unknown', this.systemAudioError, this.serverStartupLine, this.isCoachEnabled = false, this.isLiveCoachEnabled = false, this.isTranslationEnabled = false, this.translationFrom = 'en', this.translationTo = 'fr', final Map translations = const {}, this.isLiveSpeakersEnabled = true, final Map speakerLabels = const {}, this.feedback, this.isFeedbackLoading = false, this.ollamaSetupStage = OllamaSetupStage.idle, this.ollamaSetupProgress = 0.0, this.ollamaSetupError}): _segments = segments,_translations = translations,_speakerLabels = speakerLabels; /// Liste des segments de transcription de la session courante. @@ -307,6 +310,9 @@ class _LiveTranscriptionState implements LiveTranscriptionState { @override final String? serverStartupLine; /// Indique si l'option coach d'anglais est activée. @override@JsonKey() final bool isCoachEnabled; +/// Indique si le coach anglais en direct est activé (fournisseur en +/// ligne seulement). +@override@JsonKey() final bool isLiveCoachEnabled; /// Indique si la traduction temps réel est activée. @override@JsonKey() final bool isTranslationEnabled; /// Langue source de la traduction (code ISO, ex: "en"). @@ -354,16 +360,16 @@ _$LiveTranscriptionStateCopyWith<_LiveTranscriptionState> get copyWith => __$Liv @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _LiveTranscriptionState&&const DeepCollectionEquality().equals(other._segments, _segments)&&(identical(other.isRecording, isRecording) || other.isRecording == isRecording)&&(identical(other.isPaused, isPaused) || other.isPaused == isPaused)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.finalisingRemaining, finalisingRemaining) || other.finalisingRemaining == finalisingRemaining)&&(identical(other.serverState, serverState) || other.serverState == serverState)&&(identical(other.serverPortInUse, serverPortInUse) || other.serverPortInUse == serverPortInUse)&&(identical(other.sessionTitle, sessionTitle) || other.sessionTitle == sessionTitle)&&(identical(other.micPermission, micPermission) || other.micPermission == micPermission)&&(identical(other.screenRecordingPermission, screenRecordingPermission) || other.screenRecordingPermission == screenRecordingPermission)&&(identical(other.systemAudioError, systemAudioError) || other.systemAudioError == systemAudioError)&&(identical(other.serverStartupLine, serverStartupLine) || other.serverStartupLine == serverStartupLine)&&(identical(other.isCoachEnabled, isCoachEnabled) || other.isCoachEnabled == isCoachEnabled)&&(identical(other.isTranslationEnabled, isTranslationEnabled) || other.isTranslationEnabled == isTranslationEnabled)&&(identical(other.translationFrom, translationFrom) || other.translationFrom == translationFrom)&&(identical(other.translationTo, translationTo) || other.translationTo == translationTo)&&const DeepCollectionEquality().equals(other._translations, _translations)&&(identical(other.isLiveSpeakersEnabled, isLiveSpeakersEnabled) || other.isLiveSpeakersEnabled == isLiveSpeakersEnabled)&&const DeepCollectionEquality().equals(other._speakerLabels, _speakerLabels)&&(identical(other.feedback, feedback) || other.feedback == feedback)&&(identical(other.isFeedbackLoading, isFeedbackLoading) || other.isFeedbackLoading == isFeedbackLoading)&&(identical(other.ollamaSetupStage, ollamaSetupStage) || other.ollamaSetupStage == ollamaSetupStage)&&(identical(other.ollamaSetupProgress, ollamaSetupProgress) || other.ollamaSetupProgress == ollamaSetupProgress)&&(identical(other.ollamaSetupError, ollamaSetupError) || other.ollamaSetupError == ollamaSetupError)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _LiveTranscriptionState&&const DeepCollectionEquality().equals(other._segments, _segments)&&(identical(other.isRecording, isRecording) || other.isRecording == isRecording)&&(identical(other.isPaused, isPaused) || other.isPaused == isPaused)&&(identical(other.duration, duration) || other.duration == duration)&&(identical(other.finalisingRemaining, finalisingRemaining) || other.finalisingRemaining == finalisingRemaining)&&(identical(other.serverState, serverState) || other.serverState == serverState)&&(identical(other.serverPortInUse, serverPortInUse) || other.serverPortInUse == serverPortInUse)&&(identical(other.sessionTitle, sessionTitle) || other.sessionTitle == sessionTitle)&&(identical(other.micPermission, micPermission) || other.micPermission == micPermission)&&(identical(other.screenRecordingPermission, screenRecordingPermission) || other.screenRecordingPermission == screenRecordingPermission)&&(identical(other.systemAudioError, systemAudioError) || other.systemAudioError == systemAudioError)&&(identical(other.serverStartupLine, serverStartupLine) || other.serverStartupLine == serverStartupLine)&&(identical(other.isCoachEnabled, isCoachEnabled) || other.isCoachEnabled == isCoachEnabled)&&(identical(other.isLiveCoachEnabled, isLiveCoachEnabled) || other.isLiveCoachEnabled == isLiveCoachEnabled)&&(identical(other.isTranslationEnabled, isTranslationEnabled) || other.isTranslationEnabled == isTranslationEnabled)&&(identical(other.translationFrom, translationFrom) || other.translationFrom == translationFrom)&&(identical(other.translationTo, translationTo) || other.translationTo == translationTo)&&const DeepCollectionEquality().equals(other._translations, _translations)&&(identical(other.isLiveSpeakersEnabled, isLiveSpeakersEnabled) || other.isLiveSpeakersEnabled == isLiveSpeakersEnabled)&&const DeepCollectionEquality().equals(other._speakerLabels, _speakerLabels)&&(identical(other.feedback, feedback) || other.feedback == feedback)&&(identical(other.isFeedbackLoading, isFeedbackLoading) || other.isFeedbackLoading == isFeedbackLoading)&&(identical(other.ollamaSetupStage, ollamaSetupStage) || other.ollamaSetupStage == ollamaSetupStage)&&(identical(other.ollamaSetupProgress, ollamaSetupProgress) || other.ollamaSetupProgress == ollamaSetupProgress)&&(identical(other.ollamaSetupError, ollamaSetupError) || other.ollamaSetupError == ollamaSetupError)); } @override -int get hashCode => Object.hashAll([runtimeType,const DeepCollectionEquality().hash(_segments),isRecording,isPaused,duration,finalisingRemaining,serverState,serverPortInUse,sessionTitle,micPermission,screenRecordingPermission,systemAudioError,serverStartupLine,isCoachEnabled,isTranslationEnabled,translationFrom,translationTo,const DeepCollectionEquality().hash(_translations),isLiveSpeakersEnabled,const DeepCollectionEquality().hash(_speakerLabels),feedback,isFeedbackLoading,ollamaSetupStage,ollamaSetupProgress,ollamaSetupError]); +int get hashCode => Object.hashAll([runtimeType,const DeepCollectionEquality().hash(_segments),isRecording,isPaused,duration,finalisingRemaining,serverState,serverPortInUse,sessionTitle,micPermission,screenRecordingPermission,systemAudioError,serverStartupLine,isCoachEnabled,isLiveCoachEnabled,isTranslationEnabled,translationFrom,translationTo,const DeepCollectionEquality().hash(_translations),isLiveSpeakersEnabled,const DeepCollectionEquality().hash(_speakerLabels),feedback,isFeedbackLoading,ollamaSetupStage,ollamaSetupProgress,ollamaSetupError]); @override String toString() { - return 'LiveTranscriptionState(segments: $segments, isRecording: $isRecording, isPaused: $isPaused, duration: $duration, finalisingRemaining: $finalisingRemaining, serverState: $serverState, serverPortInUse: $serverPortInUse, sessionTitle: $sessionTitle, micPermission: $micPermission, screenRecordingPermission: $screenRecordingPermission, systemAudioError: $systemAudioError, serverStartupLine: $serverStartupLine, isCoachEnabled: $isCoachEnabled, isTranslationEnabled: $isTranslationEnabled, translationFrom: $translationFrom, translationTo: $translationTo, translations: $translations, isLiveSpeakersEnabled: $isLiveSpeakersEnabled, speakerLabels: $speakerLabels, feedback: $feedback, isFeedbackLoading: $isFeedbackLoading, ollamaSetupStage: $ollamaSetupStage, ollamaSetupProgress: $ollamaSetupProgress, ollamaSetupError: $ollamaSetupError)'; + return 'LiveTranscriptionState(segments: $segments, isRecording: $isRecording, isPaused: $isPaused, duration: $duration, finalisingRemaining: $finalisingRemaining, serverState: $serverState, serverPortInUse: $serverPortInUse, sessionTitle: $sessionTitle, micPermission: $micPermission, screenRecordingPermission: $screenRecordingPermission, systemAudioError: $systemAudioError, serverStartupLine: $serverStartupLine, isCoachEnabled: $isCoachEnabled, isLiveCoachEnabled: $isLiveCoachEnabled, isTranslationEnabled: $isTranslationEnabled, translationFrom: $translationFrom, translationTo: $translationTo, translations: $translations, isLiveSpeakersEnabled: $isLiveSpeakersEnabled, speakerLabels: $speakerLabels, feedback: $feedback, isFeedbackLoading: $isFeedbackLoading, ollamaSetupStage: $ollamaSetupStage, ollamaSetupProgress: $ollamaSetupProgress, ollamaSetupError: $ollamaSetupError)'; } @@ -374,7 +380,7 @@ abstract mixin class _$LiveTranscriptionStateCopyWith<$Res> implements $LiveTran factory _$LiveTranscriptionStateCopyWith(_LiveTranscriptionState value, $Res Function(_LiveTranscriptionState) _then) = __$LiveTranscriptionStateCopyWithImpl; @override @useResult $Res call({ - List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError + List segments, bool isRecording, bool isPaused, Duration duration, Duration? finalisingRemaining, ServerState serverState, int? serverPortInUse, String? sessionTitle, String micPermission, String screenRecordingPermission, String? systemAudioError, String? serverStartupLine, bool isCoachEnabled, bool isLiveCoachEnabled, bool isTranslationEnabled, String translationFrom, String translationTo, Map translations, bool isLiveSpeakersEnabled, Map speakerLabels, EnglishFeedbackEntity? feedback, bool isFeedbackLoading, OllamaSetupStage ollamaSetupStage, double ollamaSetupProgress, String? ollamaSetupError }); @@ -391,7 +397,7 @@ class __$LiveTranscriptionStateCopyWithImpl<$Res> /// Create a copy of LiveTranscriptionState /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? segments = null,Object? isRecording = null,Object? isPaused = null,Object? duration = null,Object? finalisingRemaining = freezed,Object? serverState = null,Object? serverPortInUse = freezed,Object? sessionTitle = freezed,Object? micPermission = null,Object? screenRecordingPermission = null,Object? systemAudioError = freezed,Object? serverStartupLine = freezed,Object? isCoachEnabled = null,Object? isTranslationEnabled = null,Object? translationFrom = null,Object? translationTo = null,Object? translations = null,Object? isLiveSpeakersEnabled = null,Object? speakerLabels = null,Object? feedback = freezed,Object? isFeedbackLoading = null,Object? ollamaSetupStage = null,Object? ollamaSetupProgress = null,Object? ollamaSetupError = freezed,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? segments = null,Object? isRecording = null,Object? isPaused = null,Object? duration = null,Object? finalisingRemaining = freezed,Object? serverState = null,Object? serverPortInUse = freezed,Object? sessionTitle = freezed,Object? micPermission = null,Object? screenRecordingPermission = null,Object? systemAudioError = freezed,Object? serverStartupLine = freezed,Object? isCoachEnabled = null,Object? isLiveCoachEnabled = null,Object? isTranslationEnabled = null,Object? translationFrom = null,Object? translationTo = null,Object? translations = null,Object? isLiveSpeakersEnabled = null,Object? speakerLabels = null,Object? feedback = freezed,Object? isFeedbackLoading = null,Object? ollamaSetupStage = null,Object? ollamaSetupProgress = null,Object? ollamaSetupError = freezed,}) { return _then(_LiveTranscriptionState( segments: null == segments ? _self._segments : segments // ignore: cast_nullable_to_non_nullable as List,isRecording: null == isRecording ? _self.isRecording : isRecording // ignore: cast_nullable_to_non_nullable @@ -406,6 +412,7 @@ as String,screenRecordingPermission: null == screenRecordingPermission ? _self.s as String,systemAudioError: freezed == systemAudioError ? _self.systemAudioError : systemAudioError // ignore: cast_nullable_to_non_nullable as String?,serverStartupLine: freezed == serverStartupLine ? _self.serverStartupLine : serverStartupLine // ignore: cast_nullable_to_non_nullable as String?,isCoachEnabled: null == isCoachEnabled ? _self.isCoachEnabled : isCoachEnabled // ignore: cast_nullable_to_non_nullable +as bool,isLiveCoachEnabled: null == isLiveCoachEnabled ? _self.isLiveCoachEnabled : isLiveCoachEnabled // ignore: cast_nullable_to_non_nullable as bool,isTranslationEnabled: null == isTranslationEnabled ? _self.isTranslationEnabled : isTranslationEnabled // ignore: cast_nullable_to_non_nullable as bool,translationFrom: null == translationFrom ? _self.translationFrom : translationFrom // ignore: cast_nullable_to_non_nullable as String,translationTo: null == translationTo ? _self.translationTo : translationTo // ignore: cast_nullable_to_non_nullable diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart index bf0d11de..c43ab381 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart @@ -2,13 +2,11 @@ import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart' show visibleForTesting; -import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/services.dart'; import 'package:core_domain/domain/entities/english_feedback.entity.dart'; import 'package:core_domain/domain/entities/session.entity.dart'; import 'package:core_domain/domain/entities/session_calendar_link.dart'; import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; -import 'package:core_domain/domain/enum/audio_source.enum.dart'; import 'package:core_domain/domain/enum/server_state.enum.dart'; import 'package:core_foundation/logging/logger.dart'; import 'package:ici_transcript/application/services/calendar/calendar_event.dart'; @@ -27,6 +25,8 @@ import 'package:ici_transcript/core/providers/platform/prefs_store.provider.dart import 'package:ici_transcript/core/providers/services/diarization.service.provider.dart'; import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart'; import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; import 'package:ici_transcript/core/providers/services/live_transcription.service.provider.dart'; import 'package:ici_transcript/core/providers/services/process_manager.service.provider.dart'; @@ -35,11 +35,11 @@ import 'package:ici_transcript/core/providers/services/ollama.service.provider.d import 'package:ici_transcript/core/providers/services/session_history.service.provider.dart'; import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; import 'package:ici_transcript/core/providers/services/translation.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/transcription_server_arbiter.provider.dart'; import 'package:ici_transcript/features/calendar/calendar_feed.provider.dart'; import 'package:ici_transcript/features/history/presentation/screens/detail/session_detail.view_model.dart'; import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.view_model.dart'; import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.state.dart'; -import 'package:ici_transcript/features/shared/presentation/llm_error_key.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'live_transcription.view_model.g.dart'; @@ -63,11 +63,14 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { // valeur choisie. bool _coachTouched = false; bool _speakersTouched = false; + bool _liveCoachTouched = false; + bool _startRequested = false; CalendarEvent? _nextEvent; static const String _coachKey = 'coach_enabled'; static const String _speakersKey = 'live_speakers_enabled'; + static const String _liveCoachKey = 'live_coach_enabled'; @override LiveTranscriptionState build() { @@ -159,6 +162,8 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { segment, speaker: _liveService?.speakerLabels[segment.id], ); + // Ignoré hors d'une note où le coach en direct est activé. + _coach.onSegmentFinalized(segment); }); // Après Arrêter : rattrapage restant, pour l'état « Finalisation… ». @@ -198,8 +203,29 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { LiveAnswersService get _answers => ref.read(liveAnswersServiceProvider); + LiveCoachService get _coach => ref.read(liveCoachServiceProvider); + /// Demarre une nouvelle session de transcription. Future startSession() async { + // Dès la demande : la passe du coach d'après l'appel s'arrête entre + // deux lots (attendue ci-dessous, elle retarderait le démarrage). + _startRequested = true; + try { + await _startSession(); + } finally { + _startRequested = false; + } + } + + /// Un enregistrement est demandé ou en cours (ou une dictée) : même + /// règle que le rattrapage des pertes, plus la demande en attente et + /// l'état de l'écran du direct. + bool _recordingWanted() => + _startRequested || + state.isRecording || + ref.read(transcriptionServerArbiterProvider).backfillMustYield; + + Future _startSession() async { _log.info('startSession() appele'); // Les modèles Voxtral, Ollama et Parakeet partagent la mémoire unifiée. @@ -246,7 +272,10 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { _log.info('startTranscription OK'); final SessionEntity? session = _liveService?.currentSessionStream.value; state = state.copyWith(sessionTitle: session?.title); - if (session != null) _answers.start(session.id); + if (session != null) { + _answers.start(session.id); + if (state.isLiveCoachEnabled) _coach.start(session.id); + } } catch (e) { _log.error('ERREUR startTranscription: $e'); if (e is PlatformException && e.code == 'MIC_PERMISSION_DENIED') { @@ -260,6 +289,7 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { } _durationTimer?.cancel(); await _answers.stop(); + await _coach.stop(); await _liveService?.stopTranscription(); } } @@ -320,6 +350,7 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { // Avant le rattrapage de l'arrêt : plus rien ne part pendant // « Finalisation… », la réponse en vol est abandonnée. await _answers.stop(); + await _coach.stop(); await _liveService?.stopTranscription(); final List segments = state.segments; @@ -344,6 +375,13 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { await _saveLiveSpeakers(sessionId, segments, speakerLabels); } + // Ce que le coach en direct a trouvé est rangé dès Arrêter : il + // survit à un échec ou à l'arrêt de l'app pendant la passe d'après + // l'appel (qui, si elle tourne, le reprend et complète). + if (sessionId != null) { + await _saveLiveCoach(sessionId, segments); + } + // Rafraichir la liste des sessions dans la sidebar await ref.read(sessionHistoryServiceProvider).loadSessions(); @@ -397,13 +435,7 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { required bool coachEnabled, }) async { // Coach d'abord (mistral, rapide) → trigger immédiat si activé. - if (coachEnabled) { - final String transcript = segments - .where((TranscriptSegmentEntity s) => s.source == AudioSource.input) - .map((TranscriptSegmentEntity s) => s.text) - .join('\n'); - await coachAfterCall(transcript, sessionId: sessionId); - } + if (coachEnabled) await coachAfterCall(segments, sessionId: sessionId); // Le modèle Mistral était conservé cinq minutes. Le décharger avant // Parakeet évite de cumuler plusieurs modèles Metal en mémoire unifiée. @@ -466,6 +498,9 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { isLiveSpeakersEnabled: _speakersTouched ? state.isLiveSpeakersEnabled : prefValue(prefs, _speakersKey) ?? state.isLiveSpeakersEnabled, + isLiveCoachEnabled: _liveCoachTouched + ? state.isLiveCoachEnabled + : prefValue(prefs, _liveCoachKey) ?? state.isLiveCoachEnabled, ); } @@ -480,6 +515,18 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { ); } + /// Active ou désactive le coach anglais en direct (pris en compte au + /// prochain enregistrement). + void toggleLiveCoach() { + _liveCoachTouched = true; + state = state.copyWith(isLiveCoachEnabled: !state.isLiveCoachEnabled); + unawaited( + ref.read(prefsStoreProvider).update({ + _liveCoachKey: state.isLiveCoachEnabled, + }), + ); + } + /// Active ou désactive l'identification des interlocuteurs en direct. void toggleLiveSpeakers() { _speakersTouched = true; @@ -759,56 +806,137 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { } } - /// Analyse l'anglais parlé par le fournisseur actif et sauvegarde le - /// retour. + /// Ce que le coach en direct a trouvé pour [sessionId] (rien s'il a + /// tourné pour une autre note). + ({List found, Set coached}) _liveFor( + String? sessionId, + ) { + final LiveCoachService live = _coach; + if (sessionId == null || live.snapshot.sessionId != sessionId) { + return (found: const [], coached: {}); + } + return (found: live.snapshot.corrections, coached: live.coachedSegmentIds); + } + + /// Range ce que le coach en direct a trouvé pour [sessionId] (s'il a + /// analysé au moins une phrase) ; les phrases de [segments] qu'il n'a pas + /// analysées sont dites non analysées (jamais un faux « impeccable »). + Future _saveLiveCoach( + String sessionId, + List segments, + ) async { + final ({List found, Set coached}) live = + _liveFor(sessionId); + if (live.coached.isEmpty) return; + try { + await _saveFeedback( + sessionId, + EnglishFeedbackEntity( + corrections: live.found, + unanalyzedSegmentIds: [ + for (final TranscriptSegmentEntity s in coachableLines( + segments, + skip: live.coached, + )) + s.id, + ], + ), + ); + } on Object catch (e) { + _log.warning('Sauvegarde du coach en direct échouée : $e'); + } + } + + /// Range [feedback] dans l'enveloppe partagée (résumé + coach) ; le + /// modèle rangé reste celui du résumé. + Future _saveFeedback( + String sessionId, + EnglishFeedbackEntity feedback, + ) async { + final SessionAnalysis existing = SessionAnalysis.fromStored( + await ref.read(summaryServiceProvider).getSummaryForSession(sessionId), + ); + await ref + .read(summaryServiceProvider) + .saveSummary( + sessionId: sessionId, + content: existing.copyWith(feedback: feedback).toStored(), + ); + } + + /// Coach d'après l'appel, par le fournisseur actif : les phrases + /// anglaises de l'utilisateur dans [segments], sauf celles déjà corrigées + /// en direct pour cette note ; le retour (direct + après l'appel) est + /// rangé, quel qu'il soit. Tout en échec : rangé quand même, toutes les + /// phrases non analysées (la note propose de réessayer). /// - /// [transcript] = parole du micro (MOI) uniquement. /// Rien d'utilisable (envoi coupé ou sans clé, modèle local absent) : rien - /// n'est envoyé ni téléchargé, pas de retour ; la note reste enregistrée. + /// n'est envoyé ni téléchargé ; seul le direct est rangé. @visibleForTesting - Future coachAfterCall(String transcript, {String? sessionId}) async { - if (transcript.trim().isEmpty) return; + Future coachAfterCall( + List segments, { + String? sessionId, + }) async { + final ({List found, Set coached}) live = + _liveFor(sessionId); + final List lines = coachableLines( + segments, + skip: live.coached, + ); + if (lines.isEmpty) { + if (sessionId == null) return; + if (live.coached.isEmpty && coachableLines(segments).isEmpty) { + // Aucune phrase anglaise de l'utilisateur : la note le dit. + const EnglishFeedbackEntity nothing = EnglishFeedbackEntity( + nothingToAnalyse: true, + ); + if (ref.mounted) state = state.copyWith(feedback: nothing); + await _saveFeedback(sessionId, nothing); + } else { + await _saveLiveCoach(sessionId, segments); + } + return; + } state = state.copyWith(isFeedbackLoading: true); + EnglishFeedbackEntity feedback; try { final ReadyLlm? ready = await readyLlm(ref); if (ready == null) { _log.info('Coach ignoré : aucun modèle utilisable'); - state = state.copyWith(isFeedbackLoading: false); + if (ref.mounted) state = state.copyWith(isFeedbackLoading: false); + if (sessionId != null) await _saveLiveCoach(sessionId, segments); return; } - final EnglishFeedbackEntity feedback = await coachEnglish( + final EnglishFeedbackEntity after = await coachMeeting( ready.llm, - transcript, + segments, + skipSegmentIds: live.coached, + shouldStop: _recordingWanted, + ); + feedback = after.copyWith( + corrections: mergeCorrections(live.found, after.corrections), ); - if (!ref.mounted) return; - state = state.copyWith(isFeedbackLoading: false, feedback: feedback); _log.info( 'Analyse anglais terminée (${feedback.corrections.length} corrections)', ); - - // Sauvegarder le retour dans l'enveloppe partagée (résumé + coach) ; - // le modèle rangé reste celui du résumé. - if (sessionId != null && feedback.corrections.isNotEmpty) { - final SessionAnalysis existing = SessionAnalysis.fromStored( - await ref - .read(summaryServiceProvider) - .getSummaryForSession(sessionId), - ); - await ref - .read(summaryServiceProvider) - .saveSummary( - sessionId: sessionId, - content: existing.copyWith(feedback: feedback).toStored(), - ); - _log.info('Retour coach sauvegardé pour session $sessionId'); - } } on Object catch (e) { _log.error('Coach anglais échoué : $e'); - if (!ref.mounted) return; - state = state.copyWith( - isFeedbackLoading: false, - feedback: EnglishFeedbackEntity(overall: llmErrorKey(e).tr()), + feedback = EnglishFeedbackEntity( + corrections: live.found, + unanalyzedSegmentIds: [ + for (final TranscriptSegmentEntity s in lines) s.id, + ], ); } + if (ref.mounted) { + state = state.copyWith(isFeedbackLoading: false, feedback: feedback); + } + if (sessionId == null) return; + try { + await _saveFeedback(sessionId, feedback); + _log.info('Retour coach sauvegardé pour session $sessionId'); + } on Object catch (e) { + _log.error('Sauvegarde du retour coach échouée : $e'); + } } } diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.g.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.g.dart index c7dc9a7f..61b056be 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.g.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/live_transcription.view_model.g.dart @@ -47,7 +47,7 @@ final class LiveTranscriptionViewModelProvider } String _$liveTranscriptionViewModelHash() => - r'224339b3fa5390be5c5ae321e7cb057f36e68d52'; + r'589056660ea6c1e1ddc31eb65e4051a14be28d01'; /// ViewModel de l'ecran de transcription en direct. diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_coach_block.widget.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_coach_block.widget.dart new file mode 100644 index 00000000..4f2952ad --- /dev/null +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_coach_block.widget.dart @@ -0,0 +1,126 @@ +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_presentation/core_presentation.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/features/shared/presentation/widgets/coach_feedback.widget.dart'; +import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; + +/// Corrections montrées pendant la réunion (les plus récentes). +const int kLiveCoachShown = 3; + +/// Bloc discret du coach en direct, sous les questions : les +/// [kLiveCoachShown] dernières corrections (heure, tournure corrigée, +/// original barré) ou l'état « indisponible », jamais en rouge. +class LiveCoachBlock extends ConsumerWidget { + /// Crée le bloc. + const LiveCoachBlock({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final Oats o = context.oats; + final LiveCoachSnapshot snap = + ref.watch(liveCoachSnapshotProvider).value ?? + ref.watch(liveCoachServiceProvider).snapshot; + final List all = snap.corrections; + final List shown = all + .sublist((all.length - kLiveCoachShown).clamp(0, all.length)) + .reversed + .toList(); + return Container( + padding: const EdgeInsets.fromLTRB( + OatsSpace.lg, + OatsSpace.md, + OatsSpace.lg, + OatsSpace.md, + ), + decoration: BoxDecoration( + border: Border(top: BorderSide(color: o.line)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Container( + width: 6, + height: 6, + decoration: BoxDecoration( + color: snap.unavailable ? o.faint : o.accent, + shape: BoxShape.circle, + ), + ), + const SizedBox(width: OatsSpace.xs + 2), + Expanded( + child: Semantics( + header: true, + child: Text( + snap.unavailable + ? LocaleKeys.coach_live_state_unavailable.tr() + : LocaleKeys.coach_live_option.tr(), + style: o.label, + ), + ), + ), + ], + ), + if (shown.isEmpty && !snap.unavailable) ...[ + const SizedBox(height: OatsSpace.sm), + Text(LocaleKeys.coach_live_waiting.tr(), style: o.meta), + ], + if (shown.isNotEmpty) const SizedBox(height: OatsSpace.sm), + for (final EnglishCorrectionEntity c in shown) + Padding( + padding: const EdgeInsets.only(bottom: OatsSpace.sm), + child: _LiveCorrection(c), + ), + ], + ), + ); + } +} + +class _LiveCorrection extends StatelessWidget { + const _LiveCorrection(this.correction); + + final EnglishCorrectionEntity correction; + + @override + Widget build(BuildContext context) { + final Oats o = context.oats; + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + width: 44, + padding: const EdgeInsets.only(top: 2), + child: Text( + correction.timestampMs == null + ? '' + : formatNoteTime(correction.timestampMs!), + style: o.meta.copyWith(color: o.faint), + ), + ), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(correction.corrected, style: o.bodyStrong), + Text( + correction.original, + style: o.meta.copyWith( + color: o.muted, + decoration: TextDecoration.lineThrough, + decorationColor: o.muted, + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.screen.dart b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.screen.dart index 23d56bae..4444b49e 100644 --- a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.screen.dart +++ b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.screen.dart @@ -125,6 +125,24 @@ class _SettingsScreenState extends ConsumerState { : (_) => liveVm.toggleCoach(), ), ), + // En ligne seulement : en local, la transcription + // ralentirait (rien n'est envoyé pendant la réunion). + _Row( + label: LocaleKeys.coach_live_option.tr(), + subtitle: state.llmActive == LlmProviderId.ollama + ? LocaleKeys.coach_live_unavailable.tr() + : LocaleKeys.coach_live_description.tr(), + trailing: OatsSwitch( + value: + live.isLiveCoachEnabled && + state.llmActive != LlmProviderId.ollama, + onChanged: + live.isRecording || + state.llmActive == LlmProviderId.ollama + ? null + : (_) => liveVm.toggleLiveCoach(), + ), + ), _Row( label: LocaleKeys.settings_recording_speakers.tr(), subtitle: LocaleKeys diff --git a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.dart b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.dart index c761a810..1a41352a 100644 --- a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.dart +++ b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.dart @@ -10,6 +10,7 @@ import 'package:ici_transcript/core/providers/services/active_llm_provider.provi import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.state.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; part 'settings.view_model.g.dart'; @@ -237,6 +238,7 @@ class SettingsViewModel extends _$SettingsViewModel { /// montre celui réellement utilisé. Future _llmChanged() async { ref.invalidate(activeLlmProviderProvider); + ref.invalidate(liveCoachAvailableProvider); final LlmProviderId active = await _resolve(_settings); if (ref.mounted) state = state.copyWith(llmActive: active); } diff --git a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.g.dart b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.g.dart index 4e2573be..b9a639c4 100644 --- a/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.g.dart +++ b/apps/app_macos/lib/features/settings/presentation/screens/settings/settings.view_model.g.dart @@ -50,7 +50,7 @@ final class SettingsViewModelProvider } } -String _$settingsViewModelHash() => r'd64db66412f3ef3ed299fef6e90f92c19fcf29d8'; +String _$settingsViewModelHash() => r'3770228fdfd59a1cf7077aa0912671d3484d4bc1'; /// ViewModel de l'ecran des reglages. /// diff --git a/apps/app_macos/lib/features/shared/presentation/widgets/coach_feedback.widget.dart b/apps/app_macos/lib/features/shared/presentation/widgets/coach_feedback.widget.dart index b93bc022..896e330c 100644 --- a/apps/app_macos/lib/features/shared/presentation/widgets/coach_feedback.widget.dart +++ b/apps/app_macos/lib/features/shared/presentation/widgets/coach_feedback.widget.dart @@ -5,29 +5,53 @@ import 'package:flutter/material.dart'; import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; /// Affiche le retour du coach d'anglais : commentaire global puis une ligne -/// par correction (catégorie, phrase d'origine barrée, version corrigée, -/// explication). +/// par correction (catégorie, heure dans la note, phrase d'origine barrée, +/// version corrigée, explication) ; « Aucune correction » si rien n'a été +/// trouvé ; la mention d'une partie non analysée, avec « Réessayer » si +/// [onRetry] est fourni. class CoachFeedbackView extends StatelessWidget { /// Crée une instance de [CoachFeedbackView]. - const CoachFeedbackView({required this.feedback, super.key}); + const CoachFeedbackView({required this.feedback, this.onRetry, super.key}); /// Le retour du coach à afficher. final EnglishFeedbackEntity feedback; + /// Relance les phrases non analysées ; null : pas de bouton. + final VoidCallback? onRetry; + @override Widget build(BuildContext context) { final Oats o = context.oats; final String? overall = feedback.overall; final List corrections = feedback.corrections; - if ((overall == null || overall.isEmpty) && corrections.isEmpty) { - return Text(LocaleKeys.history_detail_coach_perfect.tr(), style: o.small); - } + final bool unanalyzed = feedback.unanalyzedSegmentIds.isNotEmpty; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (overall != null && overall.isNotEmpty) ...[ + if (unanalyzed) ...[ + OatsNotice( + icon: Icons.info_outline, + message: LocaleKeys.coach_unanalyzed.tr(), + actions: [ + if (onRetry != null) + OatsButton( + label: LocaleKeys.common_action_retry.tr(), + onPressed: onRetry, + ), + ], + ), + const SizedBox(height: OatsSpace.md), + ], + if (corrections.isEmpty && !unanalyzed) + Text( + feedback.nothingToAnalyse + ? LocaleKeys.coach_nothing_to_analyse.tr() + : LocaleKeys.history_detail_coach_perfect.tr(), + style: o.small, + ) + else if (overall != null && overall.isNotEmpty) ...[ Text(overall, style: o.body), const SizedBox(height: OatsSpace.md), ], @@ -55,7 +79,15 @@ class _CorrectionRow extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - OatsChip(label: _categoryLabel(correction.category)), + Row( + children: [ + OatsChip(label: coachCategoryLabel(correction.category)), + if (correction.timestampMs case final int ms) ...[ + const SizedBox(width: OatsSpace.sm), + Text(formatNoteTime(ms), style: o.meta.copyWith(color: o.faint)), + ], + ], + ), const SizedBox(height: OatsSpace.sm), Text( correction.original, @@ -74,26 +106,28 @@ class _CorrectionRow extends StatelessWidget { ), ); } +} - String _categoryLabel(String category) { - switch (category.toLowerCase()) { - case 'grammar': - case 'grammaire': - return LocaleKeys.coach_category_grammar.tr(); - case 'conjugation': - case 'conjugaison': - return LocaleKeys.coach_category_conjugation.tr(); - case 'vocabulary': - case 'vocabulaire': - return LocaleKeys.coach_category_vocabulary.tr(); - case 'expression': - return LocaleKeys.coach_category_expression.tr(); - case 'style': - return LocaleKeys.coach_category_style.tr(); - default: - return category.isEmpty - ? LocaleKeys.coach_category_suggestion.tr() - : category; - } - } +/// Clé de traduction de [category] (« grammar » et « Grammaire » sont la +/// même) ; null : catégorie libre du modèle, affichée telle quelle. +String? coachCategoryKey(String category) => + switch (category.trim().toLowerCase()) { + 'grammar' || 'grammaire' => LocaleKeys.coach_category_grammar, + 'conjugation' || 'conjugaison' => LocaleKeys.coach_category_conjugation, + 'vocabulary' || 'vocabulaire' => LocaleKeys.coach_category_vocabulary, + 'expression' => LocaleKeys.coach_category_expression, + 'style' => LocaleKeys.coach_category_style, + '' => LocaleKeys.coach_category_suggestion, + _ => null, + }; + +/// Libellé affiché de [category]. +String coachCategoryLabel(String category) => + coachCategoryKey(category)?.tr() ?? category; + +/// Heure dans la note « mm:ss », comme les tours de la transcription. +String formatNoteTime(int ms) { + final Duration at = Duration(milliseconds: ms); + return '${at.inMinutes.toString().padLeft(2, '0')}:' + '${(at.inSeconds % 60).toString().padLeft(2, '0')}'; } diff --git a/apps/app_macos/lib/features/shell/presentation/oats_shell.screen.dart b/apps/app_macos/lib/features/shell/presentation/oats_shell.screen.dart index 2969e721..d4f17b85 100644 --- a/apps/app_macos/lib/features/shell/presentation/oats_shell.screen.dart +++ b/apps/app_macos/lib/features/shell/presentation/oats_shell.screen.dart @@ -4,6 +4,7 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:ici_transcript/core/providers/platform/dev_data_directory.provider.dart'; +import 'package:ici_transcript/features/coach/presentation/coach_overview.screen.dart'; import 'package:ici_transcript/features/documents/presentation/documents.screen.dart'; import 'package:ici_transcript/features/history/presentation/screens/detail/session_detail.screen.dart'; import 'package:ici_transcript/features/history/presentation/screens/list/session_list.state.dart'; @@ -45,16 +46,13 @@ class OatsShellScreen extends ConsumerWidget { key: ValueKey(openNote), sessionId: openNote, onClose: notes.clearSelection, + // Ouverte depuis la page « Coach anglais » : sur sa section coach. + focusCoach: view == ShellView.coach, ) : switch (view) { ShellView.home => const HomeScreen(), ShellView.documents => const DocumentsScreen(), - ShellView.coach => _EmptyPage( - title: LocaleKeys.nav_coach.tr(), - icon: Icons.school_outlined, - emptyTitle: null, - message: LocaleKeys.coach_empty.tr(), - ), + ShellView.coach => CoachOverviewScreen(onOpen: notes.selectSession), ShellView.settings => const SettingsScreen(), ShellView.live => const LiveTranscriptionScreen(), }; @@ -202,46 +200,3 @@ class _Sidebar extends ConsumerWidget { ); } } - -/// Page sans contenu encore : titre serif et état vide honnête. -class _EmptyPage extends StatelessWidget { - const _EmptyPage({ - required this.title, - required this.icon, - required this.emptyTitle, - required this.message, - }); - - final String title; - final IconData icon; - final String? emptyTitle; - final String message; - - @override - Widget build(BuildContext context) => Padding( - padding: const EdgeInsets.fromLTRB( - OatsSpace.xxxl, - OatsSpace.xl, - OatsSpace.xxxl, - OatsSpace.xl, - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: kContentMaxWidth), - child: OatsPageHeader(title: title), - ), - ), - Expanded( - child: OatsEmptyState( - icon: icon, - title: emptyTitle, - message: message, - ), - ), - ], - ), - ); -} diff --git a/apps/app_macos/lib/generated/translations/locale_keys.g.dart b/apps/app_macos/lib/generated/translations/locale_keys.g.dart index 2d270509..9d7ff3f5 100644 --- a/apps/app_macos/lib/generated/translations/locale_keys.g.dart +++ b/apps/app_macos/lib/generated/translations/locale_keys.g.dart @@ -71,6 +71,19 @@ abstract class LocaleKeys { static const documents_privacy_cloud = 'documents.privacy_cloud'; static const documents = 'documents'; static const coach_empty = 'coach.empty'; + static const coach_unanalyzed = 'coach.unanalyzed'; + static const coach_corrections = 'coach.corrections'; + static const coach_no_correction = 'coach.no_correction'; + static const coach_nothing_to_analyse = 'coach.nothing_to_analyse'; + static const coach_recurring_title = 'coach.recurring.title'; + static const coach_recurring_notes = 'coach.recurring.notes'; + static const coach_recurring = 'coach.recurring'; + static const coach_live_option = 'coach.live.option'; + static const coach_live_description = 'coach.live.description'; + static const coach_live_unavailable = 'coach.live.unavailable'; + static const coach_live_state_unavailable = 'coach.live.state_unavailable'; + static const coach_live_waiting = 'coach.live.waiting'; + static const coach_live = 'coach.live'; static const coach_category_grammar = 'coach.category.grammar'; static const coach_category_conjugation = 'coach.category.conjugation'; static const coach_category_vocabulary = 'coach.category.vocabulary'; diff --git a/apps/app_macos/test/application/services/live_coach/live_coach_service_test.dart b/apps/app_macos/test/application/services/live_coach/live_coach_service_test.dart new file mode 100644 index 00000000..62166338 --- /dev/null +++ b/apps/app_macos/test/application/services/live_coach/live_coach_service_test.dart @@ -0,0 +1,352 @@ +import 'dart:convert'; + +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart' + show LiveAnswerModel; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; + +import '../../../helpers/live_answers_fakes.dart' + show ScriptedLlmProvider, ScriptedStream, requestText; + +/// Coach anglais EN DIRECT (optionnel, coupé par défaut). +/// +/// Besoin : pendant la réunion, les phrases anglaises FINALES de +/// l'utilisateur (micro seulement) sont corrigées par lots : au plus une +/// requête par ~20 s, et seulement s'il y a de nouvelles phrases. Seulement +/// avec un fournisseur en ligne configuré et autorisé : une sonde a mesuré +/// qu'une génération locale fait passer le délai de transcription de 1,8 s à +/// 6–24 s, donc avec le modèle local RIEN ne part (état « indisponible »). +/// Ne retarde ni ne bloque jamais la transcription : un échec est +/// silencieux (état « indisponible »), une requête muette n'empêche pas les +/// phrases suivantes d'entrer, l'arrêt l'abandonne. Ce qui a été trouvé +/// reste lisible après l'arrêt pour être rangé dans la note, avec les ids +/// des phrases déjà corrigées (la passe d'après l'appel ne les refait pas). +/// +/// Décision prise (spec) : premier lot sans attente (une phrase arrivée +/// plus de 20 s après la requête précédente part tout de suite), les +/// suivantes attendent la fin des 20 s et partent ensemble. +/// +/// API supposée (à créer), lib/application/services/live_coach/ +/// live_coach.service.dart : +/// - `LiveCoachService({resolveModel, interval})` : `resolveModel` rend +/// `Future`, `interval` vaut 20 s par défaut ; modèle relu à chaque lot ; +/// - `start(sessionId)`, `Future stop()`, +/// `void onSegmentFinalized(TranscriptSegmentEntity)` ; +/// - `LiveCoachSnapshot get snapshot` (`sessionId` de la note, `corrections`, +/// `unavailable`), +/// `Stream get snapshots`, +/// `Set get coachedSegmentIds`. +/// Réponse du modèle : même JSON que le coach d'après l'appel ; heure d'une +/// correction = celle de la phrase qui contient `original`. +void main() { + late ScriptedLlmProvider llm; + late LiveCoachService coach; + late LiveAnswerModel? model; + + void setUpCoach({bool isLocal = false, bool ready = true}) { + llm = ScriptedLlmProvider(); + model = ready + ? LiveAnswerModel( + provider: llm, + modelId: 'claude-test', + isLocal: isLocal, + ) + : null; + coach = LiveCoachService(resolveModel: () async => model)..start('s1'); + } + + int n = 0; + TranscriptSegmentEntity seg( + String text, { + required int atMs, + AudioSource source = AudioSource.input, + }) => TranscriptSegmentEntity( + id: 'seg-${++n}', + sessionId: 's1', + source: source, + text: text, + timestampMs: atMs, + createdAt: DateTime(2026, 11, 23, 10), + ); + + TranscriptSegmentEntity say(String text, {int atMs = 60000}) { + final TranscriptSegmentEntity s = seg(text, atMs: atMs); + coach.onSegmentFinalized(s); + return s; + } + + String answer(List<(String, String)> fixes) => jsonEncode({ + 'overall': 'Bon niveau.', + 'corrections': >[ + for (final (String original, String corrected) in fixes) + { + 'original': original, + 'corrected': corrected, + 'category': 'grammar', + 'explanation': 'Explication courte.', + }, + ], + }); + + const Duration interval = Duration(seconds: 20); + + test('une phrase anglaise finale de l\'utilisateur part tout de suite au ' + 'fournisseur en ligne', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('I am agree with you on this point.'); + async.flushMicrotasks(); + + expect(llm.streams, hasLength(1)); + expect(requestText(llm.last.request), contains('I am agree with you')); + }); + }); + + test('au plus une requête par 20 s ; les phrases arrivées entre-temps ' + 'partent ensemble, sans rien perdre', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('I am agree with you on this point.'); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[])); + async.elapse(const Duration(seconds: 5)); + say('He have sent the deck to the client.', atMs: 65000); + async.elapse(const Duration(seconds: 5)); + say('We was ready for the demo yesterday.', atMs: 70000); + + async.elapse(const Duration(seconds: 9)); + expect(llm.streams, hasLength(1), reason: 'moins de 20 s'); + + async.elapse(const Duration(seconds: 2)); + expect(llm.streams, hasLength(2)); + final String second = requestText(llm.last.request); + expect(second, contains('He have sent the deck')); + expect(second, contains('We was ready for the demo')); + expect(second, isNot(contains('I am agree'))); + }); + }); + + test('rien de nouveau : aucune autre requête', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('I am agree with you on this point.'); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[])); + + async.elapse(const Duration(minutes: 3)); + + expect(llm.streams, hasLength(1)); + }); + }); + + test( + 'l\'interlocuteur, une phrase en français, un repère : rien ne part', + () { + fakeAsync((FakeAsync async) { + setUpCoach(); + coach + ..onSegmentFinalized( + seg( + 'Can you send me the slides today?', + atMs: 1000, + source: AudioSource.output, + ), + ) + ..onSegmentFinalized( + seg( + 'Je pense que le budget est validé pour la semaine.', + atMs: 2000, + ), + ) + ..onSegmentFinalized( + seg( + LiveTranscriptionService.untranscribedMarkerText(3000, 6000), + atMs: 3000, + ), + ) + ..onSegmentFinalized( + seg(LiveTranscriptionService.gapMarkerText(7000, 9000), atMs: 7000), + ); + + async.elapse(const Duration(minutes: 1)); + + expect(llm.streams, isEmpty); + }); + }, + ); + + test('langue indécise (même règle qu\'après l\'appel) : « I think so. » ' + 'part, « Yes exactly. » et le franglais (mot-outil français) non', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('Yes exactly.', atMs: 1000); + say('On fait le call with the team.', atMs: 2000); + async.elapse(interval * 2); + expect(llm.streams, isEmpty); + + say('I think so.', atMs: 3000); + async.flushMicrotasks(); + expect(llm.streams, hasLength(1)); + expect(requestText(llm.last.request), contains('I think so.')); + expect(requestText(llm.last.request), isNot(contains('Yes exactly'))); + }); + }); + + for (final (String name, bool isLocal, bool ready) in <(String, bool, bool)>[ + ('modèle local (envoi coupé ou pas de clé)', true, true), + ('aucun modèle prêt', false, false), + ]) { + test('$name : rien n\'est envoyé, l\'état dit « indisponible »', () { + fakeAsync((FakeAsync async) { + setUpCoach(isLocal: isLocal, ready: ready); + say('I am agree with you on this point.'); + async.elapse(interval * 3); + say('He have sent the deck to the client.', atMs: 125000); + async.elapse(interval * 3); + + expect(llm.streams, isEmpty); + expect(coach.snapshot.unavailable, isTrue); + expect(coach.coachedSegmentIds, isEmpty); + }); + }); + } + + test('envoi coupé en pleine réunion : le lot suivant ne part pas', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('I am agree with you on this point.'); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[])); + model = LiveAnswerModel(provider: llm, modelId: 'mistral', isLocal: true); + + say('He have sent the deck to the client.', atMs: 65000); + async.elapse(interval * 2); + + expect(llm.streams, hasLength(1)); + expect(coach.snapshot.unavailable, isTrue); + }); + }); + + test('une correction trouvée : montrée avec l\'heure de la phrase, la ' + 'phrase comptée comme corrigée', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + final TranscriptSegmentEntity s = say( + 'I am agree with you on this point.', + atMs: 65000, + ); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[('I am agree', 'I agree')])); + async.flushMicrotasks(); + + final EnglishCorrectionEntity c = coach.snapshot.corrections.single; + expect(c.corrected, 'I agree'); + expect(c.timestampMs, 65000); + expect(coach.coachedSegmentIds, contains(s.id)); + expect(coach.snapshot.unavailable, isFalse); + }); + }); + + test('échec d\'un lot : silencieux, état « indisponible », ses phrases ne ' + 'comptent pas comme corrigées ; un lot suivant réussi l\'efface', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + final TranscriptSegmentEntity failed = say( + 'I am agree with you on this point.', + ); + async.flushMicrotasks(); + llm.last.fail(const LlmUnreachableException('Claude')); + async.flushMicrotasks(); + + expect(coach.snapshot.unavailable, isTrue); + expect(coach.coachedSegmentIds, isNot(contains(failed.id))); + + async.elapse(interval); + final TranscriptSegmentEntity next = say( + 'He have sent the deck to the client.', + atMs: 125000, + ); + async.flushMicrotasks(); + llm.last.reply( + answer(<(String, String)>[('He have sent', 'He has sent')]), + ); + async.flushMicrotasks(); + + expect(coach.snapshot.unavailable, isFalse); + expect(coach.coachedSegmentIds, contains(next.id)); + }); + }); + + test('requête sans réponse : les phrases suivantes entrent sans attendre, ' + 'l\'arrêt abandonne la requête', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + say('I am agree with you on this point.'); + async.flushMicrotasks(); + final ScriptedStream hung = llm.last; + + // `onSegmentFinalized` est synchrone : rien n'attend le modèle. + for (int i = 0; i < 50; i++) { + say('Line $i: we need to check the figures.', atMs: 61000 + i * 100); + } + async.elapse(interval * 2); + + bool stopped = false; + coach.stop().then((_) => stopped = true); + async.flushMicrotasks(); + + expect(stopped, isTrue); + expect(hung.cancelled, isTrue); + }); + }); + + test('après l\'arrêt : plus rien ne part, ce qui a été trouvé reste lisible ' + 'jusqu\'au prochain démarrage', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + final TranscriptSegmentEntity s = say( + 'I am agree with you on this point.', + ); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[('I am agree', 'I agree')])); + async.flushMicrotasks(); + + coach.stop(); + async.flushMicrotasks(); + say('He have sent the deck to the client.', atMs: 125000); + async.elapse(interval * 2); + + expect(llm.streams, hasLength(1)); + expect(coach.snapshot.corrections.single.corrected, 'I agree'); + expect(coach.coachedSegmentIds, contains(s.id)); + + expect(coach.snapshot.sessionId, 's1'); + coach.start('s2'); + expect(coach.snapshot.sessionId, 's2'); + expect(coach.snapshot.corrections, isEmpty); + expect(coach.coachedSegmentIds, isEmpty); + }); + }); + + test('chaque nouveau résultat est publié', () { + fakeAsync((FakeAsync async) { + setUpCoach(); + final List seen = []; + coach.snapshots.listen(seen.add); + + say('I am agree with you on this point.'); + async.flushMicrotasks(); + llm.last.reply(answer(<(String, String)>[('I am agree', 'I agree')])); + async.flushMicrotasks(); + + expect(seen, isNotEmpty); + expect(seen.last.corrections.single.corrected, 'I agree'); + }); + }); +} diff --git a/apps/app_macos/test/application/services/llm/coach_language_table_test.dart b/apps/app_macos/test/application/services/llm/coach_language_table_test.dart new file mode 100644 index 00000000..a707382c --- /dev/null +++ b/apps/app_macos/test/application/services/llm/coach_language_table_test.dart @@ -0,0 +1,106 @@ +import 'dart:convert'; + +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/llm/meeting_ai.dart'; + +import '../../../helpers/llm_fakes.dart' show ScriptedLlmProvider, requestText; + +/// Quelles phrases de l'utilisateur vont au coach (revue de la PR #26). +/// +/// Une phrase écartée ne laisse aucune trace : une règle de langue trop +/// stricte fait disparaître en silence de l'anglais ordinaire. Tables +/// d'exemples inventés, phrase par phrase, par le vrai `coachMeeting` : +/// - À CORRIGER : anglais parlé ordinaire, y compris contractions (deux +/// apostrophes), « a », mots qui existent aussi en français (« me », +/// « on », « son », « pour », « an », « des » comme prénom), sigles en +/// capitales (« EST », « ETA », « LE »), nom propre ou marque française +/// dans une phrase anglaise (« La Poste », « Jean-Pierre du Pont », +/// « Le Monde »), prénom accentué, réponses courtes avec une vraie faute ; +/// - À ÉCARTER : le franglais épinglé, le français, le français avec une +/// marque anglaise, les interjections. +void main() { + TranscriptSegmentEntity mine(String text) => TranscriptSegmentEntity( + id: 'u', + sessionId: 's1', + source: AudioSource.input, + text: text, + timestampMs: 0, + createdAt: DateTime(2026, 11, 23, 10), + ); + + Future sent(String sentence) async { + final ScriptedLlmProvider llm = ScriptedLlmProvider( + (LlmChatRequest r, int i) => Stream.value( + jsonEncode({'corrections': []}), + ), + ); + await coachMeeting(llm, [mine(sentence)]); + return llm.requests.any( + (LlmChatRequest r) => requestText(r).contains(sentence), + ); + } + + const List mustBeCoached = [ + "I'm agree with you.", + 'I’m agree with you.', + "He don't know the answer.", + 'It’s a good idea.', + "I'd like to add a point.", + "We're ready for the demo.", + "That's a fair point.", + 'Can you send me the file?', + 'Me too.', + "Let's meet on Monday.", + 'My son is sick today.', + 'Could you pour me a coffee?', + 'Pour me some water, please.', + "It's an option.", + 'Des will join us later.', + 'The EST deadline works for me.', + 'What is the ETA for the release?', + 'The LE team has the numbers.', + 'The La Poste contract is signed.', + 'I met Jean-Pierre du Pont yesterday.', + 'Le Monde wrote about it.', + 'Hélène will send the file.', + 'I am agree.', + 'He don’t know.', + 'We discussed about the budget.', + 'Do you have a minute?', + 'She is in the office.', + 'We need a decision by Friday.', + ]; + + const List mustBeSkipped = [ + 'On fait le call with the team.', + 'Je pense que le budget est validé pour la semaine.', + 'Je vous envoie le deck demain.', + "C'est bon pour moi.", + 'On utilise Slack pour ça.', + 'Merci beaucoup.', + 'OK.', + 'Yes exactly.', + 'Voilà.', + 'Euh…', + 'Bah oui.', + ]; + + group('à corriger (anglais ordinaire)', () { + for (final String s in mustBeCoached) { + test('« $s » part au coach', () async { + expect(await sent(s), isTrue); + }); + } + }); + + group('à écarter', () { + for (final String s in mustBeSkipped) { + test('« $s » ne part pas', () async { + expect(await sent(s), isFalse); + }); + } + }); +} diff --git a/apps/app_macos/test/application/services/llm/coach_meeting_test.dart b/apps/app_macos/test/application/services/llm/coach_meeting_test.dart new file mode 100644 index 00000000..c6aa84c5 --- /dev/null +++ b/apps/app_macos/test/application/services/llm/coach_meeting_test.dart @@ -0,0 +1,480 @@ +import 'dart:convert'; + +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_answers/answer_prompt.dart' + show questionLanguage; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/llm/meeting_ai.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; + +import '../../../helpers/llm_fakes.dart' show ScriptedLlmProvider, requestText; + +/// Coach anglais d'une note, règle unique (après l'appel ET à la demande). +/// +/// Besoin (Clément) : corriger ce que l'UTILISATEUR a dit en anglais, jamais +/// les autres participants. Comportement épinglé ici : +/// - seules les phrases du micro partent ; jamais l'audio système, un repère +/// de perte (« Transcription interrompue… ») ni un « Passage non +/// transcrit » ; une phrase en français de l'utilisateur n'est pas envoyée ; +/// - règle de langue, qui ne s'en remet PAS au seul `questionLanguage` : une +/// phrase de l'utilisateur part seulement si elle a au moins un mot-outil +/// anglais (pronom, article, auxiliaire, préposition : « I », « so », +/// « the »…) ET aucun mot-outil français (« le », « la », « fait »…) ; +/// sinon ignorée. Un mot des deux langues (« on », « a ») ne compte pas +/// comme français. Franglais (« On fait le call with the team. », que +/// `questionLanguage` juge anglais) : ignoré. « OK », « yes », +/// « exactly » sont des interjections, pas des mots-outils ; +/// - un modèle qui dit en prose qu'il n'y a rien à corriger = aucune +/// correction pour cette partie, pas un échec ; +/// - une longue réunion part en plusieurs requêtes d'au plus +/// [kLlmMaxRequestChars] caractères (consignes comprises), chaque phrase +/// dans exactement une requête : rien de coupé ni de jeté en silence +/// (aujourd'hui `coachEnglish` ne garde que la fin) ; +/// - une partie en échec (injoignable, réponse illisible) ne fait pas tout +/// échouer : ses phrases sont notées non analysées, les autres corrections +/// restent ; si TOUTES échouent, l'erreur remonte (l'appelant l'affiche) ; +/// - chaque correction porte l'heure dans la note de la phrase qui contient +/// `original` (forme de réponse du modèle inchangée : il ne donne pas +/// d'heure ; introuvable = correction gardée, sans heure) ; +/// - les phrases déjà corrigées en direct ne repartent pas (arrêt entre +/// deux lots : coach_stop_between_batches_test.dart). +/// +/// Pas de migration : l'heure et les phrases non analysées vivent dans le +/// JSON de `summaries.content` (enveloppe [SessionAnalysis]). +/// +/// API supposée (à créer) : +/// - dans meeting_ai.dart : +/// `Future coachMeeting(llm, segments, {skipSegmentIds})` +/// (`LlmProvider`, `List`, `Set`) ; +/// - `EnglishCorrectionEntity.timestampMs` (int?, ms depuis le début de la +/// note, comme `TranscriptSegmentEntity.timestampMs`) ; +/// - `EnglishFeedbackEntity.unanalyzedSegmentIds` (`List`, défaut +/// vide) : ids des phrases dont la partie a échoué. +void main() { + TranscriptSegmentEntity seg( + String id, + String text, { + required int atMs, + AudioSource source = AudioSource.input, + }) => TranscriptSegmentEntity( + id: id, + sessionId: 's1', + source: source, + text: text, + timestampMs: atMs, + createdAt: DateTime(2026, 11, 20, 9), + ); + + String answer(List> corrections) => jsonEncode( + {'overall': 'Bon niveau.', 'corrections': corrections}, + ); + + Map fix(String original, String corrected) => + { + 'original': original, + 'corrected': corrected, + 'category': 'grammar', + 'explanation': 'Explication courte.', + }; + + ScriptedLlmProvider replying(String text) => ScriptedLlmProvider( + (LlmChatRequest r, int i) => Stream.value(text), + ); + + String allSent(ScriptedLlmProvider llm) => + llm.requests.map(requestText).join('\n'); + + /// Réunion d'une heure : une phrase de l'utilisateur toutes les 5 s + /// (720 phrases anglaises distinctes), une de l'interlocuteur entre deux. + List hourLong() => [ + for (int i = 0; i < 720; i++) ...[ + seg( + 'me-$i', + 'Line $i: we need to check the figures for the next release.', + atMs: i * 5000, + ), + seg( + 'them-$i', + 'Other $i: the budget is ready for the review.', + atMs: i * 5000 + 2500, + source: AudioSource.output, + ), + ], + ]; + + /// Ligne de l'utilisateur citée en premier dans [r] (« Line N: … »). + String firstLineOf(LlmChatRequest r) { + final RegExpMatch m = RegExp( + r'Line (\d+): we need', + ).firstMatch(requestText(r))!; + return m.group(0)!; + } + + group('ce qui part au modèle', () { + test('seules les phrases du micro : ni l\'audio système, ni un repère de ' + 'perte, ni « Passage non transcrit »', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + + await coachMeeting(llm, [ + seg('a', 'I am agree with you on this point.', atMs: 0), + seg( + 'b', + 'We need the budget by Friday.', + atMs: 5000, + source: AudioSource.output, + ), + seg( + 'c', + LiveTranscriptionService.gapMarkerText(10000, 20000), + atMs: 10000, + ), + seg( + 'd', + LiveTranscriptionService.untranscribedMarkerText(30000, 34000), + atMs: 30000, + ), + seg('e', 'He have sent the deck to the client.', atMs: 40000), + ]); + + final String sent = allSent(llm); + expect(sent, contains('I am agree with you on this point.')); + expect(sent, contains('He have sent the deck to the client.')); + expect(sent, isNot(contains('budget by Friday'))); + expect(sent, isNot(contains(LiveTranscriptionService.gapMarkerPrefix))); + expect(sent, isNot(contains('Passage non transcrit'))); + }); + + test( + 'une phrase de l\'utilisateur en français n\'est pas envoyée', + () async { + final ScriptedLlmProvider llm = replying( + answer(>[]), + ); + + await coachMeeting(llm, [ + seg( + 'fr', + 'Je pense que le budget est validé pour la semaine.', + atMs: 0, + ), + seg('en', 'We was ready for the demo yesterday.', atMs: 5000), + ]); + + expect(allSent(llm), contains('We was ready for the demo yesterday.')); + expect(allSent(llm), isNot(contains('le budget est validé'))); + }, + ); + + test('phrase sans indice ou mêlée : anglaise seulement avec un mot-outil ' + 'anglais et aucun français', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + const Map sent = { + 'I think so.': true, + 'OK.': false, + 'Yes exactly.': false, + 'Voilà.': false, + 'On fait le call with the team.': false, + }; + int i = 0; + + await coachMeeting(llm, [ + for (final String text in sent.keys) + seg('u-${i++}', text, atMs: i * 5000), + ]); + + sent.forEach((String text, bool expected) { + expect( + allSent(llm).contains(text), + expected, + reason: '« $text » ${expected ? 'doit' : 'ne doit pas'} partir', + ); + }); + }); + + test('franglais que `questionLanguage` juge anglais : ignoré quand ' + 'même (un mot-outil français suffit)', () async { + const String franglais = 'On fait le call with the team.'; + expect( + questionLanguage(franglais), + 'English', + reason: 'prémisse : le seul juge de langue se tromperait ici', + ); + final ScriptedLlmProvider llm = replying(answer(>[])); + + await coachMeeting(llm, [ + seg('mix', franglais, atMs: 0), + seg('en', 'I am agree with you on this point.', atMs: 5000), + ]); + + expect(allSent(llm), isNot(contains(franglais))); + expect( + allSent(llm), + contains('I am agree with you on this point.'), + reason: '« on » est des deux langues : ne compte pas comme français', + ); + }); + + test('rien que du français ou rien du micro : aucune requête, retour ' + 'vide', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + + final EnglishFeedbackEntity feedback = + await coachMeeting(llm, [ + seg('fr', 'Je vous envoie le compte rendu de la réunion.', atMs: 0), + seg( + 'them', + 'Can you share the slides with the team?', + atMs: 5000, + source: AudioSource.output, + ), + ]); + + expect(llm.requests, isEmpty); + expect(feedback.corrections, isEmpty); + expect(feedback.unanalyzedSegmentIds, isEmpty); + }); + + test('réunion de 60 minutes : plusieurs requêtes, chacune bornée, chaque ' + 'phrase de l\'utilisateur dans exactement une', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + final List meeting = hourLong(); + + await coachMeeting(llm, meeting); + + expect(llm.requests.length, greaterThan(1)); + for (final LlmChatRequest r in llm.requests) { + expect( + requestText(r).length, + lessThanOrEqualTo(kLlmMaxRequestChars), + reason: 'une requête dépasse la borne', + ); + } + for (final TranscriptSegmentEntity s in meeting) { + if (s.source != AudioSource.input) continue; + final int carrying = llm.requests + .where((LlmChatRequest r) => requestText(r).contains(s.text)) + .length; + expect(carrying, 1, reason: '« ${s.text} » envoyée $carrying fois'); + } + }); + + test('phrases déjà corrigées en direct : jamais renvoyées ; toutes ' + 'corrigées : aucune requête', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + final List meeting = [ + seg('a', 'I am agree with you on this point.', atMs: 0), + seg('b', 'He have sent the deck to the client.', atMs: 5000), + ]; + + await coachMeeting(llm, meeting, skipSegmentIds: {'a'}); + expect(allSent(llm), isNot(contains('I am agree'))); + expect(allSent(llm), contains('He have sent the deck')); + + final ScriptedLlmProvider none = replying( + answer(>[]), + ); + await coachMeeting(none, meeting, skipSegmentIds: {'a', 'b'}); + expect(none.requests, isEmpty); + }); + }); + + group('ce qui revient', () { + test('chaque correction porte l\'heure, dans la note, de la phrase qui ' + 'la contient', () async { + final ScriptedLlmProvider llm = replying( + answer(>[ + fix('He have sent', 'He has sent'), + fix('I am agree', 'I agree'), + ]), + ); + + final EnglishFeedbackEntity feedback = + await coachMeeting(llm, [ + seg('a', 'I am agree with you on this point.', atMs: 65000), + seg('b', 'He have sent the deck to the client.', atMs: 125000), + ]); + + final Map timeOf = { + for (final EnglishCorrectionEntity c in feedback.corrections) + c.original: c.timestampMs, + }; + expect(timeOf['I am agree'], 65000); + expect(timeOf['He have sent'], 125000); + }); + + test( + 'correction introuvable dans les phrases : gardée, sans heure', + () async { + final ScriptedLlmProvider llm = replying( + answer(>[ + fix('we discussed about', 'we discussed'), + ]), + ); + + final EnglishFeedbackEntity feedback = await coachMeeting( + llm, + [ + seg('a', 'I am agree with you on this point.', atMs: 65000), + ], + ); + + expect(feedback.corrections.single.corrected, 'we discussed'); + expect(feedback.corrections.single.timestampMs, isNull); + }, + ); + + test('le modèle dit en prose qu\'il n\'y a rien à corriger : aucune ' + 'correction, rien de non analysé, pas d\'erreur', () async { + for (final String prose in [ + 'No corrections needed.', + 'Your English is correct.', + 'Rien à corriger.', + '[]', + ]) { + final ScriptedLlmProvider llm = replying(prose); + + final EnglishFeedbackEntity feedback = await coachMeeting( + llm, + [ + seg('a', 'I agree with you on this point.', atMs: 0), + ], + ); + + expect(feedback.corrections, isEmpty, reason: prose); + expect(feedback.unanalyzedSegmentIds, isEmpty, reason: prose); + } + }); + + test('« aucune correction » : retour vide, rien de non analysé', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + + final EnglishFeedbackEntity feedback = await coachMeeting( + llm, + [ + seg('a', 'I agree with you on this point.', atMs: 0), + ], + ); + + expect(feedback.corrections, isEmpty); + expect(feedback.unanalyzedSegmentIds, isEmpty); + }); + }); + + group('une partie échoue', () { + for (final (String name, Stream Function() failure) + in <(String, Stream Function())>[ + ( + 'injoignable', + () => Stream.error(const LlmUnreachableException('Claude')), + ), + ( + 'réponse illisible', + () => Stream.value('Désolé, je ne peux pas.'), + ), + ]) { + test('$name : les autres corrections restent, les phrases de cette ' + 'partie sont notées non analysées', () async { + final ScriptedLlmProvider llm = ScriptedLlmProvider(( + LlmChatRequest r, + int i, + ) { + if (i == 1) return failure(); + final String line = firstLineOf(r); + return Stream.value( + answer(>[fix(line, '$line (corrigé)')]), + ); + }); + final List meeting = hourLong(); + + final EnglishFeedbackEntity feedback = await coachMeeting(llm, meeting); + + final String failed = requestText(llm.requests[1]); + final Set expectedIds = { + for (final TranscriptSegmentEntity s in meeting) + if (s.source == AudioSource.input && failed.contains(s.text)) s.id, + }; + expect(expectedIds, isNotEmpty); + expect(feedback.unanalyzedSegmentIds.toSet(), expectedIds); + expect(feedback.corrections, hasLength(llm.requests.length - 1)); + expect( + feedback.corrections.map((EnglishCorrectionEntity c) => c.original), + isNot(contains(firstLineOf(llm.requests[1]))), + ); + }); + } + + test('toutes les parties échouent : l\'erreur remonte', () async { + final ScriptedLlmProvider llm = ScriptedLlmProvider( + (LlmChatRequest r, int i) => + Stream.error(const LlmUnreachableException('Claude')), + ); + + await expectLater( + coachMeeting(llm, [ + seg('a', 'I am agree with you on this point.', atMs: 0), + ]), + throwsA(isA()), + ); + }); + }); + + group('enveloppe rangée (summaries.content, sans migration)', () { + test('l\'heure des corrections et les phrases non analysées survivent ' + 'à l\'aller-retour', () { + const EnglishFeedbackEntity feedback = EnglishFeedbackEntity( + corrections: [ + EnglishCorrectionEntity( + original: 'I am agree', + corrected: 'I agree', + category: 'grammar', + explanation: '« agree » est un verbe.', + timestampMs: 65000, + ), + ], + unanalyzedSegmentIds: ['me-12', 'me-13'], + ); + + final SessionAnalysis back = SessionAnalysis.fromStored( + const SessionAnalysis( + summary: 'Résumé.', + feedback: feedback, + ).toStored(), + ); + + expect(back.feedback, feedback); + expect(back.summary, 'Résumé.'); + }); + + test('enveloppe d\'avant (sans heure ni partie manquante) : se lit, ' + 'sans heure, rien de non analysé', () { + final String legacy = jsonEncode({ + 'summary': null, + 'feedback': { + 'overall': 'Bon niveau.', + 'corrections': >[ + { + 'original': 'I am agree', + 'corrected': 'I agree', + 'category': 'grammar', + 'explanation': '« agree » est un verbe.', + }, + ], + }, + 'micText': null, + 'speakers': [], + }); + + final EnglishFeedbackEntity? feedback = SessionAnalysis.fromStored( + legacy, + ).feedback; + + expect(feedback?.corrections.single.corrected, 'I agree'); + expect(feedback?.corrections.single.timestampMs, isNull); + expect(feedback?.unanalyzedSegmentIds, isEmpty); + }); + }); +} diff --git a/apps/app_macos/test/application/services/llm/coach_stop_between_batches_test.dart b/apps/app_macos/test/application/services/llm/coach_stop_between_batches_test.dart new file mode 100644 index 00000000..1666c9c9 --- /dev/null +++ b/apps/app_macos/test/application/services/llm/coach_stop_between_batches_test.dart @@ -0,0 +1,112 @@ +import 'dart:convert'; + +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/llm/meeting_ai.dart'; + +import '../../../helpers/llm_fakes.dart' show ScriptedLlmProvider, requestText; + +/// Arrêt de la passe du coach entre deux lots (revue de la PR #26). +/// +/// Besoin : avec le modèle local, une longue note fait de nombreuses +/// générations après Arrêter ; une génération locale retarde la +/// transcription (1,8 s → 6–24 s mesurés). Quand un nouvel enregistrement +/// démarre, la passe s'arrête entre deux lots : le lot en cours finit et +/// compte, le reste est noté non analysé (« Réessayer » le reprendra), +/// sans erreur. +/// +/// API supposée : `coachMeeting(..., shouldStop: bool Function())`, lu +/// avant chaque lot. Côté view model : post_call_coach_batches_test.dart. +void main() { + TranscriptSegmentEntity seg( + String id, + String text, { + required int atMs, + AudioSource source = AudioSource.input, + }) => TranscriptSegmentEntity( + id: id, + sessionId: 's1', + source: source, + text: text, + timestampMs: atMs, + createdAt: DateTime(2026, 11, 20, 9), + ); + + String answer(List> corrections) => + jsonEncode({'corrections': corrections}); + + Map fix(String original, String corrected) => + { + 'original': original, + 'corrected': corrected, + 'category': 'grammar', + 'explanation': 'Explication courte.', + }; + + ScriptedLlmProvider replying(String text) => ScriptedLlmProvider( + (LlmChatRequest r, int i) => Stream.value(text), + ); + + List hourLong() => [ + for (int i = 0; i < 720; i++) + seg( + 'me-$i', + 'Line $i: we need to check the figures for the next release.', + atMs: i * 5000, + ), + ]; + + String firstLineOf(LlmChatRequest r) => + RegExp(r'Line (\d+): we need').firstMatch(requestText(r))!.group(0)!; + + group('arrêt entre deux lots (un enregistrement démarre)', () { + test('`shouldStop` vrai après le 1er lot : plus aucune requête, les ' + 'corrections du 1er lot restent, le reste est non analysé', () async { + bool stop = false; + final ScriptedLlmProvider llm = ScriptedLlmProvider(( + LlmChatRequest r, + int i, + ) { + stop = true; + final String line = firstLineOf(r); + return Stream.value( + answer(>[fix(line, '$line (corrigé)')]), + ); + }); + final List meeting = hourLong(); + + final EnglishFeedbackEntity feedback = await coachMeeting( + llm, + meeting, + shouldStop: () => stop, + ); + + expect(llm.requests, hasLength(1)); + expect(feedback.corrections, hasLength(1)); + final String first = requestText(llm.requests.single); + final Set rest = { + for (final TranscriptSegmentEntity s in meeting) + if (s.source == AudioSource.input && !first.contains(s.text)) s.id, + }; + expect(rest, isNotEmpty); + expect(feedback.unanalyzedSegmentIds.toSet(), rest); + }); + + test('`shouldStop` vrai dès le départ : aucune requête, tout est non ' + 'analysé, pas d\'erreur', () async { + final ScriptedLlmProvider llm = replying(answer(>[])); + + final EnglishFeedbackEntity feedback = + await coachMeeting(llm, [ + seg('a', 'I am agree with you on this point.', atMs: 0), + seg('b', 'He have sent the deck to the client.', atMs: 5000), + ], shouldStop: () => true); + + expect(llm.requests, isEmpty); + expect(feedback.unanalyzedSegmentIds.toSet(), {'a', 'b'}); + }); + }); +} diff --git a/apps/app_macos/test/features/coach/coach_overview_test.dart b/apps/app_macos/test/features/coach/coach_overview_test.dart new file mode 100644 index 00000000..cde571a8 --- /dev/null +++ b/apps/app_macos/test/features/coach/coach_overview_test.dart @@ -0,0 +1,526 @@ +import 'dart:async'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/session.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:core_domain/domain/enum/session_status.enum.dart'; +import 'package:drift/drift.dart' + show ApplyInterceptor, QueryExecutor, QueryInterceptor; +import 'package:drift/native.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; +import 'package:ici_transcript/core/providers/core/repositories/session.repository.provider.dart'; +import 'package:ici_transcript/core/providers/core/repositories/transcript.repository.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/history/presentation/screens/detail/session_detail.screen.dart'; +import 'package:ici_transcript/features/history/presentation/screens/detail/session_detail.state.dart'; +import 'package:ici_transcript/presentation/app.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart' show InMemoryApiKeyStore; + +/// Lectures de la table `summaries` qui échouent ou n'aboutissent pas tant +/// que le test le veut ; le reste de la base marche. +class _Summaries extends QueryInterceptor { + bool fail = false; + Completer? hold; + + @override + Future>> runSelect( + QueryExecutor executor, + String statement, + List args, + ) async { + if (statement.contains('summaries')) { + if (fail) throw StateError('base illisible'); + if (hold case final Completer h) await h.future; + } + return executor.runSelect(statement, args); + } +} + +/// Page « Coach anglais » de la barre latérale. +/// +/// Besoin : la liste, toutes notes confondues (plus récente d'abord), des +/// notes qui ont des corrections, avec leur nombre ; un clic ouvre la note +/// SUR sa section coach (visible même sous un long résumé) ; Retour ramène +/// à la page. Puis les erreurs récurrentes : une même catégorie de +/// correction vue dans 3 notes ou plus (une note compte une fois, quelle +/// que soit le nombre de ses corrections ; « grammar » et « Grammaire » sont +/// la même catégorie, comme dans l'affichage d'une correction). Sans +/// rien : l'état vide en français d'aujourd'hui (`coach.empty`). Chargement +/// et erreur avec une issue (Réessayer) ; une enveloppe abîmée n'empêche +/// pas la liste. Une note dont le coach n'a rien trouvé y figure aussi, +/// avec « Aucune correction » (`coach.no_correction`) pour montrer que la +/// passe a tourné : jours du plus récent au plus ancien ; dans un même +/// jour, sous les notes qui ont des corrections. +/// +/// Pas de migration : tout se lit dans `summaries.content` (catégorie déjà +/// présente dans `EnglishCorrectionEntity.category`). +/// +/// Application entière (RootAppWidget + vrai routeur), vraie base en +/// mémoire (sessions + enveloppes rangées), note ouverte par +/// `FakeSessionDetailViewModel`. +/// +/// Repères supposés (fr.json) : `coach.corrections` (pluriel « {} correction +/// / {} corrections »), `coach.recurring.title`, `coach.recurring.notes` +/// (pluriel « dans {} notes »), libellés de catégorie `coach.category.*`, +/// `common.error.generic` et `common.action.retry` pour l'erreur. +void main() { + late AppDatabase db; + late _Summaries interceptor; + + DateTime day(int d) => DateTime(2026, 11, d, 10); + + SessionEntity note(String id, String title, int d) => SessionEntity( + id: id, + title: title, + createdAt: day(d), + updatedAt: day(d), + durationSeconds: 1800, + status: SessionStatus.completed, + ); + + EnglishCorrectionEntity fix(String category, [int i = 0]) => + EnglishCorrectionEntity( + original: 'mistake $category $i', + corrected: 'better $category $i', + category: category, + explanation: 'Raison.', + ); + + final SessionEntity budget = note('budget', 'Point budget', 10); + final SessionEntity produit = note('produit', 'Revue produit', 14); + final SessionEntity design = note('design', 'Atelier design', 18); + final SessionEntity comite = note('comite', 'Comité projet', 20); + + /// Rangé tel quel dans `summaries.content` (null = pas de ligne). + late Map stored; + late Map shownFeedback; + + /// Segments de la note, puis vraie passe du coach d'après l'appel. + late Map> spoken; + + String envelope(EnglishFeedbackEntity f) => + SessionAnalysis(feedback: f).toStored(); + + Future pumpApp( + WidgetTester tester, + List sessions, + ) async { + interceptor = _Summaries(); + db = AppDatabase(NativeDatabase.memory().interceptWith(interceptor)); + addTearDown(db.close); + final AppFakes fakes = AppFakes( + sessions: sessions, + ollama: kOllamaReady, + detail: (String id) async => SessionDetailState( + session: sessions.firstWhere((SessionEntity s) => s.id == id), + segments: const [], + // Long résumé : la section coach est sous la ligne de flottaison. + summary: List.generate( + 80, + (int i) => '- Point $i du résumé de la réunion.', + ).join('\n'), + feedback: shownFeedback[id], + ), + ); + // Un AppFakes par conteneur : un Notifier (ici `AppFakes.live`) ne + // s'attache qu'à un seul conteneur. + List overridesWith(AppFakes f) => [ + ...f.overrides, + ...localModelOverrides(db, InstantOllamaService(installed: true)), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + ]; + final List overrides = overridesWith(fakes); + await tester.runAsync(() async { + final ProviderContainer c = ProviderContainer( + overrides: overridesWith( + AppFakes(sessions: sessions, ollama: kOllamaReady), + ), + ); + for (final SessionEntity s in sessions) { + await c.read(sessionRepositoryProvider).create(s); + if (stored[s.id] case final String content) { + await c + .read(summaryServiceProvider) + .saveSummary(sessionId: s.id, content: content); + } + if (spoken[s.id] case final List lines) { + await c.read(transcriptRepositoryProvider).saveBatch(lines); + // Vraie passe d'après l'appel (`FakeLiveTranscriptionViewModel` + // ne remplace que build()). + await c + .read(liveTranscriptionViewModelProvider.notifier) + .coachAfterCall(lines, sessionId: s.id); + } + } + c.dispose(); + }); + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + localized( + child: const RootAppWidget(), + overrides: overrides, + withMaterialApp: false, + ), + ); + await settle(tester); + } + + Future io(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 30)), + ); + await settle(tester, frames: 2); + } + } + + Finder sidebarItem(String key) => find.descendant( + of: find.byKey(const ValueKey('oats-sidebar')), + matching: find.text(key.tr()), + ); + + Future openCoachPage(WidgetTester tester) async { + await tester.tap(sidebarItem('nav.coach')); + await io(tester); + } + + setUp(() { + stored = {}; + shownFeedback = {}; + spoken = >{}; + }); + + testWidgets('aucune note avec des corrections : l\'état vide en français', ( + WidgetTester tester, + ) async { + await pumpApp(tester, [budget]); + + await openCoachPage(tester); + + expect(find.text('coach.empty'.tr()), findsOneWidget); + }); + + testWidgets('les notes qui ont des corrections, la plus récente d\'abord, ' + 'chacune avec son nombre ; les autres n\'y sont pas', ( + WidgetTester tester, + ) async { + stored = { + budget.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + design.id: envelope( + EnglishFeedbackEntity( + corrections: [ + fix('vocabulary', 1), + fix('vocabulary', 2), + fix('expression', 3), + ], + ), + ), + // Résumé seul, sans coach. + produit.id: const SessionAnalysis(summary: 'Résumé.').toStored(), + }; + await pumpApp(tester, [budget, produit, design]); + + await openCoachPage(tester); + + expect(find.text('Atelier design'), findsOneWidget); + expect(find.text('Point budget'), findsOneWidget); + expect(find.text('Revue produit'), findsNothing); + expect( + tester.getTopLeft(find.text('Atelier design')).dy, + lessThan(tester.getTopLeft(find.text('Point budget')).dy), + reason: 'plus récente d\'abord', + ); + expect(find.text('coach.corrections'.plural(3)), findsOneWidget); + expect(find.text('coach.corrections'.plural(1)), findsOneWidget); + expect(find.text('coach.empty'.tr()), findsNothing); + }); + + testWidgets('une note sans correction figure avec « Aucune correction » : ' + 'jours du plus récent au plus ancien, sous les notes corrigées du même ' + 'jour', (WidgetTester tester) async { + SessionEntity at(String id, String title, int d, int hour) => SessionEntity( + id: id, + title: title, + createdAt: DateTime(2026, 11, d, hour), + updatedAt: DateTime(2026, 11, d, hour), + durationSeconds: 1800, + status: SessionStatus.completed, + ); + final SessionEntity comiteVide = at('comite', 'Comité projet', 20, 9); + final SessionEntity designVide = at('design', 'Atelier design', 18, 15); + final SessionEntity produitCorr = at('produit', 'Revue produit', 18, 9); + final SessionEntity budgetCorr = at('budget', 'Point budget', 10, 9); + const EnglishFeedbackEntity none = EnglishFeedbackEntity(); + stored = { + comiteVide.id: envelope(none), + designVide.id: envelope(none), + produitCorr.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + budgetCorr.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('vocabulary')], + ), + ), + }; + await pumpApp(tester, [ + budgetCorr, + produitCorr, + designVide, + comiteVide, + ]); + + await openCoachPage(tester); + + double top(String title) => tester.getTopLeft(find.text(title)).dy; + expect(find.text('coach.no_correction'.tr()), findsNWidgets(2)); + expect(top('Comité projet'), lessThan(top('Revue produit'))); + expect(top('Revue produit'), lessThan(top('Atelier design'))); + expect(top('Atelier design'), lessThan(top('Point budget'))); + expect(find.text('coach.empty'.tr()), findsNothing); + }); + + testWidgets('note sans phrase anglaise de l\'utilisateur (passe faite) : ' + 'figure avec « rien en anglais à analyser », pas « Aucune correction »', ( + WidgetTester tester, + ) async { + TranscriptSegmentEntity line(String text, AudioSource source) => + TranscriptSegmentEntity( + id: 'design-${text.length}', + sessionId: design.id, + source: source, + text: text, + timestampMs: 5000, + createdAt: day(18), + ); + spoken = >{ + design.id: [ + line('Je vous envoie le deck demain.', AudioSource.input), + line('We need the budget by Friday.', AudioSource.output), + ], + }; + await pumpApp(tester, [design]); + + await openCoachPage(tester); + + expect(find.text('Atelier design'), findsOneWidget); + expect(find.text('coach.nothing_to_analyse'.tr()), findsOneWidget); + expect(find.text('coach.no_correction'.tr()), findsNothing); + }); + + testWidgets('une ligne abîmée parmi d\'autres, dont une d\'avant les ' + 'nouveaux champs : les autres notes restent listées', ( + WidgetTester tester, + ) async { + stored = { + budget.id: '{"feedback": {"corrections": [{"original": ', + produit.id: + '{"summary": null, "feedback": {"overall": "Bon niveau.", ' + '"corrections": [{"original": "I am agree", "corrected": "I agree", ' + '"category": "grammar", "explanation": "Verbe."}]}, ' + '"micText": null, "speakers": []}', + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + }; + await pumpApp(tester, [budget, produit, design]); + + await openCoachPage(tester); + + expect(tester.takeException(), isNull); + expect(find.text('Revue produit'), findsOneWidget); + expect(find.text('Atelier design'), findsOneWidget); + expect(find.text('common.error.generic'.tr()), findsNothing); + }); + + testWidgets('une enveloppe abîmée n\'empêche pas la liste', ( + WidgetTester tester, + ) async { + stored = { + budget.id: '{"feedback": {"corrections": [{"original": ', + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + }; + await pumpApp(tester, [budget, design]); + + await openCoachPage(tester); + + expect(find.text('Atelier design'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('un clic ouvre la note sur sa section coach, visible même sous ' + 'un long résumé ; Retour ramène à la page', (WidgetTester tester) async { + final EnglishFeedbackEntity fb = EnglishFeedbackEntity( + corrections: [fix('grammar')], + ); + stored = {design.id: envelope(fb)}; + shownFeedback = {design.id: fb}; + await pumpApp(tester, [design]); + await openCoachPage(tester); + + await tester.tap(find.text('Atelier design')); + await io(tester); + + expect(find.byType(SessionDetailScreen), findsOneWidget); + final Finder coachHeading = find.descendant( + of: find.byWidgetPredicate( + (Widget w) => w is Semantics && (w.properties.header ?? false), + ), + matching: find.text('history.detail.english_coach'.tr()), + ); + expect(isOnScreen(coachHeading), isTrue, reason: 'section coach visible'); + + await tester.tap(find.byTooltip('common.action.back'.tr())); + await io(tester); + + expect(find.byType(SessionDetailScreen), findsNothing); + expect(find.text('Atelier design'), findsOneWidget); + }); + + group('erreurs récurrentes', () { + testWidgets('une catégorie vue dans 3 notes y figure (grammar = ' + 'Grammaire) ; vue dans 2 notes, non ; une note compte une fois', ( + WidgetTester tester, + ) async { + stored = { + budget.id: envelope( + EnglishFeedbackEntity( + corrections: [ + fix('grammar', 1), + fix('grammar', 2), + fix('grammar', 3), + fix('vocabulary', 4), + ], + ), + ), + produit.id: envelope( + EnglishFeedbackEntity( + corrections: [ + fix('Grammaire', 5), + fix('vocabulary', 6), + ], + ), + ), + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar', 7)], + ), + ), + comite.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('expression', 8)], + ), + ), + }; + await pumpApp(tester, [budget, produit, design, comite]); + + await openCoachPage(tester); + + expect(find.text('coach.recurring.title'.tr()), findsOneWidget); + expect(find.text('coach.category.grammar'.tr()), findsOneWidget); + expect(find.text('coach.recurring.notes'.plural(3)), findsOneWidget); + expect(find.text('coach.recurring.notes'.plural(2)), findsNothing); + }); + + testWidgets('aucune catégorie dans 3 notes : pas de section', ( + WidgetTester tester, + ) async { + stored = { + budget.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + }; + await pumpApp(tester, [budget, design]); + + await openCoachPage(tester); + + expect(find.text('Atelier design'), findsOneWidget); + expect(find.text('coach.recurring.title'.tr()), findsNothing); + }); + }); + + group('chargement et erreur', () { + testWidgets('pendant la lecture : un indicateur, pas l\'état vide', ( + WidgetTester tester, + ) async { + stored = { + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + }; + await pumpApp(tester, [design]); + interceptor.hold = Completer(); + + await openCoachPage(tester); + + expect(find.byType(CircularProgressIndicator), findsWidgets); + expect(find.text('coach.empty'.tr()), findsNothing); + interceptor.hold!.complete(); + await io(tester); + expect(find.text('Atelier design'), findsOneWidget); + }); + + testWidgets('lecture impossible : un message et « Réessayer », qui ' + 'affiche la liste une fois la base lisible', ( + WidgetTester tester, + ) async { + stored = { + design.id: envelope( + EnglishFeedbackEntity( + corrections: [fix('grammar')], + ), + ), + }; + await pumpApp(tester, [design]); + interceptor.fail = true; + + await openCoachPage(tester); + + expect(find.text('common.error.generic'.tr()), findsOneWidget); + expect(find.text('coach.empty'.tr()), findsNothing); + + interceptor.fail = false; + await tester.tap(find.text('common.action.retry'.tr())); + await io(tester); + + expect(find.text('Atelier design'), findsOneWidget); + expect(find.text('common.error.generic'.tr()), findsNothing); + }); + }); +} diff --git a/apps/app_macos/test/features/coach/coach_translations_test.dart b/apps/app_macos/test/features/coach/coach_translations_test.dart new file mode 100644 index 00000000..d07ea928 --- /dev/null +++ b/apps/app_macos/test/features/coach/coach_translations_test.dart @@ -0,0 +1,75 @@ +import 'package:flutter_test/flutter_test.dart'; + +import '../../helpers/localized_app.dart'; + +/// Textes du coach anglais (après l'appel, en direct, page « Coach anglais ») +/// : présents dans fr.json, non vides ; les pluriels ont leurs deux formes ; +/// l'état d'échec du direct dit « indisponible » (mot de Clément). +void main() { + const List keys = [ + // Note : une partie de la réunion n'a pas été analysée. + 'coach.unanalyzed', + // Direct : interrupteur, description, raison d'indisponibilité, état. + 'coach.live.option', + 'coach.live.description', + 'coach.live.unavailable', + 'coach.live.state_unavailable', + // Page « Coach anglais » : note sans correction, erreurs récurrentes. + 'coach.no_correction', + // Note sans phrase anglaise de l'utilisateur : rien n'a été analysé. + 'coach.nothing_to_analyse', + 'coach.recurring.title', + // Déjà là, réutilisés. + 'coach.empty', + 'history.detail.coach_perfect', + 'common.action.retry', + 'common.error.generic', + ]; + for (final String key in keys) { + test('$key est présent et non vide', () { + final Object? value = frValue(key); + expect(value, isA(), reason: key); + expect((value! as String).trim(), isNotEmpty, reason: key); + }); + } + + for (final String key in [ + 'coach.corrections', + 'coach.recurring.notes', + ]) { + test('$key a ses formes « one » et « other », avec le nombre', () { + final Object? value = frValue(key); + expect(value, isA>(), reason: key); + final Map forms = value! as Map; + expect(forms['one'], contains('{}')); + expect(forms['other'], contains('{}')); + }); + } + + test('une note sans correction se dit « Aucune correction »', () { + expect(frValue('coach.no_correction'), 'Aucune correction'); + }); + + test('« rien en anglais à analyser » ne se confond ni avec « Aucune ' + 'correction » ni avec une erreur', () { + final Object? v = frValue('coach.nothing_to_analyse'); + expect(v, isA()); + expect(v, isNot(frValue('coach.no_correction'))); + expect(v, isNot(frValue('history.detail.coach_perfect'))); + expect((v! as String).toLowerCase(), contains('anglais')); + }); + + test('l\'état d\'échec du coach en direct dit « indisponible »', () { + expect( + (frValue('coach.live.state_unavailable') as String?)?.toLowerCase(), + contains('indisponible'), + ); + }); + + test('la raison d\'indisponibilité parle du service en ligne', () { + expect( + (frValue('coach.live.unavailable') as String?)?.toLowerCase(), + contains('en ligne'), + ); + }); +} diff --git a/apps/app_macos/test/features/history/coach_answer_shapes_test.dart b/apps/app_macos/test/features/history/coach_answer_shapes_test.dart index c9401c2f..942c37ef 100644 --- a/apps/app_macos/test/features/history/coach_answer_shapes_test.dart +++ b/apps/app_macos/test/features/history/coach_answer_shapes_test.dart @@ -26,9 +26,15 @@ import '../../helpers/settings_fakes.dart'; /// Attendu, pour le modèle local ET pour un fournisseur en ligne (vrai /// `activeLlmProvider`, transport factice) : /// - JSON nu, dans un bloc ```json, précédé ou suivi de texte : lu ; -/// - pas de JSON, JSON coupé, objet vide ou d'une autre forme : état -/// `llm.error.malformed`, jamais un plantage, jamais un retour vide -/// affiché ou rangé comme s'il était valable. +/// - le modèle dit en prose (français ou anglais) qu'il n'y a rien à +/// corriger, ou rend une liste JSON vide : « Aucune correction » +/// (`history.detail.coach_perfect`), retour vide rangé, JAMAIS une erreur +/// (décision du 2026-11-23, même principe que le lecteur de réponses de +/// la PR #23 : un petit modèle local respecte rarement le contrat) ; +/// - réponse vide (après retrait des blancs), texte sans rapport, JSON +/// coupé, objet vide ou d'une autre forme : état `llm.error.malformed` +/// (relancer = le bouton « Coach anglais »), jamais un plantage, rien +/// rangé. void main() { late AppDatabase db; late RecordingHttpAdapter adapter; @@ -43,12 +49,23 @@ void main() { 'texte autour et bloc': 'Bien sûr ! Voici le retour :\n\n```json\n$json\n```\n\nBon courage.', }; + final Map nothingToCorrect = { + 'prose française « rien à corriger »': 'Très bon niveau, rien à corriger !', + 'prose française courte': 'Rien à corriger.', + 'prose anglaise « no corrections »': 'No corrections needed.', + 'prose anglaise « correct »': 'Your English is correct.', + 'prose anglaise « no mistakes »': + 'There are no mistakes in this transcript.', + 'liste JSON vide': '[]', + 'liste vide dans un bloc': '```json\n[]\n```', + }; final Map unreadable = { - 'du texte seul': 'Très bon niveau, rien à corriger !', + 'du texte sans rapport': 'Bonjour, je suis un assistant.', 'un JSON coupé': '{"overall": "Bon niv', 'un objet vide': '{}', 'un objet d\'une autre forme': 'Résultat : {"note": 3, "niveau": "B2"}', 'une réponse vide': '', + 'des blancs seulement': ' \n\t ', }; Future idle(WidgetTester tester) async { @@ -109,8 +126,8 @@ void main() { for (final bool cloud in [false, true]) { final String who = cloud ? 'Claude' : 'modèle local'; - final String host = kProviderHost[ - cloud ? LlmProviderId.anthropic : LlmProviderId.ollama]!; + final String host = + kProviderHost[cloud ? LlmProviderId.anthropic : LlmProviderId.ollama]!; group(who, () { readable.forEach((String name, String answer) { @@ -122,14 +139,31 @@ void main() { expect(adapter.lastHost, host); expect(tester.takeException(), isNull); expect(find.textContaining('I agree'), findsWidgets); + expect(find.textContaining('llm.error.malformed'.tr()), findsNothing); + final EnglishFeedbackEntity? saved = (await tester.runAsync( + () => storedAnalysis(db), + ))!.feedback; + expect(saved?.corrections.single.corrected, 'I agree'); + }); + }); + + nothingToCorrect.forEach((String name, String answer) { + testWidgets('$name : « Aucune correction », pas d\'erreur, retour ' + 'vide rangé', (WidgetTester tester) async { + await pumpCoach(tester, cloud: cloud, answer: answer); + + expect(adapter.lastHost, host); + expect(tester.takeException(), isNull); expect( - find.textContaining('llm.error.malformed'.tr()), - findsNothing, + find.text('history.detail.coach_perfect'.tr()), + findsOneWidget, ); + expect(find.textContaining('llm.error.malformed'.tr()), findsNothing); final EnglishFeedbackEntity? saved = (await tester.runAsync( () => storedAnalysis(db), ))!.feedback; - expect(saved?.corrections.single.corrected, 'I agree'); + expect(saved, isNotNull); + expect(saved!.corrections, isEmpty); }); }); diff --git a/apps/app_macos/test/features/history/coach_section_test.dart b/apps/app_macos/test/features/history/coach_section_test.dart new file mode 100644 index 00000000..b7031358 --- /dev/null +++ b/apps/app_macos/test/features/history/coach_section_test.dart @@ -0,0 +1,579 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:core_presentation/core_presentation.dart' show OatsButton; +import 'package:dio/dio.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; +import 'package:ici_transcript/features/history/presentation/screens/detail/session_detail.screen.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/onboarding/presentation/ollama_setup.view_model.dart'; +import 'package:ici_transcript/features/shared/presentation/widgets/coach_feedback.widget.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/llm_fakes.dart' + show noteSegment, seedNote, storedAnalysis, streamOf, writeLlmPrefs; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Transport factice dont la réponse dépend du rang de la requête (0, 1…). +class _ByIndexHttp extends RecordingHttpAdapter { + _ByIndexHttp(this.replyFor); + + FakeReply Function(int index) replyFor; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) { + reply = replyFor(requests.length); + return super.fetch(options, requestStream, cancelFuture); + } +} + +/// Section « Coach anglais » d'une note. +/// +/// Besoin : chaque correction = ce qui a été dit, la meilleure tournure, une +/// raison d'une ligne en français, et l'heure dans la note ; « aucune +/// correction » se dit comme tel, jamais comme une erreur ; une partie non +/// analysée (lot en échec, après l'appel ou à la demande) est signalée par +/// la note, avec « Réessayer » qui ne renvoie QUE ces phrases. +/// +/// Vrai `SessionDetailViewModel` + vrai écran, base en mémoire, modèle local +/// installé, transport factice (aucun réseau). +/// +/// Hors besoin ici : cliquer l'heure pour aller à la ligne (l'écran de note +/// n'a aucun défilement vers une ligne aujourd'hui : non spécifié) ; l'heure +/// est un texte simple, pas un bouton. +/// +/// API supposée : `EnglishCorrectionEntity.timestampMs`, +/// `EnglishFeedbackEntity.unanalyzedSegmentIds` ; heure affichée « mm:ss » +/// comme les tours de la transcription ; textes de fr.json : +/// `coach.unanalyzed` (mention), `common.action.retry` (bouton), +/// `history.detail.coach_perfect` (aucune correction), +/// `coach.nothing_to_analyse` (aucune phrase anglaise de l'utilisateur : +/// rien n'a été envoyé ; ni « Aucune correction » ni erreur). Relancer à +/// la main reprend toutes les phrases (le direct ne fait rien sauter) et +/// remplace le retour. Un retour rangé d'avant les nouveaux champs s'ouvre. +void main() { + group('une correction affichée', () { + testWidgets('ce qui a été dit, la meilleure tournure, la raison et ' + 'l\'heure dans la note', (WidgetTester tester) async { + await pumpLocalized( + tester, + const CoachFeedbackView( + feedback: EnglishFeedbackEntity( + corrections: [ + EnglishCorrectionEntity( + original: 'I am agree', + corrected: 'I agree', + category: 'grammar', + explanation: '« agree » est un verbe, sans « am ».', + timestampMs: 65000, + ), + ], + ), + ), + ); + + expect(find.textContaining('I am agree'), findsOneWidget); + expect(find.textContaining('I agree'), findsWidgets); + expect(find.textContaining('« agree » est un verbe'), findsOneWidget); + expect(find.textContaining('01:05'), findsOneWidget); + // Texte simple : l'écran de note ne sait pas aller à une ligne. + for (final Type tappable in [InkWell, ButtonStyleButton]) { + expect( + find.ancestor( + of: find.textContaining('01:05'), + matching: find.byType(tappable), + ), + findsNothing, + reason: 'heure cliquable ($tappable)', + ); + } + }); + + testWidgets('correction d\'avant (sans heure) : affichée, sans heure ' + 'inventée', (WidgetTester tester) async { + await pumpLocalized( + tester, + const CoachFeedbackView( + feedback: EnglishFeedbackEntity( + corrections: [ + EnglishCorrectionEntity( + original: 'I am agree', + corrected: 'I agree', + category: 'grammar', + explanation: '« agree » est un verbe.', + ), + ], + ), + ), + ); + + expect(find.textContaining('I am agree'), findsOneWidget); + expect(find.textContaining('00:00'), findsNothing); + }); + + testWidgets('aucune correction, même avec un commentaire global : ' + '« Aucune correction » affiché', (WidgetTester tester) async { + await pumpLocalized( + tester, + const CoachFeedbackView( + feedback: EnglishFeedbackEntity(overall: 'Très bon niveau.'), + ), + ); + + expect(find.text('history.detail.coach_perfect'.tr()), findsOneWidget); + }); + }); + + group('dans la note (vrai view model)', () { + late AppDatabase db; + late _ByIndexHttp http; + late List overrides; + + String feedbackJson(List<(String, String)> fixes) => + jsonEncode({ + 'overall': 'Bon niveau.', + 'corrections': >[ + for (final (String original, String corrected) in fixes) + { + 'original': original, + 'corrected': corrected, + 'category': 'grammar', + 'explanation': 'Explication courte.', + }, + ], + }); + + FakeReply ok(String json) => + BodyReply(200, streamOf(LlmProviderId.ollama, json)); + + Future until(WidgetTester tester, bool Function() done) async { + for (int i = 0; i < 80 && !done(); i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await settle(tester, frames: 2); + } + await settle(tester, frames: 3); + } + + /// Ouvre la note `s1` (deux appels = la note rouverte : nouveau view + /// model, relu depuis la base). + Future open(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await pumpLocalized( + tester, + SessionDetailScreen(sessionId: 's1', onClose: () {}), + settle: false, + overrides: overrides, + ); + await until( + tester, + () => find.byType(CircularProgressIndicator).evaluate().isEmpty, + ); + } + + /// Note `s1` avec [segments] et, si fourni, le retour [stored] déjà rangé. + Future seed( + WidgetTester tester, { + required List segments, + EnglishFeedbackEntity? stored, + String? rawStored, + bool postCall = false, + required FakeReply Function(int index) replyFor, + }) async { + await tester.runAsync(() => writeLlmPrefs(cloudAllowed: false)); + db = memoryDatabase(); + addTearDown(db.close); + http = _ByIndexHttp(replyFor); + overrides = [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + llmDioProvider.overrideWithValue(Dio()..httpClientAdapter = http), + ollamaSetupViewModelProvider.overrideWith( + () => FakeOllamaSetupViewModel(kOllamaReady), + ), + // Vrai coach d'après l'appel (`coachAfterCall`), sans serveur. + liveTranscriptionViewModelProvider.overrideWith( + FakeLiveTranscriptionViewModel.new, + ), + ]; + await tester.runAsync(() async { + final ProviderContainer c = ProviderContainer(overrides: overrides); + await seedNote(c, segments); + if (rawStored != null) { + await c + .read(summaryServiceProvider) + .saveSummary(sessionId: 's1', content: rawStored); + } + if (postCall) { + await c + .read(liveTranscriptionViewModelProvider.notifier) + .coachAfterCall(segments, sessionId: 's1'); + } + if (stored != null) { + await c + .read(summaryServiceProvider) + .saveSummary( + sessionId: 's1', + content: SessionAnalysis(feedback: stored).toStored(), + ); + } + c.dispose(); + }); + } + + Future saved(WidgetTester tester) async => + (await tester.runAsync(() => storedAnalysis(db)))!.feedback; + + Finder unanalyzed() => find.text('coach.unanalyzed'.tr()); + Finder retry() => find.text('common.action.retry'.tr()); + // Le bouton de la barre du haut (la section porte le même titre). + Finder coachAction() => + find.widgetWithText(OatsButton, 'history.detail.english_coach'.tr()); + + final List meeting = [ + noteSegment( + 0, + 'I am agree with you on this point.', + source: AudioSource.input, + ), + noteSegment(1, 'We need the budget by Friday.'), + noteSegment( + 2, + 'He have sent the deck to the client.', + source: AudioSource.input, + ), + noteSegment( + 3, + 'We was ready for the demo yesterday.', + source: AudioSource.input, + ), + ]; + const EnglishCorrectionEntity first = EnglishCorrectionEntity( + original: 'I am agree', + corrected: 'I agree', + category: 'grammar', + explanation: '« agree » est un verbe.', + timestampMs: 0, + ); + + testWidgets('note rouverte après un échec partiel : les corrections, la ' + 'mention des passages non analysés et « Réessayer »', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: meeting, + stored: const EnglishFeedbackEntity( + corrections: [first], + unanalyzedSegmentIds: ['seg-2', 'seg-3'], + ), + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await open(tester); + + expect(find.textContaining('I agree'), findsWidgets); + expect(unanalyzed(), findsOneWidget); + expect(retry(), findsOneWidget); + expect(find.text('history.detail.coach_perfect'.tr()), findsNothing); + }); + + testWidgets('rien trouvé mais tout non analysé (échec après l\'appel) : ' + 'la mention et « Réessayer », jamais « Aucune correction »', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: meeting, + stored: const EnglishFeedbackEntity( + unanalyzedSegmentIds: ['seg-0', 'seg-2', 'seg-3'], + ), + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await open(tester); + + expect(unanalyzed(), findsOneWidget); + expect(retry(), findsOneWidget); + expect(find.text('history.detail.coach_perfect'.tr()), findsNothing); + }); + + testWidgets('« Réessayer » ne renvoie que les phrases non analysées ; la ' + 'mention disparaît, les corrections s\'ajoutent et sont rangées', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: meeting, + stored: const EnglishFeedbackEntity( + corrections: [first], + unanalyzedSegmentIds: ['seg-2', 'seg-3'], + ), + replyFor: (_) => ok( + feedbackJson(<(String, String)>[('He have sent', 'He has sent')]), + ), + ); + await open(tester); + + await tester.tap(retry()); + await until(tester, () => unanalyzed().evaluate().isEmpty); + + final String sent = http.bodies.map(jsonEncode).join('\n'); + expect(sent, contains('He have sent the deck')); + expect(sent, contains('We was ready for the demo')); + expect(sent, isNot(contains('I am agree with you'))); + expect(sent, isNot(contains('budget by Friday'))); + expect(unanalyzed(), findsNothing); + expect(find.textContaining('He has sent'), findsWidgets); + expect(find.textContaining('I agree'), findsWidgets); + final EnglishFeedbackEntity? after = await saved(tester); + expect( + after?.corrections.map((EnglishCorrectionEntity c) => c.corrected), + unorderedEquals(['I agree', 'He has sent']), + ); + expect(after?.unanalyzedSegmentIds, isEmpty); + }); + + testWidgets('« Réessayer » échoue encore : la mention reste, les ' + 'corrections déjà là aussi', (WidgetTester tester) async { + await seed( + tester, + segments: meeting, + stored: const EnglishFeedbackEntity( + corrections: [first], + unanalyzedSegmentIds: ['seg-2', 'seg-3'], + ), + replyFor: (_) => const UnreachableReply(), + ); + await open(tester); + + await tester.tap(retry()); + // Fin de la nouvelle tentative : requête partie, plus rien en cours. + await until( + tester, + () => + http.requests.isNotEmpty && + find.text('history.detail.coach_loading'.tr()).evaluate().isEmpty, + ); + + expect(unanalyzed(), findsOneWidget); + expect(retry(), findsOneWidget); + expect(find.textContaining('I agree'), findsWidgets); + final EnglishFeedbackEntity? after = await saved(tester); + expect(after?.corrections.single.corrected, 'I agree'); + expect(after?.unanalyzedSegmentIds.toSet(), {'seg-2', 'seg-3'}); + }); + + testWidgets('« Coach anglais » à la demande sur une longue note, une ' + 'partie en échec : corrections montrées, mention, rangé pour la ' + 'réouverture', (WidgetTester tester) async { + final List hour = [ + for (int i = 0; i < 720; i++) + noteSegment( + i, + 'Line $i: we need to check the figures for the next release.', + source: AudioSource.input, + ), + ]; + await seed( + tester, + segments: hour, + replyFor: (int i) => i == 1 + ? const UnreachableReply() + : ok( + feedbackJson(<(String, String)>[('phrase $i', 'corrigée $i')]), + ), + ); + await open(tester); + + await tester.tap(coachAction()); + await until(tester, () => unanalyzed().evaluate().isNotEmpty); + + expect(http.requests.length, greaterThan(2)); + expect(unanalyzed(), findsOneWidget); + expect(find.textContaining('corrigée 0'), findsWidgets); + expect(find.textContaining('llm.error.unreachable'.tr()), findsNothing); + + await open(tester); + expect(unanalyzed(), findsOneWidget, reason: 'survit à la réouverture'); + }); + + testWidgets('« Coach anglais » à la demande, le modèle ne trouve rien : ' + '« Aucune correction », aucune erreur', (WidgetTester tester) async { + await seed( + tester, + segments: meeting, + replyFor: (_) => ok( + jsonEncode({ + 'overall': 'Très bon niveau.', + 'corrections': [], + }), + ), + ); + await open(tester); + + await tester.tap(coachAction()); + await until( + tester, + () => find + .text('history.detail.coach_perfect'.tr()) + .evaluate() + .isNotEmpty, + ); + + expect(find.text('history.detail.coach_perfect'.tr()), findsOneWidget); + expect(find.textContaining('llm.error.malformed'.tr()), findsNothing); + expect(unanalyzed(), findsNothing); + }); + + group('rien en anglais à analyser', () { + final List allFrench = [ + noteSegment( + 0, + 'Je pense que le budget est validé pour la semaine.', + source: AudioSource.input, + ), + noteSegment(1, 'We need the budget by Friday.'), + noteSegment(2, 'On utilise Slack pour ça.', source: AudioSource.input), + ]; + final List noMic = [ + noteSegment(0, 'We need the budget by Friday.'), + noteSegment(1, 'Can you share the slides with the team?'), + ]; + + for (final (String name, List segments) + in <(String, List)>[ + ('tout en français', allFrench), + ('aucune ligne du micro', noMic), + ]) { + testWidgets('$name, passe d\'après l\'appel faite : la note dit ' + 'qu\'il n\'y avait rien en anglais à analyser, jamais « Aucune ' + 'correction »', (WidgetTester tester) async { + await seed( + tester, + segments: segments, + postCall: true, + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await open(tester); + + expect(http.requests, isEmpty); + expect(find.text('coach.nothing_to_analyse'.tr()), findsOneWidget); + expect(find.text('history.detail.coach_perfect'.tr()), findsNothing); + }); + } + + testWidgets('« Coach anglais » à la demande sur une note tout en ' + 'français : même message, rien n\'est envoyé', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: allFrench, + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + await open(tester); + + await tester.tap(coachAction()); + await until( + tester, + () => + find.text('coach.nothing_to_analyse'.tr()).evaluate().isNotEmpty, + ); + + expect(http.requests, isEmpty); + expect(find.text('coach.nothing_to_analyse'.tr()), findsOneWidget); + expect(find.text('history.detail.coach_perfect'.tr()), findsNothing); + }); + }); + + testWidgets('relancer à la main reprend TOUTES les phrases, même celles ' + 'corrigées en direct, et remplace leur retour', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: meeting, + // Retour rangé après un direct qui avait corrigé seg-0. + stored: const EnglishFeedbackEntity( + corrections: [first], + ), + replyFor: (_) => ok( + feedbackJson(<(String, String)>[('He have sent', 'He has sent')]), + ), + ); + await open(tester); + + await tester.tap(coachAction()); + await until( + tester, + () => find.textContaining('He has sent').evaluate().isNotEmpty, + ); + + final String sent = http.bodies.map(jsonEncode).join('\n'); + expect(sent, contains('I am agree with you on this point.')); + expect(sent, contains('He have sent the deck to the client.')); + expect(sent, contains('We was ready for the demo yesterday.')); + expect( + (await saved( + tester, + ))?.corrections.map((EnglishCorrectionEntity c) => c.corrected), + ['He has sent'], + ); + }); + + testWidgets('retour rangé avant ces champs (sans heure ni partie non ' + 'analysée) : la note s\'ouvre et le montre', ( + WidgetTester tester, + ) async { + await seed( + tester, + segments: meeting, + rawStored: jsonEncode({ + 'summary': 'Résumé.', + 'feedback': { + 'overall': 'Bon niveau.', + 'corrections': >[ + { + 'original': 'I am agree', + 'corrected': 'I agree', + 'category': 'grammar', + 'explanation': '« agree » est un verbe.', + }, + ], + }, + 'micText': null, + 'speakers': [], + }), + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await open(tester); + + expect(tester.takeException(), isNull); + expect(find.textContaining('« agree » est un verbe.'), findsOneWidget); + expect(unanalyzed(), findsNothing); + }); + }); +} diff --git a/apps/app_macos/test/features/history/local_model_selection_test.dart b/apps/app_macos/test/features/history/local_model_selection_test.dart index 35aba800..c6349d73 100644 --- a/apps/app_macos/test/features/history/local_model_selection_test.dart +++ b/apps/app_macos/test/features/history/local_model_selection_test.dart @@ -118,7 +118,7 @@ void main() { await c .read(liveTranscriptionViewModelProvider.notifier) - .coachAfterCall('I am agree with you.', sessionId: 's1'); + .coachAfterCall(kShortMeeting, sessionId: 's1'); expect(adapter.requests, isEmpty); expect(ollama.ensureReadyCalls, 0); diff --git a/apps/app_macos/test/features/history/summary_row_owners_test.dart b/apps/app_macos/test/features/history/summary_row_owners_test.dart index fb40d07a..bf2fce61 100644 --- a/apps/app_macos/test/features/history/summary_row_owners_test.dart +++ b/apps/app_macos/test/features/history/summary_row_owners_test.dart @@ -151,7 +151,7 @@ void main() { await c .read(liveTranscriptionViewModelProvider.notifier) - .coachAfterCall('I am agree with you.', sessionId: 's1'); + .coachAfterCall(kShortMeeting, sessionId: 's1'); final SessionAnalysis saved = await storedAnalysis(db); expect(saved.feedback?.overall, 'Bon niveau général.'); diff --git a/apps/app_macos/test/features/live_transcription/live_coach_keep_test.dart b/apps/app_macos/test/features/live_transcription/live_coach_keep_test.dart new file mode 100644 index 00000000..432cefb7 --- /dev/null +++ b/apps/app_macos/test/features/live_transcription/live_coach_keep_test.dart @@ -0,0 +1,170 @@ +import 'dart:convert'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:dio/dio.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/llm/llm_settings.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; +import 'package:ici_transcript/core/platform/prefs_store.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_transcription.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/core/providers/services/process_manager.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; + +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/llm_fakes.dart' show kFeedbackJson, streamOf; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Ce que le coach en direct a trouvé survit (revue de la PR #26). +/// +/// Besoin : les corrections trouvées pendant la réunion sont rangées avec +/// la note DÈS Arrêter, coach d'après l'appel activé ou non : même si +/// chaque lot d'après l'appel échoue ensuite, et même si l'app quitte +/// pendant cette passe, la note les montre au lancement suivant. +/// +/// Vrai view model du direct, vrai `LiveTranscriptionService` (le test joue +/// le serveur), vrai coach en direct et vrai `activeLlmProvider` (Claude +/// autorisé), transport factice, base en mémoire relue par un 2e conteneur +/// (= relance de l'app, vrai `SummaryService`). +void main() { + late LiveServiceHarness live; + late AppDatabase db; + late RecordingHttpAdapter http; + late ProviderContainer c; + late bool quit; + + List overrides(LiveServiceHarness harness) => [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + liveTranscriptionServiceProvider.overrideWithValue(harness.service), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: harness.process), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + apiKeyStoreProvider.overrideWithValue( + InMemoryApiKeyStore({ + LlmProviderId.anthropic: 'sk-ant-test-SECRET-0123456789', + }), + ), + llmDioProvider.overrideWithValue(Dio()..httpClientAdapter = http), + ]; + + setUp(() async { + resetPrefs(); + await PrefsStore().update({ + LlmSettings.providerKey: LlmProviderId.anthropic.name, + LlmSettings.cloudAllowedKey: true, + }); + live = LiveServiceHarness(FakeAsync()); + db = memoryDatabase(); + // Le direct trouve « I am agree » → « I agree ». + http = RecordingHttpAdapter( + reply: BodyReply( + 200, + streamOf(LlmProviderId.anthropic, jsonEncode(kFeedbackJson)), + ), + ); + c = ProviderContainer(overrides: overrides(live)); + quit = false; + addTearDown(() async { + if (!quit) c.dispose(); + await db.close(); + }); + }); + + LiveTranscriptionViewModel vm() => + c.read(liveTranscriptionViewModelProvider.notifier); + LiveCoachService coach() => c.read(liveCoachServiceProvider); + + Future userSays(String text) async { + live.fakeRemote.emitDone(AudioSource.input, text); + await eventually( + () => expect( + c + .read(liveTranscriptionViewModelProvider) + .segments + .map((TranscriptSegmentEntity s) => s.text), + contains(text), + ), + ); + } + + /// Note enregistrée avec le coach en direct ET le coach d'après l'appel ; + /// le direct a trouvé une correction, une 2e phrase reste pour la passe + /// d'après l'appel, qui répondra [afterCall]. + Future meetingThenStop(FakeReply afterCall) async { + vm(); + await Future.delayed(const Duration(milliseconds: 100)); + vm() + ..toggleCoach() + ..toggleLiveCoach(); + await vm().startSession(); + final String sessionId = live.transcription.currentSessionStream.value!.id; + await userSays('I am agree with you on this point.'); + await eventually(() => expect(coach().snapshot.corrections, isNotEmpty)); + await userSays('He have sent the deck to the client.'); + http.reply = afterCall; + + await vm().stopSession(); + return sessionId; + } + + Future storedIn( + ProviderContainer container, + String sessionId, + ) async => SessionAnalysis.fromStored( + await container + .read(summaryServiceProvider) + .getSummaryForSession(sessionId), + ).feedback; + + List? correctedOf(EnglishFeedbackEntity? f) => + f?.corrections.map((EnglishCorrectionEntity x) => x.corrected).toList(); + + test('rangé dès Arrêter, avant la passe d\'après l\'appel', () async { + final String id = await meetingThenStop(const HangReply()); + + expect(correctedOf(await storedIn(c, id)), contains('I agree')); + }); + + test('chaque lot d\'après l\'appel échoue : la correction du direct reste, ' + 'les phrases restantes sont non analysées', () async { + final String id = await meetingThenStop(const UnreachableReply()); + + await eventually(() async { + final EnglishFeedbackEntity? f = await storedIn(c, id); + expect(f?.unanalyzedSegmentIds, isNotEmpty); + expect(correctedOf(f), contains('I agree')); + }); + }); + + test('l\'app quitte pendant la passe d\'après l\'appel : au lancement ' + 'suivant, la note montre la correction du direct', () async { + final String id = await meetingThenStop(const HangReply()); + await eventually( + () => expect(http.requests.length, greaterThanOrEqualTo(2)), + ); + + // Quitter, puis relancer sur la même base. + c.dispose(); + quit = true; + final ProviderContainer relaunched = ProviderContainer( + overrides: overrides(LiveServiceHarness(FakeAsync())), + ); + addTearDown(relaunched.dispose); + + expect(correctedOf(await storedIn(relaunched, id)), contains('I agree')); + }); +} diff --git a/apps/app_macos/test/features/live_transcription/live_coach_panel_test.dart b/apps/app_macos/test/features/live_transcription/live_coach_panel_test.dart new file mode 100644 index 00000000..7b89f2aa --- /dev/null +++ b/apps/app_macos/test/features/live_transcription/live_coach_panel_test.dart @@ -0,0 +1,293 @@ +import 'dart:async'; +import 'dart:ui' show Tristate; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:dio/dio.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.screen.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.state.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; + +import '../../helpers/fake_view_models.dart' show settle; +import '../../helpers/live_answers_fakes.dart' show LiveAnswersHarness; +import '../../helpers/llm_fakes.dart' show writeLlmPrefs; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Écran du direct dans l'état donné ; l'interrupteur garde le vrai code. +class _ShownLive extends LiveTranscriptionViewModel { + _ShownLive(this.initial); + + final LiveTranscriptionState initial; + + @override + LiveTranscriptionState build() => initial; + + @override + Future recheckPermissions() async {} +} + +/// Coach en direct dont le test choisit ce qu'il a trouvé. +class _ShownCoach extends LiveCoachService { + _ShownCoach(this.current) : super(resolveModel: () async => null); + + LiveCoachSnapshot current; + final StreamController _changes = + StreamController.broadcast(); + + @override + LiveCoachSnapshot get snapshot => current; + + @override + Stream get snapshots async* { + yield current; + yield* _changes.stream; + } + + void show(LiveCoachSnapshot next) { + current = next; + _changes.add(next); + } +} + +/// Coach en direct à l'écran (interrupteur et bloc discret du panneau). +/// +/// Besoin : +/// - interrupteur « Coach en direct », coupé par défaut, avant de démarrer ; +/// disponible seulement avec un fournisseur en ligne configuré ET +/// autorisé ; sinon désactivé, et l'écran dit pourquoi (le modèle local +/// ralentirait la transcription) ; +/// - pendant la réunion, coach activé : au plus les 3 corrections les plus +/// récentes (heure dans la note) dans un bloc discret ; échec : rien de +/// rouge, l'état « indisponible », la transcription reste là ; coach +/// coupé : pas de bloc. +/// +/// API supposée : `LiveTranscriptionState.isLiveCoachEnabled`, +/// `toggleLiveCoach()`, `liveCoachServiceProvider` (`snapshot`, +/// `snapshots`). L'interrupteur porte le nom accessible de son libellé +/// (`coach.live.option`) ; raison : `coach.live.unavailable` ; état : +/// `coach.live.state_unavailable`. +void main() { + late AppDatabase db; + + final DateTime t = DateTime(2026, 11, 23, 10); + TranscriptSegmentEntity line(String text) => TranscriptSegmentEntity( + id: 'seg-1', + sessionId: 's1', + source: AudioSource.input, + text: text, + timestampMs: 5000, + createdAt: t, + ); + + EnglishCorrectionEntity fix(int minute) => EnglishCorrectionEntity( + original: 'mistake number $minute', + corrected: 'better phrasing $minute', + category: 'grammar', + explanation: 'Raison $minute.', + timestampMs: minute * 60000, + ); + + Future io(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 30)), + ); + await settle(tester, frames: 2); + } + } + + /// [cloud] : Claude configuré et autorisé ; sinon clé présente mais envoi + /// coupé, modèle local installé. + Future pumpLive( + WidgetTester tester, { + required LiveTranscriptionState state, + required bool cloud, + LiveCoachService? coach, + }) async { + await tester.runAsync( + () => writeLlmPrefs( + cloudAllowed: cloud, + preferred: LlmProviderId.anthropic, + ), + ); + db = memoryDatabase(); + addTearDown(db.close); + await pumpLocalized( + tester, + const LiveTranscriptionScreen(), + size: const Size(1440, 900), + settle: false, + overrides: [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + apiKeyStoreProvider.overrideWithValue( + InMemoryApiKeyStore({ + LlmProviderId.anthropic: 'sk-ant-test-SECRET-0123456789', + }), + ), + llmDioProvider.overrideWithValue( + Dio()..httpClientAdapter = RecordingHttpAdapter(), + ), + liveTranscriptionViewModelProvider.overrideWith( + () => _ShownLive(state), + ), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + if (coach != null) liveCoachServiceProvider.overrideWithValue(coach), + ], + ); + await io(tester); + } + + /// Interrupteur dont le nom accessible contient le libellé. + SemanticsFinder liveSwitch() => find.semantics.byPredicate((SemanticsNode n) { + final SemanticsData d = n.getSemanticsData(); + return d.label.contains('coach.live.option'.tr()) && + d.flagsCollection.isToggled != Tristate.none; + }); + + SemanticsData switchData() => + liveSwitch().evaluate().single.getSemanticsData(); + + group('avant de démarrer', () { + testWidgets('Claude configuré et autorisé : interrupteur coupé par défaut, ' + 'il s\'active', (WidgetTester tester) async { + final SemanticsHandle handle = tester.ensureSemantics(); + await pumpLive( + tester, + state: LiveTranscriptionState.initial(), + cloud: true, + ); + + expect(switchData().flagsCollection.isEnabled, Tristate.isTrue); + expect(switchData().flagsCollection.isToggled, Tristate.isFalse); + expect(find.text('coach.live.unavailable'.tr()), findsNothing); + + tester.semantics.tap(liveSwitch()); + await io(tester); + + expect(switchData().flagsCollection.isToggled, Tristate.isTrue); + handle.dispose(); + }); + + testWidgets('envoi coupé, modèle local seulement : interrupteur ' + 'désactivé, l\'écran dit pourquoi', (WidgetTester tester) async { + final SemanticsHandle handle = tester.ensureSemantics(); + await pumpLive( + tester, + state: LiveTranscriptionState.initial(), + cloud: false, + ); + + expect(switchData().flagsCollection.isEnabled, Tristate.isFalse); + expect(find.text('coach.live.unavailable'.tr()), findsOneWidget); + handle.dispose(); + }); + }); + + group('pendant la réunion', () { + final LiveTranscriptionState recording = LiveTranscriptionState( + isRecording: true, + isLiveCoachEnabled: true, + segments: [ + line('I am agree with you on this point.'), + ], + ); + + testWidgets('au plus les 3 corrections les plus récentes, avec leur ' + 'heure', (WidgetTester tester) async { + final _ShownCoach coach = _ShownCoach( + LiveCoachSnapshot( + corrections: [ + for (final int m in [1, 2, 3, 4, 5]) fix(m), + ], + ), + ); + await pumpLive(tester, state: recording, cloud: true, coach: coach); + + for (final int m in [3, 4, 5]) { + expect(find.textContaining('better phrasing $m'), findsOneWidget); + } + for (final int m in [1, 2]) { + expect(find.textContaining('better phrasing $m'), findsNothing); + } + expect(find.textContaining('05:00'), findsWidgets); + }); + + testWidgets('une nouvelle correction arrive : elle apparaît, la plus ' + 'ancienne des 3 sort', (WidgetTester tester) async { + final _ShownCoach coach = _ShownCoach( + LiveCoachSnapshot( + corrections: [fix(1), fix(2), fix(3)], + ), + ); + await pumpLive(tester, state: recording, cloud: true, coach: coach); + + coach.show( + LiveCoachSnapshot( + corrections: [ + fix(1), + fix(2), + fix(3), + fix(4), + ], + ), + ); + await io(tester); + + expect(find.textContaining('better phrasing 4'), findsOneWidget); + expect(find.textContaining('better phrasing 1'), findsNothing); + }); + + testWidgets('coach en échec : « indisponible », rien de rouge, la ' + 'transcription reste', (WidgetTester tester) async { + await pumpLive( + tester, + state: recording, + cloud: true, + coach: _ShownCoach(const LiveCoachSnapshot(unavailable: true)), + ); + + expect( + find.textContaining('coach.live.state_unavailable'.tr()), + findsOneWidget, + ); + expect(find.textContaining('I am agree with you'), findsOneWidget); + expect(find.textContaining('llm.error'), findsNothing); + }); + + testWidgets('coach en direct coupé : pas de bloc', ( + WidgetTester tester, + ) async { + await pumpLive( + tester, + state: recording.copyWith(isLiveCoachEnabled: false), + cloud: true, + coach: _ShownCoach( + LiveCoachSnapshot(corrections: [fix(1)]), + ), + ); + + expect(find.textContaining('better phrasing 1'), findsNothing); + expect( + find.textContaining('coach.live.state_unavailable'.tr()), + findsNothing, + ); + }); + }); +} diff --git a/apps/app_macos/test/features/live_transcription/live_coach_wiring_test.dart b/apps/app_macos/test/features/live_transcription/live_coach_wiring_test.dart new file mode 100644 index 00000000..266a61b0 --- /dev/null +++ b/apps/app_macos/test/features/live_transcription/live_coach_wiring_test.dart @@ -0,0 +1,317 @@ +import 'dart:convert'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_data/database/dao/summary.dao.dart'; +import 'package:core_data/model/utterance_window.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:dio/dio.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/application/services/llm/llm_settings.dart'; +import 'package:ici_transcript/application/services/session_analysis.dart'; +import 'package:ici_transcript/core/platform/prefs_store.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answer_model.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_transcription.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/core/providers/services/process_manager.service.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; + +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/llm_fakes.dart' show kFeedbackJson, streamOf; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Coach en direct branché pour de vrai : vrai view model du direct, vrai +/// `LiveTranscriptionService` (le test joue le serveur), vrai +/// `activeLlmProvider` (prefs.json + trousseau en mémoire), transport HTTP +/// factice (aucun réseau), Ollama factice « installé », base en mémoire. +/// +/// Besoin : interrupteur « Coach en direct » coupé par défaut, qui survit à +/// un redémarrage ; activé, les phrases anglaises finales de l'utilisateur +/// partent au fournisseur EN LIGNE configuré et autorisé, jamais au modèle +/// local, jamais quand l'envoi est coupé (même en pleine réunion) ; jamais +/// une phrase dictée pendant la réunion (la dictée la route hors de +/// `finalizedSegmentsStream`, épinglé par live_answers_dictation_test) ; un +/// modèle muet ne bloque ni la transcription ni Arrêter ; ce que le direct a +/// trouvé est rangé dans la note à l'arrêt, même coach d'après l'appel +/// coupé. +/// +/// API supposée : `LiveTranscriptionState.isLiveCoachEnabled`, +/// `LiveTranscriptionViewModel.toggleLiveCoach()` (rangé dans prefs.json) ; +/// `liveCoachServiceProvider` (keepAlive, lib/core/providers/services/ +/// live_coach.service.provider.dart) construit sur `resolveLiveAnswerModel`, +/// démarré/arrêté avec l'enregistrement quand l'interrupteur est activé, +/// nourri par `finalizedSegmentsStream`. +void main() { + late LiveServiceHarness live; + late AppDatabase db; + late RecordingHttpAdapter http; + late ProviderContainer c; + + const String claudeKey = 'sk-ant-test-SECRET-0123456789'; + + Future launch({required bool cloud, Duration? interval}) async { + resetPrefs(); + await PrefsStore().update({ + LlmSettings.providerKey: LlmProviderId.anthropic.name, + LlmSettings.cloudAllowedKey: cloud, + }); + live = LiveServiceHarness(FakeAsync()); + db = memoryDatabase(); + http = RecordingHttpAdapter( + // Réponse valable : « aucune correction ». + reply: BodyReply( + 200, + streamOf( + LlmProviderId.anthropic, + jsonEncode({ + 'overall': 'Bon niveau.', + 'corrections': [], + }), + ), + ), + ); + c = ProviderContainer( + overrides: [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + liveTranscriptionServiceProvider.overrideWithValue(live.service), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: live.process), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + apiKeyStoreProvider.overrideWithValue( + InMemoryApiKeyStore({ + LlmProviderId.anthropic: claudeKey, + }), + ), + llmDioProvider.overrideWithValue(Dio()..httpClientAdapter = http), + // Même service, même modèle résolu ; seul l'écart entre deux lots + // est raccourci, pour ne pas attendre 20 s. + if (interval != null) + liveCoachServiceProvider.overrideWith( + (Ref ref) => LiveCoachService( + resolveModel: () => resolveLiveAnswerModel(ref), + interval: interval, + ), + ), + ], + ); + addTearDown(() async { + c.dispose(); + await db.close(); + }); + } + + LiveTranscriptionViewModel vm() => + c.read(liveTranscriptionViewModelProvider.notifier); + LiveCoachService coach() => c.read(liveCoachServiceProvider); + + /// Démarre une note ; [liveCoach] : interrupteur activé avant. + Future startRecording({required bool liveCoach}) async { + vm(); + await Future.delayed(const Duration(milliseconds: 100)); + if (liveCoach) vm().toggleLiveCoach(); + await vm().startSession(); + return live.transcription.currentSessionStream.value!.id; + } + + /// L'utilisateur dit [text] ; attendu comme segment de la note. + Future userSays(String text) async { + live.fakeRemote.emitDone(AudioSource.input, text); + await eventually( + () => expect( + c + .read(liveTranscriptionViewModelProvider) + .segments + .map((TranscriptSegmentEntity s) => s.text), + contains(text), + ), + ); + } + + bool sentAnywhere(String text) => http.bodies.any( + (Map? b) => jsonEncode(b).contains(text), + ); + + group('interrupteur', () { + test( + 'coupé par défaut ; activé, il l\'est encore au lancement suivant', + () async { + await launch(cloud: true); + vm(); + await Future.delayed(const Duration(milliseconds: 100)); + expect( + c.read(liveTranscriptionViewModelProvider).isLiveCoachEnabled, + isFalse, + ); + + vm().toggleLiveCoach(); + // Choix LLM déjà rangés (2 clés) : attendre celle de l'interrupteur. + await eventually(() => expect(readPrefs().length, greaterThan(2))); + + final ProviderContainer again = ProviderContainer( + overrides: [ + liveTranscriptionServiceProvider.overrideWithValue( + LiveServiceHarness(FakeAsync()).service, + ), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: live.process), + ), + audioCaptureChannelProvider.overrideWithValue( + DevicesAudioChannel(), + ), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + ], + ); + addTearDown(again.dispose); + again.read(liveTranscriptionViewModelProvider); + await eventually( + () => expect( + again.read(liveTranscriptionViewModelProvider).isLiveCoachEnabled, + isTrue, + ), + ); + }, + ); + + test('coupé : la phrase de l\'utilisateur ne part pas au coach (seule ' + 'la question des autres part)', () async { + await launch(cloud: true); + await startRecording(liveCoach: false); + + await userSays('I am agree with you on this point.'); + live.fakeRemote.emitDone( + AudioSource.output, + 'Quand est-ce que vous livrez le lot 1 ?', + ); + await eventually(() => expect(http.requests, isNotEmpty)); + + expect(http.requests, hasLength(1)); + expect(sentAnywhere('Quand est-ce que vous livrez'), isTrue); + }); + }); + + group('activé', () { + test('Claude configuré et autorisé : la phrase anglaise de ' + 'l\'utilisateur part chez Claude, pendant la réunion', () async { + await launch(cloud: true); + await startRecording(liveCoach: true); + + await userSays('I am agree with you on this point.'); + await eventually( + () => + expect(sentAnywhere('I am agree with you on this point.'), isTrue), + ); + + expect( + http.requests.map((RequestOptions r) => r.uri.host).toSet(), + {kProviderHost[LlmProviderId.anthropic]!}, + ); + }); + + test( + 'envoi coupé (clé présente, modèle local installé) : rien ne part, ' + 'ni chez Claude ni au modèle local ; le coach se dit indisponible', + () async { + await launch(cloud: false); + await startRecording(liveCoach: true); + + await userSays('I am agree with you on this point.'); + await eventually(() => expect(coach().snapshot.unavailable, isTrue)); + + expect(http.requests, isEmpty); + }, + ); + + test('envoi coupé en pleine réunion : le lot suivant ne part pas', () async { + await launch(cloud: true, interval: const Duration(milliseconds: 50)); + await startRecording(liveCoach: true); + await userSays('I am agree with you on this point.'); + await eventually(() => expect(http.requests, hasLength(1))); + // Le 1er lot a réussi : le coach n'est pas indisponible avant la coupure. + await eventually(() => expect(coach().coachedSegmentIds, isNotEmpty)); + expect(coach().snapshot.unavailable, isFalse); + + await PrefsStore().update({ + LlmSettings.cloudAllowedKey: false, + }); + await userSays('He have sent the deck to the client.'); + await eventually(() => expect(coach().snapshot.unavailable, isTrue)); + + expect(http.requests, hasLength(1)); + expect(sentAnywhere('He have sent the deck'), isFalse); + }); + + test( + 'une phrase dictée pendant la réunion n\'atteint jamais le coach', + () async { + await launch(cloud: true); + await startRecording(liveCoach: true); + final List dictated = []; + final int pressAt = DateTime.now().millisecondsSinceEpoch; + final MeetingDictation d = live.service.beginDictation()!; + d.onText = (String text, bool _) => dictated.add(text); + await Future.delayed(const Duration(milliseconds: 100)); + live.fakeRemote.emitDone( + AudioSource.input, + 'DICTATED please remind the supplier about the invoice.', + window: UtteranceWindow(startMs: pressAt + 50, endMs: pressAt + 90), + ); + await eventually(() => expect(dictated, isNotEmpty)); + d.release(); + + await userSays('I am agree with you on this point.'); + await eventually( + () => expect(sentAnywhere('I am agree with you'), isTrue), + ); + + expect(sentAnywhere('DICTATED'), isFalse); + }, + ); + + test( + 'modèle muet : la transcription continue et Arrêter se termine', + () async { + await launch(cloud: true); + http.reply = const HangReply(); + await startRecording(liveCoach: true); + await userSays('I am agree with you on this point.'); + await eventually(() => expect(http.requests, isNotEmpty)); + + await userSays('He have sent the deck to the client.'); + final String? id = await vm().stopSession(); + + expect(id, isNotNull); + }, + ); + + test('Arrêter (coach d\'après l\'appel coupé) : ce que le direct a trouvé ' + 'est rangé dans la note', () async { + await launch(cloud: true); + http.reply = BodyReply( + 200, + streamOf(LlmProviderId.anthropic, jsonEncode(kFeedbackJson)), + ); + final String sessionId = await startRecording(liveCoach: true); + await userSays('I am agree with you on this point.'); + await eventually(() => expect(coach().snapshot.corrections, isNotEmpty)); + + await vm().stopSession(); + + final EnglishFeedbackEntity? saved = SessionAnalysis.fromStored( + (await SummaryDao(db).getBySessionId(sessionId))?.content, + ).feedback; + expect(saved?.corrections.single.corrected, 'I agree'); + }); + }); +} diff --git a/apps/app_macos/test/features/live_transcription/post_call_coach_batches_test.dart b/apps/app_macos/test/features/live_transcription/post_call_coach_batches_test.dart new file mode 100644 index 00000000..3e72befd --- /dev/null +++ b/apps/app_macos/test/features/live_transcription/post_call_coach_batches_test.dart @@ -0,0 +1,414 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_data/database/app_database.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.state.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.view_model.dart'; + +import '../../helpers/llm_fakes.dart' + show noteSegment, seedNote, storedAnalysis, streamOf, writeLlmPrefs; +import '../../helpers/fake_view_models.dart' show FakeSettingsViewModel; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/settings_fakes.dart'; + +class _LiveVm extends LiveTranscriptionViewModel { + @override + LiveTranscriptionState build() => LiveTranscriptionState.initial(); +} + +/// Transport factice dont la réponse dépend du rang de la requête (0, 1…). +class _ByIndexHttp extends RecordingHttpAdapter { + _ByIndexHttp(this.replyFor); + + final FakeReply Function(int index) replyFor; + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) { + reply = replyFor(requests.length); + return super.fetch(options, requestStream, cancelFuture); + } +} + +/// La 1re requête reste en vol jusqu'à [release] ; les suivantes répondent +/// par [replyFor]. +class _GatedHttp extends _ByIndexHttp { + _GatedHttp(super.replyFor); + + final Completer _gate = Completer(); + final Completer firstSent = Completer(); + int _seen = 0; + + void release() => _gate.complete(); + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + if (_seen++ == 0) { + firstSent.complete(); + await _gate.future; + } + return super.fetch(options, requestStream, cancelFuture); + } +} + +/// Coach en direct qui a déjà trouvé [found] sur les phrases [coached] +/// pendant la note [sessionId]. +class _FoundLive extends LiveCoachService { + _FoundLive(this.found, this.coached, {this.sessionId = 's1'}) + : super(resolveModel: () async => null); + + final String sessionId; + + final List found; + final Set coached; + + @override + LiveCoachSnapshot get snapshot => + LiveCoachSnapshot(sessionId: sessionId, corrections: found); + + @override + Set get coachedSegmentIds => coached; +} + +/// Coach de fin d'appel (interrupteur « Coach anglais » activé), par le vrai +/// view model du direct ; modèle local installé, transport factice. +/// +/// Besoin : à la fin d'une note, le retour est produit sur la seule parole +/// anglaise de l'utilisateur, par lots bornés (règles détaillées dans +/// test/application/services/llm/coach_meeting_test.dart), et la NOTE garde +/// le résultat, quel qu'il soit : +/// - aucune correction : un retour vide est rangé (la note dira « Aucune +/// correction », pas le silence d'aujourd'hui) ; +/// - une partie échoue : corrections gardées + phrases non analysées rangées +/// (la note propose de réessayer) ; +/// - tout échoue : la note le dit quand même (toutes les phrases anglaises +/// de l'utilisateur rangées non analysées) ; aujourd'hui l'échec reste +/// dans l'état du direct et n'atteint jamais la note ; +/// - ce que le coach en direct a trouvé POUR CETTE NOTE est rangé avec, et +/// ses phrases ne repartent pas (pas de doublon, pas de travail refait) ; +/// ce qu'il a gardé d'une note précédente n'est jamais mêlé à celle-ci. +/// +/// API supposée : `coachAfterCall(segments, {sessionId})`, segments = +/// `List` (remplace la version qui prenait un +/// texte : elle ne voyait ni source, ni heure, ni repère) ; lit +/// `liveCoachServiceProvider` (`snapshot.sessionId`, `snapshot.corrections`, +/// `coachedSegmentIds`) et ne s'en sert que si `snapshot.sessionId` est +/// celui de la note. +void main() { + late AppDatabase db; + late RecordingHttpAdapter http; + + String feedbackJson(List<(String, String)> fixes) => + jsonEncode({ + 'overall': 'Bon niveau.', + 'corrections': >[ + for (final (String original, String corrected) in fixes) + { + 'original': original, + 'corrected': corrected, + 'category': 'grammar', + 'explanation': 'Explication courte.', + }, + ], + }); + + FakeReply ok(String json) => + BodyReply(200, streamOf(LlmProviderId.ollama, json)); + + Future launch({ + required List segments, + required FakeReply Function(int index) replyFor, + LiveCoachService? live, + _ByIndexHttp? adapter, + }) async { + await writeLlmPrefs(cloudAllowed: false); + db = memoryDatabase(); + http = adapter ?? _ByIndexHttp(replyFor); + final ProviderContainer c = ProviderContainer( + overrides: [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + llmDioProvider.overrideWithValue(Dio()..httpClientAdapter = http), + liveTranscriptionViewModelProvider.overrideWith(_LiveVm.new), + if (live != null) liveCoachServiceProvider.overrideWithValue(live), + settingsViewModelProvider.overrideWith(FakeSettingsViewModel.new), + ], + ); + addTearDown(() async { + c.dispose(); + await db.close(); + }); + await seedNote(c, segments); + return c; + } + + Future coach(ProviderContainer c, List s) => c + .read(liveTranscriptionViewModelProvider.notifier) + .coachAfterCall(s, sessionId: 's1'); + + String sentAt(int i) => jsonEncode(http.bodies[i]); + String allSent() => http.bodies.map(jsonEncode).join('\n'); + + /// 60 minutes : une phrase anglaise de l'utilisateur toutes les 5 s. + final List hour = [ + for (int i = 0; i < 720; i++) + noteSegment( + i, + 'Line $i: we need to check the figures for the next release.', + source: AudioSource.input, + ), + ]; + + test('seule la parole anglaise du micro part : ni l\'interlocuteur, ni un ' + 'repère, ni une phrase en français', () async { + final List meeting = [ + noteSegment( + 0, + 'I am agree with you on this point.', + source: AudioSource.input, + ), + noteSegment(1, 'We need the budget by Friday.'), + noteSegment( + 2, + LiveTranscriptionService.untranscribedMarkerText(10000, 14000), + source: AudioSource.input, + ), + noteSegment( + 3, + 'Je pense que le budget est validé pour la semaine.', + source: AudioSource.input, + ), + ]; + final ProviderContainer c = await launch( + segments: meeting, + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await coach(c, meeting); + + expect(allSent(), contains('I am agree with you on this point.')); + expect(allSent(), isNot(contains('budget by Friday'))); + expect(allSent(), isNot(contains('Passage non transcrit'))); + expect(allSent(), isNot(contains('le budget est valid'))); + }); + + test('aucune correction : un retour vide est rangé avec la note', () async { + final List meeting = [ + noteSegment( + 0, + 'I agree with you on this point.', + source: AudioSource.input, + ), + ]; + final ProviderContainer c = await launch( + segments: meeting, + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await coach(c, meeting); + + final EnglishFeedbackEntity? saved = (await storedAnalysis(db)).feedback; + expect(saved, isNotNull, reason: 'la note doit dire « Aucune correction »'); + expect(saved!.corrections, isEmpty); + expect(saved.unanalyzedSegmentIds, isEmpty); + }); + + test('60 minutes, une partie échoue : corrections des autres parties et ' + 'phrases non analysées rangées', () async { + final ProviderContainer c = await launch( + segments: hour, + replyFor: (int i) => i == 1 + ? const UnreachableReply() + : ok(feedbackJson(<(String, String)>[('phrase $i', 'corrigée $i')])), + ); + + await coach(c, hour); + + expect(http.requests.length, greaterThan(2)); + final EnglishFeedbackEntity saved = (await storedAnalysis(db)).feedback!; + expect(saved.corrections, hasLength(http.requests.length - 1)); + final Set inFailed = { + for (final TranscriptSegmentEntity s in hour) + if (sentAt(1).contains(s.text)) s.id, + }; + expect(inFailed, isNotEmpty); + expect(saved.unanalyzedSegmentIds.toSet(), inFailed); + }); + + test('tout échoue : la note le dit quand même (toutes les phrases ' + 'anglaises de l\'utilisateur non analysées)', () async { + final List meeting = [ + noteSegment( + 0, + 'I am agree with you on this point.', + source: AudioSource.input, + ), + noteSegment(1, 'We need the budget by Friday.'), + noteSegment( + 2, + 'He have sent the deck to the client.', + source: AudioSource.input, + ), + ]; + final ProviderContainer c = await launch( + segments: meeting, + replyFor: (_) => const UnreachableReply(), + ); + + await coach(c, meeting); + + final EnglishFeedbackEntity? saved = (await storedAnalysis(db)).feedback; + expect(saved, isNotNull, reason: 'l\'échec doit atteindre la note'); + expect(saved!.corrections, isEmpty); + expect(saved.unanalyzedSegmentIds.toSet(), {'seg-0', 'seg-2'}); + }); + + test('modèle local, une longue note en passe d\'après l\'appel, un ' + 'enregistrement démarre : la passe s\'arrête après le lot en cours, ' + 'le reste est noté non analysé', () async { + final _GatedHttp gated = _GatedHttp( + (int i) => + ok(feedbackJson(<(String, String)>[('phrase $i', 'corrigée $i')])), + ); + final ProviderContainer c = await launch( + segments: hour, + replyFor: gated.replyFor, + adapter: gated, + ); + + final Future pass = coach(c, hour); + await gated.firstSent.future; + await c.read(liveTranscriptionViewModelProvider.notifier).startSession(); + gated.release(); + await pass; + + expect(http.requests, hasLength(1), reason: 'aucun lot après le démarrage'); + final EnglishFeedbackEntity saved = (await storedAnalysis(db)).feedback!; + expect(saved.corrections, hasLength(1), reason: 'le lot en cours compte'); + final Set rest = { + for (final TranscriptSegmentEntity s in hour) + if (!sentAt(0).contains(s.text)) s.id, + }; + expect(rest, isNotEmpty); + expect(saved.unanalyzedSegmentIds.toSet(), rest); + }); + + group('après le coach en direct', () { + const EnglishCorrectionEntity foundLive = EnglishCorrectionEntity( + original: 'I am agree', + corrected: 'I agree', + category: 'grammar', + explanation: '« agree » est un verbe.', + timestampMs: 0, + ); + final List meeting = [ + noteSegment( + 0, + 'I am agree with you on this point.', + source: AudioSource.input, + ), + noteSegment( + 1, + 'He have sent the deck to the client.', + source: AudioSource.input, + ), + ]; + + test('les phrases corrigées en direct ne repartent pas ; la note garde ' + 'les deux retours, sans doublon', () async { + final ProviderContainer c = await launch( + segments: meeting, + live: _FoundLive( + const [foundLive], + {'seg-0'}, + ), + // Un modèle qui redit la correction du direct ne la double pas. + replyFor: (_) => ok( + feedbackJson(<(String, String)>[ + ('He have sent', 'He has sent'), + ('I am agree', 'I agree'), + ]), + ), + ); + + await coach(c, meeting); + + expect(allSent(), isNot(contains('I am agree with you'))); + expect(allSent(), contains('He have sent the deck')); + final List saved = (await storedAnalysis(db)) + .feedback! + .corrections + .map((EnglishCorrectionEntity x) => x.corrected) + .toList(); + expect(saved, unorderedEquals(['I agree', 'He has sent'])); + }); + + test('tout corrigé en direct : aucune requête, la note garde le retour ' + 'du direct', () async { + final ProviderContainer c = await launch( + segments: meeting, + live: _FoundLive( + const [foundLive], + {'seg-0', 'seg-1'}, + ), + replyFor: (_) => ok(feedbackJson(<(String, String)>[])), + ); + + await coach(c, meeting); + + expect(http.requests, isEmpty); + expect( + (await storedAnalysis(db)).feedback?.corrections.single.corrected, + 'I agree', + ); + }); + + test('résultats du direct d\'une AUTRE note (direct coupé pour celle-ci) : ' + 'ni rangés ici, ni utilisés pour sauter des phrases', () async { + final ProviderContainer c = await launch( + segments: meeting, + live: _FoundLive( + const [foundLive], + {'seg-0', 'seg-1'}, + sessionId: 'note-precedente', + ), + replyFor: (_) => ok( + feedbackJson(<(String, String)>[('He have sent', 'He has sent')]), + ), + ); + + await coach(c, meeting); + + expect(allSent(), contains('I am agree with you')); + expect(allSent(), contains('He have sent the deck')); + expect( + (await storedAnalysis(db)).feedback?.corrections.map( + (EnglishCorrectionEntity x) => x.corrected, + ), + ['He has sent'], + ); + }); + }); +} diff --git a/apps/app_macos/test/features/live_transcription/post_call_coach_routing_test.dart b/apps/app_macos/test/features/live_transcription/post_call_coach_routing_test.dart index b6fb1bf5..47979ff4 100644 --- a/apps/app_macos/test/features/live_transcription/post_call_coach_routing_test.dart +++ b/apps/app_macos/test/features/live_transcription/post_call_coach_routing_test.dart @@ -20,8 +20,9 @@ class _LiveVm extends LiveTranscriptionViewModel { LiveTranscriptionState build() => LiveTranscriptionState.initial(); } -/// Coach de fin d'appel par le fournisseur actif (besoin B7) ; API -/// existante : `coachAfterCall(micTranscript, sessionId:)`. +/// Coach de fin d'appel par le fournisseur actif (besoin B7) ; API : +/// `coachAfterCall(segments, sessionId:)` (segments de la note ; avant : +/// texte du micro). void main() { late AppDatabase db; late RecordingHttpAdapter adapter; @@ -61,7 +62,7 @@ void main() { Future coach(ProviderContainer c) => c .read(liveTranscriptionViewModelProvider.notifier) - .coachAfterCall('I am agree with you.', sessionId: 's1'); + .coachAfterCall(kShortMeeting, sessionId: 's1'); test('Claude configuré et autorisé, modèle local absent : le coach passe ' 'par Claude, le retour est montré et rangé', () async { diff --git a/apps/app_macos/test/features/live_transcription/post_call_coach_test.dart b/apps/app_macos/test/features/live_transcription/post_call_coach_test.dart index 1e7e1dd9..8b155e7a 100644 --- a/apps/app_macos/test/features/live_transcription/post_call_coach_test.dart +++ b/apps/app_macos/test/features/live_transcription/post_call_coach_test.dart @@ -29,9 +29,9 @@ class _LiveVm extends LiveTranscriptionViewModel { /// Coach de fin d'enregistrement (interrupteur coach activé). /// -/// API supposée : `LiveTranscriptionViewModel.coachAfterCall(micTranscript, -/// sessionId:)`, l'étape coach de `stopSession` rendue publique -/// (@visibleForTesting) — aujourd'hui `_analyzeEnglish`. +/// API supposée : `LiveTranscriptionViewModel.coachAfterCall(segments, +/// sessionId:)` (segments de la note ; avant : texte du micro), l'étape +/// coach de `stopSession` rendue publique (@visibleForTesting). /// /// Besoin B7 : le modèle local répond par le fournisseur Ollama, donc par /// `llmDioProvider` (transport factice), plus par `analyzeEnglish`. @@ -89,7 +89,7 @@ void main() { await c .read(liveTranscriptionViewModelProvider.notifier) - .coachAfterCall('I am agree with you.', sessionId: 's1'); + .coachAfterCall(kShortMeeting, sessionId: 's1'); expect(ollama.ensureReadyCalls, 0, reason: 'téléchargement silencieux'); expect(ollama.analyzeCalls, 0); @@ -106,7 +106,7 @@ void main() { await c .read(liveTranscriptionViewModelProvider.notifier) - .coachAfterCall('I am agree with you.', sessionId: 's1'); + .coachAfterCall(kShortMeeting, sessionId: 's1'); expect(adapter.lastHost, kProviderHost[LlmProviderId.ollama]); expect(c.read(liveTranscriptionViewModelProvider).feedback, isNotNull); diff --git a/apps/app_macos/test/features/settings/live_coach_settings_test.dart b/apps/app_macos/test/features/settings/live_coach_settings_test.dart new file mode 100644 index 00000000..b54440f0 --- /dev/null +++ b/apps/app_macos/test/features/settings/live_coach_settings_test.dart @@ -0,0 +1,150 @@ +import 'package:core_data/database/app_database.dart'; +import 'package:core_presentation/core_presentation.dart'; +import 'package:dio/dio.dart'; +import 'package:easy_localization/easy_localization.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/llm/llm_provider.dart'; +import 'package:ici_transcript/core/platform/app_data_directory.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/platform/now.provider.dart'; +import 'package:ici_transcript/core/providers/services/api_key_store.provider.dart'; +import 'package:ici_transcript/core/providers/services/llm_dio.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/onboarding/presentation/ollama_setup.view_model.dart'; +import 'package:ici_transcript/features/settings/presentation/screens/settings/settings.screen.dart'; + +import '../../helpers/calendar_fakes.dart'; +import '../../helpers/fake_view_models.dart'; +import '../../helpers/llm_fakes.dart' show writeLlmPrefs; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/settings_fakes.dart'; + +/// Réglages › Enregistrement : « Coach en direct » à côté de « Coach +/// anglais » (après l'appel). +/// +/// Besoin : interrupteur coupé par défaut ; disponible seulement avec un +/// fournisseur en ligne configuré ET autorisé ; sinon désactivé, avec la +/// raison (le modèle local ralentirait la transcription : rien n'est envoyé +/// pendant la réunion). Persistance au redémarrage : épinglée par +/// test/features/live_transcription/live_coach_wiring_test.dart (vrai view +/// model). +/// +/// Repères supposés : libellé `coach.live.option`, description +/// `coach.live.description`, raison `coach.live.unavailable` ; un +/// `OatsSwitch` sur la même `Row` que le libellé (comme les autres lignes). +void main() { + late AppDatabase db; + + setUp(resetPrefs); + tearDown(resetPrefs); + + List overrides(WidgetTester tester) => [ + ...localModelOverrides(db, InstantOllamaService(installed: true)), + apiKeyStoreProvider.overrideWithValue( + InMemoryApiKeyStore({ + LlmProviderId.anthropic: 'sk-ant-test-SECRET-0123456789', + }), + ), + llmDioProvider.overrideWithValue( + Dio()..httpClientAdapter = RecordingHttpAdapter(), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + liveTranscriptionViewModelProvider.overrideWith( + FakeLiveTranscriptionViewModel.new, + ), + ollamaSetupViewModelProvider.overrideWith( + () => FakeOllamaSetupViewModel(kOllamaReady), + ), + nowProvider.overrideWithValue( + widgetClock(tester, DateTime(2026, 11, 23, 10)), + ), + ]; + + Future io(WidgetTester tester) async { + for (int i = 0; i < 6; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 30)), + ); + await tester.pump(const Duration(milliseconds: 50)); + } + } + + Future open(WidgetTester tester, {required bool cloud}) async { + FakeCalendarPlatform().install(); + FakeMeetingPlatform().install(); + await tester.runAsync( + () => writeLlmPrefs( + cloudAllowed: cloud, + preferred: LlmProviderId.anthropic, + ), + ); + db = memoryDatabase(); + addTearDown(db.close); + await pumpLocalized( + tester, + const SettingsScreen(), + overrides: overrides(tester), + size: const Size(1280, 5000), + settle: false, + ); + for (int i = 0; i < 40; i++) { + if (find.text(appDataDirectory()).evaluate().isNotEmpty) break; + await io(tester); + } + await io(tester); + } + + String label() => 'coach.live.option'.tr(); + + Finder switchOf(String text) => find.descendant( + of: find.ancestor(of: find.text(text), matching: find.byType(Row)).first, + matching: find.byType(OatsSwitch), + ); + + OatsSwitch liveSwitch(WidgetTester tester) => + tester.widget(switchOf('coach.live.option'.tr())); + + testWidgets('Claude configuré et autorisé : la ligne est là, coupée par ' + 'défaut, et s\'active', (WidgetTester tester) async { + await open(tester, cloud: true); + + expect(find.text(label()), findsOneWidget); + expect(find.text('coach.live.description'.tr()), findsOneWidget); + expect(liveSwitch(tester).value, isFalse); + expect(liveSwitch(tester).onChanged, isNotNull); + + await tester.ensureVisible(switchOf(label())); + await tester.tap(switchOf(label())); + await tester.pump(); + await io(tester); + + expect(liveSwitch(tester).value, isTrue); + }); + + testWidgets('envoi coupé (clé présente, modèle local installé) : ' + 'désactivé, la raison est dite', (WidgetTester tester) async { + await open(tester, cloud: false); + + expect(find.text(label()), findsOneWidget); + expect(liveSwitch(tester).onChanged, isNull); + expect(find.text('coach.live.unavailable'.tr()), findsOneWidget); + }); + + testWidgets('« Coach anglais » (après l\'appel) reste là et garde son sens', ( + WidgetTester tester, + ) async { + await open(tester, cloud: false); + + expect(find.text('settings.recording.coach'.tr()), findsOneWidget); + expect( + tester + .widget(switchOf('settings.recording.coach'.tr())) + .onChanged, + isNotNull, + reason: 'le coach d\'après l\'appel marche aussi avec le modèle local', + ); + }); +} diff --git a/apps/app_macos/tool/render_screens.dart b/apps/app_macos/tool/render_screens.dart index f5854571..891f4a54 100644 --- a/apps/app_macos/tool/render_screens.dart +++ b/apps/app_macos/tool/render_screens.dart @@ -57,6 +57,12 @@ import 'package:ici_transcript/application/services/dictation/dictation_controll import 'package:ici_transcript/application/services/dictation/dictation_preferences.dart'; import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; import 'package:ici_transcript/presentation/app.dart'; +import 'package:core_domain/domain/entities/english_feedback.entity.dart'; +import 'package:ici_transcript/application/services/live_coach/live_coach.service.dart'; +import 'package:ici_transcript/core/providers/core/repositories/session.repository.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_coach.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/summary.service.provider.dart'; +import 'package:ici_transcript/features/shell/presentation/shell_view.provider.dart'; import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart'; import 'package:ici_transcript/application/services/live_answers/live_question.dart'; @@ -211,8 +217,14 @@ final Map _aiStates = { /// Live : enregistrement en cours, quelques phrases déjà transcrites. class _RecordingLiveViewModel extends LiveTranscriptionViewModel { + _RecordingLiveViewModel({this.liveCoach = false}); + + /// Coach en direct activé (sans écrire prefs.json). + final bool liveCoach; + @override - LiveTranscriptionState build() => LiveTranscriptionState.initial(); + LiveTranscriptionState build() => + LiveTranscriptionState.initial().copyWith(isLiveCoachEnabled: liveCoach); @override Future startSession() async { @@ -608,6 +620,7 @@ List _overrides( _Dictation dictation = _dictationOn, SessionDetailState Function(SessionDetailState)? detail, LiveAnswersService? answers, + bool liveCoach = false, }) => [ if (answers != null) liveAnswersServiceProvider.overrideWithValue(answers), dictationSettingsViewModelProvider.overrideWith( @@ -634,7 +647,9 @@ List _overrides( sessionListViewModelProvider.overrideWith( () => FakeSessionListViewModel(sessions), ), - liveTranscriptionViewModelProvider.overrideWith(_RecordingLiveViewModel.new), + liveTranscriptionViewModelProvider.overrideWith( + () => _RecordingLiveViewModel(liveCoach: liveCoach), + ), settingsViewModelProvider.overrideWith( () => _SettingsViewModel(settings ?? _settings), ), @@ -660,6 +675,177 @@ List _overrides( ), ]; +/// Coach en direct figé sur [_snap]. +class _FixedCoach extends LiveCoachService { + _FixedCoach(this._snap) : super(resolveModel: () async => null); + + final LiveCoachSnapshot _snap; + + @override + LiveCoachSnapshot get snapshot => _snap; + + @override + Stream get snapshots => + Stream.value(_snap); +} + +EnglishCorrectionEntity _fix( + String category, + String original, + String corrected, + String why, [ + int? atMs, +]) => EnglishCorrectionEntity( + original: original, + corrected: corrected, + category: category, + explanation: why, + timestampMs: atMs, +); + +/// Retours du coach rangés pour la page « Coach anglais » (inventés). +final Map _coachFeedback = + { + 's1': EnglishFeedbackEntity( + overall: 'Bon niveau, quelques tournures à reprendre.', + corrections: [ + _fix( + 'grammar', + 'I am agree with you on this point', + 'I agree with you on this point', + '« agree » est un verbe : pas de « am ».', + 65000, + ), + _fix( + 'vocabulary', + 'we must actualize the roadmap', + 'we must update the roadmap', + '« actualize » est un faux ami de « actualiser ».', + 372000, + ), + _fix( + 'expression', + 'it depends of the budget', + 'it depends on the budget', + 'On dit « depend on ».', + 1514000, + ), + ], + ), + 's2': const EnglishFeedbackEntity(overall: 'Très bon niveau.'), + 's3': EnglishFeedbackEntity( + corrections: [ + _fix( + 'grammar', + 'he have sent the deck', + 'he has sent the deck', + 'Troisième personne : « has ».', + 128000, + ), + _fix( + 'conjugation', + 'we have met them yesterday', + 'we met them yesterday', + 'Moment passé précis : prétérit.', + 640000, + ), + ], + unanalyzedSegmentIds: const ['seg-40', 'seg-41'], + ), + 's4': EnglishFeedbackEntity( + corrections: [ + _fix( + 'Grammaire', + 'the prices are more cheap', + 'the prices are cheaper', + 'Comparatif court : « -er ».', + 90000, + ), + ], + ), + // Coach d'après l'appel tombé en échec : tout reste à analyser. + 's5': const EnglishFeedbackEntity( + unanalyzedSegmentIds: ['seg-0', 'seg-1'], + ), + // Note sans phrase anglaise de l'utilisateur : rien d'envoyé. + 's7': const EnglishFeedbackEntity(nothingToAnalyse: true), + 's6': EnglishFeedbackEntity( + corrections: [ + _fix( + 'grammar', + 'since three months', + 'for three months', + 'Durée : « for ».', + 30000, + ), + _fix( + 'vocabulary', + 'a formation for the team', + 'a training for the team', + '« formation » est un faux ami.', + 300000, + ), + ], + ), + 's8': EnglishFeedbackEntity( + corrections: [ + _fix( + 'vocabulary', + 'I will assist to the meeting', + 'I will attend the meeting', + '« assist » veut dire aider.', + 45000, + ), + ], + ), + }; + +/// Les notes et leurs retours rangés dans [db] (page « Coach anglais »). +Future _seedCoach(AppDatabase db) async { + final ProviderContainer c = ProviderContainer( + overrides: [databaseProvider.overrideWithValue(db)], + ); + for (final SessionEntity s in _sessions) { + await c.read(sessionRepositoryProvider).create(s); + if (_coachFeedback[s.id] case final EnglishFeedbackEntity f) { + await c + .read(summaryServiceProvider) + .saveSummary( + sessionId: s.id, + content: SessionAnalysis(feedback: f).toStored(), + ); + } + } + c.dispose(); +} + +/// Corrections du coach en direct (les 3 dernières s'affichent). +final List _liveCorrections = + [ + _fix('grammar', 'I am agree', 'I agree', 'Verbe.', 61000), + _fix( + 'vocabulary', + 'we must actualize the plan', + 'we must update the plan', + 'Faux ami.', + 412000, + ), + _fix( + 'expression', + 'it depends of the team', + 'it depends on the team', + '« depend on ».', + 905000, + ), + _fix( + 'grammar', + 'he have finished the report', + 'he has finished the report', + 'Troisième personne.', + 1388000, + ), + ]; + /// Charge les polices déclarées (FontManifest) et la police système macOS. Future _loadFonts() async { final List manifest = @@ -727,6 +913,9 @@ void main() { FakeFilePicker? picker, List extra = const [], LiveAnswersService? answers, + bool liveCoach = false, + LiveCoachSnapshot? coach, + bool coachAvailable = true, }) async { final AppDatabase base = db ?? memoryDatabase(); addTearDown(base.close); @@ -752,6 +941,13 @@ void main() { dictation: dictation, detail: detail, answers: answers, + liveCoach: liveCoach, + ), + liveCoachAvailableProvider.overrideWith( + (Ref ref) async => coachAvailable, + ), + liveCoachServiceProvider.overrideWithValue( + _FixedCoach(coach ?? const LiveCoachSnapshot()), ), // Jamais le vrai agenda : états figés. ...extra.isEmpty ? _calendar() : extra, @@ -1122,6 +1318,117 @@ void main() { await _shot(tester, key, 'detail-questions-scrolled-$suffix'); }); + // Coach anglais : page (notes, erreurs récurrentes), puis une note + // ouverte sur sa section coach (corrections, aucune, non analysée). + shoot('coach-page', (WidgetTester tester) async { + final AppDatabase db = memoryDatabase(); + await tester.runAsync(() => _seedCoach(db)); + final GlobalKey key = await pumpApp( + tester, + _sessions, + db: db, + ollama: kOllamaReady, + detail: (SessionDetailState s) => + s.copyWith(feedback: _coachFeedback[s.session?.id]), + ); + Future io() async { + for (int i = 0; i < 4; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 50)), + ); + await _pump(tester, 3); + } + } + + await tester.tap(find.text('Coach anglais')); + await io(); + await _shot(tester, key, 'coach-page-$suffix'); + for (final MapEntry n in { + 'corrections': 'Point produit hebdo', + 'none': 'Revue de sprint 14', + 'unanalyzed': 'Entretien candidat backend', + 'nothing': 'Appel rapide fournisseur', + }.entries) { + await tester.tap(find.text(n.value).first); + await io(); + await _shot(tester, key, 'coach-note-${n.key}-$suffix'); + await tester.tap(find.byTooltip(LocaleKeys.common_action_back.tr())); + await io(); + } + }); + + for (final MapEntry c + in { + 'corrections': LiveCoachSnapshot( + sessionId: 's2', + corrections: _liveCorrections, + ), + 'waiting': const LiveCoachSnapshot(sessionId: 's2'), + 'unavailable': const LiveCoachSnapshot( + sessionId: 's2', + unavailable: true, + ), + }.entries) { + shoot('live-coach-${c.key}', (WidgetTester tester) async { + final GlobalKey key = await pumpApp( + tester, + _sessions, + liveCoach: true, + coach: c.value, + ); + await tester.tap(find.text('Nouvelle note')); + await _pump(tester, 10); + await _shot(tester, key, 'live-coach-${c.key}-$suffix'); + }); + } + + // Interrupteur « Coach en direct » : options du direct et Réglages, + // fournisseur en ligne autorisé ou non. + for (final bool available in [true, false]) { + final String name = available ? 'available' : 'unavailable'; + shoot('live-coach-switch-$name', (WidgetTester tester) async { + final GlobalKey key = await pumpApp( + tester, + _sessions, + liveCoach: available, + coachAvailable: available, + settings: available + ? _settings.copyWith( + llmCloudAllowed: true, + llmActive: LlmProviderId.anthropic, + llmKeySuffixes: const { + LlmProviderId.anthropic: 'a1b2', + }, + ) + : null, + ); + await tester.tap(find.text('Réglages')); + await _pump(tester, 10); + final Finder row = find.text(LocaleKeys.coach_live_option.tr()); + await tester.drag( + row, + Offset(0, 220 - tester.getTopLeft(row).dy), + ); + await _pump(tester, 10); + await _shot(tester, key, 'settings-live-coach-$name-$suffix'); + }); + shoot('live-idle-coach-$name', (WidgetTester tester) async { + final GlobalKey key = await pumpApp( + tester, + _sessions, + liveCoach: available, + coachAvailable: available, + ); + // Écran du direct avant de démarrer : options visibles. + final ProviderContainer c = ProviderScope.containerOf( + tester.element(find.byType(RootAppWidget)), + ); + c.read(shellViewControllerProvider.notifier).show(ShellView.live); + await _pump(tester, 10); + await _shot(tester, key, 'live-idle-coach-$name-$suffix'); + }); + } + shoot('live-finalising', (WidgetTester tester) async { final GlobalKey key = await pumpApp(tester, _sessions); await tester.tap(find.text('Nouvelle note')); diff --git a/packages/core_domain/lib/domain/entities/english_feedback.entity.dart b/packages/core_domain/lib/domain/entities/english_feedback.entity.dart index c760a5f2..ebe1d91a 100644 --- a/packages/core_domain/lib/domain/entities/english_feedback.entity.dart +++ b/packages/core_domain/lib/domain/entities/english_feedback.entity.dart @@ -20,6 +20,11 @@ abstract class EnglishCorrectionEntity with _$EnglishCorrectionEntity { /// Explication courte de la correction (en francais). required String explanation, + + /// Heure, dans la note, de la phrase qui contient [original] (ms depuis + /// le début, comme `TranscriptSegmentEntity.timestampMs`) ; null si + /// inconnue (retour d'avant, phrase introuvable). + int? timestampMs, }) = _EnglishCorrectionEntity; /// Construit l'entite depuis un JSON. @@ -38,6 +43,14 @@ abstract class EnglishFeedbackEntity with _$EnglishFeedbackEntity { /// Appreciation globale du niveau (optionnelle). String? overall, + + /// Phrases (ids de segments) dont la partie n'a pas pu être analysée + /// (lot en échec) : la note propose de réessayer. + @Default([]) List unanalyzedSegmentIds, + + /// Aucune phrase anglaise de l'utilisateur dans la note : rien n'a été + /// envoyé (la note le dit, ni « Aucune correction » ni erreur). + @Default(false) bool nothingToAnalyse, }) = _EnglishFeedbackEntity; /// Construit l'entite depuis un JSON. diff --git a/packages/core_domain/lib/domain/entities/english_feedback.entity.freezed.dart b/packages/core_domain/lib/domain/entities/english_feedback.entity.freezed.dart index a4c71f35..7075e63b 100644 --- a/packages/core_domain/lib/domain/entities/english_feedback.entity.freezed.dart +++ b/packages/core_domain/lib/domain/entities/english_feedback.entity.freezed.dart @@ -20,7 +20,10 @@ mixin _$EnglishCorrectionEntity { String get corrected;/// Categorie libre renvoyee par le modele /// (ex: conjugation, vocabulary, expression, grammar). String get category;/// Explication courte de la correction (en francais). - String get explanation; + String get explanation;/// Heure, dans la note, de la phrase qui contient [original] (ms depuis +/// le début, comme `TranscriptSegmentEntity.timestampMs`) ; null si +/// inconnue (retour d'avant, phrase introuvable). + int? get timestampMs; /// Create a copy of EnglishCorrectionEntity /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -33,16 +36,16 @@ $EnglishCorrectionEntityCopyWith get copyWith => _$Engl @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is EnglishCorrectionEntity&&(identical(other.original, original) || other.original == original)&&(identical(other.corrected, corrected) || other.corrected == corrected)&&(identical(other.category, category) || other.category == category)&&(identical(other.explanation, explanation) || other.explanation == explanation)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is EnglishCorrectionEntity&&(identical(other.original, original) || other.original == original)&&(identical(other.corrected, corrected) || other.corrected == corrected)&&(identical(other.category, category) || other.category == category)&&(identical(other.explanation, explanation) || other.explanation == explanation)&&(identical(other.timestampMs, timestampMs) || other.timestampMs == timestampMs)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,original,corrected,category,explanation); +int get hashCode => Object.hash(runtimeType,original,corrected,category,explanation,timestampMs); @override String toString() { - return 'EnglishCorrectionEntity(original: $original, corrected: $corrected, category: $category, explanation: $explanation)'; + return 'EnglishCorrectionEntity(original: $original, corrected: $corrected, category: $category, explanation: $explanation, timestampMs: $timestampMs)'; } @@ -53,7 +56,7 @@ abstract mixin class $EnglishCorrectionEntityCopyWith<$Res> { factory $EnglishCorrectionEntityCopyWith(EnglishCorrectionEntity value, $Res Function(EnglishCorrectionEntity) _then) = _$EnglishCorrectionEntityCopyWithImpl; @useResult $Res call({ - String original, String corrected, String category, String explanation + String original, String corrected, String category, String explanation, int? timestampMs }); @@ -70,13 +73,14 @@ class _$EnglishCorrectionEntityCopyWithImpl<$Res> /// Create a copy of EnglishCorrectionEntity /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? original = null,Object? corrected = null,Object? category = null,Object? explanation = null,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? original = null,Object? corrected = null,Object? category = null,Object? explanation = null,Object? timestampMs = freezed,}) { return _then(_self.copyWith( original: null == original ? _self.original : original // ignore: cast_nullable_to_non_nullable as String,corrected: null == corrected ? _self.corrected : corrected // ignore: cast_nullable_to_non_nullable as String,category: null == category ? _self.category : category // ignore: cast_nullable_to_non_nullable as String,explanation: null == explanation ? _self.explanation : explanation // ignore: cast_nullable_to_non_nullable -as String, +as String,timestampMs: freezed == timestampMs ? _self.timestampMs : timestampMs // ignore: cast_nullable_to_non_nullable +as int?, )); } @@ -161,10 +165,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( String original, String corrected, String category, String explanation)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( String original, String corrected, String category, String explanation, int? timestampMs)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _EnglishCorrectionEntity() when $default != null: -return $default(_that.original,_that.corrected,_that.category,_that.explanation);case _: +return $default(_that.original,_that.corrected,_that.category,_that.explanation,_that.timestampMs);case _: return orElse(); } @@ -182,10 +186,10 @@ return $default(_that.original,_that.corrected,_that.category,_that.explanation) /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( String original, String corrected, String category, String explanation) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( String original, String corrected, String category, String explanation, int? timestampMs) $default,) {final _that = this; switch (_that) { case _EnglishCorrectionEntity(): -return $default(_that.original,_that.corrected,_that.category,_that.explanation);case _: +return $default(_that.original,_that.corrected,_that.category,_that.explanation,_that.timestampMs);case _: throw StateError('Unexpected subclass'); } @@ -202,10 +206,10 @@ return $default(_that.original,_that.corrected,_that.category,_that.explanation) /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( String original, String corrected, String category, String explanation)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( String original, String corrected, String category, String explanation, int? timestampMs)? $default,) {final _that = this; switch (_that) { case _EnglishCorrectionEntity() when $default != null: -return $default(_that.original,_that.corrected,_that.category,_that.explanation);case _: +return $default(_that.original,_that.corrected,_that.category,_that.explanation,_that.timestampMs);case _: return null; } @@ -217,7 +221,7 @@ return $default(_that.original,_that.corrected,_that.category,_that.explanation) @JsonSerializable() class _EnglishCorrectionEntity implements EnglishCorrectionEntity { - const _EnglishCorrectionEntity({required this.original, required this.corrected, required this.category, required this.explanation}); + const _EnglishCorrectionEntity({required this.original, required this.corrected, required this.category, required this.explanation, this.timestampMs}); factory _EnglishCorrectionEntity.fromJson(Map json) => _$EnglishCorrectionEntityFromJson(json); /// Phrase ou tournure telle que prononcee par l'utilisateur. @@ -229,6 +233,10 @@ class _EnglishCorrectionEntity implements EnglishCorrectionEntity { @override final String category; /// Explication courte de la correction (en francais). @override final String explanation; +/// Heure, dans la note, de la phrase qui contient [original] (ms depuis +/// le début, comme `TranscriptSegmentEntity.timestampMs`) ; null si +/// inconnue (retour d'avant, phrase introuvable). +@override final int? timestampMs; /// Create a copy of EnglishCorrectionEntity /// with the given fields replaced by the non-null parameter values. @@ -243,16 +251,16 @@ Map toJson() { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _EnglishCorrectionEntity&&(identical(other.original, original) || other.original == original)&&(identical(other.corrected, corrected) || other.corrected == corrected)&&(identical(other.category, category) || other.category == category)&&(identical(other.explanation, explanation) || other.explanation == explanation)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _EnglishCorrectionEntity&&(identical(other.original, original) || other.original == original)&&(identical(other.corrected, corrected) || other.corrected == corrected)&&(identical(other.category, category) || other.category == category)&&(identical(other.explanation, explanation) || other.explanation == explanation)&&(identical(other.timestampMs, timestampMs) || other.timestampMs == timestampMs)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,original,corrected,category,explanation); +int get hashCode => Object.hash(runtimeType,original,corrected,category,explanation,timestampMs); @override String toString() { - return 'EnglishCorrectionEntity(original: $original, corrected: $corrected, category: $category, explanation: $explanation)'; + return 'EnglishCorrectionEntity(original: $original, corrected: $corrected, category: $category, explanation: $explanation, timestampMs: $timestampMs)'; } @@ -263,7 +271,7 @@ abstract mixin class _$EnglishCorrectionEntityCopyWith<$Res> implements $English factory _$EnglishCorrectionEntityCopyWith(_EnglishCorrectionEntity value, $Res Function(_EnglishCorrectionEntity) _then) = __$EnglishCorrectionEntityCopyWithImpl; @override @useResult $Res call({ - String original, String corrected, String category, String explanation + String original, String corrected, String category, String explanation, int? timestampMs }); @@ -280,13 +288,14 @@ class __$EnglishCorrectionEntityCopyWithImpl<$Res> /// Create a copy of EnglishCorrectionEntity /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? original = null,Object? corrected = null,Object? category = null,Object? explanation = null,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? original = null,Object? corrected = null,Object? category = null,Object? explanation = null,Object? timestampMs = freezed,}) { return _then(_EnglishCorrectionEntity( original: null == original ? _self.original : original // ignore: cast_nullable_to_non_nullable as String,corrected: null == corrected ? _self.corrected : corrected // ignore: cast_nullable_to_non_nullable as String,category: null == category ? _self.category : category // ignore: cast_nullable_to_non_nullable as String,explanation: null == explanation ? _self.explanation : explanation // ignore: cast_nullable_to_non_nullable -as String, +as String,timestampMs: freezed == timestampMs ? _self.timestampMs : timestampMs // ignore: cast_nullable_to_non_nullable +as int?, )); } @@ -299,7 +308,11 @@ mixin _$EnglishFeedbackEntity { /// Liste des corrections proposees. List get corrections;/// Appreciation globale du niveau (optionnelle). - String? get overall; + String? get overall;/// Phrases (ids de segments) dont la partie n'a pas pu être analysée +/// (lot en échec) : la note propose de réessayer. + List get unanalyzedSegmentIds;/// Aucune phrase anglaise de l'utilisateur dans la note : rien n'a été +/// envoyé (la note le dit, ni « Aucune correction » ni erreur). + bool get nothingToAnalyse; /// Create a copy of EnglishFeedbackEntity /// with the given fields replaced by the non-null parameter values. @JsonKey(includeFromJson: false, includeToJson: false) @@ -312,16 +325,16 @@ $EnglishFeedbackEntityCopyWith get copyWith => _$EnglishF @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is EnglishFeedbackEntity&&const DeepCollectionEquality().equals(other.corrections, corrections)&&(identical(other.overall, overall) || other.overall == overall)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is EnglishFeedbackEntity&&const DeepCollectionEquality().equals(other.corrections, corrections)&&(identical(other.overall, overall) || other.overall == overall)&&const DeepCollectionEquality().equals(other.unanalyzedSegmentIds, unanalyzedSegmentIds)&&(identical(other.nothingToAnalyse, nothingToAnalyse) || other.nothingToAnalyse == nothingToAnalyse)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(corrections),overall); +int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(corrections),overall,const DeepCollectionEquality().hash(unanalyzedSegmentIds),nothingToAnalyse); @override String toString() { - return 'EnglishFeedbackEntity(corrections: $corrections, overall: $overall)'; + return 'EnglishFeedbackEntity(corrections: $corrections, overall: $overall, unanalyzedSegmentIds: $unanalyzedSegmentIds, nothingToAnalyse: $nothingToAnalyse)'; } @@ -332,7 +345,7 @@ abstract mixin class $EnglishFeedbackEntityCopyWith<$Res> { factory $EnglishFeedbackEntityCopyWith(EnglishFeedbackEntity value, $Res Function(EnglishFeedbackEntity) _then) = _$EnglishFeedbackEntityCopyWithImpl; @useResult $Res call({ - List corrections, String? overall + List corrections, String? overall, List unanalyzedSegmentIds, bool nothingToAnalyse }); @@ -349,11 +362,13 @@ class _$EnglishFeedbackEntityCopyWithImpl<$Res> /// Create a copy of EnglishFeedbackEntity /// with the given fields replaced by the non-null parameter values. -@pragma('vm:prefer-inline') @override $Res call({Object? corrections = null,Object? overall = freezed,}) { +@pragma('vm:prefer-inline') @override $Res call({Object? corrections = null,Object? overall = freezed,Object? unanalyzedSegmentIds = null,Object? nothingToAnalyse = null,}) { return _then(_self.copyWith( corrections: null == corrections ? _self.corrections : corrections // ignore: cast_nullable_to_non_nullable as List,overall: freezed == overall ? _self.overall : overall // ignore: cast_nullable_to_non_nullable -as String?, +as String?,unanalyzedSegmentIds: null == unanalyzedSegmentIds ? _self.unanalyzedSegmentIds : unanalyzedSegmentIds // ignore: cast_nullable_to_non_nullable +as List,nothingToAnalyse: null == nothingToAnalyse ? _self.nothingToAnalyse : nothingToAnalyse // ignore: cast_nullable_to_non_nullable +as bool, )); } @@ -438,10 +453,10 @@ return $default(_that);case _: /// } /// ``` -@optionalTypeArgs TResult maybeWhen(TResult Function( List corrections, String? overall)? $default,{required TResult orElse(),}) {final _that = this; +@optionalTypeArgs TResult maybeWhen(TResult Function( List corrections, String? overall, List unanalyzedSegmentIds, bool nothingToAnalyse)? $default,{required TResult orElse(),}) {final _that = this; switch (_that) { case _EnglishFeedbackEntity() when $default != null: -return $default(_that.corrections,_that.overall);case _: +return $default(_that.corrections,_that.overall,_that.unanalyzedSegmentIds,_that.nothingToAnalyse);case _: return orElse(); } @@ -459,10 +474,10 @@ return $default(_that.corrections,_that.overall);case _: /// } /// ``` -@optionalTypeArgs TResult when(TResult Function( List corrections, String? overall) $default,) {final _that = this; +@optionalTypeArgs TResult when(TResult Function( List corrections, String? overall, List unanalyzedSegmentIds, bool nothingToAnalyse) $default,) {final _that = this; switch (_that) { case _EnglishFeedbackEntity(): -return $default(_that.corrections,_that.overall);case _: +return $default(_that.corrections,_that.overall,_that.unanalyzedSegmentIds,_that.nothingToAnalyse);case _: throw StateError('Unexpected subclass'); } @@ -479,10 +494,10 @@ return $default(_that.corrections,_that.overall);case _: /// } /// ``` -@optionalTypeArgs TResult? whenOrNull(TResult? Function( List corrections, String? overall)? $default,) {final _that = this; +@optionalTypeArgs TResult? whenOrNull(TResult? Function( List corrections, String? overall, List unanalyzedSegmentIds, bool nothingToAnalyse)? $default,) {final _that = this; switch (_that) { case _EnglishFeedbackEntity() when $default != null: -return $default(_that.corrections,_that.overall);case _: +return $default(_that.corrections,_that.overall,_that.unanalyzedSegmentIds,_that.nothingToAnalyse);case _: return null; } @@ -494,7 +509,7 @@ return $default(_that.corrections,_that.overall);case _: @JsonSerializable() class _EnglishFeedbackEntity implements EnglishFeedbackEntity { - const _EnglishFeedbackEntity({final List corrections = const [], this.overall}): _corrections = corrections; + const _EnglishFeedbackEntity({final List corrections = const [], this.overall, final List unanalyzedSegmentIds = const [], this.nothingToAnalyse = false}): _corrections = corrections,_unanalyzedSegmentIds = unanalyzedSegmentIds; factory _EnglishFeedbackEntity.fromJson(Map json) => _$EnglishFeedbackEntityFromJson(json); /// Liste des corrections proposees. @@ -508,6 +523,20 @@ class _EnglishFeedbackEntity implements EnglishFeedbackEntity { /// Appreciation globale du niveau (optionnelle). @override final String? overall; +/// Phrases (ids de segments) dont la partie n'a pas pu être analysée +/// (lot en échec) : la note propose de réessayer. + final List _unanalyzedSegmentIds; +/// Phrases (ids de segments) dont la partie n'a pas pu être analysée +/// (lot en échec) : la note propose de réessayer. +@override@JsonKey() List get unanalyzedSegmentIds { + if (_unanalyzedSegmentIds is EqualUnmodifiableListView) return _unanalyzedSegmentIds; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_unanalyzedSegmentIds); +} + +/// Aucune phrase anglaise de l'utilisateur dans la note : rien n'a été +/// envoyé (la note le dit, ni « Aucune correction » ni erreur). +@override@JsonKey() final bool nothingToAnalyse; /// Create a copy of EnglishFeedbackEntity /// with the given fields replaced by the non-null parameter values. @@ -522,16 +551,16 @@ Map toJson() { @override bool operator ==(Object other) { - return identical(this, other) || (other.runtimeType == runtimeType&&other is _EnglishFeedbackEntity&&const DeepCollectionEquality().equals(other._corrections, _corrections)&&(identical(other.overall, overall) || other.overall == overall)); + return identical(this, other) || (other.runtimeType == runtimeType&&other is _EnglishFeedbackEntity&&const DeepCollectionEquality().equals(other._corrections, _corrections)&&(identical(other.overall, overall) || other.overall == overall)&&const DeepCollectionEquality().equals(other._unanalyzedSegmentIds, _unanalyzedSegmentIds)&&(identical(other.nothingToAnalyse, nothingToAnalyse) || other.nothingToAnalyse == nothingToAnalyse)); } @JsonKey(includeFromJson: false, includeToJson: false) @override -int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(_corrections),overall); +int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(_corrections),overall,const DeepCollectionEquality().hash(_unanalyzedSegmentIds),nothingToAnalyse); @override String toString() { - return 'EnglishFeedbackEntity(corrections: $corrections, overall: $overall)'; + return 'EnglishFeedbackEntity(corrections: $corrections, overall: $overall, unanalyzedSegmentIds: $unanalyzedSegmentIds, nothingToAnalyse: $nothingToAnalyse)'; } @@ -542,7 +571,7 @@ abstract mixin class _$EnglishFeedbackEntityCopyWith<$Res> implements $EnglishFe factory _$EnglishFeedbackEntityCopyWith(_EnglishFeedbackEntity value, $Res Function(_EnglishFeedbackEntity) _then) = __$EnglishFeedbackEntityCopyWithImpl; @override @useResult $Res call({ - List corrections, String? overall + List corrections, String? overall, List unanalyzedSegmentIds, bool nothingToAnalyse }); @@ -559,11 +588,13 @@ class __$EnglishFeedbackEntityCopyWithImpl<$Res> /// Create a copy of EnglishFeedbackEntity /// with the given fields replaced by the non-null parameter values. -@override @pragma('vm:prefer-inline') $Res call({Object? corrections = null,Object? overall = freezed,}) { +@override @pragma('vm:prefer-inline') $Res call({Object? corrections = null,Object? overall = freezed,Object? unanalyzedSegmentIds = null,Object? nothingToAnalyse = null,}) { return _then(_EnglishFeedbackEntity( corrections: null == corrections ? _self._corrections : corrections // ignore: cast_nullable_to_non_nullable as List,overall: freezed == overall ? _self.overall : overall // ignore: cast_nullable_to_non_nullable -as String?, +as String?,unanalyzedSegmentIds: null == unanalyzedSegmentIds ? _self._unanalyzedSegmentIds : unanalyzedSegmentIds // ignore: cast_nullable_to_non_nullable +as List,nothingToAnalyse: null == nothingToAnalyse ? _self.nothingToAnalyse : nothingToAnalyse // ignore: cast_nullable_to_non_nullable +as bool, )); } diff --git a/packages/core_domain/lib/domain/entities/english_feedback.entity.g.dart b/packages/core_domain/lib/domain/entities/english_feedback.entity.g.dart index 6cb944d0..757a4db5 100644 --- a/packages/core_domain/lib/domain/entities/english_feedback.entity.g.dart +++ b/packages/core_domain/lib/domain/entities/english_feedback.entity.g.dart @@ -13,6 +13,7 @@ _EnglishCorrectionEntity _$EnglishCorrectionEntityFromJson( corrected: json['corrected'] as String, category: json['category'] as String, explanation: json['explanation'] as String, + timestampMs: (json['timestampMs'] as num?)?.toInt(), ); Map _$EnglishCorrectionEntityToJson( @@ -22,6 +23,7 @@ Map _$EnglishCorrectionEntityToJson( 'corrected': instance.corrected, 'category': instance.category, 'explanation': instance.explanation, + 'timestampMs': instance.timestampMs, }; _EnglishFeedbackEntity _$EnglishFeedbackEntityFromJson( @@ -35,6 +37,12 @@ _EnglishFeedbackEntity _$EnglishFeedbackEntityFromJson( .toList() ?? const [], overall: json['overall'] as String?, + unanalyzedSegmentIds: + (json['unanalyzedSegmentIds'] as List?) + ?.map((e) => e as String) + .toList() ?? + const [], + nothingToAnalyse: json['nothingToAnalyse'] as bool? ?? false, ); Map _$EnglishFeedbackEntityToJson( @@ -42,4 +50,6 @@ Map _$EnglishFeedbackEntityToJson( ) => { 'corrections': instance.corrections, 'overall': instance.overall, + 'unanalyzedSegmentIds': instance.unanalyzedSegmentIds, + 'nothingToAnalyse': instance.nothingToAnalyse, };