feat: initial Cutdex application

Add the Flutter video editing application with project management, media
import, timeline editing, preview, AI assistance, diagnostics and settings.

Include shared UI and native host packages, platform runners, application
tests and release tooling.

Provide usage and contribution guides, the MIT license and third-party
notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
lingjhf committed 2026-10-05 23:36:23 +08:00
commit 27e77fff39
718 files changed
+183958

No files matched your search

@@ -0,0 +1,44 @@
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/diagnostics/agent_request_diagnostics.dart';
import 'package:cutdex/diagnostics/request_report.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('concurrent request publication retains the most recent 20 complete reports', () async {
final root = await Directory.systemTemp.createTemp(
'cutdex-request-retention-',
);
addTearDown(() => root.delete(recursive: true));
await Future.wait(
List.generate(
25,
(index) => AgentRequestDiagnostics.persist(
root,
RequestReport(
outcome: 'completed',
elapsedUs: index,
frames: const RequestFrameReport(
count: 0,
slowFrames: 0,
maxBuildUs: 0,
maxRasterUs: 0,
maxTimerDelayUs: 0,
),
runs: const [],
),
),
),
);
final directory = Directory('${root.path}/diagnostics');
final files = await directory.list().cast<File>().toList();
expect(files, hasLength(20));
final reports = await Future.wait(
files.map((file) async => jsonDecode(await file.readAsString()) as Map),
);
final retained = reports.map((r) => r['elapsedUs'] as int).toList()..sort();
expect(retained, orderedEquals(List.generate(20, (i) => i + 5)));
expect(files.any((f) => f.path.endsWith('.tmp')), isFalse);
});
}
+189
View File
@@ -0,0 +1,189 @@
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/diagnostics/diagnostic_store.dart';
import 'package:cutdex/diagnostics/request_report.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory root;
late AppDiagnostics diagnostics;
setUp(() async {
root = await Directory.systemTemp.createTemp('cutdex-app-diagnostics-');
diagnostics = AppDiagnostics(
DiagnosticStore(Directory('${root.path}/logs')),
sessionId: 'session',
);
AppDiagnostics.instance = diagnostics;
});
tearDown(() async {
AppDiagnostics.instance = null;
await diagnostics.store.flush();
await root.delete(recursive: true);
});
Future<Map<String, dynamic>> exported() async => jsonDecode(
await (await diagnostics.export(Directory('${root.path}/out')))
.readAsString(),
) as Map<String, dynamic>;
test(
'SDK events and Agent reports share request and session identifiers',
() async {
const requestId = '12345678-1234-1234-1234-123456789abc';
await withDiagnosticContext({'requestId': requestId}, () async {
AppDiagnostics.failure(
'preview',
'start',
const RuntimeException(
code: 'failed',
message: 'decode',
domain: 'playback',
details: {'nativeCode': '-11841'},
),
StackTrace.fromString('ORIGINAL STACK'),
);
await diagnostics.request(
const RequestReport(
outcome: 'failed',
elapsedUs: 1,
frames: RequestFrameReport(
count: 0,
slowFrames: 0,
maxBuildUs: 0,
maxRasterUs: 0,
maxTimerDelayUs: 0,
),
runs: [],
),
requestId,
);
});
final report = await exported();
final event = (report['events'] as List).single;
expect(event['context']['requestId'], requestId);
expect(event['sessionId'], 'session');
expect(event['stackTrace'], 'ORIGINAL STACK');
expect(event['error']['nativeDetails']['nativeCode'], '-11841');
expect((report['requests'] as List).single['requestId'], requestId);
expect((report['requests'] as List).single['sessionId'], 'session');
expect((report['requests'] as List).single['at'], isNotNull);
},
);
test(
'SDK error severity uses reserved capacity without synchronous writes',
() async {
diagnostics = AppDiagnostics(
DiagnosticStore(
Directory('${root.path}/reserved'),
maxPending: 8,
errorReserveRecords: 2,
flushInterval: const Duration(days: 1),
),
);
AppDiagnostics.instance = diagnostics;
for (var i = 0; i < 8; i++) {
AppDiagnostics.report(
const DiagnosticEvent(
component: 'editor',
operation: 'split',
level: DiagnosticSeverity.info,
),
);
}
AppDiagnostics.failure(
'editor',
'setCaption',
StateError('failed'),
StackTrace.fromString('PROPERTY ERROR STACK'),
);
expect(File('${root.path}/reserved/fatal.jsonl').existsSync(), isFalse);
final events = (await exported())['events'] as List;
final error = events.singleWhere((e) => e['level'] == 'error');
expect(error['operation'], 'setCaption');
expect(error['stackTrace'], 'PROPERTY ERROR STACK');
expect(diagnostics.store.dropped, 2);
expect(diagnostics.store.droppedErrors, 0);
},
);
test(
'global handlers record errors and preserve existing handler behavior',
() async {
final flutter = FlutterError.onError;
final platform = PlatformDispatcher.instance.onError;
addTearDown(() {
FlutterError.onError = flutter;
PlatformDispatcher.instance.onError = platform;
});
var flutterCalls = 0, platformCalls = 0;
FlutterError.onError = (_) {
flutterCalls++;
};
PlatformDispatcher.instance.onError = (_, _) {
platformCalls++;
return true;
};
diagnostics.installErrorHandlers();
FlutterError.onError!(
FlutterErrorDetails(
exception: StateError('framework'),
stack: StackTrace.current,
),
);
expect(
PlatformDispatcher.instance.onError!(
StateError('async'),
StackTrace.current,
),
isTrue,
);
expect(File('${root.path}/logs/fatal.jsonl').existsSync(), isTrue);
final report = await exported();
expect(flutterCalls, 1);
expect(platformCalls, 1);
expect(report['events'], hasLength(2));
},
);
test('application metadata reads the installed host version', () async {
const channel = MethodChannel('cutdex_native/device_info');
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'getApplicationInfo');
return {'appVersion': '2.0.0', 'appBuild': '42'};
});
addTearDown(
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
.setMockMethodCallHandler(channel, null),
);
await diagnostics.readApplicationInfo();
expect((await exported())['metadata']['appVersion'], '2.0.0');
expect(diagnostics.metadata['appBuild'], '42');
});
test(
'format and process failures do not serialize source or arguments',
() async {
AppDiagnostics.failure(
'test',
'parse',
const FormatException('Invalid JSON', 'PRIVATE BODY'),
StackTrace.current,
);
AppDiagnostics.failure(
'test',
'spawn',
const ProcessException('/worker', ['PRIVATE PROMPT'], 'Failed', 1),
StackTrace.current,
);
final encoded = jsonEncode(await exported());
expect(encoded, isNot(contains('PRIVATE')));
},
);
}
@@ -0,0 +1,65 @@
import 'package:cutdex/diagnostics/diagnostic_redactor.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('redacts nested credentials, content, paths and URLs while preserving metrics', () {
final redactor = DiagnosticRedactor();
final safe =
redactor.value({
'nested': {
'api_key': 'secret',
'accessToken': 'secret',
'prompt': 'private text',
},
'message':
'sk-12345abc Bearer abc123 https://u:p@host/path?q=secret',
'unix': '/Users/person/Media/private.mov',
'windows': r'C:\Users\person\Media\private.mov',
'inputTokens': 25,
'outputTokens': 10,
'nativeCode': '-11841',
})!
as Map;
expect(safe['nested'], {
'api_key': '[redacted]',
'accessToken': '[redacted]',
'prompt': '[redacted]',
});
expect(safe['message'], isNot(contains('abc123')));
expect(safe['message'], isNot(contains('q=secret')));
expect(safe['unix'], '[local-path]');
expect(safe['windows'], '[local-path]');
expect(safe['inputTokens'], 25);
expect(safe['outputTokens'], 10);
expect(safe['nativeCode'], '-11841');
});
test('marker fast paths preserve every existing redaction rule', () {
final redactor = DiagnosticRedactor();
final cases = {
'identifier-123': 'identifier-123',
'BEARER credential': 'Bearer [redacted]',
'sk-credential': '[redacted]',
'PASSWORD=credential': 'PASSWORD=[redacted]',
'api-key: credential': 'api-key=[redacted]',
'https://user:credential@example.com/path?q=credential':
'http[local-path]',
'credential@private.example': '[email]',
r'C:\Users\person\credential.mov': '[local-path]',
r'\\server\share\credential.mov': '[local-path]',
'/Users/person/credential.mov': '[local-path]',
};
for (final entry in cases.entries) {
expect(redactor.text(entry.key), entry.value);
}
});
test('bounds recursion, strings and lists', () {
final redactor = DiagnosticRedactor();
expect(redactor.text('x' * 10000).length, lessThan(8300));
expect(redactor.value(List.filled(10000, 1)), hasLength(2048));
final cyclic = <String, Object?>{};
cyclic['self'] = cyclic;
expect(redactor.value(cyclic).toString(), contains('[truncated]'));
});
}
+359
View File
@@ -0,0 +1,359 @@
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/diagnostics/diagnostic_store.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:uuid/uuid.dart';
void main() {
late Directory root;
setUp(() async {
root = await Directory.systemTemp.createTemp('cutdex-diagnostics-');
});
tearDown(() => root.delete(recursive: true));
DiagnosticStore store({int pending = 256}) => DiagnosticStore(
Directory('${root.path}/logs'),
maxFileBytes: 1024,
fileCount: 3,
maxPending: pending,
);
Future<Map<String, dynamic>> bundle(DiagnosticStore value) async =>
jsonDecode(
await (await value.export(
Directory('${root.path}/out'),
const {},
)).readAsString(),
) as Map<String, dynamic>;
test(
'ordinary records wait for the deadline then share one durable append',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
flushInterval: const Duration(milliseconds: 20),
);
for (var i = 0; i < 8; i++) {
value.record({'index': i});
}
expect(
File('${value.directory.path}/events-0.jsonl').existsSync(),
isFalse,
);
final deadline = Stopwatch()..start();
while (value.eventWriteBatches == 0 &&
deadline.elapsedMilliseconds < 5000) {
await Future<void>.delayed(const Duration(milliseconds: 5));
}
expect(value.eventWriteBatches, 1);
await value.flush();
expect(value.eventFlushes, 1);
expect(value.pendingRecords, 0);
expect(value.pendingEventBytes, 0);
expect((await bundle(value))['events'], hasLength(8));
},
);
test(
'count threshold writes early and explicit flush drains the remaining tail',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
batchSize: 32,
flushInterval: const Duration(days: 1),
);
for (var i = 0; i < 32; i++) {
value.record({'index': i});
}
final deadline = Stopwatch()..start();
while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) {
await Future<void>.delayed(const Duration(milliseconds: 5));
}
expect(value.pendingRecords, 0);
expect(value.eventFlushes, 1);
value.record({'index': 32});
await value.flush();
expect(value.eventFlushes, 2);
expect((await bundle(value))['events'], hasLength(33));
},
);
test(
'encoded-byte threshold writes early even below the record count',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
batchSize: 100,
maxBatchBytes: 100,
flushInterval: const Duration(days: 1),
);
value.record({'index': 1, 'message': 'x' * 100});
final deadline = Stopwatch()..start();
while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) {
await Future<void>.delayed(const Duration(milliseconds: 5));
}
expect(value.pendingRecords, 0);
expect(value.eventFlushes, 1);
expect((await bundle(value))['events'], hasLength(1));
},
);
test(
'byte budget bounds accepted events and still allows immediate fatal logs',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
maxPendingBytes: 100,
errorReserveBytes: 0,
);
value.record({'index': 1, 'message': 'x' * 50});
value.record({'index': 2, 'message': 'x' * 50});
expect(value.pendingRecords, 1);
expect(value.pendingEventBytes, lessThanOrEqualTo(100));
expect(value.dropped, 1);
value.record({'fatal': true}, immediate: true);
expect(
File('${value.directory.path}/fatal.jsonl').readAsStringSync(),
contains('fatal'),
);
final report = await bundle(value);
expect(report['events'], hasLength(2));
expect(value.pendingRecords, 0);
expect(value.pendingEventBytes, 0);
},
);
test(
'full queues skip formatting instead of spending CPU on discarded records',
() async {
final value = store(pending: 1);
value.record({'index': 1});
final probe = _FormattingProbe();
value.record({'value': probe});
expect(probe.calls, 0);
expect(value.dropped, 1);
await value.flush();
},
);
test(
'error slots survive an information burst including queued writes',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
maxPending: 8,
errorReserveRecords: 2,
batchSize: 1,
);
for (var i = 0; i < 8; i++) {
value.record({'level': 'info', 'index': i});
}
final rejectedRequest = value.saveRequest({
'index': 1,
}, const Uuid().v4());
// The rejected request must not consume either reserved slot.
for (var i = 0; i < 3; i++) {
value.record({'level': 'error', 'index': i});
}
expect(value.pendingRecords, 8);
expect(value.dropped, 4);
expect(value.droppedErrors, 1);
await rejectedRequest;
final report = await bundle(value);
final events = report['events'] as List;
expect(events.where((e) => e['level'] == 'info'), hasLength(6));
expect(events.where((e) => e['level'] == 'error'), hasLength(2));
expect(report['requests'], isEmpty);
expect(report['storage']['droppedErrors'], 1);
expect(value.pendingRecords, 0);
expect(value.pendingEventBytes, 0);
},
);
test(
'byte reserve admits errors after warning traffic reaches its limit',
() async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
maxPendingBytes: 1000,
errorReserveBytes: 500,
flushInterval: const Duration(days: 1),
);
value.record({'level': 'warning', 'message': 'x' * 300});
value.record({'level': 'warning', 'message': 'x' * 300});
value.record({'level': 'error', 'message': 'x' * 300});
value.record({'level': 'error', 'message': 'x' * 500});
expect(value.pendingRecords, 2);
expect(value.pendingEventBytes, lessThanOrEqualTo(1000));
expect(value.dropped, 2);
expect(value.droppedErrors, 1);
value.record({'level': 'error', 'fatal': true}, immediate: true);
final events = (await bundle(value))['events'] as List;
expect(events, hasLength(3));
expect(events.where((e) => e['level'] == 'error'), hasLength(2));
expect(value.pendingEventBytes, 0);
},
);
test(
'buffered values are copied and redacted before callers can mutate them',
() async {
final value = store();
final input = {
'context': {'name': 'original', 'apiKey': 'PRIVATE'},
};
value.record(input);
input['context']!['name'] = 'changed';
input['context']!['apiKey'] = 'MUTATED SECRET';
final event = ((await bundle(value))['events'] as List).single;
expect(event['context']['name'], 'original');
expect(event['context']['apiKey'], '[redacted]');
},
);
test('requests and exports drain earlier buffered logs without waiting for the timer', () async {
final value = DiagnosticStore(
Directory('${root.path}/logs'),
flushInterval: const Duration(days: 1),
);
value.record({'index': 1});
await value.saveRequest({'index': 1}, const Uuid().v4());
expect(value.pendingRecords, 0);
value.record({'index': 2});
final report = await bundle(value);
expect((report['events'] as List).map((e) => e['index']), [1, 2]);
expect(report['requests'], hasLength(1));
expect(value.pendingRecords, 0);
});
test(
'concurrent writes rotate within bounds and retain newest complete records',
() async {
final value = store();
for (var i = 0; i < 30; i++) {
value.record({'index': i, 'message': 'x' * 250});
}
await value.flush();
final files = await value.directory.list().cast<File>().toList();
expect(files.length, 3);
for (final file in files) {
expect(await file.length(), lessThanOrEqualTo(1024));
}
final events = (await bundle(value))['events'] as List;
expect(events.last['index'], 29);
expect(
events.map((e) => e['index']).toList(),
orderedEquals(
List.generate(events.length, (i) => 30 - events.length + i),
),
);
},
);
test(
'queue overload drops predictably without blocking or corrupting output',
() async {
final value = store(pending: 2);
for (var i = 0; i < 10; i++) {
value.record({'index': i});
}
await value.flush();
expect(value.dropped, 8);
expect((await bundle(value))['events'], hasLength(2));
},
);
test(
'unwritable store retains bounded fallback events that can be exported',
() async {
final blocked = File('${root.path}/blocked')..writeAsStringSync('file');
final value = DiagnosticStore(Directory(blocked.path));
for (var i = 0; i < 120; i++) {
value.record({'index': i});
}
await value.flush();
final report = await bundle(value);
expect(value.writeFailures, 120);
expect(report['fallbackEvents'], hasLength(100));
expect((report['fallbackEvents'] as List).last['index'], 119);
expect(jsonEncode(report), isNot(contains(root.path)));
},
);
test(
'request retention keeps the latest 20 and excludes conversation files',
() async {
final value = store();
await Future.wait(
List.generate(
25,
(i) => value.saveRequest({'index': i}, const Uuid().v4()),
),
);
File('${value.directory.path}/conversation.json')
.writeAsStringSync('PRIVATE CONVERSATION');
final report = await bundle(value);
final requests = report['requests'] as List;
expect(requests, hasLength(20));
expect(
requests.map((r) => r['index']),
orderedEquals(List.generate(20, (i) => 24 - i)),
);
expect(jsonEncode(report), isNot(contains('PRIVATE CONVERSATION')));
},
);
test('exports redact secrets and skip an interrupted final append', () async {
final value = store();
value.record({
'token': 'PRIVATE TOKEN',
'url': 'https://user:secret@example.com/test?api_key=PRIVATE',
'path': '/Users/person/private.mov',
'message': 'Bearer SECRET',
});
await value.flush();
File('${value.directory.path}/events-0.jsonl')
.writeAsStringSync('{unfinished', mode: FileMode.append);
value.record({'operation': 'afterInterruptedAppend'});
final report = await bundle(value);
expect(report['events'], hasLength(2));
final encoded = jsonEncode(report);
for (final secret in ['PRIVATE', 'SECRET', 'private.mov', 'user:secret']) {
expect(encoded, isNot(contains(secret)));
}
});
test('failed export does not poison subsequent writes or exports', () async {
final value = store();
final blocked = File('${root.path}/blocked')..writeAsStringSync('file');
await expectLater(
value.export(Directory(blocked.path), const {}),
throwsA(isA<FileSystemException>()),
);
value.record({'operation': 'afterExportFailure'});
expect((await bundle(value))['events'], hasLength(1));
});
test(
'uncaught fatal records are flushed synchronously and bounded separately',
() async {
final value = store();
for (var i = 0; i < 8; i++) {
value.record({'index': i, 'error': 'x' * 250}, immediate: true);
}
final file = File('${value.directory.path}/fatal.jsonl');
expect(file.existsSync(), isTrue);
expect(file.lengthSync(), lessThanOrEqualTo(1024));
final events = (await bundle(value))['events'] as List;
expect(events.last['index'], 7);
},
);
}
class _FormattingProbe {
int calls = 0;
@override
String toString() {
calls++;
return 'value';
}
}
@@ -0,0 +1,424 @@
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/features/properties/speed_properties.dart';
import 'package:cutdex/features/timeline/timeline_speed_editor.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:cutdex/diagnostics/diagnostic_store.dart';
import 'package:cutdex/workspace/timeline_session.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:flutter_test/flutter_test.dart';
final sequence = SequenceId('sequence');
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory root;
late ProjectFile project;
late _FaultingSession session;
late AppDiagnostics diagnostics;
setUp(() async {
root = await Directory.systemTemp.createTemp('cutdex-edit-log-');
diagnostics = AppDiagnostics(
DiagnosticStore(Directory('${root.path}/logs')),
);
project = await ProjectFile.create(
Directory('${root.path}/P.cutdex'),
name: 'P',
);
await project.saveTimeline(
TimelineDocument(
id: 'timeline',
name: 'Private project name',
defaultSequenceId: sequence,
payloads: [PayloadDocument(id: 'video', type: 'video')],
sequences: [
TimelineDto(
id: sequence,
format: TimelineFormat.fps30,
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(
id: StorylineId('primary'),
elementIds: [ElementId('clip')],
),
],
elements: [
ElementDto(
id: ElementId('clip'),
name: 'Private clip name',
payloadRef: PayloadRef('video'),
structure: ElementStructure.content,
duration: RationalTime.seconds(10),
sourceRange: TimeRange(
start: RationalTime.zero,
duration: RationalTime.seconds(10),
),
mediaRange: TimeRange(
start: RationalTime.zero,
duration: RationalTime.seconds(10),
),
),
],
),
],
),
);
session = _FaultingSession(
document: await project.loadTimeline('timeline'),
persistence: await project.openTimelineSaveSession('timeline'),
diagnostics: diagnostics.event,
);
});
tearDown(() async {
session.fail = false;
session.failPreparation = false;
await session.close();
await project.close();
await diagnostics.store.flush();
await root.delete(recursive: true);
});
Future<List<dynamic>> events() async {
final output = await diagnostics.export(Directory('${root.path}/out'));
return (jsonDecode(await output.readAsString()) as Map)['events'] as List;
}
for (final operation in [
'setAudio',
'setTransform',
'editMask',
'editKeyframes',
]) {
test(
'direct $operation property rejection exports its original context',
() async {
final before = session.version;
expect(() {
switch (operation) {
case 'setAudio':
session.commands.setAudio(
sequence: sequence,
clip: ElementId('missing'),
db: 1,
);
case 'setTransform':
session.commands.setTransform(
sequence: sequence,
clip: ElementId('missing'),
tick: 10,
change: (v) => v,
);
case 'editMask':
session.commands.applyEdit(
sequence,
EditMask(
clipId: 'missing',
at: CommandTime(1, 1),
action: MaskAction.add,
),
);
default:
session.commands.editKeyframeChannel(
sequence: sequence,
clip: ElementId('missing'),
tick: 10,
parameterIds: [ClipAudioGain.gainId],
);
}
}, throwsA(isA<CommandRejected>()));
final event = (await events()).single;
expect(event['operation'], operation);
expect(event['context']['clipIds'], ['missing']);
expect(event['context']['errorCode'], 'missingClip');
expect(event['context']['operationId'], isNotEmpty);
expect(event['stackTrace'], isNotEmpty);
expect(session.version, before);
},
);
}
test(
'nested property and typed command failure share one operation ID',
() async {
await expectLater(
session.executeCommand(
sequence,
const SetClipAudio(clipId: 'missing', db: 1),
operationId: 'typed-audio',
),
throwsA(isA<CommandRejected>()),
);
final event = (await events()).single;
expect(event['context']['operationId'], 'typed-audio');
expect(event['context']['entryPoint'], 'command');
expect(event['context']['clipIds'], ['missing']);
},
);
Widget surface(Widget child) => MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penLight,
home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)),
);
testWidgets(
'speed slider logs the retained preview error only at final commit',
(tester) async {
final view = session.view(sequence);
final before = session.version;
await tester.pumpWidget(
surface(
SpeedProperties(
session: session,
sequence: sequence,
clip: ElementId('clip'),
),
),
);
AppSlider slider() =>
tester.widget<AppSlider>(find.byKey(const Key('clip-speed-slider')));
slider().onChangeStart!(0.5);
session.failPreparation = true;
slider().onChanged!(0.5);
slider().onChanged!(0.6);
expect(await tester.runAsync(events), isEmpty);
slider().onChangeEnd!(0.6);
session.failPreparation = false;
final event = (await tester.runAsync(events))!.single;
expect(event['operation'], 'setSpeed');
expect(event['context']['clipIds'], ['clip']);
expect(event['stackTrace'], 'ORIGINAL SPEED PREVIEW STACK');
expect(session.version, before);
expect(
view.version.kernelVersion,
same(session.persistence.timeline(sequence).current),
);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets(
'recovered speed preview commits without logging an earlier failure',
(tester) async {
session.view(sequence);
await tester.pumpWidget(
surface(
SpeedProperties(
session: session,
sequence: sequence,
clip: ElementId('clip'),
),
),
);
AppSlider slider() =>
tester.widget<AppSlider>(find.byKey(const Key('clip-speed-slider')));
slider().onChangeStart!(0.5);
session.failPreparation = true;
slider().onChanged!(0.5);
session.failPreparation = false;
slider().onChanged!(0.6);
slider().onChangeEnd!(0.6);
final exported = (await tester.runAsync(events))!;
expect(exported.where((e) => e['level'] == 'error'), isEmpty);
final committed = exported.singleWhere(
(e) => e['context']['outcome'] == 'committed',
);
expect(committed['operation'], 'setSpeed');
expect(committed['context']['clipIds'], ['clip']);
await tester.runAsync(() => session.flush());
expect(
session.editDiagnosticContext['operationId'],
committed['context']['operationId'],
);
await tester.pumpWidget(const SizedBox.shrink());
},
);
testWidgets('speed segment drag logs a preview error once when released', (
tester,
) async {
final view = session.view(sequence);
session.setCustomSpeedEnabled(sequence, ElementId('clip'), true);
final before = session.version;
await tester.pumpWidget(
surface(
TimelineSpeedEditor(
session: session,
sequence: sequence,
controller: view,
),
),
);
final handle = tester.widget<GestureDetector>(
find.byKey(const ValueKey('speed-segment-handle-0')),
);
handle.onPanStart!(DragStartDetails());
session.failPreparation = true;
handle.onPanUpdate!(
DragUpdateDetails(
delta: const Offset(10, 0),
globalPosition: Offset.zero,
),
);
handle.onPanUpdate!(
DragUpdateDetails(
delta: const Offset(10, 0),
globalPosition: Offset.zero,
),
);
expect(await tester.runAsync(events), isEmpty);
handle.onPanEnd!(DragEndDetails());
session.failPreparation = false;
final event = (await tester.runAsync(events))!.single;
expect(event['operation'], 'setSpeedSegment');
expect(event['context']['clipIds'], ['clip']);
expect(event['context']['segmentIndex'], 0);
expect(event['stackTrace'], 'ORIGINAL SPEED PREVIEW STACK');
expect(session.version, before);
await tester.pumpWidget(const SizedBox.shrink());
});
for (final operation in ['split', 'trimLeft', 'trimRight', 'delete']) {
test(
'handled $operation rejection reaches the exported diagnostic package',
() async {
final controller = session.view(sequence);
final query = controller.version.kernelVersion.query();
if (operation == 'delete') {
controller.setSelection([query.elementById(ElementId('clip'))!]);
}
controller.seekTo(5 * TimelineClock.ticksPerSecond);
final before = session.version;
session.fail = true;
final result = switch (operation) {
'split' => controller.cutSelectionAtPlayhead(),
'trimLeft' => controller.trimLeftAtPlayhead(),
'trimRight' => controller.trimRightAtPlayhead(),
_ => controller.deleteSelection(),
};
expect(result, isFalse);
expect(
controller.commandRejection,
contains('injected editing failure'),
);
expect(session.version, before);
final event = (await events()).single;
expect(
event['operation'],
operation.startsWith('trim') ? 'trim' : operation,
);
expect(event['context']['clipIds'], ['clip']);
expect(
event['context']['playheadTick'],
5 * TimelineClock.ticksPerSecond,
);
expect(event['context']['versionBefore'], before);
expect(event['context']['versionAfter'], before);
expect(event['context']['operationId'], isNotEmpty);
expect(event['context']['timelineId'], 'timeline');
expect(event['stackTrace'], 'ORIGINAL MANUAL EDIT STACK');
expect(jsonEncode(event), isNot(contains('Private')));
},
);
}
test(
'drag commit failure keeps move context and cleans up the gesture',
() async {
final controller = session.view(sequence);
final viewport = TimelineViewportRect(width: 800, height: 400);
final y =
controller.geometry.primaryTop +
controller.geometry.primaryHeight / 2;
expect(
controller.beginDrag(viewport: viewport, position: Offset(100, y)),
isTrue,
);
session.fail = true;
expect(
() =>
controller.finishDrag(viewport: viewport, position: Offset(160, y)),
throwsStateError,
);
expect(controller.isDragging, isFalse);
final event = (await events()).single;
expect(event['operation'], 'move');
expect(event['context']['clipIds'], ['clip']);
expect(event['stackTrace'], 'ORIGINAL MANUAL EDIT STACK');
},
);
test(
'undo failure is observed without changing the authored history',
() async {
final controller = session.view(sequence);
controller.seekTo(5 * TimelineClock.ticksPerSecond);
expect(controller.cutSelectionAtPlayhead(), isTrue);
final before = session.version;
session.fail = true;
expect(controller.undo, throwsStateError);
expect(session.version, before);
final recorded = await events();
final committed = recorded.singleWhere(
(e) => e['context']['outcome'] == 'committed',
);
expect(committed['operation'], 'split');
final error = recorded.singleWhere((e) => e['error'] != null);
expect(error['operation'], 'undo');
expect(
error['context']['operationId'],
isNot(committed['context']['operationId']),
);
},
);
test(
'a no-op at the clip boundary does not report a false failure',
() async {
final controller = session.view(sequence);
controller.seekTo(0);
expect(controller.cutSelectionAtPlayhead(), isFalse);
expect(await events(), isEmpty);
},
);
}
class _FaultingSession extends EditorTimelineSession {
_FaultingSession({
required super.document,
required super.persistence,
super.diagnostics,
});
bool fail = false;
bool failPreparation = false;
@override
TimelineLayoutEngine layout(SequenceId sequenceId) {
if (failPreparation) {
Error.throwWithStackTrace(
StateError('injected speed preparation failure'),
StackTrace.fromString('ORIGINAL SPEED PREVIEW STACK'),
);
}
return super.layout(sequenceId);
}
@override
T commit<T>(SequenceId? sequence, T Function() action) {
if (fail) {
Error.throwWithStackTrace(
StateError('injected editing failure'),
StackTrace.fromString('ORIGINAL MANUAL EDIT STACK'),
);
}
return super.commit(sequence, action);
}
}
+34
View File
@@ -0,0 +1,34 @@
import 'dart:convert';
import 'package:cutdex/diagnostics/request_report.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('diagnostics preserve the disk schema and nested run payloads', () {
final report = RequestReport(
outcome: 'completed',
elapsedUs: 20,
preparationUs: 5,
frames: const RequestFrameReport(
count: 2,
slowFrames: 1,
maxBuildUs: 17,
maxRasterUs: 8,
maxTimerDelayUs: 3,
),
runs: const [
{
'events': [
{'type': 'request', 'elapsedUs': 4},
],
},
],
at: DateTime.utc(2026, 10, 2),
);
final json =
jsonDecode(jsonEncode(report.toJson())) as Map<String, dynamic>;
expect((json['frames'] as Map)['over16ms'], 1);
expect(json['version'], 1);
expect(RequestReport.fromJson(json), report);
});
}