diff --git a/apps/app_macos/lib/application/services/gap_backfill.service.dart b/apps/app_macos/lib/application/services/gap_backfill.service.dart index 5d17e6d..a92fbe4 100644 --- a/apps/app_macos/lib/application/services/gap_backfill.service.dart +++ b/apps/app_macos/lib/application/services/gap_backfill.service.dart @@ -90,17 +90,80 @@ final class GapBackfillService { /// (jusqu'au segment intact suivant, 30 s au plus). Les autres sources, /// les segments hors fenêtre et les passages non transcrits ne sont /// jamais touchés. + /// + /// Les repères rangés d'une source qui se recoupent ou se touchent (un + /// repère provisoire et un final après un arrêt brutal, sonde 7) forment + /// une union : un seul intervalle, sous le premier repère ; les autres + /// repères de l'union sont dans [BackfillGap.replacedIds] et partent quand + /// l'union est retrouvée. static List plan( List segments, { List dictated = const [], }) => [ - for (final TranscriptSegmentEntity s in segments) - if (_isGapMarker(s)) - if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) - if (!_insideDictation(s, m, dictated)) - ..._planMarker(s, _ms(m, 4), segments, dictated), + for (final _MarkerUnion u in _unions(segments, dictated)) + for (final BackfillGap g in _planMarker( + u.first, + u.end, + segments, + dictated, + endLimit: u.nextStart, + )) + ( + markerId: g.markerId, + source: g.source, + startMs: g.startMs, + endMs: g.endMs, + replacedIds: [...g.replacedIds, ...u.others], + ), ]; + /// Unions des repères de perte d'une même source (début, fin), hors + /// dictée, triées par début. + static List<_MarkerUnion> _unions( + List segments, + List dictated, + ) { + final List<({TranscriptSegmentEntity marker, int end})> markers = + <({TranscriptSegmentEntity marker, int end})>[ + for (final TranscriptSegmentEntity s in segments) + if (_isGapMarker(s)) + if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) + if (!_insideDictation(s, m, dictated)) + (marker: s, end: _ms(m, 4)), + ]..sort( + ( + ({TranscriptSegmentEntity marker, int end}) a, + ({TranscriptSegmentEntity marker, int end}) b, + ) => a.marker.timestampMs.compareTo(b.marker.timestampMs), + ); + final List<_MarkerUnion> unions = <_MarkerUnion>[]; + for (final ({TranscriptSegmentEntity marker, int end}) m in markers) { + _MarkerUnion? open; + for (final _MarkerUnion u in unions.reversed) { + if (u.first.source == m.marker.source && + m.marker.timestampMs <= u.end) { + open = u; + break; + } + } + if (open == null) { + unions.add(_MarkerUnion(m.marker, m.end)); + } else { + open.others.add(m.marker.id); + if (m.end > open.end) open.end = m.end; + } + } + for (int i = 0; i < unions.length; i++) { + for (int j = i + 1; j < unions.length; j++) { + if (unions[j].first.source == unions[i].first.source) { + unions[i].nextStart = unions[j].first.timestampMs; + break; + } + } + } + return unions; + } + /// Un segment qui commence à moins de [edgeTolerance] d'un bord de la /// perte appartient à la phrase coupée (le texte arrive ~1 s après /// l'audio ; sonde 5 : au plus 1,2 s après le début, 1 s avant la fin). @@ -119,8 +182,9 @@ final class GapBackfillService { TranscriptSegmentEntity marker, int lostEnd, List segments, - List dictated, - ) { + List dictated, { + int? endLimit, + }) { final int tolerance = edgeTolerance.inMilliseconds; final List live = segments @@ -156,6 +220,11 @@ final class GapBackfillService { : last + _afterReplacedSpan.inMilliseconds; if (cover > end) end = cover; } + // Le prolongement s'arrête où commence l'union suivante de la source : + // son audio est retranscrit par elle (jamais deux fois). + if (endLimit != null && end > endLimit) { + end = endLimit > lostEnd ? endLimit : lostEnd; + } if (start < 0) start = 0; final List ids = [ for (final TranscriptSegmentEntity x in replaced) x.id, @@ -322,9 +391,14 @@ final class GapBackfillService { // (gap_backfill_overlap_test) : on la garde et on retire le doublon. // Tout ce qui commence avant la fin reste remplacé, quel que soit son // texte (sonde 5). - final int? lostEnd = _markerTimes.firstMatch(marker.text) == null - ? null - : _ms(_markerTimes.firstMatch(marker.text)!, 4); + // Fin de l'union : celle du plus tardif de ses repères. + final int? lostEnd = [ + for (final TranscriptSegmentEntity s in segments) + if ((s.id == marker.id || gap.replacedIds.contains(s.id)) && + _isGapMarker(s)) + if (_markerTimes.firstMatch(s.text) case final RegExpMatch m) + _ms(m, 4), + ].fold(null, (int? a, int b) => a == null || b > a ? b : a); final TranscriptSegmentEntity? edge = lostEnd == null ? null : (segments @@ -524,3 +598,16 @@ final class GapBackfillService { /// Issue d'un morceau de repère. enum _Part { noAudio, unavailable, failed, nothingNew, saved } + +/// Union de repères de perte d'une source : le premier (par début), la fin +/// la plus tardive, et les autres repères qu'elle absorbe. +class _MarkerUnion { + _MarkerUnion(this.first, this.end); + + final TranscriptSegmentEntity first; + int end; + + /// Début de l'union suivante de la même source, s'il y en a une. + int? nextStart; + final List others = []; +} diff --git a/apps/app_macos/lib/application/services/live_transcription.service.dart b/apps/app_macos/lib/application/services/live_transcription.service.dart index 375dc3e..b0cdb4e 100644 --- a/apps/app_macos/lib/application/services/live_transcription.service.dart +++ b/apps/app_macos/lib/application/services/live_transcription.service.dart @@ -409,6 +409,7 @@ final class LiveTranscriptionService { _log.info('Audio subscription active, en attente de chunks...'); _running = true; _lossOfPhrase.clear(); + _gapMarkers.clear(); _lastSealed.clear(); _provisionalTimer = Timer.periodic( const Duration(seconds: 1), @@ -864,20 +865,115 @@ final class LiveTranscriptionService { when startMs < sealed.timestampMs) { _savePartial(sealed.copyWith(timestampMs: startMs)); } + _writeGapMarker( + session, + gap.source, + startMs, + _offsetOf(session, gap.endMs), + ); + } + + // Repères de perte écrits dans cette session, par source, dans l'ordre : + // (id, début, fin) en heures de réunion. + final Map> _gapMarkers = + >{}; + + /// Seul endroit qui écrit un repère de perte. Les repères d'une source ne + /// se chevauchent jamais (sonde 7 : trois repères emboîtés) : une perte + /// qui touche ou recoupe des repères de la même source les fusionne en un + /// seul, l'union, sous l'id du premier ; les autres sont retirés. + void _writeGapMarker( + SessionEntity session, + AudioSource source, + int start, + int end, + ) { + final List<({String id, int start, int end})> markers = _gapMarkers + .putIfAbsent(source, () => <({String id, int start, int end})>[]); + final List<({String id, int start, int end})> touched = markers + .where( + (({String id, int start, int end}) m) => + m.start <= end && start <= m.end, + ) + .toList(); + int from = start; + int to = end; + for (final ({String id, int start, int end}) m in touched) { + if (m.start < from) from = m.start; + if (m.end > to) to = m.end; + } + final String id = touched.isEmpty + ? _newSegmentId(session, source) + : touched.first.id; + final List absorbed = [ + for (final ({String id, int start, int end}) m in touched.skip(1)) m.id, + ]; + markers + ..removeWhere(touched.contains) + ..add((id: id, start: from, end: to)); final TranscriptSegmentEntity marker = TranscriptSegmentEntity( - id: _newSegmentId(session, gap.source), + id: id, sessionId: session.id, - source: gap.source, - text: gapMarkerText(startMs, _offsetOf(session, gap.endMs)), - timestampMs: startMs, + source: source, + text: gapMarkerText(from, to), + timestampMs: from, createdAt: clock.now(), ); - _log.warning('Audio non transcrit: ${marker.text} (${gap.source.name})'); + _log.warning('Audio non transcrit: ${marker.text} (${source.name})'); + // Atomique pour l'utilisateur : l'union est rangée d'abord (réessayée si + // l'écriture échoue), les repères absorbés ne partent qu'ensuite ; aucun + // intervalle ne reste sans repère. + final List> absorbedWrites = >[ + for (final String other in absorbed) ?_segmentWrites[other], + ]; + _chainWrite(id, () async { + await Future.wait(absorbedWrites); + if (!await _saveWithRetry(marker)) return; + _sortAndDedupeSegments(); + for (final String other in absorbed) { + await _transcriptionService.discardProvisional(other); + _transcriptionService.segmentsStream.add( + List.from( + _transcriptionService.segmentsStream.value, + )..removeWhere((TranscriptSegmentEntity x) => x.id == other), + ); + } + }); + } + + // Un repère qui ne se range pas est réessayé : 1, 2, 4, 8 s. + // ponytail: 5 essais (15 s, Stop attend au pire autant) puis abandon + // journalisé ; file durable si un disque plein doit tenir plus longtemps. + static const int _markerWriteAttempts = 5; + + Future _saveWithRetry(TranscriptSegmentEntity segment) async { + for (int attempt = 0; attempt < _markerWriteAttempts; attempt++) { + if (attempt > 0) { + await Future.delayed(Duration(seconds: 1 << (attempt - 1))); + } + if (await _transcriptionService.saveSegment(segment)) return true; + } + _log.error('Repère non rangé après $_markerWriteAttempts essais'); + return false; + } + + // Écritures chaînées par id de segment : la dernière valeur voulue est + // toujours écrite en dernier (revue : un re-rangement non chaîné pouvait + // être écrasé par la première écriture, plus lente). + final Map> _segmentWrites = >{}; + + void _chainWrite(String id, Future Function() write) { late final Future task; - task = _transcriptionService - .saveSegment(marker) - .then((_) => _sortAndDedupeSegments()) - .whenComplete(() => _pendingFinalizations.remove(task)); + // Une écriture ratée plus tôt pour cet id n'empêche pas la suivante. + task = (_segmentWrites[id] ?? Future.value()) + .catchError((Object e) => _log.error('Écriture de $id ratée', e)) + .then((_) => write()) + .catchError((Object e) => _log.error('Écriture de $id ratée', e)) + .whenComplete(() { + _pendingFinalizations.remove(task); + if (identical(_segmentWrites[id], task)) _segmentWrites.remove(id); + }); + _segmentWrites[id] = task; _pendingFinalizations.add(task); } @@ -1144,12 +1240,11 @@ final class LiveTranscriptionService { {}; void _savePartial(TranscriptSegmentEntity segment, {Future? after}) { - late final Future task; - task = (after ?? Future.value()) - .then((_) => _transcriptionService.saveSegment(segment)) - .then((_) => _sortAndDedupeSegments()) - .whenComplete(() => _pendingFinalizations.remove(task)); - _pendingFinalizations.add(task); + _chainWrite(segment.id, () async { + await after; + await _transcriptionService.saveSegment(segment); + _sortAndDedupeSegments(); + }); } static final RegExp _wordChar = RegExp(r'[\p{L}\p{N}]', unicode: true); diff --git a/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart b/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart new file mode 100644 index 0000000..590ae0f --- /dev/null +++ b/apps/app_macos/test/application/services/gap_backfill_overlapping_markers_test.dart @@ -0,0 +1,140 @@ +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; +import 'package:ici_transcript/application/services/wav_recorder.dart'; + +import '../../fixtures/probe7_overlap.dart'; +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 1 : le repère provisoire (mis à jour chaque seconde, +// id `__pending`) s'écrit sans passer par la fusion, et +// `GapBackfillService.plan` croit ce qui est rangé. Après un arrêt brutal +// pendant une coupure, des repères qui se chevauchent peuvent donc être sur +// le disque. Le rattrapage doit s'en sortir seul. +// +// État rangé de la sonde 7 (Dlag sans rattrapage, son système) : 1:51–2:35 +// contient 1:58–2:04 et 2:12–2:14 ; plus un repère provisoire 2:40–3:10 +// qui recoupe le repère final 2:45–4:59. +// +// Attendu : un intervalle par union, chaque phrase une seule fois, dans +// l'ordre, aucun repère de l'union laissé, les segments dans l'union +// remplacés une fois (`replacedIds`). +void main() { + const String sessionId = probe7SessionId; + final TranscriptSegmentEntity provisional = TranscriptSegmentEntity( + id: '${sessionId}_output_pending', + sessionId: sessionId, + source: AudioSource.output, + text: LiveTranscriptionService.gapMarkerText(160000, 190000), + timestampMs: 160000, + createdAt: DateTime(2026, 11, 24), + ); + + List stored() => [ + for (final Probe7Segment s in probe7SystemStored) + TranscriptSegmentEntity( + id: s.id, + sessionId: sessionId, + source: AudioSource.output, + text: s.text, + timestampMs: s.timestampMs, + createdAt: DateTime(2026, 11, 24), + ), + provisional, + ]; + + bool isMarker(TranscriptSegmentEntity s) => + s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix); + + test('le plan donne un intervalle par union, et remplace une fois les ' + 'segments de l union', () { + final plan = + GapBackfillService.plan( + stored(), + ).where((p) => p.source == AudioSource.output).toList() + ..sort((a, b) => a.startMs.compareTo(b.startMs)); + + expect(plan, hasLength(3), reason: '0:18–1:15, 1:51–2:35, 2:40–4:59'); + final int margin = GapBackfillService.margin.inMilliseconds; + expect(plan[1].startMs, lessThanOrEqualTo(111630 - margin)); + expect(plan[2].startMs, lessThanOrEqualTo(160000 - margin)); + final List replaced = [ + for (final p in plan) ...p.replacedIds, + ]; + expect(replaced.toSet(), hasLength(replaced.length), reason: 'une fois'); + expect(replaced, contains('${sessionId}_output_18')); + }); + + test('après le rattrapage : chaque phrase une fois, dans l ordre, plus ' + 'aucun repère de ces unions', () async { + final Directory dir = await Directory.systemTemp.createTemp( + 'oats_overlapping_markers_', + ); + addTearDown(() => dir.delete(recursive: true)); + final WavRecorder recorder = WavRecorder(); + await recorder.open('${dir.path}/${sessionId}_system.wav'); + for (int c = 0; c < 3200; c++) { + final Uint8List chunk = Uint8List(3200); + final ByteData d = ByteData.sublistView(chunk); + for (int o = 0; o < 3200; o += 2) { + d.setInt16(o, c * 4 + 2, Endian.little); + } + await recorder.append(chunk); + } + await recorder.close(); + final InMemoryTranscriptRepository repo = InMemoryTranscriptRepository(); + for (final TranscriptSegmentEntity s in stored()) { + await repo.save(s); + } + + await GapBackfillService( + transcriber: _Recorded(), + transcripts: repo, + isRecording: () => false, + ).backfill(sessionId, recordingsDirectory: dir.path); + + final List lines = repo.of(AudioSource.output) + ..sort((a, b) => a.timestampMs.compareTo(b.timestampMs)); + expect( + lines.where( + (TranscriptSegmentEntity s) => isMarker(s) && s.timestampMs >= 100000, + ), + isEmpty, + reason: 'repères des deux unions retirés', + ); + int last = -1; + for (final ({int atMs, String text}) p in probe7SystemRecovered.where( + (({int atMs, String text}) p) => p.atMs >= 100000, + )) { + final String clause = p.text.split(',').first; + final List at = [ + for (int i = 0; i < lines.length; i++) + if (lines[i].text.contains(clause)) i, + ]; + expect(at, hasLength(1), reason: '« $clause » une seule fois'); + expect(at.single, greaterThan(last), reason: '« $clause » dans l ordre'); + last = at.single; + } + }); +} + +/// Texte du rattrapage enregistré, choisi par l'heure du PCM demandé (chaque +/// échantillon d'un pas de 100 ms vaut numéro × 4 + piste). +final class _Recorded implements PcmTranscriber { + @override + Future> transcribe(Uint8List pcm) async { + final int v = ByteData.sublistView(pcm).getInt16(0, Endian.little); + final int startMs = (v ~/ 4) * 100; + final int endMs = startMs + pcm.length ~/ 32; + return <({int offsetMs, String text})>[ + for (final ({int atMs, String text}) p in probe7SystemRecovered) + if (p.atMs >= startMs - 1500 && p.atMs < endMs) + (offsetMs: p.atMs - startMs, text: p.text), + ]; + } +} diff --git a/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart b/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart new file mode 100644 index 0000000..aab18cd --- /dev/null +++ b/apps/app_macos/test/application/services/gap_marker_merge_atomic_test.dart @@ -0,0 +1,138 @@ +import 'dart:async'; + +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 3 : la fusion des repères n'est pas atomique (les +// retraits des repères englobés et l'écriture de l'union passent par des +// chaînes différentes ; une écriture ratée plus tôt pour le même id fait +// sauter l'union). Attendu, avec un dépôt qui échoue une fois : +// - l'union est quand même rangée, aucun intervalle ne reste sans repère ; +// - l'écriture suivante d'un id passe même si la précédente a échoué ; +// - les repères englobés ne sont retirés qu'une fois l'union rangée. +// +// Pertes : A 1:00–1:10, B 1:30–1:40, puis C 1:05–1:35 qui touche les deux : +// union 1:00–1:40. +void main() { + final RegExp union = RegExp(r'00:01:00\s*[–-]\s*00:01:40'); + + List markers(InMemoryTranscriptRepository repo) => + repo + .of(AudioSource.output) + .where( + (TranscriptSegmentEntity s) => + s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + + void gaps(LiveServiceHarness h, FakeAsync async, {bool third = true}) { + for (final (int, int) g in <(int, int)>[ + (60000, 70000), + (90000, 100000), + if (third) (65000, 95000), + ]) { + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.output, + startMs: h.t0 + g.$1, + endMs: h.t0 + g.$2, + ), + ); + async.elapse(const Duration(milliseconds: 200)); + } + } + + test('la première écriture du repère échoue : l union est quand même ' + 'rangée sous un seul repère', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + failOnce: (TranscriptSegmentEntity s) => s.text.contains('00:01:10'), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 5)); + + expect(repo.failures, 1, reason: 'le dépôt a bien échoué une fois'); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); + + test('l écriture de l union échoue une fois : elle est rangée quand même, ' + 'aucun intervalle sans repère', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + failOnce: (TranscriptSegmentEntity s) => union.hasMatch(s.text), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 30)); + + expect(repo.failures, 1); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); + + test('les repères englobés restent tant que l union n est pas rangée', () { + fakeAsync((FakeAsync async) { + final _FlakyRepository repo = _FlakyRepository( + hold: (TranscriptSegmentEntity s) => union.hasMatch(s.text), + ); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 120)); + gaps(h, async); + async.elapse(const Duration(seconds: 5)); + + // L'union attend : 1:30–1:40 doit toujours avoir son repère. + expect( + markers( + repo, + ).where((TranscriptSegmentEntity s) => s.text.contains('00:01:30')), + hasLength(1), + reason: 'retiré avant que l union soit rangée', + ); + + repo.release(); + async.elapse(const Duration(seconds: 5)); + expect(markers(repo), hasLength(1)); + expect(markers(repo).single.text, matches(union)); + }); + }); +} + +/// Dépôt qui échoue une fois sur la première écriture qui vérifie +/// [failOnce], ou retient les écritures qui vérifient [hold]. +class _FlakyRepository extends InMemoryTranscriptRepository { + _FlakyRepository({this.failOnce, this.hold}); + + final bool Function(TranscriptSegmentEntity s)? failOnce; + final bool Function(TranscriptSegmentEntity s)? hold; + int failures = 0; + final Completer _gate = Completer(); + + void release() { + if (!_gate.isCompleted) _gate.complete(); + } + + @override + Future save(TranscriptSegmentEntity segment) async { + if (failures == 0 && (failOnce?.call(segment) ?? false)) { + failures++; + throw Exception('disque plein'); + } + if (hold?.call(segment) ?? false) await _gate.future; + return super.save(segment); + } +} diff --git a/apps/app_macos/test/application/services/gap_marker_merge_test.dart b/apps/app_macos/test/application/services/gap_marker_merge_test.dart new file mode 100644 index 0000000..935070b --- /dev/null +++ b/apps/app_macos/test/application/services/gap_marker_merge_test.dart @@ -0,0 +1,110 @@ +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Tour 9, point 2 (sonde 7, scénario Dlag sans rattrapage, son système) : +// trois pertes déclarées au même instant (348,56 s), dans cet ordre : +// 1:58–2:04, 2:12–2:14, puis 1:51–2:35 qui contient les deux autres. Trois +// repères se chevauchaient dans la note. +// +// Attendu : les repères d'une source ne se chevauchent jamais. Une perte +// dans un repère encore ouvert, ou qui le touche, l'étend : un seul repère, +// l'union des intervalles ; le rattrapage planifie cette union une fois. +void main() { + List markers(LiveServiceHarness h, AudioSource s) => + h.segments + .of(s) + .where( + (TranscriptSegmentEntity x) => + x.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + + void gap(LiveServiceHarness h, int startMs, int endMs) => + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.output, + startMs: h.t0 + startMs, + endMs: h.t0 + endMs, + ), + ); + + test('séquence enregistrée : un seul repère 00:01:51 – 00:02:35, planifié ' + 'une fois', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 348)); + gap(h, 118530, 124000); // 00:01:58 – 00:02:04 + gap(h, 132830, 134000); // 00:02:12 – 00:02:14 + gap(h, 111630, 155000); // 00:01:51 – 00:02:35 + async.elapse(const Duration(seconds: 1)); + + final TranscriptSegmentEntity marker = markers( + h, + AudioSource.output, + ).single; + expect(marker.timestampMs, 111630); + expect(marker.text, matches(RegExp(r'00:01:51\s*[–-]\s*00:02:35'))); + + final plan = GapBackfillService.plan(h.segments.store.values.toList()); + expect(plan.where((p) => p.source == AudioSource.output), hasLength(1)); + + // Revue PR #25, point 4 : l'écran aussi ne liste qu'un repère. + final List listed = h + .transcription + .segmentsStream + .value + .where( + (TranscriptSegmentEntity x) => + x.source == AudioSource.output && + x.text.startsWith(LiveTranscriptionService.gapMarkerPrefix), + ) + .toList(); + expect(listed, hasLength(1), reason: 'un seul repère à l écran'); + expect(listed.single.text, marker.text); + }); + }); + + test('une perte qui touche un repère ouvert l étend ; une perte à part ' + 'garde son propre repère', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 200)); + gap(h, 60000, 70000); + gap(h, 70000, 80000); // touche la fin du premier + gap(h, 150000, 160000); // à part + async.elapse(const Duration(seconds: 1)); + + final List found = markers(h, AudioSource.output) + ..sort((a, b) => a.timestampMs.compareTo(b.timestampMs)); + expect(found, hasLength(2)); + expect(found[0].text, matches(RegExp(r'00:01:00\s*[–-]\s*00:01:20'))); + expect(found[1].text, matches(RegExp(r'00:02:30\s*[–-]\s*00:02:40'))); + }); + }); + + test('les repères de deux sources différentes ne fusionnent pas', () { + fakeAsync((FakeAsync async) { + final LiveServiceHarness h = LiveServiceHarness(async)..start(); + async.elapse(const Duration(seconds: 200)); + gap(h, 60000, 70000); + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.input, + startMs: h.t0 + 65000, + endMs: h.t0 + 75000, + ), + ); + async.elapse(const Duration(seconds: 1)); + + expect(markers(h, AudioSource.output), hasLength(1)); + expect(markers(h, AudioSource.input), hasLength(1)); + }); + }); +} diff --git a/apps/app_macos/test/application/services/provisional_marker_merge_test.dart b/apps/app_macos/test/application/services/provisional_marker_merge_test.dart new file mode 100644 index 0000000..156e40d --- /dev/null +++ b/apps/app_macos/test/application/services/provisional_marker_merge_test.dart @@ -0,0 +1,141 @@ +import 'package:core_data/datasources/remote/impl/transcription.remote.data_source.impl.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ici_transcript/application/services/gap_backfill.service.dart'; +import 'package:ici_transcript/application/services/live_transcription.service.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Revue PR #25, point 2, en séance (vraie source distante, sockets +// factices) : le repère provisoire de la coupure en cours et le repère +// final d'une perte de la même source qui se touchent ne laissent jamais +// deux repères ; un repère provisoire retiré (coupure finie sans perte) ne +// fusionne pas avec une perte PLUS TARDIVE (sinon de l'audio transcrit +// serait déclaré perdu). +void main() { + late FakeAsync clock; + late FakeVoxSocket mic; + late LiveServiceHarness h; + + void setUpIn(FakeAsync async) { + clock = async; + final FakeVoxServer server = FakeVoxServer(); + mic = FakeVoxSocket(server); + h = LiveServiceHarness( + async, + remote: TranscriptionRemoteDataSourceImpl( + micClient: mic, + systemClient: FakeVoxSocket(server), + ), + )..start(outputEnabled: false); + } + + int id = 0; + + /// Parole continue du micro, [seconds] s, en 100 ms. + void speak(int seconds, {void Function()? eachSecond}) { + for (int i = 0; i < seconds * 10; i++, id++) { + h.audio.emit(chunk(AudioSource.input, id, timestampMs: h.t0 + id * 100)); + clock.elapse(const Duration(milliseconds: 100)); + if (i % 10 == 9) eachSecond?.call(); + } + } + + List<(int, int)> markerIntervals() { + final List<(int, int)> out = <(int, int)>[]; + for (final TranscriptSegmentEntity s in h.segments.of(AudioSource.input)) { + if (!s.text.startsWith(LiveTranscriptionService.gapMarkerPrefix)) { + continue; + } + final ({String markerId, AudioSource source, int startMs, int endMs})? p = + GapBackfillService.plan([s]) + .map( + (g) => ( + markerId: g.markerId, + source: g.source, + startMs: g.startMs, + endMs: g.endMs, + ), + ) + .firstOrNull; + if (p != null) out.add((p.startMs, p.endMs)); + } + return out; + } + + bool overlapOrTouch(List<(int, int)> xs) { + // Les intervalles du plan sont élargis de la marge des deux côtés. + final int slack = 2 * GapBackfillService.margin.inMilliseconds; + for (int i = 0; i < xs.length; i++) { + for (int j = i + 1; j < xs.length; j++) { + if (xs[i].$1 <= xs[j].$2 - slack && xs[j].$1 <= xs[i].$2 - slack) { + return true; + } + } + } + return false; + } + + test('coupure plus longue que le tampon : le repère provisoire et le ' + 'repère final ne coexistent jamais en se recoupant', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + speak(10); + mic + ..refusing = true + ..drop(); + final List seen = []; + void check() { + final List<(int, int)> xs = markerIntervals(); + if (overlapOrTouch(xs)) seen.add('${async.elapsed}: $xs'); + } + + speak(150, eachSecond: check); // le tampon déborde + mic.refusing = false; + speak(60, eachSecond: check); // reconnexion, renvoi, perte déclarée + + expect(seen, isEmpty, reason: 'repères qui se recoupent : $seen'); + expect(markerIntervals(), hasLength(1)); + }); + }); + + test('un repère provisoire retiré ne fusionne pas avec une perte plus ' + 'tardive', () { + fakeAsync((FakeAsync async) { + setUpIn(async); + speak(10); + mic + ..refusing = true + ..drop(); + speak(5); // courte coupure : repère provisoire + mic.refusing = false; + speak(30); // tout est livré : le provisoire est retiré + expect(markerIntervals(), isEmpty, reason: 'rien n a été perdu'); + + final int lateOutageMs = id * 100; + mic + ..refusing = true + ..drop(); + speak(150); + mic.refusing = false; + speak(60); + + final List<(int, int)> xs = markerIntervals(); + expect(xs, hasLength(1)); + // La perte peut commencer avant la seconde coupure (la phrase en vol, + // sans réponse, est perdue avec elle : 30 s au plus), jamais à la + // première, toute livrée. + expect( + xs.single.$1 + GapBackfillService.margin.inMilliseconds, + greaterThanOrEqualTo(lateOutageMs - 31000), + reason: 'la perte ne remonte pas à la première coupure', + ); + expect( + xs.single.$1 + GapBackfillService.margin.inMilliseconds, + greaterThan(45000), + ); + }); + }); +} diff --git a/apps/app_macos/test/application/services/restamp_write_order_test.dart b/apps/app_macos/test/application/services/restamp_write_order_test.dart new file mode 100644 index 0000000..3b977a6 --- /dev/null +++ b/apps/app_macos/test/application/services/restamp_write_order_test.dart @@ -0,0 +1,85 @@ +import 'dart:async'; + +import 'package:core_data/datasources/remote/transcription.remote.data_source.dart'; +import 'package:core_data/model/audio_gap.dart'; +import 'package:core_domain/domain/entities/transcript_segment.entity.dart'; +import 'package:core_domain/domain/enum/audio_source.enum.dart'; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../helpers/live_service_fakes.dart'; + +// Tour 9, point 3 (revue de `_onAudioGap`) : une phrase scellée est rangée, +// puis re-rangée à l'heure du début de la perte ; la seconde écriture n'est +// pas chaînée après la première. Si la première (heure d'arrivée) se +// termine après, elle écrase la bonne heure. +// +// Dépôt lent : chaque écriture attend qu'on la libère ; on les libère dans +// l'ordre inverse. Le segment rangé doit finir à l'heure du début de la +// perte, jamais à l'heure d'arrivée, quel que soit l'ordre de fin. +void main() { + for (final bool lastFirst in [true, false]) { + test('la phrase scellée finit à l heure de la perte (écritures libérées ' + '${lastFirst ? 'de la dernière à la première' : 'dans l ordre'})', () { + fakeAsync((FakeAsync async) { + final _SlowRepository repo = _SlowRepository(); + final LiveServiceHarness h = LiveServiceHarness(async, segments: repo) + ..start(); + async.elapse(const Duration(seconds: 306)); + h.fakeRemote.emitDelta( + AudioSource.input, + 'La boulangère a nettoyé le kiosque à journaux malgré le vent ' + 'froid, puis la', + ); + async.elapse(const Duration(seconds: 3)); // provisoire : en attente + h.fakeRemote.emitControl(AudioSource.input, utteranceLostEventType); + async.elapse(const Duration(milliseconds: 100)); // scellée : en attente + h.fakeRemote.emitGap( + AudioGap( + source: AudioSource.input, + startMs: h.t0 + 148048, + endMs: h.t0 + 165000, + ), + ); + async.elapse(const Duration(milliseconds: 100)); + + repo.releaseAll(lastFirst: lastFirst); + async.elapse(const Duration(seconds: 1)); + repo.releaseAll(lastFirst: lastFirst); // écritures chaînées ensuite + async.elapse(const Duration(seconds: 1)); + repo.releaseAll(lastFirst: lastFirst); + async.elapse(const Duration(seconds: 1)); + + final TranscriptSegmentEntity sealed = repo.store.values.singleWhere( + (TranscriptSegmentEntity s) => s.text.startsWith('La boulangère'), + ); + expect( + sealed.timestampMs, + 148048, + reason: 'heure du début de la perte', + ); + }); + }); + } +} + +/// Dépôt dont chaque écriture attend d'être libérée. +class _SlowRepository extends InMemoryTranscriptRepository { + final List> _held = >[]; + + @override + Future save(TranscriptSegmentEntity segment) async { + final Completer gate = Completer(); + _held.add(gate); + await gate.future; + return super.save(segment); + } + + void releaseAll({required bool lastFirst}) { + final List> now = List>.of(_held); + _held.clear(); + for (final Completer c in lastFirst ? now.reversed : now) { + c.complete(); + } + } +} diff --git a/apps/app_macos/test/fixtures/probe7_overlap.dart b/apps/app_macos/test/fixtures/probe7_overlap.dart new file mode 100644 index 0000000..a7d6932 --- /dev/null +++ b/apps/app_macos/test/fixtures/probe7_overlap.dart @@ -0,0 +1,236 @@ +// GÉNÉRÉ depuis la sonde 7 (scratchpad/probe/live7) : état rangé en fin de +// scénario Dlag SANS rattrapage (svc_Dlag_nobf.jsonl), son système, et +// texte rendu par le rattrapage du même audio dans le scénario Dlag +// (svc_Dlag.jsonl). Copié tel quel. + +typedef Probe7Segment = ({String id, int timestampMs, String text}); + +const String probe7SessionId = '1795396098594'; + +/// Segments système rangés (repères compris) à la fin de Dlag sans +/// rattrapage : 1:51–2:35 contient 1:58–2:04 et 2:12–2:14. +const List probe7SystemStored = [ + ( + id: '1795396098594_output_1', + timestampMs: 30, + text: + 'The baker cleaned the old greenhouse without telling anyone, and then the librarian cleaned the bus shelter with a lot of patience.', + ), + ( + id: '1795396098594_output_3', + timestampMs: 9030, + text: + 'Le libraire a rangé la fontaine ronde malgré le vent froid, puis la gardienne a réparé la vieille barrière pour la rentrée des classes.', + ), + (id: '1795396098594_output_5', timestampMs: 18730, text: 'The'), + ( + id: '1795396098594_output_7', + timestampMs: 18730, + text: 'Transcription interrompue : 00:00:18 – 00:01:15', + ), + ( + id: '1795396098594_output_11', + timestampMs: 74330, + text: + 'Graph the green bench despite the cold wind, and then the postman cleaned the green bench despite the cold wind.', + ), + ( + id: '1795396098594_output_12', + timestampMs: 83730, + text: + 'Le libraire a décoré le kiosque à journaux malgré le vent froid, puis la gardienne a nettoyé le portail pour la rentrée des classes.', + ), + ( + id: '1795396098594_output_14', + timestampMs: 92830, + text: + 'The librarian painted the old greenhouse for the start of school, and then the baker measured the round fountain before the evening rain.', + ), + ( + id: '1795396098594_output_16', + timestampMs: 101930, + text: + 'La voisine a nettoyé le kiosque à journaux avant la pluie du soir, puis le maire a mesuré le portail avec beaucoup de patience.', + ), + ( + id: '1795396098594_output_22', + timestampMs: 111630, + text: 'Transcription interrompue : 00:01:51 – 00:02:35', + ), + ( + id: '1795396098594_output_18', + timestampMs: 118530, + text: + 'The mayor painted the stone wall during the village fair, and then the gardener moved the bus shelter before the evening', + ), + ( + id: '1795396098594_output_20', + timestampMs: 118530, + text: 'Transcription interrompue : 00:01:58 – 00:02:04', + ), + ( + id: '1795396098594_output_21', + timestampMs: 132830, + text: 'Transcription interrompue : 00:02:12 – 00:02:14', + ), + ( + id: '1795396098594_output_26', + timestampMs: 156930, + text: + 'La gardienne a déplacé la vieille barrière avant la pluie de soir, puis la gardienne a nettoyé le kiosque à journaux sous un ciel gris.', + ), + ( + id: '1795396098594_output_27', + timestampMs: 165830, + text: 'The teacher cleaned', + ), + ( + id: '1795396098594_output_29', + timestampMs: 165830, + text: 'Transcription interrompue : 00:02:45 – 00:04:59', + ), +]; + +/// Texte rendu par le rattrapage du même audio (Dlag), heures de réunion. +const List<({int atMs, String text})> +probe7SystemRecovered = <({int atMs, String text})>[ + ( + atMs: 17714, + text: + 'The librarian tidied the small cabin with a lot of patience, and then the postman painted the old greenhouse with a lot of patience.', + ), + ( + atMs: 27314, + text: + 'La boulangère a décoré le portail sans prévenir personne, puis le jardinier a mesuré le banc vert avant la pluie du soir.', + ), + ( + atMs: 36114, + text: + 'The librarian photographed the garden gate despite the cold wind, and then the baker moved the green bench for the start of school.', + ), + ( + atMs: 45514, + text: + 'Le facteur a mesuré la fontaine ronde malgré le vent froid, puis le facteur a photographié le lavoir pendant la fête du village.', + ), + ( + atMs: 54114, + text: + 'The mayor measured the round fountain without telling anyone, and then the gardener photographed the old greenhouse without telling anyone.', + ), + ( + atMs: 63414, + text: + 'Lo veo a fotob vacío y el kiosque a journaux por la rentrée des classes, puis la boulangère a repeint la cabane avant la pluie du soir.', + ), + ( + atMs: 72614, + text: + 'The baker photographed the green bench despite the cold wind, and then the postman cleaned the green bench despite the cold wind.', + ), + ( + atMs: 110614, + text: + 'The mayor painted the stone wall during the village fair, and then the gardener moved the bus shelter before the evening rain.', + ), + ( + atMs: 119214, + text: + 'Le libraire a nettoyé le kiosque à journaux avec beaucoup de patience, puis la voisine a nettoyé le kiosque à journaux au lever du soleil.', + ), + ( + atMs: 128014, + text: + 'The librarian decorated the old greenhouse with a lot of patience, and then the teacher painted the round fountain with a lot of patience.', + ), + ( + atMs: 137714, + text: + 'La boulangère a décoré la cabane pendant la fête du village, puis le libraire a rangé la fontaine ronde avec beaucoup de patience.', + ), + ( + atMs: 146514, + text: + 'The baker painted the old greenhouse at sunrise, and then the librarian painted the small cabin with a lot of patience.', + ), + ( + atMs: 155814, + text: + 'La gardienne a déplacé la vieille barrière avant la pluie du soir, puis la gardienne a nettoyé le kiosque à journaux sous un ciel gris.', + ), + ( + atMs: 164814, + text: + 'The teacher cleaned the round fountain without telling anyone, and then the postman repaired the round fountain despite the cold wind.', + ), + ( + atMs: 173714, + text: + 'La boulangère a basuré la cabane malgré le vent froid, puis le libraire a basuré la cabane avec beaucoup de patience.', + ), + ( + atMs: 182414, + text: + 'The librarian repaired the wooden fence with a lot of patience, and then my neighbor photographed the stone wall at sunrise.', + ), + ( + atMs: 192514, + text: + 'La musicienne a rangé le kiosque à journaux sous un ciel gris, puis la boulangère a repeint le portail pendant la fête du village.', + ), + ( + atMs: 201814, + text: + 'The painter moved the small cabin without telling anyone, and then the gardener painted the round fountain for the start of school.', + ), + ( + atMs: 211114, + text: + 'La musicienne a basuré la cabane sous un ciel gris, puis le libraire a réparé la fontaine ronde pendant la fête du village.', + ), + ( + atMs: 219614, + text: + 'The Gognatided the Green Bench before the evening rain, and then the librarian repaired the old greenhouse without telling anyone.', + ), + ( + atMs: 229814, + text: + 'L\'omère a basuré le kiosque à journaux pour la rentrée des classes, puis le facteur a déplacé la cabane malgré le vent froid.', + ), + ( + atMs: 239114, + text: + 'The teacher painted the bus shelter before the evening rain, and then the postman painted the old greenhouse without telling anyone.', + ), + ( + atMs: 249114, + text: + 'Le libraire a repeint le kiosque à journaux pour la rentrée des classes, puis le jardinier a déplacé la serre sans prévenir personne.', + ), + ( + atMs: 258114, + text: + 'The librarian photographed the green bench despite the cold wind, and then the postman repaired the bus shelter under a grey sky.', + ), + ( + atMs: 267914, + text: + 'La gardienne allait soigner le lavoir avant la pluie du soir, puis le libraire a photographié la cabane sans prévenir personne.', + ), + ( + atMs: 277014, + text: + 'The painter measured the small cabin without telling anyone, and then the mayor measured the garden gate without telling anyone.', + ), + ( + atMs: 286214, + text: + 'Le jardinier a réparé la vieille barrière sous un ciel gris, puis le libraire a rangé la vieille barrière au lever du soleil.', + ), + ( + atMs: 294814, + text: 'The painter repaired the small cabin during the village fair, and', + ), +]; diff --git a/apps/app_macos/test/helpers/live_service_fakes.dart b/apps/app_macos/test/helpers/live_service_fakes.dart index 31e8ef0..967c171 100644 --- a/apps/app_macos/test/helpers/live_service_fakes.dart +++ b/apps/app_macos/test/helpers/live_service_fakes.dart @@ -319,7 +319,7 @@ final class InMemorySessionRepository implements SessionRepository { /// Dépôt en mémoire au contrat du port : `save` remplace un segment de même /// id (en gardant sa place), `deleteById` le retire. -final class InMemoryTranscriptRepository implements TranscriptRepository { +class InMemoryTranscriptRepository implements TranscriptRepository { final Map store = {}; @@ -384,14 +384,18 @@ final class FakeWavRecorder extends WavRecorder { /// Monte le vrai [LiveTranscriptionService] sur les faux ci-dessus. final class LiveServiceHarness { - LiveServiceHarness(this.async, {TranscriptionRemoteDataSource? remote}) - : process = FakeProcessManagerChannel(now: () => async.elapsed), - remote = remote ?? FakeTranscriptionRemoteDataSource() { + LiveServiceHarness( + this.async, { + TranscriptionRemoteDataSource? remote, + InMemoryTranscriptRepository? segments, + }) : process = FakeProcessManagerChannel(now: () => async.elapsed), + remote = remote ?? FakeTranscriptionRemoteDataSource(), + segments = segments ?? InMemoryTranscriptRepository() { transcription = TranscriptionService( startSessionUseCase: StartSessionUseCase(sessionRepository: sessions), stopSessionUseCase: StopSessionUseCase(sessionRepository: sessions), saveTranscriptSegmentUseCase: SaveTranscriptSegmentUseCase( - transcriptRepository: segments, + transcriptRepository: this.segments, ), ); service = LiveTranscriptionService( @@ -412,7 +416,7 @@ final class LiveServiceHarness { final FakeAudioCaptureChannel audio = FakeAudioCaptureChannel(); final TranscriptionRemoteDataSource remote; final InMemorySessionRepository sessions = InMemorySessionRepository(); - final InMemoryTranscriptRepository segments = InMemoryTranscriptRepository(); + final InMemoryTranscriptRepository segments; final List recorders = []; late final TranscriptionService transcription; late final LiveTranscriptionService service; diff --git a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart index e24d4dc..1043fd2 100644 --- a/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart +++ b/packages/core_data/lib/datasources/remote/impl/transcription.remote.data_source.impl.dart @@ -150,6 +150,9 @@ final class TranscriptionRemoteDataSourceImpl _systemConnected = systemAudioEnabled; _clearOutages(); _resetUtteranceState(); + // Une nouvelle séance repart de la borne de 10 s : l'app vit des jours + // dans la barre des menus, un serveur lent d'hier ne compte plus. + _learnedSlowAccepts.updateAll((_, _) => 0); if (_closedSubscriptions.isEmpty) { _closedSubscriptions ..add(_mic.onClosed.listen((_) => _onSocketClosed(AudioSource.input))) @@ -335,12 +338,22 @@ final class TranscriptionRemoteDataSourceImpl _unacked[source]! ..sentEvictionsLost() ..resetSent(); - final _Outage outage = _Outage(); + // La borne qui a réussi la dernière fois pour cette source : un serveur + // lent l'est encore (sonde 7 : repartir de 10 s coûtait une tentative + // ratée par coupure). + final _Outage outage = _Outage() + ..slowAccepts = _learnedSlowAccepts[source]!; _outages[source] = outage; _connectionStateSubject.add(domain.ConnectionState.connecting); _scheduleReconnect(source, outage); } + // Par source : nombre de doublements de la borne qui a réussi en dernier. + final Map _learnedSlowAccepts = { + AudioSource.input: 0, + AudioSource.output: 0, + }; + Duration _handshakeBound(int slowAccepts) { final Duration bound = WebSocketClient.connectTimeout * (1 << math.min(slowAccepts, 3)); @@ -361,6 +374,12 @@ final class TranscriptionRemoteDataSourceImpl final WebSocketClient client = _client(source); final Duration bound = _handshakeBound(outage.slowAccepts); client.handshakeTimeout = bound; + // Vrai si l'accueil prend plus que la première borne (10 s). + bool slowAccept = false; + final Timer slowMark = Timer( + WebSocketClient.connectTimeout, + () => slowAccept = true, + ); try { // Une seule tentative à la fois : la suivante ne part qu'une fois // celle-ci finie ou expirée. Une poignée de main sans fin est @@ -368,6 +387,7 @@ final class TranscriptionRemoteDataSourceImpl // ne jamais rendre la main). await client.connect(_url).timeout(bound); } on TimeoutException { + slowMark.cancel(); // Accueil lent, pas refus : on réessaie tout de suite, plus patient, // sans ajouter d'attente à celle déjà subie. if (identical(_outages[source], outage)) { @@ -376,11 +396,16 @@ final class TranscriptionRemoteDataSourceImpl } return; } catch (_) { + slowMark.cancel(); if (identical(_outages[source], outage)) { _scheduleReconnect(source, outage); } return; } + slowMark.cancel(); + // Retenir ce qui a marché : la borne de cette tentative si l'accueil a + // été lent, la première (10 s) sinon. + _learnedSlowAccepts[source] = slowAccept ? outage.slowAccepts : 0; // Session close ou relancée pendant la connexion. if (!identical(_outages[source], outage)) return; diff --git a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart index a4e2987..68b7668 100644 --- a/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart +++ b/packages/core_data/test/datasources/transcription_remote_data_source_slow_accept_test.dart @@ -124,8 +124,11 @@ void main() { }); // Revue PR #21 (commit 1250d05) : une seule poignée de main à la fois. + // Tour 9 (sonde 7 : coupures de 22,5 / 25,5 / 55,5 s pour des accueils de + // 12 / 15 / 25 s) : la nouvelle coupure ne repart plus à 10 s, elle part + // de la borne qui a réussi la dernière fois. test('une tentative à la fois ; à expiration le canal est fermé et jamais ' - 'réutilisé ; une nouvelle coupure repart à 10 s', () { + 'réutilisé ; la coupure suivante part de la borne qui a réussi', () { fakeAsync((FakeAsync async) { final DataSourceBench b = DataSourceBench(async); b.mic.acceptDelay = const Duration(seconds: 15); @@ -159,10 +162,11 @@ void main() { async.elapse(const Duration(seconds: 30)); expect(b.mic.connections, hasLength(2), reason: 'reconnecté'); - // Nouvelle coupure : la borne repart à 10 s. + // Nouvelle coupure, même serveur lent (15 s) : la première tentative + // attend la borne qui a réussi (20 s) ; la coupure ≈ l'accueil. final Duration secondDrop = async.elapsed; b.mic.drop(); - for (int id = 1000; id < 1150; id++) { + for (int id = 1000; id < 1250; id++) { b.tick( id, voiced: {AudioSource.input: id % 50 < 40}, @@ -171,16 +175,97 @@ void main() { final List again = b.mic.connectAttempts .where((Duration t) => t >= secondDrop) .toList(); - expect(again.length, greaterThanOrEqualTo(2)); + expect(again, hasLength(1), reason: 'une seule tentative suffit'); + expect(b.mic.connections, hasLength(3), reason: 'reconnecté'); expect( - again[1] - again[0], + b.mic.connectionOpenedAt.last - secondDrop, + lessThanOrEqualTo(const Duration(milliseconds: 16500)), + reason: 'coupure ≈ délai d accueil (15 s)', + ); + }); + }); + + test('après un accueil rapide, la borne revient à 10 s', () { + fakeAsync((FakeAsync async) { + final DataSourceBench b = DataSourceBench(async); + async.elapse(const Duration(seconds: 1)); + int id = 0; + void outage(Duration accept, int seconds) { + b.mic + ..acceptDelay = accept + ..drop(); + for (int i = 0; i < seconds * 10; i++, id++) { + b.tick( + id, + voiced: {AudioSource.input: id % 50 < 40}, + ); + } + } + + outage(const Duration(seconds: 15), 40); // apprend 20 s + outage(const Duration(seconds: 2), 10); // accueil rapide + final Duration thirdDrop = async.elapsed; + outage(const Duration(seconds: 15), 40); + + final List attempts = b.mic.connectAttempts + .where((Duration t) => t >= thirdDrop) + .toList(); + expect(attempts.length, greaterThanOrEqualTo(2)); + expect( + attempts[1] - attempts[0], + greaterThanOrEqualTo(const Duration(seconds: 10)), + ); + expect( + attempts[1] - attempts[0], lessThanOrEqualTo(const Duration(milliseconds: 11500)), - reason: 'première borne de la nouvelle coupure : 10 s', + reason: 'borne revenue à 10 s', ); + }); + }); + + // Revue PR #25, point 5 : l'app vit des jours dans la barre de menus ; la + // borne apprise ne doit pas survivre à la séance. Une nouvelle note + // (connexion de début de séance) repart à 10 s. + test('une nouvelle séance repart à 10 s, quoi que la précédente ait ' + 'appris', () { + fakeAsync((FakeAsync async) { + final DataSourceBench b = DataSourceBench(async); + async.elapse(const Duration(seconds: 1)); + int id = 0; + void outage(int seconds) { + b.mic + ..acceptDelay = const Duration(seconds: 15) + ..drop(); + for (int i = 0; i < seconds * 10; i++, id++) { + b.tick( + id, + voiced: {AudioSource.input: id % 50 < 40}, + ); + } + } + + outage(40); // apprend 20 s + b.dataSource.disconnect(); // fin de la note + async.elapse(const Duration(hours: 6)); + b.mic.acceptDelay = Duration.zero; + b.dataSource.connect(systemAudioEnabled: false); // nouvelle note + async.elapse(const Duration(seconds: 1)); + + final Duration drop = async.elapsed; + outage(40); + final List attempts = b.mic.connectAttempts + .where((Duration t) => t >= drop) + .toList(); + expect(attempts.length, greaterThanOrEqualTo(2)); expect( - again[1] - again[0], + attempts[1] - attempts[0], greaterThanOrEqualTo(const Duration(seconds: 10)), ); + expect( + attempts[1] - attempts[0], + lessThanOrEqualTo(const Duration(milliseconds: 11500)), + reason: 'borne de départ de la séance : 10 s', + ); }); }); } diff --git a/packages/core_data/test/helpers/fake_websocket_client.dart b/packages/core_data/test/helpers/fake_websocket_client.dart index 349bb74..c64f048 100644 --- a/packages/core_data/test/helpers/fake_websocket_client.dart +++ b/packages/core_data/test/helpers/fake_websocket_client.dart @@ -37,6 +37,9 @@ final class FakeWebSocketClient extends WebSocketClient { /// Numéros reçus, connexion par connexion. final List> connections = >[]; + /// Heure (horloge du test) de chaque connexion établie. + final List connectionOpenedAt = []; + /// Messages reçus, connexion par connexion. final List> connectionMessages = >[]; @@ -115,6 +118,8 @@ final class FakeWebSocketClient extends WebSocketClient { throw const SocketException('Connection refused'); } _connected = true; + final Duration? openedAt = now?.call(); + if (openedAt != null) connectionOpenedAt.add(openedAt); _generation++; _pendingUtterances.clear(); _currentUtterance = []; diff --git a/packages/core_domain/lib/domain/services/transcription.service.dart b/packages/core_domain/lib/domain/services/transcription.service.dart index d3c1c10..cbdfafe 100644 --- a/packages/core_domain/lib/domain/services/transcription.service.dart +++ b/packages/core_domain/lib/domain/services/transcription.service.dart @@ -88,23 +88,28 @@ final class TranscriptionService { /// Sauvegarde un segment de transcription et met a jour le stream. /// /// Un segment de meme id (provisoire) est remplace, en base et a l'ecran. - Future saveSegment(TranscriptSegmentEntity segment) async { + /// + /// Rend vrai si le segment est rangé. + Future saveSegment(TranscriptSegmentEntity segment) async { final ResultState result = await _saveTranscriptSegmentUseCase.execute(segment); - result.when( - success: (TranscriptSegmentEntity savedSegment) { - final List currentSegments = - List.from(segmentsStream.value) - ..removeWhere( - (TranscriptSegmentEntity s) => s.id == savedSegment.id, - ); - currentSegments.add(savedSegment); - segmentsStream.add(currentSegments); - }, - failure: (Exception e) { - _log.error('Erreur sauvegarde segment', e); - }, - ); + return result.when( + success: (TranscriptSegmentEntity savedSegment) { + final List currentSegments = + List.from(segmentsStream.value) + ..removeWhere( + (TranscriptSegmentEntity s) => s.id == savedSegment.id, + ); + currentSegments.add(savedSegment); + segmentsStream.add(currentSegments); + return true; + }, + failure: (Exception e) { + _log.error('Erreur sauvegarde segment', e); + return false; + }, + ) ?? + false; } /// Sauve en base la phrase en cours, sans la montrer : l'ecran garde son