import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:cutdex/app/app.dart'; import 'package:cutdex/features/preview/preview_panel.dart'; import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'package:cutdex_preview/cutdex_preview.dart'; import 'package:cutdex_native_flutter/cutdex_native_flutter.dart'; import 'package:cutdex_core/timeline/model.dart'; import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart'; import 'package:drift/native.dart'; import 'package:cutdex_ui/icons.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import '../test/support/preview_fixture.dart'; import 'support/native_media_fixture.dart'; void main() { final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const report = String.fromEnvironment('CUTDEX_TEST_REPORT'); testWidgets('full Cutdex app playback lifecycle and sustained editing', ( tester, ) async { final mediaFile = await nativeMediaFixture(); final fixture = await createPreviewFixture( mediaFile.uri, clipDuration: RationalTime.seconds(12), hasAudio: true, renderSize: {'width': 640, 'height': 360}, ); await fixture.workspace.close(); final database = AppDatabase(NativeDatabase.memory()); final container = ProviderContainer( overrides: [appDatabaseProvider.overrideWithValue(database)], ); // macOS can hide the test window while another app is foreground. Keep // tester.pump progressing without changing the application's lifecycle state. final hiddenWindowFrames = Timer.periodic( const Duration(milliseconds: 16), (_) { if (!binding.framesEnabled) binding.scheduleForcedFrame(); }, ); final samples = >[]; final steps = []; void mark(String step) { steps.add(step); debugPrint('ACCEPTANCE: $step'); } final watch = Stopwatch()..start(); var quit = false; final projects = container.read(projectsProvider.notifier); Future until( bool Function() condition, { String label = 'UI settled', }) async { for (var attempt = 0; attempt < 500; attempt++) { await tester.pump(const Duration(milliseconds: 20)); await Future.delayed(const Duration(milliseconds: 5)); if (condition()) { expect(tester.takeException(), isNull, reason: label); return; } } fail('Timed out: $label'); } Future settled(PreviewController preview) async { await tester.pump(); await until( () => !preview.busy && preview.ready, label: 'preview ready: ${preview.error}', ); expect(preview.error, isNull); } void sample(String phase, int edits) { samples.add({ 'phase': phase, 'edits': edits, 'elapsedMs': watch.elapsedMilliseconds, 'rssBytes': ProcessInfo.currentRss, }); debugPrint('ACCEPTANCE MEMORY: ${samples.last}'); if (report.isNotEmpty) { File(report).writeAsStringSync( jsonEncode({ 'steps': steps, 'memory': samples, 'durationMs': watch.elapsedMilliseconds, 'complete': false, }), ); } } try { await tester.pumpWidget( UncontrolledProviderScope( container: container, child: const CutdexApp(), ), ); await until(() => container.read(projectsProvider).hasValue); final phoneCut = find.byKey(const Key('workspace-cut-destination')); final desktopMode = find.byKey(const Key('sidebar-mode-trigger')); await until( () => phoneCut.evaluate().isNotEmpty || desktopMode.evaluate().isNotEmpty, ); if (phoneCut.evaluate().isNotEmpty) { expect(find.byKey(const Key('phone-workspace-shell')), findsOneWidget); await tester.tap(phoneCut); } else { await tester.tap(desktopMode); await tester.pumpAndSettle(); await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); } await tester.pumpAndSettle(); mark('selected Cut mode through the application navigation'); expect( await projects.open('${fixture.directory.path}/Preview.cutdex'), isTrue, ); final state = await container.read(projectsProvider.future); final ids = (state.activeProject!.id, 'project'); expect(await projects.openTimeline(ids.$1, ids.$2), isTrue); await until( () => container .read(editorPreviewProvider(ids.$1, ids.$2)) .asData ?.value ?.ready == true, label: 'full application preview initialized', ); final preview = container .read(editorPreviewProvider(ids.$1, ids.$2)) .requireValue!; final timeline = await container.read( editorTimelineProvider(ids.$1, ids.$2).future, ); final sequence = SequenceId('one'); final view = timeline.view(sequence); expect(find.byType(CutdexApp), findsOneWidget); await until( () => find.byType(RuntimePreview).evaluate().isNotEmpty, label: 'native preview widget mounted', ); expect(find.byType(RuntimePreview), findsOneWidget); expect(find.byType(TimelineView), findsOneWidget); mark('full application and native preview mounted'); final panel = find.byType(EditorPreviewPanel); await tester.tap( find.descendant(of: panel, matching: find.byIcon(AppIcons.play)).first, ); await until(() => preview.playing, label: 'UI play'); await Future.delayed(const Duration(milliseconds: 700)); await tester.pump(); expect( (await preview.session!.refresh()).position.seconds, greaterThan(0), ); await tester.tap( find.descendant(of: panel, matching: find.byIcon(AppIcons.pause)).first, ); await until(() => !preview.playing, label: 'UI pause'); mark('real play and pause buttons advanced native media clock'); final timelineRect = tester.getRect(find.byType(TimelineView)); await tester.dragFrom( Offset(timelineRect.left + 80, timelineRect.top + 10), const Offset(160, 0), ); await tester.pump(const Duration(milliseconds: 150)); expect(preview.error, isNull); for (final second in [3, 8, 1, 10, 0]) { view.seekTo(second * TimelineClock.ticksPerSecond); await tester.pump(const Duration(milliseconds: 120)); await Future.delayed(const Duration(milliseconds: 80)); expect(preview.error, isNull); } mark('timeline pointer drag and repeated forward/backward seeking'); expect( await projects.createTimeline(name: 'Acceptance empty timeline'), isTrue, ); await tester.pump(const Duration(milliseconds: 300)); expect(await projects.openTimeline(ids.$1, ids.$2), isTrue); await settled(preview); mark('switch to empty timeline and return'); for (final events in [ [ PlaybackSystemEvent.systemWillSleep, PlaybackSystemEvent.systemDidWake, ], [ PlaybackSystemEvent.interruptionBegan, PlaybackSystemEvent.interruptionEnded, ], ]) { await preview.session!.handleSystemEvent(events.first); final before = preview.session!.snapshot!.revision; for (var i = 0; i < 8; i++) { timeline.commands.setTransform( sequence: sequence, clip: ElementId('clip'), tick: 0, change: (value) => value.copyWith(x: i / 100), ); } await tester.pump(const Duration(milliseconds: 100)); expect(preview.session!.snapshot!.revision, before); await preview.session!.handleSystemEvent(events.last); await settled(preview); } await preview.session!.handleSystemEvent( PlaybackSystemEvent.audioRouteChanged, ); timeline.commands.setTransform( sequence: sequence, clip: ElementId('clip'), tick: 0, change: (value) => value.copyWith(x: .12), ); await settled(preview); expect(preview.session!.availability, PlaybackAvailability.available); mark( 'native sleep/wake, interruption and audio route events during real edits', ); sample('before warmup', 0); for (var index = 0; index < 180; index++) { timeline.commands.setTransform( sequence: sequence, clip: ElementId('clip'), tick: 0, change: (value) => value.copyWith(x: (index % 10) / 100), ); await settled(preview); if (index % 10 == 0) { view.seekTo((index % 11) * TimelineClock.ticksPerSecond); } await tester.pump(const Duration(milliseconds: 40)); await Future.delayed(const Duration(milliseconds: 700)); if ((index + 1) % 20 == 0) sample('editing', index + 1); expect(preview.error, isNull); expect(tester.takeException(), isNull); } await timeline.saveTimeline(); mark('180 native-backed edits with periodic seeks, saved successfully'); await preview.session!.handleSystemEvent( PlaybackSystemEvent.systemWillSleep, ); timeline.commands.setTransform( sequence: sequence, clip: ElementId('clip'), tick: 0, change: (value) => value.copyWith(x: .2), ); await tester.pump(const Duration(milliseconds: 50)); expect( await projects.prepareToQuit().timeout(const Duration(seconds: 15)), isTrue, ); quit = true; mark('close workspace while preview waits for recovery'); if (report.isNotEmpty) { await File(report).writeAsString( const JsonEncoder.withIndent(' ').convert({ 'steps': steps, 'memory': samples, 'durationMs': watch.elapsedMilliseconds, 'systemEvents': 'injected into the actual app native facade; no physical machine sleep', }), ); } } finally { if (!quit) { try { await projects.prepareToQuit(); } catch (_) {} } await tester.pumpWidget(const SizedBox.shrink()); hiddenWindowFrames.cancel(); container.dispose(); await Future.delayed(const Duration(milliseconds: 200)); await database.close(); await fixture.directory.delete(recursive: true); } }, timeout: const Timeout(Duration(minutes: 10))); }