diff --git a/apps/app_macos/lib/application/services/gap_backfill_retry.dart b/apps/app_macos/lib/application/services/gap_backfill_retry.dart index e442fade..0129b688 100644 --- a/apps/app_macos/lib/application/services/gap_backfill_retry.dart +++ b/apps/app_macos/lib/application/services/gap_backfill_retry.dart @@ -123,6 +123,14 @@ final class GapBackfillRetry { await _write(pending); return false; } + // Noté en attente AVANT la tentative, sans la compter : si l'app se + // termine pendant (Quitter passe la finalisation et arrête le serveur), + // le lancement suivant reprend la session et la tentative coupée ne + // compte pas. + if (!pending.containsKey(sessionId)) { + pending[sessionId] = 0; + await _write(pending); + } final BackfillOutcome outcome = await _backfill.backfill( sessionId, recordingsDirectory: _directory, diff --git a/apps/app_macos/lib/application/services/transcript_grouping.dart b/apps/app_macos/lib/application/services/transcript_grouping.dart index 230a6eac..9e97dd4c 100644 --- a/apps/app_macos/lib/application/services/transcript_grouping.dart +++ b/apps/app_macos/lib/application/services/transcript_grouping.dart @@ -22,7 +22,7 @@ class TranscriptBlock { /// Un repère (perte ou passage non transcrit) reste seul : il n'est la /// phrase de personne. -bool _isMarker(String text) => +bool isTranscriptMarker(String text) => text.startsWith(LiveTranscriptionService.gapMarkerPrefix) || LiveTranscriptionService.isUntranscribedMarker(text); @@ -47,8 +47,8 @@ List groupTranscript( final bool sameSpeaker = speaker == null || last.speaker == null || speaker == last.speaker; final bool continues = - !_isMarker(last.segment.text) && - !_isMarker(seg.text) && + !isTranscriptMarker(last.segment.text) && + !isTranscriptMarker(seg.text) && last.segment.source == seg.source && sameSpeaker && !_sentenceEnd.hasMatch(last.segment.text.trim()) && diff --git a/apps/app_macos/lib/core/platform/owned_processes.dart b/apps/app_macos/lib/core/platform/owned_processes.dart index 2b353fcd..c5c1429a 100644 --- a/apps/app_macos/lib/core/platform/owned_processes.dart +++ b/apps/app_macos/lib/core/platform/owned_processes.dart @@ -283,6 +283,19 @@ final class OwnedProcessRegistry { } } + /// Quitter l'app : arrête tous les serveurs lancés par ce registre, en + /// parallèle (chacun borné comme [stop], ~15 s au pire). Un échec sur l'un + /// est noté et n'arrête pas les autres ; son entrée reste dans le fichier + /// d'état pour le nettoyage du lancement suivant. Ne lève jamais. + Future stopAll() async { + await Future.wait(>[ + for (final String role in _live.keys.toList()) + stop(role).catchError((Object e) { + _log.warning('$role non arrêté en quittant: $e'); + }), + ]); + } + /// Sonde de santé, par l'hôte. Future isHealthy(Uri url) => _host.isHealthy(url); 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 fa4640ca..bf0d11de 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 @@ -5,6 +5,7 @@ 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'; @@ -243,8 +244,9 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { calendarLink: calendarLink, ); _log.info('startTranscription OK'); - final String? sessionId = _liveService?.currentSessionStream.value?.id; - if (sessionId != null) _answers.start(sessionId); + final SessionEntity? session = _liveService?.currentSessionStream.value; + state = state.copyWith(sessionTitle: session?.title); + if (session != null) _answers.start(session.id); } catch (e) { _log.error('ERREUR startTranscription: $e'); if (e is PlatformException && e.code == 'MIC_PERMISSION_DENIED') { @@ -330,6 +332,7 @@ class LiveTranscriptionViewModel extends _$LiveTranscriptionViewModel { segments: [], duration: Duration.zero, speakerLabels: {}, + sessionTitle: null, ); // Sauvegarder la transcription en local 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 ac5eb7a0..c7dc9a7f 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'02918c5dd08b0a42ec3515201bd52641235a62e0'; + r'224339b3fa5390be5c5ae321e7cb057f36e68d52'; /// ViewModel de l'ecran de transcription en direct. diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_answers_panel.widget.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_answers_panel.widget.dart index a0efda12..25ff78b1 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_answers_panel.widget.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/live_answers_panel.widget.dart @@ -1,4 +1,3 @@ -import 'package:core_domain/domain/enum/audio_source.enum.dart'; import 'package:core_presentation/core_presentation.dart'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; @@ -9,6 +8,7 @@ import 'package:ici_transcript/application/services/live_answers/live_question.d import 'package:ici_transcript/core/providers/services/live_answers.service.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/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart'; import 'package:ici_transcript/features/shared/presentation/widgets/question_answer.widget.dart'; import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; @@ -217,11 +217,7 @@ class _QuestionCard extends StatelessWidget { } static String _speaker(LiveQuestion q, int? n) => - q.source == AudioSource.input - ? LocaleKeys.transcription_live_speaker_me.tr() - : n == null - ? LocaleKeys.transcription_live_speaker_system.tr() - : LocaleKeys.transcription_live_speaker_n.tr(args: ['${n + 1}']); + liveSpeakerLabel(q.source, n); // Le générateur d'easy_localization ne crée pas de constante pour une clé // nommée « other » (mot réservé des pluriels). diff --git a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart index 1e7fafe5..6a4139d9 100644 --- a/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart +++ b/apps/app_macos/lib/features/live_transcription/presentation/screens/live/widgets/transcript_line.widget.dart @@ -5,6 +5,17 @@ import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; +/// Qui parle en direct : « Vous » au micro, « Interlocuteur n » quand le son +/// du Mac est attribué ([speaker] 0, 1, …), sinon « Interlocuteur ». +String liveSpeakerLabel(AudioSource source, int? speaker) => + source == AudioSource.input + ? LocaleKeys.transcription_live_speaker_me.tr() + : speaker == null + ? LocaleKeys.transcription_live_speaker_system.tr() + : LocaleKeys.transcription_live_speaker_n.tr( + args: ['${speaker + 1}'], + ); + /// Une ligne de transcription en direct : qui parle, quand, le texte, puis la /// traduction éventuelle. class TranscriptLineWidget extends StatelessWidget { @@ -41,14 +52,7 @@ class TranscriptLineWidget extends StatelessWidget { Widget build(BuildContext context) { final Oats o = context.oats; final bool isInput = segment.source == AudioSource.input; - final int? who = isInput ? null : speaker; - final String label = isInput - ? LocaleKeys.transcription_live_speaker_me.tr() - : who != null - ? LocaleKeys.transcription_live_speaker_n.tr( - args: ['${who + 1}'], - ) - : LocaleKeys.transcription_live_speaker_system.tr(); + final String label = liveSpeakerLabel(segment.source, speaker); final String? t = translation?.trim(); return Column( diff --git a/apps/app_macos/lib/features/shell/presentation/meeting_suggestion.widget.dart b/apps/app_macos/lib/features/shell/presentation/meeting_suggestion.widget.dart index 621a0e7a..b7bed7f9 100644 --- a/apps/app_macos/lib/features/shell/presentation/meeting_suggestion.widget.dart +++ b/apps/app_macos/lib/features/shell/presentation/meeting_suggestion.widget.dart @@ -10,6 +10,20 @@ import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; /// Largeur de l'invite de réunion. const double kMeetingSuggestionWidth = 340; +/// Titre d'une suggestion : l'événement, ou « Appel détecté ». +String suggestionTitle(MeetingSuggestion s) => switch (s.source) { + MeetingSource.calendar => s.event?.title ?? '', + MeetingSource.call => LocaleKeys.meeting_suggestion_call_title.tr(), +}; + +/// Détail d'une suggestion : « 10:00–10:30 », ou le nom de l'app d'appel. +String suggestionDetail(MeetingSuggestion s) => switch (s.source) { + MeetingSource.calendar when s.event != null => + '${formatStartTime(s.event!.start)}–${formatStartTime(s.event!.end)}', + MeetingSource.call => s.appName ?? '', + _ => '', +}; + /// Invite non bloquante « Démarrer la note / Ignorer », en bas à droite du /// contenu ; rien quand il n'y a pas de suggestion. class MeetingSuggestionPrompt extends ConsumerWidget { @@ -24,16 +38,8 @@ class MeetingSuggestionPrompt extends ConsumerWidget { meetingSuggestionControllerProvider.notifier, ); final Oats o = context.oats; - final String title = switch (s.source) { - MeetingSource.calendar => s.event?.title ?? '', - MeetingSource.call => LocaleKeys.meeting_suggestion_call_title.tr(), - }; - final String detail = switch (s.source) { - MeetingSource.calendar when s.event != null => - '${formatStartTime(s.event!.start)}–${formatStartTime(s.event!.end)}', - MeetingSource.call => s.appName ?? '', - _ => '', - }; + final String title = suggestionTitle(s); + final String detail = suggestionDetail(s); return Semantics( liveRegion: true, container: true, diff --git a/apps/app_macos/lib/features/status_panel/status_panel_snapshot.dart b/apps/app_macos/lib/features/status_panel/status_panel_snapshot.dart new file mode 100644 index 00000000..4bedda90 --- /dev/null +++ b/apps/app_macos/lib/features/status_panel/status_panel_snapshot.dart @@ -0,0 +1,86 @@ +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:ici_transcript/application/services/live_answers/live_question.dart'; +import 'package:ici_transcript/application/services/transcript_grouping.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.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/widgets/transcript_line.widget.dart'; +import 'package:ici_transcript/features/shared/presentation/widgets/question_answer.widget.dart'; +import 'package:ici_transcript/features/shell/presentation/meeting_suggestion.widget.dart'; + +/// Phrases finies montrées par le panneau de barre de menus. +const int kStatusPanelTranscriptLines = 3; + +/// Ce que le panneau de barre de menus (Swift, canal +/// `com.icitranscript/status_panel`) affiche : seulement des String, int, +/// bool, null, List et Map. Contrat détaillé en tête de +/// test/features/status_panel/status_panel_snapshot_test.dart. +Map statusPanelSnapshot({ + required LiveTranscriptionState live, + required List questions, + required MeetingSuggestion? suggestion, + required bool dictating, +}) { + final String status = live.finalisingRemaining != null + ? 'finalising' + : live.isPaused + ? 'paused' + : live.isRecording + ? 'recording' + : 'idle'; + return { + 'status': status, + 'elapsedSeconds': live.duration.inSeconds, + 'finalisingSeconds': live.finalisingRemaining?.inSeconds, + 'title': status == 'idle' ? null : live.sessionTitle, + 'transcript': _transcript(live), + 'question': questions.isEmpty ? null : _question(questions.last), + 'suggestion': suggestion == null ? null : statusPanelSuggestion(suggestion), + 'dictating': dictating, + // Un seul « Démarrer la note » : celui de la suggestion s'il y en a une. + 'showStart': status == 'idle' && suggestion == null, + }; +} + +/// Suggestion telle que le panneau l'affiche (`suggestion`, `suggest`). +Map statusPanelSuggestion(MeetingSuggestion s) => + { + 'kind': s.source.name, + 'title': suggestionTitle(s), + 'detail': suggestionDetail(s), + }; + +/// Phrase finie : ni phrase en cours, ni passage provisoire, ni repère +/// (perte ou passage non transcrit). +bool _finished(TranscriptSegmentEntity s) => + !s.id.startsWith('current_') && + !s.id.endsWith('_pending') && + !isTranscriptMarker(s.text); + +List _transcript(LiveTranscriptionState live) { + final List done = live.segments + .where(_finished) + .toList(); + return [ + for (final TranscriptSegmentEntity s in done.skip( + done.length > kStatusPanelTranscriptLines + ? done.length - kStatusPanelTranscriptLines + : 0, + )) + { + 'speaker': liveSpeakerLabel(s.source, live.speakerLabels[s.id]), + 'source': s.source.name, + 'text': s.text, + }, + ]; +} + +Map _question(LiveQuestion q) => { + 'id': q.id, + 'text': q.text, + 'state': q.status.name, + 'answer': answerPlainText(q.answer), + // Coupée au milieu d'une phrase OU lignes non montrées : pour le panneau, + // une seule mention « réponse raccourcie » (le contrat n'a qu'une clé). + 'truncated': q.truncated || q.shortened, + 'sources': [for (final AnswerSource s in q.sources) s.title], +}; diff --git a/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.dart b/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.dart new file mode 100644 index 00000000..529034cf --- /dev/null +++ b/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.dart @@ -0,0 +1,248 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:core_foundation/logging/logger.dart'; +import 'package:flutter/services.dart'; +import 'package:ici_transcript/application/services/live_answers/live_answers.service.dart'; +import 'package:ici_transcript/application/services/live_answers/live_question.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.dart'; +import 'package:ici_transcript/core/providers/platform/owned_processes.provider.dart'; +import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/features/calendar/meeting_suggestion.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/shell/presentation/start_note.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_snapshot.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'status_panel_sync.provider.g.dart'; + +/// Canal du panneau de barre de menus (StatusPanelPlugin.swift). +const MethodChannel kStatusPanelChannel = MethodChannel( + 'com.icitranscript/status_panel', +); + +/// Écart minimal entre deux envois : ~4 par seconde pendant un flux, le +/// dernier état toujours envoyé à la fin. +const Duration kStatusPanelThrottle = Duration(milliseconds: 250); + +/// Quitter : attente maximale de l'arrêt de la note… +const Duration kQuitNoteBound = Duration(seconds: 10); + +/// … puis de l'arrêt des serveurs (SIGTERM, SIGKILL après 5 s, port). +const Duration kQuitServersBound = Duration(seconds: 18); + +/// Tient le panneau de barre de menus à jour et exécute ses clics. Monté par +/// l'app (RootAppWidget) pour toute sa vie. +@Riverpod(keepAlive: true) +StatusPanelSync statusPanelSync(Ref ref) { + final StatusPanelSync sync = StatusPanelSync._(ref); + ref.onDispose(sync._dispose); + return sync; +} + +/// Voir [statusPanelSync]. +class StatusPanelSync { + StatusPanelSync._(this._ref) { + kStatusPanelChannel.setMethodCallHandler(_onCall); + _ref.listen(liveTranscriptionViewModelProvider, (_, _) => _changed()); + _ref.listen(meetingSuggestionControllerProvider, (_, MeetingSuggestion? s) { + _changed(); + _suggest(s); + }); + _ref.listen(dictationActiveProvider, (_, _) => _changed()); + _questions = _answers.questionsStream.listen((_) => _changed()); + _send(force: true); + } + + final Ref _ref; + final Log _log = Log.named('StatusPanel'); + late final StreamSubscription> _questions; + Timer? _cooldown; + bool _dirty = false; + String? _lastSent; + Future? _starting; + Future? _stopping; + Future? _quitting; + final Set _suggested = {}; + final List> _idleWaiters = >[]; + + LiveAnswersService get _answers => _ref.read(liveAnswersServiceProvider); + LiveTranscriptionState get _live => + _ref.read(liveTranscriptionViewModelProvider); + LiveTranscriptionViewModel get _liveVm => + _ref.read(liveTranscriptionViewModelProvider.notifier); + + Map _snapshot() => statusPanelSnapshot( + live: _live, + questions: _answers.questions, + suggestion: _ref.read(meetingSuggestionControllerProvider), + dictating: _ref.read(dictationActiveProvider), + ); + + bool get _idle => + !_live.isRecording && + !_live.isPaused && + _live.finalisingRemaining == null; + + void _changed() { + if (_quitting != null) _skipIfFinalising(); + if (_idle) { + for (final Completer c in _idleWaiters) { + c.complete(); + } + _idleWaiters.clear(); + } + if (_cooldown != null) { + _dirty = true; + return; + } + _send(); + } + + /// Une NOUVELLE suggestion se remarque pendant un appel : le natif ouvre + /// le panneau sans activer l'app. Une fois par clé, jamais pendant une + /// note ni une dictée. + void _suggest(MeetingSuggestion? s) { + if (s == null || !_idle || _ref.read(dictationActiveProvider)) return; + if (!_suggested.add(s.key)) return; + unawaited( + _invoke('suggest', { + 'key': s.key, + ...statusPanelSuggestion(s), + }), + ); + } + + /// Envoie l'instantané s'il a changé ([force] : même inchangé), puis + /// ouvre une période de [kStatusPanelThrottle] où les changements + /// attendent. + void _send({bool force = false}) { + _dirty = false; + final Map snapshot = _snapshot(); + final String encoded = jsonEncode(snapshot); + if (!force && encoded == _lastSent) return; + _lastSent = encoded; + unawaited(_invoke('update', snapshot)); + _cooldown?.cancel(); + _cooldown = Timer(kStatusPanelThrottle, () { + _cooldown = null; + if (_dirty) _send(); + }); + } + + /// Panneau absent (tests, plugin non chargé) ou en erreur : rien ne + /// remonte ; jamais les arguments au journal (textes de la réunion). + Future _invoke(String method, [Object? args]) async { + try { + await kStatusPanelChannel.invokeMethod(method, args); + } on MissingPluginException { + // Pas de panneau natif. + } on PlatformException catch (e) { + _log.warning('Panneau : $method refusé (${e.code})'); + } + } + + Future _onCall(MethodCall call) async { + switch (call.method) { + case 'ready': + _send(force: true); + case 'start': + await _start(() => startOrShowNote(_ref.read)); + case 'acceptSuggestion': + final MeetingSuggestionController suggestion = _ref.read( + meetingSuggestionControllerProvider.notifier, + ); + if (_ref.read(meetingSuggestionControllerProvider) == null) return; + await _start(suggestion.start); + case 'dismissSuggestion': + if (_ref.read(meetingSuggestionControllerProvider) == null) return; + _ref.read(meetingSuggestionControllerProvider.notifier).dismiss(); + case 'stop': + await _stop(); + case 'pauseResume': + if (_live.finalisingRemaining != null) return; + if (_live.isPaused) { + await _liveVm.resumeSession(); + } else if (_live.isRecording) { + await _liveVm.pauseSession(); + } + case 'skipFinalising': + if (_live.finalisingRemaining != null) _liveVm.skipFinalising(); + case 'answerNow': + final Object? id = + (call.arguments as Map?)?['questionId']; + // `retry` efface une réponse reçue : seulement une question à + // demander. + if (_answers.questions.any( + (LiveQuestion q) => + q.id == id && q.status == LiveQuestionStatus.detected, + )) { + _answers.retry(id! as String); + } + case 'openWindow': + await _invoke('showWindow'); + case 'quit': + // Panneau, ⌘Q, Dock › Quitter : une seule fin. + await (_quitting ??= _quit()); + } + } + + /// Quitter : note arrêtée et sauvée (finalisation passée : l'audio est + /// sur disque, le rattrapage reprend au lancement suivant), puis tous les + /// serveurs lancés par Oats, puis `terminate`. Chaque étape est bornée : + /// `terminate` part au plus [kQuitNoteBound] + [kQuitServersBound] après + /// la demande, quoi qu'il reste bloqué. + Future _quit() async { + _skipIfFinalising(); + try { + await _noteStopped().timeout(kQuitNoteBound); + } on Object catch (e) { + _log.warning('Note non arrêtée en quittant (${e.runtimeType})'); + } + await _ref + .read(ownedProcessRegistryProvider) + .stopAll() + .timeout(kQuitServersBound, onTimeout: () {}); + await _invoke('terminate'); + } + + Future _noteStopped() async { + await _stop(); + if (_idle) return; + final Completer idle = Completer(); + _idleWaiters.add(idle); + await idle.future; + } + + void _skipIfFinalising() { + if (_live.finalisingRemaining != null) _liveVm.skipFinalising(); + } + + /// Un seul démarrage à la fois (double clic, Démarrer + suggestion). + Future _start(Future Function() start) { + return _starting ??= start().whenComplete(() => _starting = null); + } + + /// Arrête la note en cours, une seule fois ; rien au repos ni pendant la + /// finalisation. N'ouvre pas la note. + Future _stop() { + final Future? inFlight = _stopping; + if (inFlight != null) return inFlight; + if (_live.finalisingRemaining != null || + !(_live.isRecording || _live.isPaused)) { + return Future.value(); + } + return _stopping = _liveVm + .stopSession() + .then((_) {}) + .whenComplete(() => _stopping = null); + } + + void _dispose() { + kStatusPanelChannel.setMethodCallHandler(null); + _cooldown?.cancel(); + unawaited(_questions.cancel()); + } +} diff --git a/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.g.dart b/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.g.dart new file mode 100644 index 00000000..713b4f14 --- /dev/null +++ b/apps/app_macos/lib/features/status_panel/status_panel_sync.provider.g.dart @@ -0,0 +1,59 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'status_panel_sync.provider.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Tient le panneau de barre de menus à jour et exécute ses clics. Monté par +/// l'app (RootAppWidget) pour toute sa vie. + +@ProviderFor(statusPanelSync) +const statusPanelSyncProvider = StatusPanelSyncProvider._(); + +/// Tient le panneau de barre de menus à jour et exécute ses clics. Monté par +/// l'app (RootAppWidget) pour toute sa vie. + +final class StatusPanelSyncProvider + extends + $FunctionalProvider + with $Provider { + /// Tient le panneau de barre de menus à jour et exécute ses clics. Monté par + /// l'app (RootAppWidget) pour toute sa vie. + const StatusPanelSyncProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'statusPanelSyncProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$statusPanelSyncHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + StatusPanelSync create(Ref ref) { + return statusPanelSync(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(StatusPanelSync value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$statusPanelSyncHash() => r'605509fb699edaec29ff5354d41732017569295b'; diff --git a/apps/app_macos/lib/presentation/app.dart b/apps/app_macos/lib/presentation/app.dart index fdc8039f..c8d6fd93 100644 --- a/apps/app_macos/lib/presentation/app.dart +++ b/apps/app_macos/lib/presentation/app.dart @@ -6,6 +6,7 @@ import 'package:ici_transcript/core/providers/kernel.provider.dart'; import 'package:ici_transcript/core/providers/platform/uvx_available.provider.dart'; import 'package:ici_transcript/features/onboarding/presentation/ollama_setup.view_model.dart'; import 'package:ici_transcript/features/shared/presentation/screens/onboarding/uv_onboarding.screen.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_sync.provider.dart'; import 'package:ici_transcript/foundation/routing/app_router.dart'; import 'package:ici_transcript/generated/translations/locale_keys.g.dart'; @@ -53,6 +54,8 @@ class _RootAppWidgetState extends ConsumerState { ), ), data: (_) { + // Panneau de barre de menus : tenu à jour toute la vie de l'app. + ref.read(statusPanelSyncProvider); if (!(uvxState.value ?? true)) { return _simple( UvOnboardingScreen( diff --git a/apps/app_macos/macos/Runner.xcodeproj/project.pbxproj b/apps/app_macos/macos/Runner.xcodeproj/project.pbxproj index 0b2b19dd..dda12bcb 100644 --- a/apps/app_macos/macos/Runner.xcodeproj/project.pbxproj +++ b/apps/app_macos/macos/Runner.xcodeproj/project.pbxproj @@ -31,6 +31,7 @@ A1B2C3D4E5F6A7B8C9D0E1F3 /* AudioCapturePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D4E5F6A7B8C9D0E1F2 /* AudioCapturePlugin.swift */; }; 15DF8B1E5A36BDE4D4190969 /* CalendarPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2369EDC0C5307568C58C52C4 /* CalendarPlugin.swift */; }; 3E6841B4CD2DE57829845C9A /* MeetingDetectionPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 894A3DE1C64EE6E1AE9E576E /* MeetingDetectionPlugin.swift */; }; + FBA2045EE7065DC5D10553A7 /* StatusPanelPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E55DEDFDE60C73B40D53F00 /* StatusPanelPlugin.swift */; }; B7C1E2F3A4D5B6C7D8E9F0A2 /* KeychainPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C1E2F3A4D5B6C7D8E9F0A1 /* KeychainPlugin.swift */; }; B7C1E2F3A4D5B6C7D8E9F0B2 /* DocumentTextPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C1E2F3A4D5B6C7D8E9F0B1 /* DocumentTextPlugin.swift */; }; B7C1E2F3A4D5B6C7D8E9F0C2 /* FilePickerPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = B7C1E2F3A4D5B6C7D8E9F0C1 /* FilePickerPlugin.swift */; }; @@ -93,6 +94,7 @@ A1B2C3D4E5F6A7B8C9D0E1F2 /* AudioCapturePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AudioCapturePlugin.swift; sourceTree = ""; }; 2369EDC0C5307568C58C52C4 /* CalendarPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalendarPlugin.swift; sourceTree = ""; }; 894A3DE1C64EE6E1AE9E576E /* MeetingDetectionPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MeetingDetectionPlugin.swift; sourceTree = ""; }; + 9E55DEDFDE60C73B40D53F00 /* StatusPanelPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusPanelPlugin.swift; sourceTree = ""; }; B7C1E2F3A4D5B6C7D8E9F0A1 /* KeychainPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeychainPlugin.swift; sourceTree = ""; }; B7C1E2F3A4D5B6C7D8E9F0B1 /* DocumentTextPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DocumentTextPlugin.swift; sourceTree = ""; }; B7C1E2F3A4D5B6C7D8E9F0C1 /* FilePickerPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilePickerPlugin.swift; sourceTree = ""; }; @@ -209,6 +211,7 @@ A1B2C3D4E5F6A7B8C9D0E1F2 /* AudioCapturePlugin.swift */, 2369EDC0C5307568C58C52C4 /* CalendarPlugin.swift */, 894A3DE1C64EE6E1AE9E576E /* MeetingDetectionPlugin.swift */, + 9E55DEDFDE60C73B40D53F00 /* StatusPanelPlugin.swift */, B7C1E2F3A4D5B6C7D8E9F0A1 /* KeychainPlugin.swift */, B7C1E2F3A4D5B6C7D8E9F0B1 /* DocumentTextPlugin.swift */, B7C1E2F3A4D5B6C7D8E9F0C1 /* FilePickerPlugin.swift */, @@ -466,6 +469,7 @@ A1B2C3D4E5F6A7B8C9D0E1F3 /* AudioCapturePlugin.swift in Sources */, 15DF8B1E5A36BDE4D4190969 /* CalendarPlugin.swift in Sources */, 3E6841B4CD2DE57829845C9A /* MeetingDetectionPlugin.swift in Sources */, + FBA2045EE7065DC5D10553A7 /* StatusPanelPlugin.swift in Sources */, B7C1E2F3A4D5B6C7D8E9F0A2 /* KeychainPlugin.swift in Sources */, B7C1E2F3A4D5B6C7D8E9F0B2 /* DocumentTextPlugin.swift in Sources */, B7C1E2F3A4D5B6C7D8E9F0C2 /* FilePickerPlugin.swift in Sources */, diff --git a/apps/app_macos/macos/Runner/AppDelegate.swift b/apps/app_macos/macos/Runner/AppDelegate.swift index b3c17614..b9a2e4ac 100644 --- a/apps/app_macos/macos/Runner/AppDelegate.swift +++ b/apps/app_macos/macos/Runner/AppDelegate.swift @@ -3,8 +3,25 @@ import FlutterMacOS @main class AppDelegate: FlutterAppDelegate { + // Closing the window hides it (MainFlutterWindow.windowShouldClose): the app + // lives on in the menu bar (StatusPanelPlugin) until Quit. override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { - return true + return false + } + + // Dock click with the window hidden: show it again. A minimized window + // counts as visible: AppKit restores it itself. + override func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { + if flag { return true } + StatusPanelPlugin.showMainWindow() + return false + } + + // Cmd+Q, the app menu, Dock › Quit, logout: the same Dart `quit` as the + // panel (note saved, owned servers stopped), bounded (StatusPanelPlugin). + // Without the plugin (engine not up), quit at once. + override func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + return StatusPanelPlugin.shared?.shouldTerminate() ?? .terminateNow } override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { diff --git a/apps/app_macos/macos/Runner/MainFlutterWindow.swift b/apps/app_macos/macos/Runner/MainFlutterWindow.swift index 7d890127..52d63717 100644 --- a/apps/app_macos/macos/Runner/MainFlutterWindow.swift +++ b/apps/app_macos/macos/Runner/MainFlutterWindow.swift @@ -1,7 +1,7 @@ import Cocoa import FlutterMacOS -class MainFlutterWindow: NSWindow { +class MainFlutterWindow: NSWindow, NSWindowDelegate { override func awakeFromNib() { let flutterViewController = FlutterViewController() let windowFrame = self.frame @@ -19,7 +19,19 @@ class MainFlutterWindow: NSWindow { MeetingDetectionPlugin.register(with: flutterViewController.registrar(forPlugin: "MeetingDetectionPlugin")) GlobalShortcutPlugin.register(with: flutterViewController.registrar(forPlugin: "GlobalShortcutPlugin")) TextOutputPlugin.register(with: flutterViewController.registrar(forPlugin: "TextOutputPlugin")) + StatusPanelPlugin.register(with: flutterViewController.registrar(forPlugin: "StatusPanelPlugin")) + // Flutter leaves the window delegate unset (checked 2026-11-23). + delegate = self super.awakeFromNib() } + + /// Close button and Cmd+W only hide the window: the app stays in the menu + /// bar and the Dock, a recording goes on. Quitting does not go through here + /// (windowShouldClose(_:) doc). The close button does not call + /// performClose(_:), hence the delegate. + func windowShouldClose(_ sender: NSWindow) -> Bool { + orderOut(nil) + return false + } } diff --git a/apps/app_macos/macos/Runner/StatusPanelPlugin.swift b/apps/app_macos/macos/Runner/StatusPanelPlugin.swift new file mode 100644 index 00000000..c14f1ac7 --- /dev/null +++ b/apps/app_macos/macos/Runner/StatusPanelPlugin.swift @@ -0,0 +1,676 @@ +import AppKit +import FlutterMacOS +import Foundation + +// Apple documentation (read 2026-11-23): +// - https://developer.apple.com/documentation/appkit/nsstatusbar/statusitem(withlength:) +// (the status bar does not retain the item: keep a strong reference) +// - https://developer.apple.com/documentation/appkit/nsstatusitem/button (macOS 10.10+) +// - https://developer.apple.com/documentation/appkit/nswindow/stylemask-swift.struct/nonactivatingpanel +// ("a panel ... that does not activate the owning app"; SDK header NSWindow.h: NSPanel only) +// - https://developer.apple.com/documentation/appkit/nswindow/hidesondeactivate +// (default true for NSPanel: set to false, Oats is usually inactive when the panel opens) +// - https://developer.apple.com/documentation/appkit/nswindow/canbecomekey +// (false without `titled`: overridden so the panel gets Escape) +// - https://developer.apple.com/documentation/appkit/nsevent/addglobalmonitorforevents(matching:handler:) +// (mouse-down monitoring needs no accessibility trust; never called for our own events) +// - https://developer.apple.com/documentation/appkit/nsapplicationdelegate/applicationshouldterminateafterlastwindowclosed(_:) +// - https://developer.apple.com/documentation/appkit/nsapplicationdelegate/applicationshouldhandlereopen(_:hasvisiblewindows:) +// - https://developer.apple.com/documentation/appkit/nsapplicationdelegate/applicationshouldterminate(_:) +// - https://developer.apple.com/documentation/appkit/nsapplication/reply(toapplicationshouldterminate:) +// (after terminateLater, the app must reply) +// - https://developer.apple.com/documentation/appkit/nsworkspace/willpoweroffnotification +// - https://developer.apple.com/documentation/foundation/processinfo/beginactivity(options:reason:) +// - https://developer.apple.com/documentation/appkit/nswindowdelegate/windowshouldclose(_:) +// ("not called when a user quits an application") +// SF Symbols need macOS 11: below, plain drawn shapes. + +/// Menu bar item and its panel: see that a note records, start or stop it, +/// the last lines, the live question and the meeting suggestion, without +/// bringing the main window forward. AppKit views only; everything shown +/// comes from the last `update` snapshot sent by Dart. +/// +/// Channel `com.icitranscript/status_panel` (contract: top of +/// test/features/status_panel/status_panel_snapshot_test.dart): +/// - Dart -> Swift: `update` {snapshot}, `showWindow`, `terminate` +/// - Swift -> Dart: `ready`, `start`, `stop`, `pauseResume`, `skipFinalising`, +/// `acceptSuggestion`, `dismissSuggestion`, `answerNow` {questionId}, `openWindow`, `quit` +/// Nothing is logged: titles, lines and answers stay on this Mac. +class StatusPanelPlugin: NSObject, FlutterPlugin, NSWindowDelegate { + + /// Button labels and fixed texts, French, in one place. + private enum L { + static let start = "Démarrer la note" + static let stop = "Arrêter" + static let pause = "Pause" + static let resume = "Reprendre" + static let skip = "Passer" + static let idle = "Aucune note en cours" + static let untitled = "Note sans titre" + static let paused = "En pause" + static let finalising = "Finalisation… %d s" + static let dictating = "Dictée en cours" + static let answer = "Répondre" + static let ignore = "Ignorer" + static let open = "Ouvrir Oats" + static let quit = "Quitter" + static let truncated = "Réponse raccourcie" + static let sources = "Sources : " + static let questionStates: [String: String] = [ + "detected": "Question détectée", + "answering": "Réponse en cours…", + "answered": "Réponse proposée", + "declined": "Pas de réponse utile", + "failed": "La réponse a échoué", + "needsModel": "Aucun modèle prêt", + ] + } + + private static let width: CGFloat = 340 + private static let padding: CGFloat = 14 + + /// Green of the app, reserved for "live": the recording dot only. + fileprivate static let live = PanelColor.accent + + private let channel: FlutterMethodChannel + private let statusItem: NSStatusItem + private lazy var panel: StatusPanelWindow = makePanel() + private var snapshot: [String: Any] = [:] + private var clickMonitor: Any? + private var closedAt = Date.distantPast + + init(channel: FlutterMethodChannel) { + self.channel = channel + statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + super.init() + if let button = statusItem.button { + button.target = self + button.action = #selector(toggle) + button.imagePosition = .imageLeading + } + refreshStatusItem() + powerOffObserver = NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.willPowerOffNotification, object: nil, queue: nil + ) { [weak self] _ in self?.poweringOff = true } + } + + static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "com.icitranscript/status_panel", + binaryMessenger: registrar.messenger + ) + let instance = StatusPanelPlugin(channel: channel) + registrar.addMethodCallDelegate(instance, channel: channel) + shared = instance + // Dart may not listen yet: it also sends a first snapshot itself. + channel.invokeMethod("ready", arguments: nil) + } + + func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + switch call.method { + case "update": + snapshot = call.arguments as? [String: Any] ?? [:] + refreshStatusItem() + holdActivityWhileRecording() + if panel.isVisible { rebuildPanel() } + result(nil) + case "suggest": + showSuggestion(call.arguments as? [String: Any] ?? [:]) + result(nil) + case "showWindow": + closePanel() + StatusPanelPlugin.showMainWindow() + result(nil) + case "terminate": + result(nil) + finishQuit() + default: + result(FlutterMethodNotImplemented) + } + } + + /// The live plugin, for AppDelegate's quit routing; nil before the + /// Flutter view registers it. + private(set) static weak var shared: StatusPanelPlugin? + + /// Native safety bound, a little above Dart's 30 s: the app can never + /// refuse to quit. + private static let quitTimeout: TimeInterval = 35 + private var quitPending = false + private var awaitingReply = false + private var dartQuitDone = false + private var poweringOff = false + private var powerOffObserver: NSObjectProtocol? + + /// Every way of quitting (Cmd+Q, app menu, Dock, logout) goes through + /// Dart `quit` (note saved, owned servers stopped), which answers with + /// `terminate`; then the app quits for real. + /// + /// Cmd+Q: `.terminateCancel`, then `NSApp.terminate` again once Dart is + /// done (as FlutterAppDelegate does). `.terminateLater` would run the + /// loop in NSModalPanelRunLoopMode, where Flutter messages still flow + /// (FlutterRunLoop schedules in common modes) but blocks sent with + /// `DispatchQueue.main.async` do not (checked 2026-11-23 with a swiftc + /// script) — and AudioCapturePlugin answers through the main queue, so + /// stopping the note could stall. Logout/restart/shutdown: cancelling + /// would abort them, so `.terminateLater` there, bounded by the same + /// timer, which is added in common modes so it fires in modal mode. + func shouldTerminate() -> NSApplication.TerminateReply { + if dartQuitDone { return .terminateNow } + if !quitPending { + quitPending = true + closePanel() + channel.invokeMethod("quit", arguments: nil) { [weak self] reply in + // No Dart handler or a Dart error: do not wait for `terminate`. + if reply is FlutterError || (reply as? NSObject) === FlutterMethodNotImplemented { + self?.finishQuit() + } + } + let timer = Timer(timeInterval: StatusPanelPlugin.quitTimeout, repeats: false) { [weak self] _ in + self?.finishQuit() + } + RunLoop.main.add(timer, forMode: .common) + } + if poweringOff || systemQuit() { + awaitingReply = true + return .terminateLater + } + return .terminateCancel + } + + /// Logout, restart or shutdown: the quit Apple event carries a reason + /// (keyAEQuitReason); Cmd+Q sends no Apple event, Dock › Quit no reason. + /// willPowerOffNotification covers the same case if it arrives first. + private func systemQuit() -> Bool { + let quitReason = AEKeyword(0x7768_793F) // keyAEQuitReason, 'why?' + return NSAppleEventManager.shared().currentAppleEvent? + .attributeDescriptor(forKeyword: quitReason) != nil + } + + /// Dart is done (or the bound passed): quit for real. + private func finishQuit() { + if dartQuitDone && !quitPending { return } + quitPending = false + dartQuitDone = true + if awaitingReply { + awaitingReply = false + NSApp.reply(toApplicationShouldTerminate: true) + } else { + NSApp.terminate(nil) + } + } + + // MARK: - App Nap + + private var activity: NSObjectProtocol? + + /// A note in progress must not be throttled when the window is hidden. + private func holdActivityWhileRecording() { + let busy = status != "idle" + if busy && activity == nil { + activity = ProcessInfo.processInfo.beginActivity( + options: [.userInitiated, .idleSystemSleepDisabled], + reason: "Oats records a note" + ) + } else if !busy, let current = activity { + ProcessInfo.processInfo.endActivity(current) + activity = nil + } + } + + /// Brings the main window back (closed windows are only hidden) and + /// activates the app. + static func showMainWindow() { + guard let window = (NSApp.delegate as? FlutterAppDelegate)?.mainFlutterWindow else { return } + if window.isMiniaturized { window.deminiaturize(nil) } + window.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + // MARK: - Snapshot reading + + private var status: String { snapshot["status"] as? String ?? "idle" } + private var elapsed: Int { snapshot["elapsedSeconds"] as? Int ?? 0 } + + private static func clock(_ seconds: Int) -> String { + let h = seconds / 3600, m = (seconds % 3600) / 60, s = seconds % 60 + return h > 0 ? String(format: "%d:%02d:%02d", h, m, s) : String(format: "%d:%02d", m, s) + } + + // MARK: - Status item + + private func refreshStatusItem() { + guard let button = statusItem.button else { return } + button.image = StatusPanelPlugin.icon(for: status) + let showsClock = status == "recording" || status == "paused" + button.attributedTitle = NSAttributedString( + string: showsClock ? " " + StatusPanelPlugin.clock(elapsed) : "", + attributes: [.font: NSFont.monospacedDigitSystemFont(ofSize: 13, weight: .regular)] + ) + } + + private static func icon(for status: String) -> NSImage? { + if status == "recording" { return dot() } + let name: String + switch status { + case "paused": name = "pause.circle" + case "finalising": name = "hourglass" + default: name = "waveform" + } + let image: NSImage? + if #available(macOS 11.0, *) { + image = NSImage(systemSymbolName: name, accessibilityDescription: "Oats") + } else { + image = ring() + } + image?.isTemplate = true + return image + } + + /// The only colored mark of the app: a green dot while recording. The + /// color is resolved at draw time, so it follows the menu bar appearance. + private static func dot() -> NSImage { + let image = NSImage(size: NSSize(width: 14, height: 14), flipped: false) { rect in + StatusPanelPlugin.live.setFill() + NSBezierPath(ovalIn: rect.insetBy(dx: 3, dy: 3)).fill() + return true + } + image.isTemplate = false + return image + } + + private static func ring() -> NSImage { + NSImage(size: NSSize(width: 14, height: 14), flipped: false) { rect in + NSColor.black.setStroke() + let path = NSBezierPath(ovalIn: rect.insetBy(dx: 2.5, dy: 2.5)) + path.lineWidth = 1.5 + path.stroke() + return true + } + } + + // MARK: - Panel + + private func makePanel() -> StatusPanelWindow { + let panel = StatusPanelWindow( + contentRect: NSRect(x: 0, y: 0, width: StatusPanelPlugin.width, height: 100), + styleMask: [.nonactivatingPanel, .borderless], + backing: .buffered, + defer: true + ) + panel.isFloatingPanel = true + panel.hidesOnDeactivate = false + panel.isReleasedWhenClosed = false + panel.hasShadow = true + panel.isOpaque = false + panel.backgroundColor = .clear + panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .transient] + panel.delegate = self + panel.onEscape = { [weak self] in self?.closePanel() } + panel.contentView = PanelBackground() + return panel + } + + @objc private func toggle() { + if panel.isVisible { + closePanel() + return + } + // The click that made the panel lose key focus also lands here. + if Date().timeIntervalSince(closedAt) < 0.3 { return } + rebuildPanel() + panel.makeKeyAndOrderFront(nil) + clickMonitor = NSEvent.addGlobalMonitorForEvents( + matching: [.leftMouseDown, .rightMouseDown] + ) { [weak self] _ in self?.closePanel() } + channel.invokeMethod("ready", arguments: nil) + } + + /// Seconds a panel opened by `suggest` stays up (pointer outside). + private static let suggestionVisible: TimeInterval = 12 + private var autoClose: Timer? + + /// A new meeting suggestion during a call in another app: show the panel + /// without activating the app nor taking key focus; it closes by itself + /// unless the pointer is inside. Never over a panel already open. + private func showSuggestion(_ args: [String: Any]) { + if panel.isVisible { return } + // The matching `update` may still be throttled on the Dart side. + var suggestion = args + suggestion.removeValue(forKey: "key") + snapshot["suggestion"] = suggestion + snapshot["showStart"] = false + rebuildPanel() + panel.orderFrontRegardless() + clickMonitor = NSEvent.addGlobalMonitorForEvents( + matching: [.leftMouseDown, .rightMouseDown] + ) { [weak self] _ in self?.closePanel() } + scheduleAutoClose(after: StatusPanelPlugin.suggestionVisible) + } + + private func scheduleAutoClose(after seconds: TimeInterval) { + autoClose?.invalidate() + autoClose = Timer.scheduledTimer(withTimeInterval: seconds, repeats: false) { [weak self] _ in + guard let self = self, self.panel.isVisible else { return } + if self.panel.frame.contains(NSEvent.mouseLocation) { + self.scheduleAutoClose(after: 3) + } else { + self.closePanel() + } + } + } + + private func closePanel() { + autoClose?.invalidate() + autoClose = nil + if let monitor = clickMonitor { NSEvent.removeMonitor(monitor) } + clickMonitor = nil + guard panel.isVisible else { return } + panel.orderOut(nil) + closedAt = Date() + } + + func windowDidResignKey(_ notification: Notification) { + closePanel() + } + + private func rebuildPanel() { + guard let content = panel.contentView else { return } + content.subviews.forEach { $0.removeFromSuperview() } + let stack = NSStackView() + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = 8 + stack.edgeInsets = NSEdgeInsets( + top: StatusPanelPlugin.padding, left: StatusPanelPlugin.padding, + bottom: StatusPanelPlugin.padding, right: StatusPanelPlugin.padding + ) + stack.translatesAutoresizingMaskIntoConstraints = false + let blocks: [[NSView]] = [ + statusBlock(), + transcriptBlock(), + questionBlock(), + suggestionBlock(), + [row([button(L.open, "openWindow"), button(L.quit, "quit")])], + ].filter { !$0.isEmpty } // empty blocks are hidden, not shown empty + for (i, block) in blocks.enumerated() { + if i > 0 { stack.addArrangedSubview(separator()) } + block.forEach { stack.addArrangedSubview($0) } + } + content.addSubview(stack) + NSLayoutConstraint.activate([ + stack.leadingAnchor.constraint(equalTo: content.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: content.trailingAnchor), + stack.topAnchor.constraint(equalTo: content.topAnchor), + stack.widthAnchor.constraint(equalToConstant: StatusPanelPlugin.width), + ]) + for view in stack.arrangedSubviews where view is Hairline { + view.widthAnchor.constraint(equalTo: stack.widthAnchor, constant: -2 * StatusPanelPlugin.padding) + .isActive = true + } + stack.layoutSubtreeIfNeeded() + let size = NSSize(width: StatusPanelPlugin.width, height: stack.fittingSize.height) + panel.setFrame(frameUnderItem(size: size), display: true) + panel.invalidateShadow() + } + + /// Anchored under the status item, kept inside the screen. + private func frameUnderItem(size: NSSize) -> NSRect { + guard let itemWindow = statusItem.button?.window, + let screen = itemWindow.screen ?? NSScreen.main else { + return NSRect(origin: panel.frame.origin, size: size) + } + let item = itemWindow.frame + let visible = screen.visibleFrame + var x = item.midX - size.width / 2 + x = min(max(x, visible.minX + 8), visible.maxX - size.width - 8) + return NSRect(x: x, y: item.minY - size.height - 4, width: size.width, height: size.height) + } + + // MARK: - Blocks + + private func statusBlock() -> [NSView] { + let title = snapshot["title"] as? String + var views: [NSView] = [] + switch status { + case "recording", "paused": + let clock = StatusPanelPlugin.clock(elapsed) + views.append(label(title ?? L.untitled, bold: true)) + if status == "paused" { + views.append(label("\(L.paused) · \(clock)", secondary: true)) + } else { + let time = row([LiveDot(), label(clock, secondary: true)]) + time.spacing = 6 + views.append(time) + } + views.append(row([ + button(L.stop, "stop", primary: true), + button(status == "paused" ? L.resume : L.pause, "pauseResume"), + ])) + case "finalising": + if let title = title { views.append(label(title, bold: true)) } + let seconds = snapshot["finalisingSeconds"] as? Int ?? 0 + views.append(row([ + label(String(format: L.finalising, seconds), secondary: true), + button(L.skip, "skipFinalising"), + ])) + default: + views.append(label(L.idle, secondary: true)) + // One "Démarrer la note" only: a suggestion carries its own. + if snapshot["showStart"] as? Bool ?? true { + views.append(row([button(L.start, "start", primary: true)])) + } + } + if snapshot["dictating"] as? Bool == true { + views.append(label(L.dictating, secondary: true)) + } + return views + } + + private func transcriptBlock() -> [NSView] { + let lines = snapshot["transcript"] as? [[String: Any]] ?? [] + return lines.map { line in + let stack = NSStackView(views: [ + label(line["speaker"] as? String ?? "", secondary: true, small: true), + label(line["text"] as? String ?? ""), + ]) + stack.orientation = .vertical + stack.alignment = .leading + stack.spacing = 2 + return stack + } + } + + private func questionBlock() -> [NSView] { + guard let q = snapshot["question"] as? [String: Any] else { return [] } + let state = q["state"] as? String ?? "" + var views: [NSView] = [ + label(q["text"] as? String ?? "", bold: true), + label(L.questionStates[state] ?? "", secondary: true, small: true), + ] + if let answer = q["answer"] as? String, !answer.isEmpty { + views.append(label(answer)) + } + if q["truncated"] as? Bool == true { + views.append(label(L.truncated, secondary: true, small: true)) + } + if let sources = q["sources"] as? [String], !sources.isEmpty { + views.append(label(L.sources + sources.joined(separator: ", "), secondary: true, small: true)) + } + // `detected` = an answer can be asked for (local model, on demand). + if state == "detected", let id = q["id"] as? String { + let answerButton = button(L.answer, "answerNow") + answerButton.identifier = NSUserInterfaceItemIdentifier("answerNow:" + id) + views.append(row([answerButton])) + } + return views + } + + private func suggestionBlock() -> [NSView] { + guard let s = snapshot["suggestion"] as? [String: Any] else { return [] } + var views: [NSView] = [label(s["title"] as? String ?? "", bold: true)] + if let detail = s["detail"] as? String, !detail.isEmpty { + views.append(label(detail, secondary: true)) + } + views.append(row([ + button(L.start, "acceptSuggestion", primary: true), + button(L.ignore, "dismissSuggestion"), + ])) + return views + } + + // MARK: - Views + + private func label(_ text: String, bold: Bool = false, secondary: Bool = false, small: Bool = false) -> NSTextField { + let field = NSTextField(wrappingLabelWithString: text) + let size: CGFloat = small ? 11 : 13 + field.font = bold ? .systemFont(ofSize: size, weight: .semibold) : .systemFont(ofSize: size) + field.textColor = secondary ? PanelColor.muted : PanelColor.ink + field.preferredMaxLayoutWidth = StatusPanelPlugin.width - 2 * StatusPanelPlugin.padding + field.isSelectable = false + return field + } + + /// Small outlined button; [primary] (Démarrer la note / Arrêter) is the + /// only filled one. + private func button(_ title: String, _ method: String, primary: Bool = false) -> NSButton { + let b = PanelButton(title: title, target: self, action: #selector(tap(_:))) + b.primary = primary + b.identifier = NSUserInterfaceItemIdentifier(method) + return b + } + + private func row(_ views: [NSView]) -> NSStackView { + let stack = NSStackView(views: views) + stack.orientation = .horizontal + stack.spacing = 8 + return stack + } + + private func separator() -> NSView { Hairline() } + + @objc private func tap(_ sender: NSButton) { + guard let id = sender.identifier?.rawValue else { return } + if id.hasPrefix("answerNow:") { + channel.invokeMethod("answerNow", arguments: ["questionId": String(id.dropFirst("answerNow:".count))]) + return + } + if id == "openWindow" || id == "quit" { closePanel() } + channel.invokeMethod(id, arguments: nil) + } +} + +/// Borderless non-activating panel that can still become key (Escape). +final class StatusPanelWindow: NSPanel { + var onEscape: (() -> Void)? + + override var canBecomeKey: Bool { true } + + override func cancelOperation(_ sender: Any?) { + onEscape?() + } +} + +/// Colors of the app (packages/core_presentation/lib/theme/oats_tokens.dart), +/// resolved per appearance: white / near-black ground, no vibrancy. +private enum PanelColor { + private static func pair(_ light: UInt32, _ dark: UInt32, alpha: CGFloat = 1) -> NSColor { + NSColor(name: nil) { appearance in + let hex = appearance.bestMatch(from: [.darkAqua, .aqua]) == .darkAqua ? dark : light + return NSColor( + srgbRed: CGFloat((hex >> 16) & 0xFF) / 255, + green: CGFloat((hex >> 8) & 0xFF) / 255, + blue: CGFloat(hex & 0xFF) / 255, + alpha: alpha + ) + } + } + + static let ground = pair(0xFFFFFF, 0x121212) // background + static let ink = pair(0x111111, 0xF2F2EF) // ink + static let onInk = pair(0xFFFFFF, 0x111111) // onInk + static let muted = pair(0x6C6E69, 0x8B8D87) // muted + static let line = pair(0xE8E8E6, 0x262725) // line (hairline) + static let hover = pair(0xF4F4F2, 0x1B1B1A) // hover (pressed) + static let accent = pair(0x2F7D4F, 0xA8E6BC) // accent, "live" only + static let border = pair(0x111111, 0xF2F2EF, alpha: 0.18) // button outline +} + +/// Panel ground: rounded 10, hairline border; the window adds the shadow. +private final class PanelBackground: NSView { + override func draw(_ dirtyRect: NSRect) { + let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 10, yRadius: 10) + PanelColor.ground.setFill() + path.fill() + PanelColor.line.setStroke() + path.lineWidth = 1 + path.stroke() + } +} + +/// 1 px separator between blocks. +private final class Hairline: NSView { + override var intrinsicContentSize: NSSize { NSSize(width: NSView.noIntrinsicMetric, height: 1) } + + override func draw(_ dirtyRect: NSRect) { + PanelColor.line.setFill() + bounds.fill() + } +} + +/// The green recording dot before the elapsed time. +private final class LiveDot: NSView { + override var intrinsicContentSize: NSSize { NSSize(width: 7, height: 7) } + + override func draw(_ dirtyRect: NSRect) { + PanelColor.accent.setFill() + NSBezierPath(ovalIn: bounds).fill() + } +} + +/// Small button: 1 px outline, transparent fill, radius 6, 12 pt medium; +/// primary = filled with the ink color. +private final class PanelButton: NSButton { + var primary = false + + convenience init(title: String, target: AnyObject, action: Selector) { + self.init(frame: .zero) + self.title = title + self.target = target + self.action = action + isBordered = false + font = .systemFont(ofSize: 12, weight: .medium) + setButtonType(.momentaryChange) + } + + override var intrinsicContentSize: NSSize { + let text = (title as NSString).size(withAttributes: [.font: font as Any]) + return NSSize(width: ceil(text.width) + 20, height: 24) + } + + override func draw(_ dirtyRect: NSRect) { + let path = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 6, yRadius: 6) + let pressed = isHighlighted + if primary { + (pressed ? PanelColor.muted : PanelColor.ink).setFill() + path.fill() + } else { + if pressed { + PanelColor.hover.setFill() + path.fill() + } + PanelColor.border.setStroke() + path.lineWidth = 1 + path.stroke() + } + let attributes: [NSAttributedString.Key: Any] = [ + .font: font as Any, + .foregroundColor: primary ? PanelColor.onInk : PanelColor.ink, + ] + let size = (title as NSString).size(withAttributes: attributes) + (title as NSString).draw( + at: NSPoint(x: (bounds.width - size.width) / 2, y: (bounds.height - size.height) / 2), + withAttributes: attributes + ) + } +} diff --git a/apps/app_macos/test/core/platform/owned_processes_stop_all_test.dart b/apps/app_macos/test/core/platform/owned_processes_stop_all_test.dart new file mode 100644 index 00000000..f9592323 --- /dev/null +++ b/apps/app_macos/test/core/platform/owned_processes_stop_all_test.dart @@ -0,0 +1,187 @@ +import 'dart:io'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/core/platform/owned_processes.dart'; + +import '../../helpers/process_host_fakes.dart'; + +/// Quitter Oats (T3, panneau de barre de menus) : tous les serveurs lancés +/// par l'app s'arrêtent avant la fin du processus, au lieu d'attendre le +/// nettoyage du lancement suivant. Seuls ceux du registre ; un échec sur +/// l'un n'empêche pas les autres et ne remonte jamais. +/// +/// API supposée : `Future OwnedProcessRegistry.stopAll()`. +void main() { + late Directory dir; + late String stateFile; + late FakeProcessHost host; + + setUp(() { + dir = Directory.systemTemp.createTempSync('owned_processes_stop_all_'); + stateFile = '${dir.path}/servers.json'; + host = FakeProcessHost(); + }); + tearDown(() => dir.deleteSync(recursive: true)); + + List launch(FakeAsync async, OwnedProcessRegistry registry) { + final List pids = []; + registry + .start('transcription', 'uvx', ['voxmlx-serve'], port: 8100) + .then((Process p) => pids.add(p.pid)); + registry + .start('llm', 'ollama', ['serve'], port: 11434) + .then((Process p) => pids.add(p.pid)); + async.flushMicrotasks(); + return pids; + } + + test('arrête tous les serveurs lancés et vide le fichier d\'état', () { + fakeAsync((FakeAsync async) { + final OwnedProcessRegistry registry = OwnedProcessRegistry( + host: host, + stateFile: stateFile, + ); + final List pids = launch(async, registry); + expect(pids, hasLength(2)); + + bool done = false; + registry.stopAll().then((_) => done = true); + async.elapse(const Duration(seconds: 30)); + + expect(done, isTrue); + for (final int pid in pids) { + expect(host.table.containsKey(pid), isFalse, reason: 'pid $pid'); + } + // Lancement suivant : plus rien à nettoyer. + final FakeProcessHost next = FakeProcessHost(firstPid: 9000) + ..table.addAll(host.table); + OwnedProcessRegistry(host: next, stateFile: stateFile).cleanUpLeftovers(); + async.elapse(const Duration(seconds: 30)); + expect(next.kills, isEmpty); + expect(next.groupKills, isEmpty); + }); + }); + + test('ne touche jamais un processus qu\'il n\'a pas lancé', () { + fakeAsync((FakeAsync async) { + host.addForeign( + const RunningProcess( + pid: 777, + groupId: 777, + startTime: 'Sun Nov 22 08:00:00 2026', + command: '/opt/tools/uvx voxmlx-serve --port 8000', + ), + ); + final OwnedProcessRegistry registry = OwnedProcessRegistry( + host: host, + stateFile: stateFile, + ); + launch(async, registry); + + registry.stopAll(); + async.elapse(const Duration(seconds: 30)); + + expect(host.table.containsKey(777), isTrue); + expect(host.killedPids, isNot(contains(777))); + }); + }); + + test('rien de lancé : aucun signal, fini tout de suite', () { + fakeAsync((FakeAsync async) { + bool done = false; + OwnedProcessRegistry( + host: host, + stateFile: stateFile, + ).stopAll().then((_) => done = true); + async.flushMicrotasks(); + + expect(done, isTrue); + expect(host.kills, isEmpty); + expect(host.groupKills, isEmpty); + }); + }); + + test('un serveur qui ignore SIGTERM est tué, dans une borne (< 30 s)', () { + fakeAsync((FakeAsync async) { + host.ignoreSigterm = true; + final OwnedProcessRegistry registry = OwnedProcessRegistry( + host: host, + stateFile: stateFile, + ); + final List pids = launch(async, registry); + + bool done = false; + registry.stopAll().then((_) => done = true); + async.elapse(const Duration(seconds: 30)); + + expect(done, isTrue); + expect(pids.where(host.table.containsKey), isEmpty); + }); + }); + + test('un signal qui échoue : pas d\'erreur remontée, les autres serveurs ' + 's\'arrêtent quand même', () { + fakeAsync((FakeAsync async) { + final _FailingHost failing = _FailingHost(host); + final OwnedProcessRegistry registry = OwnedProcessRegistry( + host: failing, + stateFile: stateFile, + ); + final List pids = launch(async, registry); + failing.failingPid = pids.first; + + Object? error; + bool done = false; + registry.stopAll().then( + (_) => done = true, + onError: (Object e) => error = e, + ); + async.elapse(const Duration(seconds: 30)); + + expect(error, isNull); + expect(done, isTrue); + expect(host.table.containsKey(pids.last), isFalse); + }); + }); +} + +/// Signaler [failingPid] (seul ou son groupe) lève une erreur du système. +final class _FailingHost implements ProcessHost { + _FailingHost(this._d); + + final FakeProcessHost _d; + int? failingPid; + + @override + Future start( + String executable, + List arguments, { + Map? environment, + ProcessStartMode mode = ProcessStartMode.normal, + }) => _d.start(executable, arguments, environment: environment, mode: mode); + + @override + Future> running() => _d.running(); + + @override + bool kill(int pid, [ProcessSignal signal = ProcessSignal.sigterm]) { + if (pid == failingPid) throw const ProcessException('kill', []); + return _d.kill(pid, signal); + } + + @override + bool killGroup(int groupId, [ProcessSignal signal = ProcessSignal.sigterm]) { + if (groupId == failingPid) throw const ProcessException('kill', []); + return _d.killGroup(groupId, signal); + } + + @override + int get appGroupId => _d.appGroupId; + + @override + Future isPortFree(int port) => _d.isPortFree(port); + + @override + Future isHealthy(Uri url) => _d.isHealthy(url); +} diff --git a/apps/app_macos/test/features/status_panel/recording_survives_window_close_test.dart b/apps/app_macos/test/features/status_panel/recording_survives_window_close_test.dart new file mode 100644 index 00000000..5f091a47 --- /dev/null +++ b/apps/app_macos/test/features/status_panel/recording_survives_window_close_test.dart @@ -0,0 +1,84 @@ +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/widgets.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/core/providers/data/database.provider.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_answers.service.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'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; + +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/settings_fakes.dart'; + +// Panneau de barre de menus (T3), besoin 4 : fermer la fenêtre principale +// n'arrête pas une note. Côté Dart, l'enregistrement ne dépend pas du cycle +// de vie de la fenêtre : la fenêtre masquée (inactive → hidden → paused), +// la capture continue, les phrases continuent d'arriver. +// +// Vert aujourd'hui : épingle que personne n'ajoute un arrêt sur le cycle de +// vie. Le reste ne se vérifie qu'en natif (AppDelegate.swift : +// `applicationShouldTerminateAfterLastWindowClosed` renvoie true +// aujourd'hui ; il doit renvoyer false et la fermeture masquer la fenêtre). +void main() { + final TestWidgetsFlutterBinding binding = + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'fenêtre masquée pendant une note : l\'enregistrement continue', + () async { + resetPrefs(); + final LiveServiceHarness live = LiveServiceHarness(FakeAsync()); + final ProviderContainer c = ProviderContainer( + overrides: [ + liveTranscriptionServiceProvider.overrideWithValue(live.service), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: live.process), + ), + audioCaptureChannelProvider.overrideWithValue(live.audio), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + databaseProvider.overrideWithValue(memoryDatabase()), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + ], + ); + addTearDown(c.dispose); + addTearDown(() => live.service.stopTranscription()); + addTearDown(() { + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + }); + + c.read(liveTranscriptionViewModelProvider.notifier); + await c.read(liveTranscriptionViewModelProvider.notifier).startSession(); + expect(c.read(liveTranscriptionViewModelProvider).isRecording, isTrue); + + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.paused); + + live.fakeRemote.emitDone(AudioSource.output, 'On continue sans fenêtre.'); + await eventually( + () => expect( + c + .read(liveTranscriptionViewModelProvider) + .segments + .map((TranscriptSegmentEntity s) => s.text), + contains('On continue sans fenêtre.'), + ), + ); + expect(c.read(liveTranscriptionViewModelProvider).isRecording, isTrue); + expect(live.audio.stopCalls, 0); + expect(live.service.isRecording, isTrue); + }, + ); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_app_wiring_test.dart b/apps/app_macos/test/features/status_panel/status_panel_app_wiring_test.dart new file mode 100644 index 00000000..e5dad65b --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_app_wiring_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/misc.dart' show Override; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/presentation/app.dart'; + +import '../../helpers/calendar_fakes.dart'; +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/localized_app.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3) : l'app lancée alimente le panneau sans +// que rien d'autre ne le demande (la synchro est montée par l'app, pas par +// un écran). +void main() { + testWidgets('au lancement de l\'app, le panneau reçoit un premier état', ( + WidgetTester tester, + ) async { + final FakeStatusPanelPlatform panel = FakeStatusPanelPlatform()..install(); + FakeMeetingPlatform().install(); + final AppFakes fakes = AppFakes(ollama: kOllamaReady); + tester.view.physicalSize = const Size(1280, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + + await tester.pumpWidget( + localized( + child: const RootAppWidget(), + overrides: [ + ...fakes.overrides, + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + ], + withMaterialApp: false, + ), + ); + await settle(tester); + + expect(panel.updates, isNotEmpty); + expect(panel.last['status'], 'idle'); + }); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_live_test.dart b/apps/app_macos/test/features/status_panel/status_panel_live_test.dart new file mode 100644 index 00000000..2c52dfff --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_live_test.dart @@ -0,0 +1,152 @@ +import 'dart:async'; + +import 'package:core_data/model/utterance_window.dart'; +import 'package:core_domain/domain/entities/session.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.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_transcription.service.dart'; +import 'package:ici_transcript/core/providers/data/database.provider.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/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.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'; +import 'package:ici_transcript/features/history/presentation/screens/list/session_list.view_model.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_sync.provider.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/settings_fakes.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3) avec le VRAI view model du direct et le +// vrai LiveTranscriptionService (serveur, micro, socket factices ; le test +// joue le serveur). Ce que le panneau montre vient de l'état réel : +// - « start » du panneau démarre une vraie note, dont le titre (celui de +// la session créée) est envoyé ; +// - les mots dictés pendant la réunion n'apparaissent jamais dans la fin +// de la transcription du panneau (la dictée a sa propre route, +// `beginDictation`) ; +// - « stop » du panneau arrête et sauve la note. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late LiveServiceHarness live; + late FakeStatusPanelPlatform panel; + late ProviderContainer c; + + setUp(() { + resetPrefs(); + panel = FakeStatusPanelPlatform()..install(); + live = LiveServiceHarness(FakeAsync()); + c = ProviderContainer( + overrides: [ + liveTranscriptionServiceProvider.overrideWithValue(live.service), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: live.process), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + databaseProvider.overrideWithValue(memoryDatabase()), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + sessionListViewModelProvider.overrideWith( + () => FakeSessionListViewModel(const []), + ), + ], + ); + addTearDown(c.dispose); + addTearDown(() => live.service.stopTranscription()); + c.read(liveTranscriptionViewModelProvider.notifier); + c.listen(statusPanelSyncProvider, (_, _) {}); + }); + + Map last() => panel.last; + + List tail() => (last()['transcript']! as List) + .map((Object? l) => (l! as Map)['text']) + .toList(); + + // Temps réel : borne large (cf. specs de l'agenda). + Future soon(FutureOr Function() check) => + eventually(check, timeout: const Duration(seconds: 10)); + + Future startFromPanel() async { + await soon(() => expect(panel.updates, isNotEmpty)); + await panel.send('start'); + await soon(() => expect(last()['status'], 'recording')); + } + + test('« start » du panneau : une vraie note démarre, son titre est ' + 'envoyé', () async { + await startFromPanel(); + + await soon(() { + expect(live.sessions.store.values, hasLength(1)); + expect(last()['title'], live.sessions.store.values.single.title); + }); + expect(last()['title'], isNotNull); + }); + + test( + 'une phrase finie des autres arrive dans la fin de la transcription', + () async { + await startFromPanel(); + + live.fakeRemote.emitDone(AudioSource.output, 'Le devis part demain.'); + + await soon(() => expect(tail(), contains('Le devis part demain.'))); + }, + ); + + test('les mots dictés pendant la réunion n\'apparaissent jamais dans le ' + 'panneau ; la dictée est signalée', () async { + await startFromPanel(); + final List dictated = []; + final int pressAt = DateTime.now().millisecondsSinceEpoch; + final MeetingDictation d = live.service.beginDictation()!; + d.onText = (String text, bool _) => dictated.add(text); + c.read(dictationActiveProvider.notifier).set(true); + + live.fakeRemote.emitDone( + AudioSource.input, + 'DICTÉE-PANNEAU rappeler le fournisseur', + window: UtteranceWindow(startMs: pressAt + 50, endMs: pressAt + 90), + ); + await soon(() => expect(dictated, isNotEmpty)); + live.fakeRemote.emitDone(AudioSource.output, 'On passe au point suivant.'); + + await soon(() { + expect(tail(), contains('On passe au point suivant.')); + expect(last()['dictating'], isTrue); + }); + for (final Map s in panel.updates) { + expect( + (s['transcript']! as List).toString(), + isNot(contains('DICTÉE-PANNEAU')), + ); + } + d.release(); + }); + + test('« stop » du panneau : la note s\'arrête, le panneau revient au ' + 'repos', () async { + await startFromPanel(); + + await panel.send('stop'); + + await soon(() { + expect(c.read(liveTranscriptionViewModelProvider).isRecording, isFalse); + expect(last()['status'], 'idle'); + }); + expect(live.audio.stopCalls, 1); + }); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_quit_backfill_test.dart b/apps/app_macos/test/features/status_panel/status_panel_quit_backfill_test.dart new file mode 100644 index 00000000..7bd458ae --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_quit_backfill_test.dart @@ -0,0 +1,424 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:core_data/clients/websocket_client.dart'; +import 'package:core_data/model/audio_gap.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/server_state.enum.dart'; +import 'package:core_domain/domain/services/transcription.service.dart'; +import 'package:core_domain/domain/usecases/save_transcript_segment.use_case.dart'; +import 'package:core_domain/domain/usecases/start_session.use_case.dart'; +import 'package:core_domain/domain/usecases/stop_session.use_case.dart'; +import 'package:flutter/services.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/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/gap_backfill_retry.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/websocket_pcm_transcriber.dart'; +import 'package:ici_transcript/core/platform/owned_processes.dart'; +import 'package:ici_transcript/core/providers/data/database.provider.dart'; +import 'package:ici_transcript/core/providers/platform/audio_capture.provider.dart'; +import 'package:ici_transcript/core/providers/platform/owned_processes.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_transcription.service.provider.dart'; +import 'package:ici_transcript/core/providers/services/process_manager.service.provider.dart'; +import 'package:ici_transcript/features/history/presentation/screens/list/session_list.view_model.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.view_model.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_sync.provider.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/live_service_fakes.dart'; +import '../../helpers/local_model_fakes.dart'; +import '../../helpers/process_host_fakes.dart' show FakeProcessHost; +import '../../helpers/settings_fakes.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3), revue de la PR #24 : quitter ne doit pas +// perdre le texte passé. `quit` passe la finalisation en promettant que le +// rattrapage reprend au lancement suivant, puis arrête le serveur +// (`OwnedProcessRegistry.stopAll`). Avec les VRAIS services (direct, +// GapBackfillService, GapBackfillRetry et son `.backfill_pending.json`), +// serveur de transcription et hôte de processus factices : +// - avant `terminate`, la session est notée en attente sur le disque ; +// - la tentative coupée par la fin de l'app ne compte pas parmi les trois ; +// - au lancement suivant (`retryPending`, serveur qui répond), la phrase +// revient, une fois, à son heure, et le repère de perte disparaît. +// +// La fin du processus est jouée ainsi : l'état du disque au moment du +// `terminate` est celui que lit le lancement suivant (rien n'écrit après). +// Temps réel, dossier temporaire de test, aucun réseau. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const String lost = 'Le devis part vendredi.'; + // Phrase perdue entre 10 et 20 s de réunion (repère de perte). + const int gapStart = 10000; + const int gapEnd = 20000; + + setUp(() async { + resetPrefs(); + final Directory d = Directory(LiveTranscriptionService.recordingsDir); + expect(d.path, startsWith(Directory.systemTemp.path)); + for (int i = 0; i < 5 && d.existsSync(); i++) { + try { + await d.delete(recursive: true); + } on FileSystemException { + await Future.delayed(const Duration(milliseconds: 50)); + } + } + await d.create(recursive: true); + }); + + File pendingFile() => + File('${LiveTranscriptionService.recordingsDir}/.backfill_pending.json'); + + /// [windowStopFirst] : la note est arrêtée depuis la fenêtre et le + /// rattrapage a atteint le serveur (sans réponse) quand `quit` arrive ; + /// sinon `quit` arrive pendant l'enregistrement. + Future scenario({required bool windowStopFirst}) async { + // --- Premier lancement --------------------------------------------- + final FakeProcessHost host = FakeProcessHost(); + final Directory stateDir = Directory.systemTemp.createTempSync( + 'quit_backfill_state_', + ); + addTearDown(() => stateDir.deleteSync(recursive: true)); + final OwnedProcessRegistry registry = OwnedProcessRegistry( + host: host, + stateFile: '${stateDir.path}/servers.json', + ); + final Process server = await registry.start( + 'transcription', + 'uvx', + ['voxmlx-serve'], + port: 8100, + ); + // Le serveur de rattrapage ne répond pas (phrase sans réponse) et meurt + // quand le registre l'arrête. + final _BackfillServer first = _BackfillServer( + reply: null, + alive: () => host.table.containsKey(server.pid), + ); + final _Rig rig = _Rig(backfillServer: first); + + final FakeStatusPanelPlatform panel = FakeStatusPanelPlatform()..install(); + String? pendingAtTerminate; + panel.onCall = (MethodCall call) { + if (call.method != 'terminate' || pendingAtTerminate != null) return; + pendingAtTerminate = pendingFile().existsSync() + ? pendingFile().readAsStringSync() + : ''; + }; + final ProviderContainer c = ProviderContainer( + overrides: [ + liveTranscriptionServiceProvider.overrideWithValue(rig.service), + processManagerServiceProvider.overrideWithValue( + ProcessManagerService(channel: rig.process), + ), + audioCaptureChannelProvider.overrideWithValue(DevicesAudioChannel()), + apiKeyStoreProvider.overrideWithValue(InMemoryApiKeyStore()), + databaseProvider.overrideWithValue(memoryDatabase()), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + sessionListViewModelProvider.overrideWith( + () => FakeSessionListViewModel(const []), + ), + ownedProcessRegistryProvider.overrideWithValue(registry), + ], + ); + c.read(liveTranscriptionViewModelProvider.notifier); + c.listen(statusPanelSyncProvider, (_, _) {}); + + await c.read(liveTranscriptionViewModelProvider.notifier).startSession(); + final String sessionId = rig.sessionId; + await rig.speak(0, 300); // 30 s de micro dans le WAV + rig.gap(gapStart, gapEnd); + await rig.until(() => rig.markersOf(sessionId).isNotEmpty); + expect(rig.markersOf(sessionId), hasLength(1)); + + if (windowStopFirst) { + unawaited( + c.read(liveTranscriptionViewModelProvider.notifier).stopSession(), + ); + await rig.until(() => first.commits > 0); + expect(first.commits, greaterThan(0), reason: 'rattrapage en vol'); + } + await panel.send('quit'); + await rig.until( + () => panel.callsTo('terminate').isNotEmpty, + within: const Duration(seconds: 40), + ); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(host.table.containsKey(server.pid), isFalse, reason: 'tué'); + expect( + pendingAtTerminate, + isNotEmpty, + reason: 'la session doit être notée en attente AVANT terminate', + ); + final Map pending = + jsonDecode(pendingAtTerminate!) as Map; + expect( + pending[sessionId], + 0, + reason: 'la tentative coupée par la fin de l\'app ne compte pas', + ); + + // Fin du processus : plus rien ne tourne, le disque est celui du + // terminate. + first.endOfProcess(); + c.dispose(); + await rig.dispose(); + await pendingFile().writeAsString(pendingAtTerminate!); + + // --- Lancement suivant --------------------------------------------- + final _BackfillServer second = _BackfillServer(reply: lost); + final GapBackfillRetry relaunch = GapBackfillRetry( + backfill: GapBackfillService( + transcriber: WebSocketPcmTranscriber( + url: 'ws://test', + createClient: second.client, + shouldYield: () => false, + ), + transcripts: rig.segments, + isRecording: () => false, + ), + serverStates: const Stream.empty(), + isRecording: () => false, + recordingsDirectory: LiveTranscriptionService.recordingsDir, + ); + addTearDown(relaunch.dispose); + + await relaunch.retryPending(); + + expect(rig.markersOf(sessionId), isEmpty, reason: 'repère remplacé'); + final List back = rig.segments.store.values + .where( + (TranscriptSegmentEntity s) => + s.sessionId == sessionId && s.text == lost, + ) + .toList(); + expect(back, hasLength(1), reason: 'la phrase revient, une fois'); + expect( + back.single.timestampMs, + inInclusiveRange( + gapStart - GapBackfillService.margin.inMilliseconds, + gapEnd, + ), + reason: 'à son heure dans la réunion', + ); + expect(pendingFile().existsSync(), isFalse, reason: 'plus rien en attente'); + } + + test('quitter pendant un enregistrement avec une perte : session en ' + 'attente sur le disque avant terminate, sans tentative comptée ; la ' + 'phrase revient au lancement suivant', () async { + await scenario(windowStopFirst: false); + }); + + test( + 'quitter pendant le rattrapage de l\'arrêt (serveur atteint, sans ' + 'réponse) : la tentative coupée ne compte pas, la session est en ' + 'attente avant terminate ; la phrase revient au lancement suivant', + () async { + await scenario(windowStopFirst: true); + }, + ); +} + +/// Direct réel monté sur des faux, rattrapage réel par +/// WebSocketPcmTranscriber sur [backfillServer] (comme +/// back_to_back_meetings_test.dart). +final class _Rig { + _Rig({required this.backfillServer}) { + transcription = TranscriptionService( + startSessionUseCase: StartSessionUseCase(sessionRepository: sessions), + stopSessionUseCase: StopSessionUseCase(sessionRepository: sessions), + saveTranscriptSegmentUseCase: SaveTranscriptSegmentUseCase( + transcriptRepository: segments, + ), + ); + bool recording() => transcription.isTranscribingStream.value; + retry = GapBackfillRetry( + backfill: GapBackfillService( + transcriber: WebSocketPcmTranscriber( + url: 'ws://test', + createClient: backfillServer.client, + shouldYield: recording, + ), + transcripts: segments, + isRecording: recording, + ), + serverStates: process.stateStream, + isRecording: recording, + recordingsDirectory: LiveTranscriptionService.recordingsDir, + ); + service = LiveTranscriptionService( + processManagerService: ProcessManagerService(channel: process), + audioCaptureChannel: audio, + transcriptionRemoteDataSource: remote, + transcriptionService: transcription, + gapBackfillRetry: retry, + ); + } + + final _BackfillServer backfillServer; + final FakeTranscriptionRemoteDataSource remote = + FakeTranscriptionRemoteDataSource(); + final FakeProcessManagerChannel process = FakeProcessManagerChannel(); + final FakeAudioCaptureChannel audio = FakeAudioCaptureChannel(); + final InMemorySessionRepository sessions = InMemorySessionRepository(); + final InMemoryTranscriptRepository segments = InMemoryTranscriptRepository(); + late final TranscriptionService transcription; + late final GapBackfillRetry retry; + late final LiveTranscriptionService service; + + Future dispose() async { + await retry.dispose(); + await service.dispose(); + } + + String get sessionId => transcription.currentSessionStream.value!.id; + int get t0 => transcription + .currentSessionStream + .value! + .createdAt + .millisecondsSinceEpoch; + + Future speak(int fromId, int count) async { + for (int id = fromId; id < fromId + count; id++) { + audio.emit(chunk(AudioSource.input, id, timestampMs: t0 + id * 100)); + if (id % 50 == 0) await Future.delayed(Duration.zero); + } + await Future.delayed(const Duration(milliseconds: 100)); + } + + void gap(int startMs, int endMs) => remote.emitGap( + AudioGap( + source: AudioSource.input, + startMs: t0 + startMs, + endMs: t0 + endMs, + ), + ); + + List markersOf(String sessionId) => segments + .store + .values + .where( + (TranscriptSegmentEntity s) => + s.sessionId == sessionId && + (s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix) || + LiveTranscriptionService.isUntranscribedMarker(s.text)), + ) + .toList(); + + Future until( + bool Function() condition, { + Duration within = const Duration(seconds: 10), + }) async { + final Stopwatch w = Stopwatch()..start(); + while (!condition() && w.elapsed < within) { + await Future.delayed(const Duration(milliseconds: 20)); + } + } +} + +/// Serveur de rattrapage factice : répond [reply] à chaque commit final +/// (null : jamais) ; quand [alive] devient faux (serveur arrêté), toute +/// socket ouverte se ferme en silence. +final class _BackfillServer { + _BackfillServer({required this.reply, this.alive}); + + final String? reply; + final bool Function()? alive; + + /// Commits finaux reçus (le rattrapage a atteint le serveur). + int commits = 0; + + final List<_BackfillSocket> _sockets = <_BackfillSocket>[]; + + WebSocketClient client() { + final _BackfillSocket socket = _BackfillSocket(this); + _sockets.add(socket); + return socket; + } + + /// Fin du processus jouée : toute attente en vol se termine (en erreur) + /// pour que le test puisse libérer ses services ; ce qu'elle écrit + /// ensuite n'est plus lu (le disque du `terminate` est restauré). + void endOfProcess() { + for (final _BackfillSocket s in _sockets) { + s._messages.addError(const SocketException('process ended')); + } + } +} + +final class _BackfillSocket extends WebSocketClient { + _BackfillSocket(this._server); + + final _BackfillServer _server; + bool _connected = false; + Timer? _watch; + final StreamController _messages = + StreamController.broadcast(); + + bool get _serverUp => _server.alive?.call() ?? true; + + @override + bool get isConnected => _connected; + + @override + Stream get messageStream => _messages.stream; + + @override + Future connect(String url) async { + if (!_serverUp) throw const SocketException('Connection refused'); + _connected = true; + _watch = Timer.periodic(const Duration(milliseconds: 50), (_) { + if (_serverUp || !_connected) return; + // Comme WebSocketClient quand le serveur meurt : la connexion se + // ferme (onDone), aucune erreur ni `done` sur messageStream ; le + // rattrapage en vol attend alors son délai (60 s), bien après la fin + // de l'app. + _close(); + }); + } + + @override + void send(String message) { + if (!_connected) return; + final Map json = + jsonDecode(message) as Map; + if (json['type'] != 'input_audio_buffer.commit') return; + _server.commits++; + final String? text = _server.reply; + if (text == null) return; + Timer(const Duration(milliseconds: 100), () { + if (!_connected) return; + _messages.add( + jsonEncode({ + 'type': 'response.audio_transcript.done', + 'text': text, + }), + ); + }); + } + + @override + Future disconnect() async => _close(); + + @override + Future dispose() async => _close(); + + void _close() { + _connected = false; + _watch?.cancel(); + } +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_quit_test.dart b/apps/app_macos/test/features/status_panel/status_panel_quit_test.dart new file mode 100644 index 00000000..063c473d --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_quit_test.dart @@ -0,0 +1,378 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:core_domain/domain/entities/session.entity.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/services.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/core/platform/owned_processes.dart'; +import 'package:ici_transcript/core/providers/platform/owned_processes.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/features/calendar/meeting_suggestion.provider.dart'; +import 'package:ici_transcript/features/history/presentation/screens/list/session_list.view_model.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/status_panel/status_panel_sync.provider.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/process_host_fakes.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3) : quitter. `quit` vient du panneau, et +// aussi de ⌘Q et Dock › Quitter (le natif route la demande du système vers +// la même action). Ordre épinglé : arrêter la note (sauvée) → arrêter les +// serveurs lancés par Oats (tout le registre des processus : un serveur de +// modèle de plusieurs Go ne survit pas à l'app) → `terminate`. +// +// Choix : quitter PASSE la finalisation (l'audio est sur disque, le +// rattrapage reprend au lancement suivant) ; quitter ne prend jamais des +// minutes. Borne : `terminate` part au plus 30 s après `quit`, même si +// l'arrêt de la note reste bloqué et qu'un serveur ignore SIGTERM (le +// registre attend 5 s avant SIGKILL, puis le port, d'où la marge). +// Idempotent : plusieurs `quit` → un arrêt, un `terminate`. +// +// Faux : direct (compte les actions), panneau natif, hôte de processus +// (aucun vrai processus). Temps simulé. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const Duration bound = Duration(seconds: 30); + + late FakeStatusPanelPlatform panel; + late QuitLiveViewModel live; + late FakeProcessHost host; + late OwnedProcessRegistry registry; + late ProviderContainer c; + late Directory dir; + late List servers; + + /// État noté au moment du `terminate`. + ({Duration at, Set alive, int stops, List log})? atTerminate; + + final LiveTranscriptionState recordingState = LiveTranscriptionState.initial() + .copyWith( + isRecording: true, + duration: const Duration(minutes: 2), + sessionTitle: 'Revue de sprint', + ); + + void mount(FakeAsync async, {ProcessHost Function(FakeProcessHost)? wrap}) { + dir = Directory.systemTemp.createTempSync('status_panel_quit_test_'); + addTearDown(() => dir.deleteSync(recursive: true)); + host = FakeProcessHost(); + registry = OwnedProcessRegistry( + host: wrap == null ? host : wrap(host), + stateFile: '${dir.path}/servers.json', + ); + servers = []; + // Le serveur de transcription et un autre serveur du registre. + registry + .start('transcription', 'uvx', ['voxmlx-serve'], port: 8100) + .then((Process p) => servers.add(p.pid)); + registry + .start('llm', 'ollama', ['serve'], port: 11434) + .then((Process p) => servers.add(p.pid)); + async.flushMicrotasks(); + expect(servers, hasLength(2), reason: 'deux serveurs lancés'); + + atTerminate = null; + panel = FakeStatusPanelPlatform()..install(); + live = QuitLiveViewModel(); + final List log = []; + panel.log = log; + live.log = log; + panel.onCall = (MethodCall call) { + if (call.method != 'terminate' || atTerminate != null) return; + atTerminate = ( + at: async.elapsed, + alive: servers.where(host.table.containsKey).toSet(), + stops: live.stopCalls, + log: List.of(log), + ); + }; + c = ProviderContainer( + overrides: [ + liveTranscriptionViewModelProvider.overrideWith(() => live), + meetingSuggestionControllerProvider.overrideWith( + PanelSuggestionController.new, + ), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + sessionListViewModelProvider.overrideWith( + () => FakeSessionListViewModel(const []), + ), + ownedProcessRegistryProvider.overrideWithValue(registry), + ], + ); + c.listen(statusPanelSyncProvider, (_, _) {}); + async.elapse(const Duration(seconds: 1)); + } + + void dispose(FakeAsync async) { + c.dispose(); + async.flushMicrotasks(); + } + + /// `quit` du panneau ; renvoie l'heure (simulée) de la demande. + Duration quit(FakeAsync async) { + final Duration at = async.elapsed; + panel.send('quit'); + async.flushMicrotasks(); + return at; + } + + test('au repos : les serveurs lancés par Oats s\'arrêtent, puis l\'app se ' + 'termine', () { + fakeAsync((FakeAsync async) { + mount(async); + + quit(async); + async.elapse(bound); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.alive, isEmpty, reason: 'serveurs arrêtés avant'); + expect(live.stopCalls, 0); + dispose(async); + }); + }); + + test('pendant une note : note arrêtée et sauvée → serveurs arrêtés → ' + 'terminate', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + live.stopGate = Completer(); + // Pas de finalisation ici : seul le complètement de l'arrêt compte. + live.skipReleasesStop = false; + + quit(async); + async.elapse(const Duration(seconds: 1)); + expect(live.stopCalls, 1); + expect( + host.killedPids, + isEmpty, + reason: 'aucun serveur arrêté tant que la note n\'est pas sauvée', + ); + expect(panel.callsTo('terminate'), isEmpty); + + live.stopGate!.complete(); + async.elapse(bound); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.alive, isEmpty); + expect( + atTerminate!.log.where((String l) => l.startsWith('live.')), + ['live.stop', 'live.stopped'], + ); + dispose(async); + }); + }); + + test('quitter pendant une note passe la finalisation (pas d\'attente de ' + 'minutes)', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + live.stopGate = Completer(); + // Arrêter vide l'audio restant : 2 min d'audio à transcrire. + live.drainOnStop = const Duration(minutes: 2); + + final Duration asked = quit(async); + async.elapse(bound); + + expect(live.skipCalls, greaterThanOrEqualTo(1)); + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.at - asked, lessThanOrEqualTo(bound)); + expect(atTerminate!.stops, 1); + expect(atTerminate!.log, contains('live.stopped')); + dispose(async); + }); + }); + + test('quitter pendant une finalisation lancée depuis la fenêtre : elle est ' + 'passée, pas de second arrêt, puis terminate', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show( + LiveTranscriptionState.initial().copyWith( + finalisingRemaining: const Duration(minutes: 2), + ), + ); + + final Duration asked = quit(async); + async.elapse(bound); + + expect(live.skipCalls, greaterThanOrEqualTo(1)); + expect(live.stopCalls, 0); + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.at - asked, lessThanOrEqualTo(bound)); + expect(atTerminate!.alive, isEmpty); + dispose(async); + }); + }); + + test('idempotent : deux quit de suite (panneau puis ⌘Q) → un arrêt, un ' + 'terminate, chaque serveur signalé une fois', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + live.stopGate = Completer(); + + quit(async); + quit(async); + async.elapse(const Duration(seconds: 1)); + live.stopGate!.complete(); + async.elapse(bound); + quit(async); + async.elapse(bound); + + expect(live.stopCalls, 1); + expect(panel.callsTo('terminate'), hasLength(1)); + expect( + host.groupKills + .where((k) => k.signal == ProcessSignal.sigterm) + .map((k) => k.groupId), + unorderedEquals(servers), + ); + dispose(async); + }); + }); + + test('l\'arrêt de la note reste bloqué et un serveur ignore SIGTERM : ' + 'terminate part quand même dans la borne, serveurs arrêtés', () { + fakeAsync((FakeAsync async) { + mount(async); + host.ignoreSigterm = true; + live.show(recordingState); + live.stopGate = Completer(); // jamais complété + live.skipReleasesStop = false; + + final Duration asked = quit(async); + async.elapse(const Duration(seconds: 60)); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.at - asked, lessThanOrEqualTo(bound)); + expect(atTerminate!.alive, isEmpty); + dispose(async); + }); + }); + + test('un serveur qu\'on ne peut pas arrêter (erreur du système) ' + 'n\'empêche ni l\'arrêt des autres ni la fin de l\'app', () { + fakeAsync((FakeAsync async) { + late FailingKillHost failing; + mount(async, wrap: (FakeProcessHost h) => failing = FailingKillHost(h)); + failing.failingGroup = servers.first; + + final Duration asked = quit(async); + async.elapse(bound); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(atTerminate!.at - asked, lessThanOrEqualTo(bound)); + expect(host.table.containsKey(servers.last), isFalse); + dispose(async); + }); + }); +} + +/// Direct factice pour quitter : l'arrêt peut vider de l'audio restant +/// (« Finalisation… ») jusqu'à `skipFinalising`, comme le vrai. +class QuitLiveViewModel extends PanelLiveViewModel { + /// Audio restant affiché pendant l'arrêt ; null = pas de finalisation. + Duration? drainOnStop; + + /// `skipFinalising` termine l'arrêt en cours (vrai comportement). + bool skipReleasesStop = true; + + @override + Future stopSession() { + final Duration? drain = drainOnStop; + if (drain != null) { + // L'état passe en finalisation juste après la demande d'arrêt. + scheduleMicrotask( + () => show(current.copyWith(finalisingRemaining: drain)), + ); + } + return super.stopSession(); + } + + @override + void skipFinalising() { + super.skipFinalising(); + if (!skipReleasesStop) return; + final Completer? gate = stopGate; + if (gate != null && !gate.isCompleted) { + gate.complete(); + } else if (gate == null && current.finalisingRemaining != null) { + // Finalisation lancée depuis la fenêtre : elle se termine. + scheduleMicrotask( + () => show( + current.copyWith( + finalisingRemaining: null, + isRecording: false, + isPaused: false, + ), + ), + ); + } + } +} + +/// Hôte qui lève une erreur en signalant un groupe donné ; le reste passe +/// au faux habituel. +final class FailingKillHost implements ProcessHost { + FailingKillHost(this._d); + + final FakeProcessHost _d; + + /// Groupe (= PID du meneur) dont le signal échoue. + int? failingGroup; + + @override + Future start( + String executable, + List arguments, { + Map? environment, + ProcessStartMode mode = ProcessStartMode.normal, + }) => _d.start(executable, arguments, environment: environment, mode: mode); + + @override + Future> running() => _d.running(); + + @override + bool kill(int pid, [ProcessSignal signal = ProcessSignal.sigterm]) { + if (pid == failingGroup) { + throw const ProcessException( + 'kill', + [], + 'Operation not permitted', + ); + } + return _d.kill(pid, signal); + } + + @override + bool killGroup(int groupId, [ProcessSignal signal = ProcessSignal.sigterm]) { + if (groupId == failingGroup) { + throw const ProcessException( + 'kill', + [], + 'Operation not permitted', + ); + } + return _d.killGroup(groupId, signal); + } + + @override + int get appGroupId => _d.appGroupId; + + @override + Future isPortFree(int port) => _d.isPortFree(port); + + @override + Future isHealthy(Uri url) => _d.isHealthy(url); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_snapshot_test.dart b/apps/app_macos/test/features/status_panel/status_panel_snapshot_test.dart new file mode 100644 index 00000000..8bd54f32 --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_snapshot_test.dart @@ -0,0 +1,627 @@ +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/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/calendar/calendar_event.dart'; +import 'package:ici_transcript/application/services/live_answers/live_question.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.state.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_snapshot.dart'; + +import '../../helpers/localized_app.dart'; + +// Panneau de barre de menus (T3) : ce que le panneau natif reçoit. +// +// Le panneau (NSStatusItem + NSPanel non activant, Swift) ne lit RIEN +// d'autre que le canal `com.icitranscript/status_panel`. Contrat : +// +// Dart → Swift +// - `update` {instantané} : état complet du panneau (voir ci-dessous) ; +// envoyé au lancement, à chaque changement (au plus ~4 par seconde +// pendant un flux de texte, le dernier état toujours envoyé), et en +// entier en réponse à `ready` ; +// - `showWindow` : montrer la fenêtre principale (au premier plan) ; +// - `terminate` : quitter l'app (après l'arrêt d'une note en cours) ; +// - `suggest` {`key`, `kind`, `title`, `detail`} (mêmes valeurs que +// `suggestion` ci-dessous, `key` = MeetingSuggestion.key) : une NOUVELLE +// suggestion à remarquer pendant un appel, le natif ouvre le panneau sans +// activer l'app ; une fois par clé, jamais pendant un enregistrement ou +// une dictée, fenêtre masquée comprise (status_panel_suggest_test.dart). +// +// Swift → Dart (clics du panneau, sans argument sauf mention) +// - `ready` : le panneau vient de s'ouvrir, renvoyer l'instantané entier ; +// - `start` : « Nouvelle note » (même chemin : `startOrShowNote`) ; +// - `stop` : arrêter la note ; `pauseResume` : pause ou reprise ; +// - `skipFinalising` : ne plus attendre la fin de la transcription ; +// - `acceptSuggestion` / `dismissSuggestion` : comme l'invite du shell ; +// - `answerNow` {questionId: String} : proposer une réponse à la question +// affichée (modèle local, à la demande) ; +// - `openWindow` : Dart répond par `showWindow` ; +// - `quit` (aussi ⌘Q et Dock › Quitter, routés par le natif) : Dart +// arrête la note en cours (sauvée ; la finalisation est passée, l'audio +// reste sur disque et le rattrapage reprend au lancement suivant), puis +// arrête les serveurs lancés par Oats (registre des processus), puis +// `terminate` ; idempotent, `terminate` part en 30 s au plus même si un +// arrêt reste bloqué (voir status_panel_quit_test.dart). +// +// Instantané (Map JSON, uniquement String, int, bool, null, List, Map) : +// - `status` : `idle` | `recording` | `paused` | `finalising` (après +// Arrêter, pendant que le reste de l'audio se transcrit) ; +// - `elapsedSeconds` : int, durée de la note (0 au repos) ; +// - `finalisingSeconds` : int, audio restant à transcrire, null hors +// finalisation ; +// - `title` : titre de la note en cours, null au repos ; +// - `transcript` : List des 3 dernières phrases FINIES, la plus ancienne +// d'abord, chacune {`speaker`: String affichable (« Vous », +// « Interlocuteur 2 », « Interlocuteur »), `source`: `input` | `output`, +// `text`: String} ; jamais un repère de perte ni de passage non +// transcrit, jamais la phrase en cours (`current_*`), jamais une dictée ; +// - `question` : la plus récente question détectée, ou null : +// {`id`: String, `text`: String, `state`: `detected` | `answering` | +// `answered` | `declined` | `failed` | `needsModel` (noms de +// LiveQuestionStatus ; `detected` = à demander, `declined` = pas de +// réponse utile, `needsModel` = aucun modèle prêt), `answer`: String, +// texte affiché sans repères `[S1]`, `truncated`: bool, `sources`: +// List titres des documents cités, dans l'ordre} ; +// - `suggestion` : la suggestion du shell, ou null : {`kind`: `calendar` | +// `call`, `title`: String (titre de l'événement ou « Appel détecté »), +// `detail`: String (« 10:00–10:30 » ou nom de l'app d'appel)} ; +// - `dictating` : bool, une dictée est en cours ; +// - `showStart` : bool, le bouton générique « Démarrer la note » est +// visible : vrai seulement au repos SANS suggestion (une suggestion +// affichée porte son propre « Démarrer la note » : un seul à l'écran). +// Les textes affichables arrivent déjà en français (fr.json) ; Swift +// n'a que ses propres libellés de boutons. +// +// API supposée (lib/features/status_panel/status_panel_snapshot.dart) : +// `Map statusPanelSnapshot({required LiveTranscriptionState +// live, required List questions, required MeetingSuggestion? +// suggestion, required bool dictating})`, fonction pure. +void main() { + // Traductions marquées ⟦…⟧ : un libellé vient de fr.json. + Future loadFrench(WidgetTester tester) => + pumpLocalized(tester, const SizedBox.shrink()); + + String fr(String key, [String? arg]) { + final String value = frValue(key)! as String; + return '$kOpen${arg == null ? value : value.replaceFirst('{}', arg)}$kClose'; + } + + int n = 0; + TranscriptSegmentEntity line( + String text, { + AudioSource source = AudioSource.output, + String? id, + int? atMs, + }) { + n++; + return TranscriptSegmentEntity( + id: id ?? 'note-1_${source.name}_$n', + sessionId: 'note-1', + source: source, + text: text, + timestampMs: atMs ?? n * 1000, + createdAt: DateTime(2026, 11, 23, 10), + ); + } + + LiveTranscriptionState recording({ + List segments = const [], + Map speakers = const {}, + }) => LiveTranscriptionState.initial().copyWith( + isRecording: true, + duration: const Duration(minutes: 1, seconds: 15), + sessionTitle: 'Revue de sprint', + segments: segments, + speakerLabels: speakers, + ); + + LiveQuestion question( + String id, { + String text = 'Quel est le délai de livraison prévu ?', + LiveQuestionStatus status = LiveQuestionStatus.detected, + String answer = '', + bool truncated = false, + List sources = const [], + bool onDemand = false, + }) => LiveQuestion( + id: id, + sessionId: 'note-1', + text: text, + timestampMs: 60000, + status: status, + answer: answer, + truncated: truncated, + sources: sources, + onDemand: onDemand, + ); + + Map snap({ + LiveTranscriptionState? live, + List questions = const [], + MeetingSuggestion? suggestion, + bool dictating = false, + }) => statusPanelSnapshot( + live: live ?? LiveTranscriptionState.initial(), + questions: questions, + suggestion: suggestion, + dictating: dictating, + ); + + List texts(Map s) => + (s['transcript']! as List) + .map((Object? l) => (l! as Map)['text']) + .toList(); + + group('état de la note', () { + test('au repos : toutes les clés du contrat, rien en cours', () { + expect(snap(), { + 'status': 'idle', + 'elapsedSeconds': 0, + 'finalisingSeconds': null, + 'title': null, + 'transcript': [], + 'question': null, + 'suggestion': null, + 'dictating': false, + 'showStart': true, + }); + }); + + test('une note enregistre : statut, durée en secondes, titre', () { + final Map s = snap(live: recording()); + + expect(s['status'], 'recording'); + expect(s['elapsedSeconds'], 75); + expect(s['title'], 'Revue de sprint'); + expect(s['finalisingSeconds'], isNull); + }); + + test('en pause', () { + final Map s = snap( + live: recording().copyWith(isPaused: true), + ); + + expect(s['status'], 'paused'); + expect(s['elapsedSeconds'], 75); + }); + + test('après Arrêter, pendant la transcription du reste : finalising, ' + 'même si l\'enregistrement n\'est pas encore marqué fini', () { + final Map s = snap( + live: recording().copyWith( + finalisingRemaining: const Duration(seconds: 12), + ), + ); + + expect(s['status'], 'finalising'); + expect(s['finalisingSeconds'], 12); + }); + + test('finalisation terminée (plus d\'audio restant) : retour au repos', () { + final Map s = snap( + live: LiveTranscriptionState.initial().copyWith( + finalisingRemaining: null, + ), + ); + + expect(s['status'], 'idle'); + expect(s['title'], isNull); + }); + + test('une dictée en cours est signalée', () { + expect(snap(dictating: true)['dictating'], isTrue); + expect(snap(live: recording(), dictating: true)['dictating'], isTrue); + }); + }); + + group('fin de la transcription', () { + testWidgets('les 3 dernières phrases finies, la plus ancienne d\'abord, ' + 'avec qui parle', (WidgetTester tester) async { + await loadFrench(tester); + final TranscriptSegmentEntity a = line('Bonjour à tous.'); + final TranscriptSegmentEntity b = line( + 'On commence par le budget.', + source: AudioSource.input, + ); + final TranscriptSegmentEntity c = line('Les chiffres sont prêts.'); + final TranscriptSegmentEntity d = line('Je partage mon écran.'); + + final Map s = snap( + live: recording( + segments: [a, b, c, d], + speakers: {c.id: 1}, + ), + ); + + expect(s['transcript'], [ + { + 'speaker': fr('transcription.live.speaker_me'), + 'source': 'input', + 'text': 'On commence par le budget.', + }, + { + 'speaker': fr('transcription.live.speaker_n', '2'), + 'source': 'output', + 'text': 'Les chiffres sont prêts.', + }, + { + 'speaker': fr('transcription.live.speaker_system'), + 'source': 'output', + 'text': 'Je partage mon écran.', + }, + ]); + }); + + test('moins de 3 phrases : seulement celles-là', () { + final Map s = snap( + live: recording(segments: [line('Bonjour.')]), + ); + + expect(texts(s), ['Bonjour.']); + }); + + test('jamais la phrase en cours : elle ne prend pas de place', () { + final Map s = snap( + live: recording( + segments: [ + line('Un.'), + line('Deux.'), + line('Trois.'), + line('Quatre.'), + line('et donc on va', id: 'current_output'), + line( + 'je pense que', + id: 'current_input', + source: AudioSource.input, + ), + ], + ), + ); + + expect(texts(s), ['Deux.', 'Trois.', 'Quatre.']); + }); + + test('jamais un repère de perte « Transcription interrompue… » : ' + 'il ne prend pas de place', () { + final Map s = snap( + live: recording( + segments: [ + line('Un.'), + line('Deux.'), + line('Trois.'), + line(LiveTranscriptionService.gapMarkerText(61000, 83000)), + ], + ), + ); + + expect(texts(s), ['Un.', 'Deux.', 'Trois.']); + }); + + test( + 'jamais le repère d\'un passage pas encore transcrit (provisoire)', + () { + final Map s = snap( + live: recording( + segments: [ + line('Un.'), + line('Deux.'), + line('Trois.'), + line( + LiveTranscriptionService.gapMarkerText(90000, 95000), + id: 'note-1_input_pending', + source: AudioSource.input, + ), + ], + ), + ); + + expect(texts(s), ['Un.', 'Deux.', 'Trois.']); + }, + ); + + test('rien que des repères : transcription vide', () { + final Map s = snap( + live: recording( + segments: [ + line(LiveTranscriptionService.gapMarkerText(0, 20000)), + ], + ), + ); + + expect(s['transcript'], isEmpty); + }); + + // Repères des deux sortes, au milieu des phrases : L1 L2 repère L3 donne + // L1 L2 L3 (le repère ne prend pas la place de L1). + final Map markers = { + 'perte « Transcription interrompue… »': + LiveTranscriptionService.gapMarkerText(61000, 83000), + 'passage non transcrit « Passage non transcrit (…) »': + LiveTranscriptionService.untranscribedMarkerText(61000, 83000), + }; + markers.forEach((String kind, String marker) { + test('repère de $kind entre deux phrases : jamais montré, ne prend pas ' + 'de place', () { + expect( + LiveTranscriptionService.isUntranscribedMarker(marker) || + marker.startsWith(LiveTranscriptionService.gapMarkerPrefix), + isTrue, + reason: 'repère tel que le service l\'écrit', + ); + final Map s = snap( + live: recording( + segments: [ + line('L1 bonjour.'), + line('L2 le budget.', source: AudioSource.input), + line(marker), + line('L3 la suite.'), + ], + ), + ); + + expect(texts(s), [ + 'L1 bonjour.', + 'L2 le budget.', + 'L3 la suite.', + ]); + }); + }); + + test('les deux sortes de repères ensemble : aucune ne s\'affiche', () { + final Map s = snap( + live: recording( + segments: [ + line('L1.'), + line(LiveTranscriptionService.untranscribedMarkerText(2000, 4000)), + line('L2.'), + line(LiveTranscriptionService.gapMarkerText(5000, 9000)), + line('L3.'), + line( + LiveTranscriptionService.untranscribedMarkerText(9000, 9500), + source: AudioSource.input, + ), + ], + ), + ); + + expect(texts(s), ['L1.', 'L2.', 'L3.']); + }); + }); + + group('question en direct', () { + test('aucune question détectée : null', () { + expect(snap(live: recording())['question'], isNull); + }); + + test('réponse en cours : état answering et texte partiel', () { + final Map s = snap( + live: recording(), + questions: [ + question( + 'q1', + status: LiveQuestionStatus.answering, + answer: 'La livraison est prévue', + ), + ], + ); + + expect(s['question'], { + 'id': 'q1', + 'text': 'Quel est le délai de livraison prévu ?', + 'state': 'answering', + 'answer': 'La livraison est prévue', + 'truncated': false, + 'sources': [], + }); + }); + + test('réponse reçue : le texte affiché par le direct, sans repères de ' + 'citation, et les titres des sources dans l\'ordre', () { + final Map s = snap( + live: recording(), + questions: [ + question( + 'q1', + status: LiveQuestionStatus.answered, + answer: + 'Livraison sous six semaines [S1].\n' + '- Pénalités au-delà de huit semaines [S2]', + truncated: true, + sources: const [ + AnswerSource( + documentId: 'd1', + title: 'Contrat cadre fictif', + excerpt: 'délai de six semaines', + ), + AnswerSource( + documentId: 'd2', + title: 'Annexe tarifaire', + excerpt: 'pénalités', + ), + ], + ), + ], + ); + + final Map q = s['question']! as Map; + expect(q['state'], 'answered'); + expect( + q['answer'], + 'Livraison sous six semaines.\n' + '- Pénalités au-delà de huit semaines', + ); + expect(q['answer'], isNot(contains('[S'))); + expect(q['truncated'], isTrue); + expect(q['sources'], [ + 'Contrat cadre fictif', + 'Annexe tarifaire', + ]); + }); + + for (final (LiveQuestionStatus status, String name) + in <(LiveQuestionStatus, String)>[ + (LiveQuestionStatus.declined, 'declined'), + (LiveQuestionStatus.needsModel, 'needsModel'), + (LiveQuestionStatus.failed, 'failed'), + ]) { + test('$name : état transmis, pas de réponse', () { + final Map s = snap( + live: recording(), + questions: [question('q1', status: status)], + ); + + final Map q = s['question']! as Map; + expect(q['state'], name); + expect(q['answer'], ''); + }); + } + + test('modèle local, réponse à demander : detected', () { + final Map s = snap( + live: recording(), + questions: [question('q1', onDemand: true)], + ); + + expect((s['question']! as Map)['state'], 'detected'); + }); + + test('plusieurs questions réglées : la plus récente', () { + final Map s = snap( + live: recording(), + questions: [ + question('q1', status: LiveQuestionStatus.answered, answer: 'Oui.'), + question( + 'q2', + text: 'Qui valide le budget ?', + status: LiveQuestionStatus.declined, + ), + ], + ); + + final Map q = s['question']! as Map; + expect(q['id'], 'q2'); + expect(q['text'], 'Qui valide le budget ?'); + }); + }); + + group('bouton générique « Démarrer la note »', () { + const MeetingSuggestion call = MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + ); + + test('au repos sans suggestion : visible', () { + expect(snap()['showStart'], isTrue); + }); + + test('une suggestion est affichée : masqué (un seul « Démarrer la ' + 'note »)', () { + expect(snap(suggestion: call)['showStart'], isFalse); + }); + + test('la suggestion disparaît : de nouveau visible', () { + expect(snap(suggestion: call)['showStart'], isFalse); + expect(snap()['showStart'], isTrue); + }); + + test('une note enregistre, en pause ou se finalise : masqué', () { + expect(snap(live: recording())['showStart'], isFalse); + expect( + snap(live: recording().copyWith(isPaused: true))['showStart'], + isFalse, + ); + expect( + snap( + live: LiveTranscriptionState.initial().copyWith( + finalisingRemaining: const Duration(seconds: 5), + ), + )['showStart'], + isFalse, + ); + }); + }); + + group('suggestion de réunion', () { + testWidgets('événement d\'agenda : titre et horaires', ( + WidgetTester tester, + ) async { + await loadFrench(tester); + final Map s = snap( + suggestion: MeetingSuggestion( + source: MeetingSource.calendar, + key: 'event:evt-1', + event: CalendarEvent( + id: 'evt-1', + title: 'Atelier roadmap', + start: DateTime(2026, 11, 23, 10), + end: DateTime(2026, 11, 23, 10, 30), + attendeeCount: 3, + ), + ), + ); + + expect(s['suggestion'], { + 'kind': 'calendar', + 'title': 'Atelier roadmap', + 'detail': '10:00–10:30', + }); + }); + + testWidgets('appel détecté : « Appel détecté » et le nom de l\'app', ( + WidgetTester tester, + ) async { + await loadFrench(tester); + final Map s = snap( + suggestion: const MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + bundleId: 'us.zoom.xos', + ), + ); + + expect(s['suggestion'], { + 'kind': 'call', + 'title': fr('meeting.suggestion.call_title'), + 'detail': 'Zoom', + }); + }); + }); + + test('l\'instantané passe par le canal et en JSON tel quel', () { + final Map s = snap( + live: recording( + segments: [line('Bonjour.')], + ).copyWith(finalisingRemaining: const Duration(seconds: 3)), + questions: [ + question( + 'q1', + status: LiveQuestionStatus.answered, + answer: 'Oui [S1].', + sources: const [ + AnswerSource(documentId: 'd1', title: 'Note', excerpt: 'oui'), + ], + ), + ], + suggestion: const MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + ), + dictating: true, + ); + + expect(jsonDecode(jsonEncode(s)), s); + const StandardMethodCodec codec = StandardMethodCodec(); + final MethodCall decoded = codec.decodeMethodCall( + codec.encodeMethodCall(MethodCall('update', s)), + ); + expect(decoded.arguments, s); + }); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_suggest_test.dart b/apps/app_macos/test/features/status_panel/status_panel_suggest_test.dart new file mode 100644 index 00000000..bb4476ef --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_suggest_test.dart @@ -0,0 +1,261 @@ +import 'package:core_domain/domain/entities/session.entity.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.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/calendar/calendar_event.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.dart'; +import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/features/calendar/meeting_suggestion.provider.dart'; +import 'package:ici_transcript/features/history/presentation/screens/list/session_list.view_model.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/status_panel/status_panel_sync.provider.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3) : une suggestion de réunion se remarque +// pendant un appel dans une autre app, sans ouvrir le panneau. Pour chaque +// NOUVELLE suggestion (clé `MeetingSuggestion.key`, jamais deux fois la +// même), Dart envoie UN appel `suggest` en plus de l'instantané ; le natif +// ouvre alors le panneau sans activer l'app. +// +// Contenu de `suggest` : {`key`: String, `kind`: `calendar` | `call`, +// `title`: String, `detail`: String} (mêmes `kind`/`title`/`detail` que la +// clé `suggestion` de l'instantané). +// Jamais pendant un enregistrement (pause et finalisation comprises) ni +// pendant une dictée ; jamais de nouveau après « Ignorer » tant que la clé +// est la même ; envoyé aussi quand la fenêtre principale est masquée. +void main() { + final TestWidgetsFlutterBinding binding = + TestWidgetsFlutterBinding.ensureInitialized(); + + late FakeStatusPanelPlatform panel; + late PanelLiveViewModel live; + late PanelSuggestionController suggestion; + late ProviderContainer c; + + final CalendarEvent atelier = CalendarEvent( + id: 'evt-atelier', + title: 'Atelier roadmap', + start: DateTime(2026, 11, 23, 10), + end: DateTime(2026, 11, 23, 10, 30), + attendeeCount: 3, + ); + final MeetingSuggestion calendar = MeetingSuggestion( + source: MeetingSource.calendar, + key: 'event:evt-atelier', + event: atelier, + ); + const MeetingSuggestion zoom = MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + bundleId: 'us.zoom.xos', + ); + + void mount(FakeAsync async) { + panel = FakeStatusPanelPlatform()..install(); + live = PanelLiveViewModel(); + suggestion = PanelSuggestionController(); + c = ProviderContainer( + overrides: [ + liveTranscriptionViewModelProvider.overrideWith(() => live), + meetingSuggestionControllerProvider.overrideWith(() => suggestion), + liveAnswersServiceProvider.overrideWithValue( + LiveAnswersHarness().service, + ), + sessionListViewModelProvider.overrideWith( + () => FakeSessionListViewModel(const []), + ), + ], + ); + c.listen(statusPanelSyncProvider, (_, _) {}); + async.elapse(const Duration(seconds: 1)); + } + + void dispose(FakeAsync async) { + c.dispose(); + async.flushMicrotasks(); + } + + void showSuggestion(FakeAsync async, MeetingSuggestion? s) { + suggestion.show(s); + async.elapse(const Duration(milliseconds: 500)); + } + + List suggests() => panel.callsTo('suggest'); + + final LiveTranscriptionState recording = LiveTranscriptionState.initial() + .copyWith(isRecording: true, sessionTitle: 'Revue de sprint'); + + test('événement d\'agenda : un appel `suggest` avec clé, titre et ' + 'horaires', () { + fakeAsync((FakeAsync async) { + mount(async); + + showSuggestion(async, calendar); + + expect(suggests(), hasLength(1)); + expect(suggests().single.arguments, { + 'key': 'event:evt-atelier', + 'kind': 'calendar', + 'title': 'Atelier roadmap', + 'detail': '10:00–10:30', + }); + expect( + (panel.last['suggestion'] as Map?)?['title'], + 'Atelier roadmap', + reason: 'l\'instantané porte aussi la suggestion', + ); + dispose(async); + }); + }); + + test('appel détecté : `suggest` avec le nom de l\'app', () { + fakeAsync((FakeAsync async) { + mount(async); + + showSuggestion(async, zoom); + + final Map args = + suggests().single.arguments as Map; + expect(args['key'], 'call:us.zoom.xos'); + expect(args['kind'], 'call'); + expect(args['detail'], 'Zoom'); + expect(args['title'], isA()); + expect(args['title'], isNotEmpty); + dispose(async); + }); + }); + + test('la même clé jamais deux fois (instantanés répétés, `ready`, ' + 'réapparition)', () { + fakeAsync((FakeAsync async) { + mount(async); + showSuggestion(async, zoom); + + panel.send('ready'); + async.elapse(const Duration(milliseconds: 500)); + showSuggestion(async, null); + showSuggestion(async, zoom); + + expect(suggests(), hasLength(1)); + dispose(async); + }); + }); + + test('une nouvelle clé : un nouvel appel', () { + fakeAsync((FakeAsync async) { + mount(async); + showSuggestion(async, zoom); + + showSuggestion(async, calendar); + + expect( + suggests().map((MethodCall m) => (m.arguments as Map)['key']), + ['call:us.zoom.xos', 'event:evt-atelier'], + ); + dispose(async); + }); + }); + + test('après « Ignorer » : rien tant que la clé est la même, une nouvelle ' + 'clé repart', () { + fakeAsync((FakeAsync async) { + mount(async); + showSuggestion(async, zoom); + + panel.send('dismissSuggestion'); + async.elapse(const Duration(milliseconds: 500)); + showSuggestion(async, zoom); + expect(suggests(), hasLength(1)); + + showSuggestion(async, calendar); + expect(suggests(), hasLength(2)); + dispose(async); + }); + }); + + for (final (String name, LiveTranscriptionState state) + in <(String, LiveTranscriptionState)>[ + ('un enregistrement', recording), + ('une pause', recording.copyWith(isPaused: true)), + ( + 'une finalisation', + LiveTranscriptionState.initial().copyWith( + finalisingRemaining: const Duration(seconds: 30), + ), + ), + ]) { + test('pendant $name : aucun `suggest`', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(state); + async.elapse(const Duration(milliseconds: 500)); + + showSuggestion(async, zoom); + + expect(suggests(), isEmpty); + dispose(async); + }); + }); + } + + test('pendant une dictée : aucun `suggest`', () { + fakeAsync((FakeAsync async) { + mount(async); + c.read(dictationActiveProvider.notifier).set(true); + async.elapse(const Duration(milliseconds: 500)); + + showSuggestion(async, zoom); + + expect(suggests(), isEmpty); + dispose(async); + }); + }); + + test('fenêtre principale masquée : `suggest` part quand même', () { + fakeAsync((FakeAsync async) { + addTearDown(() { + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + }); + mount(async); + binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + binding.handleAppLifecycleStateChanged(AppLifecycleState.hidden); + async.elapse(const Duration(milliseconds: 500)); + + showSuggestion(async, calendar); + + expect(suggests(), hasLength(1)); + dispose(async); + }); + }); + + test('canal en erreur pour `suggest` : rien ne remonte, l\'instantané ' + 'part quand même', () { + fakeAsync((FakeAsync async) { + mount(async); + panel.onCall = (MethodCall call) { + if (call.method == 'suggest') { + throw PlatformException(code: 'PANEL_UNAVAILABLE'); + } + }; + + showSuggestion(async, zoom); + + expect( + (panel.last['suggestion'] as Map?)?['detail'], + 'Zoom', + ); + dispose(async); + }); + }); +} diff --git a/apps/app_macos/test/features/status_panel/status_panel_sync_test.dart b/apps/app_macos/test/features/status_panel/status_panel_sync_test.dart new file mode 100644 index 00000000..6fa23395 --- /dev/null +++ b/apps/app_macos/test/features/status_panel/status_panel_sync_test.dart @@ -0,0 +1,616 @@ +import 'dart:async'; + +import 'package:core_domain/domain/entities/session.entity.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/calendar/calendar_event.dart'; +import 'package:ici_transcript/application/services/live_answers/live_question.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.dart'; +import 'package:ici_transcript/core/providers/services/dictation.provider.dart'; +import 'package:ici_transcript/core/providers/services/live_answers.service.provider.dart'; +import 'package:ici_transcript/features/calendar/meeting_suggestion.provider.dart'; +import 'package:ici_transcript/features/history/presentation/screens/list/session_list.view_model.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/shell/presentation/shell_view.provider.dart'; +import 'package:ici_transcript/features/status_panel/status_panel_sync.provider.dart'; + +import '../../helpers/fake_view_models.dart'; +import '../../helpers/live_answers_fakes.dart'; +import '../../helpers/status_panel_fakes.dart'; + +// Panneau de barre de menus (T3) : envoi de l'instantané et actions du +// panneau, sur le vrai canal `com.icitranscript/status_panel` (contrat : +// en-tête de status_panel_snapshot_test.dart), panneau natif factice. +// +// Faux : direct (PanelLiveViewModel, compte les actions), suggestion du +// shell (PanelSuggestionController, vrais start/dismiss), questions en +// direct (vrai LiveAnswersService, LLM joué par le test). Temps simulé. +// +// API supposée : `statusPanelSyncProvider` +// (lib/features/status_panel/status_panel_sync.provider.dart), gardé en +// vie ; l'écouter démarre l'envoi et la réception des actions. +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + late FakeStatusPanelPlatform panel; + late PanelLiveViewModel live; + late PanelSuggestionController suggestion; + late LiveAnswersHarness answers; + late ProviderContainer c; + + const String q = 'Est-ce que vous avez prévu une date de livraison ?'; + + final LiveTranscriptionState recordingState = LiveTranscriptionState.initial() + .copyWith( + isRecording: true, + duration: const Duration(minutes: 2), + sessionTitle: 'Revue de sprint', + ); + + /// Monte la synchro dans [async] ; [installPanel] = faux si le plugin + /// natif manque (vieux macOS, tests). + void mount( + FakeAsync async, { + bool installPanel = true, + bool localModel = false, + bool modelReady = true, + }) { + panel = FakeStatusPanelPlatform(); + if (installPanel) panel.install(); + live = PanelLiveViewModel(); + suggestion = PanelSuggestionController(); + answers = LiveAnswersHarness(isLocal: localModel, modelReady: modelReady); + c = ProviderContainer( + overrides: [ + liveTranscriptionViewModelProvider.overrideWith(() => live), + meetingSuggestionControllerProvider.overrideWith(() => suggestion), + liveAnswersServiceProvider.overrideWithValue(answers.service), + sessionListViewModelProvider.overrideWith( + () => FakeSessionListViewModel(const []), + ), + ], + ); + c.listen(statusPanelSyncProvider, (_, _) {}); + async.elapse(const Duration(seconds: 1)); + } + + void dispose(FakeAsync async) { + c.dispose(); + async.flushMicrotasks(); + } + + void fromPanel(FakeAsync async, String method, [Object? args]) { + panel.send(method, args); + async.elapse(const Duration(milliseconds: 500)); + } + + Map? questionOf(Map s) => + s['question'] as Map?; + + group('envoi de l\'instantané', () { + test('au lancement, l\'état courant part tout de suite', () { + fakeAsync((FakeAsync async) { + mount(async); + + expect(panel.updates, isNotEmpty); + expect(panel.last['status'], 'idle'); + dispose(async); + }); + }); + + test('un changement après un moment calme part sans attendre ' + '(moins de 300 ms)', () { + fakeAsync((FakeAsync async) { + mount(async); + async.elapse(const Duration(seconds: 2)); + + live.show(recordingState); + async.elapse(const Duration(milliseconds: 300)); + + expect(panel.last['status'], 'recording'); + expect(panel.last['title'], 'Revue de sprint'); + expect(panel.last['elapsedSeconds'], 120); + dispose(async); + }); + }); + + test('rien ne part quand l\'instantané ne change pas', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + async.elapse(const Duration(seconds: 1)); + final int before = panel.updates.length; + + // Champs que le panneau ne montre pas. + live.show( + recordingState.copyWith( + micPermission: 'authorized', + translations: {'x': 'y'}, + ), + ); + async.elapse(const Duration(seconds: 2)); + + expect(panel.updates.length, before); + dispose(async); + }); + }); + + test('pendant le flux d\'une réponse : environ 4 envois par seconde, ' + 'pas un par mot, et l\'état final part après la rafale', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + answers.hear(q); + async.elapse(const Duration(seconds: 1)); + expect(answers.llm.streams, hasLength(1)); + final int before = panel.updates.length; + + // 2 s de flux, un mot toutes les 50 ms (40 changements). + for (int i = 0; i < 40; i++) { + answers.llm.last.delta('mot$i '); + async.elapse(const Duration(milliseconds: 50)); + } + final int during = panel.updates.length - before; + + expect(during, inInclusiveRange(4, 10)); + expect(questionOf(panel.last)?['state'], 'answering'); + + answers.llm.last.delta('fin.'); + answers.llm.last.end(); + async.elapse(const Duration(seconds: 1)); + + expect(answers.only.status, LiveQuestionStatus.answered); + expect(questionOf(panel.last)?['state'], 'answered'); + expect(questionOf(panel.last)?['answer'], answers.only.answer); + dispose(async); + }); + }); + + test('« ready » (panneau ouvert après le lancement) : l\'instantané ' + 'entier repart, même inchangé', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + async.elapse(const Duration(seconds: 1)); + final int before = panel.updates.length; + final Map shown = panel.last; + + fromPanel(async, 'ready'); + + expect(panel.updates.length, before + 1); + expect(panel.last, shown); + dispose(async); + }); + }); + + test('la suggestion du shell apparaît puis disparaît dans le panneau', () { + fakeAsync((FakeAsync async) { + mount(async); + + suggestion.show( + const MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + ), + ); + async.elapse(const Duration(milliseconds: 500)); + expect( + (panel.last['suggestion'] as Map?)?['detail'], + 'Zoom', + ); + + suggestion.show(null); + async.elapse(const Duration(milliseconds: 500)); + expect(panel.last['suggestion'], isNull); + dispose(async); + }); + }); + + test('une dictée qui commence est signalée', () { + fakeAsync((FakeAsync async) { + mount(async); + + c.read(dictationActiveProvider.notifier).set(true); + async.elapse(const Duration(milliseconds: 500)); + + expect(panel.last['dictating'], isTrue); + dispose(async); + }); + }); + }); + + group('robustesse', () { + test('plugin natif absent : aucune erreur, le direct continue', () { + fakeAsync((FakeAsync async) { + mount(async, installPanel: false); + + live.show(recordingState); + async.elapse(const Duration(seconds: 2)); + live.show(recordingState.copyWith(isPaused: true)); + async.elapse(const Duration(seconds: 2)); + + expect(c.read(liveTranscriptionViewModelProvider).isPaused, isTrue); + dispose(async); + }); + }); + + test('le canal lève une erreur : aucune erreur remontée, les envois ' + 'suivants partent', () { + fakeAsync((FakeAsync async) { + mount(async); + panel.failUpdates = 2; + + live.show(recordingState); + async.elapse(const Duration(seconds: 1)); + live.show(recordingState.copyWith(isPaused: true)); + async.elapse(const Duration(seconds: 1)); + live.show(recordingState); + async.elapse(const Duration(seconds: 1)); + + expect(panel.failUpdates, 0, reason: 'les échecs ont bien eu lieu'); + expect(panel.last['status'], 'recording'); + dispose(async); + }); + }); + + test('action inconnue du panneau : ignorée sans erreur', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'doSomethingElse', {'x': 1}); + + expect(live.startCalls, 0); + dispose(async); + }); + }); + }); + + group('confidentialité', () { + test('aucun modèle configuré : construire et envoyer l\'instantané ne ' + 'déclenche aucune requête', () { + fakeAsync((FakeAsync async) { + mount(async, modelReady: false); + live.show(recordingState); + answers.hear(q); + async.elapse(const Duration(seconds: 1)); + final int resolves = answers.resolveCalls; + + live.show( + recordingState.copyWith(duration: const Duration(minutes: 3)), + ); + async.elapse(const Duration(seconds: 1)); + fromPanel(async, 'ready'); + async.elapse(const Duration(seconds: 1)); + + expect(questionOf(panel.last)?['state'], 'needsModel'); + expect(answers.resolveCalls, resolves); + expect(answers.llm.requests, isEmpty); + dispose(async); + }); + }); + + test('envoi coupé, modèle local : la question listée ne part nulle part ' + 'tant qu\'on ne la demande pas', () { + fakeAsync((FakeAsync async) { + mount(async, localModel: true); + live.show(recordingState); + answers.hear(q); + async.elapse(const Duration(seconds: 1)); + final int resolves = answers.resolveCalls; + + fromPanel(async, 'ready'); + live.show( + recordingState.copyWith(duration: const Duration(minutes: 3)), + ); + async.elapse(const Duration(seconds: 2)); + + expect(questionOf(panel.last)?['state'], 'detected'); + expect(answers.resolveCalls, resolves); + expect(answers.llm.requests, isEmpty); + dispose(async); + }); + }); + }); + + group('actions du panneau', () { + test('start : même chemin que « Nouvelle note » (le direct s\'affiche ' + 'dans le shell, une note démarre)', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'start'); + + expect(live.startCalls, 1); + expect(c.read(shellViewControllerProvider), ShellView.live); + expect(panel.last['status'], 'recording'); + dispose(async); + }); + }); + + test('start deux fois pendant que le démarrage est en vol : une seule ' + 'note', () { + fakeAsync((FakeAsync async) { + mount(async); + live.startGate = Completer(); + + panel.send('start'); + panel.send('start'); + async.elapse(const Duration(milliseconds: 500)); + live.startGate!.complete(); + async.elapse(const Duration(milliseconds: 500)); + fromPanel(async, 'start'); + + expect(live.startCalls, 1); + dispose(async); + }); + }); + + test('start en pause : pas de seconde note', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState.copyWith(isPaused: true)); + + fromPanel(async, 'start'); + + expect(live.startCalls, 0); + dispose(async); + }); + }); + + test('stop arrête la note en cours', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + + fromPanel(async, 'stop'); + + expect(live.stopCalls, 1); + expect(panel.last['status'], 'idle'); + dispose(async); + }); + }); + + test( + 'stop deux fois pendant l\'arrêt (vidange en cours) : un seul arrêt', + () { + fakeAsync((FakeAsync async) { + mount(async); + live.show(recordingState); + live.stopGate = Completer(); + + panel.send('stop'); + panel.send('stop'); + async.elapse(const Duration(milliseconds: 500)); + panel.send('stop'); + async.elapse(const Duration(milliseconds: 500)); + live.stopGate!.complete(); + async.elapse(const Duration(milliseconds: 500)); + + expect(live.stopCalls, 1); + dispose(async); + }); + }, + ); + + test('stop pendant « Finalisation… » : pas de second arrêt', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show( + recordingState.copyWith( + finalisingRemaining: const Duration(seconds: 20), + ), + ); + + fromPanel(async, 'stop'); + + expect(live.stopCalls, 0); + dispose(async); + }); + }); + + test('stop au repos : rien', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'stop'); + + expect(live.stopCalls, 0); + dispose(async); + }); + }); + + test('pauseResume : pause pendant l\'enregistrement, reprise en pause, ' + 'rien au repos', () { + fakeAsync((FakeAsync async) { + mount(async); + fromPanel(async, 'pauseResume'); + expect(live.pauseCalls + live.resumeCalls, 0); + + live.show(recordingState); + fromPanel(async, 'pauseResume'); + expect(live.pauseCalls, 1); + expect(panel.last['status'], 'paused'); + + fromPanel(async, 'pauseResume'); + expect(live.resumeCalls, 1); + expect(panel.last['status'], 'recording'); + dispose(async); + }); + }); + + test('skipFinalising pendant « Finalisation… »', () { + fakeAsync((FakeAsync async) { + mount(async); + live.show( + recordingState.copyWith( + finalisingRemaining: const Duration(seconds: 20), + ), + ); + + fromPanel(async, 'skipFinalising'); + + expect(live.skipCalls, 1); + dispose(async); + }); + }); + + final CalendarEvent atelier = CalendarEvent( + id: 'evt-atelier', + title: 'Atelier roadmap', + start: DateTime(2026, 11, 23, 10), + end: DateTime(2026, 11, 23, 11), + attendeeNames: const ['Personne A', 'Personne B'], + attendeeCount: 2, + ); + + test('acceptSuggestion : comme « Démarrer la note » du shell, la note ' + 'démarre liée à l\'événement affiché', () { + fakeAsync((FakeAsync async) { + mount(async); + suggestion.show( + MeetingSuggestion( + source: MeetingSource.calendar, + key: 'event:evt-atelier', + event: atelier, + ), + ); + async.elapse(const Duration(milliseconds: 500)); + + fromPanel(async, 'acceptSuggestion'); + fromPanel(async, 'acceptSuggestion'); + + expect(suggestion.startCalls, greaterThanOrEqualTo(1)); + expect(live.linked.map((CalendarEvent e) => e.id), [ + 'evt-atelier', + ]); + expect(live.startCalls, 1); + expect(panel.last['suggestion'], isNull); + dispose(async); + }); + }); + + test('acceptSuggestion sans suggestion (clic après sa disparition) : ' + 'aucune note ne démarre', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'acceptSuggestion'); + + expect(live.startCalls, 0); + dispose(async); + }); + }); + + test('dismissSuggestion : comme « Ignorer » du shell (sourdine)', () { + fakeAsync((FakeAsync async) { + mount(async); + suggestion.show( + const MeetingSuggestion( + source: MeetingSource.call, + key: 'call:us.zoom.xos', + appName: 'Zoom', + ), + ); + async.elapse(const Duration(milliseconds: 500)); + + fromPanel(async, 'dismissSuggestion'); + + expect(suggestion.dismissCalls, 1); + expect(c.read(meetingSuggestionControllerProvider), isNull); + expect(panel.last['suggestion'], isNull); + expect(live.startCalls, 0); + dispose(async); + }); + }); + + test('answerNow : la question affichée part au modèle local, une seule ' + 'fois même en double clic', () { + fakeAsync((FakeAsync async) { + mount(async, localModel: true); + live.show(recordingState); + answers.hear(q); + async.elapse(const Duration(seconds: 1)); + final String id = questionOf(panel.last)!['id']! as String; + expect(answers.llm.streams, isEmpty); + + panel.send('answerNow', {'questionId': id}); + panel.send('answerNow', {'questionId': id}); + async.elapse(const Duration(seconds: 1)); + + expect(answers.llm.streams, hasLength(1)); + expect(questionOf(panel.last)?['state'], 'answering'); + dispose(async); + }); + }); + + test('answerNow pour une question qui n\'existe plus : rien ne part', () { + fakeAsync((FakeAsync async) { + mount(async, localModel: true); + live.show(recordingState); + answers.hear(q); + async.elapse(const Duration(seconds: 1)); + + fromPanel(async, 'answerNow', { + 'questionId': 'q-gone', + }); + + expect(answers.llm.streams, isEmpty); + dispose(async); + }); + }); + + test('openWindow : Dart demande au natif de montrer la fenêtre', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'openWindow'); + + expect(panel.callsTo('showWindow'), hasLength(1)); + dispose(async); + }); + }); + + test('quit au repos : l\'app se termine', () { + fakeAsync((FakeAsync async) { + mount(async); + + fromPanel(async, 'quit'); + + expect(panel.callsTo('terminate'), hasLength(1)); + expect(live.stopCalls, 0); + dispose(async); + }); + }); + + test('quit pendant un enregistrement : la note s\'arrête et se sauve ' + 'd\'abord, puis l\'app se termine', () { + fakeAsync((FakeAsync async) { + mount(async); + final List log = []; + panel.log = log; + live.log = log; + live.show(recordingState); + live.stopGate = Completer(); + + panel.send('quit'); + async.elapse(const Duration(seconds: 1)); + expect(panel.callsTo('terminate'), isEmpty, reason: 'arrêt en cours'); + + live.stopGate!.complete(); + async.elapse(const Duration(seconds: 1)); + + expect(live.stopCalls, 1); + expect(log.where((String l) => l != 'panel.update').toList(), [ + 'live.stop', + 'live.stopped', + 'panel.terminate', + ]); + dispose(async); + }); + }); + }); +} diff --git a/apps/app_macos/test/helpers/status_panel_fakes.dart b/apps/app_macos/test/helpers/status_panel_fakes.dart new file mode 100644 index 00000000..aa2910f9 --- /dev/null +++ b/apps/app_macos/test/helpers/status_panel_fakes.dart @@ -0,0 +1,168 @@ +import 'dart:async'; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/calendar/calendar_event.dart'; +import 'package:ici_transcript/application/services/meeting/meeting_rules.dart'; +import 'package:ici_transcript/features/calendar/meeting_suggestion.provider.dart'; +import 'package:ici_transcript/features/live_transcription/presentation/screens/live/live_transcription.state.dart'; + +import 'fake_view_models.dart'; + +// Faux côté Swift du panneau de barre de menus (T3). Contrat du canal +// `com.icitranscript/status_panel` : voir l'en-tête de +// test/features/status_panel/status_panel_snapshot_test.dart. + +const String kStatusPanelChannel = 'com.icitranscript/status_panel'; + +TestDefaultBinaryMessenger get _messenger => + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + +/// Panneau natif factice derrière `com.icitranscript/status_panel`. +class FakeStatusPanelPlatform { + /// Tous les appels Dart → Swift, dans l'ordre. + final List calls = []; + + /// Journal partageable avec d'autres faux (ordre entre eux). + List log = []; + + /// Si non nul, chaque `update` lève cette erreur (puis le compteur + /// [failUpdates] décroît ; 0 = de nouveau normal). + int failUpdates = 0; + + /// Appelé à chaque appel Dart → Swift (ex. noter l'état au `terminate`). + void Function(MethodCall call)? onCall; + + /// Instantanés reçus par `update`, dans l'ordre. + List> get updates => calls + .where((MethodCall c) => c.method == 'update') + .map((MethodCall c) => c.arguments as Map) + .toList(); + + /// Dernier instantané reçu. + Map get last => updates.last; + + List callsTo(String method) => + calls.where((MethodCall c) => c.method == method).toList(); + + void install() { + _messenger.setMockMethodCallHandler( + const MethodChannel(kStatusPanelChannel), + (MethodCall call) async { + calls.add(call); + log.add('panel.${call.method}'); + onCall?.call(call); + if (call.method == 'update' && failUpdates > 0) { + failUpdates--; + throw PlatformException(code: 'PANEL_UNAVAILABLE'); + } + return null; + }, + ); + addTearDown( + () => _messenger.setMockMethodCallHandler( + const MethodChannel(kStatusPanelChannel), + null, + ), + ); + } + + /// Le panneau natif envoie [method] (clic, ouverture, `ready`). + Future send(String method, [Object? args]) => + _messenger.handlePlatformMessage( + kStatusPanelChannel, + const StandardMethodCodec().encodeMethodCall(MethodCall(method, args)), + (ByteData? _) {}, + ); +} + +/// Contrôleur de suggestion sans détection ni agenda : le test fixe la +/// suggestion affichée ; « Démarrer » et « Ignorer » restent les vrais +/// (`start()` → `startOrShowNote` avec l'événement, `dismiss()` → sourdine). +class PanelSuggestionController extends MeetingSuggestionController { + int startCalls = 0; + int dismissCalls = 0; + + @override + MeetingSuggestion? build() => null; + + /// Fixe la suggestion affichée par le shell. + void show(MeetingSuggestion? s) => state = s; + + @override + Future start() { + startCalls++; + return super.start(); + } + + @override + void dismiss() { + dismissCalls++; + super.dismiss(); + } +} + +/// Direct sans serveur : compte chaque action ; démarrage et arrêt peuvent +/// rester « en vol » (portes [startGate] / [stopGate]) pour tester un double +/// clic. +class PanelLiveViewModel extends FakeLiveTranscriptionViewModel { + int stopCalls = 0; + int pauseCalls = 0; + int resumeCalls = 0; + int skipCalls = 0; + final List linked = []; + + /// Journal partageable (ordre arrêt / fin de l'app). + List log = []; + + /// Si non nul, `startSession` attend ce futur avant de démarrer. + Completer? startGate; + + /// Si non nul, `stopSession` attend ce futur (vidange) avant de remettre + /// l'état au repos. + Completer? stopGate; + + LiveTranscriptionState get current => state; + + @override + void linkNextNoteTo(CalendarEvent event) => linked.add(event); + + /// Comme le vrai : l'état ne passe à « enregistre » qu'après une attente + /// (post-traitement de la note précédente), ici [startGate]. + @override + Future startSession() async { + await startGate?.future; + await super.startSession(); + log.add('live.start'); + } + + @override + Future stopSession() async { + stopCalls++; + log.add('live.stop'); + await stopGate?.future; + state = state.copyWith( + isRecording: false, + isPaused: false, + finalisingRemaining: null, + duration: Duration.zero, + ); + log.add('live.stopped'); + return 'note-1'; + } + + @override + Future pauseSession() async { + pauseCalls++; + state = state.copyWith(isPaused: true); + } + + @override + Future resumeSession() async { + resumeCalls++; + state = state.copyWith(isPaused: false); + } + + @override + void skipFinalising() => skipCalls++; +}