// Native Profile entrypoint. Uses the production app with an isolated database // and temporary project. No WidgetTester pumps or forced hidden-window frames. import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math' as math; import 'dart:ui' as ui; import 'package:cutdex/app/app.dart'; import 'package:cutdex/diagnostics/full_app_viewport_bench/drag.dart'; import 'package:cutdex/features/assistant/agent_chat_panel.dart'; import 'package:cutdex/features/assistant/chat_controller.dart'; import 'package:cutdex/features/assistant/chat_state.dart'; import 'package:cutdex/features/preview/preview_panel.dart'; import 'package:cutdex/features/projects/conversation_sidebar.dart'; import 'package:cutdex/integrations/app_updates.dart'; import 'package:cutdex/integrations/editor_tools.dart'; import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'package:cutdex/workspace/view_settings.dart'; import 'package:cutdex/workspace/workspace_mode.dart'; import 'package:cutdex/workspace/workspace_navigation.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/preview.dart'; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/timeline/layout.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:drift/native.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../test/support/preview_fixture.dart'; class _StreamingChat extends ChatController { @override ChatState build( String projectId, { String? conversationId, String? draftKey, }) => ChatState( messages: [ for (var i = 0; i < 30; i++) ChatMessage(text: '历史消息 $i:时间线、画布和素材的编辑记录。' * 12), ], ); void chunk(String text) => state = state.copyWith(busy: true, partialResponse: text); } Future _sleep(int ms) => Future.delayed(Duration(milliseconds: ms)); Element _element(bool Function(Widget) matches) { Element? found; void visit(Element element) { if (matches(element.widget)) found ??= element; element.visitChildElements(visit); } WidgetsBinding.instance.rootElement!.visitChildElements(visit); if (found == null) throw StateError('Expected visible benchmark widget'); return found!; } Future _until(bool Function() ready, String label) async { final clock = Stopwatch()..start(); while (!ready()) { if (clock.elapsed.inSeconds > 60) throw TimeoutException(label); await _sleep(20); } } Future _boundary() async { SchedulerBinding.instance.scheduleFrame(); await SchedulerBinding.instance.endOfFrame; } Future main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kProfileMode) throw StateError('Run this benchmark in Profile mode'); final output = Directory(Platform.environment['CUTDEX_APP_FRAME_BENCH']!); final rounds = int.parse(Platform.environment['CUTDEX_BENCH_ROUNDS'] ?? '3'); if (rounds < 1) throw ArgumentError('CUTDEX_BENCH_ROUNDS must be positive'); await output.create(recursive: true); final frames = []; final errors = []; SchedulerBinding.instance.addTimingsCallback(frames.addAll); final previousError = FlutterError.onError; FlutterError.onError = (details) { errors.add(details.exceptionAsString()); previousError?.call(details); }; final result = { 'status': 'running', 'mode': 'profile', 'rounds': rounds, 'platform': Platform.operatingSystem, 'startedAt': DateTime.now().toUtc().toIso8601String(), 'scope': 'Production CutdexApp, native preview, temporary project and in-memory settings database', 'input': 'Replayed pointer protocol for tab clicks, ruler drag and trackpad zoom; production commands for property values', 'assistant': 'Local deterministic streaming fixture, 30 history messages; no network/model latency', 'measurement': 'Flutter engine build/raster durations; not physical display scanout or video decoder dropped-frame counters', 'phases': >[], }; void save() => File('${output.path}/report.json') .writeAsStringSync(const JsonEncoder.withIndent(' ').convert(result)); final phases = result['phases']! as List>; save(); final fixture = await createPreviewFixture( File(Platform.environment['CUTDEX_BENCH_SOURCE']!).uri, hasAudio: true, clipDuration: RationalTime.seconds(12), renderSize: {'width': 1920, 'height': 1080}, ); final document = await fixture.workspace.project!.loadTimeline('project'); for (final id in ['second', 'third']) { await fixture.workspace.project!.saveTimeline( TimelineDocument( id: id, name: id, sequences: document.sequences, defaultSequenceId: document.defaultSequenceId, payloads: document.payloads, settings: document.settings, ), ); } await fixture.workspace.close(); final database = AppDatabase(NativeDatabase.memory()); final container = ProviderContainer( overrides: [ appDatabaseProvider.overrideWithValue(database), applicationMcpConnectionProvider.overrideWith((ref) {}), appUpdateLifecycleProvider.overrideWith((ref) {}), chatControllerProvider.overrideWith2((_) => _StreamingChat()), ], ); final projects = container.read(projectsProvider.notifier); try { runApp( UncontrolledProviderScope(container: container, child: const CutdexApp()), ); await container.read(workspaceViewSettingsProvider.future); await _until( () => container.read(workspaceNavigationProvider).ready, 'navigation', ); container .read(workspaceViewSettingsProvider.notifier) .setMode(WorkspaceMode.cut); if (!await projects.open('${fixture.directory.path}/Preview.cutdex')) { throw StateError('Could not open isolated project'); } final project = container .read(projectsProvider) .requireValue .activeProject! .id; await projects.openTimeline(project, 'project'); PreviewController? active() { final state = container.read(projectsProvider).value; if (state?.timeline == null || state!.openingTimelineId != null) { return null; } return container .read(editorPreviewProvider(project, state.timeline!.id)) .value; } Future ready() => _until( () => active()?.ready == true && active()?.busy == false, 'native preview', ); await ready(); await File('${output.path}/ready.json').writeAsString('{"ready":true}'); if (Platform.environment['CUTDEX_APP_FRAME_BENCH_GATE'] case final gate?) { await _until(() => File(gate).existsSync(), 'benchmark start gate'); } await _sleep(3000); final display = ui.PlatformDispatcher.instance.views.first.display; final hz = display.refreshRate > 0 ? display.refreshRate : 60.0; final budgetUs = 1000000 / hz; final root = _element((w) => w is EditorPreviewPanel); final logicalSize = MediaQuery.sizeOf(root); final pixelRatio = View.of(root).devicePixelRatio; result.addAll({ 'refreshHz': hz, 'budgetMs': budgetUs / 1000, 'windowLogicalSize': [logicalSize.width, logicalSize.height], 'devicePixelRatio': pixelRatio, 'media': '12s 1920x1080 H.264 30fps with AAC audio', }); Future phase(String name, Future Function() action) async { debugPrint('FRAME BENCH START: $name'); await _boundary(); final start = SchedulerBinding.instance.currentSystemFrameTimeStamp.inMicroseconds; final clock = Stopwatch()..start(); await action(); await _boundary(); final end = SchedulerBinding.instance.currentSystemFrameTimeStamp.inMicroseconds; final duration = clock.elapsedMilliseconds; // Engine timing callbacks arrive in batches. Keep the scenario boundary // in engine vsync time and wait for its last batch before selecting rows. await _sleep(2200); final selected = frames.where((f) { final vsync = f.timestampInMicroseconds(ui.FramePhase.vsyncStart); return vsync > start && vsync <= end; }).toList(); Map stats(List values) { values.sort(); if (values.isEmpty) throw StateError('No engine frames for $name'); return { for (final p in [50, 95, 99]) 'p${p}Ms': values[((values.length - 1) * p / 100).floor()] / 1000, 'maxMs': values.last / 1000, 'overBudget': values.where((v) => v > budgetUs).length, }; } final row = { 'name': name, 'durationMs': duration, 'frames': selected.length, 'build': stats([ for (final f in selected) f.buildDuration.inMicroseconds, ]), 'raster': stats([ for (final f in selected) f.rasterDuration.inMicroseconds, ]), 'overBudgetFrames': selected .where( (f) => f.buildDuration.inMicroseconds > budgetUs || f.rasterDuration.inMicroseconds > budgetUs, ) .length, 'overBudget60Hz': selected .where( (f) => f.buildDuration.inMicroseconds > 1000000 / 60 || f.rasterDuration.inMicroseconds > 1000000 / 60, ) .length, 'overBudget120Hz': selected .where( (f) => f.buildDuration.inMicroseconds > 1000000 / 120 || f.rasterDuration.inMicroseconds > 1000000 / 120, ) .length, 'engineRangeUs': [start, end], 'rawFrames': [ for (final f in selected) [ f.timestampInMicroseconds(ui.FramePhase.vsyncStart), f.buildDuration.inMicroseconds, f.rasterDuration.inMicroseconds, f.totalSpan.inMicroseconds, ], ], }; phases.add(row); save(); debugPrint( 'FRAME BENCH: $name ${selected.length} frames, ${row['overBudgetFrames']} over budget', ); if (errors.isNotEmpty) throw StateError(errors.join('\n')); if (active()?.error != null) { throw StateError('Preview error: ${active()!.error}'); } } final clock = Stopwatch()..start(); Future tapKey(String key) async { final element = _element((w) => w.key == ValueKey(key)); await Scrollable.ensureVisible(element, alignment: .5); await _boundary(); final box = element.findRenderObject()! as RenderBox; final point = box.localToGlobal(box.size.center(Offset.zero)); for (final event in [ PointerAddedEvent(pointer: 7300, device: 73, position: point), PointerDownEvent( pointer: 7300, device: 73, position: point, buttons: kPrimaryButton, timeStamp: clock.elapsed, ), PointerUpEvent( pointer: 7300, device: 73, position: point, timeStamp: clock.elapsed, ), PointerRemovedEvent(pointer: 7300, device: 73, position: point), ]) { GestureBinding.instance.handlePointerEvent(event); } } await phase('cold-timeline-switch', () async { await tapKey('timeline-tab-second'); await _until( () => container.read(projectsProvider).value?.timeline?.id == 'second', 'cold switch', ); await ready(); }); for (final id in ['third', 'project']) { await projects.openTimeline(project, id); await ready(); } await _sleep(2000); for (var round = 1; round <= rounds; round++) { await phase('warm-timeline-switch-$round', () async { for (var i = 0; i < 30; i++) { final id = ['second', 'third', 'project'][i % 3]; await tapKey('timeline-tab-$id'); await _until( () => container.read(projectsProvider).value?.timeline?.id == id, 'warm switch', ); await ready(); await _sleep(160); } }); final preview = active()!; final timeline = await container.read( editorTimelineProvider(project, 'project').future, ); final view = timeline.view(SequenceId('one')); await phase('playback-$round', () async { await preview.controlPreview( SequenceId('one'), PreviewAction.seek, at: CommandTime(0, 30), ); await preview.controlPreview(SequenceId('one'), PreviewAction.play); await _sleep(8000); final position = (await preview.session!.refresh()).position.seconds; result['playbackPositionSeconds-$round'] = position; if (position < 7) { throw StateError('Native video clock did not advance'); } await preview.controlPreview(SequenceId('one'), PreviewAction.pause); }); view.fitTimeline(); view.seekTo(TimelineClock.ticksPerSecond); await ready(); await _sleep(500); final ruler = _element((w) => w is TimelineRuler).findRenderObject()! as RenderBox; final drag = BenchPlayheadDrag( view: view, ruler: ruler, viewport: TimelineViewportRect( width: ruler.size.width, height: ruler.size.height, ), scale: pixelRatio, clock: clock, pointer: 7400 + round, warmFrame: 30, fps: 30, ); await phase('playhead-drag-$round', () async { try { await drag.begin(); for (var i = 0; i < 480; i++) { drag.moveTo(30 + (270 * (math.sin(i / 30) + 1) / 2).round()); await _sleep(16); } drag.end(); await preview.waitForPendingPreview(); } finally { drag.cancel(); } }); final region = _element( (w) => w is TimelineInteractionRegion && !w.ruler, ); final box = region.findRenderObject()! as RenderBox; final point = box.localToGlobal(box.size.center(Offset.zero)); final camera = view.camera; await phase('timeline-zoom-$round', () async { GestureBinding.instance.handlePointerEvent( PointerPanZoomStartEvent(pointer: 7500, device: 75, position: point), ); for (var i = 0; i < 480; i++) { GestureBinding.instance.handlePointerEvent( PointerPanZoomUpdateEvent( pointer: 7500, device: 75, position: point, scale: 1.5 + math.sin(i / 30) * .45, ), ); await _sleep(16); } GestureBinding.instance.handlePointerEvent( PointerPanZoomEndEvent(pointer: 7500, device: 75, position: point), ); view.setCamera(camera); }); container .read(projectViewSettingsProvider(project).notifier) .setPropertiesOpen(true); preview.selectVisual(ElementId('clip')); await _sleep(500); await phase('property-edit-$round', () async { for (var i = 0; i < 240; i++) { timeline.commands.setTransform( sequence: SequenceId('one'), clip: ElementId('clip'), tick: 0, change: (value) => value.copyWith(x: math.sin(i / 20) * .1), ); await _sleep(33); } await preview.waitForPendingPreview(); await timeline.flush(); }); container .read(workspaceViewSettingsProvider.notifier) .setMode(WorkspaceMode.agent); await _sleep(1500); final selection = container.read(conversationSelectionProvider(project)); final chat = container.read( chatControllerProvider( project, conversationId: selection.selectedId, draftKey: selection.selectedId == null ? selection.draftKey : null, ).notifier, ) as _StreamingChat; _element((w) => w is AgentChatPanel); await phase('assistant-stream-$round', () async { var text = ''; for (var i = 0; i < 480; i++) { text += '这是逐字更新的回复内容 $i。'; chat.chunk(text); await _sleep(16); } }); // Narrow desktop windows show properties as an overlay over tab hit // targets. Restore the same navigation geometry before the next round. container .read(projectViewSettingsProvider(project).notifier) .setPropertiesOpen(false); preview.selectVisual(null); container .read(workspaceViewSettingsProvider.notifier) .setMode(WorkspaceMode.cut); await _sleep(1000); } result['status'] = 'passed'; } catch (error, stack) { result['status'] = 'failed'; result['error'] = '$error\n$stack'; } finally { result['flutterErrors'] = errors; result['endedAt'] = DateTime.now().toUtc().toIso8601String(); save(); await projects.prepareToQuit(); runApp(const ProviderScope(child: SizedBox.shrink())); await _sleep(300); container.dispose(); await database.close(); await fixture.directory.delete(recursive: true); } exit(result['status'] == 'passed' ? 0 : 1); }