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:
commit
27e77fff39
718 files changed
+183958
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,595 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
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/assistant/composer_document.dart';
|
||||
import 'package:cutdex/features/assistant/composer_suggestion_surface.dart';
|
||||
import 'package:cutdex/features/media/media_asset_drag.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_provider.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _AttachmentProjects extends Projects {
|
||||
@visibleForTesting
|
||||
int importCalls = 0;
|
||||
|
||||
@override
|
||||
Future<MediaImportResult?> importExternalMedia(
|
||||
String projectId,
|
||||
List<ExternalMediaFile> files, {
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
importCalls++;
|
||||
return null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ProjectState> build() async => ProjectState(
|
||||
activeProject: const RecentProject(
|
||||
id: 'project',
|
||||
name: 'Project',
|
||||
path: '/Project.cutdex',
|
||||
),
|
||||
assets: [
|
||||
AssetDocument(
|
||||
id: 'asset-1',
|
||||
name: '片段.mov',
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('/tmp/片段.mov').toString(),
|
||||
metadata: const {'kind': 'file'},
|
||||
),
|
||||
],
|
||||
timelines: const [
|
||||
TimelineSummary(id: 'timeline', name: '主时间线', revision: 1),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _MessagesChatController extends ChatController {
|
||||
@override
|
||||
ChatState build(
|
||||
String projectId, {
|
||||
String? conversationId,
|
||||
String? draftKey,
|
||||
}) => const ChatState(
|
||||
messages: [
|
||||
ChatMessage(text: 'Assistant reply'),
|
||||
ChatMessage(text: 'User prompt', isUser: true),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('conversation content aligns with the composer at both widths', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
for (final width in [1200.0, 500.0]) {
|
||||
tester.view.physicalSize = Size(width, 800);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_AttachmentProjects.new),
|
||||
chatControllerProvider('project')
|
||||
.overrideWith(_MessagesChatController.new),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(body: AgentChatPanel(projectId: 'project')),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final conversation = tester.getRect(
|
||||
find.byKey(const Key('agent-conversation-content')),
|
||||
);
|
||||
final composer = tester.getRect(find.byKey(const Key('agent-composer')));
|
||||
expect(conversation.left, composer.left);
|
||||
expect(conversation.right, composer.right);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('left and right arrows cross an inline reference as one item', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = ComposerDocumentController(text: '@时间线 1');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(
|
||||
0,
|
||||
4,
|
||||
const ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: 'project',
|
||||
id: 'timeline',
|
||||
label: '时间线',
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(body: TextField(controller: controller)),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byType(TextField));
|
||||
controller.selection = TextSelection.collapsed(
|
||||
offset: controller.text.length,
|
||||
);
|
||||
await tester.pump();
|
||||
for (var index = 0; index < 2; index++) {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
|
||||
}
|
||||
expect(controller.selection.extentOffset, controller.marks.single.end);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
|
||||
expect(controller.selection.extentOffset, controller.marks.single.start);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
|
||||
expect(controller.selection.extentOffset, controller.marks.single.end);
|
||||
});
|
||||
|
||||
testWidgets('keyboard selection scrolls grouped suggestions into view', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = ComposerDocumentController();
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Align(
|
||||
alignment: Alignment.bottomCenter,
|
||||
child: ComposerSuggestionSurface(
|
||||
controller: controller,
|
||||
width: 260,
|
||||
projectId: 'project',
|
||||
assets: [
|
||||
for (var index = 0; index < 20; index++)
|
||||
AssetDocument(
|
||||
id: 'asset-$index',
|
||||
name: '片段 $index',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///tmp/$index',
|
||||
),
|
||||
],
|
||||
timelines: const [
|
||||
TimelineSummary(id: 'timeline', name: '主时间线', revision: 1),
|
||||
],
|
||||
onSend: () {},
|
||||
builder: (context, focus) =>
|
||||
TextField(controller: controller, focusNode: focus),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.enterText(find.byType(TextField), '@');
|
||||
await tester.pumpAndSettle();
|
||||
final list = find.byKey(const Key('agent-composer-suggestion-list'));
|
||||
ScrollController scroll() => tester.widget<ListView>(list).controller!;
|
||||
|
||||
for (var index = 0; index < 15; index++) {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect(scroll().offset, greaterThan(0));
|
||||
final scrolledOffset = scroll().offset;
|
||||
final selected = find.byKey(const Key('agent-suggestion-media-asset-15'));
|
||||
expect(selected, findsOneWidget);
|
||||
expect(tester.getRect(list).overlaps(tester.getRect(selected)), isTrue);
|
||||
|
||||
for (var index = 0; index < 15; index++) {
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect(scroll().offset, lessThan(scrolledOffset));
|
||||
expect(
|
||||
tester
|
||||
.getRect(list)
|
||||
.overlaps(
|
||||
tester.getRect(
|
||||
find.byKey(const Key('agent-suggestion-media-asset-0')),
|
||||
),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-timeline-timeline')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(scroll().offset, greaterThan(0));
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester
|
||||
.getRect(list)
|
||||
.overlaps(
|
||||
tester.getRect(
|
||||
find.byKey(const Key('agent-suggestion-media-asset-0')),
|
||||
),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'composer @ menu inserts an atomic asset reference and empty triggers stay open',
|
||||
(tester) async {
|
||||
final platform = SystemChannels.platform;
|
||||
String? copiedText;
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(platform, (call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
copiedText = (call.arguments as Map)['text'] as String?;
|
||||
}
|
||||
if (call.method == 'Clipboard.hasStrings') {
|
||||
return {'value': copiedText != null};
|
||||
}
|
||||
if (call.method == 'Clipboard.getData') {
|
||||
return {'text': copiedText};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(platform, null));
|
||||
final controller = ComposerDocumentController();
|
||||
var outsideTaps = 0;
|
||||
addTearDown(controller.dispose);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_AttachmentProjects.new),
|
||||
agentRuntimeProvider.overrideWithValue(const AsyncData(null)),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Stack(
|
||||
children: [
|
||||
AgentChatPanel(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
inputController: controller,
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: TextButton(
|
||||
onPressed: () => outsideTaps++,
|
||||
child: const Text('outside target'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final field = find.byType(TextField).last;
|
||||
await tester.enterText(field, '@片');
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('agent-composer-suggestions')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-media-asset-1')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-media')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-timeline')),
|
||||
findsNothing,
|
||||
);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.marks.single.reference.id, 'asset-1');
|
||||
expect(controller.text, '@片段.mov ');
|
||||
expect(controller.selection.extentOffset, controller.text.length);
|
||||
final assetSpan = controller.buildTextSpan(
|
||||
context: tester.element(field),
|
||||
withComposing: false,
|
||||
);
|
||||
final referenceColor = AppTheme.composerReferenceColor(
|
||||
tester.element(field),
|
||||
);
|
||||
expect(
|
||||
referenceColor,
|
||||
isNot(Theme.of(tester.element(field)).colorScheme.onSurface),
|
||||
);
|
||||
final assetIcon =
|
||||
((assetSpan.children!.first as WidgetSpan).child as Padding).child
|
||||
as Icon;
|
||||
expect(assetIcon.icon, Icons.attach_file);
|
||||
expect(assetIcon.color, referenceColor);
|
||||
expect((assetSpan.children![1] as TextSpan).style?.color, referenceColor);
|
||||
expect(
|
||||
tester.getSemantics(find.byType(EditableText).last).value,
|
||||
contains('片段.mov'),
|
||||
);
|
||||
controller.selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: controller.text.length,
|
||||
);
|
||||
tester
|
||||
.state<EditableTextState>(find.byType(EditableText).last)
|
||||
.copySelection(SelectionChangedCause.keyboard);
|
||||
await tester.pump();
|
||||
expect(copiedText, '@片段.mov ');
|
||||
controller.clearDocument();
|
||||
await tester.pump();
|
||||
await tester
|
||||
.state<EditableTextState>(find.byType(EditableText).last)
|
||||
.pasteText(SelectionChangedCause.keyboard);
|
||||
await tester.pump();
|
||||
expect(controller.text, '@片段.mov ');
|
||||
expect(controller.marks, isEmpty);
|
||||
controller.clearDocument();
|
||||
await tester.enterText(field, '@');
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-media')),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-timeline')),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.marks.single.reference.id, 'timeline');
|
||||
final timelineSpan = controller.buildTextSpan(
|
||||
context: tester.element(field),
|
||||
withComposing: false,
|
||||
);
|
||||
final timelineIcon =
|
||||
((timelineSpan.children!.first as WidgetSpan).child as Padding).child
|
||||
as Icon;
|
||||
expect(timelineIcon.icon, Icons.view_timeline_outlined);
|
||||
expect(timelineIcon.color, referenceColor);
|
||||
final timelineLabel = timelineSpan.children![1] as TextSpan;
|
||||
expect(timelineLabel.text, '主时间线');
|
||||
expect(timelineLabel.style?.color, referenceColor);
|
||||
controller.selection = TextSelection.collapsed(
|
||||
offset: controller.text.length,
|
||||
);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.marks.single.reference.id, 'timeline');
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.backspace);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.marks, isEmpty);
|
||||
expect(controller.text, isEmpty);
|
||||
controller.clearDocument();
|
||||
await tester.enterText(field, '@主');
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-media')),
|
||||
findsNothing,
|
||||
);
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-group-timeline')),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.tap(
|
||||
find.byKey(const Key('agent-suggestion-timeline-timeline')),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.marks.single.reference.id, 'timeline');
|
||||
controller.clearDocument();
|
||||
await tester.enterText(field, '/');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('暂无可用选项'), findsOneWidget);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing);
|
||||
await tester.enterText(field, '/a');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('暂无可用选项'), findsOneWidget);
|
||||
await tester.tap(find.text('outside target'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing);
|
||||
expect(outsideTaps, 1);
|
||||
controller.clearDocument();
|
||||
await tester.enterText(field, r'$');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('暂无可用选项'), findsOneWidget);
|
||||
controller.clearDocument();
|
||||
controller.value = const TextEditingValue(
|
||||
text: '@片',
|
||||
selection: TextSelection.collapsed(offset: 2),
|
||||
composing: TextRange(start: 1, end: 2),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing);
|
||||
controller.value = controller.value.copyWith(composing: TextRange.empty);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byKey(const Key('agent-suggestion-media-asset-1')),
|
||||
findsOneWidget,
|
||||
);
|
||||
},
|
||||
);
|
||||
testWidgets('project asset can be dropped anywhere in the Agent panel', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_AttachmentProjects.new),
|
||||
agentRuntimeProvider.overrideWithValue(const AsyncData(null)),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
Draggable<MediaAssetDrag>(
|
||||
data: MediaAssetDrag(
|
||||
projectId: 'project',
|
||||
assetId: 'asset-1',
|
||||
),
|
||||
feedback: const Material(child: Text('dragging')),
|
||||
child: const SizedBox(
|
||||
width: 100,
|
||||
height: 100,
|
||||
child: Text('素材'),
|
||||
),
|
||||
),
|
||||
const Expanded(
|
||||
child: AgentChatPanel(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final gesture = await tester.startGesture(
|
||||
tester.getCenter(find.text('素材')),
|
||||
);
|
||||
await gesture.moveBy(const Offset(20, 0));
|
||||
await tester.pump();
|
||||
await gesture.moveTo(
|
||||
tester.getCenter(find.byKey(const Key('agent-conversation'))),
|
||||
);
|
||||
await tester.pump();
|
||||
final overlay = find.byKey(const Key('agent-drop-overlay'));
|
||||
expect(overlay, findsOneWidget);
|
||||
expect(tester.widget(overlay), isA<DropToAddOverlay>());
|
||||
expect(find.text('松手即可添加'), findsOneWidget);
|
||||
expect(
|
||||
tester.getRect(overlay),
|
||||
tester.getRect(find.byType(AgentChatPanel)),
|
||||
);
|
||||
await gesture.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(overlay, findsNothing);
|
||||
expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget);
|
||||
final duplicate = await tester.startGesture(
|
||||
tester.getCenter(find.text('素材')),
|
||||
);
|
||||
await duplicate.moveBy(const Offset(20, 0));
|
||||
await tester.pump();
|
||||
await duplicate.moveTo(
|
||||
tester.getCenter(find.byKey(const Key('agent-conversation'))),
|
||||
);
|
||||
await tester.pump();
|
||||
expect(overlay, findsNothing);
|
||||
await duplicate.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('agent-attachment-remove-asset-1')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-attachment-asset-1')), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('Finder drop reuses an existing project asset without flashing', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel('cutdex_native/file_drop/attachments');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => null);
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_AttachmentProjects.new),
|
||||
agentRuntimeProvider.overrideWithValue(const AsyncData(null)),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(
|
||||
body: AgentChatPanel(projectId: 'project', timelineId: 'timeline'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
Future<void> event(String phase, int session) async {
|
||||
final done = Completer<void>();
|
||||
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
'cutdex_native/file_drop/attachments',
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('event', {
|
||||
'phase': phase,
|
||||
'session': session,
|
||||
'files': [
|
||||
const {'path': '/tmp/片段.mov'},
|
||||
],
|
||||
}),
|
||||
),
|
||||
(_) => done.complete(),
|
||||
);
|
||||
await done.future;
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
await event('enter', 1);
|
||||
expect(find.byKey(const Key('agent-drop-overlay')), findsOneWidget);
|
||||
await event('drop', 1);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-drop-overlay')), findsNothing);
|
||||
expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget);
|
||||
expect(
|
||||
(container.read(
|
||||
projectsProvider.notifier,
|
||||
) as _AttachmentProjects).importCalls,
|
||||
0,
|
||||
);
|
||||
|
||||
await event('enter', 2);
|
||||
expect(find.byKey(const Key('agent-drop-overlay')), findsNothing);
|
||||
await event('drop', 2);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget);
|
||||
expect(
|
||||
(container.read(
|
||||
projectsProvider.notifier,
|
||||
) as _AttachmentProjects).importCalls,
|
||||
0,
|
||||
);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex/integrations/agent/agent_models.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_prompt_policy.dart';
|
||||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
import 'package:cutdex_sdk/editor/commands.dart';
|
||||
|
||||
class _CatalogHost implements EditorCommandHost {
|
||||
_CatalogHost([this.operations]);
|
||||
final Set<EditorOperation>? operations;
|
||||
@override
|
||||
Set<EditorOperation> get supportedOperations =>
|
||||
operations ?? EditorOperation.values.toSet();
|
||||
@override
|
||||
Future<CommandResult> execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) => throw UnimplementedError('Only declarations are read by this test');
|
||||
}
|
||||
|
||||
class _SnapshotHost extends _CatalogHost {
|
||||
_SnapshotHost(this.result);
|
||||
final CommandResult result;
|
||||
@override
|
||||
Future<CommandResult> execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) async => result;
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('Agent capabilities do not repeat already registered schemas', () async {
|
||||
final source = CommandResult(
|
||||
status: CommandStatus.succeeded,
|
||||
message: 'Available tools',
|
||||
data: {
|
||||
'tools': editorToolDefinitions.map((tool) => tool.toJson()).toList(),
|
||||
},
|
||||
);
|
||||
final tools = editorAgentTools({
|
||||
'timeline': EditorToolDispatcher(host: _SnapshotHost(source)),
|
||||
});
|
||||
final tool = tools.singleWhere((tool) => tool.name == 'tools_capabilities');
|
||||
final result = await tool.execute(
|
||||
ToolCall(
|
||||
id: 'c',
|
||||
name: tool.name,
|
||||
arguments: {'workspaceId': 'timeline'},
|
||||
),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: 'c',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
final declarations = ((result.data['data'] as Map)['tools'] as List)
|
||||
.cast<Map<String, Object?>>();
|
||||
expect(declarations, hasLength(editorToolDefinitions.length));
|
||||
expect(
|
||||
declarations.map((d) => d['name']),
|
||||
editorToolDefinitions.map((d) => d.name),
|
||||
);
|
||||
expect(declarations.every((d) => !d.containsKey('inputSchema')), isTrue);
|
||||
expect((source.data['tools'] as List).first, contains('inputSchema'));
|
||||
});
|
||||
|
||||
test(
|
||||
'multi-lane mask queries retain edit values and fit repeated verification',
|
||||
() async {
|
||||
final parameters = [
|
||||
'canvas.position.x',
|
||||
'canvas.scale.x',
|
||||
'canvas.rotation',
|
||||
for (final mask in ['ellipse', 'hole'])
|
||||
for (final field in [
|
||||
'center.x',
|
||||
'center.y',
|
||||
'width',
|
||||
'height',
|
||||
'rotation',
|
||||
'feather',
|
||||
'shape',
|
||||
'enabled',
|
||||
'inverted',
|
||||
'mode',
|
||||
'order',
|
||||
])
|
||||
'mask.$mask.$field',
|
||||
];
|
||||
final source = CommandResult(
|
||||
status: CommandStatus.succeeded,
|
||||
message: 'Timeline',
|
||||
data: {
|
||||
'duration': {'numerator': '35', 'denominator': 1},
|
||||
'saveState': 'saved',
|
||||
'clips': [
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
'clipId': 'clip-$i',
|
||||
'parameters': [
|
||||
for (final id
|
||||
in i < 2
|
||||
? parameters
|
||||
: ['canvas.position.x', 'canvas.position.y'])
|
||||
{
|
||||
'id': id,
|
||||
'defaultValue': .5,
|
||||
'minimum': -1000000,
|
||||
'maximum': 1000000,
|
||||
'unit': '',
|
||||
'keyframes': id == 'canvas.position.x'
|
||||
? [
|
||||
{
|
||||
'sourceTime': {
|
||||
'numerator': '5',
|
||||
'denominator': 1,
|
||||
},
|
||||
'value': 0,
|
||||
'interpolation': 'linear',
|
||||
},
|
||||
{
|
||||
'sourceTime': {
|
||||
'numerator': '15',
|
||||
'denominator': 1,
|
||||
},
|
||||
'value': .15625,
|
||||
'interpolation': 'linear',
|
||||
},
|
||||
]
|
||||
: <Object?>[],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
final tools = editorAgentTools({
|
||||
'timeline': EditorToolDispatcher(host: _SnapshotHost(source)),
|
||||
});
|
||||
final query = tools.singleWhere((tool) => tool.name == 'timeline_query');
|
||||
final result = await query.execute(
|
||||
ToolCall(
|
||||
id: 'q',
|
||||
name: query.name,
|
||||
arguments: {'workspaceId': 'timeline'},
|
||||
),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: 'q',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
final data = result.data['data'] as Map;
|
||||
final actual =
|
||||
((data['clips'] as List).first as Map)['parameters'] as List;
|
||||
final original =
|
||||
((source.data['clips'] as List).first as Map)['parameters'] as List;
|
||||
expect(actual.first['keyframes'], original.first['keyframes']);
|
||||
expect(
|
||||
actual.map((p) => p['defaultValue']),
|
||||
original.map((p) => p['defaultValue']),
|
||||
);
|
||||
expect(data['duration'], source.data['duration']);
|
||||
expect(original.first['maximum'], 1000000);
|
||||
List<AgentMessage> history(String text) => [
|
||||
AgentMessage(
|
||||
role: MessageRole.user,
|
||||
text: 'Split all lanes, verify, undo and redo.',
|
||||
),
|
||||
for (var i = 0; i < 5; i++) ...[
|
||||
AgentMessage(
|
||||
role: MessageRole.assistant,
|
||||
calls: [
|
||||
ToolCall(
|
||||
id: 'q$i',
|
||||
name: query.name,
|
||||
arguments: {'workspaceId': 'timeline'},
|
||||
),
|
||||
],
|
||||
),
|
||||
AgentMessage(role: MessageRole.tool, callId: 'q$i', text: text),
|
||||
],
|
||||
];
|
||||
final builder = HarnessContextBuilder(maxResultBytes: 1024);
|
||||
final raw = jsonEncode(
|
||||
ToolResult(source.message, data: source.toJson()).toJson(),
|
||||
);
|
||||
expect(
|
||||
builder.measureInput(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
history: history(raw),
|
||||
tools: tools,
|
||||
),
|
||||
greaterThan(builder.maxInputTokens),
|
||||
);
|
||||
final request = await builder.build(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
history: history(jsonEncode(result.toJson())),
|
||||
tools: tools,
|
||||
cancellation: CancellationToken(),
|
||||
);
|
||||
expect(request.messages, hasLength(11));
|
||||
final fullHistory = history(jsonEncode(result.toJson()));
|
||||
final changed = jsonDecode(fullHistory[4].text);
|
||||
changed['data']['data']['clips'][0]['parameters'][1]['defaultValue'] =
|
||||
.75;
|
||||
fullHistory[4] = AgentMessage.fromJson({
|
||||
...fullHistory[4].toJson(),
|
||||
'text': jsonEncode(changed),
|
||||
});
|
||||
final projection = HarnessContextBuilder(maxResultBytes: 1024);
|
||||
final bounded = await projection.build(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
history: fullHistory,
|
||||
tools: tools,
|
||||
cancellation: CancellationToken(),
|
||||
);
|
||||
expect(bounded.messages, hasLength(fullHistory.length));
|
||||
expect(jsonDecode(bounded.messages[4].text)['resultId'], 'q1');
|
||||
expect(jsonDecode(bounded.messages[4].text)['omitted'], isTrue);
|
||||
expect(fullHistory[4].text, contains('"defaultValue":0.75'));
|
||||
final snapshot = SessionSnapshot(id: 's', history: fullHistory);
|
||||
final reader = projection
|
||||
.runtimeTools(() => snapshot, tools)
|
||||
.singleWhere((tool) => tool.name == 'read_tool_result');
|
||||
final recovered = await reader.execute(
|
||||
ToolCall(
|
||||
id: 'read',
|
||||
name: reader.name,
|
||||
arguments: {
|
||||
'resultId': 'q1',
|
||||
'path': '/data/data/clips/0/parameters/1/defaultValue',
|
||||
},
|
||||
),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: 'read',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
expect(recovered.data['value'], .75);
|
||||
expect(
|
||||
bounded.messages.map((m) => m.callId),
|
||||
fullHistory.map((m) => m.callId),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('workspace discovery identifies timeline tools and rejects application routing', () async {
|
||||
final tools = editorAgentTools({
|
||||
'application': EditorToolDispatcher(
|
||||
host: _CatalogHost({EditorOperation.queryProjects}),
|
||||
),
|
||||
'timeline-id': EditorToolDispatcher(
|
||||
host: _CatalogHost({
|
||||
EditorOperation.queryTimeline,
|
||||
EditorOperation.split,
|
||||
}),
|
||||
),
|
||||
});
|
||||
final listing = await tools.first.execute(
|
||||
ToolCall(id: 'list', name: 'cutdex_workspaces'),
|
||||
ToolContext(
|
||||
sessionId: 'session',
|
||||
runId: 'run',
|
||||
operationId: 'op',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
final data = jsonDecode(listing.text);
|
||||
final targets = data['targets'] as List;
|
||||
expect(
|
||||
data['toolSets'][targets.last['toolSetId']],
|
||||
contains('timeline_split'),
|
||||
);
|
||||
expect(
|
||||
data['toolSets'][targets.first['toolSetId']],
|
||||
isNot(contains('timeline_split')),
|
||||
);
|
||||
final query = tools.firstWhere((tool) => tool.name == 'timeline_query');
|
||||
expect(
|
||||
query.validate({'workspaceId': 'application'}),
|
||||
contains('timeline-id'),
|
||||
);
|
||||
expect(query.validate({'workspaceId': 'timeline-id'}), isNull);
|
||||
expect(
|
||||
query.validate({'workspaceId': 'timeline-typo'}),
|
||||
contains('timeline-id'),
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'large workspace discovery is lossless and shares a single tool catalog',
|
||||
() async {
|
||||
final dispatcher = EditorToolDispatcher(host: _CatalogHost());
|
||||
final tool = editorAgentTools({
|
||||
for (var i = 0; i < 100; i++) 'timeline-$i': dispatcher,
|
||||
}).first;
|
||||
final listing = await tool.execute(
|
||||
ToolCall(id: 'list', name: tool.name),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: 'list',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
final data = jsonDecode(listing.text);
|
||||
expect(data['targets'], hasLength(100));
|
||||
expect(data['toolSets'], hasLength(1));
|
||||
final original = AgentMessage(
|
||||
role: MessageRole.tool,
|
||||
callId: 'list',
|
||||
text: jsonEncode(listing.toJson()),
|
||||
);
|
||||
final projected = HarnessContextBuilder(maxResultBytes: 1024)
|
||||
.projectHistory([original]);
|
||||
expect(jsonDecode(projected.single.text)['resultId'], 'list');
|
||||
expect(original.text, jsonEncode(listing.toJson()));
|
||||
},
|
||||
);
|
||||
|
||||
test('workspace growth does not duplicate IDs into every tool schema', () {
|
||||
final dispatcher = EditorToolDispatcher(host: _CatalogHost());
|
||||
final one = editorAgentTools({'first': dispatcher});
|
||||
final many = editorAgentTools({
|
||||
for (var i = 0; i < 100; i++) 'project/timeline-$i': dispatcher,
|
||||
});
|
||||
String schema(List<AgentTool> tools) =>
|
||||
jsonEncode(tools.map((t) => t.declaration).toList());
|
||||
expect(schema(many), schema(one));
|
||||
final operation = many.firstWhere(
|
||||
(tool) => tool.name != 'cutdex_workspaces',
|
||||
);
|
||||
expect(operation.validate.call({'workspaceId': 'missing'}), isNotNull);
|
||||
});
|
||||
test(
|
||||
'greeting loads runtime tools without the full editor catalog',
|
||||
() async {
|
||||
final tools = editorAgentTools({}, dynamicWorkspaces: true);
|
||||
const model = AgentModelSettings(id: 'custom-model');
|
||||
final builder = HarnessContextBuilder(
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
maxInputTokens: model.effectiveMaxInputTokens,
|
||||
maxOutputTokens: model.effectiveMaxOutputTokens,
|
||||
);
|
||||
final history = [AgentMessage(role: MessageRole.user, text: 'hi')];
|
||||
final input = builder.measureInput(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
history: history,
|
||||
tools: tools,
|
||||
);
|
||||
// Keep a real catalog regression rather than a small placeholder tool.
|
||||
expect(tools.length, greaterThan(20));
|
||||
final request = await builder.build(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
history: history,
|
||||
tools: [
|
||||
...tools,
|
||||
...builder.runtimeTools(
|
||||
() => SessionSnapshot(id: 's', history: history),
|
||||
tools,
|
||||
),
|
||||
],
|
||||
cancellation: CancellationToken(),
|
||||
);
|
||||
expect(
|
||||
request.tools.map((t) => t.name),
|
||||
unorderedEquals([
|
||||
'cutdex_workspaces',
|
||||
'tool_search',
|
||||
'read_tool_result',
|
||||
'update_plan',
|
||||
]),
|
||||
);
|
||||
expect(request.messages.single.text, 'hi');
|
||||
final projectedInput = builder.measureInput(
|
||||
system: request.system,
|
||||
history: request.messages,
|
||||
tools: request.tools,
|
||||
);
|
||||
expect(projectedInput, lessThan(input));
|
||||
expect(projectedInput, lessThan(model.effectiveMaxInputTokens * .8));
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,774 @@
|
||||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/assistant/agent_conversation_service.dart';
|
||||
import 'package:cutdex/features/assistant/agent_message_codec.dart';
|
||||
import 'package:cutdex/features/assistant/composer_document.dart';
|
||||
import 'package:cutdex/features/assistant/chat_state.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_runtime.dart';
|
||||
import 'package:cutdex/integrations/editor_tools.dart';
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Model implements ModelAdapter {
|
||||
int calls = 0;
|
||||
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken cancellation,
|
||||
) async* {
|
||||
calls++;
|
||||
yield ModelResponse(text: 'done');
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressModel implements ModelAdapter {
|
||||
int calls = 0;
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken token,
|
||||
) async* {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
switch (calls++) {
|
||||
case 0:
|
||||
yield ModelResponse(
|
||||
calls: [ToolCall(id: 'edit', name: 'clip_edit')],
|
||||
);
|
||||
case 1:
|
||||
yield ModelResponse(
|
||||
calls: [ToolCall(id: 'query', name: 'timeline_query')],
|
||||
);
|
||||
default:
|
||||
yield ModelResponse(text: 'done');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _ProgressSummary implements ContextSummarizer {
|
||||
@override
|
||||
String get source => 'test';
|
||||
@override
|
||||
Future<String> summarize(
|
||||
List<AgentMessage> messages,
|
||||
CancellationToken token,
|
||||
) async {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
return 'Completed: edit saved. Pending: query and verify.';
|
||||
}
|
||||
}
|
||||
|
||||
class _SlowPublishRepository extends ConversationRepository {
|
||||
_SlowPublishRepository(super.root);
|
||||
final entered = Completer<void>();
|
||||
final release = Completer<void>();
|
||||
@override
|
||||
Future<ConversationMetadata> publish(ConversationMetadata item) async {
|
||||
entered.complete();
|
||||
await release.future;
|
||||
return super.publish(item);
|
||||
}
|
||||
}
|
||||
|
||||
class _EarlyTextModel implements ModelAdapter {
|
||||
final emitted = Completer<void>();
|
||||
final finish = Completer<void>();
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken token,
|
||||
) async* {
|
||||
yield const TextDelta('early reply');
|
||||
emitted.complete();
|
||||
await finish.future;
|
||||
yield ModelResponse(text: 'early reply complete');
|
||||
}
|
||||
}
|
||||
|
||||
class _ExportThenDisconnect implements ModelAdapter {
|
||||
int calls = 0;
|
||||
bool retry = false;
|
||||
bool disconnected = true;
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken token,
|
||||
) async* {
|
||||
calls++;
|
||||
if (retry) {
|
||||
expect(request.tools, isEmpty);
|
||||
if (disconnected) {
|
||||
throw const ModelConnectionException(kind: ModelConnectionKind.socket);
|
||||
}
|
||||
expect(
|
||||
request.messages.any(
|
||||
(m) =>
|
||||
m.role == MessageRole.tool && m.text.contains('/test/export.mp4'),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
yield ModelResponse(text: 'Exported /test/export.mp4; edits saved.');
|
||||
} else if (calls == 1) {
|
||||
yield ModelResponse(
|
||||
calls: [ToolCall(id: 'export-once', name: 'project_export')],
|
||||
);
|
||||
} else {
|
||||
throw const ModelConnectionException(
|
||||
kind: ModelConnectionKind.socket,
|
||||
osErrorCode: 61,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test(
|
||||
'referenced timeline is loaded by ID without changing the run target',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('agent-timeline-ref-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final loadedRuns = <String>[];
|
||||
final loadedReferences = <String>[];
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => ConversationRepository(root),
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: _Model(),
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'test',
|
||||
),
|
||||
loadTools: (timelineId) async {
|
||||
loadedRuns.add(timelineId);
|
||||
return EditorAgentBinding(
|
||||
owner: Object(),
|
||||
tools: const [],
|
||||
ensureTimeline: (id) async => loadedReferences.add(id),
|
||||
);
|
||||
},
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
const reference = ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: 'project',
|
||||
id: 'other-timeline',
|
||||
label: '另一条时间线',
|
||||
);
|
||||
final result = await service.send(
|
||||
AgentComposerMessage.encodeDocument(const [
|
||||
ComposerSegment.text('看看 '),
|
||||
ComposerSegment.reference(reference),
|
||||
], const []),
|
||||
timelineId: 'current-timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(result.completed, isTrue);
|
||||
expect(loadedRuns, ['current-timeline']);
|
||||
expect(loadedReferences, ['other-timeline']);
|
||||
},
|
||||
);
|
||||
test('reply elapsed times survive reopening the conversation', () async {
|
||||
final root = await Directory.systemTemp.createTemp('agent-elapsed-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
AgentConversationService service(String? id) => AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: id,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: _Model(),
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'test',
|
||||
),
|
||||
loadTools: (_) async =>
|
||||
const EditorAgentBinding(owner: 'test', tools: []),
|
||||
);
|
||||
final original = service(null);
|
||||
addTearDown(original.dispose);
|
||||
final first = await original.send(
|
||||
'first',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
final second = await original.send(
|
||||
'second',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(first.elapsedMs, isNotNull);
|
||||
expect(second.elapsedMs, isNotNull);
|
||||
final id = second.conversation!.id;
|
||||
expect((await repository.read('project', id))!.responseDurationsMs, [
|
||||
first.elapsedMs,
|
||||
second.elapsedMs,
|
||||
]);
|
||||
original.dispose();
|
||||
final reopened = service(id);
|
||||
addTearDown(reopened.dispose);
|
||||
final replies = (await reopened.restore())!.messages
|
||||
.where((message) => !message.isUser)
|
||||
.toList();
|
||||
expect(replies.map((message) => message.elapsedMs), [
|
||||
first.elapsedMs,
|
||||
second.elapsedMs,
|
||||
]);
|
||||
});
|
||||
|
||||
test('export receipt survives disconnect, disk restart and summary-only retry without replay', () async {
|
||||
final root = await Directory.systemTemp.createTemp('export-recovery-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final model = _ExportThenDisconnect();
|
||||
var exports = 0;
|
||||
var toolLoads = 0;
|
||||
AgentConversationService service(String? id) => AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: id,
|
||||
loadRepository: () async => ConversationRepository(root),
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'test',
|
||||
),
|
||||
loadTools: (_) async {
|
||||
toolLoads++;
|
||||
return EditorAgentBinding(
|
||||
owner: Object(),
|
||||
tools: [
|
||||
AgentTool(
|
||||
name: 'project_export',
|
||||
description: 'export',
|
||||
parameters: {'type': 'object'},
|
||||
validate: (_) => null,
|
||||
execute: (_, _) async {
|
||||
exports++;
|
||||
return ToolResult(
|
||||
'Sequence exported',
|
||||
data: {
|
||||
'status': 'succeeded',
|
||||
'data': {'destination': '/test/export.mp4'},
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
final first = service(null);
|
||||
addTearDown(first.dispose);
|
||||
final result = await first.send(
|
||||
'export',
|
||||
timelineId: 't',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(result.exportReplyFailed, isTrue);
|
||||
expect(result.failure, RunFailure.connection);
|
||||
expect(exports, 1);
|
||||
final id = result.conversation!.id;
|
||||
first.dispose();
|
||||
final restarted = service(id);
|
||||
addTearDown(restarted.dispose);
|
||||
expect((await restarted.restore())!.exportReplyFailed, isTrue);
|
||||
model.retry = true;
|
||||
final stillOffline = await restarted.send(
|
||||
'Retry summary',
|
||||
summaryOnly: true,
|
||||
timelineId: 't',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(stillOffline.exportReplyFailed, isTrue);
|
||||
expect(exports, 1);
|
||||
expect(toolLoads, 1);
|
||||
restarted.dispose();
|
||||
final online = service(id);
|
||||
addTearDown(online.dispose);
|
||||
expect((await online.restore())!.exportReplyFailed, isTrue);
|
||||
model.disconnected = false;
|
||||
final recovered = await online.send(
|
||||
'Retry summary',
|
||||
summaryOnly: true,
|
||||
timelineId: 't',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(recovered.completed, isTrue);
|
||||
expect(recovered.exportReplyFailed, isFalse);
|
||||
expect(recovered.response, contains('/test/export.mp4'));
|
||||
expect(exports, 1);
|
||||
expect(toolLoads, 1);
|
||||
expect((await online.restore())!.exportReplyFailed, isFalse);
|
||||
});
|
||||
|
||||
test('service exposes editing, compaction and verification phases', () async {
|
||||
final root = await Directory.systemTemp.createTemp('agent-progress-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: _ProgressModel(),
|
||||
contextBuilder: ContextBuilder(
|
||||
maxInputTokens: 5000,
|
||||
summarizer: _ProgressSummary(),
|
||||
),
|
||||
revision: 0,
|
||||
sessionIdentity: 'test',
|
||||
),
|
||||
loadTools: (_) async => EditorAgentBinding(
|
||||
owner: Object(),
|
||||
tools: [
|
||||
for (final name in ['clip_edit', 'timeline_query'])
|
||||
AgentTool(
|
||||
name: name,
|
||||
description: name,
|
||||
parameters: {'type': 'object'},
|
||||
validate: (_) => null,
|
||||
execute: (_, _) async => ToolResult(
|
||||
name == 'clip_edit' ? 'saved ' * 5000 : 'verified',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
final activities = <AgentChatActivity>[];
|
||||
final subscription = service.changes.listen(
|
||||
(_) => activities.add(service.activity),
|
||||
);
|
||||
addTearDown(subscription.cancel);
|
||||
final result = await service.send(
|
||||
'edit then verify',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(result.completed, isTrue);
|
||||
expect(
|
||||
activities,
|
||||
containsAllInOrder([
|
||||
AgentChatActivity.editing,
|
||||
AgentChatActivity.compacting,
|
||||
AgentChatActivity.verifying,
|
||||
]),
|
||||
);
|
||||
expect(service.busy, isFalse);
|
||||
final reports = await Directory('${root.path}/diagnostics').list().toList();
|
||||
expect(reports, hasLength(1));
|
||||
final encoded = await File(reports.single.path).readAsString();
|
||||
final report = jsonDecode(encoded) as Map<String, dynamic>;
|
||||
expect(report['outcome'], 'completed');
|
||||
expect(report['preparationUs'], isA<int>());
|
||||
final stages = (report['runs'][0]['spans'] as List).map((s) => s['stage']);
|
||||
expect(
|
||||
stages,
|
||||
containsAll(['model', 'tool', 'save', 'summary', 'prepare']),
|
||||
);
|
||||
expect(encoded, isNot(contains('edit then verify')));
|
||||
});
|
||||
|
||||
test('default runtime sends with all real editor tools attached', () async {
|
||||
final model = _Model();
|
||||
final root = await Directory.systemTemp.createTemp('full-catalog-send-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) async => EditorAgentBinding(
|
||||
owner: Object(),
|
||||
tools: editorAgentTools({}, dynamicWorkspaces: true),
|
||||
),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
final outcome = await service.send(
|
||||
'hi',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(outcome.completed, isTrue);
|
||||
expect(outcome.response, 'done');
|
||||
expect(model.calls, 1);
|
||||
expect(await repository.list('project'), hasLength(1));
|
||||
});
|
||||
|
||||
test(
|
||||
'unfinished runs require explicit resume without appending another prompt',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('recovered-chat-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final item = await repository.begin(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
providerId: 'model',
|
||||
modelId: 'model',
|
||||
title: 'interrupted',
|
||||
);
|
||||
await repository
|
||||
.store(item)
|
||||
.save(
|
||||
SessionSnapshot(
|
||||
id: item.id,
|
||||
runId: 'interrupted',
|
||||
status: RunStatus.paused,
|
||||
turns: 20,
|
||||
maxTurns: 20,
|
||||
history: [AgentMessage(role: MessageRole.user, text: 'old task')],
|
||||
),
|
||||
expectedRevision: null,
|
||||
);
|
||||
await repository.publish(item);
|
||||
final model = _Model();
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: item.id,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) async =>
|
||||
// Keep a fresh owner for each tool binding.
|
||||
// ignore: prefer_const_constructors
|
||||
EditorAgentBinding(owner: Object(), tools: const []),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
AgentConversationPreparation? preparation;
|
||||
final blocked = await service.send(
|
||||
'new task',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(blocked.recoveryRequired, isTrue);
|
||||
expect(model.calls, 0);
|
||||
final outcome = await service.send(
|
||||
'continue task',
|
||||
resumeOnly: true,
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (value) => preparation = value,
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(outcome.completed, isTrue);
|
||||
expect(model.calls, 1);
|
||||
expect(preparation!.messages.map((m) => m.text), ['old task']);
|
||||
expect(
|
||||
(await repository.store(item).read(item.id))!.history
|
||||
.where((m) => m.role == MessageRole.user),
|
||||
hasLength(1),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'stream listener is attached before slow conversation publication',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('early-text-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = _SlowPublishRepository(root);
|
||||
final model = _EarlyTextModel();
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'test',
|
||||
),
|
||||
loadTools: (_) async =>
|
||||
// Keep a fresh owner for each tool binding.
|
||||
// ignore: prefer_const_constructors
|
||||
EditorAgentBinding(owner: Object(), tools: const []),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
final deltas = <String>[];
|
||||
final sending = service.send(
|
||||
'hello',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: deltas.add,
|
||||
);
|
||||
await repository.entered.future;
|
||||
await model.emitted.future;
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final beforePublication = List<String>.of(deltas);
|
||||
repository.release.complete();
|
||||
model.finish.complete();
|
||||
final outcome = await sending;
|
||||
expect(beforePublication, ['early reply']);
|
||||
expect(outcome.response, 'early reply complete');
|
||||
expect(outcome.completed, true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'unconfirmed write recovery is reported without replay or a new prompt',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('unknown-edit-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final item = await repository.begin(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
providerId: 'model',
|
||||
modelId: 'model',
|
||||
title: 'interrupted',
|
||||
);
|
||||
final call = ToolCall(id: 'write', name: 'edit');
|
||||
await repository
|
||||
.store(item)
|
||||
.save(
|
||||
SessionSnapshot(
|
||||
id: item.id,
|
||||
runId: 'old',
|
||||
status: RunStatus.running,
|
||||
history: [
|
||||
AgentMessage(role: MessageRole.user, text: 'edit'),
|
||||
AgentMessage(role: MessageRole.assistant, calls: [call]),
|
||||
],
|
||||
pending: [
|
||||
CallRecord(
|
||||
call: call,
|
||||
operationId: 'stable',
|
||||
status: CallStatus.started,
|
||||
),
|
||||
],
|
||||
),
|
||||
expectedRevision: null,
|
||||
);
|
||||
await repository.publish(item);
|
||||
final model = _Model();
|
||||
var writes = 0;
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: item.id,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) async => EditorAgentBinding(
|
||||
owner: Object(),
|
||||
tools: [
|
||||
AgentTool(
|
||||
name: 'edit',
|
||||
description: 'edit',
|
||||
parameters: {'type': 'object'},
|
||||
validate: (_) => null,
|
||||
execute: (_, _) async {
|
||||
writes++;
|
||||
return ToolResult('saved');
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
// A fresh process must surface the uncertain write before another send.
|
||||
expect((await service.restore())!.recoveryRequired, isTrue);
|
||||
final result = await service.send(
|
||||
'continue',
|
||||
resumeOnly: true,
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
expect(result.recoveryRequired, true);
|
||||
expect(result.completed, false);
|
||||
expect(model.calls, 0);
|
||||
expect(writes, 0);
|
||||
final stored = (await repository.store(item).read(item.id))!;
|
||||
expect(stored.status, RunStatus.waiting);
|
||||
expect((await service.restore())!.recoveryRequired, isTrue);
|
||||
expect(
|
||||
stored.history.where((m) => m.role == MessageRole.user),
|
||||
hasLength(1),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'restored history hides final replies rejected by artifact verification',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('verified-chat-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final item = await repository.begin(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
providerId: 'model',
|
||||
modelId: 'model',
|
||||
title: 'verification',
|
||||
);
|
||||
await repository
|
||||
.store(item)
|
||||
.save(
|
||||
SessionSnapshot(
|
||||
id: item.id,
|
||||
runId: 'run',
|
||||
status: RunStatus.paused,
|
||||
completionEvidence: {
|
||||
'result': {'isError': true},
|
||||
},
|
||||
history: [
|
||||
AgentMessage(role: MessageRole.user, text: 'Translate'),
|
||||
AgentMessage(
|
||||
role: MessageRole.assistant,
|
||||
text: 'Done prematurely',
|
||||
),
|
||||
AgentMessage(
|
||||
role: MessageRole.user,
|
||||
text: '[Runtime artifact verification, not a new user request] missing cues',
|
||||
runtimeNotice: true,
|
||||
),
|
||||
AgentMessage(
|
||||
role: MessageRole.assistant,
|
||||
text: 'Still not verified',
|
||||
),
|
||||
],
|
||||
),
|
||||
expectedRevision: null,
|
||||
);
|
||||
await repository.publish(item);
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: item.id,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: _Model(),
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) async =>
|
||||
// Keep a fresh owner for each tool binding.
|
||||
// ignore: prefer_const_constructors
|
||||
EditorAgentBinding(owner: Object(), tools: const []),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
expect((await service.restore())!.messages.map((m) => m.text), [
|
||||
'Translate',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test('budget preflight creates no conversation or model request', () async {
|
||||
final model = _Model();
|
||||
final root = await Directory.systemTemp.createTemp('budget-preflight-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(maxInputTokens: 1),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) async =>
|
||||
// Keep a fresh owner for each tool binding.
|
||||
// ignore: prefer_const_constructors
|
||||
EditorAgentBinding(owner: Object(), tools: const []),
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
await expectLater(
|
||||
service.send(
|
||||
'hello',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
),
|
||||
throwsA(
|
||||
isA<AgentConversationException>().having(
|
||||
(e) => e.failure,
|
||||
'failure',
|
||||
AgentConversationFailure.contextBudget,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(model.calls, 0);
|
||||
expect(await repository.list('project'), isEmpty);
|
||||
});
|
||||
|
||||
for (final dispose in [false, true]) {
|
||||
test(
|
||||
'${dispose ? 'dispose' : 'cancel'} during preparation stops before opening storage',
|
||||
() async {
|
||||
final model = _Model();
|
||||
final entered = Completer<void>();
|
||||
final binding = Completer<EditorAgentBinding>();
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'conversation-test-',
|
||||
);
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final repository = ConversationRepository(root);
|
||||
final service = AgentConversationService(
|
||||
projectId: 'project',
|
||||
conversationId: null,
|
||||
loadRepository: () async => repository,
|
||||
loadRuntime: (_) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: 0,
|
||||
sessionIdentity: 'model',
|
||||
),
|
||||
loadTools: (_) {
|
||||
entered.complete();
|
||||
return binding.future;
|
||||
},
|
||||
);
|
||||
addTearDown(service.dispose);
|
||||
final sending = service.send(
|
||||
'hello',
|
||||
timelineId: 'timeline',
|
||||
onPrepared: (_) {},
|
||||
onTextDelta: (_) {},
|
||||
);
|
||||
// Disposal may reject the caller; neither path may start more work.
|
||||
final settled = sending.then<void>((_) {}, onError: (Object _) {});
|
||||
await entered.future;
|
||||
if (dispose) {
|
||||
service.dispose();
|
||||
} else {
|
||||
await service.cancel();
|
||||
}
|
||||
binding.complete(const EditorAgentBinding(owner: 'test', tools: []));
|
||||
await settled;
|
||||
expect(await repository.list('project'), isEmpty);
|
||||
expect(model.calls, 0);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/assistant/agent_attachment_card.dart';
|
||||
import 'package:cutdex/integrations/runtime/media_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('a dropped image uses its pixels in the attachment preview', (
|
||||
tester,
|
||||
) async {
|
||||
late AssetDocument asset;
|
||||
late MediaThumbnails thumbnails;
|
||||
final preview = await tester.runAsync(() async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex-image-preview-',
|
||||
);
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final file = File('${directory.path}/picture.png');
|
||||
await file.writeAsBytes(
|
||||
base64Decode(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==',
|
||||
),
|
||||
);
|
||||
asset = AssetDocument(
|
||||
id: 'image-1',
|
||||
name: 'picture.png',
|
||||
storage: AssetStorage.external,
|
||||
location: file.uri.toString(),
|
||||
metadata: const {'kind': 'image'},
|
||||
);
|
||||
thumbnails = MediaThumbnails(
|
||||
loadMedia: <T>(asset, action) =>
|
||||
action(MediaReference(id: asset.id, uri: file.uri, isImage: true)),
|
||||
);
|
||||
return thumbnails.load(asset);
|
||||
});
|
||||
expect(preview, isNotNull);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [mediaThumbnailsProvider.overrideWithValue(thumbnails)],
|
||||
child: MaterialApp(
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(body: AgentAttachmentCard(asset: asset)),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 20)),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Image), findsOneWidget);
|
||||
expect(find.text('picture.png'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'package:cutdex/features/assistant/agent_media_attachments.dart';
|
||||
import 'package:cutdex/features/assistant/agent_message_codec.dart';
|
||||
import 'package:cutdex/features/assistant/composer_document.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('inline references coexist with attachment cards', () {
|
||||
const reference = ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: 'project',
|
||||
id: 'timeline-2',
|
||||
label: '另一条时间线',
|
||||
);
|
||||
const segments = [
|
||||
ComposerSegment.text('查看 '),
|
||||
ComposerSegment.reference(reference),
|
||||
];
|
||||
final encoded = AgentComposerMessage.encodeDocument(segments, const [
|
||||
AgentMediaAttachment(id: 'media-1', name: '片段.mp4', kind: 'video'),
|
||||
]);
|
||||
final decoded = AgentComposerMessage.decode(encoded);
|
||||
expect(decoded.text, '查看 另一条时间线');
|
||||
expect(decoded.references.single.id, 'timeline-2');
|
||||
expect(decoded.segments, segments);
|
||||
expect(decoded.attachments.single.id, 'media-1');
|
||||
expect(encoded, contains('"projectId":"project"'));
|
||||
});
|
||||
test('media references survive encode and decode without leaking into the chat text', () {
|
||||
const attachments = [
|
||||
AgentMediaAttachment(id: 'media-1', name: '画面.mp4', kind: 'video'),
|
||||
AgentMediaAttachment(id: 'media-2', name: '声音.mp3', kind: 'audio'),
|
||||
];
|
||||
final prompt = AgentComposerMessage.encodeDocument(const [
|
||||
ComposerSegment.text('剪辑这两个素材'),
|
||||
], attachments);
|
||||
expect(prompt, contains('media-1'));
|
||||
expect(prompt, contains('media-2'));
|
||||
final decoded = AgentComposerMessage.decode(prompt);
|
||||
expect(decoded.text, '剪辑这两个素材');
|
||||
expect(decoded.attachments.map((item) => item.name), ['画面.mp4', '声音.mp3']);
|
||||
});
|
||||
|
||||
test('attachment-only and ordinary chat text remain displayable', () {
|
||||
const attachment = AgentMediaAttachment(
|
||||
id: 'a',
|
||||
name: '片段.mov',
|
||||
kind: 'video',
|
||||
);
|
||||
final decoded = AgentComposerMessage.decode(
|
||||
AgentComposerMessage.encodeDocument(const [], [attachment]),
|
||||
);
|
||||
expect(decoded.text, isEmpty);
|
||||
expect(decoded.attachments.single.id, 'a');
|
||||
expect(AgentComposerMessage.decode('普通文本').text, '普通文本');
|
||||
expect(
|
||||
AgentComposerMessage.decode('[Cutdex composer message] broken').text,
|
||||
'[Cutdex composer message] broken',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'damaged message data stays visible without partial resource references',
|
||||
() {
|
||||
for (final data in [
|
||||
'broken',
|
||||
'{"text":"hello","attachments":[{"id":"a","name":"A",'
|
||||
'"kind":"video"}]}',
|
||||
'{"text":"hello","attachments":[{"id":"a"}]}',
|
||||
'{"text":"hello","segments":[{"runtimeType":"unknown"}]}',
|
||||
'{"text":"hello","segments":[{"runtimeType":"reference",'
|
||||
'"value":{"kind":"unknown","projectId":"p","id":"a",'
|
||||
'"label":"a"}}]}',
|
||||
]) {
|
||||
final message = '[Cutdex composer message] $data\n\nInstructions';
|
||||
final decoded = AgentComposerMessage.decode(message);
|
||||
expect(decoded.text, message);
|
||||
expect(decoded.references, isEmpty);
|
||||
expect(decoded.attachments, isEmpty);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/assistant/agent_chat_panel.dart';
|
||||
import 'package:cutdex/features/assistant/agent_conversation_service.dart';
|
||||
import 'package:cutdex/features/assistant/chat_controller.dart';
|
||||
import 'package:cutdex/features/settings/agent_settings_panel.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_credentials.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_provider.dart';
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex/integrations/editor_tools.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Settings implements AgentSettingsRepository {
|
||||
AgentSettingsState value = const AgentSettingsState(
|
||||
enabled: true,
|
||||
selectedProviderId: 'one',
|
||||
selectedModelId: 'model-one',
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'one',
|
||||
name: 'Provider One',
|
||||
apiType: 'openAiResponses',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
models: [
|
||||
AgentModelSettings(id: 'model-one'),
|
||||
AgentModelSettings(id: 'model-two'),
|
||||
],
|
||||
),
|
||||
AgentProviderSettings(
|
||||
id: 'off',
|
||||
name: 'Disabled Provider',
|
||||
apiType: 'openAiResponses',
|
||||
enabled: false,
|
||||
baseUrl: 'https://example.com/v1',
|
||||
models: [AgentModelSettings(id: 'hidden-model')],
|
||||
),
|
||||
AgentProviderSettings(
|
||||
id: 'two',
|
||||
name: 'Provider Two',
|
||||
apiType: 'anthropicMessages',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
models: [AgentModelSettings(id: 'claude-test')],
|
||||
),
|
||||
],
|
||||
);
|
||||
@override
|
||||
Future<AgentSettingsState> load() async => value;
|
||||
@override
|
||||
Future<void> save(AgentSettingsState settings) async => value = settings;
|
||||
}
|
||||
|
||||
class _Model implements ModelAdapter {
|
||||
final requests = <ModelRequest>[];
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken cancellation,
|
||||
) async* {
|
||||
requests.add(request);
|
||||
yield ModelResponse(text: 'reply');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
late Directory root;
|
||||
late ConversationRepository repository;
|
||||
late _Settings settings;
|
||||
late _Model model;
|
||||
late ProviderContainer container;
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('model-picker-');
|
||||
repository = ConversationRepository(root);
|
||||
settings = _Settings();
|
||||
model = _Model();
|
||||
container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(settings),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
conversationRepositoryProvider.overrideWith((ref) async => repository),
|
||||
agentConversationToolsResolverProvider.overrideWithValue(
|
||||
(_, _) async => const EditorAgentBinding(owner: 'test', tools: []),
|
||||
),
|
||||
agentConversationRuntimeResolverProvider.overrideWithValue(
|
||||
(item) async => AgentRuntime(
|
||||
model: model,
|
||||
contextBuilder: ContextBuilder(),
|
||||
revision: settings.value.revision,
|
||||
sessionIdentity:
|
||||
'${item?.providerId ?? settings.value.selectedProviderId}/${item?.modelId ?? settings.value.selectedModelId}',
|
||||
providerId: item?.providerId ?? settings.value.selectedProviderId,
|
||||
modelId: item?.modelId ?? settings.value.selectedModelId,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
});
|
||||
tearDown(() async {
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
Future<void> panel(WidgetTester tester, {String? conversationId}) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1000, 760));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 360,
|
||||
child: AgentChatPanel(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
conversationId: conversationId,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
if (conversationId != null) {
|
||||
final provider = chatControllerProvider(
|
||||
'project',
|
||||
conversationId: conversationId,
|
||||
);
|
||||
for (
|
||||
var i = 0;
|
||||
i < 50 && container.read(provider).conversation == null;
|
||||
i++
|
||||
) {
|
||||
await tester.runAsync(
|
||||
() => Future<void>.delayed(const Duration(milliseconds: 10)),
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
}
|
||||
|
||||
Future<ConversationMetadata> existing() async {
|
||||
final item = await repository.begin(
|
||||
projectId: 'project',
|
||||
timelineId: 'timeline',
|
||||
providerId: 'one',
|
||||
modelId: 'model-one',
|
||||
title: 'Original',
|
||||
);
|
||||
final manager = SessionManager(model: model, store: repository.store(item));
|
||||
await manager.create(id: item.id, system: 'policy');
|
||||
await (await manager.prompt(item.id, 'original-context')).done;
|
||||
return repository.publish(item);
|
||||
}
|
||||
|
||||
testWidgets('picker groups available models and remembers the selection', (
|
||||
tester,
|
||||
) async {
|
||||
await panel(tester);
|
||||
expect(find.text('model-one'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('agent-model-picker')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Provider One'), findsOneWidget);
|
||||
expect(find.text('Provider Two'), findsOneWidget);
|
||||
expect(find.text('hidden-model'), findsNothing);
|
||||
expect(find.text('Disabled Provider'), findsNothing);
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.text('claude-test'));
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(settings.value.selectedProviderId, 'two');
|
||||
expect(settings.value.selectedModelId, 'claude-test');
|
||||
expect(find.text('claude-test'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
testWidgets(
|
||||
'missing configuration opens the Agent tab and keeps the input usable',
|
||||
(tester) async {
|
||||
settings.value = const AgentSettingsState();
|
||||
container.invalidate(agentSettingsProvider);
|
||||
await panel(tester);
|
||||
await tester.enterText(find.byType(TextField), 'draft');
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester
|
||||
.widget<IconButton>(
|
||||
find.widgetWithIcon(IconButton, Icons.arrow_upward),
|
||||
)
|
||||
.onPressed,
|
||||
isNull,
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('agent-configure-model')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(AgentSettingsPanel), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
testWidgets(
|
||||
'an existing conversation stays pinned and disabled providers block sending',
|
||||
(tester) async {
|
||||
final item = (await tester.runAsync(existing))!;
|
||||
settings.value = AgentSettingsState(
|
||||
enabled: true,
|
||||
providers: settings.value.providers,
|
||||
selectedProviderId: 'two',
|
||||
selectedModelId: 'claude-test',
|
||||
);
|
||||
await panel(tester, conversationId: item.id);
|
||||
expect(find.text('model-one'), findsOneWidget);
|
||||
expect(find.text('claude-test'), findsNothing);
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.setProviderEnabled('one', false);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Select model'), findsOneWidget);
|
||||
expect(
|
||||
find.text(
|
||||
'The model for this conversation is unavailable. Select another model to start a new conversation.',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.enterText(find.byType(TextField), 'draft');
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester
|
||||
.widget<IconButton>(
|
||||
find.widgetWithIcon(IconButton, Icons.arrow_upward),
|
||||
)
|
||||
.onPressed,
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
(await tester.runAsync(() => repository.read('project', item.id)))!
|
||||
.providerId,
|
||||
'one',
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
test(
|
||||
'explicit model changes start a new conversation without old context',
|
||||
() async {
|
||||
final item = await existing();
|
||||
final provider = chatControllerProvider(
|
||||
'project',
|
||||
conversationId: item.id,
|
||||
);
|
||||
final subscription = container.listen(provider, (_, _) {});
|
||||
addTearDown(subscription.close);
|
||||
for (
|
||||
var i = 0;
|
||||
i < 50 && container.read(provider).conversation == null;
|
||||
i++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
}
|
||||
expect(container.read(provider).conversation?.id, item.id);
|
||||
final controller = container.read(provider.notifier);
|
||||
await controller.selectModel('two', 'claude-test');
|
||||
expect(container.read(provider).messages, isEmpty);
|
||||
await controller.send('new-context', timelineId: 'timeline');
|
||||
final state = container.read(provider);
|
||||
expect(state.error, isNull);
|
||||
expect(state.conversation!.id, isNot(item.id));
|
||||
expect(state.conversation!.modelId, 'claude-test');
|
||||
expect(
|
||||
model.requests.last.messages.any(
|
||||
(m) => m.text.contains('original-context'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
expect((await repository.read('project', item.id))!.modelId, 'model-one');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,301 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/settings/agent_settings_panel.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_credentials.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_models.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Repository implements AgentSettingsRepository {
|
||||
AgentSettingsState value = const AgentSettingsState();
|
||||
|
||||
@override
|
||||
Future<AgentSettingsState> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(AgentSettingsState settings) async => value = settings;
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('provider model fields stack in a narrow settings viewport', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(390, 640));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(_Repository()),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(
|
||||
body: AgentSettingsPanel(
|
||||
contentPadding: AppSettingsMetrics.contentPadding,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Add provider'));
|
||||
await tester.pumpAndSettle();
|
||||
final model = tester.getRect(find.byKey(const Key('agent-model-id-0')));
|
||||
final budget = tester.getRect(
|
||||
find.byKey(const Key('agent-model-context-0')),
|
||||
);
|
||||
expect(budget.top, greaterThan(model.bottom));
|
||||
expect(budget.left, model.left);
|
||||
expect(budget.width, model.width);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('inline Provider form has one stable scroll region', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.binding.setSurfaceSize(const Size(1000, 420));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(_Repository()),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(body: AgentSettingsPanel()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('Add provider'));
|
||||
await tester.pumpAndSettle();
|
||||
final scroll = find.byKey(const Key('agent-settings-scroll'));
|
||||
final controller = tester.widget<SingleChildScrollView>(scroll).controller!;
|
||||
final extent = controller.position.maxScrollExtent;
|
||||
expect(extent, greaterThan(0));
|
||||
expect(find.byType(Scrollbar), findsOneWidget);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
await tester.drag(scroll, const Offset(0, -80));
|
||||
await tester.pumpAndSettle();
|
||||
final offset = controller.offset;
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
expect(controller.offset, offset);
|
||||
expect(controller.position.maxScrollExtent, extent);
|
||||
}
|
||||
// Desktop edge scrolling must not stretch the viewport or thumb.
|
||||
controller.jumpTo(extent);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.drag(scroll, const Offset(0, -160));
|
||||
await tester.pump();
|
||||
expect(controller.offset, extent);
|
||||
expect(controller.position.maxScrollExtent, extent);
|
||||
await tester.pumpAndSettle();
|
||||
controller.jumpTo(0);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.drag(scroll, const Offset(0, 160));
|
||||
await tester.pump();
|
||||
expect(controller.offset, 0);
|
||||
expect(controller.position.maxScrollExtent, extent);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('agent-provider-back')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.offset, 0);
|
||||
expect(controller.position.maxScrollExtent, 0);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
test('all supported non-English locales translate Agent settings', () {
|
||||
final english = lookupAppLocalizations(const Locale('en'));
|
||||
for (final languageCode in [
|
||||
'de',
|
||||
'es',
|
||||
'fr',
|
||||
'it',
|
||||
'ja',
|
||||
'ko',
|
||||
'pt',
|
||||
'ru',
|
||||
]) {
|
||||
final localized = lookupAppLocalizations(Locale(languageCode));
|
||||
expect(
|
||||
localized.agentAddProvider,
|
||||
isNot(english.agentAddProvider),
|
||||
reason: languageCode,
|
||||
);
|
||||
expect(
|
||||
localized.agentConversationLocation,
|
||||
isNot(english.agentConversationLocation),
|
||||
reason: languageCode,
|
||||
);
|
||||
expect(
|
||||
localized.agentTrash,
|
||||
isNot(english.agentTrash),
|
||||
reason: languageCode,
|
||||
);
|
||||
expect(
|
||||
localized.agentDeleteProviderDescription('Example'),
|
||||
contains('Example'),
|
||||
reason: languageCode,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('renders Agent settings in Chinese', (tester) async {
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(_Repository()),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
locale: const Locale('zh'),
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(body: AgentSettingsPanel()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('自定义 Provider'), findsNothing);
|
||||
expect(find.text('添加 Provider'), findsOneWidget);
|
||||
expect(find.text('请先添加 Provider,再启用助手。'), findsNothing);
|
||||
expect(find.byType(Switch), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('adds provider inline and returns to the provider list', (
|
||||
tester,
|
||||
) async {
|
||||
final repository = _Repository();
|
||||
final credentials = MemoryAgentCredentialStore();
|
||||
await tester.binding.setSurfaceSize(const Size(1000, 760));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(body: AgentSettingsPanel()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
await tester.tap(find.text('Add provider'));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 70));
|
||||
expect(
|
||||
tester
|
||||
.widget<FadeTransition>(
|
||||
find.byKey(const Key('agent-provider-page-transition')),
|
||||
)
|
||||
.opacity
|
||||
.value,
|
||||
lessThan(1),
|
||||
);
|
||||
expect(find.byKey(const Key('agent-provider-list')), findsOneWidget);
|
||||
expect(find.byKey(const Key('agent-provider-editor')), findsNothing);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Dialog), findsNothing);
|
||||
expect(find.byKey(const Key('agent-provider-editor')), findsOneWidget);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-provider-name')),
|
||||
'Unsaved',
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('agent-provider-back')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('agent-provider-list')), findsOneWidget);
|
||||
expect(repository.value.providers, isEmpty);
|
||||
await tester.tap(find.text('Add provider'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-provider-name')),
|
||||
'Local provider',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-provider-base-url')),
|
||||
'http://127.0.0.1:11434/v1',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-provider-api-key')),
|
||||
'secret',
|
||||
);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-model-id-0')),
|
||||
'local-model',
|
||||
);
|
||||
await tester.tap(find.text('Save provider'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('Local provider'), findsOneWidget);
|
||||
expect(find.byKey(const Key('agent-provider-list')), findsOneWidget);
|
||||
expect(find.byKey(const Key('agent-provider-editor')), findsNothing);
|
||||
expect(repository.value.providers.single.models.single.id, 'local-model');
|
||||
expect(
|
||||
await credentials.read(repository.value.providers.single.credentialId!),
|
||||
'secret',
|
||||
);
|
||||
|
||||
expect(find.byType(Switch), findsOneWidget);
|
||||
final providerId = repository.value.providers.single.id;
|
||||
await tester.tap(find.byKey(ValueKey('agent-provider-edit-$providerId')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester
|
||||
.widget<TextFormField>(find.byKey(const Key('agent-provider-name')))
|
||||
.controller!
|
||||
.text,
|
||||
'Local provider',
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<TextFormField>(
|
||||
find.byKey(const Key('agent-provider-api-key')),
|
||||
)
|
||||
.controller!
|
||||
.text,
|
||||
isEmpty,
|
||||
);
|
||||
expect(find.text('Leave blank to keep the saved key.'), findsOneWidget);
|
||||
await tester.enterText(
|
||||
find.byKey(const Key('agent-provider-name')),
|
||||
'Edited provider',
|
||||
);
|
||||
await tester.ensureVisible(find.text('Save provider'));
|
||||
await tester.tap(find.text('Save provider'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(repository.value.providers.length, 1);
|
||||
expect(repository.value.providers.single.id, providerId);
|
||||
expect(repository.value.providers.single.name, 'Edited provider');
|
||||
expect(
|
||||
await credentials.read(repository.value.providers.single.credentialId!),
|
||||
'secret',
|
||||
);
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
expect(repository.value.providers.single.enabled, false);
|
||||
expect(repository.value.selectedProviderId, isNull);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,435 @@
|
||||
import 'package:cutdex/integrations/agent/agent_runtime_factory.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_credentials.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_models.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_settings.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _MemoryRepository implements AgentSettingsRepository {
|
||||
AgentSettingsState value = const AgentSettingsState();
|
||||
|
||||
@override
|
||||
Future<AgentSettingsState> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(AgentSettingsState settings) async => value = settings;
|
||||
}
|
||||
|
||||
class _FailingDeleteCredentials extends MemoryAgentCredentialStore {
|
||||
@override
|
||||
Future<void> delete(String id) => throw StateError('keychain unavailable');
|
||||
}
|
||||
|
||||
class _FailingSaveRepository extends _MemoryRepository {
|
||||
_FailingSaveRepository(this.failure);
|
||||
|
||||
final Object failure;
|
||||
|
||||
@override
|
||||
Future<void> save(AgentSettingsState settings) => Future.error(failure);
|
||||
}
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'rejects positive input budget too small for mandatory instructions',
|
||||
() async {
|
||||
final repository = _MemoryRepository();
|
||||
final credentials = MemoryAgentCredentialStore();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
await expectLater(
|
||||
container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
name: 'small',
|
||||
apiType: AgentApiType.openAiResponses,
|
||||
baseUrl: 'https://example.com/v1',
|
||||
apiKey: 'secret',
|
||||
models: const [
|
||||
AgentModelSettings(
|
||||
id: 'model',
|
||||
contextWindow: 8192,
|
||||
maxOutputTokens: 8191,
|
||||
),
|
||||
],
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(repository.value.providers, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
for (final apiType in AgentApiType.values) {
|
||||
test(
|
||||
'${apiType.name} persists and constructs the matching adapter',
|
||||
() async {
|
||||
final repository = _MemoryRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
final settings = container.read(agentSettingsProvider.notifier);
|
||||
await settings.upsertProvider(
|
||||
id: 'provider',
|
||||
name: 'Provider',
|
||||
apiType: apiType,
|
||||
baseUrl: 'https://api.example.com/v1',
|
||||
apiKey: 'test-only',
|
||||
models: const [AgentModelSettings(id: 'test-model')],
|
||||
);
|
||||
await settings.setEnabled(true);
|
||||
expect(repository.value.providers.single.apiType, apiType.name);
|
||||
final runtime = await container.read(agentRuntimeProvider.future);
|
||||
expect(runtime, isNotNull);
|
||||
switch (apiType) {
|
||||
case AgentApiType.openAiChatCompletions:
|
||||
expect(runtime!.model, isA<OpenAiChatAdapter>());
|
||||
case AgentApiType.openAiResponses:
|
||||
expect(runtime!.model, isA<OpenAiResponsesAdapter>());
|
||||
case AgentApiType.anthropicMessages:
|
||||
expect(runtime!.model, isA<AnthropicMessagesAdapter>());
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'provider toggles normalize selection and block disabled runtimes',
|
||||
() async {
|
||||
final repository = _MemoryRepository();
|
||||
final credentials = MemoryAgentCredentialStore();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
final settings = container.read(agentSettingsProvider.notifier);
|
||||
for (final id in ['one', 'two']) {
|
||||
await settings.upsertProvider(
|
||||
id: id,
|
||||
name: id,
|
||||
apiType: AgentApiType.openAiResponses,
|
||||
baseUrl: 'https://example.com/v1',
|
||||
apiKey: 'secret-$id',
|
||||
models: [AgentModelSettings(id: 'model-$id')],
|
||||
);
|
||||
}
|
||||
expect(repository.value.enabled, true);
|
||||
expect(repository.value.selectedProviderId, 'one');
|
||||
await settings.setProviderEnabled('one', false);
|
||||
expect(repository.value.selectedProviderId, 'two');
|
||||
expect(repository.value.selectedModelId, 'model-two');
|
||||
await expectLater(
|
||||
settings.selectModel('one', 'model-one'),
|
||||
throwsArgumentError,
|
||||
);
|
||||
final factory = AgentRuntimeFactory(credentials);
|
||||
expect(
|
||||
await factory.createFor(
|
||||
repository.value,
|
||||
providerId: 'one',
|
||||
modelId: 'model-one',
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
await settings.upsertProvider(
|
||||
id: 'one',
|
||||
name: 'Edited',
|
||||
apiType: AgentApiType.anthropicMessages,
|
||||
baseUrl: 'https://edited.example/v1',
|
||||
models: const [AgentModelSettings(id: 'edited-model')],
|
||||
);
|
||||
expect(
|
||||
repository.value.providers.where((p) => p.id == 'one').single.enabled,
|
||||
false,
|
||||
);
|
||||
expect(await credentials.read('cutdex-agent-provider-one'), 'secret-one');
|
||||
await settings.setProviderEnabled('two', false);
|
||||
expect(repository.value.selectedProviderId, isNull);
|
||||
expect(repository.value.selectedModelId, isNull);
|
||||
expect(await factory.create(repository.value), isNull);
|
||||
await settings.setProviderEnabled('one', true);
|
||||
expect(repository.value.selectedProviderId, 'one');
|
||||
expect(repository.value.selectedModelId, 'edited-model');
|
||||
expect(
|
||||
(await factory.create(repository.value))!.model,
|
||||
isA<AnthropicMessagesAdapter>(),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'loading preserves disabled Agent settings until a model is selected',
|
||||
() async {
|
||||
final repository = _MemoryRepository();
|
||||
repository.value = const AgentSettingsState(
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'provider',
|
||||
name: 'Provider',
|
||||
apiType: 'openAiResponses',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
models: [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
],
|
||||
selectedProviderId: 'provider',
|
||||
selectedModelId: 'model',
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
expect(repository.value.enabled, false);
|
||||
expect(repository.value.revision, 0);
|
||||
final runtime = container.listen(agentRuntimeProvider, (_, _) {});
|
||||
addTearDown(runtime.close);
|
||||
expect(await container.read(agentRuntimeProvider.future), isNull);
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.selectModel('provider', 'model');
|
||||
expect(repository.value.enabled, true);
|
||||
expect(await container.read(agentRuntimeProvider.future), isNotNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('overlapping settings commands preserve both changes', () async {
|
||||
final repository = _MemoryRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
final settings = container.read(agentSettingsProvider.notifier);
|
||||
await Future.wait([
|
||||
settings.upsertProvider(
|
||||
id: 'one',
|
||||
name: 'One',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'http://localhost/v1',
|
||||
models: const [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
settings.setEnabled(true),
|
||||
]);
|
||||
expect(repository.value.providers.map((provider) => provider.id), ['one']);
|
||||
expect(repository.value.enabled, isTrue);
|
||||
expect(repository.value.revision, 2);
|
||||
});
|
||||
|
||||
test('provider rejects a window too small for editor instructions', () async {
|
||||
final repository = _MemoryRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
final settings = container.read(agentSettingsProvider.notifier);
|
||||
const model = AgentModelSettings(id: 'model', contextWindow: 2048);
|
||||
expect(
|
||||
model.effectiveMaxInputTokens + model.effectiveMaxOutputTokens,
|
||||
2048,
|
||||
);
|
||||
expect(model.hasInstructionBudget, isFalse);
|
||||
await expectLater(
|
||||
settings.upsertProvider(
|
||||
id: 'small',
|
||||
name: 'Small',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'http://localhost/v1',
|
||||
models: const [model],
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(
|
||||
container.read(agentSettingsProvider).requireValue.providers,
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'provider settings build runtime and keep API keys out of metadata',
|
||||
() async {
|
||||
final repository = _MemoryRepository();
|
||||
final credentials = MemoryAgentCredentialStore();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
id: 'provider',
|
||||
name: 'Local',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'http://127.0.0.1:11434/v1',
|
||||
apiKey: 'secret',
|
||||
models: const [
|
||||
AgentModelSettings(
|
||||
id: 'model',
|
||||
contextWindow: 16000,
|
||||
maxOutputTokens: 2000,
|
||||
),
|
||||
],
|
||||
);
|
||||
await container.read(agentSettingsProvider.notifier).setEnabled(true);
|
||||
|
||||
final savedProvider = repository.value.providers.single;
|
||||
expect(savedProvider.credentialId, 'cutdex-agent-provider-provider');
|
||||
expect(savedProvider.baseUrl, isNot(contains('secret')));
|
||||
expect(await credentials.read(savedProvider.credentialId!), 'secret');
|
||||
final runtime = await container.read(agentRuntimeProvider.future);
|
||||
expect(runtime?.model, isA<OpenAiChatAdapter>());
|
||||
expect(runtime?.contextBuilder.maxInputTokens, 14000);
|
||||
expect(runtime?.contextBuilder.maxOutputTokens, 2000);
|
||||
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.deleteProvider('provider');
|
||||
expect(await credentials.read('cutdex-agent-provider-provider'), isNull);
|
||||
expect(repository.value.selectedProviderId, isNull);
|
||||
expect(repository.value.selectedModelId, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('invalid provider data is rejected before persistence', () async {
|
||||
final repository = _MemoryRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(
|
||||
MemoryAgentCredentialStore(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
|
||||
await expectLater(
|
||||
container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
name: 'Broken',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'file:///tmp/model',
|
||||
models: const [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(repository.value.providers, isEmpty);
|
||||
});
|
||||
|
||||
test('credential cleanup failure does not undo saved metadata', () async {
|
||||
final repository = _MemoryRepository();
|
||||
final credentials = _FailingDeleteCredentials();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
id: 'provider',
|
||||
name: 'Local',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'http://127.0.0.1:11434/v1',
|
||||
apiKey: 'secret',
|
||||
models: const [AgentModelSettings(id: 'model')],
|
||||
);
|
||||
|
||||
await container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.deleteProvider('provider');
|
||||
|
||||
expect(repository.value.providers, isEmpty);
|
||||
expect(
|
||||
container.read(agentSettingsProvider).requireValue.providers,
|
||||
isEmpty,
|
||||
);
|
||||
});
|
||||
|
||||
test('failed metadata save removes a newly written credential', () async {
|
||||
final failure = StateError('metadata unavailable');
|
||||
final repository = _FailingSaveRepository(failure)
|
||||
..value = const AgentSettingsState(
|
||||
enabled: true,
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'provider',
|
||||
name: 'Local',
|
||||
apiType: 'openAiChatCompletions',
|
||||
baseUrl: 'http://127.0.0.1:11434/v1',
|
||||
credentialId: 'existing-id',
|
||||
models: [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
],
|
||||
selectedProviderId: 'provider',
|
||||
selectedModelId: 'model',
|
||||
);
|
||||
final credentials = MemoryAgentCredentialStore();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
agentSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
agentCredentialStoreProvider.overrideWithValue(credentials),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(agentSettingsProvider.future);
|
||||
|
||||
await expectLater(
|
||||
container
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
id: 'provider',
|
||||
name: 'Local',
|
||||
apiType: AgentApiType.openAiChatCompletions,
|
||||
baseUrl: 'http://127.0.0.1:11434/v1',
|
||||
apiKey: 'new-secret',
|
||||
models: const [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
throwsA(same(failure)),
|
||||
);
|
||||
expect(await credentials.read('existing-id'), isNull);
|
||||
expect(repository.value.revision, 0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:cutdex_sdk/editor/commands.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Host implements EditorCommandHost {
|
||||
int reads = 0;
|
||||
int writes = 0;
|
||||
@override
|
||||
Set<EditorOperation> get supportedOperations =>
|
||||
EditorOperation.values.toSet();
|
||||
@override
|
||||
Future<CommandResult> execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) async {
|
||||
if (command is QueryTimeline) {
|
||||
reads++;
|
||||
} else {
|
||||
writes++;
|
||||
}
|
||||
return CommandResult(
|
||||
status: CommandStatus.succeeded,
|
||||
message: 'fresh state',
|
||||
version: 'new-process:0',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Model implements ModelAdapter {
|
||||
int requests = 0;
|
||||
@override
|
||||
Stream<ModelEvent> stream(
|
||||
ModelRequest request,
|
||||
CancellationToken cancellation,
|
||||
) async* {
|
||||
requests++;
|
||||
expect(request.messages.last.role, MessageRole.tool);
|
||||
yield ModelResponse(text: 'verified');
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
for (final (name, status) in [
|
||||
('cutdex_workspaces', CallStatus.started),
|
||||
('timeline_query', CallStatus.started),
|
||||
('clip_setAudio', CallStatus.started),
|
||||
('clip_setAudio', CallStatus.planned),
|
||||
]) {
|
||||
test('restart recovery of $name $status preserves replay safety', () async {
|
||||
final root = await Directory.systemTemp.createTemp('agent-recovery-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final call = ToolCall(
|
||||
id: 'call',
|
||||
name: name,
|
||||
arguments: {
|
||||
if (name != 'cutdex_workspaces') 'workspaceId': 'timeline',
|
||||
if (name == 'clip_setAudio') ...{
|
||||
'clipId': 'clip',
|
||||
'db': -10,
|
||||
'muted': false,
|
||||
'expectedVersion': status == CallStatus.planned
|
||||
? 'new-process:0'
|
||||
: 'old-process:1',
|
||||
},
|
||||
},
|
||||
);
|
||||
await FileSessionStore(root).save(
|
||||
SessionSnapshot(
|
||||
id: 'session',
|
||||
runId: 'interrupted',
|
||||
status: RunStatus.running,
|
||||
history: [
|
||||
AgentMessage(role: MessageRole.user, text: 'do the task'),
|
||||
AgentMessage(role: MessageRole.assistant, calls: [call]),
|
||||
],
|
||||
pending: [
|
||||
CallRecord(
|
||||
call: call,
|
||||
operationId: 'stable-operation',
|
||||
status: status,
|
||||
),
|
||||
],
|
||||
),
|
||||
expectedRevision: null,
|
||||
);
|
||||
// All dispatcher memory is fresh, as after a process restart.
|
||||
final host = _Host();
|
||||
final model = _Model();
|
||||
final manager = SessionManager(
|
||||
model: model,
|
||||
store: FileSessionStore(root),
|
||||
tools: editorAgentTools({'timeline': EditorToolDispatcher(host: host)}),
|
||||
);
|
||||
final run = await manager.resume('session');
|
||||
final result = await run.done;
|
||||
expect(host.writes, status == CallStatus.planned ? 1 : 0);
|
||||
if (name == 'clip_setAudio' && status == CallStatus.started) {
|
||||
expect(result.status, RunStatus.waiting);
|
||||
expect(result.pending.single.operationId, 'stable-operation');
|
||||
expect(model.requests, 0);
|
||||
} else {
|
||||
expect(result.status, RunStatus.completed);
|
||||
expect(model.requests, 1);
|
||||
expect(host.reads, name == 'timeline_query' ? 1 : 0);
|
||||
expect(
|
||||
result.history.where((m) => m.role == MessageRole.tool),
|
||||
hasLength(1),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/agent_models.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/workspace_mode.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:drift/drift.dart' show Value;
|
||||
import 'package:cutdex_sdk/timeline/layout.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:sqlite3/sqlite3.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'old app settings schema is rejected without changing its data',
|
||||
() async {
|
||||
final directory = await Directory.systemTemp.createTemp('app-schema-');
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final file = File(p.join(directory.path, 'app.sqlite'));
|
||||
final current = AppDatabase(NativeDatabase(file));
|
||||
await DriftWorkspaceViewSettingsRepository(current)
|
||||
.save(const WorkspaceViewSettingsData(mode: WorkspaceMode.cut));
|
||||
await current.close();
|
||||
final old = sqlite3.open(file.path);
|
||||
try {
|
||||
old.execute(
|
||||
'ALTER TABLE workspace_view_configurations RENAME COLUMN mode TO layout_mode',
|
||||
);
|
||||
old.userVersion = 1;
|
||||
} finally {
|
||||
old.close();
|
||||
}
|
||||
final before = await file.readAsBytes();
|
||||
final reopened = AppDatabase(NativeDatabase(file));
|
||||
addTearDown(reopened.close);
|
||||
await expectLater(
|
||||
DriftWorkspaceViewSettingsRepository(reopened).load(),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(await file.readAsBytes(), orderedEquals(before));
|
||||
},
|
||||
);
|
||||
|
||||
test('unknown stored language falls back to the system locale', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
await database
|
||||
.into(database.languageConfigurations)
|
||||
.insert(
|
||||
LanguageConfigurationsCompanion.insert(
|
||||
id: const Value(0),
|
||||
language: 'unknown',
|
||||
),
|
||||
);
|
||||
expect(
|
||||
await DriftLanguageSettingsRepository(database).load(),
|
||||
AppLanguage.system,
|
||||
);
|
||||
});
|
||||
|
||||
test('provider enabled state persists across repository loads', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final repository = DriftAgentSettingsRepository(database);
|
||||
await repository.save(
|
||||
const AgentSettingsState(
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'disabled',
|
||||
name: 'Disabled',
|
||||
apiType: 'anthropicMessages',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
enabled: false,
|
||||
models: [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
final loaded = await repository.load();
|
||||
expect(loaded.providers.single.enabled, false);
|
||||
expect(loaded.providers.single.models.single.id, 'model');
|
||||
});
|
||||
|
||||
test('typed app repositories share one Drift database', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
expect(
|
||||
(await database.customSelect('PRAGMA user_version').getSingle())
|
||||
.read<int>('user_version'),
|
||||
2,
|
||||
);
|
||||
|
||||
final appearance = DriftAppearanceSettingsRepository(database);
|
||||
expect(await appearance.load(), AppAppearance.system);
|
||||
await appearance.save(AppAppearance.penLight);
|
||||
expect(await appearance.load(), AppAppearance.penLight);
|
||||
await appearance.save(AppAppearance.penDark);
|
||||
expect(await appearance.load(), AppAppearance.penDark);
|
||||
|
||||
final language = DriftLanguageSettingsRepository(database);
|
||||
expect(await language.load(), AppLanguage.system);
|
||||
await language.save(AppLanguage.japanese);
|
||||
expect(await language.load(), AppLanguage.japanese);
|
||||
await language.save(AppLanguage.system);
|
||||
expect(await language.load(), AppLanguage.system);
|
||||
|
||||
final conversationLocation = DriftConversationLocationSettingsRepository(
|
||||
database,
|
||||
);
|
||||
expect(await conversationLocation.load(), isNull);
|
||||
await conversationLocation.save('/conversations');
|
||||
expect(await conversationLocation.load(), '/conversations');
|
||||
|
||||
final projectLocation = DriftProjectLocationSettingsRepository(database);
|
||||
expect(await projectLocation.load(), isNull);
|
||||
await projectLocation.save('/projects');
|
||||
expect(await projectLocation.load(), '/projects');
|
||||
|
||||
final resourceLocation = DriftResourceLocationSettingsRepository(database);
|
||||
expect(await resourceLocation.load(), isNull);
|
||||
await resourceLocation.save('/resources');
|
||||
expect(await resourceLocation.load(), '/resources');
|
||||
|
||||
final mcp = DriftMcpSettingsRepository(database);
|
||||
expect(await mcp.load(), isNull);
|
||||
await mcp.save(
|
||||
const McpSettingsValue(enabled: true, port: 47831, token: 'token'),
|
||||
);
|
||||
final mcpValue = await mcp.load();
|
||||
expect(mcpValue?.enabled, isTrue);
|
||||
expect(mcpValue?.port, 47831);
|
||||
expect(mcpValue?.token, 'token');
|
||||
|
||||
final agent = DriftAgentSettingsRepository(database);
|
||||
await agent.save(
|
||||
const AgentSettingsState(
|
||||
enabled: true,
|
||||
selectedProviderId: 'provider',
|
||||
selectedModelId: 'model',
|
||||
revision: 3,
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'provider',
|
||||
name: 'Provider',
|
||||
apiType: 'openAiChatCompletions',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
credentialId: 'credential',
|
||||
models: [
|
||||
AgentModelSettings(
|
||||
id: 'model',
|
||||
contextWindow: 32000,
|
||||
maxOutputTokens: 4096,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
final agentValue = await agent.load();
|
||||
expect(agentValue.enabled, isTrue);
|
||||
expect(agentValue.selectedModelId, 'model');
|
||||
expect(agentValue.providers.single.credentialId, 'credential');
|
||||
expect(agentValue.providers.single.models.single.contextWindow, 32000);
|
||||
|
||||
final workspaceView = DriftWorkspaceViewSettingsRepository(database);
|
||||
final columns = await database
|
||||
.customSelect('PRAGMA table_info(workspace_view_configurations)')
|
||||
.get();
|
||||
expect(columns.map((row) => row.read<String>('name')), contains('mode'));
|
||||
expect(
|
||||
columns.map((row) => row.read<String>('name')),
|
||||
isNot(contains('layout_mode')),
|
||||
);
|
||||
final initialWorkspace = await workspaceView.load();
|
||||
expect(initialWorkspace.hasSavedState, isFalse);
|
||||
expect(initialWorkspace.mode, WorkspaceMode.agent);
|
||||
await workspaceView.save(
|
||||
const WorkspaceViewSettingsData(
|
||||
activeProjectId: 'two',
|
||||
sidebarCollapsed: true,
|
||||
sidebarWidth: 312,
|
||||
),
|
||||
);
|
||||
final workspaceValue = await workspaceView.load();
|
||||
expect(workspaceValue.hasSavedState, isTrue);
|
||||
expect(workspaceValue.activeProjectId, 'two');
|
||||
expect(workspaceValue.sidebarCollapsed, isTrue);
|
||||
expect(workspaceValue.sidebarWidth, 312);
|
||||
|
||||
final projectView = DriftProjectViewSettingsRepository(database);
|
||||
await projectView.save(
|
||||
'two',
|
||||
const ProjectViewSettingsData(propertiesOpen: true, timelineHeight: 280),
|
||||
);
|
||||
final projectValue = await projectView.load('two');
|
||||
expect(projectValue.propertiesOpen, isTrue);
|
||||
expect(projectValue.timelineHeight, 280);
|
||||
|
||||
final timelineView = DriftTimelineViewSettingsRepository(database);
|
||||
await timelineView.save(
|
||||
'two',
|
||||
'timeline',
|
||||
SequenceId('one'),
|
||||
TimelineSequenceViewState(
|
||||
playheadTick: 120,
|
||||
camera: TimelineCamera(
|
||||
baseTick: 40,
|
||||
fractionalTick: .25,
|
||||
pixelsPerTick: .5,
|
||||
verticalOffset: 18,
|
||||
),
|
||||
),
|
||||
);
|
||||
await timelineView.save(
|
||||
'two',
|
||||
'timeline',
|
||||
SequenceId('two'),
|
||||
TimelineSequenceViewState(
|
||||
playheadTick: 240,
|
||||
camera: TimelineCamera(
|
||||
baseTick: 80,
|
||||
pixelsPerTick: .75,
|
||||
verticalOffset: 24,
|
||||
),
|
||||
),
|
||||
);
|
||||
final timelineValue = await timelineView.load('two', 'timeline');
|
||||
expect(timelineValue.activeSequenceId, SequenceId('two'));
|
||||
expect(timelineValue.sequences.keys, {
|
||||
SequenceId('one'),
|
||||
SequenceId('two'),
|
||||
});
|
||||
expect(timelineValue.sequences[SequenceId('one')]?.playheadTick, 120);
|
||||
expect(timelineValue.sequences[SequenceId('one')]?.camera.baseTick, 40);
|
||||
|
||||
final recent = DriftRecentProjectsRepository(database);
|
||||
const first = RecentProject(id: 'one', name: 'One', path: '/one');
|
||||
const second = RecentProject(id: 'two', name: 'Two', path: '/two');
|
||||
await recent.save([second, first]);
|
||||
expect(await recent.load(), [second, first]);
|
||||
await expectLater(
|
||||
recent.save([first, first]),
|
||||
throwsA(isA<SqliteException>()),
|
||||
);
|
||||
expect(await recent.load(), [second, first]);
|
||||
await recent.rememberTimeline('two', 'timeline');
|
||||
expect(await recent.lastTimeline('two'), 'timeline');
|
||||
await recent.save([]);
|
||||
expect(await recent.load(), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'project location defaults to Documents/Cutdex/Projects and is persisted',
|
||||
() async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final documents = await Directory.systemTemp.createTemp(
|
||||
'cutdex-documents-',
|
||||
);
|
||||
addTearDown(() => documents.delete(recursive: true));
|
||||
final stored = DriftProjectLocationSettingsRepository(database);
|
||||
final repository = DefaultingProjectLocationSettingsRepository(
|
||||
stored,
|
||||
documentsDirectory: () async => documents,
|
||||
);
|
||||
|
||||
final location = await repository.load();
|
||||
|
||||
expect(location, p.join(documents.path, 'Cutdex', 'Projects'));
|
||||
expect(await Directory(location).exists(), isFalse);
|
||||
expect(await stored.load(), location);
|
||||
await Directory(location).create(recursive: true);
|
||||
await Directory(location).delete();
|
||||
expect(await repository.load(), location);
|
||||
expect(await Directory(location).exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('resource location creates the managed directory layout', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final documents = await Directory.systemTemp.createTemp(
|
||||
'cutdex-resource-documents-',
|
||||
);
|
||||
addTearDown(() => documents.delete(recursive: true));
|
||||
final stored = DriftResourceLocationSettingsRepository(database);
|
||||
final repository = DefaultingResourceLocationSettingsRepository(
|
||||
stored,
|
||||
documentsDirectory: () async => documents,
|
||||
);
|
||||
|
||||
final location = await repository.load();
|
||||
|
||||
expect(location, p.join(documents.path, 'Cutdex', 'Resources'));
|
||||
for (final name in ['Processing', 'Downloads', 'Cache']) {
|
||||
expect(await Directory(p.join(location, name)).exists(), isTrue);
|
||||
}
|
||||
expect(await stored.load(), location);
|
||||
});
|
||||
|
||||
test('app settings survive closing and reopening the database', () async {
|
||||
final directory = await Directory.systemTemp.createTemp('cutdex-app-db-');
|
||||
final file = File('${directory.path}/app.sqlite');
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
|
||||
final first = AppDatabase(NativeDatabase(file));
|
||||
await DriftAppearanceSettingsRepository(first).save(AppAppearance.penLight);
|
||||
await DriftProjectLocationSettingsRepository(first).save('/projects');
|
||||
await DriftLanguageSettingsRepository(first)
|
||||
.save(AppLanguage.simplifiedChinese);
|
||||
await DriftConversationLocationSettingsRepository(first)
|
||||
.save('/conversations');
|
||||
await DriftMcpSettingsRepository(first).save(
|
||||
const McpSettingsValue(enabled: true, port: 47832, token: 'persisted'),
|
||||
);
|
||||
await DriftAgentSettingsRepository(first).save(
|
||||
const AgentSettingsState(
|
||||
enabled: true,
|
||||
selectedProviderId: 'provider',
|
||||
selectedModelId: 'model',
|
||||
revision: 1,
|
||||
providers: [
|
||||
AgentProviderSettings(
|
||||
id: 'provider',
|
||||
name: 'Provider',
|
||||
apiType: 'openAiChatCompletions',
|
||||
baseUrl: 'https://example.com/v1',
|
||||
models: [AgentModelSettings(id: 'model')],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
await DriftRecentProjectsRepository(first)
|
||||
.rememberTimeline('project', 'timeline');
|
||||
await DriftWorkspaceViewSettingsRepository(first).save(
|
||||
const WorkspaceViewSettingsData(
|
||||
activeProjectId: 'project',
|
||||
mode: WorkspaceMode.cut,
|
||||
sidebarWidth: 300,
|
||||
),
|
||||
);
|
||||
await DriftProjectViewSettingsRepository(first)
|
||||
.save('project', const ProjectViewSettingsData(propertiesOpen: true));
|
||||
await DriftTimelineViewSettingsRepository(first).save(
|
||||
'project',
|
||||
'timeline',
|
||||
SequenceId('sequence'),
|
||||
TimelineSequenceViewState(
|
||||
playheadTick: 360,
|
||||
camera: TimelineCamera(baseTick: 120, pixelsPerTick: .5),
|
||||
),
|
||||
);
|
||||
await first.close();
|
||||
|
||||
final reopened = AppDatabase(NativeDatabase(file));
|
||||
addTearDown(reopened.close);
|
||||
expect(
|
||||
await DriftAppearanceSettingsRepository(reopened).load(),
|
||||
AppAppearance.penLight,
|
||||
);
|
||||
expect(
|
||||
await DriftProjectLocationSettingsRepository(reopened).load(),
|
||||
'/projects',
|
||||
);
|
||||
expect(
|
||||
await DriftLanguageSettingsRepository(reopened).load(),
|
||||
AppLanguage.simplifiedChinese,
|
||||
);
|
||||
expect(
|
||||
await DriftConversationLocationSettingsRepository(reopened).load(),
|
||||
'/conversations',
|
||||
);
|
||||
final mcp = await DriftMcpSettingsRepository(reopened).load();
|
||||
expect((mcp?.enabled, mcp?.port, mcp?.token), (true, 47832, 'persisted'));
|
||||
final agent = await DriftAgentSettingsRepository(reopened).load();
|
||||
expect((agent.enabled, agent.selectedModelId), (true, 'model'));
|
||||
expect(
|
||||
await DriftRecentProjectsRepository(reopened).lastTimeline('project'),
|
||||
'timeline',
|
||||
);
|
||||
final workspace = await DriftWorkspaceViewSettingsRepository(reopened)
|
||||
.load();
|
||||
expect(workspace.activeProjectId, 'project');
|
||||
expect(workspace.mode, WorkspaceMode.cut);
|
||||
expect(workspace.sidebarWidth, 300);
|
||||
expect(
|
||||
(await DriftProjectViewSettingsRepository(reopened).load('project'))
|
||||
.propertiesOpen,
|
||||
isTrue,
|
||||
);
|
||||
final timeline = await DriftTimelineViewSettingsRepository(reopened)
|
||||
.load('project', 'timeline');
|
||||
expect(timeline.activeSequenceId, SequenceId('sequence'));
|
||||
expect(timeline.sequences[SequenceId('sequence')]?.playheadTick, 360);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
import 'package:cutdex/integrations/app_failure_adapter.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('SDK rejection codes translate regardless of diagnostic wording', () {
|
||||
final en = lookupAppLocalizations(const Locale('en'));
|
||||
final zh = lookupAppLocalizations(const Locale('zh'));
|
||||
for (final diagnostic in [
|
||||
'Old wording',
|
||||
'Different punctuation!',
|
||||
'任意描述',
|
||||
]) {
|
||||
final failure = appFailureFromError(
|
||||
CommandRejected('missingMedia', diagnostic),
|
||||
);
|
||||
expect(failure.code, AppErrorCode.mediaNoLongerExists);
|
||||
expect(failure.diagnostic, diagnostic);
|
||||
expect(en.failureMessage(failure), en.mediaNoLongerExists);
|
||||
expect(zh.failureMessage(failure), zh.mediaNoLongerExists);
|
||||
}
|
||||
expect(
|
||||
appFailureFromError(const CommandRejected('staleVersion', 'Changed'))
|
||||
.code,
|
||||
AppErrorCode.timelineChanged,
|
||||
);
|
||||
expect(
|
||||
appFailureFromError(
|
||||
const ProjectFileException(ProjectFileError.notFound, 'Any wording'),
|
||||
).code,
|
||||
AppErrorCode.projectMissingDirectory,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'unknown diagnostics are preserved without guessing from their wording',
|
||||
() {
|
||||
final en = lookupAppLocalizations(const Locale('en'));
|
||||
const error = CommandRejected('futureCode', '素材已不存在');
|
||||
expect(appFailureFromError(error).code, AppErrorCode.diagnostic);
|
||||
expect(en.errorMessage(error), error.message);
|
||||
final io = const FileSystemException('Native detail', '/missing');
|
||||
final failure = projectFailureFromError(io);
|
||||
expect(failure.code, AppErrorCode.projectAccessFailed);
|
||||
expect(failure.diagnostic, io.toString());
|
||||
expect(en.failureMessage(failure), en.projectAccessFailed);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'project location actions depend on the code, not the displayed text',
|
||||
() {
|
||||
const failure = AppFailure(
|
||||
AppErrorCode.projectLocationUnavailable,
|
||||
diagnostic: 'No Chinese keywords',
|
||||
);
|
||||
expect(failure.requiresProjectLocation, isTrue);
|
||||
expect(
|
||||
const AppFailure(
|
||||
AppErrorCode.diagnostic,
|
||||
diagnostic: '项目位置 保存位置',
|
||||
).requiresProjectLocation,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'an existing error follows locale changes without changing state',
|
||||
(tester) async {
|
||||
const state = ProjectState(
|
||||
error: AppFailure(
|
||||
AppErrorCode.mediaReadFailed,
|
||||
diagnostic: 'Low-level read failure',
|
||||
),
|
||||
);
|
||||
Widget view(Locale locale) => MaterialApp(
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Builder(
|
||||
builder: (context) => Text(context.l10n.failureMessage(state.error!)),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(view(const Locale('en')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text(lookupAppLocalizations(const Locale('en')).mediaReadFailed),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.pumpWidget(view(const Locale('zh')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text(lookupAppLocalizations(const Locale('zh')).mediaReadFailed),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(state.error!.diagnostic, 'Low-level read failure');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'package:cutdex/integrations/app_update_bridge.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('deskup-test');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
|
||||
Future<Object?> nativeCall(String method, [Object? arguments]) async {
|
||||
final response = Completer<Object?>();
|
||||
await messenger.handlePlatformMessage(
|
||||
method == 'prepareToQuit' ? appLifecycleChannel.name : channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall(method, arguments),
|
||||
),
|
||||
(data) {
|
||||
try {
|
||||
response.complete(
|
||||
data == null
|
||||
? null
|
||||
: const StandardMethodCodec().decodeEnvelope(data),
|
||||
);
|
||||
} catch (error, stack) {
|
||||
response.completeError(error, stack);
|
||||
}
|
||||
},
|
||||
);
|
||||
return response.future;
|
||||
}
|
||||
|
||||
setUp(() {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
|
||||
messenger.setMockMethodCallHandler(appLifecycleChannel, (_) async => null);
|
||||
});
|
||||
tearDown(() {
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
messenger.setMockMethodCallHandler(appLifecycleChannel, null);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
|
||||
test(
|
||||
'bridge initializes once and delegates native quit preparation',
|
||||
() async {
|
||||
var ready = 0;
|
||||
var quits = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'ready') ready++;
|
||||
return null;
|
||||
});
|
||||
final bridge = AppUpdateBridge(channel);
|
||||
addTearDown(bridge.dispose);
|
||||
Future<void> prepare() async {
|
||||
quits++;
|
||||
}
|
||||
|
||||
bridge.start(
|
||||
() async => fail('The obsolete quit coordinator was invoked'),
|
||||
);
|
||||
bridge.start(prepare);
|
||||
expect(await nativeCall('prepareToQuit'), isTrue);
|
||||
expect(ready, 1);
|
||||
expect(quits, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('disposing a bridge closes its own event stream', () async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => null);
|
||||
final bridge = AppUpdateBridge(channel);
|
||||
bridge.start(() async {});
|
||||
addTearDown(bridge.dispose);
|
||||
final events = expectLater(
|
||||
bridge.events.map((status) => status.phase),
|
||||
emitsInOrder([UpdatePhase.ready, emitsDone]),
|
||||
);
|
||||
await nativeCall('statusChanged', {'phase': 'ready'});
|
||||
bridge.dispose();
|
||||
await events;
|
||||
// No handler survives disposal to invoke business logic or publish events.
|
||||
expect(await nativeCall('prepareToQuit'), isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'failed save refuses quit and a later successful save acknowledges it',
|
||||
() async {
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => null);
|
||||
var saveFails = true;
|
||||
final bridge = AppUpdateBridge(channel);
|
||||
addTearDown(bridge.dispose);
|
||||
bridge.start(() async {
|
||||
if (saveFails) throw PlatformException(code: 'workspaceBusy');
|
||||
});
|
||||
await expectLater(
|
||||
nativeCall('prepareToQuit'),
|
||||
throwsA(
|
||||
isA<PlatformException>().having(
|
||||
(error) => error.code,
|
||||
'code',
|
||||
'workspaceBusy',
|
||||
),
|
||||
),
|
||||
);
|
||||
saveFails = false;
|
||||
expect(await nativeCall('prepareToQuit'), isTrue);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/assistant/agent_conversation_service.dart';
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
import 'package:cutdex/features/settings/update_controller.dart';
|
||||
import 'package:cutdex/integrations/app_updates.dart';
|
||||
import 'package:cutdex/settings/settings_operation.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
import 'support/project_write_lock.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
for (final saveFails in [false, true]) {
|
||||
test(
|
||||
'Windows ${saveFails ? 'save failure prevents install' : 'failed updater restores saved workspace'}',
|
||||
() async {
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-update-recovery-',
|
||||
);
|
||||
final path = '${root.path}/Test.cutdex';
|
||||
void Function()? releaseWriteLock;
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
agentConversationRegistryProvider.overrideWithValue(
|
||||
AgentConversationRegistry(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, null);
|
||||
releaseWriteLock?.call();
|
||||
try {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
} catch (_) {}
|
||||
container.dispose();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
var installs = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, (call) async {
|
||||
if (call.method == 'status') {
|
||||
return {'configured': true, 'canCheck': true, 'phase': 'ready'};
|
||||
}
|
||||
if (call.method == 'install') {
|
||||
installs++;
|
||||
throw PlatformException(code: 'installFailed');
|
||||
}
|
||||
return null;
|
||||
});
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
await projects.open(path, name: 'Update recovery');
|
||||
await projects.createTimeline();
|
||||
final before = container.read(projectsProvider).requireValue;
|
||||
final session = await projects.openTimelineSession(
|
||||
before.activeProject!.id,
|
||||
before.timeline!.id,
|
||||
);
|
||||
if (saveFails) {
|
||||
releaseWriteLock = blockProjectWrites(path);
|
||||
}
|
||||
session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!);
|
||||
final listener = container.listen(updateControllerProvider, (_, _) {});
|
||||
addTearDown(listener.close);
|
||||
await container.read(updateControllerProvider.future);
|
||||
await container.read(updateControllerProvider.notifier).install();
|
||||
expect(
|
||||
container.read(settingsOperationProvider('updates')).hasError,
|
||||
isTrue,
|
||||
);
|
||||
expect(installs, saveFails ? 0 : 1);
|
||||
final after = container.read(projectsProvider).requireValue;
|
||||
expect(after.projectBusy, isFalse);
|
||||
expect(after.activeProject?.id, before.activeProject!.id);
|
||||
expect(after.timeline?.id, before.timeline!.id);
|
||||
final recovered = await container
|
||||
.read(projectsProvider.notifier)
|
||||
.openTimelineSession(before.activeProject!.id, before.timeline!.id);
|
||||
expect(recovered.acceptsEdits, isTrue);
|
||||
if (saveFails) {
|
||||
expect(recovered.dirty, isTrue);
|
||||
} else {
|
||||
expect(recovered.document.settings['renderSize'], {
|
||||
'width': 1440.0,
|
||||
'height': 1080.0,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import 'dart:io';
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
import 'support/project_write_lock.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
for (final opening in [false, true]) {
|
||||
test(
|
||||
'shutdown refuses to interrupt timeline ${opening ? 'opening' : 'creation'}',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-update-timeline-',
|
||||
);
|
||||
var container = ProviderContainer(
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
],
|
||||
);
|
||||
var projects = container.read(projectsProvider.notifier);
|
||||
addTearDown(() async {
|
||||
try {
|
||||
await projects.prepareToQuit();
|
||||
} catch (_) {}
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
expect(
|
||||
await projects.open('${root.path}/Test.cutdex', name: 'Test'),
|
||||
isTrue,
|
||||
);
|
||||
String? target;
|
||||
if (opening) {
|
||||
await projects.createTimeline();
|
||||
target = container.read(projectsProvider).requireValue.timeline!.id;
|
||||
await projects.createTimeline();
|
||||
await projects.prepareToQuit();
|
||||
container.dispose();
|
||||
container = ProviderContainer(
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
],
|
||||
);
|
||||
projects = container.read(projectsProvider.notifier);
|
||||
expect(await projects.open('${root.path}/Test.cutdex'), isTrue);
|
||||
}
|
||||
final projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
final started = Completer<void>();
|
||||
container.listen(projectsProvider, (_, next) {
|
||||
final busy = opening
|
||||
? next.value?.openingTimelineId != null
|
||||
: next.value?.creatingTimeline == true;
|
||||
if (busy && !started.isCompleted) started.complete();
|
||||
});
|
||||
final operation = opening
|
||||
? projects.openTimeline(projectId, target!)
|
||||
: projects.createTimeline();
|
||||
await started.future;
|
||||
Object? shutdown;
|
||||
try {
|
||||
shutdown = await projects.prepareToQuit();
|
||||
} catch (error) {
|
||||
shutdown = error;
|
||||
}
|
||||
final completed = await operation;
|
||||
expect(
|
||||
shutdown,
|
||||
isA<PlatformException>().having(
|
||||
(error) => error.code,
|
||||
'code',
|
||||
'workspaceBusy',
|
||||
),
|
||||
);
|
||||
expect(completed, isTrue);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'update shutdown flushes dirty edits before releasing the project',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-update-save-');
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final path = '${root.path}/Test.cutdex';
|
||||
expect(await projects.open(path, name: 'Update test'), isTrue);
|
||||
expect(await projects.createTimeline(), isTrue);
|
||||
final state = container.read(projectsProvider).requireValue;
|
||||
final session = await projects.openTimelineSession(
|
||||
state.activeProject!.id,
|
||||
state.timeline!.id,
|
||||
);
|
||||
session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!);
|
||||
expect(session.dirty, isTrue);
|
||||
expect(await projects.prepareToQuit(), isTrue);
|
||||
expect(await projects.createTimeline(), isFalse);
|
||||
final saved = await ProjectFile.open(Directory(path));
|
||||
expect(
|
||||
(await saved.loadTimeline(state.timeline!.id)).settings['renderSize'],
|
||||
{'width': 1440.0, 'height': 1080.0},
|
||||
);
|
||||
await saved.close();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a blocked save cancels update shutdown and keeps edits available',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-update-conflict-',
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final path = '${root.path}/Test.cutdex';
|
||||
await projects.open(path, name: 'Update conflict');
|
||||
await projects.createTimeline();
|
||||
final state = container.read(projectsProvider).requireValue;
|
||||
final session = await projects.openTimelineSession(
|
||||
state.activeProject!.id,
|
||||
state.timeline!.id,
|
||||
);
|
||||
final release = blockProjectWrites(path);
|
||||
addTearDown(release);
|
||||
session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!);
|
||||
await expectLater(
|
||||
projects.prepareToQuit(),
|
||||
throwsA(
|
||||
isA<PlatformException>().having(
|
||||
(error) => error.code,
|
||||
'code',
|
||||
'saveFailed',
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(session.dirty, isTrue);
|
||||
expect(session.acceptsEdits, isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.projectBusy,
|
||||
isFalse,
|
||||
);
|
||||
release();
|
||||
expect(await projects.prepareToQuit(), isTrue);
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/settings/update_settings.dart';
|
||||
import 'package:cutdex/integrations/app_updates.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, null);
|
||||
});
|
||||
|
||||
Widget app() => MaterialApp(
|
||||
theme: EditorTheme.penLight,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const Scaffold(body: UpdateSettings()),
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'configured updates check natively and persist automatic checks',
|
||||
(tester) async {
|
||||
var automatic = false;
|
||||
var checks = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, (call) async {
|
||||
switch (call.method) {
|
||||
case 'status':
|
||||
return {
|
||||
'configured': true,
|
||||
'canCheck': true,
|
||||
'automaticChecks': automatic,
|
||||
'version': '1.0.0',
|
||||
'build': '42',
|
||||
};
|
||||
case 'check':
|
||||
checks++;
|
||||
case 'automaticChecks':
|
||||
automatic = call.arguments as bool;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('1.0.0 (42)'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const Key('check-for-updates')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(checks, 1);
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
expect(automatic, isTrue);
|
||||
},
|
||||
variant: const TargetPlatformVariant({
|
||||
TargetPlatform.macOS,
|
||||
TargetPlatform.windows,
|
||||
}),
|
||||
);
|
||||
|
||||
testWidgets('missing native configuration disables checks', (tester) async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
appUpdatesChannel,
|
||||
(_) async => {'configured': false},
|
||||
);
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
final button = tester.widget<OutlinedButton>(
|
||||
find.byKey(const Key('check-for-updates')),
|
||||
);
|
||||
expect(button.onPressed, isNull);
|
||||
expect(find.text('Updates are unavailable in this build.'), findsOneWidget);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets('native failure is visible and permits retry', (tester) async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, (call) async {
|
||||
if (call.method == 'status') {
|
||||
return {'configured': true, 'canCheck': true};
|
||||
}
|
||||
throw PlatformException(code: 'failed');
|
||||
});
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('check-for-updates')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text('Could not check for updates. Please try again.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<OutlinedButton>(find.byKey(const Key('check-for-updates')))
|
||||
.onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets('Windows download progress leads to an explicit restart action', (
|
||||
tester,
|
||||
) async {
|
||||
var downloads = 0;
|
||||
var status = <String, Object?>{
|
||||
'configured': true,
|
||||
'canCheck': true,
|
||||
'phase': 'available',
|
||||
'availableVersion': '1.0.0-build.2',
|
||||
};
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, (call) async {
|
||||
if (call.method == 'status') return status;
|
||||
if (call.method == 'download') {
|
||||
downloads++;
|
||||
status = {
|
||||
...status,
|
||||
'canCheck': false,
|
||||
'phase': 'downloading',
|
||||
'progress': 35,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('install-update')), findsNothing);
|
||||
await tester.tap(find.byKey(const Key('download-update')));
|
||||
await tester.pump();
|
||||
await tester.pump(const Duration(milliseconds: 100));
|
||||
expect(downloads, 1);
|
||||
expect(find.text('Downloading update: 35%'), findsOneWidget);
|
||||
expect(
|
||||
tester
|
||||
.widget<OutlinedButton>(find.byKey(const Key('check-for-updates')))
|
||||
.onPressed,
|
||||
isNull,
|
||||
);
|
||||
final message = const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('statusChanged', {
|
||||
...status,
|
||||
'phase': 'ready',
|
||||
'progress': 100,
|
||||
'canCheck': true,
|
||||
}),
|
||||
);
|
||||
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.handlePlatformMessage(appUpdatesChannel.name, message, (_) {});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('download-update')), findsNothing);
|
||||
expect(find.text('Restart to update'), findsOneWidget);
|
||||
expect(find.byType(LinearProgressIndicator), findsNothing);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
|
||||
|
||||
testWidgets('Windows corrupt download exposes retry instead of install', (
|
||||
tester,
|
||||
) async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
appUpdatesChannel,
|
||||
(call) async => call.method == 'status'
|
||||
? {
|
||||
'configured': true,
|
||||
'canCheck': true,
|
||||
'phase': 'available',
|
||||
'availableVersion': '1.0.0-build.2',
|
||||
'error': 'Checksum failed',
|
||||
}
|
||||
: null,
|
||||
);
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.text('Could not update. Finish active tasks and try again.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byKey(const Key('install-update')), findsNothing);
|
||||
expect(
|
||||
tester
|
||||
.widget<OutlinedButton>(find.byKey(const Key('download-update')))
|
||||
.onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
|
||||
|
||||
testWidgets('late status response preserves the newer Windows update event', (
|
||||
tester,
|
||||
) async {
|
||||
final response = Completer<Map<String, Object?>>();
|
||||
var loads = 0;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(appUpdatesChannel, (call) async {
|
||||
if (call.method == 'status') {
|
||||
if (++loads > 1) return response.future;
|
||||
return {'configured': true, 'canCheck': true};
|
||||
}
|
||||
return null;
|
||||
});
|
||||
await tester.pumpWidget(ProviderScope(child: app()));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('check-for-updates')));
|
||||
await tester.pump();
|
||||
expect(loads, 2);
|
||||
final message = const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('statusChanged', {
|
||||
'configured': true,
|
||||
'canCheck': true,
|
||||
'phase': 'ready',
|
||||
'availableVersion': '1.0.0-build.2',
|
||||
}),
|
||||
);
|
||||
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.handlePlatformMessage(appUpdatesChannel.name, message, (_) {});
|
||||
await tester.pump();
|
||||
response.complete({
|
||||
'configured': true,
|
||||
'canCheck': false,
|
||||
'phase': 'checking',
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Restart to update'), findsOneWidget);
|
||||
expect(find.text('Checking for updates…'), findsNothing);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:cutdex/features/settings/appearance_settings.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'theme persists across providers and failed saves retain current mode',
|
||||
() async {
|
||||
final repository = MemoryAppearanceSettingsRepository();
|
||||
ProviderContainer container() => ProviderContainer(
|
||||
overrides: [
|
||||
appearanceSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
final first = container();
|
||||
addTearDown(first.dispose);
|
||||
expect(
|
||||
await first.read(appearanceSettingsProvider.future),
|
||||
AppAppearance.system,
|
||||
);
|
||||
await first
|
||||
.read(appearanceSettingsProvider.notifier)
|
||||
.setMode(AppAppearance.penLight);
|
||||
expect(
|
||||
first.read(appearanceSettingsProvider).requireValue,
|
||||
AppAppearance.penLight,
|
||||
);
|
||||
final restored = container();
|
||||
addTearDown(restored.dispose);
|
||||
expect(
|
||||
await restored.read(appearanceSettingsProvider.future),
|
||||
AppAppearance.penLight,
|
||||
);
|
||||
repository.failWrites = true;
|
||||
await expectLater(
|
||||
restored
|
||||
.read(appearanceSettingsProvider.notifier)
|
||||
.setMode(AppAppearance.penDark),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(
|
||||
restored.read(appearanceSettingsProvider).requireValue,
|
||||
AppAppearance.penLight,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,590 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/editor_tools.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class MemoryRecent implements RecentProjectsRepository {
|
||||
List<RecentProject> records = [];
|
||||
final projects = <String, String>{};
|
||||
@override
|
||||
Future<List<RecentProject>> load() async => records;
|
||||
@override
|
||||
Future<void> save(List<RecentProject> projects) async {
|
||||
records = projects;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> lastTimeline(String projectId) async => projects[projectId];
|
||||
@override
|
||||
Future<void> rememberTimeline(String projectId, String timelineId) async {
|
||||
projects[projectId] = timelineId;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late Directory root;
|
||||
late ProviderContainer container;
|
||||
late EditorToolAccess access;
|
||||
late int port;
|
||||
const token = "test-only-application-token-0123456789";
|
||||
const native = MethodChannel('cutdex_runtime');
|
||||
const events = MethodChannel('cutdex_runtime/sessions/source-test');
|
||||
final calls = <MethodCall>[];
|
||||
Completer<void>? blockedProbe;
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('cutdex-application-tools-');
|
||||
final reservation = await ServerSocket.bind(
|
||||
InternetAddress.loopbackIPv4,
|
||||
0,
|
||||
);
|
||||
port = reservation.port;
|
||||
await reservation.close();
|
||||
container = ProviderContainer(
|
||||
retry: (_, _) => null,
|
||||
overrides: [
|
||||
recentProjectsProvider.overrideWithValue(MemoryRecent()),
|
||||
projectLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryProjectLocationSettingsRepository(root.path),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
editorMcpConfigurationProvider.overrideWithValue(
|
||||
EditorMcpConfiguration(port: port, token: token),
|
||||
),
|
||||
],
|
||||
);
|
||||
access = container.read(applicationToolAccessProvider);
|
||||
calls.clear();
|
||||
blockedProbe = null;
|
||||
messenger.setMockMethodCallHandler(events, (call) async {
|
||||
if (call.method == 'listen') {
|
||||
scheduleMicrotask(
|
||||
() => messenger.handlePlatformMessage(
|
||||
events.name,
|
||||
const StandardMethodCodec().encodeSuccessEnvelope({
|
||||
'type': 'attached',
|
||||
}),
|
||||
(_) {},
|
||||
),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
messenger.setMockMethodCallHandler(native, (call) async {
|
||||
calls.add(call);
|
||||
switch (call.method) {
|
||||
case 'probe':
|
||||
await blockedProbe?.future;
|
||||
return {
|
||||
'duration': MediaTime(10, 1).toMap(),
|
||||
'videoTrackCount': 1,
|
||||
'videoTrackIds': [1],
|
||||
'audioTrackCount': 0,
|
||||
'audioTrackIds': <int>[],
|
||||
'audioTracks': <Object?>[],
|
||||
'isProtected': false,
|
||||
'videoDisplaySizes': [
|
||||
{'width': 1080.0, 'height': 1920.0},
|
||||
],
|
||||
};
|
||||
case 'createSession':
|
||||
return {'sessionId': 'source-test'};
|
||||
case 'load':
|
||||
return '1';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
});
|
||||
tearDown(() async {
|
||||
final state = container.read(projectsProvider).asData?.value;
|
||||
if (state?.activeProject != null && state?.timeline != null) {
|
||||
await container
|
||||
.read(
|
||||
previewTargetProvider(state!.activeProject!.id, state.timeline!.id),
|
||||
)
|
||||
.closeSource();
|
||||
}
|
||||
await access.dispose();
|
||||
// UI/provider disposal owns the project; allow its async cleanup to finish.
|
||||
container.dispose();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 50));
|
||||
await root.delete(recursive: true);
|
||||
messenger.setMockMethodCallHandler(native, null);
|
||||
messenger.setMockMethodCallHandler(events, null);
|
||||
});
|
||||
|
||||
test(
|
||||
'opening a known path with a wrong project ID is a definite rejection',
|
||||
() async {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final path = '${root.path}/Mismatch.cutdex';
|
||||
expect(await projects.open(path, name: 'Mismatch'), isTrue);
|
||||
final before = container.read(projectsProvider).requireValue;
|
||||
final result = await access.workspaces['application']!.invoke(
|
||||
name: 'project.open',
|
||||
arguments: {'path': path, 'projectId': 'wrong-id'},
|
||||
context: CommandContext(
|
||||
operationId: 'mismatch',
|
||||
isCancelled: () => false,
|
||||
),
|
||||
);
|
||||
expect(result.status, CommandStatus.rejected);
|
||||
expect(result.code, 'projectIdMismatch');
|
||||
expect(result.message, contains(before.activeProject!.id));
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.activeProject!.id,
|
||||
before.activeProject!.id,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('Agent adds explicitly created timelines to its run binding', () async {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open(
|
||||
'${root.path}/AgentCreate.cutdex',
|
||||
name: 'AgentCreate',
|
||||
),
|
||||
true,
|
||||
);
|
||||
final state = container.read(projectsProvider).requireValue;
|
||||
final projectId = state.activeProject!.id;
|
||||
final binding = await container.read(
|
||||
FutureProvider<EditorAgentBinding>(
|
||||
(ref) => createEditorAgentBinding(ref, projectId, state.timeline!.id),
|
||||
).future,
|
||||
);
|
||||
addTearDown(() async => binding.release?.call());
|
||||
Future<ToolResult> call(String name, Map<String, Object?> arguments) =>
|
||||
binding.tools
|
||||
.singleWhere((tool) => tool.name == name)
|
||||
.execute(
|
||||
ToolCall(id: name, name: name, arguments: arguments),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: name,
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
final created = await call('timeline_create', {
|
||||
'workspaceId': 'application',
|
||||
'projectId': projectId,
|
||||
'name': 'Commentary',
|
||||
});
|
||||
expect(created.isError, false);
|
||||
final current = container.read(projectsProvider).requireValue;
|
||||
expect(current.timeline!.id, isNot(state.timeline!.id));
|
||||
final target = 'sequence:${current.timeline!.sequences.first.id.value}';
|
||||
final workspaces = await call('cutdex_workspaces', {});
|
||||
expect(workspaces.text, contains(target));
|
||||
expect(
|
||||
workspaces.text,
|
||||
contains('sequence:${state.timeline!.sequences.first.id.value}'),
|
||||
);
|
||||
final query = await call('timeline_query', {'workspaceId': target});
|
||||
expect(query.isError, false);
|
||||
expect(query.data.toString(), contains(current.timeline!.id));
|
||||
});
|
||||
|
||||
test(
|
||||
'Agent tool binding keeps its timeline after switching projects',
|
||||
() async {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open('${root.path}/Pinned.cutdex', name: 'Pinned'),
|
||||
isTrue,
|
||||
);
|
||||
final first = container.read(projectsProvider).requireValue;
|
||||
final projectId = first.activeProject!.id;
|
||||
final timelineId = first.timeline!.id;
|
||||
final bindingProvider = FutureProvider<EditorAgentBinding>(
|
||||
(ref) => createEditorAgentBinding(ref, projectId, timelineId),
|
||||
);
|
||||
final binding = await container.read(bindingProvider.future);
|
||||
var released = false;
|
||||
addTearDown(() async {
|
||||
if (!released) await binding.release?.call();
|
||||
});
|
||||
final catalog = binding.tools.singleWhere(
|
||||
(tool) => tool.name == 'cutdex_workspaces',
|
||||
);
|
||||
final before = await catalog.execute(
|
||||
ToolCall(id: 'before', name: catalog.name, arguments: const {}),
|
||||
ToolContext(
|
||||
sessionId: 'session',
|
||||
runId: 'run',
|
||||
operationId: 'before',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
expect(
|
||||
before.text,
|
||||
contains('sequence:${first.timeline!.sequences.first.id.value}'),
|
||||
);
|
||||
|
||||
expect(
|
||||
await projects.open('${root.path}/Other.cutdex', name: 'Other'),
|
||||
isTrue,
|
||||
);
|
||||
final after = await catalog.execute(
|
||||
ToolCall(id: 'after', name: catalog.name, arguments: const {}),
|
||||
ToolContext(
|
||||
sessionId: 'session',
|
||||
runId: 'run',
|
||||
operationId: 'after',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
expect(after.text, before.text);
|
||||
final workspaceId = ((jsonDecode(after.text) as Map)['targets'] as List)
|
||||
.map((target) => (target as Map)['workspaceId'] as String)
|
||||
.firstWhere((id) => id != 'application');
|
||||
final query = binding.tools.singleWhere(
|
||||
(tool) => tool.name == 'timeline_query',
|
||||
);
|
||||
final queried = await query.execute(
|
||||
ToolCall(
|
||||
id: 'query',
|
||||
name: query.name,
|
||||
arguments: {'workspaceId': workspaceId},
|
||||
),
|
||||
ToolContext(
|
||||
sessionId: 'session',
|
||||
runId: 'run',
|
||||
operationId: 'query',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
expect(queried.isError, isFalse);
|
||||
final manifest = File('${root.path}/Pinned.cutdex/manifest.json');
|
||||
final backup = await manifest.rename('${manifest.path}.backup');
|
||||
final cancellation = CancellationToken();
|
||||
await expectLater(
|
||||
catalog.execute(
|
||||
ToolCall(id: 'missing', name: catalog.name, arguments: const {}),
|
||||
ToolContext(
|
||||
sessionId: 'session',
|
||||
runId: 'run',
|
||||
operationId: 'missing',
|
||||
cancellation: cancellation,
|
||||
onProgress: (_) {},
|
||||
),
|
||||
),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
expect(cancellation.isCancelled, isTrue);
|
||||
await backup.rename(manifest.path);
|
||||
await binding.release?.call();
|
||||
released = true;
|
||||
},
|
||||
);
|
||||
|
||||
test('one MCP connection creates projects and switches projects; Agent catalog stays usable', () async {
|
||||
final subscription = container.listen(
|
||||
applicationMcpConnectionProvider,
|
||||
(_, _) {},
|
||||
);
|
||||
addTearDown(subscription.close);
|
||||
await container.read(applicationMcpConnectionProvider.future);
|
||||
final socket = await Socket.connect(InternetAddress.loopbackIPv4, port);
|
||||
final lines = StreamIterator(
|
||||
socket
|
||||
.cast<List<int>>()
|
||||
.transform(utf8.decoder)
|
||||
.transform(const LineSplitter()),
|
||||
);
|
||||
addTearDown(() async {
|
||||
socket.destroy();
|
||||
await lines.cancel();
|
||||
});
|
||||
socket.writeln(token);
|
||||
var requestId = 0;
|
||||
Future<Map<dynamic, dynamic>> invoke(
|
||||
String name,
|
||||
Map<String, Object?> args, {
|
||||
String workspace = 'application',
|
||||
String? operation,
|
||||
}) async {
|
||||
socket.writeln(
|
||||
jsonEncode({
|
||||
'jsonrpc': '2.0',
|
||||
'id': ++requestId,
|
||||
'method': 'tools/call',
|
||||
'params': {
|
||||
'_meta': {
|
||||
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
||||
'io.modelcontextprotocol/clientCapabilities': <String, Object?>{},
|
||||
},
|
||||
'name': name,
|
||||
'arguments': {
|
||||
if (name != 'cutdex.workspaces') 'workspaceId': workspace,
|
||||
'operationId': ?operation,
|
||||
...args,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(await lines.moveNext().timeout(const Duration(seconds: 5)), true);
|
||||
final response = jsonDecode(lines.current) as Map;
|
||||
expect(response['error'], isNull, reason: '$response');
|
||||
return (response['result'] as Map)['structuredContent'] as Map;
|
||||
}
|
||||
|
||||
// Cache Agent declarations before any project exists.
|
||||
final agentTools = access.agentTools;
|
||||
final created = await invoke('project.create', {
|
||||
'name': 'A',
|
||||
}, operation: 'project');
|
||||
expect(created['status'], 'succeeded', reason: '$created');
|
||||
expect((created['data'] as Map)['activeTimelineId'], isA<String>());
|
||||
final project =
|
||||
((created['data'] as Map)['project'] as Map)['projectId'] as String;
|
||||
final first = await invoke('timeline.create', {
|
||||
'projectId': project,
|
||||
'name': 'One',
|
||||
}, operation: 'one');
|
||||
expect(first['status'], 'succeeded', reason: '$first');
|
||||
final one = (first['data'] as Map)['timelineId'] as String;
|
||||
expect((first['data'] as Map)['activeTimelineId'], one);
|
||||
final originalWorkspace = access.workspaces.keys.singleWhere(
|
||||
(id) => id != 'application',
|
||||
);
|
||||
final edited = await invoke(
|
||||
'project.setCanvas',
|
||||
{'width': 1080, 'height': 1920},
|
||||
workspace: originalWorkspace,
|
||||
operation: 'canvas',
|
||||
);
|
||||
expect(edited['edit'], 'committed');
|
||||
final second = await invoke('timeline.create', {
|
||||
'projectId': project,
|
||||
'name': 'Two',
|
||||
}, operation: 'two');
|
||||
final two = (second['data'] as Map)['timelineId'] as String;
|
||||
final opened = await invoke('timeline.open', {
|
||||
'projectId': project,
|
||||
'timelineId': two,
|
||||
}, operation: 'open-two');
|
||||
expect(opened['status'], 'succeeded', reason: '$opened');
|
||||
expect((opened['data'] as Map)['activeTimelineId'], two);
|
||||
expect(access.workspaces.containsKey(originalWorkspace), false);
|
||||
final receipt = await invoke('cutdex.operation', {
|
||||
'operationId': 'canvas',
|
||||
}, workspace: originalWorkspace);
|
||||
expect(receipt['code'], 'unknownWorkspace');
|
||||
final query = agentTools.singleWhere(
|
||||
(tool) => tool.name == 'timeline_query',
|
||||
);
|
||||
final workspace = access.workspaces.keys.singleWhere(
|
||||
(id) => id != 'application',
|
||||
);
|
||||
final args = {'workspaceId': workspace};
|
||||
expect(query.validate(args), isNull);
|
||||
final agentResult = await query.execute(
|
||||
ToolCall(id: 'query', name: query.name, arguments: args),
|
||||
ToolContext(
|
||||
sessionId: 's',
|
||||
runId: 'r',
|
||||
operationId: 'query',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
),
|
||||
);
|
||||
expect(agentResult.isError, false);
|
||||
expect(agentResult.text, 'Timeline');
|
||||
expect(agentResult.data['status'], 'succeeded');
|
||||
expect(agentResult.data['data'], contains('clips'));
|
||||
final reopened = await invoke('timeline.open', {
|
||||
'projectId': project,
|
||||
'timelineId': one,
|
||||
}, operation: 'return-one');
|
||||
expect(reopened['status'], 'succeeded', reason: '$reopened');
|
||||
final session = await container.read(
|
||||
editorTimelineProvider(project, one).future,
|
||||
);
|
||||
expect(session.canvas.width, 1080);
|
||||
expect(session.canvas.height, 1920);
|
||||
final version = session.version;
|
||||
final selected = await invoke('sequence.select', {
|
||||
'projectId': project,
|
||||
'timelineId': one,
|
||||
'sequenceId': session.document.sequences.first.id.value,
|
||||
}, operation: 'select');
|
||||
expect(selected['status'], 'succeeded');
|
||||
expect(session.version, version);
|
||||
final missing = await invoke('timeline.open', {
|
||||
'projectId': project,
|
||||
'timelineId': 'missing',
|
||||
}, operation: 'missing');
|
||||
expect(missing['status'], 'rejected');
|
||||
expect(missing['code'], 'missingTimeline');
|
||||
expect(session.acceptsEdits, true);
|
||||
final projects = await invoke('project.query', {});
|
||||
expect(jsonEncode(projects), contains('A.cutdex'));
|
||||
final b = await invoke('project.create', {
|
||||
'name': 'B',
|
||||
}, operation: 'project-b');
|
||||
expect(b['status'], 'succeeded', reason: '$b');
|
||||
final back = await invoke('project.open', {
|
||||
'path': '${root.path}/A.cutdex',
|
||||
'projectId': project,
|
||||
}, operation: 'back-a');
|
||||
expect(back['status'], 'succeeded', reason: '$back');
|
||||
final listed = await invoke('timeline.list', {'projectId': project});
|
||||
expect(listed['status'], 'succeeded');
|
||||
final listData = listed['data'] as Map;
|
||||
expect(listData['activeTimelineId'], one);
|
||||
expect(
|
||||
(listData['timelines'] as List).map(
|
||||
(item) => (item as Map)['timelineId'],
|
||||
),
|
||||
containsAll([one, two]),
|
||||
);
|
||||
expect(listData.containsKey('projects'), isFalse);
|
||||
final replay = await invoke('timeline.create', {
|
||||
'projectId': project,
|
||||
'name': 'Two',
|
||||
}, operation: 'two');
|
||||
expect((replay['data'] as Map)['timelineId'], two);
|
||||
});
|
||||
|
||||
test(
|
||||
'source tools share target, preserve timeline and reuse one native player',
|
||||
() async {
|
||||
final tools = access.workspaces['application']!;
|
||||
var operation = 0;
|
||||
Future<CommandResult> invoke(String name, Map<String, Object?> args) =>
|
||||
tools.invoke(
|
||||
name: name,
|
||||
arguments: args,
|
||||
context: CommandContext(operationId: 'source-${++operation}'),
|
||||
);
|
||||
final created = await invoke('project.create', {'name': 'Sources'});
|
||||
final projectId = (created.data['project'] as Map)['projectId'] as String;
|
||||
final timelineId =
|
||||
(await invoke('timeline.create', {
|
||||
'projectId': projectId,
|
||||
'name': 'Timeline',
|
||||
})).data['timelineId']
|
||||
as String;
|
||||
final sequence = access.workspaces.values.last;
|
||||
final file = await File('${root.path}/video.mov')
|
||||
.writeAsString('fixture');
|
||||
await sequence.invoke(
|
||||
name: 'media.import',
|
||||
arguments: {'path': file.path},
|
||||
context: const CommandContext(operationId: 'import'),
|
||||
);
|
||||
final asset = container.read(projectsProvider).requireValue.assets.single;
|
||||
final target = container.read(
|
||||
previewTargetProvider(projectId, timelineId),
|
||||
);
|
||||
final session = await container.read(
|
||||
editorTimelineProvider(projectId, timelineId).future,
|
||||
);
|
||||
final version = session.version;
|
||||
final ids = {'projectId': projectId, 'timelineId': timelineId};
|
||||
final opened = await invoke('sourcePreview.open', {
|
||||
...ids,
|
||||
'mediaId': asset.id,
|
||||
});
|
||||
expect(
|
||||
opened.status.name,
|
||||
'succeeded',
|
||||
reason: '${opened.toJson()} native: ${target.source?.error}',
|
||||
);
|
||||
expect(target.asset?.id, asset.id);
|
||||
await invoke('sourcePreview.open', {...ids, 'mediaId': asset.id});
|
||||
final source = target.source;
|
||||
expect(
|
||||
(await invoke('sourcePreview.play', {
|
||||
...ids,
|
||||
'mediaId': asset.id,
|
||||
})).status.name,
|
||||
'succeeded',
|
||||
);
|
||||
expect(
|
||||
(await invoke('sourcePreview.pause', {
|
||||
...ids,
|
||||
'mediaId': asset.id,
|
||||
})).status.name,
|
||||
'succeeded',
|
||||
);
|
||||
final seek = await invoke('sourcePreview.seek', {
|
||||
...ids,
|
||||
'mediaId': asset.id,
|
||||
'at': {'numerator': '3', 'denominator': 2},
|
||||
});
|
||||
expect(seek.status.name, 'succeeded', reason: '${seek.toJson()}');
|
||||
expect(target.source, same(source));
|
||||
expect(calls.where((c) => c.method == 'createSession'), hasLength(1));
|
||||
expect(calls.any((c) => c.method == 'pause'), true);
|
||||
expect(
|
||||
(await invoke('sourcePreview.seek', {
|
||||
...ids,
|
||||
'mediaId': 'wrong',
|
||||
'at': {'numerator': '0', 'denominator': 1},
|
||||
})).status.name,
|
||||
'rejected',
|
||||
);
|
||||
expect(session.version, version);
|
||||
expect(session.dirty, false);
|
||||
expect(
|
||||
(await invoke('sourcePreview.close', ids)).status.name,
|
||||
'succeeded',
|
||||
);
|
||||
expect(target.asset, isNull);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
expect(
|
||||
(await invoke('sourcePreview.query', ids)).data['available'],
|
||||
false,
|
||||
);
|
||||
|
||||
blockedProbe = Completer<void>();
|
||||
final count = calls.where((call) => call.method == 'probe').length;
|
||||
final opening = invoke('sourcePreview.open', {
|
||||
...ids,
|
||||
'mediaId': asset.id,
|
||||
});
|
||||
for (
|
||||
var i = 0;
|
||||
i < 100 &&
|
||||
calls.where((call) => call.method == 'probe').length == count;
|
||||
i++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 2));
|
||||
}
|
||||
target.showTimeline();
|
||||
blockedProbe!.complete();
|
||||
expect((await opening).status.name, 'unknown');
|
||||
await target.closeSource();
|
||||
expect(target.source, isNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,527 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/editor_acceptance.dart';
|
||||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||||
import 'package:cutdex/integrations/editor_command_host.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_prompt_policy.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime/contracts.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _AudioMedia implements EditorMediaService, EditorAudioSource {
|
||||
_AudioMedia(this.source);
|
||||
final Uri source;
|
||||
bool silent = false;
|
||||
void Function()? onRead;
|
||||
@override
|
||||
Future<List<EditorMediaAsset>> query() async => [
|
||||
EditorMediaAsset(id: 'source', name: 'Original'),
|
||||
];
|
||||
@override
|
||||
Future<PreparedEditorMedia> prepare(String id) async => PreparedEditorMedia(
|
||||
asset: EditorMediaAsset(id: id, name: 'Original'),
|
||||
uri: source,
|
||||
duration: RationalTime.seconds(12),
|
||||
kind: EditorMediaKind.audio,
|
||||
hasAudio: true,
|
||||
);
|
||||
@override
|
||||
Future<EditorMediaImportResult> importFile(
|
||||
String path, {
|
||||
bool Function()? isCancelled,
|
||||
}) => throw UnimplementedError();
|
||||
@override
|
||||
Future<MediaWaveform> waveform(String id, int track) async {
|
||||
onRead?.call();
|
||||
final nativePath = Platform.environment['CUTDEX_BEAT_NATIVE_WAVEFORM'];
|
||||
if (nativePath != null && !silent) {
|
||||
return MediaWaveform.fromMap(
|
||||
jsonDecode(await File(nativePath).readAsString()) as Map,
|
||||
);
|
||||
}
|
||||
|
||||
final values = <double>[];
|
||||
for (var i = 0; i < 1200; i++) {
|
||||
final v = silent
|
||||
? 0.0
|
||||
: i % 50 == 10
|
||||
? (i % 200 == 10 ? .9 : .4)
|
||||
: .01;
|
||||
values.addAll([-v, v, v]);
|
||||
}
|
||||
return MediaWaveform.fromMap({
|
||||
'sampleRate': 1000,
|
||||
'sourceStartSeconds': 0,
|
||||
'frameCount': 12000,
|
||||
'trackId': track,
|
||||
'channelCount': 1,
|
||||
'levels': [
|
||||
{
|
||||
'samplesPerBucket': 10,
|
||||
'channels': [values],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late Directory root;
|
||||
late ProjectFile project;
|
||||
late EditorTimelineSession session;
|
||||
late List<AgentTool> originals;
|
||||
late EditorAcceptance acceptance;
|
||||
late Map<String, AgentTool> tools;
|
||||
final sequence = SequenceId('main');
|
||||
var serial = 0;
|
||||
final history = <AgentMessage>[];
|
||||
ToolContext context() => ToolContext(
|
||||
sessionId: 'trial',
|
||||
runId: 'run',
|
||||
operationId: 'op-${serial++}',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
);
|
||||
Future<ToolResult> invoke(
|
||||
String name,
|
||||
Map<String, Object?> args, {
|
||||
bool record = true,
|
||||
}) async {
|
||||
final call = ToolCall(
|
||||
id: 'call-${serial++}',
|
||||
name: name,
|
||||
arguments: {'workspaceId': 'timeline', ...args},
|
||||
);
|
||||
final t = tools[name]!;
|
||||
expect(t.validate(call.arguments), isNull);
|
||||
final result = await t.execute(call, context());
|
||||
if (record) {
|
||||
history.add(AgentMessage(role: MessageRole.assistant, calls: [call]));
|
||||
history.add(
|
||||
AgentMessage(
|
||||
role: MessageRole.tool,
|
||||
callId: call.id,
|
||||
text: jsonEncode(result.toJson()),
|
||||
isError: result.isError,
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<String> version() async =>
|
||||
(await invoke('timeline_query', {}, record: false)).data['version']
|
||||
as String;
|
||||
Future<void> save() async {
|
||||
expect(
|
||||
(await invoke('project_save', {
|
||||
'expectedVersion': await version(),
|
||||
}, record: false)).isError,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
Future<ToolResult> check() => acceptance.check(
|
||||
SessionSnapshot(id: 'trial', runId: 'run', history: history),
|
||||
CancellationToken(),
|
||||
);
|
||||
setUp(() async {
|
||||
history.clear();
|
||||
serial = 0;
|
||||
root = await Directory.systemTemp.createTemp('cutdex-acceptance-');
|
||||
project = await ProjectFile.create(
|
||||
Directory('${root.path}/acceptance.cutdex'),
|
||||
name: 'Acceptance',
|
||||
);
|
||||
await project.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'source',
|
||||
name: 'Original',
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('${root.path}/source.wav').toString(),
|
||||
),
|
||||
);
|
||||
final document = TimelineDocument(
|
||||
id: 'p',
|
||||
name: 'Acceptance',
|
||||
sequences: [
|
||||
TimelineDto(
|
||||
id: sequence,
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: []),
|
||||
],
|
||||
elements: [],
|
||||
),
|
||||
],
|
||||
);
|
||||
await project.saveTimeline(document);
|
||||
session = EditorTimelineSession(
|
||||
document: await project.loadTimeline('p'),
|
||||
persistence: await project.openTimelineSaveSession('p'),
|
||||
media: _AudioMedia(Uri.file('${root.path}/source.wav')),
|
||||
);
|
||||
session.insertAsset(
|
||||
sequenceId: sequence,
|
||||
assetId: 'source',
|
||||
assetName: 'Original',
|
||||
uri: Uri.file('${root.path}/source.wav'),
|
||||
duration: RationalTime.seconds(12),
|
||||
position: 0,
|
||||
kind: 'audio',
|
||||
hasAudio: true,
|
||||
clipId: ElementId('clip'),
|
||||
);
|
||||
session.insertAsset(
|
||||
sequenceId: sequence,
|
||||
assetId: 'source',
|
||||
assetName: 'Reference',
|
||||
uri: Uri.file('${root.path}/source.wav'),
|
||||
duration: RationalTime.seconds(12),
|
||||
position: 12 * TimelineClock.ticksPerSecond,
|
||||
kind: 'audio',
|
||||
hasAudio: true,
|
||||
clipId: ElementId('music'),
|
||||
);
|
||||
session.commands.applyEdit(
|
||||
sequence,
|
||||
PlaceClip(
|
||||
clipId: 'music',
|
||||
at: CommandTime(0, 1),
|
||||
side: ClipPlacement.above,
|
||||
),
|
||||
);
|
||||
originals = editorAgentTools({
|
||||
'timeline': editorToolsFor(session, sequence),
|
||||
});
|
||||
acceptance = EditorAcceptance(originals);
|
||||
tools = {
|
||||
for (final t in [...originals, ...acceptance.tools]) t.name: t,
|
||||
};
|
||||
});
|
||||
tearDown(() async {
|
||||
await session.close();
|
||||
await project.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
test(
|
||||
'real tool chain plans, cuts, saves and verifies every second beat',
|
||||
() async {
|
||||
final plan = await invoke('timeline_planBeatCuts', {
|
||||
'audioClipId': 'music',
|
||||
'clipIds': ['clip'],
|
||||
'durationSeconds': 12,
|
||||
'every': 2,
|
||||
'requireCuts': true,
|
||||
});
|
||||
expect(plan.isError, false, reason: plan.text);
|
||||
final data = plan.data['data'] as Map;
|
||||
final actions = data['actions'] as List;
|
||||
expect(actions.length, 12);
|
||||
expect((await check()).isError, true);
|
||||
for (final action in actions) {
|
||||
final result = await invoke(action['tool'] as String, {
|
||||
...(action['arguments'] as Map).cast<String, Object?>(),
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
expect(result.isError, false, reason: result.text);
|
||||
}
|
||||
await save();
|
||||
final verified = await check();
|
||||
expect(verified.isError, false, reason: jsonEncode(verified.toJson()));
|
||||
final stored = await project.loadTimeline('p');
|
||||
expect(stored.sequences.single.elements.length, 14);
|
||||
// An extra off-beat split must invalidate the old receipt.
|
||||
final extra = await invoke('timeline_split', {
|
||||
'clipId': 'clip',
|
||||
'at': {'numerator': '1', 'denominator': 30},
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
expect(extra.isError, false, reason: extra.text);
|
||||
await save();
|
||||
expect((await check()).isError, true);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'read-only plans do not demand edits; source trim and speed map beats',
|
||||
() async {
|
||||
await invoke('clip_setSpeed', {
|
||||
'clipId': 'music',
|
||||
'speed': 2,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
final plan = await invoke('timeline_planBeatCuts', {
|
||||
'audioClipId': 'music',
|
||||
'clipIds': ['clip'],
|
||||
'durationSeconds': 12,
|
||||
'every': 2,
|
||||
});
|
||||
expect(plan.isError, false, reason: plan.text);
|
||||
final data = plan.data['data'] as Map;
|
||||
final actions = data['actions'] as List;
|
||||
final last = (actions.last['arguments'] as Map)['at'] as Map;
|
||||
final t =
|
||||
double.parse(last['numerator'] as String) /
|
||||
(last['denominator'] as int);
|
||||
expect(t, closeTo(2 / 30, 0.000001));
|
||||
await save();
|
||||
expect((await check()).isError, false);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'low-confidence audio and concurrent timeline edits cannot authorize cuts',
|
||||
() async {
|
||||
final media = session.media as _AudioMedia;
|
||||
media.silent = true;
|
||||
final silent = await invoke('timeline_planBeatCuts', {
|
||||
'audioClipId': 'music',
|
||||
'clipIds': ['clip'],
|
||||
'durationSeconds': 12,
|
||||
'requireCuts': true,
|
||||
});
|
||||
expect(silent.isError, true);
|
||||
expect(silent.data['code'], 'uncertainBeat');
|
||||
media.silent = false;
|
||||
media.onRead = () => session.commands.applyEdit(
|
||||
sequence,
|
||||
const SetClipAudio(clipId: 'clip', db: -3),
|
||||
);
|
||||
final stale = await invoke('audio_analyze', {
|
||||
'clipId': 'music',
|
||||
'durationSeconds': 12,
|
||||
});
|
||||
expect(stale.isError, true);
|
||||
expect(stale.data['code'], 'staleVersion');
|
||||
},
|
||||
);
|
||||
test(
|
||||
'trimmed reference maps only beats inside the retained source range',
|
||||
() async {
|
||||
final trim = await invoke('timeline_trim', {
|
||||
'clipId': 'music',
|
||||
'duration': {'numerator': '10', 'denominator': 1},
|
||||
'leading': true,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
expect(trim.isError, false, reason: trim.text);
|
||||
final plan = await invoke('timeline_planBeatCuts', {
|
||||
'audioClipId': 'music',
|
||||
'clipIds': ['clip'],
|
||||
'durationSeconds': 12,
|
||||
'every': 2,
|
||||
});
|
||||
expect(plan.isError, false, reason: plan.text);
|
||||
final actions = (plan.data['data'] as Map)['actions'] as List;
|
||||
expect(actions.length, 10);
|
||||
final time = actions.last['arguments']['at'] as Map;
|
||||
expect(
|
||||
double.parse(time['numerator'] as String) /
|
||||
(time['denominator'] as num),
|
||||
closeTo(2.1, 0.000001),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('montage mode trims three shots to successive beats and verifies saved ranges', () async {
|
||||
for (var i = 2; i <= 3; i++) {
|
||||
session.insertAsset(
|
||||
sequenceId: sequence,
|
||||
assetId: 'source',
|
||||
assetName: 'Shot $i',
|
||||
uri: Uri.file('${root.path}/source.wav'),
|
||||
duration: RationalTime.seconds(12),
|
||||
position: (i - 1) * 12 * TimelineClock.ticksPerSecond,
|
||||
kind: 'video',
|
||||
hasAudio: false,
|
||||
clipId: ElementId('shot$i'),
|
||||
);
|
||||
}
|
||||
final plan = await invoke('timeline_planBeatCuts', {
|
||||
'audioClipId': 'music',
|
||||
'clipIds': ['clip', 'shot2', 'shot3'],
|
||||
'durationSeconds': 4,
|
||||
'every': 2,
|
||||
'phase': 1,
|
||||
'mode': 'fitClips',
|
||||
'requireCuts': true,
|
||||
});
|
||||
expect(plan.isError, false, reason: plan.text);
|
||||
expect((await check()).isError, true);
|
||||
for (final action in (plan.data['data'] as Map)['actions'] as List) {
|
||||
final result = await invoke(action['tool'] as String, {
|
||||
...(action['arguments'] as Map).cast<String, Object?>(),
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
expect(result.isError, false, reason: result.text);
|
||||
}
|
||||
await save();
|
||||
final verified = await check();
|
||||
expect(verified.isError, false, reason: jsonEncode(verified.toJson()));
|
||||
final stored = (await project.loadTimeline('p')).sequences.single;
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('clip'))
|
||||
.duration
|
||||
.seconds,
|
||||
closeTo(.6, .00001),
|
||||
);
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('shot2'))
|
||||
.duration
|
||||
.seconds,
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('shot3'))
|
||||
.duration
|
||||
.seconds,
|
||||
1,
|
||||
);
|
||||
});
|
||||
test(
|
||||
'live agent discovers audio tools and completes beat editing',
|
||||
() async {
|
||||
final config =
|
||||
jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map;
|
||||
final overrides = HttpOverrides.current;
|
||||
HttpOverrides.global = null;
|
||||
addTearDown(() => HttpOverrides.global = overrides);
|
||||
final model = OpenAiResponsesAdapter(
|
||||
baseUrl: Uri.parse(config['baseUrl'] as String),
|
||||
model: config['model'] as String,
|
||||
apiKey: config['key'] as String,
|
||||
);
|
||||
final manager = SessionManager(
|
||||
model: model,
|
||||
store: InMemorySessionStore(),
|
||||
tools: tools.values,
|
||||
completionCheck: acceptance.check,
|
||||
contextBuilder: HarnessContextBuilder(
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
maxInputTokens: 32000,
|
||||
summarizer: ModelContextSummarizer(
|
||||
model: model,
|
||||
budget: ContextBuilder(maxInputTokens: 32000),
|
||||
),
|
||||
),
|
||||
);
|
||||
final conversation = await manager.create(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
);
|
||||
final end = await (await manager.prompt(
|
||||
conversation.id,
|
||||
'对timeline工作区的clip片段做音乐卡点,参考music音频素材前4秒,每两拍切一次;实际执行分割,保留全部画面内容和音频,保存并核验。',
|
||||
maxTurns: 45,
|
||||
)).done;
|
||||
expect(end.status, RunStatus.completed, reason: end.error);
|
||||
final evidence =
|
||||
(end.completionEvidence!['result'] as Map)['data'] as Map;
|
||||
expect(evidence['contracts'], 1);
|
||||
expect(evidence['issues'], isEmpty);
|
||||
final current = await invoke('timeline_query', {}, record: false);
|
||||
expect(
|
||||
((current.data['data'] as Map)['primaryClipIds'] as List).length,
|
||||
5,
|
||||
);
|
||||
stdout.writeln(
|
||||
'LIVE_BEAT_EDIT_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
|
||||
);
|
||||
},
|
||||
skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null,
|
||||
timeout: const Timeout(Duration(minutes: 5)),
|
||||
);
|
||||
test(
|
||||
'live agent trims a montage to beat-aligned shot changes',
|
||||
() async {
|
||||
for (var i = 2; i <= 3; i++) {
|
||||
session.insertAsset(
|
||||
sequenceId: sequence,
|
||||
assetId: 'source',
|
||||
assetName: 'Shot $i',
|
||||
uri: Uri.file('${root.path}/source.wav'),
|
||||
duration: RationalTime.seconds(12),
|
||||
position: (i - 1) * 12 * TimelineClock.ticksPerSecond,
|
||||
kind: 'video',
|
||||
hasAudio: false,
|
||||
clipId: ElementId('shot$i'),
|
||||
);
|
||||
}
|
||||
final config =
|
||||
jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map;
|
||||
final overrides = HttpOverrides.current;
|
||||
HttpOverrides.global = null;
|
||||
addTearDown(() => HttpOverrides.global = overrides);
|
||||
final model = OpenAiResponsesAdapter(
|
||||
baseUrl: Uri.parse(config['baseUrl'] as String),
|
||||
model: config['model'] as String,
|
||||
apiKey: config['key'] as String,
|
||||
);
|
||||
final manager = SessionManager(
|
||||
model: model,
|
||||
store: InMemorySessionStore(),
|
||||
tools: tools.values,
|
||||
completionCheck: acceptance.check,
|
||||
contextBuilder: HarnessContextBuilder(
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
maxInputTokens: 32000,
|
||||
summarizer: ModelContextSummarizer(
|
||||
model: model,
|
||||
budget: ContextBuilder(maxInputTokens: 32000),
|
||||
),
|
||||
),
|
||||
);
|
||||
final conversation = await manager.create(
|
||||
system: AgentPromptPolicy.editorAssistant,
|
||||
);
|
||||
final end = await (await manager.prompt(
|
||||
conversation.id,
|
||||
'在timeline工作区,把clip、shot2、shot3三个主时间线镜头按现有顺序做卡点换镜头。参考music音频素材前4秒,从第2个检测到的节拍开始每两拍一个切点,裁短每个镜头尾部来匹配连续切点;保留音乐,不要只把原片段分割,实际执行、保存并核验。',
|
||||
maxTurns: 45,
|
||||
)).done;
|
||||
expect(end.status, RunStatus.completed, reason: end.error);
|
||||
final evidence =
|
||||
(end.completionEvidence!['result'] as Map)['data'] as Map;
|
||||
expect(evidence['contracts'], 1);
|
||||
expect(evidence['issues'], isEmpty);
|
||||
final stored = (await project.loadTimeline('p')).sequences.single;
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('clip'))
|
||||
.duration
|
||||
.seconds,
|
||||
closeTo(.6, .00001),
|
||||
);
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('shot2'))
|
||||
.duration
|
||||
.seconds,
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
stored.elements
|
||||
.singleWhere((e) => e.id == ElementId('shot3'))
|
||||
.duration
|
||||
.seconds,
|
||||
1,
|
||||
);
|
||||
stdout.writeln(
|
||||
'LIVE_BEAT_MONTAGE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
|
||||
);
|
||||
},
|
||||
skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null,
|
||||
timeout: const Timeout(Duration(minutes: 5)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/integrations/runtime/timeline_waveforms.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/features/properties/audio_gain_scale.dart';
|
||||
import 'package:cutdex/features/properties/audio_properties.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'gain mapping is monotonic, reversible and reserves a mute endpoint',
|
||||
() {
|
||||
var previous = -91.0;
|
||||
for (var i = 0; i <= 1020; i++) {
|
||||
final db = -90 + i / 10;
|
||||
final position = AudioGainScale.positionAt(db);
|
||||
expect(position, greaterThan(0));
|
||||
expect(AudioGainScale.dbAt(position), closeTo(db, 1e-10));
|
||||
expect(db, greaterThan(previous));
|
||||
previous = db;
|
||||
}
|
||||
expect(
|
||||
AudioGainScale.positionAt(6) - AudioGainScale.positionAt(-24),
|
||||
closeTo(.7, 1e-10),
|
||||
);
|
||||
expect(AudioGainScale.dbAt(1), closeTo(12, 1e-10));
|
||||
expect(() => AudioGainScale.positionAt(double.nan), throwsArgumentError);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'detached audio shows restore and preserves the independent clip',
|
||||
(tester) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true),
|
||||
))!;
|
||||
final sequence = SequenceId('one');
|
||||
final id = ElementId('clip');
|
||||
final waveforms = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (ref) => f.timeline.mediaBinding(ref)?.media,
|
||||
);
|
||||
addTearDown(waveforms.dispose);
|
||||
final view = f.timeline.view(sequence);
|
||||
ElementRecord current() {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return q.element(q.elementById(id)!);
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 225,
|
||||
child: AudioProperties(
|
||||
session: f.timeline,
|
||||
sequence: sequence,
|
||||
clip: current(),
|
||||
hasAudio: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.runAsync(() async {
|
||||
f.timeline.commands.setAudio(
|
||||
sequence: sequence,
|
||||
clip: id,
|
||||
db: -18,
|
||||
muted: true,
|
||||
);
|
||||
await f.timeline.flush();
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('音频已分离'), findsNothing);
|
||||
expect(waveforms.hasAudioFor(current()), isTrue);
|
||||
late ElementId detached;
|
||||
await tester.runAsync(() async {
|
||||
f.timeline.commands.setAudio(
|
||||
sequence: sequence,
|
||||
clip: id,
|
||||
muted: false,
|
||||
);
|
||||
detached = f.timeline.detachAudio(sequence, id);
|
||||
await f.timeline.flush();
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('音频已分离'), findsOneWidget);
|
||||
expect(find.byKey(const Key('audio-slider')), findsNothing);
|
||||
final before = view.version.kernelVersion;
|
||||
final q = before.query();
|
||||
final copy = q.element(q.elementById(detached)!);
|
||||
final speedPreview = f.timeline.previewClipSpeed(sequence, detached, 2)!;
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
final speedQuery = speedPreview.result.version.kernelVersion.query();
|
||||
expect(
|
||||
speedQuery.element(speedQuery.elementById(detached)!).duration,
|
||||
copy.duration ~/ 2,
|
||||
);
|
||||
expect(
|
||||
speedQuery.element(speedQuery.elementById(id)!).duration,
|
||||
q.element(q.elementById(id)!).duration,
|
||||
);
|
||||
speedPreview.cancel();
|
||||
// Keep the audio region while suppressing only its waveform.
|
||||
expect(waveforms.hasAudioFor(current()), isTrue);
|
||||
expect(waveforms.waveformFor(current()), isNull);
|
||||
expect(waveforms.hasAudioFor(copy), isTrue);
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.byKey(const Key('audio-restore')));
|
||||
await tester.pump();
|
||||
await f.timeline.flush();
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('音频已分离'), findsNothing);
|
||||
expect(find.byKey(const Key('audio-slider')), findsOneWidget);
|
||||
expect(ClipAudioGain.fromRecord(current()).muted, isFalse);
|
||||
expect(waveforms.hasAudioFor(current()), isTrue);
|
||||
expect(ClipAudioGain.fromRecord(current()).db, -18);
|
||||
final restored = view.version.kernelVersion.query();
|
||||
expect(restored.element(restored.elementById(detached)!), same(copy));
|
||||
await tester.runAsync(() async {
|
||||
f.timeline.undo(sequence);
|
||||
await f.timeline.flush();
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(find.text('音频已分离'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('gain input, mute, drag history, reset and persistence', (
|
||||
tester,
|
||||
) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true),
|
||||
))!;
|
||||
final sequence = SequenceId('one');
|
||||
final view = f.timeline.view(sequence);
|
||||
final query = view.version.kernelVersion.query();
|
||||
final clip = query.element(query.elementById(ElementId('clip'))!);
|
||||
ClipAudioGain current() {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return ClipAudioGain.fromRecord(q.element(q.elementById(clip.id)!));
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 225,
|
||||
child: AudioProperties(
|
||||
session: f.timeline,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
hasAudio: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final field = find.byType(TextField);
|
||||
await tester.enterText(field, '-18');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await tester.pump();
|
||||
expect(current().db, -18);
|
||||
await tester.tap(find.byKey(const Key('audio-mute')));
|
||||
await tester.pump();
|
||||
expect(current().muted, isTrue);
|
||||
expect(current().db, -18);
|
||||
await tester.tap(find.byKey(const Key('audio-mute')));
|
||||
await tester.pump();
|
||||
expect(current().muted, isFalse);
|
||||
final before = view.version.kernelVersion;
|
||||
AppSlider slider() => tester.widget<AppSlider>(find.byType(AppSlider));
|
||||
slider().onChangeStart!(.5);
|
||||
for (final p in [.3, .4, .8]) {
|
||||
slider().onChanged!(p);
|
||||
await tester.pump();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(
|
||||
f.timeline.waveformGain(clip),
|
||||
closeTo(ClipAudioGain(AudioGainScale.dbAt(p)).amplitudeScale, .02),
|
||||
);
|
||||
}
|
||||
slider().onChangeEnd!(.8);
|
||||
await tester.pump();
|
||||
expect(current().db, 1.7);
|
||||
expect(f.timeline.audioGainPreview.value, isNull);
|
||||
view.undo();
|
||||
await tester.pump();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(current().db, -18);
|
||||
slider().onChangeStart!(.5);
|
||||
slider().onChanged!(0);
|
||||
await tester.pump();
|
||||
expect(f.timeline.waveformGain(clip), 0);
|
||||
slider().onChangeEnd!(0);
|
||||
await tester.pump();
|
||||
expect(current().muted, isTrue);
|
||||
await tester.runAsync(() async {
|
||||
await f.timeline.flush();
|
||||
final saved = await f.workspace.project!.loadTimeline('project');
|
||||
final curves = saved.sequences.first.elements.single.parameters;
|
||||
expect(
|
||||
curves
|
||||
.firstWhere((p) => p.definition.id == ClipAudioGain.muteId)
|
||||
.definition
|
||||
.defaultValue,
|
||||
0,
|
||||
);
|
||||
expect(curves.every((p) => p.definition.defaultValue.isFinite), isTrue);
|
||||
expect(
|
||||
saved.settings['parameterTargets'],
|
||||
containsPair(ClipAudioGain.muteId, 'audioVolume'),
|
||||
);
|
||||
final compiled = const ExecutionCompiler().compile(
|
||||
ExecutionInput(
|
||||
timeline: f.timeline.persistence.timeline(sequence),
|
||||
renderSize: RenderSize(64, 64),
|
||||
parameterTargets: ClipAudioGain.targets,
|
||||
media: {
|
||||
PayloadRef('source'): ExecutionMediaBinding(
|
||||
media: MediaReference(
|
||||
id: 'media',
|
||||
uri: Uri.file('/test/video.mov'),
|
||||
),
|
||||
audioTrackSelection: TrackSelection.index(0),
|
||||
),
|
||||
},
|
||||
),
|
||||
);
|
||||
final automation = compiled.plan.audioLayers.single.automation;
|
||||
expect(
|
||||
automation.firstWhere((a) => a.target == 'audioVolume').defaultValue,
|
||||
0,
|
||||
);
|
||||
expect(
|
||||
automation.firstWhere((a) => a.target == 'audioGainDb').defaultValue,
|
||||
-18,
|
||||
);
|
||||
expect(compiled.plan.visualLayers, isNotEmpty);
|
||||
});
|
||||
await tester.tap(find.byKey(const Key('audio-reset')));
|
||||
await tester.pump();
|
||||
expect(current().db, 0);
|
||||
expect(current().muted, isFalse);
|
||||
await tester.enterText(field, '20');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await tester.pump();
|
||||
expect(current().db, 0);
|
||||
expect(find.text('请输入 -90 到 +12 之间的数值'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
slider().onChangeStart!(.5);
|
||||
slider().onChanged!(.9);
|
||||
await tester.pump();
|
||||
expect(f.timeline.audioGainPreview.value, isNotNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
expect(f.timeline.audioGainPreview.value, isNull);
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
});
|
||||
testWidgets(
|
||||
'volume keys interpolate, retain mute edits and survive undo and save',
|
||||
(tester) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true),
|
||||
))!;
|
||||
final sequence = SequenceId('one');
|
||||
final view = f.timeline.view(sequence);
|
||||
final id = ElementId('clip');
|
||||
ElementRecord record() {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return q.element(q.elementById(id)!);
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 225,
|
||||
child: AudioProperties(
|
||||
session: f.timeline,
|
||||
sequence: sequence,
|
||||
clip: record(),
|
||||
hasAudio: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
tester.getCenter(find.byKey(const Key('audio-slider'))).dy,
|
||||
closeTo(tester.getCenter(find.byKey(const Key('audio-db'))).dy, .01),
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('audio-key')));
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 1);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.enterText(find.byType(TextField), '-12');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 2);
|
||||
view.seekTo(TimelineClock.ticksPerSecond ~/ 2);
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.widget<TextField>(find.byType(TextField)).controller!.text,
|
||||
'-6.0',
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('audio-mute')));
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 2);
|
||||
expect(ClipAudioGain.fromRecord(record()).muted, isTrue);
|
||||
view.undo();
|
||||
await tester.pump();
|
||||
expect(ClipAudioGain.fromRecord(record()).muted, isFalse);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.tap(find.byKey(const Key('audio-key')));
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 1);
|
||||
view.undo();
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 2);
|
||||
await tester.runAsync(f.timeline.flush);
|
||||
final saved = f.timeline.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.singleWhere((element) => element.id == id);
|
||||
expect(
|
||||
saved.parameters
|
||||
.firstWhere((curve) => curve.definition.id == ClipAudioGain.gainId)
|
||||
.keyframes
|
||||
.length,
|
||||
2,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import 'package:cutdex/features/assistant/breakable_selectable_text.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('long path wraps by character and copies without soft breaks', (
|
||||
tester,
|
||||
) async {
|
||||
const path = '/Users/example/Desktop/包含中文的长截图文件名.png';
|
||||
String? copied;
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
copied = (call.arguments as Map<dynamic, dynamic>)['text'] as String?;
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(
|
||||
() => messenger.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 220,
|
||||
child: BreakableSelectableText(
|
||||
text: path,
|
||||
style: TextStyle(fontSize: 16),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final selectable = tester.widget<SelectableText>(
|
||||
find.byType(SelectableText),
|
||||
);
|
||||
expect(selectable.data, contains('\u200B'));
|
||||
expect(selectable.data!.replaceAll('\u200B', ''), path);
|
||||
final paragraph = TextPainter(
|
||||
text: TextSpan(text: selectable.data, style: selectable.style),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout(maxWidth: 220);
|
||||
expect(paragraph.computeLineMetrics().first.width, greaterThan(190));
|
||||
|
||||
await tester.tap(find.byType(SelectableText));
|
||||
final editable = tester.state<EditableTextState>(find.byType(EditableText));
|
||||
editable.userUpdateTextEditingValue(
|
||||
editable.textEditingValue.copyWith(
|
||||
selection: TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: selectable.data!.length,
|
||||
),
|
||||
),
|
||||
SelectionChangedCause.keyboard,
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.keyC);
|
||||
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
|
||||
await tester.pump();
|
||||
expect(copied, path);
|
||||
|
||||
copied = null;
|
||||
final menu = selectable.contextMenuBuilder!(
|
||||
tester.element(find.byType(SelectableText)),
|
||||
editable,
|
||||
) as AdaptiveTextSelectionToolbar;
|
||||
menu.buttonItems!
|
||||
.singleWhere((button) => button.type == ContextMenuButtonType.copy)
|
||||
.onPressed!();
|
||||
await tester.pump();
|
||||
expect(copied, path);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,135 @@
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test(
|
||||
'grouped keys interpolate, retain other channels, undo and persist',
|
||||
() async {
|
||||
final f = await createPreviewFixture(
|
||||
Uri.file('/test/video.mov'),
|
||||
clipDuration: RationalTime.seconds(5),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
final id = SequenceId('one');
|
||||
final clip = ElementId('clip');
|
||||
final view = f.timeline.view(id);
|
||||
ClipAnimation at(int second) {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return ClipAnimation.at(
|
||||
q,
|
||||
q.elementById(clip)!,
|
||||
second * TimelineClock.ticksPerSecond,
|
||||
TimelineClock.ticksPerSecond ~/ 30,
|
||||
);
|
||||
}
|
||||
|
||||
void commit(List<ParameterCurveDto> curves) =>
|
||||
f.timeline.commitParameters(
|
||||
id,
|
||||
f.timeline.previewParameters(id, clip, curves),
|
||||
parameterTargets: ClipTransform.targets,
|
||||
);
|
||||
commit(at(0).toggle(TransformChannel.position));
|
||||
commit(at(2).edit(at(2).value.copyWith(x: .4, y: .2)));
|
||||
expect(at(1).value.x, closeTo(.2, 1e-10));
|
||||
expect(at(1).value.y, closeTo(.1, 1e-10));
|
||||
expect(at(2).keyed(TransformChannel.position), isTrue);
|
||||
expect(at(0).keyTimes(TransformChannel.position), [
|
||||
0,
|
||||
2 * TimelineClock.ticksPerSecond,
|
||||
]);
|
||||
commit(at(1).edit(at(1).value.copyWith(rotation: 45)));
|
||||
expect(at(0).value.rotation, 45);
|
||||
expect(at(2).value.x, .4);
|
||||
final before = view.version.kernelVersion;
|
||||
commit(
|
||||
at(0).setInterpolation(
|
||||
TransformChannel.position,
|
||||
ParameterInterpolation.hold,
|
||||
),
|
||||
);
|
||||
expect(at(1).value.x, 0);
|
||||
view.undo();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(at(1).value.x, closeTo(.2, 1e-10));
|
||||
view.redo();
|
||||
expect(at(1).value.x, 0);
|
||||
view.undo();
|
||||
await f.timeline.flush();
|
||||
final saved = await f.workspace.project!.loadTimeline('project');
|
||||
final savedClip = saved.sequences.first.elements.single;
|
||||
expect(
|
||||
savedClip.parameters
|
||||
.firstWhere((p) => p.definition.id == 'canvas.position.x')
|
||||
.keyframes
|
||||
.length,
|
||||
2,
|
||||
);
|
||||
expect(
|
||||
saved.settings['parameterTargets'],
|
||||
containsPair('canvas.position.y', 'position.y'),
|
||||
);
|
||||
commit(at(2).toggle(TransformChannel.position));
|
||||
expect(at(2).value.x, 0);
|
||||
commit(at(0).toggle(TransformChannel.position));
|
||||
expect(at(0).animated(TransformChannel.position), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'independent dimensions remain grouped and clearing holds evaluated values',
|
||||
() async {
|
||||
final f = await createPreviewFixture(
|
||||
Uri.file('/test/video.mov'),
|
||||
clipDuration: RationalTime.seconds(5),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
final id = SequenceId('one');
|
||||
final clip = ElementId('clip');
|
||||
final view = f.timeline.view(id);
|
||||
ClipAnimation at(int seconds) {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return ClipAnimation.at(
|
||||
q,
|
||||
q.elementById(clip)!,
|
||||
seconds * TimelineClock.ticksPerSecond,
|
||||
TimelineClock.ticksPerSecond ~/ 30,
|
||||
);
|
||||
}
|
||||
|
||||
void commit(List<ParameterCurveDto> curves) =>
|
||||
f.timeline.commitParameters(
|
||||
id,
|
||||
f.timeline.previewParameters(id, clip, curves),
|
||||
parameterTargets: ClipTransform.targets,
|
||||
);
|
||||
commit(at(0).toggle(TransformChannel.scale));
|
||||
commit(at(2).edit(at(2).value.copyWith(scaleY: 3)));
|
||||
expect(at(1).value.scale, 1);
|
||||
expect(at(1).value.scaleY, 2);
|
||||
expect(at(2).keyed(TransformChannel.scale), isTrue);
|
||||
commit(at(1).clear(TransformChannel.scale));
|
||||
expect(at(0).animated(TransformChannel.scale), isFalse);
|
||||
expect(at(0).value.scaleY, 2);
|
||||
expect(at(4).value.scaleY, 2);
|
||||
expect(at(5).containsPlayhead, isFalse);
|
||||
expect(() => at(5).toggle(TransformChannel.scale), throwsStateError);
|
||||
commit(at(2).toggle(TransformChannel.rotation));
|
||||
commit(at(2).edit(at(2).value.copyWith(rotation: 90)));
|
||||
commit(at(2).toggle(TransformChannel.rotation));
|
||||
expect(at(0).animated(TransformChannel.rotation), isFalse);
|
||||
expect(at(0).value.rotation, 90);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:cutdex/features/properties/animation_labels.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test(
|
||||
'mask grouped animation retains values, interpolates, and survives undo',
|
||||
() async {
|
||||
final f = await createPreviewFixture(
|
||||
Uri.file('/test/video.mov'),
|
||||
clipDuration: RationalTime.seconds(5),
|
||||
);
|
||||
addTearDown(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
final sequence = SequenceId('one');
|
||||
final id = ElementId('clip');
|
||||
final view = f.timeline.view(sequence);
|
||||
ClipMaskAnimation at(int seconds) {
|
||||
final query = view.version.kernelVersion.query();
|
||||
return ClipMaskAnimation(
|
||||
query.element(query.elementById(id)!),
|
||||
seconds * TimelineClock.ticksPerSecond,
|
||||
maskId: 'first',
|
||||
);
|
||||
}
|
||||
|
||||
void commit(List<ParameterCurveDto> curves) =>
|
||||
f.timeline.commitParameters(
|
||||
sequence,
|
||||
f.timeline.previewParameters(sequence, id, curves),
|
||||
);
|
||||
commit(at(0).edit(const ClipMask(shape: ClipMaskShape.rectangle)));
|
||||
commit(at(0).toggle(maskChannels['position']!));
|
||||
commit(at(2).edit(at(2).value.copyWith(x: .9)));
|
||||
expect(at(1).value.x, closeTo(.7, 1e-9));
|
||||
expect(at(1).value.y, .5);
|
||||
expect(at(2).keyed(maskChannels['position']!), isTrue);
|
||||
view.undo();
|
||||
expect(at(2).value.x, .5);
|
||||
view.redo();
|
||||
expect(at(2).value.x, .9);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:cutdex/features/assistant/composer_document.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _media = ComposerReference(
|
||||
kind: ComposerReferenceKind.media,
|
||||
projectId: 'project',
|
||||
id: 'media-1',
|
||||
label: '片段.mp4',
|
||||
);
|
||||
|
||||
void main() {
|
||||
test('reference insertion adds one separating space and places the caret after it', () {
|
||||
final atEnd = ComposerDocumentController(text: '看 @片段');
|
||||
addTearDown(atEnd.dispose);
|
||||
atEnd.insertReference(2, 5, _media);
|
||||
expect(atEnd.text, '看 @片段.mp4 ');
|
||||
expect(atEnd.selection.extentOffset, atEnd.text.length);
|
||||
expect(atEnd.marks.single.end, atEnd.text.length - 1);
|
||||
|
||||
final beforeSpace = ComposerDocumentController(text: '@片段 后面');
|
||||
addTearDown(beforeSpace.dispose);
|
||||
beforeSpace.insertReference(0, 3, _media);
|
||||
expect(beforeSpace.text, '@片段.mp4 后面');
|
||||
expect(
|
||||
beforeSpace.selection.extentOffset,
|
||||
beforeSpace.marks.single.end + 1,
|
||||
);
|
||||
});
|
||||
|
||||
test('reference insertion, atomic deletion and undo/redo', () {
|
||||
final controller = ComposerDocumentController(text: '看 @片段 后面');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(2, 5, _media);
|
||||
expect(controller.text, '看 @片段.mp4 后面');
|
||||
expect(
|
||||
controller.segments.map(
|
||||
(segment) => switch (segment) {
|
||||
ComposerText() => null,
|
||||
ComposerReferenceSegment(:final value) => value.id,
|
||||
},
|
||||
),
|
||||
[null, 'media-1', null],
|
||||
);
|
||||
|
||||
final mark = controller.marks.single;
|
||||
controller.value = controller.value.copyWith(
|
||||
text: controller.text.replaceRange(mark.end - 1, mark.end, ''),
|
||||
selection: TextSelection.collapsed(offset: mark.end - 1),
|
||||
);
|
||||
expect(controller.text, '看 后面');
|
||||
expect(controller.marks, isEmpty);
|
||||
controller.undoDocument();
|
||||
expect(controller.text, '看 @片段.mp4 后面');
|
||||
expect(controller.marks.single.reference.id, 'media-1');
|
||||
controller.redoDocument();
|
||||
expect(controller.marks, isEmpty);
|
||||
});
|
||||
|
||||
test('caret and selection cannot split a reference', () {
|
||||
final controller = ComposerDocumentController(text: 'a @m z');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(2, 4, _media);
|
||||
final mark = controller.marks.single;
|
||||
controller.selection = TextSelection.collapsed(offset: mark.start + 1);
|
||||
expect(controller.selection.extentOffset, mark.start);
|
||||
controller.selection = TextSelection(
|
||||
baseOffset: mark.start + 1,
|
||||
extentOffset: mark.end + 1,
|
||||
);
|
||||
expect(controller.selection.start, mark.start);
|
||||
expect(controller.selection.end, mark.end + 1);
|
||||
});
|
||||
|
||||
test('Chinese composing range and plain paste remain text', () {
|
||||
final controller = ComposerDocumentController();
|
||||
addTearDown(controller.dispose);
|
||||
controller.value = const TextEditingValue(
|
||||
text: '拼',
|
||||
selection: TextSelection.collapsed(offset: 1),
|
||||
composing: TextRange(start: 0, end: 1),
|
||||
);
|
||||
expect(controller.value.composing, const TextRange(start: 0, end: 1));
|
||||
controller.value = const TextEditingValue(
|
||||
text: '图片.png',
|
||||
selection: TextSelection.collapsed(offset: 6),
|
||||
);
|
||||
expect(controller.marks, isEmpty);
|
||||
});
|
||||
|
||||
test('invalid reference blocks send until project is restored', () {
|
||||
final controller = ComposerDocumentController(text: '@');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(0, 1, _media);
|
||||
controller.updateValidity((reference) => reference.projectId == 'other');
|
||||
expect(controller.hasInvalidReferences, isTrue);
|
||||
controller.updateValidity((reference) => reference.projectId == 'project');
|
||||
expect(controller.hasInvalidReferences, isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import 'package:cutdex/features/assistant/composer_document.dart';
|
||||
import 'package:cutdex/features/assistant/composer_reference_validator.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const media = ComposerReference(
|
||||
kind: ComposerReferenceKind.media,
|
||||
projectId: 'project',
|
||||
id: 'asset',
|
||||
label: '旧名称.mp4',
|
||||
);
|
||||
const timeline = ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: 'project',
|
||||
id: 'timeline',
|
||||
label: '时间线',
|
||||
);
|
||||
final workspace = ProjectState(
|
||||
activeProject: const RecentProject(
|
||||
id: 'project',
|
||||
name: '项目',
|
||||
path: '/project.cutdex',
|
||||
),
|
||||
assets: [
|
||||
AssetDocument(
|
||||
id: 'asset',
|
||||
name: '新名称.mp4',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///tmp/asset',
|
||||
),
|
||||
],
|
||||
timelines: const [
|
||||
TimelineSummary(id: 'timeline', name: '时间线', revision: 1),
|
||||
],
|
||||
);
|
||||
|
||||
test('rename keeps the stable media ID valid, deletion invalidates it', () {
|
||||
final controller = ComposerDocumentController(text: '@');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(0, 1, media);
|
||||
ComposerReferenceValidator(
|
||||
workspace: workspace,
|
||||
projectId: 'project',
|
||||
).validate(controller);
|
||||
expect(controller.hasInvalidReferences, isFalse);
|
||||
expect(controller.marks.single.reference.label, '旧名称.mp4');
|
||||
ComposerReferenceValidator(
|
||||
workspace: workspace.copyWith(assets: const []),
|
||||
projectId: 'project',
|
||||
).validate(controller);
|
||||
expect(controller.hasInvalidReferences, isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'draft references follow the active project without changing their IDs',
|
||||
() {
|
||||
final controller = ComposerDocumentController(text: '@');
|
||||
addTearDown(controller.dispose);
|
||||
controller.insertReference(0, 1, timeline);
|
||||
ComposerReferenceValidator(
|
||||
workspace: workspace,
|
||||
projectId: 'other',
|
||||
).validate(controller);
|
||||
expect(controller.hasInvalidReferences, isTrue);
|
||||
ComposerReferenceValidator(
|
||||
workspace: workspace,
|
||||
projectId: 'project',
|
||||
).validate(controller);
|
||||
expect(controller.hasInvalidReferences, isFalse);
|
||||
expect(controller.marks.single.reference.id, 'timeline');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'package:cutdex/features/assistant/composer_suggestions.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex/l10n/app_localizations_en.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('all triggers appear at word boundaries but not in paths or email', () {
|
||||
for (final trigger in ['@', '/', r'$']) {
|
||||
final value = TextEditingValue(
|
||||
text: 'hello $trigger片段',
|
||||
selection: TextSelection.collapsed(offset: 'hello $trigger片段'.length),
|
||||
);
|
||||
final query = findComposerTrigger(value, const []);
|
||||
expect(query?.trigger, trigger);
|
||||
expect(query?.query, '片段');
|
||||
}
|
||||
for (final plain in ['foo@example.com', '/Users/name', r'price$100']) {
|
||||
expect(
|
||||
findComposerTrigger(
|
||||
TextEditingValue(
|
||||
text: plain,
|
||||
selection: TextSelection.collapsed(offset: plain.length),
|
||||
),
|
||||
const [],
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
}
|
||||
const chinese = '看看@片段';
|
||||
expect(
|
||||
findComposerTrigger(
|
||||
const TextEditingValue(
|
||||
text: chinese,
|
||||
selection: TextSelection.collapsed(offset: 5),
|
||||
),
|
||||
const [],
|
||||
)?.query,
|
||||
'片段',
|
||||
);
|
||||
expect(
|
||||
findComposerTrigger(
|
||||
const TextEditingValue(
|
||||
text: '@p',
|
||||
selection: TextSelection.collapsed(offset: 2),
|
||||
composing: TextRange(start: 1, end: 2),
|
||||
),
|
||||
const [],
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'built-in current-project options distinguish equal names and filter',
|
||||
() {
|
||||
final options = ComposerOptionCatalog.forTrigger(
|
||||
'@',
|
||||
l10n: AppLocalizationsEn(),
|
||||
projectId: 'project',
|
||||
assets: [
|
||||
AssetDocument(
|
||||
id: 'asset',
|
||||
name: '片段',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///tmp/a',
|
||||
),
|
||||
],
|
||||
timelines: [
|
||||
const TimelineSummary(id: 'timeline', name: '片段', revision: 1),
|
||||
],
|
||||
);
|
||||
expect(options.length, 2);
|
||||
expect(options.map((option) => option.subtitle).toSet().length, 2);
|
||||
expect(filterComposerOptions(options, '片').length, 2);
|
||||
expect(
|
||||
ComposerOptionCatalog.forTrigger(
|
||||
'/',
|
||||
l10n: AppLocalizationsEn(),
|
||||
projectId: 'project',
|
||||
assets: const [],
|
||||
timelines: const [],
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
expect(
|
||||
ComposerOptionCatalog.forTrigger(
|
||||
r'$',
|
||||
l10n: AppLocalizationsEn(),
|
||||
projectId: 'project',
|
||||
assets: const [],
|
||||
timelines: const [],
|
||||
),
|
||||
isEmpty,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
void main() {
|
||||
final metadata = ConversationMetadata(
|
||||
id: 'conversation',
|
||||
projectId: 'project',
|
||||
title: 'Hello',
|
||||
createdAt: DateTime.utc(2026, 10, 1, 2),
|
||||
updatedAt: DateTime.utc(2026, 10, 1, 3),
|
||||
providerId: 'provider',
|
||||
modelId: 'model',
|
||||
timelineId: 'timeline',
|
||||
pending: false,
|
||||
responseDurationsMs: const [null, 1234],
|
||||
);
|
||||
|
||||
test('metadata persists identity, dates and missing reply durations', () {
|
||||
final restored = ConversationMetadata.fromJson(
|
||||
(jsonDecode(jsonEncode(metadata.toJson())) as Map)
|
||||
.cast<String, Object?>(),
|
||||
);
|
||||
expect(restored, metadata);
|
||||
expect(restored.copyWith(title: 'Renamed').responseDurationsMs, [
|
||||
null,
|
||||
1234,
|
||||
]);
|
||||
});
|
||||
|
||||
test('new metadata stores explicit pending state and empty durations', () {
|
||||
final encoded = metadata.copyWith(responseDurationsMs: []).toJson();
|
||||
expect(encoded['pending'], false);
|
||||
expect(encoded['responseDurationsMs'], isEmpty);
|
||||
expect(encoded.containsKey('version'), false);
|
||||
});
|
||||
|
||||
for (final field in ['pending', 'responseDurationsMs']) {
|
||||
test('stored metadata requires an explicit $field field', () {
|
||||
final json = metadata.toJson()..remove(field);
|
||||
expect(
|
||||
() => ConversationMetadata.fromJson(json),
|
||||
throwsA(isA<MissingRequiredKeysException>()),
|
||||
);
|
||||
});
|
||||
test('stored metadata rejects null $field values', () {
|
||||
final json = metadata.toJson()..[field] = null;
|
||||
expect(
|
||||
() => ConversationMetadata.fromJson(json),
|
||||
throwsA(isA<DisallowedNullValueException>()),
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
void main() {
|
||||
late Directory root;
|
||||
late ConversationRepository repository;
|
||||
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('cutdex-conversations-');
|
||||
repository = ConversationRepository(
|
||||
Directory('${root.path}/Conversations'),
|
||||
);
|
||||
});
|
||||
tearDown(() async => root.delete(recursive: true));
|
||||
|
||||
Future<ConversationMetadata> pending([String title = 'Hello']) =>
|
||||
repository.begin(
|
||||
projectId: 'project-1',
|
||||
timelineId: 'timeline-1',
|
||||
providerId: 'provider-1',
|
||||
modelId: 'model-1',
|
||||
title: title,
|
||||
);
|
||||
|
||||
Future<void> saveUser(ConversationMetadata item) => repository
|
||||
.store(item)
|
||||
.save(
|
||||
SessionSnapshot(
|
||||
id: item.id,
|
||||
history: [AgentMessage(role: MessageRole.user, text: 'Hello')],
|
||||
),
|
||||
expectedRevision: null,
|
||||
);
|
||||
|
||||
test('project and empty draft create no conversation files', () async {
|
||||
expect(await repository.list('project-1'), isEmpty);
|
||||
expect(await repository.root.exists(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'first persisted user message publishes a durable conversation',
|
||||
() async {
|
||||
final item = await pending();
|
||||
expect(await repository.list('project-1'), isEmpty);
|
||||
await saveUser(item);
|
||||
final published = await repository.publish(item);
|
||||
expect(published.pending, isFalse);
|
||||
expect(await repository.selected('project-1'), item.id);
|
||||
final reopened = ConversationRepository(repository.root);
|
||||
expect((await reopened.list('project-1')).single.id, item.id);
|
||||
expect(
|
||||
(await reopened.store(item).read(item.id))!.history.single.text,
|
||||
'Hello',
|
||||
);
|
||||
expect(await reopened.list('project-2'), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'startup discards empty pending draft but recovers saved user message',
|
||||
() async {
|
||||
final empty = await pending('empty');
|
||||
final recoverable = await pending('saved');
|
||||
await saveUser(recoverable);
|
||||
final reopened = ConversationRepository(repository.root);
|
||||
expect((await reopened.list('project-1')).map((item) => item.id), [
|
||||
recoverable.id,
|
||||
]);
|
||||
expect(
|
||||
await repository.directory('project-1', empty.id).exists(),
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'permanent deletion removes active history and selection only',
|
||||
() async {
|
||||
final first = await pending('delete');
|
||||
final second = await pending('keep');
|
||||
await saveUser(first);
|
||||
await saveUser(second);
|
||||
await repository.publish(second);
|
||||
await repository.publish(first);
|
||||
await repository.deletePermanently(first.projectId, first.id);
|
||||
expect(await repository.selected(first.projectId), second.id);
|
||||
expect(
|
||||
await repository.directory(first.projectId, first.id).exists(),
|
||||
isFalse,
|
||||
);
|
||||
expect((await repository.list(first.projectId)).single.id, second.id);
|
||||
expect(await repository.list(first.projectId, trash: true), isEmpty);
|
||||
await repository.deletePermanently(first.projectId, first.id);
|
||||
await repository.trash(second.projectId, second.id);
|
||||
await repository.deletePermanently(second.projectId, second.id);
|
||||
expect(await repository.list(second.projectId, trash: true), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'trash is reversible and does not affect another conversation',
|
||||
() async {
|
||||
final first = await pending('first');
|
||||
final second = await pending('second');
|
||||
await saveUser(first);
|
||||
await saveUser(second);
|
||||
await repository.publish(first);
|
||||
await repository.publish(second);
|
||||
await repository.trash('project-1', first.id);
|
||||
expect((await repository.list('project-1')).map((item) => item.id), [
|
||||
second.id,
|
||||
]);
|
||||
expect(
|
||||
(await repository.list('project-1', trash: true)).single.id,
|
||||
first.id,
|
||||
);
|
||||
await repository.restore('project-1', first.id);
|
||||
expect((await repository.list('project-1')).length, 2);
|
||||
},
|
||||
);
|
||||
|
||||
test('malformed metadata does not hide other conversations', () async {
|
||||
final healthy = await pending('healthy');
|
||||
final damaged = await pending('damaged');
|
||||
await saveUser(healthy);
|
||||
await repository.publish(healthy);
|
||||
await File(
|
||||
'${repository.directory('project-1', damaged.id).path}/metadata.json',
|
||||
).writeAsString('{"id":42}');
|
||||
final reopened = ConversationRepository(repository.root);
|
||||
expect((await reopened.list('project-1')).map((item) => item.id), [
|
||||
healthy.id,
|
||||
]);
|
||||
});
|
||||
|
||||
test('metadata requires a timeline identity', () async {
|
||||
final item = await pending('missing timeline');
|
||||
final file = File(
|
||||
'${repository.directory('project-1', item.id).path}/metadata.json',
|
||||
);
|
||||
final json =
|
||||
(jsonDecode(await file.readAsString()) as Map).cast<String, Object?>()
|
||||
..remove('timelineId');
|
||||
await file.writeAsString(jsonEncode(json));
|
||||
|
||||
expect(await repository.list('project-1'), isEmpty);
|
||||
await expectLater(
|
||||
repository.read('project-1', item.id),
|
||||
throwsA(isA<TypeError>()),
|
||||
);
|
||||
});
|
||||
|
||||
for (final field in ['pending', 'responseDurationsMs']) {
|
||||
test(
|
||||
'metadata missing $field is skipped without being rewritten',
|
||||
() async {
|
||||
final healthy = await pending('healthy');
|
||||
await saveUser(healthy);
|
||||
await repository.publish(healthy);
|
||||
final item = await pending('missing field');
|
||||
await repository.select(item.projectId, item.id);
|
||||
final file = File(
|
||||
'${repository.directory('project-1', item.id).path}/metadata.json',
|
||||
);
|
||||
final json = (jsonDecode(
|
||||
await file.readAsString(),
|
||||
) as Map).cast<String, Object?>()..remove(field);
|
||||
final stored = jsonEncode(json);
|
||||
await file.writeAsString(stored);
|
||||
final reopened = ConversationRepository(repository.root);
|
||||
expect((await reopened.list('project-1')).map((item) => item.id), [
|
||||
healthy.id,
|
||||
]);
|
||||
expect(await reopened.selected('project-1'), healthy.id);
|
||||
expect(await file.readAsString(), stored);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('selection state requires version 1', () async {
|
||||
final older = await pending('older');
|
||||
await saveUser(older);
|
||||
await repository.publish(older);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 2));
|
||||
final newer = await pending('newer');
|
||||
await saveUser(newer);
|
||||
await repository.publish(newer);
|
||||
final state = File(
|
||||
'${repository.directory('project-1', older.id).parent.path}/state.json',
|
||||
);
|
||||
await state.writeAsString(
|
||||
jsonEncode({'version': 2, 'conversationId': older.id}),
|
||||
);
|
||||
|
||||
expect(await repository.selected('project-1'), newer.id);
|
||||
});
|
||||
|
||||
test(
|
||||
'unset conversation location uses Documents without creating files',
|
||||
() async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final settings = DriftConversationLocationSettingsRepository(database);
|
||||
final location = ConversationLocation(
|
||||
settings,
|
||||
documentsDirectory: () async => root,
|
||||
);
|
||||
final directory = await location.load();
|
||||
expect(directory.path, p.join(root.path, 'Cutdex', 'Conversations'));
|
||||
expect(await directory.exists(), isFalse);
|
||||
expect(await settings.load(), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'selected conversation directory persists after reopening the database',
|
||||
() async {
|
||||
final file = File('${root.path}/app.sqlite');
|
||||
final database = AppDatabase(NativeDatabase(file));
|
||||
final item = await pending();
|
||||
await saveUser(item);
|
||||
await repository.publish(item);
|
||||
final location = ConversationLocation(
|
||||
DriftConversationLocationSettingsRepository(database),
|
||||
);
|
||||
await location.useExisting(repository.root);
|
||||
await database.close();
|
||||
|
||||
final reopened = AppDatabase(NativeDatabase(file));
|
||||
addTearDown(reopened.close);
|
||||
final restored = ConversationLocation(
|
||||
DriftConversationLocationSettingsRepository(reopened),
|
||||
);
|
||||
expect((await restored.load()).path, repository.root.path);
|
||||
expect(
|
||||
(await ConversationRepository(await restored.load()).list('project-1'))
|
||||
.single
|
||||
.id,
|
||||
item.id,
|
||||
);
|
||||
await expectLater(
|
||||
restored.useExisting(Directory('${root.path}/missing')),
|
||||
throwsA(
|
||||
isA<AppException>().having(
|
||||
(error) => error.failure.code,
|
||||
'code',
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect((await restored.load()).path, repository.root.path);
|
||||
},
|
||||
);
|
||||
|
||||
test('location relocation verifies journals and retains source', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final location = ConversationLocation(
|
||||
DriftConversationLocationSettingsRepository(database),
|
||||
);
|
||||
final item = await pending();
|
||||
await saveUser(item);
|
||||
await repository.publish(item);
|
||||
await repository.trash('project-1', item.id);
|
||||
final target = Directory('${root.path}/Moved');
|
||||
await location.relocate(repository.root, target);
|
||||
expect((await location.load()).path, target.path);
|
||||
expect(await repository.root.exists(), isTrue);
|
||||
expect(
|
||||
(await ConversationRepository(
|
||||
target,
|
||||
).list('project-1', trash: true)).single.id,
|
||||
item.id,
|
||||
);
|
||||
await target.delete(recursive: true);
|
||||
await expectLater(
|
||||
location.load(),
|
||||
throwsA(
|
||||
isA<AppException>().having(
|
||||
(error) => error.failure.code,
|
||||
'code',
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(await repository.root.exists(), isTrue);
|
||||
});
|
||||
|
||||
test('relocation refuses a destination inside its source', () async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final location = ConversationLocation(
|
||||
DriftConversationLocationSettingsRepository(database),
|
||||
);
|
||||
final item = await pending();
|
||||
await saveUser(item);
|
||||
await repository.publish(item);
|
||||
await expectLater(
|
||||
location.relocate(
|
||||
repository.root,
|
||||
Directory('${repository.root.path}/nested/Conversations'),
|
||||
),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
expect((await repository.list('project-1')).single.id, item.id);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import 'package:cutdex/integrations/platform/device_experience.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
const channel = MethodChannel('cutdex_native/device_info');
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
Future<DeviceExperience> detect(
|
||||
TargetPlatform platform, {
|
||||
Size displaySize = const Size(390, 844),
|
||||
double pixelRatio = 1,
|
||||
bool web = false,
|
||||
}) => DeviceExperienceDetector.detect(
|
||||
platform: platform,
|
||||
displaySize: displaySize,
|
||||
pixelRatio: pixelRatio,
|
||||
web: web,
|
||||
);
|
||||
|
||||
test('desktop and web hosts do not query mobile device facts', () async {
|
||||
var nativeCalls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
nativeCalls++;
|
||||
return {'interfaceIdiom': 'phone'};
|
||||
});
|
||||
for (final platform in [
|
||||
TargetPlatform.macOS,
|
||||
TargetPlatform.windows,
|
||||
TargetPlatform.linux,
|
||||
]) {
|
||||
expect(await detect(platform), DeviceExperience.desktop);
|
||||
}
|
||||
expect(
|
||||
await detect(TargetPlatform.android, web: true),
|
||||
DeviceExperience.phone,
|
||||
);
|
||||
expect(nativeCalls, 0);
|
||||
});
|
||||
|
||||
test('iOS device identity takes precedence over display size', () async {
|
||||
for (final entry in {
|
||||
'phone': DeviceExperience.phone,
|
||||
'pad': DeviceExperience.tablet,
|
||||
'mac': DeviceExperience.desktop,
|
||||
}.entries) {
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'getDeviceInfo');
|
||||
return {'interfaceIdiom': entry.key};
|
||||
});
|
||||
expect(await detect(TargetPlatform.iOS), entry.value);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'Android classification applies the app threshold to native bounds',
|
||||
() async {
|
||||
for (final entry in {
|
||||
599.5: DeviceExperience.phone,
|
||||
600.0: DeviceExperience.tablet,
|
||||
800.0: DeviceExperience.tablet,
|
||||
}.entries) {
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => {'displayShortestSideDp': entry.key},
|
||||
);
|
||||
expect(await detect(TargetPlatform.android), entry.value);
|
||||
}
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => {'displayShortestSideDp': 390},
|
||||
);
|
||||
expect(
|
||||
await detect(
|
||||
TargetPlatform.android,
|
||||
displaySize: const Size(1600, 2560),
|
||||
pixelRatio: 2,
|
||||
),
|
||||
DeviceExperience.phone,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'missing platform facts fall back to full display logical size',
|
||||
() async {
|
||||
for (final value in [
|
||||
<String, Object?>{},
|
||||
{'interfaceIdiom': 'pad'},
|
||||
{'displayShortestSideDp': 0},
|
||||
]) {
|
||||
messenger.setMockMethodCallHandler(channel, (call) async => value);
|
||||
expect(
|
||||
await detect(
|
||||
TargetPlatform.android,
|
||||
displaySize: const Size(1200, 1920),
|
||||
pixelRatio: 2,
|
||||
),
|
||||
DeviceExperience.tablet,
|
||||
);
|
||||
}
|
||||
messenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => {'displayShortestSideDp': 800},
|
||||
);
|
||||
expect(await detect(TargetPlatform.iOS), DeviceExperience.phone);
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
throw PlatformException(code: 'unavailable');
|
||||
});
|
||||
expect(
|
||||
await detect(
|
||||
TargetPlatform.iOS,
|
||||
displaySize: const Size(1170, 2532),
|
||||
pixelRatio: 3,
|
||||
),
|
||||
DeviceExperience.phone,
|
||||
);
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
expect(
|
||||
await detect(TargetPlatform.android, displaySize: Size.zero),
|
||||
DeviceExperience.phone,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||||
import 'package:cutdex/diagnostics/diagnostic_store.dart';
|
||||
import 'package:cutdex/features/settings/diagnostic_settings.dart';
|
||||
import 'package:cutdex/integrations/platform/file_picker.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/settings/settings_operation.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _Picker extends AppFilePicker {
|
||||
_Picker(this.destination);
|
||||
final String? destination;
|
||||
@override
|
||||
Future<String?> pickDirectory({
|
||||
String? initialDirectory,
|
||||
String? confirmButtonText,
|
||||
}) async => destination;
|
||||
}
|
||||
|
||||
void main() {
|
||||
late Directory root;
|
||||
setUp(() {
|
||||
root = Directory.systemTemp.createTempSync('cutdex-export-ui-');
|
||||
AppDiagnostics.instance = AppDiagnostics(
|
||||
DiagnosticStore(Directory('${root.path}/logs')),
|
||||
);
|
||||
});
|
||||
tearDown(() async {
|
||||
await AppDiagnostics.instance?.store.flush();
|
||||
AppDiagnostics.instance = null;
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
Future<ProviderContainer> show(
|
||||
WidgetTester tester,
|
||||
String? destination,
|
||||
) async {
|
||||
final container = ProviderContainer(
|
||||
overrides: [filePickerProvider.overrideWithValue(_Picker(destination))],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
theme: EditorTheme.penLight,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: const Scaffold(body: DiagnosticSettings()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return container;
|
||||
}
|
||||
|
||||
Future<void> click(WidgetTester tester, ProviderContainer container) async {
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(find.byKey(const Key('export-diagnostics')));
|
||||
for (
|
||||
var i = 0;
|
||||
i < 2000 &&
|
||||
container
|
||||
.read(settingsOperationProvider('diagnosticsExport'))
|
||||
.isLoading;
|
||||
i++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
expect(
|
||||
container
|
||||
.read(settingsOperationProvider('diagnosticsExport'))
|
||||
.isLoading,
|
||||
isFalse,
|
||||
);
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
testWidgets('exports a diagnostic package into the selected directory', (
|
||||
tester,
|
||||
) async {
|
||||
final container = await show(tester, '${root.path}/export');
|
||||
await tester.runAsync(() async {
|
||||
AppDiagnostics.report(
|
||||
const DiagnosticEvent(
|
||||
component: 'preview',
|
||||
operation: 'test',
|
||||
error: 'Bearer PRIVATE',
|
||||
),
|
||||
);
|
||||
await AppDiagnostics.instance!.store.flush();
|
||||
});
|
||||
await click(tester, container);
|
||||
expect(find.text('Diagnostic package saved.'), findsOneWidget);
|
||||
final directory = Directory('${root.path}/export');
|
||||
final files = directory.listSync().cast<File>().toList();
|
||||
expect(files, hasLength(1));
|
||||
final contents = files.single.readAsStringSync();
|
||||
expect(jsonDecode(contents)['events'], hasLength(1));
|
||||
expect(contents, isNot(contains('PRIVATE')));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'canceling directory selection leaves no success message or export',
|
||||
(tester) async {
|
||||
final container = await show(tester, null);
|
||||
await click(tester, container);
|
||||
expect(find.text('Diagnostic package saved.'), findsNothing);
|
||||
expect(
|
||||
container.read(settingsOperationProvider('diagnosticsExport')).hasError,
|
||||
isFalse,
|
||||
);
|
||||
expect(root.listSync(), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('export failures show feedback and leave the button usable', (
|
||||
tester,
|
||||
) async {
|
||||
final blocked = File('${root.path}/blocked')..writeAsStringSync('file');
|
||||
final container = await show(tester, blocked.path);
|
||||
await click(tester, container);
|
||||
expect(
|
||||
find.text('Could not export diagnostics. Please try again.'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
tester
|
||||
.widget<OutlinedButton>(find.byKey(const Key('export-diagnostics')))
|
||||
.onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -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]'));
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/editor_acceptance.dart';
|
||||
import 'package:cutdex/integrations/agent/agent_prompt_policy.dart';
|
||||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||||
import 'package:cutdex/integrations/editor_command_host.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'transcription_tools_test.dart' show Media;
|
||||
|
||||
class _Model implements ModelAdapter {
|
||||
_Model(this.action);
|
||||
final Future<ModelResponse> Function(ModelRequest, int) action;
|
||||
int requests = 0;
|
||||
@override
|
||||
Stream<ModelEvent> stream(ModelRequest request, CancellationToken c) async* {
|
||||
yield await action(request, requests++);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
late Directory root;
|
||||
late ProjectFile project;
|
||||
late EditorTimelineSession session;
|
||||
late List<AgentTool> originals;
|
||||
late EditorAcceptance acceptance;
|
||||
late Map<String, AgentTool> tools;
|
||||
final sequence = SequenceId('main');
|
||||
var serial = 0;
|
||||
final history = <AgentMessage>[];
|
||||
ToolContext context() => ToolContext(
|
||||
sessionId: 'trial',
|
||||
runId: 'run',
|
||||
operationId: 'op-${serial++}',
|
||||
cancellation: CancellationToken(),
|
||||
onProgress: (_) {},
|
||||
);
|
||||
Future<ToolResult> invoke(
|
||||
String name,
|
||||
Map<String, Object?> args, {
|
||||
bool record = true,
|
||||
}) async {
|
||||
final call = ToolCall(
|
||||
id: 'call-${serial++}',
|
||||
name: name,
|
||||
arguments: {'workspaceId': 'timeline', ...args},
|
||||
);
|
||||
final t = tools[name]!;
|
||||
expect(t.validate(call.arguments), isNull);
|
||||
final result = await t.execute(call, context());
|
||||
if (record) {
|
||||
history.add(AgentMessage(role: MessageRole.assistant, calls: [call]));
|
||||
history.add(
|
||||
AgentMessage(
|
||||
role: MessageRole.tool,
|
||||
callId: call.id,
|
||||
text: jsonEncode(result.toJson()),
|
||||
isError: result.isError,
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<String> version() async =>
|
||||
(await invoke('timeline_query', {}, record: false)).data['version']
|
||||
as String;
|
||||
Future<void> save() async {
|
||||
expect(
|
||||
(await invoke('project_save', {
|
||||
'expectedVersion': await version(),
|
||||
}, record: false)).isError,
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
Future<ToolResult> check() => acceptance.check(
|
||||
SessionSnapshot(id: 'trial', runId: 'run', history: history),
|
||||
CancellationToken(),
|
||||
);
|
||||
setUp(() async {
|
||||
history.clear();
|
||||
serial = 0;
|
||||
root = await Directory.systemTemp.createTemp('cutdex-acceptance-');
|
||||
project = await ProjectFile.create(
|
||||
Directory('${root.path}/acceptance.cutdex'),
|
||||
name: 'Acceptance',
|
||||
);
|
||||
await project.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'source',
|
||||
name: 'Original',
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('${root.path}/source.wav').toString(),
|
||||
),
|
||||
);
|
||||
final document = TimelineDocument(
|
||||
id: 'p',
|
||||
name: 'Acceptance',
|
||||
sequences: [
|
||||
TimelineDto(
|
||||
id: sequence,
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: []),
|
||||
],
|
||||
elements: [],
|
||||
),
|
||||
],
|
||||
);
|
||||
await project.saveTimeline(document);
|
||||
session = EditorTimelineSession(
|
||||
document: await project.loadTimeline('p'),
|
||||
persistence: await project.openTimelineSaveSession('p'),
|
||||
media: Media(Uri.file('${root.path}/source.wav')),
|
||||
);
|
||||
session.insertAsset(
|
||||
sequenceId: sequence,
|
||||
assetId: 'source',
|
||||
assetName: 'Original',
|
||||
uri: Uri.file('${root.path}/source.wav'),
|
||||
duration: RationalTime.seconds(5),
|
||||
position: 0,
|
||||
kind: 'audio',
|
||||
hasAudio: true,
|
||||
clipId: ElementId('clip'),
|
||||
);
|
||||
originals = editorAgentTools({
|
||||
'timeline': editorToolsFor(session, sequence),
|
||||
});
|
||||
acceptance = EditorAcceptance(originals);
|
||||
tools = {
|
||||
for (final t in [...originals, ...acceptance.tools]) t.name: t,
|
||||
};
|
||||
});
|
||||
tearDown(() async {
|
||||
await session.close();
|
||||
await project.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
test('real project readback detects wrong parameter and fresh edits invalidate success', () async {
|
||||
final registered = await invoke('editor_expect_clips', {
|
||||
'clips': [
|
||||
{
|
||||
'clipId': 'clip',
|
||||
'name': 'Original',
|
||||
'parameters': [
|
||||
{'parameterId': 'cutdex.audio.gainDb', 'value': -12},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(registered.isError, false);
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -6,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
final failed = await check();
|
||||
expect(failed.isError, true);
|
||||
expect(jsonEncode(failed.data), contains('cutdex.audio.gainDb'));
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -12,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
expect((await check()).isError, false);
|
||||
final persisted = (await project.loadTimeline('p'))
|
||||
.sequences
|
||||
.single
|
||||
.elements
|
||||
.singleWhere((e) => e.id == ElementId('clip'));
|
||||
expect(
|
||||
persisted.parameters
|
||||
.singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb')
|
||||
.definition
|
||||
.defaultValue,
|
||||
-12,
|
||||
);
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -3,
|
||||
'expectedVersion': await version(),
|
||||
}, record: false);
|
||||
await save();
|
||||
expect((await check()).isError, true);
|
||||
});
|
||||
test(
|
||||
'saved contracts survive fresh verifier and cannot be weakened',
|
||||
() async {
|
||||
await invoke('editor_expect_clips', {
|
||||
'clips': [
|
||||
{'clipId': 'clip', 'name': 'Expected'},
|
||||
],
|
||||
});
|
||||
acceptance = EditorAcceptance(originals);
|
||||
expect((await check()).isError, true);
|
||||
await invoke('editor_expect_clips', {
|
||||
'clips': [
|
||||
{'clipId': 'clip', 'name': 'Original'},
|
||||
],
|
||||
});
|
||||
final result = await check();
|
||||
expect(result.isError, true);
|
||||
expect(jsonEncode(result.data), contains('contractChanged'));
|
||||
},
|
||||
);
|
||||
test(
|
||||
'audio edits require the edited field and honor implicit defaults',
|
||||
() async {
|
||||
await invoke('editor_expect_clips', {
|
||||
'clips': [
|
||||
{'clipId': 'clip', 'name': 'Original'},
|
||||
],
|
||||
});
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -12,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
expect(jsonEncode((await check()).data), contains('missingExpectation'));
|
||||
history.clear();
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': 0,
|
||||
'muted': false,
|
||||
'expectedVersion': await version(),
|
||||
}, record: false);
|
||||
await invoke('editor_expect_clips', {
|
||||
'clips': [
|
||||
{
|
||||
'clipId': 'clip',
|
||||
'parameters': [
|
||||
{'parameterId': 'cutdex.audio.gainDb', 'value': 0},
|
||||
{'parameterId': 'cutdex.audio.mute', 'value': 1},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
await save();
|
||||
expect((await check()).isError, false);
|
||||
},
|
||||
);
|
||||
test('real captions check all pages and detect missing cues without semantic certification', () async {
|
||||
final a = await invoke('captionTrack_create', {
|
||||
'name': '日本語',
|
||||
'language': 'ja',
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
final source = ((a.data['data'] as Map)['roleId']) as String;
|
||||
final b = await invoke('captionTrack_create', {
|
||||
'name': '中文',
|
||||
'language': 'zh',
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
final target = ((b.data['data'] as Map)['roleId']) as String;
|
||||
await invoke('caption_add', {
|
||||
'roleId': source,
|
||||
'cues': [
|
||||
for (var i = 0; i < 101; i++)
|
||||
{
|
||||
'text': '字幕$i',
|
||||
'start': {'numerator': '${i * 2}', 'denominator': 1},
|
||||
'duration': {'numerator': '1', 'denominator': 1},
|
||||
},
|
||||
],
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
expect(
|
||||
(await invoke('editor_expect_translation', {
|
||||
'sourceRoleId': source,
|
||||
'targetRoleId': target,
|
||||
})).isError,
|
||||
false,
|
||||
);
|
||||
final page = await invoke('caption_list', {
|
||||
'roleId': source,
|
||||
'limit': 100,
|
||||
}, record: false);
|
||||
final cues = (page.data['data'] as Map)['cues'] as List;
|
||||
await invoke('caption_addTranslations', {
|
||||
'roleId': target,
|
||||
'cues': [
|
||||
for (final c in cues) {'sourceCaptionId': c['captionId'], 'text': '译文'},
|
||||
],
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
expect((await check()).isError, true);
|
||||
final rest = await invoke('caption_list', {
|
||||
'roleId': source,
|
||||
'offset': 100,
|
||||
'limit': 100,
|
||||
}, record: false);
|
||||
final last = ((rest.data['data'] as Map)['cues'] as List).single;
|
||||
await invoke('caption_addTranslations', {
|
||||
'roleId': target,
|
||||
'cues': [
|
||||
{'sourceCaptionId': last['captionId'], 'text': '译文'},
|
||||
],
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
final result = await check();
|
||||
expect(result.isError, false);
|
||||
expect(result.data['semanticQuality'], 'unverified');
|
||||
var changed = false;
|
||||
acceptance = EditorAcceptance(
|
||||
originals.map(
|
||||
(tool) => tool.name != 'caption_list'
|
||||
? tool
|
||||
: AgentTool(
|
||||
name: tool.name,
|
||||
description: tool.description,
|
||||
parameters: tool.parameters,
|
||||
validate: tool.validate,
|
||||
execute: (call, context) async {
|
||||
final result = await tool.execute(call, context);
|
||||
if (!changed && call.arguments['roleId'] == source) {
|
||||
changed = true;
|
||||
await invoke('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -3,
|
||||
'expectedVersion': await version(),
|
||||
}, record: false);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(jsonEncode((await check()).data), contains('unavailableEvidence'));
|
||||
acceptance = EditorAcceptance(originals);
|
||||
await invoke('caption_set', {
|
||||
'captionId': cues.first['captionId'],
|
||||
'text': '改变了原文',
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
expect(jsonEncode((await check()).data), contains('sourceChanged'));
|
||||
});
|
||||
test(
|
||||
'runtime repairs failed final verification through actual editor tools',
|
||||
() async {
|
||||
var repaired = false;
|
||||
final model = _Model((request, step) async {
|
||||
ModelResponse call(String name, Map<String, Object?> args) =>
|
||||
ModelResponse(
|
||||
calls: [
|
||||
ToolCall(
|
||||
id: 'model-$step',
|
||||
name: name,
|
||||
arguments: {'workspaceId': 'timeline', ...args},
|
||||
),
|
||||
],
|
||||
);
|
||||
if (step == 0) {
|
||||
return call('editor_expect_clips', {
|
||||
'clips': [
|
||||
{
|
||||
'clipId': 'clip',
|
||||
'parameters': [
|
||||
{'parameterId': 'cutdex.audio.gainDb', 'value': -12},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
if (step == 1) return ModelResponse(text: '完成');
|
||||
if (step == 2) {
|
||||
expect(request.messages.last.runtimeNotice, true);
|
||||
expect(request.messages.last.text, contains('cutdex.audio.gainDb'));
|
||||
repaired = true;
|
||||
return call('clip_setAudio', {
|
||||
'clipId': 'clip',
|
||||
'db': -12,
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
}
|
||||
if (step == 3) {
|
||||
return call('project_save', {'expectedVersion': await version()});
|
||||
}
|
||||
return ModelResponse(text: '已修正并核验');
|
||||
});
|
||||
final manager = SessionManager(
|
||||
model: model,
|
||||
store: FileSessionStore(Directory('${root.path}/sessions')),
|
||||
contextBuilder: ContextBuilder(),
|
||||
tools: tools.values,
|
||||
completionCheck: acceptance.check,
|
||||
);
|
||||
final s = await manager.create(id: 'agent');
|
||||
final end = await (await manager.prompt(s.id, 'set volume')).done;
|
||||
expect(repaired, true);
|
||||
expect(end.status, RunStatus.completed);
|
||||
expect((end.completionEvidence!['result'] as Map)['isError'], false);
|
||||
},
|
||||
);
|
||||
test(
|
||||
'live model verifies real persisted project through application tools',
|
||||
() async {
|
||||
final raw = Platform.environment['CUTDEX_ACCEPTANCE_LIVE'];
|
||||
if (raw == null) return;
|
||||
// This opt-in integration case uses the configured real provider.
|
||||
final overrides = HttpOverrides.current;
|
||||
HttpOverrides.global = null;
|
||||
addTearDown(() => HttpOverrides.global = overrides);
|
||||
final config = jsonDecode(raw) as Map;
|
||||
final model = OpenAiResponsesAdapter(
|
||||
baseUrl: Uri.parse(config['baseUrl'] as String),
|
||||
model: config['model'] as String,
|
||||
apiKey: config['key'] as String,
|
||||
);
|
||||
final manager = SessionManager(
|
||||
model: model,
|
||||
store: FileSessionStore(Directory('${root.path}/live')),
|
||||
contextBuilder: HarnessContextBuilder(
|
||||
maxInputTokens: 32000,
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
summarizer: ModelContextSummarizer(
|
||||
model: model,
|
||||
budget: ContextBuilder(maxInputTokens: 32000),
|
||||
),
|
||||
),
|
||||
tools: tools.values,
|
||||
completionCheck: acceptance.check,
|
||||
);
|
||||
final s = await manager.create(system: AgentPromptPolicy.editorAssistant);
|
||||
final end = await (await manager.prompt(
|
||||
s.id,
|
||||
'在timeline工作区把clip片段音量设为-12 dB,保持顺序、时间和其他内容。',
|
||||
maxTurns: 35,
|
||||
)).done;
|
||||
if (end.status != RunStatus.completed) {
|
||||
stdout.writeln(
|
||||
'LIVE_FAILURE ${jsonEncode(end.history.map((m) => m.toJson()).toList())}',
|
||||
);
|
||||
}
|
||||
expect(end.status, RunStatus.completed, reason: end.error);
|
||||
expect(end.completionEvidence, isNotNull);
|
||||
final query = await invoke('timeline_query', {}, record: false);
|
||||
final clip = ((query.data['data'] as Map)['clips'] as List).firstWhere(
|
||||
(c) => c['clipId'] == 'clip',
|
||||
);
|
||||
expect(clip['name'], 'Original');
|
||||
expect(
|
||||
(clip['parameters'] as List).firstWhere(
|
||||
(p) => p['id'] == 'cutdex.audio.gainDb',
|
||||
)['defaultValue'],
|
||||
-12,
|
||||
);
|
||||
final persistedClip = (await project.loadTimeline('p'))
|
||||
.sequences
|
||||
.single
|
||||
.elements
|
||||
.singleWhere((e) => e.id == ElementId('clip'));
|
||||
expect(
|
||||
persistedClip.parameters
|
||||
.singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb')
|
||||
.definition
|
||||
.defaultValue,
|
||||
-12,
|
||||
);
|
||||
stdout.writeln(
|
||||
'LIVE_ACCEPTANCE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
|
||||
);
|
||||
final sourceResult = await invoke('captionTrack_create', {
|
||||
'name': '日本語',
|
||||
'language': 'ja',
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
final source = (sourceResult.data['data'] as Map)['roleId'];
|
||||
const japanese = [
|
||||
'こんにちは。',
|
||||
'ここで待ってください。',
|
||||
'彼はまだ来ていません。',
|
||||
'会議は午後三時に始まります。',
|
||||
];
|
||||
await invoke('caption_add', {
|
||||
'roleId': source,
|
||||
'cues': [
|
||||
for (var i = 0; i < japanese.length; i++)
|
||||
{
|
||||
'text': japanese[i],
|
||||
'start': {'numerator': '$i', 'denominator': 1},
|
||||
'duration': {'numerator': '1', 'denominator': 1},
|
||||
},
|
||||
],
|
||||
'expectedVersion': await version(),
|
||||
});
|
||||
await save();
|
||||
final translated = await (await manager.prompt(
|
||||
s.id,
|
||||
'把timeline工作区日本語轨道的全部字幕由你翻译成简体中文,新增中文轨道并保留原字幕和时间,完成后保存。',
|
||||
maxTurns: 45,
|
||||
)).done;
|
||||
expect(translated.status, RunStatus.completed, reason: translated.error);
|
||||
expect(
|
||||
(translated.completionEvidence!['result'] as Map)['isError'],
|
||||
false,
|
||||
);
|
||||
final tracks = await invoke('caption_list', {}, record: false);
|
||||
final target = ((tracks.data['data'] as Map)['tracks'] as List)
|
||||
.singleWhere((t) => t['roleId'] != source);
|
||||
final captions = await invoke('caption_list', {
|
||||
'roleId': target['roleId'],
|
||||
}, record: false);
|
||||
final cues = (captions.data['data'] as Map)['cues'] as List;
|
||||
expect(cues.length, japanese.length);
|
||||
stdout.writeln(
|
||||
'LIVE_TRANSLATION_VERIFIED turns=${translated.turns} cues=${jsonEncode(cues)} evidence=${jsonEncode(translated.completionEvidence)}',
|
||||
);
|
||||
},
|
||||
timeout: const Timeout(Duration(minutes: 5)),
|
||||
skip: Platform.environment['CUTDEX_ACCEPTANCE_LIVE'] == null,
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,105 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'Pen presets give timeline the same Codex surface and ink hierarchy',
|
||||
() {
|
||||
final light = EditorTheme.penLight;
|
||||
final dark = EditorTheme.penDark;
|
||||
expect(light.colorScheme.surface, const Color(0xFFF6F6F6));
|
||||
expect(light.colorScheme.surfaceContainerLow, const Color(0xFFFAFAFA));
|
||||
expect(light.colorScheme.onSurface, const Color(0xFF020202));
|
||||
expect(light.colorScheme.onSurfaceVariant, const Color(0xFF71717A));
|
||||
expect(dark.colorScheme.surface, const Color(0xFF111111));
|
||||
expect(dark.colorScheme.surfaceContainerLow, const Color(0xFF151515));
|
||||
expect(dark.colorScheme.onSurface, const Color(0xFFFCFCFC));
|
||||
expect(dark.colorScheme.outline, const Color(0xFF3B82F6));
|
||||
expect(dark.dividerColor, const Color(0xFF303030));
|
||||
expect(dark.dividerTheme.color, dark.dividerColor);
|
||||
expect(light.dividerColor, light.colorScheme.outlineVariant);
|
||||
expect(dark.colorScheme.outlineVariant, isNot(dark.dividerColor));
|
||||
|
||||
final inspector = AppTheme.propertiesPanelTheme(dark);
|
||||
expect(inspector.colorScheme.surface, const Color(0xFF151515));
|
||||
expect(inspector.textTheme.bodyMedium?.fontSize, 13);
|
||||
expect(inspector.textTheme.labelLarge?.fontSize, 13);
|
||||
expect(inspector.textTheme.labelMedium?.fontSize, 12);
|
||||
expect(inspector.textTheme.labelSmall?.fontSize, 12);
|
||||
|
||||
final timeline = dark.extension<TimelineThemeData>()!;
|
||||
expect(timeline.backgroundColor, dark.colorScheme.surface);
|
||||
expect(
|
||||
timeline.primaryLaneBackgroundColor,
|
||||
dark.colorScheme.surfaceContainerLow,
|
||||
);
|
||||
expect(timeline.rulerBackgroundColor, dark.colorScheme.surface);
|
||||
expect(timeline.rulerHeight, 20);
|
||||
expect(timeline.clipBorderColor, const Color(0xFF303030));
|
||||
expect(timeline.gapColor, const Color(0xFF303030));
|
||||
expect(timeline.clipBorderWidth, 1);
|
||||
expect(timeline.visualClipColor, const Color(0xFF2F2F2F));
|
||||
expect(timeline.audioClipColor, const Color(0xFF242424));
|
||||
expect(timeline.connectionLineColor, const Color(0xFF303030));
|
||||
expect(timeline.connectionLineWidth, 3);
|
||||
expect(timeline.selectionOutlineColor, dark.colorScheme.onSurface);
|
||||
expect(timeline.selectionOutlineWidth, 2);
|
||||
expect(timeline.clipCornerRadius, 4);
|
||||
expect(timeline.clipNameTextStyle.color, dark.colorScheme.onSurface);
|
||||
expect(timeline.rulerTextStyle.color, dark.colorScheme.onSurfaceVariant);
|
||||
expect(timeline.playheadColor, dark.colorScheme.onSurface);
|
||||
expect(AppTheme.timelinePanelTheme(dark).dividerColor, dark.dividerColor);
|
||||
final lightTimeline = light.extension<TimelineThemeData>()!;
|
||||
expect(lightTimeline.backgroundColor, light.colorScheme.surface);
|
||||
expect(
|
||||
lightTimeline.clipNameTextStyle.color,
|
||||
light.colorScheme.onSurface,
|
||||
);
|
||||
expect(lightTimeline.clipBorderColor, light.colorScheme.outlineVariant);
|
||||
expect(
|
||||
timeline.scrollbarThumbColor,
|
||||
const Color(0xFFFCFCFC).withValues(alpha: .084),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('Neutral text and timeline labels remain legible in both modes', () {
|
||||
for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) {
|
||||
final colors = theme.colorScheme;
|
||||
expect(
|
||||
_contrast(colors.onSurface, colors.surface),
|
||||
greaterThanOrEqualTo(7),
|
||||
);
|
||||
if (colors.surface != const Color(0xFFF6F6F6)) {
|
||||
for (final surface in [colors.surface, colors.surfaceContainerLow]) {
|
||||
expect(
|
||||
_contrast(colors.onSurfaceVariant, surface),
|
||||
greaterThanOrEqualTo(4.5),
|
||||
);
|
||||
}
|
||||
}
|
||||
expect(
|
||||
_contrast(colors.onPrimary, colors.primary),
|
||||
greaterThanOrEqualTo(7),
|
||||
);
|
||||
final timeline = theme.extension<TimelineThemeData>()!;
|
||||
for (final color in [timeline.visualClipColor, timeline.audioClipColor]) {
|
||||
expect(
|
||||
_contrast(timeline.clipNameTextStyle.color!, color),
|
||||
greaterThanOrEqualTo(4.5),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
double _contrast(Color first, Color second) {
|
||||
final a = first.computeLuminance();
|
||||
final b = second.computeLuminance();
|
||||
return (math.max(a, b) + .05) / (math.min(a, b) + .05);
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/integrations/platform/editor_window_chrome.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const channel = MethodChannel('cutdex_native/window');
|
||||
const controlsChannel = MethodChannel('cutdex_native/window_controls');
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
tearDown(() {
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
controlsChannel,
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
Widget app(
|
||||
String id, {
|
||||
VoidCallback? onCloseRequested,
|
||||
TargetPlatform platform = TargetPlatform.macOS,
|
||||
Widget Function(BuildContext, bool)? builder,
|
||||
GlobalKey<NavigatorState>? navigatorKey,
|
||||
}) {
|
||||
debugDefaultTargetPlatformOverride = platform;
|
||||
addTearDown(() => debugDefaultTargetPlatformOverride = null);
|
||||
return MaterialApp(
|
||||
navigatorKey: navigatorKey,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
home: EditorWindowChrome(
|
||||
key: ValueKey(id),
|
||||
headerHeight: 40,
|
||||
onCloseRequested: onCloseRequested ?? () {},
|
||||
builder:
|
||||
builder ??
|
||||
(context, integrated) =>
|
||||
Text(integrated ? 'integrated' : 'standard'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> nativeCall(String method, Object arguments) async {
|
||||
final reply = Completer<ByteData?>();
|
||||
binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall(method, arguments),
|
||||
),
|
||||
reply.complete,
|
||||
);
|
||||
expect(
|
||||
const StandardMethodCodec().decodeEnvelope((await reply.future)!),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets(
|
||||
'Windows buttons dispatch commands and follow native window state',
|
||||
(tester) async {
|
||||
final calls = <MethodCall>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
calls.add(call);
|
||||
return call.method == 'configureChrome'
|
||||
? (call.arguments as Map)['enabled']
|
||||
: null;
|
||||
});
|
||||
await tester.pumpWidget(app('windows', platform: TargetPlatform.windows));
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls.first.arguments, {
|
||||
'enabled': true,
|
||||
'headerHeight': 40.0,
|
||||
'interceptClose': true,
|
||||
'headerInteractive': true,
|
||||
});
|
||||
expect(EditorWindowChrome.leadingWidth, 0);
|
||||
await tester.tap(find.byKey(const Key('window-minimize')));
|
||||
await tester.tap(find.byKey(const Key('window-maximize')));
|
||||
await tester.tap(find.byKey(const Key('window-close')));
|
||||
expect(calls.skip(1).map((c) => c.method), [
|
||||
'minimize',
|
||||
'toggleMaximize',
|
||||
'close',
|
||||
]);
|
||||
await nativeCall('windowState', {
|
||||
'maximized': true,
|
||||
'maximizeHovered': true,
|
||||
});
|
||||
await tester.pump();
|
||||
expect(find.byTooltip('还原'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.filter_none), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(calls.last.arguments, {'enabled': false});
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Windows headers reserve caption space only in the rightmost pane',
|
||||
(tester) async {
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => call.method == 'configureChrome'
|
||||
? (call.arguments as Map)['enabled']
|
||||
: null,
|
||||
);
|
||||
final width = ValueNotifier(250.0);
|
||||
addTearDown(width.dispose);
|
||||
await tester.pumpWidget(
|
||||
app(
|
||||
'layout',
|
||||
platform: TargetPlatform.windows,
|
||||
builder: (context, integrated) => ValueListenableBuilder<double>(
|
||||
valueListenable: width,
|
||||
builder: (context, sidebarWidth, _) => Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: sidebarWidth,
|
||||
child: Column(
|
||||
children: [
|
||||
WindowHeaderPadding(
|
||||
child: SizedBox(
|
||||
height: 40,
|
||||
child: Row(
|
||||
children: [
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
key: const Key('left-action'),
|
||||
onPressed: () {},
|
||||
child: const Text('Left'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: WindowHeaderPane(
|
||||
offset: Offset(sidebarWidth, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
WindowHeaderPadding(
|
||||
child: SizedBox(
|
||||
height: 40,
|
||||
child: Row(
|
||||
children: [
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
key: const Key('right-action'),
|
||||
onPressed: () {},
|
||||
child: const Text('Right'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final controlsLeft = tester
|
||||
.getTopLeft(find.byKey(const Key('window-minimize')))
|
||||
.dx;
|
||||
expect(tester.getTopRight(find.byKey(const Key('left-action'))).dx, 250);
|
||||
expect(
|
||||
tester.getTopRight(find.byKey(const Key('right-action'))).dx,
|
||||
controlsLeft,
|
||||
);
|
||||
width.value = 700;
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.getTopRight(find.byKey(const Key('left-action'))).dx,
|
||||
controlsLeft,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.byKey(const Key('right-action')), findsNothing);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Windows reports actual maximize bounds without rebuilding the workspace',
|
||||
(tester) async {
|
||||
var builds = 0;
|
||||
final regions = <MethodCall>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => call.method == 'configureChrome'
|
||||
? (call.arguments as Map)['enabled']
|
||||
: null,
|
||||
);
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(controlsChannel, (
|
||||
call,
|
||||
) async {
|
||||
regions.add(call);
|
||||
return null;
|
||||
});
|
||||
await tester.pumpWidget(
|
||||
app(
|
||||
'regions',
|
||||
platform: TargetPlatform.windows,
|
||||
builder: (context, integrated) {
|
||||
builds++;
|
||||
return const SizedBox.expand();
|
||||
},
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final count = builds;
|
||||
final rect = tester.getRect(find.byKey(const Key('window-maximize')));
|
||||
final report = regions
|
||||
.map((c) => c.arguments as Map)
|
||||
.singleWhere((args) => args['role'] == 'maximize');
|
||||
expect(report['rect'], {
|
||||
'x': rect.left,
|
||||
'y': rect.top,
|
||||
'width': rect.width,
|
||||
'height': rect.height,
|
||||
});
|
||||
await nativeCall('windowState', {
|
||||
'maximized': true,
|
||||
'maximizeHovered': true,
|
||||
});
|
||||
await tester.pump();
|
||||
expect(builds, count);
|
||||
expect(find.byTooltip('还原'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(
|
||||
regions.any(
|
||||
(c) =>
|
||||
(c.arguments as Map)['role'] == 'maximize' &&
|
||||
(c.arguments as Map)['rect'] == null,
|
||||
),
|
||||
true,
|
||||
);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'nested pane offsets reserve caption space on the first integrated frame',
|
||||
(tester) async {
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(call) async => call.method == 'configureChrome'
|
||||
? (call.arguments as Map)['enabled']
|
||||
: null,
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
app(
|
||||
'nested',
|
||||
platform: TargetPlatform.windows,
|
||||
builder: (context, integrated) => Row(
|
||||
children: [
|
||||
const SizedBox(width: 200),
|
||||
Expanded(
|
||||
child: WindowHeaderPane(
|
||||
offset: const Offset(200, 0),
|
||||
child: Row(
|
||||
children: [
|
||||
const SizedBox(width: 100),
|
||||
Expanded(
|
||||
child: WindowHeaderPane(
|
||||
offset: const Offset(100, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
WindowHeaderPadding(
|
||||
child: SizedBox(
|
||||
height: 40,
|
||||
child: Row(
|
||||
children: [
|
||||
const Spacer(),
|
||||
TextButton(
|
||||
key: const Key('nested-action'),
|
||||
onPressed: () {},
|
||||
child: const Text('Action'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.getTopRight(find.byKey(const Key('nested-action'))).dx,
|
||||
tester.getTopLeft(find.byKey(const Key('window-minimize'))).dx,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Windows modal routes suspend header hit testing until dismissed',
|
||||
(tester) async {
|
||||
final calls = <MethodCall>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
calls.add(call);
|
||||
return call.method == 'configureChrome'
|
||||
? (call.arguments as Map)['enabled']
|
||||
: null;
|
||||
});
|
||||
final navigatorKey = GlobalKey<NavigatorState>();
|
||||
await tester.pumpWidget(
|
||||
app(
|
||||
'modal',
|
||||
platform: TargetPlatform.windows,
|
||||
navigatorKey: navigatorKey,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
unawaited(
|
||||
showDialog<void>(
|
||||
context: tester.element(find.byType(EditorWindowChrome)),
|
||||
builder: (_) => const AlertDialog(content: Text('Modal')),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
calls.where((c) => c.method == 'setHeaderInteractive').last.arguments,
|
||||
false,
|
||||
);
|
||||
navigatorKey.currentState!.pop();
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
calls.where((c) => c.method == 'setHeaderInteractive').last.arguments,
|
||||
true,
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'Windows hosts without the native plugin retain the standard header',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(
|
||||
app('old-windows', platform: TargetPlatform.windows),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('standard'), findsOneWidget);
|
||||
expect(find.byKey(const Key('window-close')), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('enables native chrome and restores it when leaving the editor', (
|
||||
tester,
|
||||
) async {
|
||||
final calls = <MethodCall>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
calls.add(call);
|
||||
return (call.arguments as Map)['enabled'];
|
||||
});
|
||||
await tester.pumpWidget(app('one'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('integrated'), findsOneWidget);
|
||||
expect(calls.single.method, 'configureChrome');
|
||||
expect(calls.single.arguments, {
|
||||
'enabled': true,
|
||||
'headerHeight': 40.0,
|
||||
'interceptClose': true,
|
||||
});
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(calls.last.arguments, {'enabled': false});
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
|
||||
testWidgets('forwards the native close request to the current editor', (
|
||||
tester,
|
||||
) async {
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
return (call.arguments as Map)['enabled'];
|
||||
});
|
||||
var requests = 0;
|
||||
await tester.pumpWidget(app('one', onCloseRequested: () => requests += 1));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final reply = Completer<ByteData?>();
|
||||
binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('requestClose'),
|
||||
),
|
||||
reply.complete,
|
||||
);
|
||||
final result = const StandardMethodCodec().decodeEnvelope(
|
||||
(await reply.future)!,
|
||||
);
|
||||
await tester.pump();
|
||||
|
||||
expect(result, isTrue);
|
||||
expect(requests, 1);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
|
||||
testWidgets('late enable reply cannot re-enable a disposed editor', (
|
||||
tester,
|
||||
) async {
|
||||
final enabled = Completer<bool>();
|
||||
final calls = <bool>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
final enable = (call.arguments as Map)['enabled'] as bool;
|
||||
calls.add(enable);
|
||||
return enable ? enabled.future : false;
|
||||
});
|
||||
await tester.pumpWidget(app('one'));
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
enabled.complete(true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls, [true, false]);
|
||||
expect(tester.takeException(), isNull);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'replacing an editor does not let the old owner disable the new one',
|
||||
(tester) async {
|
||||
final calls = <bool>[];
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
final enable = (call.arguments as Map)['enabled'] as bool;
|
||||
calls.add(enable);
|
||||
return enable;
|
||||
});
|
||||
await tester.pumpWidget(app('one'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(app('two'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls.last, isTrue);
|
||||
expect(find.text('integrated'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(calls.last, isFalse);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'an unregistered native plugin keeps the standard Flutter heading',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(app('one'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('standard'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex/integrations/runtime/export_publication.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
late Directory root;
|
||||
setUp(
|
||||
() async =>
|
||||
root = await Directory.systemTemp.createTemp('export-recovery-'),
|
||||
);
|
||||
tearDown(() => root.delete(recursive: true));
|
||||
test(
|
||||
'published output is recovered repeatedly without encoding again',
|
||||
() async {
|
||||
final destination = File('${root.path}/result.mp4').uri;
|
||||
var calls = 0;
|
||||
Future<Uri> encode(Uri uri) async {
|
||||
calls++;
|
||||
await File.fromUri(uri).writeAsString('encoded movie');
|
||||
return uri;
|
||||
}
|
||||
|
||||
await ExportPublication(destination, 'op').run('snapshot', encode);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
expect(
|
||||
await ExportPublication(destination, 'op').run('snapshot', encode),
|
||||
destination,
|
||||
);
|
||||
}
|
||||
expect(calls, 1);
|
||||
await expectLater(
|
||||
ExportPublication(destination, 'op').run('other', encode),
|
||||
throwsA(isA<CommandRejected>()),
|
||||
);
|
||||
},
|
||||
);
|
||||
test('ready staging receipt recovers the publication crash window', () async {
|
||||
final destination = File('${root.path}/result.mp4').uri;
|
||||
final job = ExportPublication(destination, 'op');
|
||||
await job.directory.create();
|
||||
final bytes = utf8.encode('complete movie');
|
||||
await job.staged.writeAsBytes(bytes);
|
||||
await job.receipt.writeAsString(
|
||||
jsonEncode({
|
||||
'operationId': 'op',
|
||||
'destination': destination.toString(),
|
||||
'fingerprint': 'snapshot',
|
||||
'bytes': bytes.length,
|
||||
'sha256': sha256.convert(bytes).toString(),
|
||||
}),
|
||||
);
|
||||
expect(await ExportPublication(destination, 'op').recover(), destination);
|
||||
expect(await job.staged.exists(), false);
|
||||
expect(await File.fromUri(destination).readAsBytes(), bytes);
|
||||
});
|
||||
test(
|
||||
'incomplete and externally changed output never silently overwrites',
|
||||
() async {
|
||||
final destination = File('${root.path}/result.mp4').uri;
|
||||
final job = ExportPublication(destination, 'op');
|
||||
await expectLater(
|
||||
job.run('snapshot', (_) async => throw StateError('killed encoder')),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(await job.recover(), null);
|
||||
await expectLater(
|
||||
job.run('snapshot', (_) async => destination),
|
||||
throwsA(isA<CommandRejected>()),
|
||||
);
|
||||
expect(await File.fromUri(destination).exists(), false);
|
||||
final next = ExportPublication(destination, 'explicit-retry');
|
||||
await next.run('snapshot', (uri) async {
|
||||
await File.fromUri(uri).writeAsString('complete');
|
||||
return uri;
|
||||
});
|
||||
await File.fromUri(destination).writeAsString('changed');
|
||||
await expectLater(next.recover(), throwsA(isA<CommandRejected>()));
|
||||
expect(await File.fromUri(destination).readAsString(), 'changed');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/assistant/agent_composer_controller.dart';
|
||||
import 'package:cutdex/features/assistant/agent_composer_store.dart';
|
||||
import 'package:cutdex/workspace/external_media_import.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
final _asset = AssetDocument(
|
||||
id: 'asset',
|
||||
name: 'Photo',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///photo.png',
|
||||
metadata: {'kind': 'image'},
|
||||
);
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'deleting a conversation discards its pending attachment destination',
|
||||
() async {
|
||||
final completed = Completer<ExternalMediaSelection?>();
|
||||
final started = Completer<void>();
|
||||
final store = AgentComposerStore(
|
||||
createComposer: (_) => AgentComposerController(
|
||||
canImport: () => true,
|
||||
pickFiles: () async => [],
|
||||
importMedia: (_) {
|
||||
started.complete();
|
||||
return completed.future;
|
||||
},
|
||||
),
|
||||
);
|
||||
addTearDown(store.dispose);
|
||||
final old = store.composer('project', 'chat');
|
||||
final pending = old.importAttachments([
|
||||
const ExternalMediaFile(path: '/photo.png'),
|
||||
]);
|
||||
await started.future;
|
||||
store.removeConversation('project', 'chat');
|
||||
final replacement = store.composer('project', 'chat');
|
||||
completed.complete(ExternalMediaSelection(selected: [_asset]));
|
||||
await pending;
|
||||
expect(old.attachments, isEmpty);
|
||||
expect(replacement.attachments, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('promoting a draft preserves controllers and pending imports until deletion', () async {
|
||||
final completed = Completer<ExternalMediaSelection?>();
|
||||
final started = Completer<void>();
|
||||
final store = AgentComposerStore(
|
||||
createComposer: (_) => AgentComposerController(
|
||||
canImport: () => true,
|
||||
pickFiles: () async => [],
|
||||
importMedia: (_) {
|
||||
started.complete();
|
||||
return completed.future;
|
||||
},
|
||||
),
|
||||
);
|
||||
addTearDown(store.dispose);
|
||||
final input = store.input('project', null)..text = 'Follow-up';
|
||||
final composer = store.composer('project', 'draft');
|
||||
final pending = composer.importAttachments([
|
||||
const ExternalMediaFile(path: '/photo.png'),
|
||||
]);
|
||||
await started.future;
|
||||
store.promoteDraft('project', 'draft', 'chat');
|
||||
store.removeDraft('project', 'draft');
|
||||
expect(store.input('project', 'chat'), same(input));
|
||||
expect(store.composer('project', 'chat'), same(composer));
|
||||
expect(store.input('project', null), isNot(same(input)));
|
||||
expect(store.input('project', null).text, isEmpty);
|
||||
completed.complete(ExternalMediaSelection(selected: [_asset]));
|
||||
await pending;
|
||||
expect(composer.attachments.single.id, _asset.id);
|
||||
expect(input.text, 'Follow-up');
|
||||
store.removeConversation('project', 'chat');
|
||||
expect(store.input('project', 'chat'), isNot(same(input)));
|
||||
expect(store.composer('project', 'chat'), isNot(same(composer)));
|
||||
});
|
||||
|
||||
test('partial import failures survive until consumed, successful imports add no notice', () async {
|
||||
var fail = true;
|
||||
final composer = AgentComposerController(
|
||||
canImport: () => true,
|
||||
pickFiles: () async => [const ExternalMediaFile(path: '/photo.png')],
|
||||
importMedia: (_) async => fail
|
||||
? const ExternalMediaSelection(
|
||||
selected: [],
|
||||
result: MediaImportResult(
|
||||
assets: [],
|
||||
added: 0,
|
||||
duplicates: 0,
|
||||
failures: [
|
||||
MediaImportFailure(
|
||||
name: 'photo.png',
|
||||
failure: AppFailure(
|
||||
AppErrorCode.diagnostic,
|
||||
diagnostic: 'unreadable',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
)
|
||||
: ExternalMediaSelection(selected: [_asset]),
|
||||
);
|
||||
addTearDown(composer.dispose);
|
||||
await composer.pickAttachments();
|
||||
expect(composer.feedback.hasPending, isTrue);
|
||||
expect(
|
||||
composer.feedback.takePending().single!.result!.failures.single.name,
|
||||
'photo.png',
|
||||
);
|
||||
expect(composer.feedback.hasPending, isFalse);
|
||||
fail = false;
|
||||
await composer.pickAttachments();
|
||||
expect(composer.attachments.single.id, _asset.id);
|
||||
expect(composer.feedback.hasPending, isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'changing projects while file picking does not import into another project',
|
||||
() async {
|
||||
var active = true;
|
||||
var imports = 0;
|
||||
final files = Completer<List<ExternalMediaFile>>();
|
||||
final composer = AgentComposerController(
|
||||
canImport: () => active,
|
||||
pickFiles: () => files.future,
|
||||
importMedia: (_) async {
|
||||
imports++;
|
||||
return ExternalMediaSelection(selected: [_asset]);
|
||||
},
|
||||
);
|
||||
addTearDown(composer.dispose);
|
||||
final pending = composer.pickAttachments();
|
||||
active = false;
|
||||
files.complete([const ExternalMediaFile(path: '/photo.png')]);
|
||||
await pending;
|
||||
expect(imports, 0);
|
||||
expect(composer.attachments, isEmpty);
|
||||
expect(composer.busy, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'attachment commands serialize and recover after import failure',
|
||||
() async {
|
||||
final completed = Completer<ExternalMediaSelection?>();
|
||||
var calls = 0;
|
||||
final composer = AgentComposerController(
|
||||
canImport: () => true,
|
||||
pickFiles: () async => [],
|
||||
importMedia: (_) {
|
||||
calls++;
|
||||
return completed.future;
|
||||
},
|
||||
);
|
||||
addTearDown(composer.dispose);
|
||||
final first = composer.importAttachments([
|
||||
const ExternalMediaFile(path: '/photo.png'),
|
||||
]);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(composer.busy, isTrue);
|
||||
expect(
|
||||
await composer.importAttachments([
|
||||
const ExternalMediaFile(path: '/second.png'),
|
||||
]),
|
||||
isNull,
|
||||
);
|
||||
completed.completeError(StateError('import failed'));
|
||||
await expectLater(first, throwsStateError);
|
||||
expect(calls, 1);
|
||||
expect(composer.busy, isFalse);
|
||||
expect(composer.feedback.hasPending, isTrue);
|
||||
expect(composer.feedback.takePending(), [null]);
|
||||
expect(composer.feedback.hasPending, isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex/features/media/background_removal_controller.dart';
|
||||
import 'package:cutdex/features/media/processing_targets.dart';
|
||||
import 'package:cutdex/integrations/runtime/processing_resource_repository.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
test('closing the download view retains the operation until explicit cancellation', () async {
|
||||
final fixture = await createPreviewFixture(Uri.file('/unused.mov'));
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final started = Completer<void>();
|
||||
final release = Completer<void>();
|
||||
const payload = [1, 2, 3];
|
||||
server.listen((request) async {
|
||||
started.complete();
|
||||
await release.future;
|
||||
try {
|
||||
request.response.add(payload);
|
||||
await request.response.close();
|
||||
} on SocketException {
|
||||
// Cancellation closes the downloading client's socket.
|
||||
} on HttpException {
|
||||
// The cancelled request may already have closed.
|
||||
}
|
||||
});
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: Directory('${fixture.directory.path}/Processing'),
|
||||
catalog: [
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.backgroundRemoval,
|
||||
id: 'model',
|
||||
version: '1',
|
||||
name: 'Model',
|
||||
description: '',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.onnx',
|
||||
url: Uri.parse('http://localhost:${server.port}/model'),
|
||||
sha256: sha256.convert(payload).toString(),
|
||||
bytes: payload.length,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
final container = ProviderContainer();
|
||||
addTearDown(() async {
|
||||
if (!release.isCompleted) release.complete();
|
||||
container.dispose();
|
||||
await server.close(force: true);
|
||||
repository.dispose();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
final provider = backgroundRemovalControllerProvider(
|
||||
fixture.timeline,
|
||||
BackgroundRemovalClipTarget(
|
||||
sequence: fixture.timeline.activeSequenceId!,
|
||||
clipId: 'clip',
|
||||
mediaId: 'media',
|
||||
name: 'Clip',
|
||||
),
|
||||
);
|
||||
final subscription = container.listen(provider, (_, _) {});
|
||||
final controller = container.read(provider.notifier);
|
||||
final operation = controller.start(repository, download: true);
|
||||
await started.future.timeout(const Duration(seconds: 5));
|
||||
subscription.close();
|
||||
await container.pump();
|
||||
expect(container.exists(provider), isTrue);
|
||||
expect(container.read(provider), isA<RemovalDownloading>());
|
||||
controller.cancel(repository);
|
||||
release.complete();
|
||||
await operation.timeout(const Duration(seconds: 5));
|
||||
expect(fixture.timeline.backgroundRemovals.tasks, isEmpty);
|
||||
expect(
|
||||
repository.installFor(ProcessingCapability.backgroundRemoval).state,
|
||||
ProcessingResourceState.notInstalled,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import 'package:cutdex/features/assistant/agent_composer_store.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/projects/conversation_sidebar.dart';
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
const _projects = [
|
||||
RecentProject(id: 'a', name: 'A', path: '/a'),
|
||||
RecentProject(id: 'b', name: 'B', path: '/b'),
|
||||
];
|
||||
|
||||
class _Projects extends Projects {
|
||||
@override
|
||||
Future<ProjectState> build() async =>
|
||||
ProjectState(recent: _projects, activeProject: _projects[0]);
|
||||
void selectProject(int index) => state = AsyncData(
|
||||
state.requireValue.copyWith(activeProject: _projects[index]),
|
||||
);
|
||||
void renameProjectLocally() => state = AsyncData(
|
||||
state.requireValue.copyWith(
|
||||
recent: [
|
||||
_projects[0].copyWith(name: 'Renamed'),
|
||||
_projects[1],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SlowProjects extends _Projects {
|
||||
_SlowProjects(this._loaded);
|
||||
final Completer<void> _loaded;
|
||||
@override
|
||||
Future<ProjectState> build() async {
|
||||
await _loaded.future;
|
||||
return super.build();
|
||||
}
|
||||
}
|
||||
|
||||
ConversationMetadata _item(String projectId) => ConversationMetadata(
|
||||
id: '$projectId-chat',
|
||||
projectId: projectId,
|
||||
title: projectId,
|
||||
createdAt: DateTime.utc(2026),
|
||||
updatedAt: DateTime.utc(2026),
|
||||
providerId: 'provider',
|
||||
modelId: 'model',
|
||||
timelineId: 'timeline',
|
||||
pending: false,
|
||||
responseDurationsMs: const [],
|
||||
);
|
||||
|
||||
class _Repository extends ConversationRepository {
|
||||
_Repository() : super(Directory('/unused'));
|
||||
Completer<List<ConversationMetadata>>? blocked;
|
||||
final started = Completer<void>();
|
||||
bool fail = false;
|
||||
bool failDelete = false;
|
||||
final trashed = <ConversationMetadata>[];
|
||||
final deleted = <String>{};
|
||||
final selections = <String, String?>{};
|
||||
@override
|
||||
Future<List<ConversationMetadata>> list(
|
||||
String projectId, {
|
||||
bool trash = false,
|
||||
}) async {
|
||||
if (trash) return List.of(trashed);
|
||||
if (fail) throw StateError('read failed');
|
||||
if (projectId == 'a' && blocked != null) {
|
||||
if (!started.isCompleted) started.complete();
|
||||
return blocked!.future;
|
||||
}
|
||||
return [if (!deleted.contains('$projectId-chat')) _item(projectId)];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deletePermanently(
|
||||
String projectId,
|
||||
String conversationId,
|
||||
) async {
|
||||
if (failDelete) throw StateError('delete failed');
|
||||
deleted.add(conversationId);
|
||||
trashed.removeWhere((item) => item.id == conversationId);
|
||||
if (selections[projectId] == conversationId) selections[projectId] = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> select(String projectId, String? conversationId) async {
|
||||
selections[projectId] = conversationId;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> selected(String projectId) async =>
|
||||
selections.containsKey(projectId)
|
||||
? selections[projectId]
|
||||
: '$projectId-chat';
|
||||
}
|
||||
|
||||
void main() {
|
||||
late _Repository repository;
|
||||
late ProviderContainer container;
|
||||
setUp(() async {
|
||||
repository = _Repository();
|
||||
container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_Projects.new),
|
||||
conversationRepositoryProvider.overrideWith((ref) async => repository),
|
||||
],
|
||||
);
|
||||
await container.read(projectsProvider.future);
|
||||
await container.read(conversationSidebarProvider.future);
|
||||
});
|
||||
tearDown(() => container.dispose());
|
||||
|
||||
test(
|
||||
'permanent deletion releases only the removed conversation cache',
|
||||
() async {
|
||||
final store = container.read(agentComposerStoreProvider);
|
||||
final removedInput = store.input('a', 'a-chat')..text = 'removed draft';
|
||||
final keptInput = store.input('b', 'b-chat')..text = 'keep this draft';
|
||||
final removedComposer = store.composer('a', 'a-chat');
|
||||
await container
|
||||
.read(conversationSidebarProvider.notifier)
|
||||
.delete(_item('a'));
|
||||
expect(store.input('a', 'a-chat'), isNot(same(removedInput)));
|
||||
expect(store.composer('a', 'a-chat'), isNot(same(removedComposer)));
|
||||
expect(store.input('b', 'b-chat'), same(keptInput));
|
||||
expect(keptInput.text, 'keep this draft');
|
||||
},
|
||||
);
|
||||
|
||||
test('failed permanent deletion preserves drafts', () async {
|
||||
repository.failDelete = true;
|
||||
final store = container.read(agentComposerStoreProvider);
|
||||
final input = store.input('a', 'a-chat')..text = 'preserve';
|
||||
final composer = store.composer('a', 'a-chat');
|
||||
await expectLater(
|
||||
container.read(conversationSidebarProvider.notifier).delete(_item('a')),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(store.input('a', 'a-chat'), same(input));
|
||||
expect(store.composer('a', 'a-chat'), same(composer));
|
||||
expect(input.text, 'preserve');
|
||||
});
|
||||
|
||||
test('empty trash removes all trashed conversation caches', () async {
|
||||
repository.trashed.addAll([
|
||||
_item('a'),
|
||||
_item('a').copyWith(id: 'a-second'),
|
||||
]);
|
||||
await container.read(conversationSidebarProvider.notifier).reload();
|
||||
final store = container.read(agentComposerStoreProvider);
|
||||
final first = store.input('a', 'a-chat');
|
||||
final second = store.input('a', 'a-second');
|
||||
await container.read(conversationSidebarProvider.notifier).emptyTrash();
|
||||
expect(store.input('a', 'a-chat'), isNot(same(first)));
|
||||
expect(store.input('a', 'a-second'), isNot(same(second)));
|
||||
expect(repository.deleted, containsAll(['a-chat', 'a-second']));
|
||||
});
|
||||
|
||||
test('initial loading waits for workspace data without publishing an obsolete snapshot', () async {
|
||||
final loaded = Completer<void>();
|
||||
final cold = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(() => _SlowProjects(loaded)),
|
||||
conversationRepositoryProvider.overrideWith((ref) async => repository),
|
||||
],
|
||||
);
|
||||
addTearDown(cold.dispose);
|
||||
final snapshot = cold.read(conversationSidebarProvider.future);
|
||||
loaded.complete();
|
||||
expect((await snapshot).projectId, 'a');
|
||||
});
|
||||
|
||||
test(
|
||||
'refresh and project rename preserve an explicitly opened draft',
|
||||
() async {
|
||||
container.read(conversationSidebarProvider.notifier).newConversation();
|
||||
final draft = container.read(conversationSelectionProvider('a')).draftKey;
|
||||
repository.blocked = Completer();
|
||||
final refresh = container
|
||||
.read(conversationSidebarProvider.notifier)
|
||||
.reload();
|
||||
await repository.started.future;
|
||||
repository.blocked!.complete([_item('a').copyWith(title: 'Updated')]);
|
||||
await refresh;
|
||||
(container.read(projectsProvider.notifier) as _Projects)
|
||||
.renameProjectLocally();
|
||||
await container.pump();
|
||||
expect(
|
||||
container.read(conversationSelectionProvider('a')).selectedId,
|
||||
isNull,
|
||||
);
|
||||
expect(
|
||||
container.read(conversationSelectionProvider('a')).draftKey,
|
||||
draft,
|
||||
);
|
||||
expect(
|
||||
container
|
||||
.read(conversationSidebarProvider)
|
||||
.requireValue
|
||||
.groups['a']!
|
||||
.single
|
||||
.title,
|
||||
'Updated',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'late conversation creation does not promote a replaced draft',
|
||||
() async {
|
||||
final sidebar = container.read(conversationSidebarProvider.notifier);
|
||||
sidebar.newConversation();
|
||||
final selection = conversationSelectionProvider('a');
|
||||
final firstKey = container.read(selection).draftKey;
|
||||
final store = container.read(agentComposerStoreProvider);
|
||||
store.composer('a', firstKey);
|
||||
sidebar.newConversation();
|
||||
final secondKey = container.read(selection).draftKey;
|
||||
final secondComposer = store.composer('a', secondKey);
|
||||
final input = store.input('a', null)..text = 'New draft';
|
||||
await sidebar.updateListing(
|
||||
_item('a').copyWith(id: 'created'),
|
||||
selectIfDraftKey: firstKey,
|
||||
);
|
||||
expect(container.read(selection).selectedId, isNull);
|
||||
expect(container.read(selection).draftKey, secondKey);
|
||||
expect(store.input('a', null), same(input));
|
||||
expect(input.text, 'New draft');
|
||||
expect(store.composer('a', secondKey), same(secondComposer));
|
||||
expect(store.input('a', 'created').text, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a late refresh from the prior project never replaces the active list',
|
||||
() async {
|
||||
repository.blocked = Completer();
|
||||
final refresh = container
|
||||
.read(conversationSidebarProvider.notifier)
|
||||
.reload();
|
||||
await repository.started.future;
|
||||
final blocked = repository.blocked!;
|
||||
repository.blocked = null;
|
||||
(container.read(projectsProvider.notifier) as _Projects).selectProject(1);
|
||||
await container.pump();
|
||||
expect(
|
||||
(await container.read(conversationSidebarProvider.future)).projectId,
|
||||
'b',
|
||||
);
|
||||
blocked.complete([_item('a')]);
|
||||
await refresh;
|
||||
expect(
|
||||
container.read(conversationSidebarProvider).requireValue.projectId,
|
||||
'b',
|
||||
);
|
||||
expect(
|
||||
container.read(conversationSelectionProvider('b')).selectedId,
|
||||
'b-chat',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('reopening a project reloads its saved selection', () async {
|
||||
final provider = conversationSelectionProvider('a');
|
||||
container.listen(provider, (_, _) {});
|
||||
expect(container.read(provider).selectedId, 'a-chat');
|
||||
repository.selections['a'] = null;
|
||||
final projects = container.read(projectsProvider.notifier) as _Projects;
|
||||
projects.selectProject(1);
|
||||
await container.pump();
|
||||
await container.read(conversationSidebarProvider.future);
|
||||
projects.selectProject(0);
|
||||
await container.pump();
|
||||
await container.read(conversationSidebarProvider.future);
|
||||
expect(container.read(provider).selectedId, isNull);
|
||||
expect(container.read(provider).initialized, isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'a failed refresh retains the current rows and reports the failure',
|
||||
() async {
|
||||
repository.fail = true;
|
||||
await container.read(conversationSidebarProvider.notifier).reload();
|
||||
final value = container.read(conversationSidebarProvider).requireValue;
|
||||
expect(value.groups['a']!.single.id, 'a-chat');
|
||||
expect(value.reloadFailed, isTrue);
|
||||
repository.fail = false;
|
||||
await container.read(conversationSidebarProvider.notifier).reload();
|
||||
expect(
|
||||
container.read(conversationSidebarProvider).requireValue.reloadFailed,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex/features/timeline/timeline_external_drop_target.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_drop_preparation.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../support/preview_fixture.dart';
|
||||
|
||||
class _Projects extends Projects {
|
||||
_Projects(this.session);
|
||||
final EditorTimelineSession session;
|
||||
|
||||
@override
|
||||
Future<ProjectState> build() async => ProjectState(
|
||||
activeProject: const RecentProject(
|
||||
id: 'project',
|
||||
name: 'Project',
|
||||
path: '/project',
|
||||
),
|
||||
timeline: session.document,
|
||||
);
|
||||
|
||||
@override
|
||||
Future<T> withAssetMedia<T>(
|
||||
String? projectId,
|
||||
AssetDocument asset,
|
||||
Future<T> Function(MediaReference) action,
|
||||
) => action(MediaReference(id: asset.id, uri: Uri.parse(asset.location)));
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
testWidgets('releasing an MPG drag commits its precise source duration', (
|
||||
tester,
|
||||
) async {
|
||||
// Actual native probe duration of VENU662C.mpg (100 ns source clock).
|
||||
const numerator = 64737467444;
|
||||
const denominator = 10000000;
|
||||
const ticks = 9135751405697;
|
||||
const channel = MethodChannel('drop-duration-test');
|
||||
debugDefaultTargetPlatformOverride = TargetPlatform.windows;
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/file_drop/timeline'),
|
||||
(_) async => null,
|
||||
);
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
final request = jsonDecode((call.arguments as Map)['request'] as String);
|
||||
expect(request['method'], 'probe');
|
||||
return jsonEncode({
|
||||
'value': {
|
||||
'duration': {'numerator': '$numerator', 'denominator': denominator},
|
||||
'videoTrackCount': 1,
|
||||
'audioTrackCount': 0,
|
||||
'videoTrackIds': [0],
|
||||
'audioTrackIds': <int>[],
|
||||
'isProtected': false,
|
||||
'audioTracks': <Object?>[],
|
||||
},
|
||||
});
|
||||
});
|
||||
final fixture = await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/VENU662C.mpg')),
|
||||
);
|
||||
final session = fixture!.timeline;
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(() => _Projects(session)),
|
||||
runtimeConnectionProvider.overrideWithValue(
|
||||
CutdexRuntime(channel: channel),
|
||||
),
|
||||
],
|
||||
);
|
||||
final incoming = ValueNotifier<TimelineIncomingAsset?>(null);
|
||||
addTearDown(() async {
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
incoming.dispose();
|
||||
container.dispose();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
null,
|
||||
);
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/file_drop/timeline'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
final sequence = SequenceId('empty');
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
home: Scaffold(
|
||||
body: TimelineExternalDropTarget(
|
||||
projectId: 'project',
|
||||
session: session,
|
||||
sequenceId: sequence,
|
||||
incoming: incoming,
|
||||
child: const SizedBox(width: 600, height: 300),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final finder = find.byType(TimelineExternalDropTarget);
|
||||
incoming.value = (
|
||||
asset: AssetDocument(
|
||||
id: 'media',
|
||||
name: 'VENU662C.mpg',
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('/VENU662C.mpg').toString(),
|
||||
),
|
||||
globalPosition: tester.getCenter(finder),
|
||||
);
|
||||
await tester.runAsync(
|
||||
() => container
|
||||
.read(
|
||||
timelineDropPreparationProvider(
|
||||
'project',
|
||||
session,
|
||||
sequence,
|
||||
).notifier,
|
||||
)
|
||||
.waitForPreparation(),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final drop = tester.state<TimelineExternalDropTargetState>(finder);
|
||||
final preparation = container
|
||||
.read(timelineDropPreparationProvider('project', session, sequence))
|
||||
.preparation;
|
||||
expect(
|
||||
drop.preparedMedia,
|
||||
isNotNull,
|
||||
reason: '${preparation.error}\n${preparation.stackTrace}',
|
||||
);
|
||||
expect(
|
||||
session.persistence.timeline(sequence).exportDto().elements,
|
||||
isEmpty,
|
||||
);
|
||||
|
||||
// This is the same release entry point as the media-library drag target.
|
||||
await drop.drop();
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byType(SnackBar),
|
||||
findsNothing,
|
||||
reason: find
|
||||
.descendant(of: find.byType(SnackBar), matching: find.byType(Text))
|
||||
.evaluate()
|
||||
.map((element) => (element.widget as Text).data)
|
||||
.join('\n'),
|
||||
);
|
||||
final element = session.persistence
|
||||
.timeline(sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.singleWhere((element) => element.payloadRef != null);
|
||||
final clock = session.persistence.timeline(sequence).clock;
|
||||
expect(clock.toTicks(element.duration), ticks);
|
||||
expect(element.sourceRange.start, RationalTime.zero);
|
||||
expect(element.sourceRange.duration, element.duration);
|
||||
expect(element.mediaRange!.duration, element.duration);
|
||||
final remainder =
|
||||
BigInt.from(numerator) * BigInt.from(TimelineClock.ticksPerSecond) -
|
||||
BigInt.from(ticks) * BigInt.from(denominator);
|
||||
expect(remainder >= BigInt.zero, isTrue);
|
||||
expect(remainder < BigInt.from(denominator), isTrue);
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await tester.runAsync(session.close);
|
||||
final stored = await tester.runAsync(
|
||||
() => fixture.workspace.project!.loadTimeline(session.document.id),
|
||||
);
|
||||
final restored = stored!.sequences
|
||||
.singleWhere((item) => item.id == sequence)
|
||||
.elements
|
||||
.singleWhere((item) => item.payloadRef != null);
|
||||
expect(clock.toTicks(restored.duration), ticks);
|
||||
expect(restored.sourceRange.duration, element.sourceRange.duration);
|
||||
expect(restored.mediaRange!.duration, element.mediaRange!.duration);
|
||||
debugDefaultTargetPlatformOverride = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex/features/timeline/timeline_drop_preparation.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../support/preview_fixture.dart';
|
||||
|
||||
AssetDocument _image(String id) => AssetDocument(
|
||||
id: id,
|
||||
name: id,
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('/$id.png').toString(),
|
||||
metadata: const {'kind': 'image'},
|
||||
);
|
||||
|
||||
class _Projects extends Projects {
|
||||
_Projects(this._session);
|
||||
final EditorTimelineSession _session;
|
||||
Completer<MediaReference>? _gate;
|
||||
Completer<void>? _acquiring;
|
||||
@override
|
||||
Future<ProjectState> build() async => ProjectState(
|
||||
activeProject: const RecentProject(
|
||||
id: 'project',
|
||||
name: 'Project',
|
||||
path: '/project',
|
||||
),
|
||||
timeline: _session.document,
|
||||
);
|
||||
@override
|
||||
Future<T> withAssetMedia<T>(
|
||||
String? projectId,
|
||||
AssetDocument asset,
|
||||
Future<T> Function(MediaReference) action,
|
||||
) async {
|
||||
if (_acquiring?.isCompleted == false) _acquiring!.complete();
|
||||
final media = _gate == null
|
||||
? MediaReference(id: asset.id, uri: Uri.parse(asset.location))
|
||||
: await _gate!.future;
|
||||
return action(media);
|
||||
}
|
||||
|
||||
void leave() =>
|
||||
state = AsyncData(state.requireValue.copyWith(activeProject: null));
|
||||
}
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test(
|
||||
'probe prepares validated metadata before placement or commit',
|
||||
() async {
|
||||
final fixture = await createPreviewFixture(Uri.file('/source.mpg'));
|
||||
final projects = _Projects(fixture.timeline);
|
||||
const channel = MethodChannel('prepared-drop-test');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
var probes = 0;
|
||||
var response = <String, Object?>{
|
||||
'duration': {'numerator': '64737467444', 'denominator': 10000000},
|
||||
'videoTrackCount': 1,
|
||||
'audioTrackCount': 0,
|
||||
'videoTrackIds': [0],
|
||||
'audioTrackIds': <int>[],
|
||||
'audioTracks': <Object?>[],
|
||||
'isProtected': false,
|
||||
};
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'request') {
|
||||
final request = jsonDecode(
|
||||
(call.arguments as Map)['request'] as String,
|
||||
);
|
||||
expect(request['method'], 'probe');
|
||||
} else {
|
||||
expect(call.method, 'probe');
|
||||
}
|
||||
probes++;
|
||||
return call.method == 'request'
|
||||
? jsonEncode({'value': response})
|
||||
: response;
|
||||
});
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(() => projects),
|
||||
runtimeConnectionProvider.overrideWithValue(
|
||||
CutdexRuntime(channel: channel),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
final provider = timelineDropPreparationProvider(
|
||||
'project',
|
||||
fixture.timeline,
|
||||
fixture.timeline.activeSequenceId!,
|
||||
);
|
||||
container.listen(provider, (_, _) {});
|
||||
final controller = container.read(provider.notifier);
|
||||
final source = TimelineDropSource.asset(
|
||||
AssetDocument(
|
||||
id: 'source',
|
||||
name: 'Source',
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file('/source.mpg').toString(),
|
||||
),
|
||||
);
|
||||
await controller.probe(source);
|
||||
final prepared = container.read(provider).preparation.requireValue!;
|
||||
expect(prepared.metadata.kind, EditorMediaKind.video);
|
||||
expect(prepared.metadata.hasAudio, isFalse);
|
||||
expect(
|
||||
TimelineClock.standard.toTicks(prepared.metadata.duration),
|
||||
9135751405697,
|
||||
);
|
||||
await controller.commit((_, _) async {}, isCurrent: () => true);
|
||||
expect(probes, 1);
|
||||
|
||||
// Unusable metadata must never reach placement validation or insertion.
|
||||
for (final changes in <Map<String, Object?>>[
|
||||
{
|
||||
'duration': {'numerator': '1', 'denominator': 0xffffffff},
|
||||
},
|
||||
{
|
||||
'duration': {'numerator': '9223372036854775807', 'denominator': 1},
|
||||
},
|
||||
{'isProtected': true},
|
||||
{'videoTrackCount': 0, 'videoTrackIds': <int>[]},
|
||||
]) {
|
||||
response = {...response, ...changes};
|
||||
await controller.probe(source);
|
||||
expect(container.read(provider).preparation.hasError, isTrue);
|
||||
expect(container.read(provider).preparation.value, isNull);
|
||||
final preparationError = container.read(provider).preparation.error;
|
||||
var validations = 0;
|
||||
var inserts = 0;
|
||||
await expectLater(
|
||||
controller.commit(
|
||||
(_, _) async {
|
||||
inserts++;
|
||||
},
|
||||
isCurrent: () => true,
|
||||
validatePlacement: () {
|
||||
validations++;
|
||||
},
|
||||
),
|
||||
throwsA(same(preparationError)),
|
||||
);
|
||||
expect(validations, 0);
|
||||
expect(inserts, 0);
|
||||
expect(fixture.timeline.dirty, isFalse);
|
||||
response = {
|
||||
...response,
|
||||
'duration': {'numerator': '64737467444', 'denominator': 10000000},
|
||||
'videoTrackCount': 1,
|
||||
'videoTrackIds': [0],
|
||||
'isProtected': false,
|
||||
};
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a late probe cannot replace or delay a newer incoming source',
|
||||
() async {
|
||||
final fixture = await createPreviewFixture(Uri.file('/unused.mov'));
|
||||
final projects = _Projects(fixture.timeline);
|
||||
final container = ProviderContainer(
|
||||
overrides: [projectsProvider.overrideWith(() => projects)],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
final provider = timelineDropPreparationProvider(
|
||||
'project',
|
||||
fixture.timeline,
|
||||
fixture.timeline.activeSequenceId!,
|
||||
);
|
||||
container.listen(provider, (_, _) {});
|
||||
final controller = container.read(provider.notifier);
|
||||
final delayed = projects._gate = Completer<MediaReference>();
|
||||
final old = controller.probe(TimelineDropSource.asset(_image('old')));
|
||||
var oldFinished = false;
|
||||
final oldCompletion = controller.waitForCompletion().then((_) {
|
||||
oldFinished = true;
|
||||
});
|
||||
projects._gate = null;
|
||||
await controller.probe(TimelineDropSource.asset(_image('new')));
|
||||
await controller.waitForCompletion();
|
||||
expect(oldFinished, isFalse);
|
||||
delayed.complete(MediaReference(id: 'old', uri: Uri.file('/old.png')));
|
||||
await old;
|
||||
await oldCompletion;
|
||||
expect(oldFinished, isTrue);
|
||||
expect(
|
||||
container.read(provider).preparation.requireValue!.media.id,
|
||||
'new',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('a drop waits for its probe and ignores a duplicate commit', () async {
|
||||
final fixture = await createPreviewFixture(Uri.file('/unused.mov'));
|
||||
final projects = _Projects(fixture.timeline);
|
||||
final container = ProviderContainer(
|
||||
overrides: [projectsProvider.overrideWith(() => projects)],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
final provider = timelineDropPreparationProvider(
|
||||
'project',
|
||||
fixture.timeline,
|
||||
fixture.timeline.activeSequenceId!,
|
||||
);
|
||||
container.listen(provider, (_, _) {});
|
||||
final controller = container.read(provider.notifier);
|
||||
final delayed = projects._gate = Completer<MediaReference>();
|
||||
final probe = controller.probe(TimelineDropSource.asset(_image('source')));
|
||||
var inserts = 0;
|
||||
var validations = 0;
|
||||
final commit = controller.commit(
|
||||
(_, _) async {
|
||||
inserts++;
|
||||
},
|
||||
isCurrent: () => true,
|
||||
validatePlacement: () {
|
||||
validations++;
|
||||
},
|
||||
);
|
||||
expect(container.read(provider).commit.isLoading, isTrue);
|
||||
expect(inserts, 0);
|
||||
await controller.commit((_, _) async {
|
||||
inserts++;
|
||||
}, isCurrent: () => true);
|
||||
expect(inserts, 0);
|
||||
projects._gate = null;
|
||||
delayed.complete(
|
||||
MediaReference(id: 'source', uri: Uri.file('/source.png')),
|
||||
);
|
||||
await probe;
|
||||
await commit;
|
||||
expect(validations, 1);
|
||||
expect(inserts, 1);
|
||||
expect(container.read(provider).commit.hasValue, isTrue);
|
||||
expect(container.read(provider).commit.isLoading, isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'a project switch during media acquisition prevents committing a drag',
|
||||
() async {
|
||||
final fixture = await createPreviewFixture(Uri.file('/unused.mov'));
|
||||
final projects = _Projects(fixture.timeline);
|
||||
final container = ProviderContainer(
|
||||
overrides: [projectsProvider.overrideWith(() => projects)],
|
||||
);
|
||||
addTearDown(() async {
|
||||
container.dispose();
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(projectsProvider.future);
|
||||
final provider = timelineDropPreparationProvider(
|
||||
'project',
|
||||
fixture.timeline,
|
||||
fixture.timeline.activeSequenceId!,
|
||||
);
|
||||
container.listen(provider, (_, _) {});
|
||||
final controller = container.read(provider.notifier);
|
||||
await controller.probe(TimelineDropSource.asset(_image('source')));
|
||||
final delayed = projects._gate = Completer<MediaReference>();
|
||||
final acquiring = projects._acquiring = Completer<void>();
|
||||
var inserted = false;
|
||||
final pending = controller.commit((_, _) async {
|
||||
inserted = true;
|
||||
}, isCurrent: () => true);
|
||||
await acquiring.future;
|
||||
projects.leave();
|
||||
delayed.complete(
|
||||
MediaReference(id: 'source', uri: Uri.file('/source.png')),
|
||||
);
|
||||
await pending;
|
||||
expect(inserted, isFalse);
|
||||
expect(fixture.timeline.dirty, isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/preview/fullscreen_playback_bar.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'fullscreen transport previews during dragging and settles on release',
|
||||
(tester) async {
|
||||
final seeks = <int>[];
|
||||
final updates = <int>[];
|
||||
final ends = <int>[];
|
||||
var starts = 0;
|
||||
var plays = 0;
|
||||
var exits = 0;
|
||||
const second = TimelineClock.ticksPerSecond;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: EditorTheme.penDark,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('en'),
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: 560,
|
||||
child: FullscreenPlaybackBar(
|
||||
positionTick: second,
|
||||
durationTick: 48 * 60 * second,
|
||||
frameTick: second ~/ 30,
|
||||
playing: false,
|
||||
onPlayPause: () => plays++,
|
||||
onSeek: seeks.add,
|
||||
onExit: () => exits++,
|
||||
onScrubStart: () => starts++,
|
||||
onScrubUpdate: updates.add,
|
||||
onScrubEnd: ends.add,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('00:01'), findsOneWidget);
|
||||
expect(find.text('-47:59'), findsOneWidget);
|
||||
await tester.tap(find.byTooltip('Play'));
|
||||
await tester.tap(find.byTooltip('Exit fullscreen'));
|
||||
expect(plays, 1);
|
||||
expect(exits, 1);
|
||||
await tester.tap(find.byTooltip('Previous frame'));
|
||||
await tester.tap(find.byTooltip('Next frame'));
|
||||
expect(seeks, [second - second ~/ 30, second + second ~/ 30]);
|
||||
seeks.clear();
|
||||
final rect = tester.getRect(find.byKey(const Key('fullscreen-progress')));
|
||||
final gesture = await tester.startGesture(
|
||||
Offset(rect.left + 20, rect.center.dy),
|
||||
);
|
||||
await gesture.moveTo(rect.center);
|
||||
await tester.pump();
|
||||
expect(seeks, isEmpty);
|
||||
expect(starts, 1);
|
||||
expect(updates, isNotEmpty);
|
||||
expect(updates.last, closeTo(24 * 60 * second, second));
|
||||
expect(ends, isEmpty);
|
||||
await gesture.up();
|
||||
await tester.pump();
|
||||
expect(ends, hasLength(1));
|
||||
expect(ends.single, closeTo(24 * 60 * second, second));
|
||||
await tester.tap(find.byTooltip('Go to start'));
|
||||
expect(seeks.last, 0);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('empty fullscreen transport stays usable at narrow widths', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('en'),
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: 280,
|
||||
child: FullscreenPlaybackBar(
|
||||
positionTick: 0,
|
||||
durationTick: 0,
|
||||
frameTick: TimelineClock.ticksPerSecond ~/ 30,
|
||||
playing: false,
|
||||
onPlayPause: null,
|
||||
onSeek: null,
|
||||
onExit: () {},
|
||||
onScrubStart: null,
|
||||
onScrubUpdate: null,
|
||||
onScrubEnd: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(tester.widget<Slider>(find.byType(Slider)).onChanged, isNull);
|
||||
expect(
|
||||
tester
|
||||
.widget<IconButton>(find.byKey(const Key('preview-fullscreen')))
|
||||
.onPressed,
|
||||
isNotNull,
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
const _generatedFiles = [
|
||||
':(glob)lib/**/*.g.dart',
|
||||
':(glob)lib/**/*.freezed.dart',
|
||||
':(glob)test/**/*.g.dart',
|
||||
':(glob)test/**/*.freezed.dart',
|
||||
];
|
||||
|
||||
void main() {
|
||||
test('workspace generated code is up to date', () async {
|
||||
await _expectNoUntrackedGeneratedFiles();
|
||||
final before = await _generatedContents();
|
||||
final flutterRoot = Platform.environment['FLUTTER_ROOT'];
|
||||
final dart = flutterRoot == null
|
||||
? (Platform.isWindows ? 'dart.exe' : 'dart')
|
||||
: '$flutterRoot/bin/cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}';
|
||||
for (final directory in _generatorRoots()) {
|
||||
final result = await Process.run(dart, [
|
||||
'run',
|
||||
'build_runner',
|
||||
'build',
|
||||
], workingDirectory: directory);
|
||||
expect(
|
||||
result.exitCode,
|
||||
0,
|
||||
reason: '$directory\n${result.stdout}\n${result.stderr}',
|
||||
);
|
||||
}
|
||||
expect(
|
||||
await _generatedContents(),
|
||||
before,
|
||||
reason: 'Generated files changed. Run dart run build_runner build and review the output.',
|
||||
);
|
||||
await _expectNoUntrackedGeneratedFiles();
|
||||
}, timeout: const Timeout(Duration(minutes: 5)));
|
||||
}
|
||||
|
||||
Future<void> _expectNoUntrackedGeneratedFiles() async {
|
||||
final result = await Process.run('git', [
|
||||
'ls-files',
|
||||
'--others',
|
||||
'--',
|
||||
..._generatedFiles,
|
||||
]);
|
||||
expect(result.exitCode, 0, reason: '${result.stderr}');
|
||||
expect(
|
||||
(result.stdout as String).trim(),
|
||||
isEmpty,
|
||||
reason: 'Generate and track the .g.dart and .freezed.dart files in Git.',
|
||||
);
|
||||
}
|
||||
|
||||
Future<Map<String, String>> _generatedContents() async {
|
||||
final contents = <String, String>{};
|
||||
for (final root in [
|
||||
for (final directory in _generatorRoots()) ...[
|
||||
'$directory/lib',
|
||||
'$directory/test',
|
||||
],
|
||||
]) {
|
||||
if (!Directory(root).existsSync()) continue;
|
||||
await for (final entity in Directory(root).list(recursive: true)) {
|
||||
if (entity is File &&
|
||||
(entity.path.endsWith('.g.dart') ||
|
||||
entity.path.endsWith('.freezed.dart'))) {
|
||||
contents[entity.path] = sha256
|
||||
.convert(
|
||||
utf8.encode(
|
||||
(await entity.readAsString()).replaceAll('\r\n', '\n'),
|
||||
),
|
||||
)
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
return contents;
|
||||
}
|
||||
|
||||
Iterable<String> _generatorRoots() sync* {
|
||||
yield '.';
|
||||
for (final directory in Directory(
|
||||
'packages',
|
||||
).listSync().whereType<Directory>()) {
|
||||
final manifest = File('${directory.path}/pubspec.yaml').readAsStringSync();
|
||||
if (RegExp(r'^ build_runner:', multiLine: true).hasMatch(manifest)) {
|
||||
yield directory.path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../../integration_test/support/real_media_report.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'incremental report saves preserve metadata and the latest failures',
|
||||
() async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'real-media-report-',
|
||||
);
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final file = File('${directory.path}/results.json');
|
||||
final metadata = <String, Object?>{
|
||||
'platform': 'android',
|
||||
'previewOnly': true,
|
||||
};
|
||||
final report = RealMediaReport(file, metadata: metadata);
|
||||
metadata['previewOnly'] = false;
|
||||
final checks = <Map<String, Object?>>[];
|
||||
report.files.add({
|
||||
'path': 'source.mp4',
|
||||
'checks': checks,
|
||||
'passed': false,
|
||||
});
|
||||
report.save();
|
||||
expect(
|
||||
(jsonDecode(await file.readAsString()) as Map)['previewOnly'],
|
||||
isTrue,
|
||||
);
|
||||
checks.add({'stage': 'probe', 'passed': true});
|
||||
checks.add({
|
||||
'stage': 'preview',
|
||||
'passed': false,
|
||||
'error': 'frame timeout',
|
||||
});
|
||||
report.save();
|
||||
final saved = jsonDecode(await file.readAsString()) as Map;
|
||||
expect(saved['platform'], 'android');
|
||||
final recorded = (saved['files'] as List).single as Map;
|
||||
expect(recorded['passed'], isFalse);
|
||||
expect(
|
||||
(recorded['checks'] as List).last,
|
||||
containsPair('error', 'frame timeout'),
|
||||
);
|
||||
expect(File('${file.path}.part').existsSync(), isFalse);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:cutdex/integrations/platform/file_picker.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const picker = AppFilePicker();
|
||||
const channel = MethodChannel('filegate');
|
||||
Object? response;
|
||||
MethodCall? lastCall;
|
||||
|
||||
setUp(() {
|
||||
response = null;
|
||||
lastCall = null;
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, (call) async {
|
||||
lastCall = call;
|
||||
return response;
|
||||
});
|
||||
});
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(channel, null);
|
||||
});
|
||||
|
||||
test(
|
||||
'selects an empty directory and preserves the initial location and label',
|
||||
() async {
|
||||
response = [
|
||||
{'path': '/tmp/empty', 'name': 'empty', 'kind': 'directory'},
|
||||
];
|
||||
expect(
|
||||
await picker.pickDirectory(
|
||||
initialDirectory: '/tmp',
|
||||
confirmButtonText: '选择',
|
||||
),
|
||||
'/tmp/empty',
|
||||
);
|
||||
expect(lastCall!.arguments, containsPair('enumerateDirectories', false));
|
||||
expect(lastCall!.arguments, containsPair('initialDirectory', '/tmp'));
|
||||
expect(lastCall!.arguments, containsPair('confirmButtonText', '选择'));
|
||||
},
|
||||
);
|
||||
|
||||
test('cancelled directory and file dialogs produce no selection', () async {
|
||||
expect(await picker.pickDirectory(), isNull);
|
||||
expect(await picker.pickFiles(allowedExtensions: ['mp4']), isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'converts file URLs to local paths while retaining extension filtering',
|
||||
() async {
|
||||
response = [
|
||||
{'path': 'file:///tmp/a%20b.mp4', 'name': 'a b.mp4', 'kind': 'file'},
|
||||
{'path': '/tmp/c.wav', 'name': 'c.wav', 'kind': 'file'},
|
||||
];
|
||||
expect(await picker.pickFiles(allowedExtensions: ['.MP4', 'wav']), [
|
||||
const ExternalMediaFile(path: '/tmp/a b.mp4'),
|
||||
const ExternalMediaFile(path: '/tmp/c.wav'),
|
||||
]);
|
||||
expect(lastCall!.arguments, containsPair('allowMultiple', true));
|
||||
expect(
|
||||
lastCall!.arguments,
|
||||
containsPair('allowedExtensions', ['mp4', 'wav']),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'preserves provider URI, display name and size for project import',
|
||||
() async {
|
||||
response = [
|
||||
{
|
||||
'path': 'content://provider/file/1',
|
||||
'name': 'a.mp4',
|
||||
'kind': 'file',
|
||||
'metadata': {'size': 42},
|
||||
},
|
||||
];
|
||||
expect(await picker.pickFiles(allowedExtensions: ['mp4']), [
|
||||
ExternalMediaFile.content(
|
||||
uri: Uri.parse('content://provider/file/1'),
|
||||
name: 'a.mp4',
|
||||
byteLength: 42,
|
||||
),
|
||||
]);
|
||||
expect(lastCall!.arguments, containsPair('persistAccess', false));
|
||||
},
|
||||
);
|
||||
|
||||
test('propagates native picker failures', () async {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => throw PlatformException(code: 'picker_active'),
|
||||
);
|
||||
await expectLater(
|
||||
picker.pickDirectory(),
|
||||
throwsA(isA<PlatformException>()),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
import 'package:cutdex/app/app.dart';
|
||||
import 'package:cutdex/app/router/app_router.dart';
|
||||
import 'package:cutdex/features/settings/appearance_settings.dart';
|
||||
import 'package:cutdex/features/settings/language_settings.dart';
|
||||
import 'package:cutdex/persistence/settings/language_settings_repository.dart';
|
||||
import 'package:cutdex/features/settings/settings_dialog.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/l10n/app_localizations_en.dart';
|
||||
import 'package:cutdex/l10n/app_messages.dart';
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
import 'package:cutdex/l10n/app_localizations_zh.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
void main() {
|
||||
test('Agent errors use both Simplified and Traditional Chinese', () {
|
||||
final simplified = AppLocalizationsZhHans();
|
||||
final traditional = AppLocalizationsZhHant();
|
||||
expect(simplified.agentContextBudgetExceeded, contains('输入预算不足'));
|
||||
expect(traditional.agentContextBudgetExceeded, contains('輸入預算不足'));
|
||||
expect(simplified.agentAuthenticationFailed, contains('鉴权失败'));
|
||||
expect(traditional.agentAuthenticationFailed, contains('驗證失敗'));
|
||||
});
|
||||
|
||||
test(
|
||||
'language choice is saved and restored by a new provider container',
|
||||
() async {
|
||||
final repository = _LanguageRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
expect(
|
||||
await container.read(languageSettingsProvider.future),
|
||||
AppLanguage.system,
|
||||
);
|
||||
await container
|
||||
.read(languageSettingsProvider.notifier)
|
||||
.setLanguage(AppLanguage.english);
|
||||
container.dispose();
|
||||
|
||||
final reopened = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
addTearDown(reopened.dispose);
|
||||
expect(
|
||||
await reopened.read(languageSettingsProvider.future),
|
||||
AppLanguage.english,
|
||||
);
|
||||
await reopened
|
||||
.read(languageSettingsProvider.notifier)
|
||||
.setLanguage(AppLanguage.system);
|
||||
expect(
|
||||
reopened.read(languageSettingsProvider).requireValue.locale,
|
||||
isNull,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('failed persistence preserves the current language', () async {
|
||||
final repository = _LanguageRepository()
|
||||
..language = AppLanguage.simplifiedChinese;
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(languageSettingsProvider.future);
|
||||
repository.failSave = true;
|
||||
await expectLater(
|
||||
container
|
||||
.read(languageSettingsProvider.notifier)
|
||||
.setLanguage(AppLanguage.english),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(
|
||||
container.read(languageSettingsProvider).requireValue,
|
||||
AppLanguage.simplifiedChinese,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'settings switch immediately and system choice follows device locale',
|
||||
(tester) async {
|
||||
tester.platformDispatcher.localesTestValue = const [Locale('zh')];
|
||||
addTearDown(tester.platformDispatcher.clearLocalesTestValue);
|
||||
final repository = _LanguageRepository();
|
||||
final router = GoRouter(
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/',
|
||||
builder: (_, _) => const Scaffold(body: SettingsDialog()),
|
||||
),
|
||||
],
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
appearanceSettingsProvider.overrideWith(_Appearance.new),
|
||||
appRouterProvider.overrideWithValue(router),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
addTearDown(router.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: const CutdexApp(),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('通用'), findsNWidgets(3));
|
||||
|
||||
await tester.tap(find.byType(AppSelect<AppLanguage>));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('English'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('General'), findsNWidgets(3));
|
||||
expect(repository.language, AppLanguage.english);
|
||||
|
||||
tester.platformDispatcher.localesTestValue = const [Locale('zh', 'CN')];
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('General'), findsNWidgets(3));
|
||||
|
||||
await tester.tap(find.byType(AppSelect<AppLanguage>));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('System default').last);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('通用'), findsNWidgets(3));
|
||||
expect(repository.language, AppLanguage.system);
|
||||
|
||||
tester.platformDispatcher.localesTestValue = const [Locale('sw')];
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('General'), findsNWidgets(3));
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
test('Chinese scripts and regions resolve in device preference order', () {
|
||||
final supported = AppLocalizations.supportedLocales;
|
||||
const hans = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans');
|
||||
const hant = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant');
|
||||
for (final country in ['TW', 'HK', 'MO']) {
|
||||
expect(resolveAppLocale([Locale('zh', country)], supported), hant);
|
||||
}
|
||||
expect(resolveAppLocale(const [Locale('zh', 'CN')], supported), hans);
|
||||
expect(resolveAppLocale(const [Locale('zh', 'SG')], supported), hans);
|
||||
expect(resolveAppLocale(const [Locale('zh')], supported), hans);
|
||||
expect(
|
||||
resolveAppLocale(const [
|
||||
Locale.fromSubtags(
|
||||
languageCode: 'zh',
|
||||
scriptCode: 'Hans',
|
||||
countryCode: 'TW',
|
||||
),
|
||||
], supported),
|
||||
hans,
|
||||
);
|
||||
expect(
|
||||
resolveAppLocale(const [
|
||||
Locale.fromSubtags(
|
||||
languageCode: 'zh',
|
||||
scriptCode: 'Hant',
|
||||
countryCode: 'CN',
|
||||
),
|
||||
], supported),
|
||||
hant,
|
||||
);
|
||||
expect(
|
||||
resolveAppLocale(const [Locale('sw'), Locale('pt', 'BR')], supported),
|
||||
const Locale('pt'),
|
||||
);
|
||||
expect(
|
||||
resolveAppLocale(const [Locale('sw')], supported),
|
||||
const Locale('en'),
|
||||
);
|
||||
expect(resolveAppLocale(null, supported), const Locale('en'));
|
||||
// Fallback stays English regardless of generator ordering.
|
||||
expect(
|
||||
resolveAppLocale(const [Locale('sw')], supported.reversed),
|
||||
const Locale('en'),
|
||||
);
|
||||
});
|
||||
|
||||
test('default timeline names follow every supported locale', () {
|
||||
final expected = <String, String>{
|
||||
'de': 'Timeline 2',
|
||||
'en': 'Timeline 2',
|
||||
'es': 'Línea de tiempo 2',
|
||||
'fr': 'Timeline 2',
|
||||
'it': 'Timeline 2',
|
||||
'ja': 'タイムライン 2',
|
||||
'ko': '타임라인 2',
|
||||
'pt': 'Linha do tempo 2',
|
||||
'ru': 'Таймлайн 2',
|
||||
'zh': '时间线 2',
|
||||
'zh-Hans': '时间线 2',
|
||||
'zh-Hant': '時間軸 2',
|
||||
};
|
||||
for (final locale in AppLocalizations.supportedLocales) {
|
||||
final key = [locale.languageCode, ?locale.scriptCode].join('-');
|
||||
expect(
|
||||
lookupAppLocalizations(locale).defaultTimelineName(2),
|
||||
expected[key],
|
||||
reason: key,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'every language is selectable and updates settings and direction',
|
||||
(tester) async {
|
||||
final repository = _LanguageRepository();
|
||||
final router = GoRouter(
|
||||
routes: [
|
||||
GoRoute(
|
||||
path: '/',
|
||||
builder: (_, _) => const Scaffold(body: SettingsDialog()),
|
||||
),
|
||||
],
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
appearanceSettingsProvider.overrideWith(_Appearance.new),
|
||||
appRouterProvider.overrideWithValue(router),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
addTearDown(router.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: const CutdexApp(),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final choices = [
|
||||
(AppLanguage.english, 'Settings'),
|
||||
(AppLanguage.simplifiedChinese, '设置'),
|
||||
(AppLanguage.traditionalChinese, '設定'),
|
||||
(AppLanguage.japanese, '設定'),
|
||||
(AppLanguage.korean, '설정'),
|
||||
(AppLanguage.french, 'Paramètres'),
|
||||
(AppLanguage.german, 'Einstellungen'),
|
||||
(AppLanguage.spanish, 'Ajustes'),
|
||||
(AppLanguage.portuguese, 'Configurações'),
|
||||
(AppLanguage.italian, 'Impostazioni'),
|
||||
(AppLanguage.russian, 'Настройки'),
|
||||
];
|
||||
for (final (language, heading) in choices) {
|
||||
final languageSelect = find.byType(AppSelect<AppLanguage>);
|
||||
await tester.ensureVisible(languageSelect);
|
||||
await tester.tap(languageSelect);
|
||||
await tester.pumpAndSettle();
|
||||
final option = find.text(language.nativeName).last;
|
||||
await tester.ensureVisible(option);
|
||||
await tester.tap(option);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.widget<AppDialog>(find.byType(AppDialog)).title, heading);
|
||||
expect(find.text(heading), findsOneWidget);
|
||||
final l10n = AppLocalizations.of(
|
||||
tester.element(find.byType(SettingsDialog)),
|
||||
)!;
|
||||
expect(find.text(l10n.general), findsNWidgets(3));
|
||||
expect(repository.language, language);
|
||||
final context = tester.element(find.byType(SettingsDialog));
|
||||
expect(Localizations.localeOf(context), language.locale);
|
||||
expect(Directionality.of(context), TextDirection.ltr);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
// Rebuild at a narrow size to exercise field wrapping and dialog layout.
|
||||
tester.view.physicalSize = const Size(360, 400);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.widget<AppDialog>(find.byType(AppDialog)).title,
|
||||
'Настройки',
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
test('localized parameters and known domain errors preserve diagnostics', () {
|
||||
final en = AppLocalizationsEn();
|
||||
final zh = AppLocalizationsZh();
|
||||
expect(en.removeMediaConfirmation('shot.mp4'), contains('shot.mp4'));
|
||||
expect(zh.captionsImported('3'), '已导入 3 条字幕');
|
||||
expect(
|
||||
en.failureMessage(const AppFailure(AppErrorCode.mediaNoLongerExists)),
|
||||
'Media no longer exists',
|
||||
);
|
||||
expect(en.errorMessage('Native error 123'), 'Native error 123');
|
||||
});
|
||||
}
|
||||
|
||||
class _Appearance extends AppearanceSettings {
|
||||
@override
|
||||
Future<AppAppearance> build() async => AppAppearance.system;
|
||||
}
|
||||
|
||||
class _LanguageRepository implements LanguageSettingsRepository {
|
||||
AppLanguage language = AppLanguage.system;
|
||||
bool failSave = false;
|
||||
|
||||
@override
|
||||
Future<AppLanguage> load() async => language;
|
||||
|
||||
@override
|
||||
Future<void> save(AppLanguage value) async {
|
||||
if (failSave) throw StateError('Storage unavailable');
|
||||
language = value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/settings/language_settings.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
final template = _read('en');
|
||||
final keys = template.keys.where((key) => !key.startsWith('@')).toSet();
|
||||
final locales = [
|
||||
'en',
|
||||
'zh',
|
||||
'zh_Hans',
|
||||
'zh_Hant',
|
||||
'ja',
|
||||
'ko',
|
||||
'fr',
|
||||
'de',
|
||||
'es',
|
||||
'pt',
|
||||
'it',
|
||||
'ru',
|
||||
];
|
||||
for (final locale in locales) {
|
||||
test(
|
||||
'$locale has complete nonempty translations and unchanged parameters',
|
||||
() {
|
||||
final translations = _read(locale);
|
||||
expect(translations['@@locale'], locale);
|
||||
expect(
|
||||
translations.keys.where((key) => !key.startsWith('@')).toSet(),
|
||||
keys,
|
||||
);
|
||||
for (final key in keys) {
|
||||
final value = translations[key] as String;
|
||||
expect(value.trim(), isNotEmpty, reason: '$locale:$key');
|
||||
expect(value, isNot(contains('ZXQ')), reason: '$locale:$key');
|
||||
expect(
|
||||
_parameters(value),
|
||||
_parameters(template[key] as String),
|
||||
reason: '$locale:$key',
|
||||
);
|
||||
// Preserve the names of formats, models, and diagnostic codes.
|
||||
for (final term in [
|
||||
'MCP',
|
||||
'MP4',
|
||||
'SRT',
|
||||
'iTT',
|
||||
'CEA-608',
|
||||
'SCC',
|
||||
'SubRip',
|
||||
'Rec.709',
|
||||
'HDR',
|
||||
'SDR',
|
||||
'MelBand',
|
||||
'Whisper Turbo',
|
||||
'notConfigured',
|
||||
'noAudio',
|
||||
'invalidResult',
|
||||
'workerExited',
|
||||
'processingFailed',
|
||||
]) {
|
||||
if ((template[key] as String).contains(term)) {
|
||||
expect(value, contains(term), reason: '$locale:$key');
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('all eleven selectable locales have generated resource support', () {
|
||||
final choices = AppLanguage.values.where(
|
||||
(language) => language != AppLanguage.system,
|
||||
);
|
||||
expect(choices.length, 11);
|
||||
for (final choice in choices) {
|
||||
expect(AppLocalizations.supportedLocales, contains(choice.locale));
|
||||
}
|
||||
expect(AppLocalizations.supportedLocales.first.languageCode, 'en');
|
||||
});
|
||||
}
|
||||
|
||||
Map<String, dynamic> _read(String locale) =>
|
||||
jsonDecode(File('lib/l10n/app_$locale.arb').readAsStringSync())
|
||||
as Map<String, dynamic>;
|
||||
|
||||
Set<String> _parameters(String value) =>
|
||||
RegExp(r'\{(\w+)(?:\}|,)')
|
||||
.allMatches(value)
|
||||
.map((match) => match[1]!)
|
||||
.toSet();
|
||||
@@ -0,0 +1,211 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
import 'package:cutdex/workspace/persistence/timeline_creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/app/shells/phone_workspace_shell.dart';
|
||||
import 'package:cutdex/app/shells/tablet_workspace_shell.dart';
|
||||
import 'package:cutdex/features/assistant/composer_document.dart';
|
||||
import 'package:cutdex/features/assistant/composer_suggestion_surface.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex/workspace/media_color_interpretation.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/workspace_mode.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
Widget _localized(Locale locale, Widget child) => MaterialApp(
|
||||
locale: locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
|
||||
void main() {
|
||||
for (final tablet in [false, true]) {
|
||||
testWidgets(
|
||||
'${tablet ? 'tablet' : 'phone'} navigation follows locale changes',
|
||||
(tester) async {
|
||||
Widget shell() => tablet
|
||||
? TabletWorkspaceShell(
|
||||
mode: WorkspaceMode.agent,
|
||||
onModeChanged: (_) {},
|
||||
navigation: const SizedBox(),
|
||||
headerActions: const SizedBox(),
|
||||
title: '',
|
||||
integratedTitlebar: false,
|
||||
agent: const SizedBox(),
|
||||
editor: const SizedBox(),
|
||||
)
|
||||
: PhoneWorkspaceShell(
|
||||
mode: WorkspaceMode.agent,
|
||||
onModeChanged: (_) {},
|
||||
navigation: const SizedBox(),
|
||||
headerActions: const SizedBox(),
|
||||
title: '',
|
||||
integratedTitlebar: false,
|
||||
agent: const SizedBox(),
|
||||
editor: const SizedBox(),
|
||||
);
|
||||
for (final (locale, agent, cut) in [
|
||||
(const Locale('en'), 'Agent', 'Cut'),
|
||||
(const Locale('zh'), '助手', '剪辑'),
|
||||
(const Locale('fr'), 'Assistant', 'Montage'),
|
||||
]) {
|
||||
await tester.pumpWidget(_localized(locale, shell()));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(agent), findsOneWidget);
|
||||
expect(find.text(cut), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('open reference menu follows locale without changing the draft', (
|
||||
tester,
|
||||
) async {
|
||||
final controller = ComposerDocumentController();
|
||||
addTearDown(controller.dispose);
|
||||
Widget composer() => Center(
|
||||
child: ComposerSuggestionSurface(
|
||||
controller: controller,
|
||||
projectId: 'project',
|
||||
assets: const [],
|
||||
timelines: const [],
|
||||
width: 300,
|
||||
onSend: () {},
|
||||
builder: (_, focus) =>
|
||||
TextField(controller: controller, focusNode: focus),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(_localized(const Locale('en'), composer()));
|
||||
await tester.enterText(find.byType(TextField), '@missing');
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('No options available'), findsOneWidget);
|
||||
await tester.pumpWidget(_localized(const Locale('zh'), composer()));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('暂无可用选项'), findsOneWidget);
|
||||
expect(controller.text, '@missing');
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
test('subtitle languages localize names while preserving protocol codes', () {
|
||||
final expected = {
|
||||
'en': ['English', 'Japanese', 'Cantonese'],
|
||||
'zh': ['英语', '日语', '粤语'],
|
||||
'zh-Hant': ['英文', '日文', '粵語'],
|
||||
'fr': ['anglais', 'japonais', 'cantonais'],
|
||||
};
|
||||
for (final locale in AppLocalizations.supportedLocales) {
|
||||
final l10n = lookupAppLocalizations(locale);
|
||||
final key = [locale.languageCode, ?locale.scriptCode].join('-');
|
||||
if (expected[key] case final names?) {
|
||||
expect(['en', 'ja', 'yue'].map(l10n.subtitleLanguageName), names);
|
||||
}
|
||||
for (final code in {
|
||||
...m2m100LanguageNames.keys,
|
||||
...subtitleNativeLanguageNames.keys,
|
||||
}) {
|
||||
expect(
|
||||
l10n.subtitleLanguageName(code),
|
||||
isNot(code),
|
||||
reason: '$key:$code',
|
||||
);
|
||||
}
|
||||
expect(l10n.subtitleLanguageName('auto'), l10n.autoDetect);
|
||||
expect(l10n.subtitleLanguageName('none'), l10n.noTranslation);
|
||||
expect(l10n.subtitleLanguageName('unknown-code'), 'unknown-code');
|
||||
}
|
||||
});
|
||||
|
||||
test('known exceptions translate without losing unknown diagnostic text', () {
|
||||
final en = lookupAppLocalizations(const Locale('en'));
|
||||
final zh = lookupAppLocalizations(const Locale('zh'));
|
||||
expect(
|
||||
en.errorMessage(
|
||||
AppException(AppErrorCode.mediaReadFailed, diagnostic: 'Any wording'),
|
||||
),
|
||||
en.mediaReadFailed,
|
||||
);
|
||||
expect(
|
||||
en.errorMessage(
|
||||
AppException(
|
||||
AppErrorCode.timelineRequired,
|
||||
diagnostic: 'Different punctuation!',
|
||||
),
|
||||
),
|
||||
en.timelineRequired,
|
||||
);
|
||||
expect(
|
||||
en.errorMessage(
|
||||
AppException(
|
||||
AppErrorCode.resourceDownloadHttpFailed,
|
||||
httpStatusCode: 503,
|
||||
),
|
||||
),
|
||||
en.resourceDownloadHttpFailed('503'),
|
||||
);
|
||||
expect(
|
||||
en.errorMessage(AppException(AppErrorCode.resourceChecksumFailed)),
|
||||
en.resourceChecksumFailed,
|
||||
);
|
||||
expect(
|
||||
zh.errorMessage(AppException(AppErrorCode.timelineMissing)),
|
||||
zh.timelineMissing,
|
||||
);
|
||||
expect(en.errorMessage('Native error 123'), 'Native error 123');
|
||||
final unknown = const FileSystemException(
|
||||
'Native error 123',
|
||||
'/missing.mov',
|
||||
);
|
||||
expect(en.errorMessage(unknown), unknown.toString());
|
||||
expect(
|
||||
zh.errorMessage(AppException(AppErrorCode.mediaReadFailed)),
|
||||
'无法读取素材',
|
||||
);
|
||||
expect(
|
||||
en.errorMessage('FormatException: diagnostic 123'),
|
||||
'FormatException: diagnostic 123',
|
||||
);
|
||||
expect(RenderColorSpace.linearRec2020.label(zh), '线性 Rec.2020');
|
||||
});
|
||||
|
||||
test('new sequence names follow the current language and saved names stay intact', () async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-localized-names-',
|
||||
);
|
||||
var l10n = lookupAppLocalizations(const Locale('en'));
|
||||
TimelineCreationNames names() => TimelineCreationNames(
|
||||
timeline: l10n.defaultTimelineName(1),
|
||||
sequence: l10n.primarySequence,
|
||||
storyline: l10n.primaryStoryline,
|
||||
);
|
||||
final workspace = ProjectWorkspace(creationNames: names());
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await workspace.open('${root.path}/Project.cutdex', name: 'My project');
|
||||
final projectId = workspace.project!.info.id;
|
||||
final originalId = (await workspace.project!.listTimelines()).first.id;
|
||||
final original = await workspace.loadTimeline(projectId, originalId);
|
||||
expect(original.name, 'Timeline 1');
|
||||
expect(original.sequences.single.name, 'Main sequence');
|
||||
expect(original.sequences.single.storylines.single.name, 'Main storyline');
|
||||
|
||||
l10n = lookupAppLocalizations(const Locale('zh'));
|
||||
final timelines = await workspace.createTimeline(
|
||||
'User-chosen name',
|
||||
creationNames: names(),
|
||||
);
|
||||
final added = await workspace.loadTimeline(projectId, timelines.last.id);
|
||||
expect(added.name, 'User-chosen name');
|
||||
expect(added.sequences.single.name, '主序列');
|
||||
expect(added.sequences.single.storylines.single.name, '主线');
|
||||
final retained = await workspace.loadTimeline(projectId, originalId);
|
||||
expect(retained.name, 'Timeline 1');
|
||||
expect(retained.sequences.single.name, 'Main sequence');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/settings/location_settings.dart';
|
||||
import 'package:cutdex/integrations/runtime/processing_resource_repository.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_location_directory.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_riverpod/misc.dart' show ProviderListenable;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'project location load errors can be retried and re-inspected',
|
||||
() async {
|
||||
final repository = _ProjectRepository()..failLoads = true;
|
||||
final inspector = _DirectoryInspector(ProjectLocationStatus.missing);
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
projectLocationDirectoryProvider.overrideWithValue(inspector),
|
||||
],
|
||||
);
|
||||
await _ready(container, projectLocationSettingsProvider);
|
||||
expect(
|
||||
container.read(projectLocationSettingsProvider).error,
|
||||
LocationSettingsError.load,
|
||||
);
|
||||
repository.failLoads = false;
|
||||
final controller = container.read(
|
||||
projectLocationSettingsProvider.notifier,
|
||||
);
|
||||
await controller.reload();
|
||||
final loaded = container.read(projectLocationSettingsProvider);
|
||||
expect(loaded.directory, '/projects');
|
||||
expect(loaded.status, ProjectLocationStatus.missing);
|
||||
expect(loaded.error, isNull);
|
||||
inspector.status = ProjectLocationStatus.ready;
|
||||
await controller.reload();
|
||||
expect(
|
||||
container.read(projectLocationSettingsProvider).status,
|
||||
ProjectLocationStatus.ready,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'project saves keep the previous path on failure and reload on success',
|
||||
() async {
|
||||
final repository = _ProjectRepository();
|
||||
final inspector = _DirectoryInspector(ProjectLocationStatus.ready);
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
projectLocationDirectoryProvider.overrideWithValue(inspector),
|
||||
],
|
||||
);
|
||||
await _ready(container, projectLocationSettingsProvider);
|
||||
final controller = container.read(
|
||||
projectLocationSettingsProvider.notifier,
|
||||
);
|
||||
repository.failWrites = true;
|
||||
await controller.save('/other');
|
||||
final failed = container.read(projectLocationSettingsProvider);
|
||||
expect(failed.directory, '/projects');
|
||||
expect(failed.error, LocationSettingsError.save);
|
||||
expect(failed.saving, isFalse);
|
||||
repository.failWrites = false;
|
||||
inspector.status = ProjectLocationStatus.unavailable;
|
||||
await controller.save('/other');
|
||||
final saved = container.read(projectLocationSettingsProvider);
|
||||
expect(saved.directory, '/other');
|
||||
expect(saved.status, ProjectLocationStatus.unavailable);
|
||||
expect(saved.error, isNull);
|
||||
expect(inspector.paths, ['/projects', '/other']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'project saves and reloads run in order while storage is pending',
|
||||
() async {
|
||||
final repository = _ProjectRepository()..writeGate = Completer<void>();
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
projectLocationDirectoryProvider.overrideWithValue(
|
||||
_DirectoryInspector(ProjectLocationStatus.ready),
|
||||
),
|
||||
],
|
||||
);
|
||||
await _ready(container, projectLocationSettingsProvider);
|
||||
final controller = container.read(
|
||||
projectLocationSettingsProvider.notifier,
|
||||
);
|
||||
final first = controller.save('/first');
|
||||
await repository.started.future;
|
||||
final second = controller.save('/second');
|
||||
final retry = controller.reload();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(repository.writes, ['/first']);
|
||||
expect(container.read(projectLocationSettingsProvider).saving, isTrue);
|
||||
expect(
|
||||
container.read(projectLocationSettingsProvider).directory,
|
||||
'/projects',
|
||||
);
|
||||
repository.writeGate!.complete();
|
||||
await Future.wait([first, second, retry]);
|
||||
expect(repository.writes, ['/first', '/second']);
|
||||
expect(
|
||||
container.read(projectLocationSettingsProvider).directory,
|
||||
'/second',
|
||||
);
|
||||
expect(container.read(projectLocationSettingsProvider).saving, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a resource save refreshes the repository even after the page closes',
|
||||
() async {
|
||||
final repository = _ResourceRepository()..writeGate = Completer<void>();
|
||||
var resourceBuilds = 0;
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
processingResourceRepositoryProvider.overrideWith((ref) {
|
||||
resourceBuilds++;
|
||||
final resources = ProcessingResourceRepository(
|
||||
root: Directory('${repository.value}/Processing'),
|
||||
catalog: [],
|
||||
);
|
||||
ref.onDispose(resources.dispose);
|
||||
return resources;
|
||||
}),
|
||||
],
|
||||
);
|
||||
container.listen(processingResourceRepositoryProvider, (_, _) {});
|
||||
final oldResources = await container.read(
|
||||
processingResourceRepositoryProvider.future,
|
||||
);
|
||||
expect(oldResources.root.path, '/resources/Processing');
|
||||
final page = container.listen(
|
||||
resourceLocationSettingsProvider,
|
||||
(_, _) {},
|
||||
);
|
||||
await _ready(
|
||||
container,
|
||||
resourceLocationSettingsProvider,
|
||||
closeAfterReady: true,
|
||||
);
|
||||
final save = container
|
||||
.read(resourceLocationSettingsProvider.notifier)
|
||||
.save('/new');
|
||||
await repository.started.future;
|
||||
page.close();
|
||||
await container.pump();
|
||||
expect(container.exists(resourceLocationSettingsProvider), isTrue);
|
||||
repository.writeGate!.complete();
|
||||
await save;
|
||||
await container.pump();
|
||||
final newResources = await container.read(
|
||||
processingResourceRepositoryProvider.future,
|
||||
);
|
||||
expect(newResources.root.path, '/new/Processing');
|
||||
expect(resourceBuilds, 2);
|
||||
expect(container.exists(resourceLocationSettingsProvider), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('resource location load errors are owned by the controller', () async {
|
||||
final repository = _ResourceRepository()..failLoads = true;
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
],
|
||||
);
|
||||
await _ready(container, resourceLocationSettingsProvider);
|
||||
final state = container.read(resourceLocationSettingsProvider);
|
||||
expect(state.error, LocationSettingsError.load);
|
||||
expect(state.loading, isFalse);
|
||||
repository.failLoads = false;
|
||||
await container
|
||||
.read(resourceLocationSettingsProvider.notifier)
|
||||
.save('/new');
|
||||
expect(container.read(resourceLocationSettingsProvider).directory, '/new');
|
||||
expect(container.read(resourceLocationSettingsProvider).error, isNull);
|
||||
});
|
||||
|
||||
test(
|
||||
'resource save failures retain the path and allow a later save',
|
||||
() async {
|
||||
final repository = _ResourceRepository();
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
],
|
||||
);
|
||||
await _ready(container, resourceLocationSettingsProvider);
|
||||
final controller = container.read(
|
||||
resourceLocationSettingsProvider.notifier,
|
||||
);
|
||||
repository.failWrites = true;
|
||||
await controller.save('/new');
|
||||
final failed = container.read(resourceLocationSettingsProvider);
|
||||
expect(failed.directory, '/resources');
|
||||
expect(failed.error, LocationSettingsError.save);
|
||||
expect(failed.saving, isFalse);
|
||||
repository.failWrites = false;
|
||||
await controller.save('/new');
|
||||
final saved = container.read(resourceLocationSettingsProvider);
|
||||
expect(saved.directory, '/new');
|
||||
expect(saved.error, isNull);
|
||||
expect(saved.saving, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'closing directory settings during a save skips queued writes safely',
|
||||
() async {
|
||||
final repository = _ResourceRepository()..writeGate = Completer<void>();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
repository,
|
||||
),
|
||||
],
|
||||
);
|
||||
await _ready(container, resourceLocationSettingsProvider);
|
||||
final controller = container.read(
|
||||
resourceLocationSettingsProvider.notifier,
|
||||
);
|
||||
final first = controller.save('/first');
|
||||
await repository.started.future;
|
||||
final second = controller.save('/second');
|
||||
container.dispose();
|
||||
repository.writeGate!.complete();
|
||||
await Future.wait([first, second]);
|
||||
expect(repository.value, '/first');
|
||||
expect(repository.writes, ['/first']);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _ready(
|
||||
ProviderContainer container,
|
||||
ProviderListenable<LocationSettingsState> provider, {
|
||||
bool closeAfterReady = false,
|
||||
}) {
|
||||
final completer = Completer<void>();
|
||||
final subscription = container.listen(provider, (_, state) {
|
||||
if (!state.loading && !completer.isCompleted) completer.complete();
|
||||
}, fireImmediately: true);
|
||||
return completer.future.then((_) {
|
||||
if (closeAfterReady) subscription.close();
|
||||
});
|
||||
}
|
||||
|
||||
class _DirectoryInspector extends ProjectLocationDirectory {
|
||||
_DirectoryInspector(this.status);
|
||||
ProjectLocationStatus status;
|
||||
final paths = <String>[];
|
||||
|
||||
@override
|
||||
Future<ProjectLocationStatus> inspect(String path) async {
|
||||
paths.add(path);
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
class _ProjectRepository extends MemoryProjectLocationSettingsRepository {
|
||||
_ProjectRepository() : super('/projects');
|
||||
bool failLoads = false;
|
||||
bool failWrites = false;
|
||||
final writes = <String>[];
|
||||
final started = Completer<void>();
|
||||
Completer<void>? writeGate;
|
||||
|
||||
@override
|
||||
Future<String?> load() async {
|
||||
if (failLoads) throw StateError('read failed');
|
||||
return super.load();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(String directory) async {
|
||||
writes.add(directory);
|
||||
if (!started.isCompleted) started.complete();
|
||||
await writeGate?.future;
|
||||
if (failWrites) throw StateError('write failed');
|
||||
await super.save(directory);
|
||||
}
|
||||
}
|
||||
|
||||
class _ResourceRepository extends MemoryResourceLocationSettingsRepository {
|
||||
_ResourceRepository() : super('/resources');
|
||||
bool failLoads = false;
|
||||
bool failWrites = false;
|
||||
final writes = <String>[];
|
||||
final started = Completer<void>();
|
||||
Completer<void>? writeGate;
|
||||
|
||||
@override
|
||||
Future<String?> load() async {
|
||||
if (failLoads) throw StateError('read failed');
|
||||
return super.load();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(String directory) async {
|
||||
writes.add(directory);
|
||||
if (!started.isCompleted) started.complete();
|
||||
await writeGate?.future;
|
||||
if (failWrites) throw StateError('write failed');
|
||||
await super.save(directory);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('native build refuses only its running executable', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex build guard ');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final executable = await File('/bin/sleep').copy('${root.path}/cutdex');
|
||||
await Process.run('/bin/chmod', ['u+x', executable.path]);
|
||||
Future<ProcessResult> check(String path) => Process.run('/bin/sh', [
|
||||
'tool/macos/check_macos_build_target.sh',
|
||||
path,
|
||||
]);
|
||||
|
||||
expect((await check(executable.path)).exitCode, 0);
|
||||
final process = await Process.start(executable.path, ['60']);
|
||||
try {
|
||||
final blocked = await check(executable.path);
|
||||
expect(blocked.exitCode, 1);
|
||||
expect(blocked.stderr, contains('Save your edits'));
|
||||
expect((await check('${root.path}/other/cutdex')).exitCode, 0);
|
||||
} finally {
|
||||
process.kill();
|
||||
await process.exitCode;
|
||||
}
|
||||
expect((await check(executable.path)).exitCode, 0);
|
||||
}, skip: !Platform.isMacOS);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/integrations/mcp/mcp_settings.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex/features/settings/mcp_settings_panel.dart';
|
||||
import 'package:cutdex/features/settings/settings_dialog.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
void main() {
|
||||
test('overlapping MCP updates retain enablement and port', () async {
|
||||
final repository = MemoryMcpSettingsRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [mcpSettingsRepositoryProvider.overrideWithValue(repository)],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(mcpSettingsProvider.future);
|
||||
final settings = container.read(mcpSettingsProvider.notifier);
|
||||
await Future.wait([
|
||||
settings.saveSettings(enabled: true),
|
||||
settings.saveSettings(port: 47832),
|
||||
]);
|
||||
expect(repository.value!.enabled, isTrue);
|
||||
expect(repository.value!.port, 47832);
|
||||
await expectLater(settings.saveSettings(port: 0), throwsArgumentError);
|
||||
await settings.saveSettings(port: 47833);
|
||||
expect(repository.value!.port, 47833);
|
||||
});
|
||||
|
||||
testWidgets('sidebar settings fit desktop and narrow windows', (
|
||||
tester,
|
||||
) async {
|
||||
for (final size in [const Size(1280, 800), const Size(390, 640)]) {
|
||||
await tester.binding.setSurfaceSize(size);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
appearanceSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryAppearanceSettingsRepository(),
|
||||
),
|
||||
mcpSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryMcpSettingsRepository(),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(body: SettingsDialog()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final closeButton = find.byKey(const Key('app-dialog-close-button'));
|
||||
final sidebar = find.byKey(const Key('settings-sidebar'));
|
||||
final divider = find.byKey(const Key('settings-sidebar-divider'));
|
||||
expect(sidebar, findsOneWidget);
|
||||
expect(divider, findsOneWidget);
|
||||
expect(closeButton, findsOneWidget);
|
||||
expect(find.byKey(const Key('app-dialog-header-content')), findsNothing);
|
||||
final frameSize = tester.getSize(
|
||||
find.byKey(const Key('app-dialog-frame')),
|
||||
);
|
||||
final viewport = MediaQuery.sizeOf(
|
||||
tester.element(find.byType(SettingsDialog)),
|
||||
);
|
||||
if (size.width == 1280) {
|
||||
expect(
|
||||
frameSize.width,
|
||||
closeTo((viewport.width * .9).clamp(560, 1120), .001),
|
||||
);
|
||||
expect(
|
||||
frameSize.height,
|
||||
closeTo((viewport.height * .88).clamp(520, 704), .001),
|
||||
);
|
||||
}
|
||||
expect(tester.getSize(closeButton), const Size.square(24));
|
||||
expect(tester.getRect(sidebar).right, tester.getRect(divider).left);
|
||||
expect(tester.getRect(sidebar).height, frameSize.height);
|
||||
expect(
|
||||
tester.getRect(find.text('外观')).left,
|
||||
greaterThan(tester.getRect(divider).right),
|
||||
);
|
||||
expect(
|
||||
tester.widget<Text>(find.text('外观')).style?.fontSize,
|
||||
AppTheme.settingsContentTheme(EditorTheme.penDark)
|
||||
.textTheme
|
||||
.labelLarge
|
||||
?.fontSize,
|
||||
);
|
||||
expect(find.text('外观'), findsOneWidget);
|
||||
await tester.tap(find.text('MCP').first);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('监听端口'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
}
|
||||
await tester.binding.setSurfaceSize(null);
|
||||
});
|
||||
test('settings persist the token and enablement; invalid or failed writes retain state', () async {
|
||||
final repository = MemoryMcpSettingsRepository();
|
||||
ProviderContainer create() => ProviderContainer(
|
||||
overrides: [mcpSettingsRepositoryProvider.overrideWithValue(repository)],
|
||||
);
|
||||
final container = create();
|
||||
addTearDown(container.dispose);
|
||||
final initial = await container.read(mcpSettingsProvider.future);
|
||||
expect(initial.enabled, false);
|
||||
expect(initial.token.length, greaterThanOrEqualTo(32));
|
||||
await container
|
||||
.read(mcpSettingsProvider.notifier)
|
||||
.saveSettings(enabled: true, port: 47832);
|
||||
final restored = create();
|
||||
addTearDown(restored.dispose);
|
||||
final value = await restored.read(mcpSettingsProvider.future);
|
||||
expect(value.enabled, true);
|
||||
expect(value.port, 47832);
|
||||
expect(value.token, initial.token);
|
||||
await expectLater(
|
||||
restored.read(mcpSettingsProvider.notifier).saveSettings(port: 0),
|
||||
throwsArgumentError,
|
||||
);
|
||||
repository.failWrites = true;
|
||||
await expectLater(
|
||||
restored.read(mcpSettingsProvider.notifier).saveSettings(enabled: false),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(restored.read(mcpSettingsProvider).requireValue, same(value));
|
||||
});
|
||||
|
||||
testWidgets('settings switch enables and disables MCP and validates ports', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
mcpSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryMcpSettingsRepository(),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penLight,
|
||||
home: const Scaffold(body: McpSettingsPanel()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byType(TextFormField), '0');
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('端口必须为 1–65535'), findsOneWidget);
|
||||
await tester.enterText(find.byType(TextFormField), '47831');
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('等待打开工程'), findsOneWidget);
|
||||
await tester.tap(find.byType(Switch));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('已停用'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/media_availability.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'detects missing originals and restoration independently of preview caches',
|
||||
() async {
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex-availability-',
|
||||
);
|
||||
addTearDown(() => directory.delete(recursive: true));
|
||||
final file = File('${directory.path}/source.mp4');
|
||||
expect(await checkMediaAvailability(file.uri), MediaAvailability.missing);
|
||||
await file.writeAsBytes([1, 2, 3]);
|
||||
// A readable file is available even when it is not a decodable video.
|
||||
expect(
|
||||
await checkMediaAvailability(file.uri),
|
||||
MediaAvailability.available,
|
||||
);
|
||||
await file.delete();
|
||||
expect(await checkMediaAvailability(file.uri), MediaAvailability.missing);
|
||||
await file.writeAsBytes([4]);
|
||||
expect(
|
||||
await checkMediaAvailability(file.uri),
|
||||
MediaAvailability.available,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'unsupported locations are unavailable rather than reported missing',
|
||||
() async {
|
||||
expect(
|
||||
await checkMediaAvailability(
|
||||
Uri.parse('https://example.com/video.mp4'),
|
||||
),
|
||||
MediaAvailability.inaccessible,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import 'support/creation_names.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/integrations/runtime/media_thumbnails.dart';
|
||||
import 'package:cutdex/integrations/runtime/media_waveforms.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test(
|
||||
'binding preserves selected tracks, explicit disabled tracks and images',
|
||||
() {
|
||||
final uris = {'asset': Uri.file('/movie.mov')};
|
||||
EditorMediaBinding? binding(String type, Map<String, Object?> data) =>
|
||||
EditorMediaBinding.resolve(
|
||||
PayloadDocument(
|
||||
id: 'payload',
|
||||
type: type,
|
||||
assetIds: ['asset'],
|
||||
data: data,
|
||||
),
|
||||
uris,
|
||||
);
|
||||
expect(
|
||||
binding('video', {
|
||||
'videoTrackIndex': 2,
|
||||
'audioTrackIndex': 1,
|
||||
})!.videoTrackIndex,
|
||||
2,
|
||||
);
|
||||
expect(
|
||||
binding('video', {
|
||||
'videoTrackIndex': 2,
|
||||
'audioTrackIndex': 1,
|
||||
})!.audioTrackIndex,
|
||||
1,
|
||||
);
|
||||
expect(
|
||||
binding('video', {'videoTrackIndex': null})!.videoTrackIndex,
|
||||
isNull,
|
||||
);
|
||||
expect(binding('audio', {'audioTrackIndex': 0})!.audioTrackIndex, 0);
|
||||
expect(binding('audio', {}), isNull);
|
||||
expect(binding('video', {}), isNull);
|
||||
expect(binding('image', {})!.media.isImage, isTrue);
|
||||
expect(binding('audio', {'audioTrackIndex': -1}), isNull);
|
||||
expect(binding('video', {'videoTrackIndex': 'invalid'}), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('managed covers use resolved paths and generation survives a project switch', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-bindings-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await workspace.open('${root.path}/one.cutdex', name: 'One');
|
||||
final project = workspace.project!;
|
||||
final file = File('${root.path}/source.wav');
|
||||
await file.writeAsBytes([1, 2, 3, 4]);
|
||||
final asset = await project.importFile(file);
|
||||
expect(Uri.parse(asset.location).hasScheme, isFalse);
|
||||
final resolved = await project.resolveAsset(asset);
|
||||
final calls = <String>[];
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect((call.arguments as Map)['media']['uri'], resolved.toString());
|
||||
calls.add(call.method);
|
||||
throw PlatformException(code: 'testSource');
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
Future<T> load<T>(
|
||||
AssetDocument asset,
|
||||
Future<T> Function(MediaReference) action,
|
||||
) => workspace.withAssetMedia(project.info.id, asset, action);
|
||||
await MediaThumbnails(loadMedia: load).load(asset);
|
||||
await MediaWaveforms(loadMedia: load).load(asset);
|
||||
expect(calls, ['thumbnail', 'waveform']);
|
||||
|
||||
final started = Completer<void>(), finish = Completer<void>();
|
||||
final operation = load(asset, (media) async {
|
||||
started.complete();
|
||||
await finish.future;
|
||||
return File.fromUri(media.uri).readAsBytes();
|
||||
});
|
||||
await started.future;
|
||||
await workspace.open('${root.path}/two.cutdex', name: 'Two');
|
||||
finish.complete();
|
||||
expect(await operation, [1, 2, 3, 4]);
|
||||
expect((await load(asset, (media) async => media)).uri, resolved);
|
||||
await workspace.close();
|
||||
await expectLater(load(asset, (media) async => media), throwsStateError);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/color_interpretation_properties.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex/workspace/media_color_interpretation.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
class _ColorPreview extends PreviewController {
|
||||
_ColorPreview(EditorTimelineSession timeline)
|
||||
: super(
|
||||
timeline: timeline,
|
||||
runtime: CutdexRuntime(),
|
||||
activeSequence: () => timeline.activeSequenceId,
|
||||
viewForSequence: timeline.view,
|
||||
);
|
||||
@override
|
||||
List<RenderColorSpace?>? videoColorSpaces(String assetId) => [null];
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('only reported unknown inputs receive the display assumption', () {
|
||||
for (final detected in [null, ...RenderColorSpace.values]) {
|
||||
expect(
|
||||
resolveMediaColor(
|
||||
detected: detected,
|
||||
override: null,
|
||||
metadataReported: true,
|
||||
),
|
||||
detected == null ? RenderColorSpace.rec709 : null,
|
||||
);
|
||||
expect(
|
||||
resolveMediaColor(
|
||||
detected: detected,
|
||||
override: RenderColorSpace.sRGB,
|
||||
metadataReported: true,
|
||||
),
|
||||
RenderColorSpace.sRGB,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
resolveMediaColor(
|
||||
detected: null,
|
||||
override: null,
|
||||
metadataReported: false,
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
for (final width in [240.0, 400.0]) {
|
||||
testWidgets(
|
||||
'color inspector at $width saves source interpretation and restores automatic',
|
||||
(tester) async {
|
||||
await tester.runAsync(() async {
|
||||
final f = await createPreviewFixture(Uri.file('/test/video.mov'));
|
||||
final preview = _ColorPreview(f.timeline);
|
||||
addTearDown(
|
||||
() => tester.runAsync(() async {
|
||||
await preview.close();
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
}),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorPreviewProvider(
|
||||
'project',
|
||||
'project',
|
||||
).overrideWith((_) async => preview),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: width,
|
||||
child: ColorInterpretationProperties(
|
||||
projectId: 'project',
|
||||
timelineId: 'project',
|
||||
session: f.timeline,
|
||||
assetId: 'media',
|
||||
trackIndex: 0,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('色彩空间未知,暂按 Rec.709 显示'), findsOneWidget);
|
||||
expect(
|
||||
f.timeline.settings.containsKey('mediaColorInterpretations'),
|
||||
isFalse,
|
||||
);
|
||||
await tester.tap(find.byKey(const Key('media-color-menu')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('线性 Rec.2020'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('手动指定:线性 Rec.2020'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
{
|
||||
await f.timeline.flush();
|
||||
final saved = await f.workspace.project!.loadTimeline('project');
|
||||
final reopened = EditorTimelineSession(
|
||||
document: saved,
|
||||
persistence: f.timeline.persistence,
|
||||
assetUris: f.timeline.assetUris,
|
||||
);
|
||||
expect(
|
||||
reopened.mediaColorInterpretation('media', 0),
|
||||
RenderColorSpace.linearRec2020,
|
||||
);
|
||||
expect(reopened.mediaColorInterpretation('media', 1), isNull);
|
||||
}
|
||||
await tester.tap(find.byKey(const Key('media-color-menu')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('自动'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('色彩空间未知,暂按 Rec.709 显示'), findsOneWidget);
|
||||
expect(f.timeline.mediaColorInterpretation('media', 0), isNull);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:cutdex/features/media/media_browser_feedback.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/workspace/external_media_import.dart';
|
||||
import 'package:cutdex/workspace/media_import_feedback.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'offstage import feedback waits for visibility and is consumed once',
|
||||
(tester) async {
|
||||
final feedback = MediaImportFeedbackController();
|
||||
addTearDown(feedback.dispose);
|
||||
var visible = false;
|
||||
late StateSetter changeVisibility;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: StatefulBuilder(
|
||||
builder: (context, setState) {
|
||||
changeVisibility = setState;
|
||||
return Offstage(
|
||||
offstage: !visible,
|
||||
child: TickerMode(
|
||||
enabled: visible,
|
||||
child: MediaImportFeedbackListener(
|
||||
feedback: feedback,
|
||||
child: const Text('Browser'),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
feedback.recordResult(
|
||||
const ExternalMediaSelection(selected: [], failed: true),
|
||||
);
|
||||
feedback.recordFailure();
|
||||
await tester.pumpAndSettle();
|
||||
expect(feedback.hasPending, isTrue);
|
||||
expect(find.byType(SnackBar), findsNothing);
|
||||
changeVisibility(() => visible = true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(feedback.hasPending, isFalse);
|
||||
expect(find.byType(SnackBar), findsOneWidget);
|
||||
final messenger = ScaffoldMessenger.of(
|
||||
tester.element(find.text('Browser')),
|
||||
);
|
||||
messenger.clearSnackBars();
|
||||
messenger.removeCurrentSnackBar();
|
||||
await tester.pumpAndSettle();
|
||||
changeVisibility(() => visible = false);
|
||||
await tester.pumpAndSettle();
|
||||
changeVisibility(() => visible = true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(SnackBar), findsNothing);
|
||||
feedback.recordFailure();
|
||||
await tester.pumpAndSettle();
|
||||
expect(feedback.hasPending, isFalse);
|
||||
expect(find.byType(SnackBar), findsOneWidget);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
import 'support/creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/integrations/platform/media_source_reader.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
late Directory root;
|
||||
late ProjectWorkspace workspace;
|
||||
late String projectId;
|
||||
late String path;
|
||||
late _ProviderReader reader;
|
||||
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('cutdex-media-test-');
|
||||
reader = _ProviderReader();
|
||||
workspace = ProjectWorkspace(
|
||||
creationNames: testCreationNames,
|
||||
mediaSourceReader: reader,
|
||||
);
|
||||
path = '${root.path}/Project.cutdex';
|
||||
await workspace.open(path, name: '媒体库');
|
||||
projectId = workspace.project!.info.id;
|
||||
});
|
||||
|
||||
test(
|
||||
'provider originals are managed, deduplicated and readable after reopen',
|
||||
() async {
|
||||
final source = ExternalMediaFile.content(
|
||||
uri: Uri.parse('content://provider/document/42'),
|
||||
name: '中文 空格 #.MP4',
|
||||
byteLength: 3,
|
||||
);
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
source,
|
||||
source,
|
||||
]);
|
||||
expect(result.added, 1);
|
||||
expect(result.duplicates, 1);
|
||||
expect(result.failures, isEmpty);
|
||||
expect(reader.opens, 1);
|
||||
expect(reader.closes, 1);
|
||||
final asset = result.assets.single;
|
||||
expect(asset.storage, AssetStorage.managed);
|
||||
expect(asset.name, source.displayName);
|
||||
expect(asset.metadata['kind'], 'video');
|
||||
expect(mediaSourceLocation(asset), source.sourceUri.toString());
|
||||
expect(
|
||||
await workspace.withAssetMedia(
|
||||
projectId,
|
||||
asset,
|
||||
(media) => File.fromUri(media.uri).readAsBytes(),
|
||||
),
|
||||
[1, 2, 3],
|
||||
);
|
||||
await workspace.close();
|
||||
workspace = ProjectWorkspace(
|
||||
creationNames: testCreationNames,
|
||||
mediaSourceReader: reader,
|
||||
);
|
||||
await workspace.open(path);
|
||||
final repeated = await workspace.importExternalMedia(projectId, [source]);
|
||||
expect(repeated.added, 0);
|
||||
expect(repeated.duplicates, 1);
|
||||
expect(repeated.assets.single.id, asset.id);
|
||||
expect(reader.opens, 1);
|
||||
expect(
|
||||
await workspace.withAssetMedia(
|
||||
projectId,
|
||||
repeated.assets.single,
|
||||
(media) => File.fromUri(media.uri).readAsBytes(),
|
||||
),
|
||||
[1, 2, 3],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'provider stream failure or size mismatch never registers a partial asset',
|
||||
() async {
|
||||
final source = ExternalMediaFile.content(
|
||||
uri: Uri.parse('content://provider/document/42'),
|
||||
name: 'a.wav',
|
||||
byteLength: 4,
|
||||
);
|
||||
var result = await workspace.importExternalMedia(projectId, [source]);
|
||||
expect(result.failures, hasLength(1));
|
||||
expect(result.assets, isEmpty);
|
||||
reader.fail = true;
|
||||
result = await workspace.importExternalMedia(projectId, [source]);
|
||||
expect(result.failures, hasLength(1));
|
||||
expect(result.assets, isEmpty);
|
||||
expect(reader.closes, 2);
|
||||
expect(await Directory('$path/media').exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'cancelling a provider read closes the stream without registering media',
|
||||
() async {
|
||||
var cancelled = false;
|
||||
reader.afterFirstChunk = () => cancelled = true;
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile.content(
|
||||
uri: Uri.parse('content://provider/document/42'),
|
||||
name: 'a.mp4',
|
||||
),
|
||||
], isCancelled: () => cancelled);
|
||||
expect(result.failures, hasLength(1));
|
||||
expect(result.assets, isEmpty);
|
||||
expect(reader.closes, 1);
|
||||
expect(await Directory('$path/media').exists(), isFalse);
|
||||
},
|
||||
);
|
||||
tearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
test('video, audio and image drops persist only references across reopen', () async {
|
||||
final files = <File>[];
|
||||
for (final name in ['中文 空格 #.MOV', 'sound.wav', 'photo.PNG']) {
|
||||
files.add(await File('${root.path}/$name').writeAsBytes([1, 2, 3]));
|
||||
}
|
||||
final before = await workspace.createTimeline('剪辑');
|
||||
final result = await workspace.importExternalMedia(
|
||||
projectId,
|
||||
files.map((file) => ExternalMediaFile(path: file.path)),
|
||||
);
|
||||
expect(result.added, 3);
|
||||
expect(result.failures, isEmpty);
|
||||
expect(
|
||||
result.assets.map((asset) => asset.metadata['kind']),
|
||||
unorderedEquals(['video', 'audio', 'image']),
|
||||
);
|
||||
for (final asset in result.assets) {
|
||||
expect(asset.storage, AssetStorage.external);
|
||||
expect(asset.byteLength, 3);
|
||||
expect(await File.fromUri(Uri.parse(asset.location)).readAsBytes(), [
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
]);
|
||||
expect(asset.contentHash, isNull);
|
||||
}
|
||||
final after = await workspace.project!.listTimelines();
|
||||
expect(
|
||||
after.map((timeline) => timeline.revision),
|
||||
before.map((timeline) => timeline.revision),
|
||||
);
|
||||
expect(await Directory('$path/media').exists(), isFalse);
|
||||
await workspace.close();
|
||||
final reopened = await ProjectFile.open(Directory(path));
|
||||
try {
|
||||
expect(
|
||||
(await reopened.listAssets()).map((a) => a.location),
|
||||
unorderedEquals(result.assets.map((a) => a.location)),
|
||||
);
|
||||
// Losing a source does not delete its reference or prevent project open.
|
||||
await files.first.delete();
|
||||
expect(await reopened.listAssets(), hasLength(3));
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('large sparse file is registered without copying its bytes', () async {
|
||||
final file = File('${root.path}/large.mp4');
|
||||
final handle = await file.open(mode: FileMode.write);
|
||||
await handle.truncate(4 * 1024 * 1024 * 1024);
|
||||
await handle.close();
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: file.path),
|
||||
]);
|
||||
expect(result.added, 1);
|
||||
expect(result.assets.single.byteLength, 4 * 1024 * 1024 * 1024);
|
||||
expect(await Directory('$path/media').exists(), isFalse);
|
||||
});
|
||||
|
||||
test(
|
||||
'FLV, RealMedia and TS drops persist video references with original names',
|
||||
() async {
|
||||
final files = <File>[];
|
||||
for (final name in [
|
||||
'中文 空格 [视频].flv',
|
||||
'中文 空格 [视频].RMVB',
|
||||
'legacy.rm',
|
||||
'transport.ts',
|
||||
'中文 空格 [视频].TS',
|
||||
]) {
|
||||
files.add(await File('${root.path}/$name').writeAsString('fixture'));
|
||||
}
|
||||
final result = await workspace.importExternalMedia(
|
||||
projectId,
|
||||
files.map((file) => ExternalMediaFile(path: file.path)),
|
||||
);
|
||||
expect(result.added, 5);
|
||||
expect(result.failures, isEmpty);
|
||||
expect(
|
||||
result.assets.every((asset) => asset.metadata['kind'] == 'video'),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
result.assets.map((asset) => asset.name),
|
||||
unorderedEquals([
|
||||
'中文 空格 [视频].flv',
|
||||
'中文 空格 [视频].RMVB',
|
||||
'legacy.rm',
|
||||
'transport.ts',
|
||||
'中文 空格 [视频].TS',
|
||||
]),
|
||||
);
|
||||
await workspace.close();
|
||||
workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
await workspace.open(path);
|
||||
expect(
|
||||
(await workspace.project!.listAssets()).map((asset) => asset.location),
|
||||
unorderedEquals(result.assets.map((asset) => asset.location)),
|
||||
);
|
||||
expect(await Directory('$path/media').exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'duplicates in a batch, queued drops and reopened projects reuse identity',
|
||||
() async {
|
||||
final file = await File('${root.path}/video.mp4')
|
||||
.writeAsString('fixture');
|
||||
final source = ExternalMediaFile(path: file.path);
|
||||
final results = await Future.wait([
|
||||
workspace.importExternalMedia(projectId, [source, source]),
|
||||
workspace.importExternalMedia(projectId, [source]),
|
||||
]);
|
||||
expect(results.first.added, 1);
|
||||
expect(results.first.duplicates, 1);
|
||||
expect(results.last.added, 0);
|
||||
expect(results.last.duplicates, 1);
|
||||
final id = results.first.assets.single.id;
|
||||
await workspace.close();
|
||||
workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
await workspace.open(path);
|
||||
expect(
|
||||
(await workspace.importExternalMedia(projectId, [
|
||||
source,
|
||||
])).assets.single.id,
|
||||
id,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'symlink aliases use the same external identity',
|
||||
() async {
|
||||
final file = await File('${root.path}/video.mp4')
|
||||
.writeAsString('fixture');
|
||||
final alias = await Link('${root.path}/alias.mp4').create(file.path);
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: file.path),
|
||||
ExternalMediaFile(path: alias.path),
|
||||
]);
|
||||
expect(result.added, 1);
|
||||
expect(result.duplicates, 1);
|
||||
},
|
||||
skip: Platform.isWindows
|
||||
? 'Symlink creation requires Windows privileges'
|
||||
: false,
|
||||
);
|
||||
|
||||
test('mixed drops report failures and still save valid files', () async {
|
||||
final file = await File('${root.path}/ok.jpg').writeAsString('fixture');
|
||||
final unsupported = await File('${root.path}/notes.txt')
|
||||
.writeAsString('not media');
|
||||
final directory = await Directory('${root.path}/folder.mp4').create();
|
||||
final result = await workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: '${root.path}/missing.wav'),
|
||||
ExternalMediaFile(path: directory.path),
|
||||
ExternalMediaFile(path: unsupported.path),
|
||||
const ExternalMediaFile(path: 'relative.mp4'),
|
||||
const ExternalMediaFile(path: 'https://example.com/video.mp4'),
|
||||
ExternalMediaFile(path: file.path),
|
||||
]);
|
||||
expect(result.added, 1);
|
||||
expect(result.failures, hasLength(5));
|
||||
expect(result.assets.single.name, 'ok.jpg');
|
||||
});
|
||||
|
||||
test('queued drop cannot register files into a different project', () async {
|
||||
final file = await File('${root.path}/video.mp4').writeAsString('fixture');
|
||||
final switchProject = workspace.open(
|
||||
'${root.path}/Other.cutdex',
|
||||
name: 'Other',
|
||||
);
|
||||
final drop = workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: file.path),
|
||||
]);
|
||||
final imported = await drop;
|
||||
expect(imported.added, 1);
|
||||
await switchProject;
|
||||
expect(await workspace.project!.listAssets(), isEmpty);
|
||||
await workspace.open(path);
|
||||
expect(
|
||||
(await workspace.project!.listAssets()).single.id,
|
||||
imported.assets.single.id,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
class _ProviderReader extends MediaSourceReader {
|
||||
int opens = 0;
|
||||
int closes = 0;
|
||||
bool fail = false;
|
||||
void Function()? afterFirstChunk;
|
||||
|
||||
@override
|
||||
Stream<List<int>> openRead(Uri uri) async* {
|
||||
opens++;
|
||||
try {
|
||||
yield [1, 2];
|
||||
afterFirstChunk?.call();
|
||||
if (fail) throw const FileSystemException('Provider read failed');
|
||||
yield [3];
|
||||
} finally {
|
||||
closes++;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,810 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/media/media_browser_page.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/features/media/media_panel.dart';
|
||||
import 'package:cutdex/features/media/media_asset_strip.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/media_availability.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex/integrations/platform/native_project_drop_region.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
setUp(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/file_drop/media-library'),
|
||||
(_) async => null,
|
||||
);
|
||||
});
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(
|
||||
const MethodChannel('cutdex_native/file_drop/media-library'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
testWidgets(
|
||||
'list and grid share a context menu targeting the clicked asset',
|
||||
(tester) async {
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_Projects.new),
|
||||
mediaAvailabilityProvider.overrideWith(
|
||||
(ref, key) async => MediaAvailability.available,
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await container.read(projectsProvider.future);
|
||||
final projects = container.read(projectsProvider.notifier) as _Projects;
|
||||
await projects.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/first.txt'),
|
||||
const ExternalMediaFile(path: '/second.txt'),
|
||||
]);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penLight,
|
||||
home: const Scaffold(body: MediaPanel(projectId: 'project')),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
for (final layout in ['列表布局', '宫格布局']) {
|
||||
await tester.tap(find.byTooltip(layout));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('first.txt'));
|
||||
await tester.tap(
|
||||
find.text('second.txt'),
|
||||
buttons: kSecondaryMouseButton,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('添加到时间线'), findsOneWidget);
|
||||
expect(
|
||||
tester
|
||||
.widget<MenuItemButton>(
|
||||
find.widgetWithText(MenuItemButton, '添加到时间线'),
|
||||
)
|
||||
.onPressed,
|
||||
isNull,
|
||||
);
|
||||
await tester.tap(find.text('重命名'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.widget<TextField>(find.byType(TextField)).controller!.text,
|
||||
'second.txt',
|
||||
);
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
Future<void> platformEvent(
|
||||
WidgetTester tester,
|
||||
String method,
|
||||
Object? args,
|
||||
) async {
|
||||
final done = Completer<void>();
|
||||
final eventArgs = {
|
||||
'phase': method,
|
||||
'session': 1,
|
||||
'x': 0.0,
|
||||
'y': 0.0,
|
||||
'files': method == 'exit'
|
||||
? <Object?>[]
|
||||
: method == 'enter'
|
||||
? <Object?>[
|
||||
{'path': '/originals/video.mp4'},
|
||||
]
|
||||
: [
|
||||
for (final f in args as List)
|
||||
if (f is String) {'path': f} else {'path': (f as Map)['path']},
|
||||
],
|
||||
};
|
||||
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
|
||||
'cutdex_native/file_drop/media-library',
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('event', eventArgs),
|
||||
),
|
||||
(_) => done.complete(),
|
||||
);
|
||||
await done.future;
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
Future<ProviderContainer> mount(
|
||||
WidgetTester tester, {
|
||||
MediaAvailability availability = MediaAvailability.available,
|
||||
bool touch = false,
|
||||
}) async {
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
projectsProvider.overrideWith(_Projects.new),
|
||||
mediaAvailabilityProvider.overrideWith(
|
||||
(ref, key) async => availability,
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: touch
|
||||
? const MediaBrowserPage(projectId: 'project')
|
||||
: const MediaPanel(projectId: 'project'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
return container;
|
||||
}
|
||||
|
||||
testWidgets('list uses a filmstrip with real duration above its name', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final times = <int>[];
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
|
||||
call,
|
||||
) async {
|
||||
if (call.method == 'probe') {
|
||||
return {
|
||||
'duration': {'numerator': '290', 'denominator': 1},
|
||||
'videoTrackCount': 1,
|
||||
'videoTrackIds': [1],
|
||||
'audioTrackCount': 0,
|
||||
'audioTrackIds': <int>[],
|
||||
'audioTracks': <Object?>[],
|
||||
'isProtected': false,
|
||||
};
|
||||
}
|
||||
if (call.method == 'thumbnail') {
|
||||
final args = call.arguments as Map;
|
||||
final time = args['time'] as Map;
|
||||
times.add(int.parse(time['numerator'].toString()));
|
||||
}
|
||||
throw PlatformException(code: 'no-preview');
|
||||
});
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
null,
|
||||
),
|
||||
);
|
||||
final container = await mount(tester);
|
||||
await (container.read(projectsProvider.notifier) as _Projects)
|
||||
.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/movie.mp4'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byTooltip('列表布局'));
|
||||
await tester.pumpAndSettle();
|
||||
final strip = tester.getRect(find.byType(MediaAssetStrip));
|
||||
final name = tester.getRect(find.text('movie.mp4'));
|
||||
final duration = tester.getRect(find.text('04:50'));
|
||||
expect(strip.height, 46);
|
||||
expect(name.top, greaterThanOrEqualTo(strip.bottom));
|
||||
expect(duration.right, lessThanOrEqualTo(strip.right));
|
||||
expect(duration.left, greaterThan(strip.center.dx));
|
||||
expect(duration.top, strip.top + 5);
|
||||
expect(times.any((time) => time > 0), isTrue);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'missing assets stay named and marked in both layouts without dragging',
|
||||
(tester) async {
|
||||
final container = await mount(
|
||||
tester,
|
||||
availability: MediaAvailability.missing,
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier) as _Projects;
|
||||
await projects.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/missing.mov'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
for (final layout in ['列表布局', '宫格布局']) {
|
||||
await tester.tap(find.byTooltip(layout));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('素材缺失'), findsOneWidget);
|
||||
expect(find.text('missing.mov'), findsOneWidget);
|
||||
final drag = tester.widget<Draggable>(
|
||||
find.byWidgetPredicate((widget) => widget is Draggable),
|
||||
);
|
||||
expect(drag.maxSimultaneousDrags, 0);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'category dropdown filters both layouts and restores all assets',
|
||||
(tester) async {
|
||||
final container = await mount(tester);
|
||||
final projects = container.read(projectsProvider.notifier) as _Projects;
|
||||
await projects.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/photo.png'),
|
||||
const ExternalMediaFile(path: '/movie.mp4'),
|
||||
const ExternalMediaFile(path: '/song.wav'),
|
||||
const ExternalMediaFile(path: '/notes.txt'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byKey(const Key('media-import-button')), findsOneWidget);
|
||||
expect(
|
||||
tester.getSize(find.byKey(const Key('media-panel-header'))).height,
|
||||
AppControlSize.panelToolbar,
|
||||
);
|
||||
expect(
|
||||
tester.getSize(find.byKey(const Key('media-import-button'))).height,
|
||||
AppControlSize.headerButton,
|
||||
);
|
||||
final header = tester.getRect(
|
||||
find.byKey(const Key('media-panel-header')),
|
||||
);
|
||||
expect(
|
||||
tester.getRect(find.byKey(const Key('media-panel-body'))).top,
|
||||
header.bottom,
|
||||
);
|
||||
final importButton = tester.getRect(
|
||||
find.byKey(const Key('media-import-button')),
|
||||
);
|
||||
final layoutButton = tester.getRect(
|
||||
find.byKey(const Key('media-layout-toggle')),
|
||||
);
|
||||
final filter = find.byWidgetPredicate(
|
||||
(widget) => widget is AppSelect && widget.label == '素材分类',
|
||||
);
|
||||
final filterButton = tester.getRect(
|
||||
find.descendant(of: filter, matching: find.byType(TextButton)),
|
||||
);
|
||||
expect(importButton.left - header.left, AppSpacing.gap);
|
||||
expect(importButton.top - header.top, AppSpacing.gap);
|
||||
expect(header.right - layoutButton.right, AppSpacing.gap);
|
||||
expect(layoutButton.left - filterButton.right, AppSpacing.tiny);
|
||||
expect(tester.getSize(filter).height, AppControlSize.headerButton);
|
||||
final importStyle = tester
|
||||
.widget<TextButton>(find.byKey(const Key('media-import-button')))
|
||||
.style!
|
||||
.textStyle!
|
||||
.resolve({})!;
|
||||
final filterStyle = tester.widget<AppSelect<Object?>>(filter).textStyle!;
|
||||
expect(importStyle.fontSize, 13);
|
||||
expect(importStyle.height, 18 / 13);
|
||||
expect(filterStyle.fontSize, importStyle.fontSize);
|
||||
expect(filterStyle.height, importStyle.height);
|
||||
expect(find.text('4 个素材'), findsNothing);
|
||||
for (final entry in {
|
||||
'图片': 'photo.png',
|
||||
'视频': 'movie.mp4',
|
||||
'音频': 'song.wav',
|
||||
}.entries) {
|
||||
await tester.tap(
|
||||
find.descendant(
|
||||
of: find.byWidgetPredicate(
|
||||
(widget) => widget is AppSelect && widget.label == '素材分类',
|
||||
),
|
||||
matching: find.byType(TextButton),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.widgetWithText(MenuItemButton, entry.key));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('1 个素材'), findsNothing);
|
||||
expect(find.text(entry.value), findsOneWidget);
|
||||
expect(find.text('notes.txt'), findsNothing);
|
||||
}
|
||||
await tester.tap(find.byTooltip('列表布局'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('song.wav'), findsOneWidget);
|
||||
expect(find.text('movie.mp4'), findsNothing);
|
||||
await tester.tap(
|
||||
find.descendant(
|
||||
of: find.byWidgetPredicate(
|
||||
(widget) => widget is AppSelect && widget.label == '素材分类',
|
||||
),
|
||||
matching: find.byType(TextButton),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.widgetWithText(MenuItemButton, '全部'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('4 个素材'), findsNothing);
|
||||
expect(find.text('notes.txt'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'media layouts resize columns and retain selection and dragging',
|
||||
(tester) async {
|
||||
await tester.binding.setSurfaceSize(const Size(280, 600));
|
||||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||||
final container = await mount(tester);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
await controller.importExternalMedia('project', [
|
||||
for (var i = 0; i < 8; i++)
|
||||
ExternalMediaFile(path: '/originals/very-long-asset-name-$i.png'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
int columns() =>
|
||||
(tester.widget<GridView>(find.byType(GridView)).gridDelegate
|
||||
as SliverGridDelegateWithFixedCrossAxisCount)
|
||||
.crossAxisCount;
|
||||
expect(columns(), 2);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.byType(GridView),
|
||||
matching: find.byType(ShaderMask),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.byKey(const Key('media-panel-header')),
|
||||
matching: find.byType(ShaderMask),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
final first = find.text('very-long-asset-name-0.png');
|
||||
await tester.tap(first);
|
||||
await tester.tap(find.byTooltip('列表布局'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(GridView), findsNothing);
|
||||
expect(find.byType(ListView), findsOneWidget);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.byType(ListView),
|
||||
matching: find.byType(ShaderMask),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: first,
|
||||
matching: find.byWidgetPredicate(
|
||||
(w) => w is Semantics && w.properties.selected == true,
|
||||
),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: first,
|
||||
matching: find.byWidgetPredicate((w) => w is Draggable),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.tap(find.byTooltip('宫格布局'));
|
||||
await tester.pumpAndSettle();
|
||||
for (final (width, count) in [
|
||||
(180.0, 1),
|
||||
(280.0, 2),
|
||||
(520.0, 3),
|
||||
(560.0, 4),
|
||||
(900.0, 6),
|
||||
]) {
|
||||
await tester.binding.setSurfaceSize(Size(width, 600));
|
||||
await tester.pumpAndSettle();
|
||||
expect(columns(), count);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: first,
|
||||
matching: find.byWidgetPredicate(
|
||||
(w) => w is Semantics && w.properties.selected == true,
|
||||
),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('native file event imports real paths without a success prompt', (
|
||||
tester,
|
||||
) async {
|
||||
final container = await mount(tester);
|
||||
final target = tester.getCenter(find.byType(NativeProjectDropRegion));
|
||||
await platformEvent(tester, 'enter', [target.dx, target.dy]);
|
||||
expect(find.byKey(const Key('media-drop-highlight')), findsOneWidget);
|
||||
expect(
|
||||
tester.widget(find.byKey(const Key('media-drop-highlight'))),
|
||||
isA<DropToAddOverlay>(),
|
||||
);
|
||||
expect(find.text('松手即可添加'), findsOneWidget);
|
||||
await platformEvent(tester, 'drop', [
|
||||
{'path': '/originals/video.mp4'},
|
||||
{'path': '/originals/audio.wav'},
|
||||
{'path': '/originals/image.png'},
|
||||
{'path': '/originals/中文 视频.RMVB'},
|
||||
{'path': '/originals/中文 视频.flv'},
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
expect(controller.received.map((f) => f.localPath!), [
|
||||
'/originals/video.mp4',
|
||||
'/originals/audio.wav',
|
||||
'/originals/image.png',
|
||||
'/originals/中文 视频.RMVB',
|
||||
'/originals/中文 视频.flv',
|
||||
]);
|
||||
expect(find.text('video.mp4'), findsOneWidget);
|
||||
expect(find.text('中文 视频.RMVB'), findsOneWidget);
|
||||
expect(find.text('中文 视频.flv'), findsOneWidget);
|
||||
expect(find.byType(SnackBar), findsNothing);
|
||||
expect(find.byKey(const Key('media-drop-highlight')), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets(
|
||||
'duplicate native drop selects the existing asset without a prompt',
|
||||
(tester) async {
|
||||
final container = await mount(tester);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
await controller.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/originals/first.mp4'),
|
||||
const ExternalMediaFile(path: '/originals/second.wav'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('second.wav'));
|
||||
await platformEvent(tester, 'enter', [0.0, 0.0]);
|
||||
await platformEvent(tester, 'drop', ['/originals/first.mp4']);
|
||||
await tester.pumpAndSettle();
|
||||
expect(controller.received.map((file) => file.localPath!), [
|
||||
'/originals/first.mp4',
|
||||
'/originals/second.wav',
|
||||
]);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.assets,
|
||||
hasLength(2),
|
||||
);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.text('first.mp4'),
|
||||
matching: find.byWidgetPredicate(
|
||||
(w) => w is Semantics && w.properties.selected == true,
|
||||
),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.byType(SnackBar), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
|
||||
);
|
||||
|
||||
testWidgets('native drop without an entered session is ignored', (
|
||||
tester,
|
||||
) async {
|
||||
final container = await mount(tester);
|
||||
await platformEvent(tester, 'drop', ['/originals/video.mp4']);
|
||||
await tester.pumpAndSettle();
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
expect(controller.received, isEmpty);
|
||||
expect(find.byType(SnackBar), findsNothing);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.windows));
|
||||
|
||||
testWidgets('busy project ignores drops and clears active hover', (
|
||||
tester,
|
||||
) async {
|
||||
final container = await mount(tester);
|
||||
final target = tester.getCenter(find.byType(NativeProjectDropRegion));
|
||||
await platformEvent(tester, 'enter', [target.dx, target.dy]);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
controller.setBusy(true);
|
||||
await tester.pump();
|
||||
expect(find.byKey(const Key('media-drop-highlight')), findsNothing);
|
||||
await platformEvent(tester, 'drop', ['/originals/video.mp4']);
|
||||
expect(controller.received, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
|
||||
|
||||
testWidgets(
|
||||
'audio assets display a cached full-source single-sided waveform',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
var requests = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'waveform');
|
||||
requests++;
|
||||
return {
|
||||
'sampleRate': 4.0,
|
||||
'sourceStartSeconds': 2.0,
|
||||
'frameCount': 4,
|
||||
'trackId': 1,
|
||||
'channelCount': 2,
|
||||
'levels': [
|
||||
{
|
||||
'samplesPerBucket': 2,
|
||||
'channels': [
|
||||
[-0.25, 0.0, 0.1, -0.75, 0.0, 0.4],
|
||||
[0.0, 0.25, 0.1, 0.0, 0.75, 0.4],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final container = await mount(tester);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
await controller.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/originals/song.wav'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
final finder = find.byKey(
|
||||
const ValueKey('audio-waveform-/originals/song.wav'),
|
||||
);
|
||||
expect(finder, findsOneWidget);
|
||||
expect(find.text('song.wav'), findsOneWidget);
|
||||
final painter = tester.widget<CustomPaint>(finder).painter!;
|
||||
final recorder = ui.PictureRecorder();
|
||||
painter.paint(Canvas(recorder), const Size(100, 40));
|
||||
final picture = recorder.endRecording();
|
||||
final alpha = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(100, 40);
|
||||
try {
|
||||
final data = (await image.toByteData())!;
|
||||
return [
|
||||
for (final (x, y) in [(11, 35), (11, 15), (71, 15), (71, 5)])
|
||||
data.getUint8((y * 100 + x) * 4 + 3),
|
||||
];
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
expect(alpha, [255, 0, 255, 0]);
|
||||
final pixelRecorder = ui.PictureRecorder();
|
||||
final pixelCanvas = Canvas(pixelRecorder)..scale(2);
|
||||
painter.paint(pixelCanvas, const Size(101, 40));
|
||||
final pixelPicture = pixelRecorder.endRecording();
|
||||
final barAlphas = await tester.runAsync(() async {
|
||||
final image = await pixelPicture.toImage(202, 80);
|
||||
try {
|
||||
final data = (await image.toByteData())!;
|
||||
return {
|
||||
for (var x = 0; x < 202; x++)
|
||||
if (data.getUint8((78 * 202 + x) * 4 + 3) > 0)
|
||||
data.getUint8((78 * 202 + x) * 4 + 3),
|
||||
};
|
||||
} finally {
|
||||
image.dispose();
|
||||
pixelPicture.dispose();
|
||||
}
|
||||
});
|
||||
expect(barAlphas, {255});
|
||||
controller.setBusy(true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, 1);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'audio cover failures retain a stable fallback without retry loops',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
var requests = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
requests++;
|
||||
throw PlatformException(code: 'unsupported');
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final container = await mount(tester);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
await controller.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/originals/bad.wav'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byIcon(Icons.audio_file_outlined), findsOneWidget);
|
||||
final before = tester.getSize(
|
||||
find.byKey(const ValueKey('audio-cover-/originals/bad.wav')),
|
||||
);
|
||||
controller.setBusy(true);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.getSize(
|
||||
find.byKey(const ValueKey('audio-cover-/originals/bad.wav')),
|
||||
),
|
||||
before,
|
||||
);
|
||||
expect(requests, 2);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('touch can open media actions without a mouse', (tester) async {
|
||||
final container = await mount(tester, touch: true);
|
||||
final projects = container.read(projectsProvider.notifier) as _Projects;
|
||||
await projects.importExternalMedia('project', [
|
||||
const ExternalMediaFile(path: '/originals/notes.txt'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.longPress(find.text('notes.txt'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('重命名'), findsOneWidget);
|
||||
expect(find.widgetWithText(MenuItemButton, '添加到时间线'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('mobile file selection imports without native desktop drop', (
|
||||
tester,
|
||||
) async {
|
||||
final channel = const MethodChannel('filegate');
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
(_) async => [
|
||||
{'path': '/originals/phone.mp4', 'name': 'phone.mp4', 'kind': 'file'},
|
||||
],
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
channel,
|
||||
null,
|
||||
),
|
||||
);
|
||||
final container = await mount(tester);
|
||||
await tester.tap(find.byKey(const Key('media-import-button')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
(container.read(
|
||||
projectsProvider.notifier,
|
||||
) as _Projects).received.single.localPath,
|
||||
'/originals/phone.mp4',
|
||||
);
|
||||
expect(find.byType(NativeProjectDropRegion), findsNothing);
|
||||
expect(find.text('phone.mp4'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
|
||||
|
||||
testWidgets('mobile shows assets without a desktop drop target', (
|
||||
tester,
|
||||
) async {
|
||||
await mount(tester);
|
||||
expect(find.byType(NativeProjectDropRegion), findsNothing);
|
||||
expect(find.text('暂无素材'), findsOneWidget);
|
||||
}, variant: TargetPlatformVariant.only(TargetPlatform.android));
|
||||
|
||||
testWidgets('imported still images request and display native covers', (
|
||||
tester,
|
||||
) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.green, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(12, 16);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final requested = <String>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
expect(call.method, 'thumbnail');
|
||||
final args = call.arguments as Map;
|
||||
final media = args['media'] as Map;
|
||||
expect(media['isImage'], isTrue);
|
||||
requested.add(media['uri'] as String);
|
||||
return {
|
||||
'requestedTime': args['time'],
|
||||
'actualTime': args['time'],
|
||||
'width': 12,
|
||||
'height': 16,
|
||||
'format': args['format'],
|
||||
'data': bytes,
|
||||
};
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final container = await mount(tester);
|
||||
final controller = container.read(projectsProvider.notifier) as _Projects;
|
||||
await controller.importExternalMedia('project', [
|
||||
for (final ext in ['heic', 'png', 'jpg'])
|
||||
ExternalMediaFile(path: '/originals/photo.$ext'),
|
||||
]);
|
||||
await tester.pumpAndSettle();
|
||||
expect(requested, hasLength(3));
|
||||
expect(find.byType(Image), findsNWidgets(3));
|
||||
for (final ext in ['heic', 'png', 'jpg']) {
|
||||
expect(find.text('photo.$ext'), findsOneWidget);
|
||||
}
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
|
||||
class _Projects extends Projects {
|
||||
@override
|
||||
Future<T> withAssetMedia<T>(
|
||||
String? projectId,
|
||||
AssetDocument asset,
|
||||
Future<T> Function(MediaReference media) action,
|
||||
) => action(
|
||||
MediaReference(
|
||||
id: asset.id,
|
||||
uri: Uri.parse(asset.location),
|
||||
isImage: asset.metadata['kind'] == 'image',
|
||||
),
|
||||
);
|
||||
@visibleForTesting
|
||||
List<ExternalMediaFile> received = [];
|
||||
@override
|
||||
Future<ProjectState> build() async => const ProjectState(
|
||||
activeProject: RecentProject(
|
||||
id: 'project',
|
||||
name: 'Project',
|
||||
path: '/Project.cutdex',
|
||||
),
|
||||
);
|
||||
|
||||
void setBusy(bool busy) {
|
||||
state = AsyncData(state.requireValue.copyWith(projectBusy: busy));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MediaImportResult?> importExternalMedia(
|
||||
String projectId,
|
||||
List<ExternalMediaFile> files, {
|
||||
bool Function()? isCancelled,
|
||||
}) async {
|
||||
received = files;
|
||||
final previous = state.requireValue.assets;
|
||||
final previousIds = {for (final asset in previous) asset.id};
|
||||
final assets = [
|
||||
...previous,
|
||||
for (final file in files)
|
||||
if (!previousIds.contains(file.localPath!))
|
||||
AssetDocument(
|
||||
id: file.localPath!,
|
||||
name: file.localPath!.split('/').last,
|
||||
storage: AssetStorage.external,
|
||||
location: Uri.file(file.localPath!).toString(),
|
||||
metadata: {'kind': mediaKindForPath(file.localPath!)},
|
||||
),
|
||||
];
|
||||
state = AsyncData(state.requireValue.copyWith(assets: assets));
|
||||
return MediaImportResult(
|
||||
assets: assets,
|
||||
added: assets.length - previous.length,
|
||||
duplicates: files
|
||||
.where((file) => previousIds.contains(file.localPath!))
|
||||
.length,
|
||||
failures: [],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex/features/projects/widgets/name_dialog.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('rename chat uses the same dialog and compact input', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: EditorTheme.penDark,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: Builder(
|
||||
builder: (context) => TextButton(
|
||||
onPressed: () => askName(
|
||||
context,
|
||||
title: '重命名聊天',
|
||||
description: '保持简短且易于识别',
|
||||
label: '名称',
|
||||
initialValue: '实现图片页面并添加跳转',
|
||||
submitLabel: '保存',
|
||||
),
|
||||
child: const Text('Open'),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('Open'));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final frame = tester.getRect(find.byKey(const Key('app-dialog-frame')));
|
||||
final field = tester.getRect(find.byType(TextFormField));
|
||||
final save = tester.getRect(find.widgetWithText(FilledButton, '保存'));
|
||||
expect(frame.width, 420);
|
||||
expect(find.text('重命名聊天'), findsOneWidget);
|
||||
expect(find.text('保持简短且易于识别'), findsOneWidget);
|
||||
expect(field.left - frame.left, AppSpacing.large);
|
||||
expect(frame.right - field.right, AppSpacing.large);
|
||||
expect(field.height, 36);
|
||||
expect(save.top - field.bottom, AppSpacing.compact);
|
||||
expect(
|
||||
tester
|
||||
.widget<EditableText>(
|
||||
find.descendant(
|
||||
of: find.byType(TextFormField),
|
||||
matching: find.byType(EditableText),
|
||||
),
|
||||
)
|
||||
.style
|
||||
.fontSize,
|
||||
14,
|
||||
);
|
||||
expect(
|
||||
(Theme.of(tester.element(find.byType(TextFormField)))
|
||||
.inputDecorationTheme
|
||||
.focusedBorder!
|
||||
as OutlineInputBorder)
|
||||
.borderSide
|
||||
.color,
|
||||
const Color(0xFF6084AF),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
import 'package:cutdex/integrations/platform/native_project_drop_region.dart';
|
||||
import 'package:cutdex/integrations/platform/native_file_drop_policy.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const manager = MethodChannel('cutdex_native/file_drop');
|
||||
setUp(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(manager, (_) async => null);
|
||||
});
|
||||
tearDown(() {
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(manager, null);
|
||||
});
|
||||
for (final name in [
|
||||
'cutdex_native/file_drop/media-library',
|
||||
'cutdex_native/file_drop/attachments',
|
||||
]) {
|
||||
testWidgets('$name receives events after replacement', (tester) async {
|
||||
final channel = MethodChannel(name);
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => null);
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
var entered = 0;
|
||||
Widget target(String key) => MaterialApp(
|
||||
home: NativeProjectDropRegion(
|
||||
key: ValueKey(key),
|
||||
regionId: name.split('/').last,
|
||||
policy: name == 'cutdex_native/file_drop/attachments'
|
||||
? NativeFileDropPolicy.attachments
|
||||
: NativeFileDropPolicy.mediaLibrary,
|
||||
enabled: true,
|
||||
onEnter: (_) => entered++,
|
||||
onExit: () {},
|
||||
onDrop: (_) async {},
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(target('old'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(target('new'));
|
||||
await tester.pumpAndSettle();
|
||||
await messenger.handlePlatformMessage(
|
||||
name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('event', {
|
||||
'phase': 'enter',
|
||||
'session': 1,
|
||||
'files': [
|
||||
{'path': '/sample.mp4'},
|
||||
],
|
||||
}),
|
||||
),
|
||||
(_) {},
|
||||
);
|
||||
await tester.pump();
|
||||
expect(entered, 1);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
}
|
||||
testWidgets('policy changes at fixed bounds update native acceptance', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel('cutdex_native/file_drop/media-library');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
Widget target(NativeFileDropPolicy policy) => MaterialApp(
|
||||
home: NativeProjectDropRegion(
|
||||
policy: policy,
|
||||
enabled: true,
|
||||
onEnter: (_) {},
|
||||
onExit: () {},
|
||||
onDrop: (_) async {},
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.mediaLibrary));
|
||||
await tester.pumpAndSettle();
|
||||
final library = calls.last.arguments as Map;
|
||||
// The importer handles failures per file, preserving valid mixed batches.
|
||||
expect(library['allowedExtensions'], isNull);
|
||||
calls.clear();
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.timeline));
|
||||
await tester.pumpAndSettle();
|
||||
final timeline = calls.single.arguments as Map;
|
||||
expect(timeline['width'], library['width']);
|
||||
expect(timeline['allowedExtensions'], contains('wav'));
|
||||
expect(timeline['allowedExtensions'], isNot(contains('png')));
|
||||
expect(timeline['maximumFileCount'], 1);
|
||||
calls.clear();
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.attachments));
|
||||
await tester.pumpAndSettle();
|
||||
final attachments = calls.single.arguments as Map;
|
||||
expect(attachments['allowedExtensions'], isNull);
|
||||
expect(attachments['maximumFileCount'], isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
testWidgets(
|
||||
'timeline rejects images and batches while attachments accept documents',
|
||||
(tester) async {
|
||||
const name = 'cutdex_native/file_drop/media-library';
|
||||
const channel = MethodChannel(name);
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final released = <int>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'release') {
|
||||
released.add((call.arguments as Map)['session'] as int);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
var entered = 0, dropped = 0, exited = 0;
|
||||
Widget target(NativeFileDropPolicy policy) => MaterialApp(
|
||||
home: NativeProjectDropRegion(
|
||||
policy: policy,
|
||||
enabled: true,
|
||||
onEnter: (_) => entered++,
|
||||
onExit: () => exited++,
|
||||
onDrop: (_) async {
|
||||
dropped++;
|
||||
},
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
);
|
||||
Future<void> event(String phase, int id, List<String> paths) async {
|
||||
await messenger.handlePlatformMessage(
|
||||
name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
MethodCall('event', {
|
||||
'phase': phase,
|
||||
'session': id,
|
||||
'files': [
|
||||
for (final path in paths) {'path': path},
|
||||
],
|
||||
}),
|
||||
),
|
||||
(_) {},
|
||||
);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.timeline));
|
||||
await tester.pumpAndSettle();
|
||||
await event('enter', 1, ['/image.png']);
|
||||
await event('enter', 2, ['/a.wav', '/b.mov']);
|
||||
expect(entered, 0);
|
||||
expect(released, [1, 2]);
|
||||
await event('enter', 3, ['/a.WAV']);
|
||||
await event('drop', 3, ['/a.WAV']);
|
||||
expect(entered, 1);
|
||||
expect(dropped, 1);
|
||||
// A changed drop payload must not commit now-rejected paths.
|
||||
await event('enter', 4, ['/a.wav']);
|
||||
await event('drop', 4, ['/image.png']);
|
||||
expect(dropped, 1);
|
||||
expect(exited, 1);
|
||||
expect(released, [1, 2, 3, 4]);
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.attachments));
|
||||
await tester.pumpAndSettle();
|
||||
await event('enter', 5, ['/notes.pdf', '/README']);
|
||||
await event('drop', 5, ['/notes.pdf', '/README']);
|
||||
expect(entered, 3);
|
||||
expect(dropped, 2);
|
||||
expect(released, [1, 2, 3, 4, 5]);
|
||||
await tester.pumpWidget(target(NativeFileDropPolicy.timeline));
|
||||
await tester.pumpAndSettle();
|
||||
await event('enter', 6, ['/素材/transport stream.TS']);
|
||||
await event('drop', 6, ['/素材/transport stream.TS']);
|
||||
expect(entered, 4);
|
||||
expect(dropped, 3);
|
||||
expect(released, [1, 2, 3, 4, 5, 6]);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
},
|
||||
);
|
||||
testWidgets('disabled drop region activates without a geometry change', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel('cutdex_native/file_drop/media-library');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final enabled = ValueNotifier(false);
|
||||
addTearDown(enabled.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: ValueListenableBuilder<bool>(
|
||||
valueListenable: enabled,
|
||||
child: const SizedBox.expand(),
|
||||
builder: (_, value, child) => NativeProjectDropRegion(
|
||||
enabled: value,
|
||||
onEnter: (_) {},
|
||||
onExit: () {},
|
||||
onDrop: (_) async {},
|
||||
child: child!,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
calls.clear();
|
||||
enabled.value = true;
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
calls.where((c) => c.method == 'setRegion' && c.arguments != null),
|
||||
isNotEmpty,
|
||||
);
|
||||
calls.clear();
|
||||
enabled.value = false;
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls.last.arguments, isNull);
|
||||
calls.clear();
|
||||
enabled.value = true;
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls.single.arguments, isNotNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
expect(calls.last.arguments, isNull);
|
||||
});
|
||||
testWidgets('TickerMode restores the drop region without changing layout', (
|
||||
tester,
|
||||
) async {
|
||||
const channel = MethodChannel('cutdex_native/file_drop/media-library');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
final active = ValueNotifier(false);
|
||||
addTearDown(active.dispose);
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: ValueListenableBuilder<bool>(
|
||||
valueListenable: active,
|
||||
child: NativeProjectDropRegion(
|
||||
enabled: true,
|
||||
onEnter: (_) {},
|
||||
onExit: () {},
|
||||
onDrop: (_) async {},
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
builder: (_, value, child) =>
|
||||
TickerMode(enabled: value, child: child!),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
for (final value in [true, false, true]) {
|
||||
calls.clear();
|
||||
active.value = value;
|
||||
await tester.pumpAndSettle();
|
||||
final region = calls
|
||||
.lastWhere((call) => call.method == 'setRegion')
|
||||
.arguments;
|
||||
expect(region, value ? isNotNull : isNull);
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/picture_properties.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'compact keyframe inspector authors, seeks, interpolates and clears',
|
||||
(tester) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(
|
||||
Uri.file('/test/video.mov'),
|
||||
clipDuration: RationalTime.seconds(5),
|
||||
),
|
||||
))!;
|
||||
final view = f.timeline.view(SequenceId('one'));
|
||||
final project = f.workspace.project!.info.id;
|
||||
ClipAnimation current() {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return ClipAnimation.at(
|
||||
q,
|
||||
q.elementById(ElementId('clip'))!,
|
||||
view.playheadTick,
|
||||
TimelineClock.ticksPerSecond ~/ 30,
|
||||
);
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorPreviewProvider(project, 'project').overrideWith(
|
||||
(ref) async => throw StateError('No native preview'),
|
||||
),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: Align(
|
||||
alignment: Alignment.topLeft,
|
||||
child: SizedBox(
|
||||
width: 225,
|
||||
child: SingleChildScrollView(
|
||||
child: PictureProperties(
|
||||
projectId: project,
|
||||
timelineId: 'project',
|
||||
session: f.timeline,
|
||||
sequence: SequenceId('one'),
|
||||
clip: current().record,
|
||||
animationView: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
Future<void> settleEdit() async {
|
||||
await tester.pump();
|
||||
await tester.runAsync(f.timeline.flush);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
|
||||
Future<void> tap(String key) async {
|
||||
await tester.ensureVisible(find.byKey(ValueKey(key)));
|
||||
await tester.tap(find.byKey(ValueKey(key)));
|
||||
await settleEdit();
|
||||
}
|
||||
|
||||
Finder input(String key) => find.descendant(
|
||||
of: find.byKey(ValueKey(key)),
|
||||
matching: find.byType(TextField),
|
||||
);
|
||||
await tap('picture-key-position');
|
||||
expect(current().keyed(TransformChannel.position), isTrue);
|
||||
view.seekTo(2 * TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.enterText(input('picture-x'), '216');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await settleEdit();
|
||||
expect(current().value.x, .2);
|
||||
expect(current().keyTimes(TransformChannel.position).length, 2);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.widget<TextField>(input('picture-x')).controller!.text,
|
||||
'108',
|
||||
);
|
||||
await tap('picture-key-previous-position');
|
||||
expect(view.playheadTick, 0);
|
||||
await tap('picture-key-menu-position');
|
||||
await tester.tap(find.widgetWithText(MenuItemButton, '保持'));
|
||||
await settleEdit();
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
expect(current().value.x, 0);
|
||||
await tap('picture-key-next-position');
|
||||
expect(view.playheadTick, 2 * TimelineClock.ticksPerSecond);
|
||||
await tap('picture-key-position');
|
||||
expect(current().keyTimes(TransformChannel.position), [0]);
|
||||
await tap('picture-key-marker-position-0');
|
||||
expect(view.playheadTick, 0);
|
||||
await tap('picture-key-position');
|
||||
expect(current().animated(TransformChannel.position), isFalse);
|
||||
await tap('picture-key-scale');
|
||||
await tap('picture-lock');
|
||||
view.seekTo(2 * TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.enterText(input('picture-scale-y'), '200');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await settleEdit();
|
||||
expect(current().value.scale, 1);
|
||||
expect(current().value.scaleY, 2);
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.widget<TextField>(input('picture-scale-y')).controller!.text,
|
||||
'150',
|
||||
);
|
||||
await tap('picture-key-menu-scale');
|
||||
await tester.tap(find.text('移除全部关键帧'));
|
||||
await settleEdit();
|
||||
expect(current().animated(TransformChannel.scale), isFalse);
|
||||
expect(current().value.scaleY, 1.5);
|
||||
// Unsubmitted text cannot leak into a different playhead position.
|
||||
await tester.enterText(input('picture-x'), '999');
|
||||
view.seekTo(3 * TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await settleEdit();
|
||||
expect(current().value.x, 0);
|
||||
await tester.enterText(input('picture-rotation'), '25');
|
||||
await tap('picture-key-rotation');
|
||||
expect(current().value.rotation, 25);
|
||||
expect(current().keyed(TransformChannel.rotation), isTrue);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,295 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/preview/preview_fullscreen.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'disposal waits for native fullscreen entry before restoring the window',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_native/fullscreen');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final entered = Completer<void>();
|
||||
final requests = <bool>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
final entering = call.arguments as bool;
|
||||
requests.add(entering);
|
||||
if (entering) await entered.future;
|
||||
if (!entering && !entered.isCompleted) {
|
||||
throw PlatformException(code: 'busy');
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
await tester.pumpWidget(
|
||||
const MaterialApp(
|
||||
home: Scaffold(body: PreviewFullscreenHost(child: _Toggle('enter'))),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('enter'));
|
||||
await tester.pump();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pump();
|
||||
expect(requests, [true]);
|
||||
entered.complete();
|
||||
await tester.pump();
|
||||
expect(requests, [true, false]);
|
||||
},
|
||||
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'native fullscreen exit restores the panel and disposal restores the window',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_native/fullscreen');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final requests = <bool>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
requests.add(call.arguments as bool);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: 320,
|
||||
height: 200,
|
||||
child: PreviewFullscreenHost(
|
||||
child: _Preview(onInit: () {}, onDispose: () {}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, [true]);
|
||||
messenger.handlePlatformMessage(
|
||||
channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('exited'),
|
||||
),
|
||||
(_) {},
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getSize(find.byType(_Preview)), const Size(320, 200));
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, [true, true, false]);
|
||||
},
|
||||
variant: const TargetPlatformVariant({TargetPlatform.macOS}),
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'fullscreen reparents the same preview and Escape restores its size',
|
||||
(tester) async {
|
||||
var initialized = 0;
|
||||
var disposed = 0;
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: Center(
|
||||
child: SizedBox(
|
||||
width: 320,
|
||||
height: 200,
|
||||
child: PreviewFullscreenHost(
|
||||
child: _Preview(
|
||||
onInit: () => initialized++,
|
||||
onDispose: () => disposed++,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final preview = find.byType(_Preview);
|
||||
final initialState = tester.state(preview);
|
||||
expect(tester.getSize(preview), const Size(320, 200));
|
||||
expect(Theme.of(tester.element(preview)).brightness, Brightness.light);
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getSize(preview), const Size(800, 600));
|
||||
expect(tester.state(preview), same(initialState));
|
||||
final fullscreenTheme = Theme.of(tester.element(preview));
|
||||
expect(fullscreenTheme.brightness, Brightness.dark);
|
||||
expect(fullscreenTheme.colorScheme.surface, Colors.black);
|
||||
expect(
|
||||
fullscreenTheme.extension<AppSurfaces>()!.previewBackground,
|
||||
Colors.black,
|
||||
);
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getSize(preview), const Size(320, 200));
|
||||
expect(Theme.of(tester.element(preview)).brightness, Brightness.light);
|
||||
expect(initialized, 1);
|
||||
expect(disposed, 0);
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byType(TextButton));
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.getSize(preview), const Size(320, 200));
|
||||
expect(disposed, 0);
|
||||
},
|
||||
);
|
||||
testWidgets(
|
||||
'old fullscreen host disposal preserves the active exit listener',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_native/fullscreen');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async => null);
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
Widget page({required bool old, required bool next}) => MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
if (old)
|
||||
const Expanded(
|
||||
key: ValueKey('old'),
|
||||
child: PreviewFullscreenHost(child: _Toggle('old')),
|
||||
),
|
||||
if (next)
|
||||
const Expanded(
|
||||
key: ValueKey('new'),
|
||||
child: PreviewFullscreenHost(child: _Toggle('new')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(page(old: true, next: false));
|
||||
await tester.tap(find.text('old'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('old'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(page(old: true, next: true));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('new'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(page(old: false, next: true));
|
||||
await tester.pumpAndSettle();
|
||||
await messenger.handlePlatformMessage(
|
||||
channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('exited'),
|
||||
),
|
||||
(_) {},
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
PreviewFullscreenScope.of(tester.element(find.text('new')))!.fullscreen,
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
|
||||
);
|
||||
testWidgets(
|
||||
'disposing a superseded fullscreen host does not exit the active window',
|
||||
(tester) async {
|
||||
const channel = MethodChannel('cutdex_native/fullscreen');
|
||||
final messenger = tester.binding.defaultBinaryMessenger;
|
||||
final requests = <bool>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
requests.add(call.arguments as bool);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
Widget page(bool old) => MaterialApp(
|
||||
home: Scaffold(
|
||||
body: Row(
|
||||
children: [
|
||||
if (old)
|
||||
const Expanded(
|
||||
key: ValueKey('old'),
|
||||
child: PreviewFullscreenHost(child: _Toggle('old')),
|
||||
),
|
||||
const Expanded(
|
||||
key: ValueKey('new'),
|
||||
child: PreviewFullscreenHost(child: _Toggle('new')),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(page(true));
|
||||
await tester.tap(find.text('old'));
|
||||
await tester.pumpAndSettle();
|
||||
// A newly mounted route can take ownership while the old route is retiring.
|
||||
tester
|
||||
.widget<TextButton>(find.widgetWithText(TextButton, 'new'))
|
||||
.onPressed!();
|
||||
await tester.pumpAndSettle();
|
||||
await tester.pumpWidget(page(false));
|
||||
await tester.pumpAndSettle();
|
||||
expect(requests, [true, true]);
|
||||
await messenger.handlePlatformMessage(
|
||||
channel.name,
|
||||
const StandardMethodCodec().encodeMethodCall(
|
||||
const MethodCall('exited'),
|
||||
),
|
||||
(_) {},
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
PreviewFullscreenScope.of(tester.element(find.text('new')))!.fullscreen,
|
||||
isFalse,
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.pumpAndSettle();
|
||||
},
|
||||
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
|
||||
);
|
||||
}
|
||||
|
||||
class _Preview extends StatefulWidget {
|
||||
const _Preview({required this.onInit, required this.onDispose});
|
||||
final VoidCallback onInit;
|
||||
final VoidCallback onDispose;
|
||||
@override
|
||||
State<_Preview> createState() => _PreviewState();
|
||||
}
|
||||
|
||||
class _PreviewState extends State<_Preview> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.onInit();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.onDispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: TextButton(
|
||||
onPressed: PreviewFullscreenScope.of(context)!.toggle,
|
||||
child: const Text('Fullscreen'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Toggle extends StatelessWidget {
|
||||
const _Toggle(this.label);
|
||||
final String label;
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: TextButton(
|
||||
onPressed: PreviewFullscreenScope.of(context)!.toggle,
|
||||
child: Text(label),
|
||||
),
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,508 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex/workspace/media_availability.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
final surface = find.byKey(const Key('preview-surface'));
|
||||
final toolbar = find.byKey(const Key('preview-toolbar'));
|
||||
final canvas = find.byKey(const Key('preview-canvas'));
|
||||
final playButton = find.byWidgetPredicate(
|
||||
(widget) => widget is IconButton && widget.tooltip == '播放',
|
||||
);
|
||||
|
||||
Future<void> mount(
|
||||
WidgetTester tester,
|
||||
Future<PreviewController> Function() load, {
|
||||
ThemeData? theme,
|
||||
MediaAvailability availability = MediaAvailability.available,
|
||||
}) => tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
mediaAvailabilityProvider.overrideWith(
|
||||
(ref, key) async => availability,
|
||||
),
|
||||
editorPreviewProvider(
|
||||
'project',
|
||||
'project',
|
||||
).overrideWith((ref) => load()),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: theme ?? EditorTheme.penLight,
|
||||
home: const Scaffold(
|
||||
body: EditorPreviewPanel(projectId: 'project', timelineId: 'project'),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'missing source shows the project placeholder and disables playback',
|
||||
(tester) async {
|
||||
final preview = _Preview();
|
||||
addTearDown(preview.dispose);
|
||||
await mount(
|
||||
tester,
|
||||
() async => preview,
|
||||
availability: MediaAvailability.missing,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final container = ProviderScope.containerOf(
|
||||
tester.element(find.byType(EditorPreviewPanel)),
|
||||
);
|
||||
container
|
||||
.read(previewTargetProvider('project', 'project'))
|
||||
.showAsset(
|
||||
AssetDocument(
|
||||
id: 'missing',
|
||||
name: 'missing.mov',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///missing.mov',
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('素材缺失'), findsOneWidget);
|
||||
expect(find.byIcon(Icons.broken_image_outlined), findsOneWidget);
|
||||
expect(find.textContaining('RuntimeException'), findsNothing);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
|
||||
expect(find.byTooltip('画布比例'), findsNothing);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('workspace follows theme while canvas content stays dark', (
|
||||
tester,
|
||||
) async {
|
||||
final preview = _Preview()..error = 'Preview error';
|
||||
addTearDown(preview.dispose);
|
||||
for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) {
|
||||
await mount(tester, () async => preview, theme: theme);
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
tester.widget<ColoredBox>(surface).color,
|
||||
theme.colorScheme.surface,
|
||||
);
|
||||
expect(tester.widget<ColoredBox>(canvas).color, Colors.black);
|
||||
expect(Theme.of(tester.element(toolbar)).brightness, theme.brightness);
|
||||
expect(
|
||||
Theme.of(tester.element(find.text('Preview error'))).brightness,
|
||||
Brightness.dark,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('preview has a fixed toolbar below flexible video', (
|
||||
tester,
|
||||
) async {
|
||||
final preview = _Preview();
|
||||
addTearDown(preview.dispose);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
for (final size in [const Size(640, 400), const Size(240, 180)]) {
|
||||
tester.view.physicalSize = size;
|
||||
await tester.pumpAndSettle();
|
||||
final videoRect = tester.getRect(surface);
|
||||
final canvasRect = tester.getRect(canvas);
|
||||
final toolbarRect = tester.getRect(toolbar);
|
||||
expect(find.text('视频预览'), findsNothing);
|
||||
expect(videoRect.left, AppSpacing.panelContentHorizontal);
|
||||
expect(videoRect.right, size.width - AppSpacing.panelContentHorizontal);
|
||||
expect(videoRect.top, AppSpacing.small);
|
||||
expect(videoRect.bottom, toolbarRect.top - AppSpacing.small);
|
||||
expect(canvasRect.center.dx, closeTo(videoRect.center.dx, 0.01));
|
||||
expect(canvasRect.center.dy, closeTo(videoRect.center.dy, 0.01));
|
||||
expect(toolbarRect.bottom, size.height);
|
||||
expect(toolbarRect.height, AppControlSize.panelHeader);
|
||||
expect(tester.getCenter(find.byTooltip('播放')).dx, size.width / 2);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: toolbar,
|
||||
matching: find.text('00:00:00:00 / 02:00:00:00'),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(Theme.of(tester.element(surface)).brightness, Brightness.light);
|
||||
expect(Theme.of(tester.element(toolbar)).brightness, Brightness.light);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
|
||||
await tester.tap(find.byTooltip('播放'));
|
||||
await tester.pump();
|
||||
expect(preview.playing, isTrue);
|
||||
expect(find.byTooltip('暂停播放'), findsOneWidget);
|
||||
preview.moveTo(3661 * TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
expect(find.text('01:01:01:00 / 02:00:00:00'), findsOneWidget);
|
||||
await tester.tap(find.byTooltip('暂停播放'));
|
||||
await tester.pump();
|
||||
expect(preview.playing, isFalse);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('empty timeline does not render a video canvas', (tester) async {
|
||||
final preview = _Preview()..durationTick = 0;
|
||||
addTearDown(preview.dispose);
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(canvas, findsNothing);
|
||||
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
|
||||
expect(find.text('暂无可预览内容'), findsNothing);
|
||||
expect(toolbar, findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
|
||||
preview.durationTick = TimelineClock.ticksPerSecond;
|
||||
preview.notifyListeners();
|
||||
await tester.pump();
|
||||
expect(canvas, findsOneWidget);
|
||||
expect(find.byKey(const Key('empty-preview-area')), findsNothing);
|
||||
|
||||
preview.durationTick = 0;
|
||||
preview.notifyListeners();
|
||||
await tester.pump();
|
||||
expect(canvas, findsNothing);
|
||||
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('empty timeline skips native preview initialization', (
|
||||
tester,
|
||||
) async {
|
||||
final empty = TimelineDto(
|
||||
id: SequenceId('one'),
|
||||
name: 'Empty',
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: const []),
|
||||
],
|
||||
elements: const [],
|
||||
);
|
||||
final fixture = (await tester.runAsync(
|
||||
() => createPreviewFixture(
|
||||
Uri.file('/unused.mov'),
|
||||
timelineOverride: empty,
|
||||
),
|
||||
))!;
|
||||
addTearDown(() async {
|
||||
await fixture.workspace.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
final calls = <MethodCall>[];
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
const runtimeChannel = MethodChannel('cutdex_runtime');
|
||||
messenger.setMockMethodCallHandler(runtimeChannel, (call) async {
|
||||
calls.add(call);
|
||||
return null;
|
||||
});
|
||||
addTearDown(() => messenger.setMockMethodCallHandler(runtimeChannel, null));
|
||||
final ids = (fixture.workspace.project!.info.id, 'project');
|
||||
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
ids.$1,
|
||||
ids.$2,
|
||||
).overrideWith((ref) async => fixture.timeline),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: EditorPreviewPanel(projectId: ids.$1, timelineId: ids.$2),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.byKey(const Key('empty-preview-area')), findsOneWidget);
|
||||
expect(canvas, findsNothing);
|
||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||
expect(calls, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('time display follows project frames and duration changes', (
|
||||
tester,
|
||||
) async {
|
||||
final preview = _Preview()
|
||||
..frameDuration = TimelineFormat.fps25.frameDuration;
|
||||
addTearDown(preview.dispose);
|
||||
final frame = TimelineClock.standard.toTicks(preview.frameDuration);
|
||||
preview.durationTick = 129 * frame;
|
||||
preview.positionTick = 15 * frame;
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('00:00:00:15 / 00:00:05:04'), findsOneWidget);
|
||||
preview.durationTick = 150 * frame;
|
||||
preview.moveTo(25 * frame);
|
||||
await tester.pump();
|
||||
expect(find.text('00:00:01:00 / 00:00:06:00'), findsOneWidget);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('editor failure retry recreates the editor provider', (
|
||||
tester,
|
||||
) async {
|
||||
var attempts = 0;
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider('project', 'project').overrideWith((
|
||||
ref,
|
||||
) async {
|
||||
attempts++;
|
||||
throw StateError('checkpoint failed');
|
||||
}),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: const Scaffold(
|
||||
body: EditorPreviewPanel(
|
||||
projectId: 'project',
|
||||
timelineId: 'project',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
for (var i = 0; i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 10));
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('无法打开时间线编辑器'), findsOneWidget);
|
||||
expect(attempts, 1);
|
||||
await tester.tap(find.text('重试'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(attempts, 2);
|
||||
expect(find.text('无法启动原生预览'), findsNothing);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'editor startup failure is distinct from native preview failure',
|
||||
(tester) async {
|
||||
await mount(
|
||||
tester,
|
||||
() async =>
|
||||
throw EditorSessionStartupException(StateError('checkpoint')),
|
||||
);
|
||||
for (
|
||||
var i = 0;
|
||||
i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty;
|
||||
i++
|
||||
) {
|
||||
await tester.pump(const Duration(milliseconds: 10));
|
||||
}
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('无法打开时间线编辑器'), findsOneWidget);
|
||||
expect(find.text('无法启动原生预览'), findsNothing);
|
||||
expect(find.text('重试'), findsOneWidget);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('loading and initialization failure keep the toolbar disabled', (
|
||||
tester,
|
||||
) async {
|
||||
final pending = Completer<PreviewController>();
|
||||
var loads = 0;
|
||||
await mount(tester, () {
|
||||
loads++;
|
||||
return pending.future;
|
||||
});
|
||||
final loadingRect = tester.getRect(toolbar);
|
||||
expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
|
||||
pending.completeError(StateError('unavailable'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('无法启动原生预览'), findsOneWidget);
|
||||
expect(tester.getRect(toolbar), loadingRect);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
|
||||
await tester.tap(find.text('重试'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(loads, 2);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'canvas ratio changes independently of the workspace and toolbar',
|
||||
(tester) async {
|
||||
final preview = _Preview();
|
||||
addTearDown(preview.dispose);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
for (final size in [const Size(640, 400), const Size(240, 180)]) {
|
||||
tester.view.physicalSize = size;
|
||||
await tester.pumpAndSettle();
|
||||
final toolbarRect = tester.getRect(toolbar);
|
||||
final surfaceRect = tester.getRect(surface);
|
||||
for (final entry in ProjectCanvasPresets.values.entries) {
|
||||
await tester.tap(find.byType(AppSelect<ProjectCanvas>));
|
||||
await tester.pumpAndSettle();
|
||||
final item = find.text(entry.key).last;
|
||||
await tester.ensureVisible(item);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(item);
|
||||
await tester.pumpAndSettle();
|
||||
final rect = tester.getRect(canvas);
|
||||
expect(
|
||||
rect.width / rect.height,
|
||||
closeTo(entry.value.aspectRatio, 0.000001),
|
||||
);
|
||||
expect(rect.center.dx, closeTo(surfaceRect.center.dx, 0.000001));
|
||||
expect(rect.top, closeTo(surfaceRect.top, 0.000001));
|
||||
expect(rect.left, greaterThan(surfaceRect.left));
|
||||
expect(rect.right, lessThan(surfaceRect.right));
|
||||
expect(rect.bottom, lessThanOrEqualTo(surfaceRect.bottom + 0.000001));
|
||||
expect(tester.getRect(toolbar), toolbarRect);
|
||||
expect(
|
||||
tester.widget<ColoredBox>(canvas).color,
|
||||
isNot(tester.widget<ColoredBox>(surface).color),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('offline media keeps playback available with a local notice', (
|
||||
tester,
|
||||
) async {
|
||||
final preview = _Preview()
|
||||
..hasUnavailableMedia = true
|
||||
..unavailableAtPlayhead = ['image'];
|
||||
addTearDown(preview.dispose);
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('素材离线或不可用:image'), findsOneWidget);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNotNull);
|
||||
expect(find.byTooltip('重试预览'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
|
||||
testWidgets('playback failure offers retry in the bottom toolbar', (
|
||||
tester,
|
||||
) async {
|
||||
final preview = _Preview()..error = '预览失败';
|
||||
addTearDown(preview.dispose);
|
||||
await mount(tester, () async => preview);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNull);
|
||||
expect(
|
||||
find.descendant(of: toolbar, matching: find.byTooltip('重试预览')),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.tap(find.byTooltip('重试预览'));
|
||||
await tester.pump();
|
||||
expect(preview.retries, 1);
|
||||
expect(find.byTooltip('重试预览'), findsNothing);
|
||||
expect(tester.widget<IconButton>(playButton).onPressed, isNotNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
});
|
||||
}
|
||||
|
||||
class _Preview extends ChangeNotifier implements PreviewController {
|
||||
@override
|
||||
Listenable get positionChanges => this;
|
||||
|
||||
@override
|
||||
bool hasUnavailableMedia = false;
|
||||
@override
|
||||
List<String> unavailableAtPlayhead = [];
|
||||
@override
|
||||
ProjectCanvas canvas = ProjectCanvas.widescreen;
|
||||
|
||||
@override
|
||||
void setCanvas(ProjectCanvas value) {
|
||||
canvas = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
RuntimeSession? get session => null;
|
||||
@override
|
||||
bool playing = false;
|
||||
@override
|
||||
bool busy = false;
|
||||
@override
|
||||
Object? error;
|
||||
@override
|
||||
int positionTick = 0;
|
||||
@override
|
||||
int durationTick = 7200 * TimelineClock.ticksPerSecond;
|
||||
@override
|
||||
RationalTime frameDuration = TimelineFormat.fps30.frameDuration;
|
||||
@override
|
||||
bool get canPlay => !busy && error == null;
|
||||
int retries = 0;
|
||||
|
||||
void moveTo(int tick) {
|
||||
positionTick = tick;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> togglePlayback() async {
|
||||
playing = !playing;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pauseForCanvasInteraction() async {
|
||||
playing = false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> retry() async {
|
||||
retries++;
|
||||
error = null;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/processing_fixture.dart';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
|
||||
void main() {
|
||||
for (var mask = 0; mask < 16; mask++) {
|
||||
test('processing capabilities are independent: $mask', () async {
|
||||
final root = await Directory.systemTemp.createTemp('processing-matrix-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final config = await processingFixture(root, mask);
|
||||
expect(config.transcriptionModel != null, mask & 1 != 0);
|
||||
expect(config.translationModel != null, mask & 2 != 0);
|
||||
expect(config.vocalSeparationModel != null, mask & 4 != 0);
|
||||
expect(config.backgroundRemovalModel != null, mask & 8 != 0);
|
||||
});
|
||||
}
|
||||
test(
|
||||
'stale model paths and missing runtime disable optional capabilities',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('processing-stale-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final config = await processingFixture(root, 7, stale: true);
|
||||
expect(config.transcriptionModel, isNull);
|
||||
expect(config.translationModel, isNull);
|
||||
expect(config.vocalSeparationModel, isNull);
|
||||
expect(config.backgroundRemovalModel, isNull);
|
||||
expect(
|
||||
ProcessingConfiguration.fromPaths(
|
||||
root: '${root.path}/missing',
|
||||
transcriptionPath: '${root.path}/asr',
|
||||
translationPath: '${root.path}/translation',
|
||||
vocalPath: '${root.path}/audio/melband.pt',
|
||||
),
|
||||
isNull,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('translation configuration is independent of ASR, audio models and FFmpeg', () async {
|
||||
final suffix = Platform.isWindows ? '.exe' : '';
|
||||
final root = await Directory.systemTemp.createTemp('cutdex configuration ');
|
||||
try {
|
||||
for (final path in [
|
||||
'runtime/bin/cutdex-processing-worker$suffix',
|
||||
'runtime/workers/translation/cutdex-m2m100-worker$suffix',
|
||||
'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/model.bin',
|
||||
'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/config.json',
|
||||
'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/shared_vocabulary.json',
|
||||
'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/sentencepiece.bpe.model',
|
||||
]) {
|
||||
final file = File('${root.path}/$path');
|
||||
await file.parent.create(recursive: true);
|
||||
await file.writeAsString('fixture');
|
||||
}
|
||||
final script = File('${root.path}/configuration.dart');
|
||||
await script.writeAsString('''
|
||||
import 'dart:convert';
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
void main() {
|
||||
final config = ProcessingConfiguration.configured()!;
|
||||
print(jsonEncode({
|
||||
'translation': config.translationModel != null,
|
||||
'transcription': config.transcriptionModel != null,
|
||||
'vocals': config.vocalSeparationModel != null,
|
||||
'inheritsEnvironment': config.backend.includeParentEnvironment,
|
||||
'provider': config.backend.environment['CUTDEX_ORT_PROVIDER'],
|
||||
}));
|
||||
}
|
||||
''');
|
||||
final result = await Process.run(
|
||||
'dart',
|
||||
[
|
||||
'--packages=${File('.dart_tool/package_config.json').absolute.path}',
|
||||
script.path,
|
||||
],
|
||||
runInShell: Platform.isWindows,
|
||||
environment: {
|
||||
'HOME': root.path,
|
||||
'USERPROFILE': root.path,
|
||||
'CUTDEX_PROCESSING_ROOT': '${root.path}/runtime',
|
||||
},
|
||||
);
|
||||
expect(result.exitCode, 0, reason: result.stderr.toString());
|
||||
expect(jsonDecode(result.stdout as String), {
|
||||
'translation': true,
|
||||
'transcription': false,
|
||||
'vocals': false,
|
||||
'inheritsEnvironment': false,
|
||||
'provider': 'cpu',
|
||||
});
|
||||
} finally {
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
}, skip: !(Platform.isMacOS || Platform.isWindows));
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/shared/widgets/processing_resource_download_dialog.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('resource download keeps the same actions across phases', (
|
||||
tester,
|
||||
) async {
|
||||
var cancelled = 0;
|
||||
var downloaded = 0;
|
||||
var paused = 0;
|
||||
var backgrounded = 0;
|
||||
|
||||
Future<void> show({bool downloading = false, bool isPaused = false}) =>
|
||||
tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
home: Scaffold(
|
||||
body: ProcessingResourceDownloadDialog(
|
||||
title: '下载抠像资源',
|
||||
description: '下载完成后自动开始抠像。',
|
||||
resourceName: '抠像模型',
|
||||
downloadSize: '需下载 973 MB',
|
||||
downloading: downloading,
|
||||
paused: isPaused,
|
||||
downloadedBytes: 250,
|
||||
totalBytes: 1000,
|
||||
bytesPerSecond: 100,
|
||||
onCancel: () => cancelled++,
|
||||
onDownload: () => downloaded++,
|
||||
onTogglePause: () => paused++,
|
||||
onBackground: () => backgrounded++,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await show();
|
||||
expect(find.text('下载抠像资源'), findsOneWidget);
|
||||
expect(find.text('下载完成后自动开始抠像。'), findsOneWidget);
|
||||
expect(find.text('需下载 973 MB'), findsOneWidget);
|
||||
expect(find.text('取消'), findsOneWidget);
|
||||
expect(find.text('下载'), findsOneWidget);
|
||||
expect(find.text('后台下载'), findsNothing);
|
||||
await tester.tap(find.text('下载'));
|
||||
expect(downloaded, 1);
|
||||
|
||||
await show(downloading: true);
|
||||
expect(find.text('需下载 973 MB'), findsNothing);
|
||||
expect(find.text('抠像模型'), findsOneWidget);
|
||||
expect(find.text('25%'), findsOneWidget);
|
||||
expect(find.text('取消下载'), findsOneWidget);
|
||||
expect(find.text('暂停'), findsOneWidget);
|
||||
expect(find.text('后台下载'), findsOneWidget);
|
||||
await tester.tap(find.text('暂停'));
|
||||
await tester.tap(find.text('后台下载'));
|
||||
expect(paused, 1);
|
||||
expect(backgrounded, 1);
|
||||
|
||||
await show(downloading: true, isPaused: true);
|
||||
expect(find.text('已暂停'), findsOneWidget);
|
||||
expect(find.text('继续'), findsOneWidget);
|
||||
await tester.tap(find.text('取消下载'));
|
||||
expect(cancelled, 1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
import 'package:cutdex/integrations/runtime/processing_resource_repository.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:cutdex/integrations/runtime/processing_resource_state.dart';
|
||||
|
||||
void main() {
|
||||
test('disposing the resource owner cancels a pending subtitle bundle without late notifications', () async {
|
||||
final fixture = await _subtitleFixture();
|
||||
var disposed = false;
|
||||
await expectLater(
|
||||
fixture.repository.ensureSubtitleResources(
|
||||
onProgress: (_, _) {
|
||||
if (!disposed) {
|
||||
disposed = true;
|
||||
fixture.repository.dispose();
|
||||
}
|
||||
},
|
||||
),
|
||||
throwsA(isA<ProcessingResourceCancelledException>()),
|
||||
);
|
||||
expect(fixture.requests, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'resource snapshots freeze installed states and observe bundle completion',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture();
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
final provider = processingResourcesProvider(fixture.repository);
|
||||
final updates = <ProcessingResourcesSnapshot>[];
|
||||
container.listen(
|
||||
provider,
|
||||
(_, next) => updates.add(next),
|
||||
fireImmediately: true,
|
||||
);
|
||||
final before = container.read(provider);
|
||||
await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {});
|
||||
final after = container.read(provider);
|
||||
expect(updates.any((value) => value.subtitleDownloading), isTrue);
|
||||
expect(after.subtitleDownloading, isFalse);
|
||||
expect(after.subtitleDownloadedBytes, after.subtitleTotalBytes);
|
||||
expect(
|
||||
after.installs.every(
|
||||
(value) => value.state == ProcessingResourceState.installed,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
before.installs.any(
|
||||
(value) => value.state == ProcessingResourceState.installed,
|
||||
),
|
||||
isFalse,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'subtitle bundle downloads both models with one monotonic byte progress',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture();
|
||||
final reports = <(ProcessingCapability, double)>[];
|
||||
expect(fixture.repository.subtitleTotalBytes, 80);
|
||||
await fixture.repository.ensureSubtitleResources(
|
||||
onProgress: (stage, progress) {
|
||||
reports.add((stage, progress));
|
||||
if (stage == ProcessingCapability.translation && progress == .25) {
|
||||
expect(fixture.repository.subtitleDownloadedBytes, 20);
|
||||
expect(fixture.repository.subtitleDownloading, isTrue);
|
||||
}
|
||||
},
|
||||
);
|
||||
expect(fixture.repository.subtitleDownloading, isFalse);
|
||||
expect(fixture.requests, ['transcription', 'translation']);
|
||||
expect(reports.first.$2, 0);
|
||||
expect(reports.last.$2, 1);
|
||||
expect(
|
||||
reports
|
||||
.where((entry) => entry.$1 == ProcessingCapability.translation)
|
||||
.first
|
||||
.$2,
|
||||
0.25,
|
||||
);
|
||||
for (var i = 1; i < reports.length; i++) {
|
||||
expect(reports[i].$2, greaterThanOrEqualTo(reports[i - 1].$2));
|
||||
}
|
||||
expect(
|
||||
fixture.repository.installs.every(
|
||||
(install) => install.state == ProcessingResourceState.installed,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {});
|
||||
expect(fixture.requests, ['transcription', 'translation']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'subtitle bundle skips configured speech and still installs translation',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture();
|
||||
final reports = <(ProcessingCapability, double)>[];
|
||||
await fixture.repository.ensureSubtitleResources(
|
||||
available: {ProcessingCapability.transcription},
|
||||
onProgress: (stage, progress) => reports.add((stage, progress)),
|
||||
);
|
||||
expect(fixture.requests, ['translation']);
|
||||
expect(reports.first, (ProcessingCapability.translation, 0.25));
|
||||
expect(reports.last.$2, 1);
|
||||
},
|
||||
);
|
||||
|
||||
test('pausing a subtitle download keeps its bytes and resumes the same request', () async {
|
||||
final root = await Directory.systemTemp.createTemp('subtitle-pause-');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final firstChunk = List<int>.filled(10, 1);
|
||||
final secondChunk = List<int>.filled(10, 2);
|
||||
final speech = [...firstChunk, ...secondChunk];
|
||||
final translation = List<int>.filled(5, 3);
|
||||
final requests = <String>[];
|
||||
final releaseSecondChunk = Completer<void>();
|
||||
final secondChunkSent = Completer<void>();
|
||||
server.listen((request) async {
|
||||
final name = request.uri.pathSegments.single;
|
||||
requests.add(name);
|
||||
if (name == 'transcription') {
|
||||
request.response.bufferOutput = false;
|
||||
request.response.contentLength = speech.length;
|
||||
request.response.add(firstChunk);
|
||||
await request.response.flush();
|
||||
await releaseSecondChunk.future;
|
||||
request.response.add(secondChunk);
|
||||
await request.response.flush();
|
||||
secondChunkSent.complete();
|
||||
} else {
|
||||
request.response.contentLength = translation.length;
|
||||
request.response.add(translation);
|
||||
}
|
||||
await request.response.close();
|
||||
});
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [
|
||||
for (final (capability, payload) in [
|
||||
(ProcessingCapability.transcription, speech),
|
||||
(ProcessingCapability.translation, translation),
|
||||
])
|
||||
ProcessingResourcePackage(
|
||||
capability: capability,
|
||||
id: capability.name,
|
||||
version: '1',
|
||||
name: capability.name,
|
||||
description: '',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse(
|
||||
'http://127.0.0.1:${server.port}/${capability.name}',
|
||||
),
|
||||
sha256: sha256.convert(payload).toString(),
|
||||
bytes: payload.length,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
if (!releaseSecondChunk.isCompleted) releaseSecondChunk.complete();
|
||||
repository.dispose();
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final paused = Completer<void>();
|
||||
final progress = <double>[];
|
||||
final download = repository.ensureSubtitleResources(
|
||||
onProgress: (stage, value) {
|
||||
progress.add(value);
|
||||
if (stage == ProcessingCapability.transcription &&
|
||||
repository.installFor(stage).downloadedBytes == firstChunk.length &&
|
||||
!paused.isCompleted) {
|
||||
paused.complete();
|
||||
repository.pauseSubtitleResources();
|
||||
}
|
||||
},
|
||||
);
|
||||
await paused.future.timeout(
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () => throw StateError(
|
||||
'first chunk was not observed: requests=$requests progress=$progress '
|
||||
'install=${repository.installFor(ProcessingCapability.transcription).downloadedBytes}',
|
||||
),
|
||||
);
|
||||
expect(repository.subtitlePaused, isTrue);
|
||||
final atPause = progress.last;
|
||||
releaseSecondChunk.complete();
|
||||
await secondChunkSent.future.timeout(
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () => throw StateError('server did not send the second chunk'),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
expect(progress.last, atPause);
|
||||
expect(
|
||||
repository.installFor(ProcessingCapability.transcription).downloadedBytes,
|
||||
firstChunk.length,
|
||||
);
|
||||
repository.resumeSubtitleResources();
|
||||
await download.timeout(
|
||||
const Duration(seconds: 5),
|
||||
onTimeout: () => throw StateError('download did not resume'),
|
||||
);
|
||||
expect(repository.subtitlePaused, isFalse);
|
||||
expect(requests, ['transcription', 'translation']);
|
||||
expect(progress.last, 1);
|
||||
});
|
||||
|
||||
test('download speed remains available without a progress widget', () async {
|
||||
final root = await Directory.systemTemp.createTemp('resource-speed-');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final releaseLastChunk = Completer<void>();
|
||||
final payload = <int>[
|
||||
...List<int>.filled(10, 1),
|
||||
...List<int>.filled(10, 2),
|
||||
...List<int>.filled(10, 3),
|
||||
];
|
||||
server.listen((request) async {
|
||||
request.response.bufferOutput = false;
|
||||
request.response.contentLength = payload.length;
|
||||
request.response.add(payload.sublist(0, 10));
|
||||
await request.response.flush();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 550));
|
||||
request.response.add(payload.sublist(10, 20));
|
||||
await request.response.flush();
|
||||
await releaseLastChunk.future;
|
||||
request.response.add(payload.sublist(20));
|
||||
await request.response.close();
|
||||
});
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.backgroundRemoval,
|
||||
id: 'speed-test',
|
||||
version: '1',
|
||||
name: 'Speed test',
|
||||
description: '',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse('http://127.0.0.1:${server.port}/model'),
|
||||
sha256: sha256.convert(payload).toString(),
|
||||
bytes: payload.length,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
if (!releaseLastChunk.isCompleted) releaseLastChunk.complete();
|
||||
repository.dispose();
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final secondChunk = Completer<void>();
|
||||
repository.addListener(() {
|
||||
if (repository
|
||||
.installFor(ProcessingCapability.backgroundRemoval)
|
||||
.downloadedBytes ==
|
||||
20 &&
|
||||
!secondChunk.isCompleted) {
|
||||
secondChunk.complete();
|
||||
}
|
||||
});
|
||||
final download = repository.ensureAvailable(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
);
|
||||
await secondChunk.future.timeout(const Duration(seconds: 5));
|
||||
expect(
|
||||
repository.downloadBytesPerSecondFor(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
),
|
||||
greaterThan(0),
|
||||
);
|
||||
repository.pauseDownload(ProcessingCapability.backgroundRemoval);
|
||||
expect(
|
||||
repository.downloadPausedFor(ProcessingCapability.backgroundRemoval),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
repository.downloadBytesPerSecondFor(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
),
|
||||
0,
|
||||
);
|
||||
releaseLastChunk.complete();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
expect(
|
||||
repository
|
||||
.installFor(ProcessingCapability.backgroundRemoval)
|
||||
.downloadedBytes,
|
||||
20,
|
||||
);
|
||||
repository.resumeDownload(ProcessingCapability.backgroundRemoval);
|
||||
await download.timeout(const Duration(seconds: 5));
|
||||
expect(
|
||||
repository.downloadPausedFor(ProcessingCapability.backgroundRemoval),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
repository.downloadBytesPerSecondFor(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
),
|
||||
0,
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'cancelling between models stops translation and retry reuses speech',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture();
|
||||
await expectLater(
|
||||
fixture.repository.ensureSubtitleResources(
|
||||
onProgress: (stage, progress) {
|
||||
if (stage == ProcessingCapability.transcription &&
|
||||
fixture.repository.installFor(stage).state ==
|
||||
ProcessingResourceState.installed) {
|
||||
fixture.repository.cancelSubtitleResources();
|
||||
}
|
||||
},
|
||||
),
|
||||
throwsA(isA<ProcessingResourceCancelledException>()),
|
||||
);
|
||||
expect(fixture.requests, ['transcription']);
|
||||
await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {});
|
||||
expect(fixture.requests, ['transcription', 'translation']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'cancelling a paused subtitle download releases the pause gate',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture();
|
||||
final paused = Completer<void>();
|
||||
final download = fixture.repository.ensureSubtitleResources(
|
||||
onProgress: (stage, progress) {
|
||||
if (stage == ProcessingCapability.transcription &&
|
||||
progress == 0 &&
|
||||
!paused.isCompleted) {
|
||||
paused.complete();
|
||||
fixture.repository.pauseSubtitleResources();
|
||||
}
|
||||
},
|
||||
);
|
||||
await paused.future.timeout(const Duration(seconds: 5));
|
||||
fixture.repository.cancel(ProcessingCapability.transcription);
|
||||
await expectLater(
|
||||
download.timeout(const Duration(seconds: 5)),
|
||||
throwsA(isA<ProcessingResourceCancelledException>()),
|
||||
);
|
||||
expect(fixture.repository.subtitlePaused, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'translation verification failure keeps speech and can be retried',
|
||||
() async {
|
||||
final fixture = await _subtitleFixture(corruptTranslationOnce: true);
|
||||
await expectLater(
|
||||
fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}),
|
||||
throwsA(
|
||||
isA<AppException>().having(
|
||||
(error) => error.failure.code,
|
||||
'code',
|
||||
AppErrorCode.resourceChecksumFailed,
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(
|
||||
fixture.repository.installFor(ProcessingCapability.transcription).state,
|
||||
ProcessingResourceState.installed,
|
||||
);
|
||||
expect(
|
||||
fixture.repository.installFor(ProcessingCapability.translation).state,
|
||||
ProcessingResourceState.failed,
|
||||
);
|
||||
await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {});
|
||||
expect(fixture.requests, ['transcription', 'translation', 'translation']);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'downloads, verifies and atomically publishes a processing resource',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-models-');
|
||||
final payload = utf8.encode('verified model');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
server.listen((request) async {
|
||||
request.response.add(payload);
|
||||
await request.response.close();
|
||||
});
|
||||
addTearDown(() async {
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final package = ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.transcription,
|
||||
id: 'test-model',
|
||||
version: '7',
|
||||
name: 'Test',
|
||||
description: 'Test model',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse('http://127.0.0.1:${server.port}/model'),
|
||||
sha256: sha256.convert(payload).toString(),
|
||||
bytes: payload.length,
|
||||
),
|
||||
],
|
||||
);
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [package],
|
||||
);
|
||||
|
||||
await repository.ensureAvailable(ProcessingCapability.transcription);
|
||||
|
||||
expect(
|
||||
repository.installs.single.state,
|
||||
ProcessingResourceState.installed,
|
||||
);
|
||||
expect(
|
||||
File('${root.path}/Transcription/test-model/7/model.bin')
|
||||
.readAsBytesSync(),
|
||||
payload,
|
||||
);
|
||||
expect(
|
||||
Directory('${root.path}/Transcription/test-model/7.download')
|
||||
.existsSync(),
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'HTTP download failure retains its status code in the install state',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-http-error-');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
server.listen((request) async {
|
||||
request.response.statusCode = 503;
|
||||
await request.response.close();
|
||||
});
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.transcription,
|
||||
id: 'http-test',
|
||||
version: '1',
|
||||
name: 'Test',
|
||||
description: 'Test',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse('http://127.0.0.1:${server.port}/model'),
|
||||
sha256: List.filled(64, '0').join(),
|
||||
bytes: 1,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
repository.dispose();
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await expectLater(
|
||||
repository.ensureAvailable(ProcessingCapability.transcription),
|
||||
throwsA(isA<AppException>()),
|
||||
);
|
||||
final install = repository.installs.single;
|
||||
expect(install.state, ProcessingResourceState.failed);
|
||||
expect(install.error?.code, AppErrorCode.resourceDownloadHttpFailed);
|
||||
expect(install.error?.httpStatusCode, 503);
|
||||
expect(await repository.directoryFor(install.package).exists(), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('does not publish a resource with a mismatched checksum', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-models-');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
server.listen((request) async {
|
||||
request.response.write('corrupt');
|
||||
await request.response.close();
|
||||
});
|
||||
addTearDown(() async {
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final package = ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.transcription,
|
||||
id: 'test-model',
|
||||
version: '1',
|
||||
name: 'Test',
|
||||
description: 'Test model',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse('http://127.0.0.1:${server.port}/model'),
|
||||
sha256: List.filled(64, '0').join(),
|
||||
bytes: 7,
|
||||
),
|
||||
],
|
||||
);
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [package],
|
||||
);
|
||||
|
||||
await expectLater(
|
||||
repository.ensureAvailable(ProcessingCapability.transcription),
|
||||
throwsA(
|
||||
isA<AppException>().having(
|
||||
(error) => error.failure.code,
|
||||
'code',
|
||||
AppErrorCode.resourceChecksumFailed,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(repository.installs.single.state, ProcessingResourceState.failed);
|
||||
expect(
|
||||
repository.installs.single.error?.code,
|
||||
AppErrorCode.resourceChecksumFailed,
|
||||
);
|
||||
expect(
|
||||
Directory('${root.path}/Transcription/test-model/1').existsSync(),
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
Directory('${root.path}/Transcription/test-model/1.download')
|
||||
.existsSync(),
|
||||
false,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
Future<({ProcessingResourceRepository repository, List<String> requests})>
|
||||
_subtitleFixture({bool corruptTranslationOnce = false}) async {
|
||||
final root = await Directory.systemTemp.createTemp('subtitle-bundle-');
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||||
final requests = <String>[];
|
||||
final data = {
|
||||
ProcessingCapability.transcription: List.filled(20, 1),
|
||||
ProcessingCapability.translation: List.filled(60, 2),
|
||||
};
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: root,
|
||||
catalog: [
|
||||
for (final entry in data.entries)
|
||||
ProcessingResourcePackage(
|
||||
capability: entry.key,
|
||||
id: entry.key.name,
|
||||
version: '1',
|
||||
name: entry.key.name,
|
||||
description: '',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse(
|
||||
'http://127.0.0.1:${server.port}/${entry.key.name}',
|
||||
),
|
||||
sha256: sha256.convert(entry.value).toString(),
|
||||
bytes: entry.value.length,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
server.listen((request) async {
|
||||
final name = request.uri.pathSegments.single;
|
||||
requests.add(name);
|
||||
final payload = data[ProcessingCapability.values.byName(name)]!;
|
||||
if (name == 'translation' && corruptTranslationOnce) {
|
||||
corruptTranslationOnce = false;
|
||||
request.response.add(List.filled(payload.length, 0));
|
||||
} else {
|
||||
request.response.add(payload);
|
||||
}
|
||||
await request.response.close();
|
||||
});
|
||||
addTearDown(() async {
|
||||
repository.dispose();
|
||||
await server.close(force: true);
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
return (repository: repository, requests: requests);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/settings/language_settings.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
test(
|
||||
'creation waits for saved language and later changes only new names',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-creation-locale-',
|
||||
);
|
||||
final repository = _DelayedLanguageRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
addTearDown(() async {
|
||||
await projects.prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
final opening = projects.open('${root.path}/My.cutdex', name: 'My name');
|
||||
await repository.loadStarted.future;
|
||||
expect(await Directory('${root.path}/My.cutdex').exists(), isFalse);
|
||||
repository.loaded.complete(AppLanguage.traditionalChinese);
|
||||
expect(await opening, isTrue);
|
||||
final initial = container.read(projectsProvider).requireValue;
|
||||
expect(initial.activeProject!.name, 'My name');
|
||||
expect(initial.timeline!.name, '時間軸 1');
|
||||
expect(initial.timeline!.sequences.single.name, '主序列');
|
||||
expect(initial.timeline!.sequences.single.storylines.single.name, '主線');
|
||||
|
||||
await container
|
||||
.read(languageSettingsProvider.notifier)
|
||||
.setLanguage(AppLanguage.english);
|
||||
expect(await projects.createTimeline(name: 'User title'), isTrue);
|
||||
final added = container.read(projectsProvider).requireValue;
|
||||
expect(added.timeline!.name, 'User title');
|
||||
expect(added.timeline!.sequences.single.name, 'Main sequence');
|
||||
expect(
|
||||
added.timeline!.sequences.single.storylines.single.name,
|
||||
'Main storyline',
|
||||
);
|
||||
expect(
|
||||
await projects.openTimeline(
|
||||
initial.activeProject!.id,
|
||||
initial.timeline!.id,
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final retained = container.read(projectsProvider).requireValue;
|
||||
expect(retained.activeProject!.name, 'My name');
|
||||
expect(retained.timeline!.name, '時間軸 1');
|
||||
expect(retained.timeline!.sequences.single.name, '主序列');
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _DelayedLanguageRepository implements LanguageSettingsRepository {
|
||||
final loaded = Completer<AppLanguage>();
|
||||
final loadStarted = Completer<void>();
|
||||
|
||||
@override
|
||||
Future<AppLanguage> load() {
|
||||
loadStarted.complete();
|
||||
return loaded.future;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(AppLanguage language) async {}
|
||||
}
|
||||
@@ -0,0 +1,739 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/integrations/platform/device_experience.dart';
|
||||
|
||||
import 'support/empty_conversation_repository.dart';
|
||||
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/integrations/editor_command_host.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/app/router/app_router.dart';
|
||||
import 'package:cutdex/features/editor/editor_page.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/memory_app_settings.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test('superseded prepared project never publishes and restores the prior workspace', () async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-stale-selection-',
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
await projects.open('${root.path}/One.cutdex', name: 'One');
|
||||
final initial = container.read(projectsProvider).requireValue;
|
||||
final firstSession = await projects.openTimelineSession(
|
||||
initial.activeProject!.id,
|
||||
initial.timeline!.id,
|
||||
);
|
||||
var checks = 0;
|
||||
final publishedIds = <String?>[];
|
||||
final subscription = container.listen(projectsProvider, (_, next) {
|
||||
publishedIds.add(next.value?.activeProject?.id);
|
||||
});
|
||||
final opened = await projects.open(
|
||||
'${root.path}/Two.cutdex',
|
||||
name: 'Two',
|
||||
isCurrent: () => ++checks < 6,
|
||||
);
|
||||
expect(opened, isFalse);
|
||||
expect(
|
||||
publishedIds.every((id) => id == initial.activeProject!.id),
|
||||
isTrue,
|
||||
);
|
||||
expect(container.read(projectsProvider).requireValue.error, isNull);
|
||||
expect(
|
||||
await projects.openTimelineSession(
|
||||
initial.activeProject!.id,
|
||||
initial.timeline!.id,
|
||||
),
|
||||
same(firstSession),
|
||||
);
|
||||
subscription.close();
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test('creating a project rebuilds a deleted local save directory', () async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-recreate-projects-',
|
||||
);
|
||||
final location = Directory('${root.path}/deleted/projects');
|
||||
await location.create(recursive: true);
|
||||
await location.parent.delete(recursive: true);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
projectLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
DefaultingProjectLocationSettingsRepository(
|
||||
MemoryProjectLocationSettingsRepository(location.path),
|
||||
),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
expect(
|
||||
await container
|
||||
.read(projectsProvider.notifier)
|
||||
.createProject('Recovered', initialTimelineName: 'Timeline'),
|
||||
isTrue,
|
||||
);
|
||||
expect(await location.exists(), isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.activeProject?.name,
|
||||
'Recovered',
|
||||
);
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test('selecting an existing project keeps its sidebar position', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-project-order-');
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
final firstPath = '${root.path}/First.cutdex';
|
||||
final secondPath = '${root.path}/Second.cutdex';
|
||||
expect(await projects.open(firstPath, name: 'First'), isTrue);
|
||||
expect(await projects.open(secondPath, name: 'Second'), isTrue);
|
||||
final before = container.read(projectsProvider).requireValue.recent;
|
||||
expect(before.map((project) => project.name), ['Second', 'First']);
|
||||
|
||||
expect(
|
||||
await projects.open(firstPath, expectedId: before.last.id),
|
||||
isTrue,
|
||||
);
|
||||
final after = container.read(projectsProvider).requireValue.recent;
|
||||
expect(
|
||||
after.map((project) => project.id),
|
||||
before.map((project) => project.id),
|
||||
);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.activeProject?.id,
|
||||
before.last.id,
|
||||
);
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'removing a project preserves files and undo restores its position',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-remove-project-',
|
||||
);
|
||||
final repository = MemoryRecentProjectsRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(repository),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open('${root.path}/First.cutdex', name: 'First'),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
await projects.open('${root.path}/Second.cutdex', name: 'Second'),
|
||||
isTrue,
|
||||
);
|
||||
final before = container.read(projectsProvider).requireValue;
|
||||
final removed = before.recent.first;
|
||||
expect(await projects.removeRecentProject(removed.id), isTrue);
|
||||
expect((await repository.load()).map((item) => item.id), [
|
||||
before.recent.last.id,
|
||||
]);
|
||||
expect(await Directory(removed.path).exists(), isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.activeProject?.id,
|
||||
removed.id,
|
||||
);
|
||||
expect(await projects.restoreRecentProject(removed, 0), isTrue);
|
||||
expect(
|
||||
(await repository.load()).map((item) => item.id),
|
||||
before.recent.map((item) => item.id),
|
||||
);
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'deleting the selected timeline selects its previous neighbor',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-delete-timeline-',
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open('${root.path}/Project.cutdex', name: 'Project'),
|
||||
isTrue,
|
||||
);
|
||||
final initial = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timelines
|
||||
.single;
|
||||
expect(initial.pinned, isTrue);
|
||||
expect(await projects.createTimeline(name: 'Second'), isTrue);
|
||||
final second = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
expect(await projects.createTimeline(name: 'Third'), isTrue);
|
||||
final third = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
expect(await projects.createTimeline(name: 'Fourth'), isTrue);
|
||||
final fourth = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
expect(await projects.deleteTimeline(fourth), isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.timeline?.id,
|
||||
third,
|
||||
);
|
||||
final projectId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
expect(await projects.openTimeline(projectId, initial.id), isTrue);
|
||||
expect(await projects.deleteTimeline(initial.id), isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.timeline?.id,
|
||||
second,
|
||||
);
|
||||
expect(await projects.deleteTimeline(third), isTrue);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.timeline?.id,
|
||||
second,
|
||||
);
|
||||
expect(await projects.deleteTimeline(second), isFalse);
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'all timeline providers are ready before active state is published',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-switch-sync-');
|
||||
final viewSettings = _MemoryTimelineViewSettingsRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
timelineViewSettingsRepositoryProvider.overrideWithValue(
|
||||
viewSettings,
|
||||
),
|
||||
],
|
||||
);
|
||||
try {
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open('${root.path}/Project.cutdex', name: 'Project'),
|
||||
isTrue,
|
||||
);
|
||||
final id = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.activeProject!
|
||||
.id;
|
||||
final firstId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
final firstProvider = editorTimelineProvider(id, firstId);
|
||||
final firstSubscription = container.listen(firstProvider, (_, _) {});
|
||||
final firstSession = container.read(firstProvider).requireValue;
|
||||
firstSubscription.close();
|
||||
final firstPreviewProvider = editorPreviewProvider(id, firstId);
|
||||
final firstPreviewSubscription = container.listen(
|
||||
firstPreviewProvider,
|
||||
(_, _) {},
|
||||
);
|
||||
expect(container.read(firstPreviewProvider).hasValue, isTrue);
|
||||
expect(container.read(firstPreviewProvider).requireValue, isNull);
|
||||
firstPreviewSubscription.close();
|
||||
await container.pump();
|
||||
|
||||
expect(await projects.createTimeline(name: 'Second'), isTrue);
|
||||
final secondId = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timeline!
|
||||
.id;
|
||||
final secondProvider = editorTimelineProvider(id, secondId);
|
||||
final secondSubscription = container.listen(secondProvider, (_, _) {});
|
||||
expect(container.read(secondProvider).hasValue, isTrue);
|
||||
secondSubscription.close();
|
||||
final secondPreviewProvider = editorPreviewProvider(id, secondId);
|
||||
final secondPreviewSubscription = container.listen(
|
||||
secondPreviewProvider,
|
||||
(_, _) {},
|
||||
);
|
||||
expect(container.read(secondPreviewProvider).hasValue, isTrue);
|
||||
expect(container.read(secondPreviewProvider).requireValue, isNull);
|
||||
secondPreviewSubscription.close();
|
||||
await container.pump();
|
||||
|
||||
final openingStates = <String?>[];
|
||||
final stateSubscription = container.listen(projectsProvider, (_, next) {
|
||||
openingStates.add(next.value?.openingTimelineId);
|
||||
});
|
||||
expect(await projects.openTimeline(id, firstId), isTrue);
|
||||
stateSubscription.close();
|
||||
expect(openingStates, isNot(contains(firstId)));
|
||||
final returning = container.listen(firstProvider, (_, _) {});
|
||||
expect(container.read(firstProvider).asData?.value, same(firstSession));
|
||||
expect(viewSettings.loads, 2);
|
||||
returning.close();
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
);
|
||||
test('opening a project restores its last timeline and handles missing records and empty projects', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-entry-');
|
||||
final recent = MemoryRecentProjectsRepository();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(recent),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
expect(
|
||||
await projects.open(
|
||||
'${root.path}/A.cutdex',
|
||||
name: 'A',
|
||||
initialTimelineName: '时间线 1',
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
final id = container.read(projectsProvider).requireValue.activeProject!.id;
|
||||
final first = container.read(projectsProvider).requireValue.timeline!.id;
|
||||
expect(await projects.createTimeline(name: '时间线 2'), isTrue);
|
||||
expect(
|
||||
container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timelines
|
||||
.map((timeline) => timeline.name),
|
||||
containsAll(['时间线 1', '时间线 2']),
|
||||
);
|
||||
final second = container
|
||||
.read(projectsProvider)
|
||||
.requireValue
|
||||
.timelines
|
||||
.firstWhere((project) => project.id != first)
|
||||
.id;
|
||||
expect(await projects.openTimeline(id, second), isTrue);
|
||||
expect(await projects.open('${root.path}/B.cutdex', name: 'B'), isTrue);
|
||||
expect(container.read(projectsProvider).requireValue.timeline, isNotNull);
|
||||
expect(await projects.open('${root.path}/A.cutdex'), isTrue);
|
||||
expect(container.read(projectsProvider).requireValue.timeline!.id, second);
|
||||
expect(projects.cachedTimelineSession(id, second), isNotNull);
|
||||
expect(projects.cachedTimelineSession(id, first), isNull);
|
||||
expect(await projects.openTimeline(id, first), isTrue);
|
||||
expect(projects.cachedTimelineSession(id, first), isNotNull);
|
||||
expect(await projects.openTimeline(id, second), isTrue);
|
||||
recent.projects[id] = 'deleted';
|
||||
expect(await projects.open('${root.path}/A.cutdex'), isTrue);
|
||||
final current = container.read(projectsProvider).requireValue;
|
||||
expect(
|
||||
current.timelines.map((timeline) => timeline.id),
|
||||
contains(current.timeline?.id),
|
||||
);
|
||||
expect(recent.projects[id], current.timeline?.id);
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
|
||||
test(
|
||||
'tool imports publish project assets without depending on UI busy state',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-project-events-',
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
recentProjectsProvider.overrideWithValue(
|
||||
MemoryRecentProjectsRepository(),
|
||||
),
|
||||
resourceLocationSettingsRepositoryProvider.overrideWithValue(
|
||||
MemoryResourceLocationSettingsRepository(root.path),
|
||||
),
|
||||
],
|
||||
);
|
||||
final projects = container.read(projectsProvider.notifier);
|
||||
try {
|
||||
expect(
|
||||
await projects.open('${root.path}/Project.cutdex', name: 'Project'),
|
||||
isTrue,
|
||||
);
|
||||
expect(await projects.createTimeline(name: 'Timeline'), isTrue);
|
||||
final current = container.read(projectsProvider).requireValue;
|
||||
final session = await projects.openTimelineSession(
|
||||
current.activeProject!.id,
|
||||
current.timeline!.id,
|
||||
);
|
||||
final busy = <bool>[];
|
||||
final subscription = container.listen(
|
||||
projectsProvider,
|
||||
(_, next) => busy.add(next.requireValue.projectBusy),
|
||||
);
|
||||
final file = await File('${root.path}/image.png').writeAsBytes([1]);
|
||||
final result = await editorToolsFor(session, session.activeSequenceId!)
|
||||
.invoke(
|
||||
name: 'media.import',
|
||||
arguments: {'path': file.path},
|
||||
context: const CommandContext(operationId: 'headless-import'),
|
||||
);
|
||||
expect(result.edit, EditOutcome.committed);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.assets.single.name,
|
||||
'image.png',
|
||||
);
|
||||
expect(busy, isNotEmpty);
|
||||
expect(busy, everyElement(isFalse));
|
||||
subscription.close();
|
||||
await session.close();
|
||||
} finally {
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await root.delete(recursive: true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'editing page opens an empty project without creating a timeline',
|
||||
(tester) async {
|
||||
tester.view.physicalSize = const Size(1200, 800);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
conversationRepositoryProvider.overrideWith(
|
||||
(ref) async => EmptyConversationRepository(),
|
||||
),
|
||||
projectsProvider.overrideWith(_EmptyProjects.new),
|
||||
],
|
||||
);
|
||||
final router = container.read(appRouterProvider);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp.router(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
routerConfig: router,
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
await mouse.addPointer(location: Offset.zero);
|
||||
await mouse.moveTo(
|
||||
tester.getCenter(find.byKey(const Key('projects-heading'))),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const Key('create-project')));
|
||||
await mouse.removePointer();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('新建项目'), findsOneWidget);
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('sidebar-project-empty')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(router.routeInformationProvider.value.uri.path, '/');
|
||||
expect(find.text('项目中还没有时间线'), findsOneWidget);
|
||||
expect(find.byTooltip('新建时间线'), findsNothing);
|
||||
expect(find.byType(EditorWorkspace), findsNothing);
|
||||
expect(find.byType(EditorPreviewPanel), findsNothing);
|
||||
expect(
|
||||
container.read(projectsProvider).requireValue.activeProject?.id,
|
||||
'empty',
|
||||
);
|
||||
expect(container.read(projectsProvider).requireValue.timelines, isEmpty);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
container.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('missing recent project stays visible and is dimmed', (
|
||||
tester,
|
||||
) async {
|
||||
tester.platformDispatcher.localesTestValue = const [Locale('zh')];
|
||||
addTearDown(tester.platformDispatcher.clearLocalesTestValue);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
conversationRepositoryProvider.overrideWith(
|
||||
(ref) async => EmptyConversationRepository(),
|
||||
),
|
||||
|
||||
projectsProvider.overrideWith(_MissingProjects.new),
|
||||
workspaceViewSettingsRepositoryProvider.overrideWithValue(
|
||||
_ExpandedMissingProjectSettings(),
|
||||
),
|
||||
],
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp.router(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
routerConfig: container.read(appRouterProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final tile = tester.widget<ListTile>(
|
||||
find.byKey(const ValueKey('sidebar-project-missing')),
|
||||
);
|
||||
expect(tile.enabled, isTrue);
|
||||
expect(tile.textColor, EditorTheme.penDark.disabledColor);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const ValueKey('sidebar-project-missing')),
|
||||
matching: find.byIcon(Icons.folder_off_outlined),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byKey(const ValueKey('sidebar-project-missing')),
|
||||
matching: find.text('项目不可用'),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
container.dispose();
|
||||
});
|
||||
|
||||
testWidgets('project errors use a dismissible floating toast', (
|
||||
tester,
|
||||
) async {
|
||||
tester.platformDispatcher.localesTestValue = const [Locale('zh')];
|
||||
addTearDown(tester.platformDispatcher.clearLocalesTestValue);
|
||||
tester.view.physicalSize = const Size(1200, 800);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
conversationRepositoryProvider.overrideWith(
|
||||
(ref) async => EmptyConversationRepository(),
|
||||
),
|
||||
projectsProvider.overrideWith(_ErrorProjects.new),
|
||||
],
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp.router(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
routerConfig: container.read(appRouterProvider),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byIcon(Icons.error_outline), findsOneWidget);
|
||||
expect(find.text('操作失败,请重试'), findsOneWidget);
|
||||
expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200));
|
||||
await tester.tap(find.byIcon(Icons.close));
|
||||
await tester.pump(const Duration(milliseconds: 200));
|
||||
final opacity = tester.widgetList<AnimatedOpacity>(
|
||||
find.byType(AnimatedOpacity),
|
||||
);
|
||||
expect(opacity.any((widget) => widget.opacity == 0), isTrue);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
container.dispose();
|
||||
});
|
||||
}
|
||||
|
||||
class _MemoryTimelineViewSettingsRepository
|
||||
implements TimelineViewSettingsRepository {
|
||||
int loads = 0;
|
||||
|
||||
@override
|
||||
Future<TimelineViewState> load(String projectId, String timelineId) async {
|
||||
loads++;
|
||||
return const TimelineViewState();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(
|
||||
String projectId,
|
||||
String timelineId,
|
||||
SequenceId sequenceId,
|
||||
TimelineSequenceViewState state,
|
||||
) async {}
|
||||
}
|
||||
|
||||
class _EmptyProjects extends Projects {
|
||||
static const project = RecentProject(
|
||||
id: 'empty',
|
||||
name: 'Empty',
|
||||
path: '/Empty.cutdex',
|
||||
);
|
||||
@override
|
||||
Future<ProjectState> build() async => const ProjectState(recent: [project]);
|
||||
|
||||
@override
|
||||
Future<List<TimelineSummary>> listProjectTimelines(
|
||||
RecentProject project,
|
||||
) async => const [];
|
||||
|
||||
@override
|
||||
Future<bool> open(
|
||||
String path, {
|
||||
String? name,
|
||||
String? expectedId,
|
||||
String? timelineId,
|
||||
String? initialTimelineName,
|
||||
bool Function()? isCurrent,
|
||||
}) async {
|
||||
state = AsyncData(state.requireValue.copyWith(activeProject: project));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class _MissingProjects extends Projects {
|
||||
@override
|
||||
Future<ProjectState> build() async => const ProjectState(
|
||||
recent: [
|
||||
RecentProject(
|
||||
id: 'missing',
|
||||
name: 'Missing',
|
||||
path: '/Missing.cutdex',
|
||||
availability: ProjectAvailability.missing,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class _ExpandedMissingProjectSettings
|
||||
implements WorkspaceViewSettingsRepository {
|
||||
@override
|
||||
Future<WorkspaceViewSettingsData> load() async =>
|
||||
const WorkspaceViewSettingsData(hasSavedState: true);
|
||||
|
||||
@override
|
||||
Future<void> save(WorkspaceViewSettingsData settings) async {}
|
||||
}
|
||||
|
||||
class _ErrorProjects extends Projects {
|
||||
@override
|
||||
Future<ProjectState> build() async =>
|
||||
const ProjectState(error: AppFailure(AppErrorCode.operationFailed));
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_location_directory.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
const service = ProjectLocationDirectory();
|
||||
late Directory root;
|
||||
setUp(() async {
|
||||
root = await Directory.systemTemp.createTemp('cutdex-location-');
|
||||
});
|
||||
tearDown(() => root.delete(recursive: true));
|
||||
|
||||
test(
|
||||
'inspection preserves a missing folder, preparation creates it',
|
||||
() async {
|
||||
final folder = Directory('${root.path}/deleted/projects');
|
||||
expect(await service.inspect(folder.path), ProjectLocationStatus.missing);
|
||||
expect(await folder.exists(), isFalse);
|
||||
expect(await root.list().toList(), isEmpty);
|
||||
await service.prepare(folder.path);
|
||||
expect(await service.inspect(folder.path), ProjectLocationStatus.ready);
|
||||
expect(await folder.list().toList(), isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test('a file or broken symlink in the path is never replaced', () async {
|
||||
final file = File('${root.path}/file');
|
||||
await file.writeAsString('keep');
|
||||
expect(
|
||||
await service.inspect('${file.path}/projects'),
|
||||
ProjectLocationStatus.unavailable,
|
||||
);
|
||||
await expectLater(
|
||||
service.prepare('${file.path}/projects'),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(await file.readAsString(), 'keep');
|
||||
if (!Platform.isWindows) {
|
||||
final link = Link('${root.path}/link');
|
||||
await link.create('${root.path}/missing');
|
||||
expect(
|
||||
await service.inspect('${link.path}/projects'),
|
||||
ProjectLocationStatus.unavailable,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing external mount paths are not recreated', () async {
|
||||
if (Platform.isWindows) return;
|
||||
final path =
|
||||
'/Volumes/cutdex-offline-${DateTime.now().microsecondsSinceEpoch}/Projects';
|
||||
expect(await service.inspect(path), ProjectLocationStatus.unavailable);
|
||||
await expectLater(service.prepare(path), throwsStateError);
|
||||
expect(await Directory(path).exists(), isFalse);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_locator.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('locator reports a real directory as available', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-locator-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final location = await ProjectLocator().locate(
|
||||
RecentProject(id: 'id', name: 'Demo', path: root.path),
|
||||
);
|
||||
expect(location.availability, ProjectAvailability.available);
|
||||
expect(location.project.path, root.path);
|
||||
});
|
||||
|
||||
test('locator keeps a missing project record disabled', () async {
|
||||
final location = await ProjectLocator().locate(
|
||||
const RecentProject(
|
||||
id: 'id',
|
||||
name: 'Demo',
|
||||
path: '/definitely-missing/Demo.cutdex',
|
||||
),
|
||||
);
|
||||
expect(location.availability, ProjectAvailability.missing);
|
||||
expect(location.project.availability, ProjectAvailability.missing);
|
||||
});
|
||||
|
||||
test(
|
||||
'recent project storage preserves paths, order and last timelines',
|
||||
() async {
|
||||
final database = AppDatabase(NativeDatabase.memory());
|
||||
addTearDown(database.close);
|
||||
final repository = DriftRecentProjectsRepository(database);
|
||||
const record = RecentProject(
|
||||
id: 'id',
|
||||
name: 'Demo',
|
||||
path: '/Demo.cutdex',
|
||||
);
|
||||
await repository.save([record]);
|
||||
await repository.rememberTimeline(record.id, 'timeline');
|
||||
expect(await repository.load(), [record]);
|
||||
expect(await repository.lastTimeline(record.id), 'timeline');
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/runtime/contracts.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('timeline switch does not expose the previous session', (
|
||||
tester,
|
||||
) async {
|
||||
final f = (await tester.runAsync(
|
||||
() =>
|
||||
createPreviewFixture(Uri.file('/test/audio.wav'), mediaType: 'audio'),
|
||||
))!;
|
||||
addTearDown(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
final pending = Completer<EditorTimelineSession>();
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
'project',
|
||||
'first',
|
||||
).overrideWith((ref) async => f.timeline),
|
||||
editorTimelineProvider(
|
||||
'project',
|
||||
'second',
|
||||
).overrideWith((ref) => pending.future),
|
||||
],
|
||||
);
|
||||
addTearDown(container.dispose);
|
||||
|
||||
Widget panel(String timelineId) => UncontrolledProviderScope(
|
||||
container: container,
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 280,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: 'project',
|
||||
timelineId: timelineId,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.pumpWidget(panel('first'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('项目属性'), findsOneWidget);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.byType(SingleChildScrollView),
|
||||
matching: find.byType(ShaderMask),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.descendant(
|
||||
of: find.byType(EditorPropertiesPanel),
|
||||
matching: find.byType(ClipRRect),
|
||||
),
|
||||
findsNothing,
|
||||
);
|
||||
|
||||
await tester.pumpWidget(panel('second'));
|
||||
await tester.pump();
|
||||
expect(find.text('项目属性'), findsNothing);
|
||||
expect(find.byKey(const Key('properties-pending')), findsOneWidget);
|
||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||
|
||||
pending.complete(f.timeline);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('项目属性'), findsOneWidget);
|
||||
expect(find.byType(CircularProgressIndicator), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('project properties follow edits and return after deselection', (
|
||||
tester,
|
||||
) async {
|
||||
final f = (await tester.runAsync(
|
||||
() =>
|
||||
createPreviewFixture(Uri.file('/test/audio.wav'), mediaType: 'audio'),
|
||||
))!;
|
||||
await tester.pumpWidget(
|
||||
ProviderScope(
|
||||
overrides: [
|
||||
editorTimelineProvider(
|
||||
'project',
|
||||
'project',
|
||||
).overrideWith((ref) async => f.timeline),
|
||||
],
|
||||
child: MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(
|
||||
body: SizedBox(
|
||||
width: 280,
|
||||
child: EditorPropertiesPanel(
|
||||
projectId: 'project',
|
||||
timelineId: 'project',
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('项目属性'), findsOneWidget);
|
||||
expect(find.text('Preview test'), findsOneWidget);
|
||||
expect(find.text('1080 × 1920 px'), findsOneWidget);
|
||||
expect(find.text('30 fps'), findsOneWidget);
|
||||
expect(find.text('2.00 秒'), findsOneWidget);
|
||||
await tester.tap(find.byKey(const ValueKey('project-settings-edit')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('项目设置'), findsOneWidget);
|
||||
await tester.enterText(find.byKey(const ValueKey('project-width')), '0');
|
||||
await tester.tap(find.byKey(const ValueKey('project-settings-save')));
|
||||
await tester.pump();
|
||||
expect(find.text('请输入 1–16384 的整数'), findsOneWidget);
|
||||
expect(f.timeline.canvas, const ProjectCanvas(1080, 1920));
|
||||
await tester.enterText(find.byKey(const ValueKey('project-width')), '3840');
|
||||
await tester.enterText(
|
||||
find.byKey(const ValueKey('project-height')),
|
||||
'2160',
|
||||
);
|
||||
await tester.tap(find.byKey(const ValueKey('project-frame-rate')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('29.97 fps').last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('project-color-space')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text('HDR · Rec.2020 PQ').last);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.byKey(const ValueKey('project-settings-save')));
|
||||
await tester.runAsync(f.timeline.flush);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('项目设置'), findsNothing);
|
||||
expect(find.text('3840 × 2160 px'), findsOneWidget);
|
||||
expect(find.text('29.97 fps'), findsOneWidget);
|
||||
expect(f.timeline.projectColorSpace, RenderColorSpace.rec2020PQ);
|
||||
expect(
|
||||
f.timeline.view(SequenceId('one')).format.frameDuration,
|
||||
RationalTime(1001, 30000),
|
||||
);
|
||||
f.timeline.view(SequenceId('one')).undo();
|
||||
await tester.runAsync(f.timeline.flush);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('1080 × 1920 px'), findsOneWidget);
|
||||
expect(find.text('30 fps'), findsOneWidget);
|
||||
expect(f.timeline.projectColorSpace, RenderColorSpace.rec709);
|
||||
await tester.tap(find.byKey(const ValueKey('project-settings-edit')));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.enterText(find.byKey(const ValueKey('project-width')), '1280');
|
||||
await tester.tap(find.text('取消'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(f.timeline.canvas, const ProjectCanvas(1080, 1920));
|
||||
f.timeline.commands.setCanvas(ProjectCanvas.widescreen);
|
||||
await tester.pump();
|
||||
expect(find.text('1920 × 1080 px'), findsOneWidget);
|
||||
final view = f.timeline.view(SequenceId('one'));
|
||||
view.setSelection([
|
||||
view.version.kernelVersion.query().elementById(ElementId('clip'))!,
|
||||
]);
|
||||
await tester.pump();
|
||||
expect(find.text('项目属性'), findsNothing);
|
||||
expect(find.text('Preview clip'), findsNothing);
|
||||
view.clearSelection();
|
||||
await tester.pump();
|
||||
expect(find.text('项目属性'), findsOneWidget);
|
||||
f.timeline.selectSequence(SequenceId('empty'));
|
||||
await tester.pump();
|
||||
expect(find.text('0.00 秒'), findsOneWidget);
|
||||
expect(tester.takeException(), isNull);
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
import 'support/creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/editor/commands.dart';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/background_task_registry.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'recent project sessions are reused and cache eviction closes old sessions',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-warm-projects-',
|
||||
);
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final timelines = await workspace.open(
|
||||
'${root.path}/One.cutdex',
|
||||
name: 'One',
|
||||
);
|
||||
final firstId = workspace.project!.info.id;
|
||||
final document = await workspace.loadTimeline(
|
||||
firstId,
|
||||
timelines.single.id,
|
||||
);
|
||||
final session = await workspace.openTimelineSession(firstId, document);
|
||||
await workspace.open('${root.path}/Two.cutdex', name: 'Two');
|
||||
await workspace.open('${root.path}/One.cutdex', expectedId: firstId);
|
||||
final restored = await workspace.openTimelineSession(firstId, document);
|
||||
expect(restored, same(session));
|
||||
expect(restored.acceptsEdits, isTrue);
|
||||
await workspace.open('${root.path}/Two.cutdex');
|
||||
await workspace.open('${root.path}/Three.cutdex', name: 'Three');
|
||||
await workspace.open('${root.path}/Four.cutdex', name: 'Four');
|
||||
expect(workspace.cachedProjectIds.length, 3);
|
||||
expect(workspace.cachedProjectIds, isNot(contains(firstId)));
|
||||
expect(session.acceptsEdits, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test('superseded project loading preserves the current project', () async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-cancel-project-',
|
||||
);
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await workspace.open('${root.path}/One.cutdex', name: 'One');
|
||||
final firstId = workspace.project!.info.id;
|
||||
var checks = 0;
|
||||
await expectLater(
|
||||
workspace.open(
|
||||
'${root.path}/Two.cutdex',
|
||||
name: 'Two',
|
||||
isCurrent: () => ++checks < 2,
|
||||
),
|
||||
throwsA(isA<ProjectOpenSuperseded>()),
|
||||
);
|
||||
expect(workspace.project!.info.id, firstId);
|
||||
});
|
||||
|
||||
test('default timeline is pinned and deleting a prepared timeline clears its session', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-timeline-menu-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final path = '${root.path}/Project.cutdex';
|
||||
final initial = await workspace.open(path, name: 'Project');
|
||||
expect(initial.single.pinned, isTrue);
|
||||
final project = RecentProject(
|
||||
id: workspace.project!.info.id,
|
||||
name: 'Project',
|
||||
path: path,
|
||||
);
|
||||
final created = await workspace.createPreparedTimeline('Second');
|
||||
final pinned = await workspace.setTimelinePinned(
|
||||
project,
|
||||
created.document.id,
|
||||
true,
|
||||
);
|
||||
expect(pinned.map((item) => item.pinned), [isTrue, isTrue]);
|
||||
final remaining = await workspace.deleteTimeline(
|
||||
project,
|
||||
created.document.id,
|
||||
);
|
||||
expect(remaining.map((item) => item.id), [initial.single.id]);
|
||||
expect(
|
||||
workspace.cachedTimelineSession(project.id, created.document.id),
|
||||
isNull,
|
||||
);
|
||||
});
|
||||
|
||||
test('removed assets retain references and reimport restores the original record', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-asset-menu-');
|
||||
var workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await workspace.open('${root.path}/Project.cutdex', name: 'Project');
|
||||
final project = workspace.project!;
|
||||
final sourceFile = await File('${root.path}/source.mov')
|
||||
.writeAsString('original');
|
||||
final source = File(await sourceFile.resolveSymbolicLinks());
|
||||
await project.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'asset',
|
||||
name: 'Original',
|
||||
storage: AssetStorage.external,
|
||||
location: source.uri.toString(),
|
||||
metadata: {'kind': 'video'},
|
||||
accessData: {'test': 'retained'},
|
||||
),
|
||||
);
|
||||
final renamed = (await workspace.editAsset(
|
||||
project.info.id,
|
||||
'asset',
|
||||
name: ' Renamed ',
|
||||
)).single;
|
||||
expect(renamed.name, 'Renamed');
|
||||
expect(renamed.location, source.uri.toString());
|
||||
expect(renamed.accessData['test'], 'retained');
|
||||
await expectLater(
|
||||
workspace.editAsset('other', 'asset', name: 'wrong'),
|
||||
throwsA(isA<CommandRejected>().having((e) => e.code, 'code', 'closed')),
|
||||
);
|
||||
await project.saveCollection(
|
||||
AssetCollection(
|
||||
id: 'collection',
|
||||
name: 'Collection',
|
||||
assetIds: ['asset'],
|
||||
),
|
||||
);
|
||||
final projectId = project.info.id;
|
||||
expect(await workspace.editAsset(projectId, 'asset'), isEmpty);
|
||||
expect((await project.listAssets()).single.id, 'asset');
|
||||
expect(
|
||||
await project.resolveAsset((await project.listAssets()).single),
|
||||
source.uri,
|
||||
);
|
||||
await workspace.close();
|
||||
workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
await workspace.open('${root.path}/Project.cutdex');
|
||||
expect(await workspace.listAssets(projectId), isEmpty);
|
||||
final restored = await workspace.importExternalMedia(projectId, [
|
||||
ExternalMediaFile(path: source.path),
|
||||
ExternalMediaFile(path: source.path),
|
||||
]);
|
||||
expect(restored.added, 1);
|
||||
expect(restored.duplicates, 1);
|
||||
expect(restored.assets.single.id, 'asset');
|
||||
expect(restored.assets.single.name, 'Renamed');
|
||||
expect(restored.assets.single.accessData['test'], 'retained');
|
||||
expect((await workspace.project!.listAssets()).length, 1);
|
||||
await workspace.project!.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'unused',
|
||||
name: 'Unused',
|
||||
storage: AssetStorage.external,
|
||||
location: source.uri.toString(),
|
||||
),
|
||||
);
|
||||
final remaining = await workspace.editAsset(projectId, 'unused');
|
||||
expect(remaining.map((asset) => asset.id), ['asset']);
|
||||
expect(await source.readAsString(), 'original');
|
||||
});
|
||||
test(
|
||||
'project contains multiple durable timelines and releases its lock',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-app-test-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final path = '${root.path}/Project.cutdex';
|
||||
expect(await workspace.open(path, name: '项目'), hasLength(1));
|
||||
final id = workspace.project!.info.id;
|
||||
await workspace.createTimeline('时间线一');
|
||||
final timelines = await workspace.createTimeline('时间线二');
|
||||
expect(timelines.map((item) => item.name), [
|
||||
'Timeline 1',
|
||||
'时间线一',
|
||||
'时间线二',
|
||||
]);
|
||||
final timeline = await workspace.loadTimeline(id, timelines.first.id);
|
||||
expect(timeline.revision, greaterThan(0));
|
||||
expect(timeline.sequences.single.name, 'Main sequence');
|
||||
expect(timeline.sequences.single.elements, isEmpty);
|
||||
expect(timeline.defaultSequenceId, timeline.sequences.single.id);
|
||||
await workspace.close();
|
||||
|
||||
final reopened = await ProjectFile.open(Directory(path));
|
||||
try {
|
||||
expect(reopened.info.id, id);
|
||||
expect(await reopened.listTimelines(), hasLength(3));
|
||||
} finally {
|
||||
await reopened.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('prepared timeline is cached before it is published', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-prepared-');
|
||||
final registry = BackgroundTaskRegistry();
|
||||
final workspace = ProjectWorkspace(
|
||||
creationNames: testCreationNames,
|
||||
backgroundTasks: registry,
|
||||
);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
registry.dispose();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
await workspace.open('${root.path}/Project.cutdex', name: 'Project');
|
||||
final projectId = workspace.project!.info.id;
|
||||
|
||||
final created = await workspace.createPreparedTimeline('Timeline 2');
|
||||
|
||||
expect(created.timelines.last.id, created.document.id);
|
||||
expect(
|
||||
workspace.cachedTimelineSession(projectId, created.document.id),
|
||||
same(created.session),
|
||||
);
|
||||
expect(registry.entries.map((entry) => entry.timelineId), [
|
||||
created.document.id,
|
||||
]);
|
||||
await workspace.close();
|
||||
expect(registry.entries, isEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'failed opens preserve current project and successful switch caches it',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-app-test-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final path = '${root.path}/One.cutdex';
|
||||
await workspace.open(path, name: 'One');
|
||||
final id = workspace.project!.info.id;
|
||||
await expectLater(
|
||||
workspace.open('${root.path}/missing'),
|
||||
throwsA(isA<FileSystemException>()),
|
||||
);
|
||||
expect(workspace.project!.info.id, id);
|
||||
await expectLater(
|
||||
workspace.open(path, expectedId: 'wrong'),
|
||||
throwsStateError,
|
||||
);
|
||||
expect(workspace.project!.info.id, id);
|
||||
await expectLater(
|
||||
workspace.open(path, name: 'Overwrite'),
|
||||
throwsA(isA<ProjectFileException>()),
|
||||
);
|
||||
expect(workspace.project!.info.id, id);
|
||||
await workspace.open('${root.path}/Two.cutdex', name: 'Two');
|
||||
expect(workspace.cachedProjectIds, contains(id));
|
||||
await workspace.open(path, expectedId: id);
|
||||
expect(workspace.project!.info.id, id);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'timeline inspection and opening the same project are serialized',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-app-race-');
|
||||
final creator = ProjectWorkspace(creationNames: testCreationNames);
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await creator.close();
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final path = '${root.path}/Project.cutdex';
|
||||
await creator.open(path, name: 'Project');
|
||||
await creator.createTimeline('Timeline');
|
||||
final id = creator.project!.info.id;
|
||||
await creator.close();
|
||||
|
||||
final inspected = workspace.listProjectTimelines(path, expectedId: id);
|
||||
final opened = workspace.open(path, expectedId: id);
|
||||
|
||||
expect((await inspected).map((item) => item.name), contains('Timeline'));
|
||||
expect((await opened).map((item) => item.name), contains('Timeline'));
|
||||
expect(workspace.project!.info.id, id);
|
||||
},
|
||||
);
|
||||
|
||||
test('close waits for accepted creation and prevents later work', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-app-test-');
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
final path = '${root.path}/Queued.cutdex';
|
||||
final opening = workspace.open(path, name: 'Queued');
|
||||
final creating = workspace.createTimeline('Saved before close');
|
||||
final closing = workspace.close();
|
||||
expect(workspace.close(), same(closing));
|
||||
await opening;
|
||||
await creating;
|
||||
await closing;
|
||||
await expectLater(workspace.createTimeline('Late'), throwsStateError);
|
||||
final file = await ProjectFile.open(Directory(path));
|
||||
try {
|
||||
expect(
|
||||
(await file.listTimelines()).map((item) => item.name),
|
||||
contains('Saved before close'),
|
||||
);
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'leased timeline survives project switch and is reused on return',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-lease-test-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final firstPath = '${root.path}/First.cutdex';
|
||||
final timelines = await workspace.open(firstPath, name: 'First');
|
||||
final projectId = workspace.project!.info.id;
|
||||
final document = await workspace.loadTimeline(
|
||||
projectId,
|
||||
timelines.single.id,
|
||||
);
|
||||
final session = await workspace.openTimelineSession(projectId, document);
|
||||
final lease = await workspace.leaseTimeline(projectId, document.id);
|
||||
|
||||
await workspace.open('${root.path}/Second.cutdex', name: 'Second');
|
||||
expect(session.acceptsEdits, isTrue);
|
||||
await lease.validate();
|
||||
expect(
|
||||
await workspace.listProjectTimelines(firstPath, expectedId: projectId),
|
||||
hasLength(1),
|
||||
);
|
||||
|
||||
await workspace.open(firstPath, expectedId: projectId);
|
||||
final reopened = await workspace.loadTimeline(projectId, document.id);
|
||||
final returned = await workspace.openTimelineSession(projectId, reopened);
|
||||
expect(identical(returned, session), isTrue);
|
||||
final manifest = File('$firstPath/manifest.json');
|
||||
final backup = await manifest.rename('$firstPath/manifest.json.backup');
|
||||
await expectLater(lease.validate(), throwsA(isA<FileSystemException>()));
|
||||
await backup.rename(manifest.path);
|
||||
await lease.release();
|
||||
expect(returned.acceptsEdits, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
test('leased timeline survives switching to another timeline', () async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-timeline-lease-',
|
||||
);
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final timelines = await workspace.open(
|
||||
'${root.path}/Project.cutdex',
|
||||
name: 'Project',
|
||||
);
|
||||
final id = workspace.project!.info.id;
|
||||
final firstDocument = await workspace.loadTimeline(id, timelines.single.id);
|
||||
final firstSession = await workspace.openTimelineSession(id, firstDocument);
|
||||
final lease = await workspace.leaseTimeline(id, firstDocument.id);
|
||||
final added = await workspace.createTimeline('Second');
|
||||
final secondId = added
|
||||
.singleWhere((item) => item.id != firstDocument.id)
|
||||
.id;
|
||||
final secondDocument = await workspace.loadTimeline(id, secondId);
|
||||
final secondSession = await workspace.openTimelineSession(
|
||||
id,
|
||||
secondDocument,
|
||||
);
|
||||
expect(firstSession.acceptsEdits, isTrue);
|
||||
expect(secondSession.acceptsEdits, isTrue);
|
||||
await lease.validate();
|
||||
await lease.release();
|
||||
expect(firstSession.acceptsEdits, isTrue);
|
||||
expect(secondSession.acceptsEdits, isTrue);
|
||||
final returnedDocument = await workspace.loadTimeline(id, firstDocument.id);
|
||||
final returned = await workspace.openTimelineSession(id, returnedDocument);
|
||||
expect(identical(returned, firstSession), isTrue);
|
||||
});
|
||||
|
||||
test(
|
||||
'timeline switch keeps old UI notifiers alive until project close',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-timeline-ui-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final timelines = await workspace.open(
|
||||
'${root.path}/Project.cutdex',
|
||||
name: 'Project',
|
||||
);
|
||||
final id = workspace.project!.info.id;
|
||||
final first = await workspace.loadTimeline(id, timelines.single.id);
|
||||
final session = await workspace.openTimelineSession(id, first);
|
||||
final releaseViews = session.retainViews();
|
||||
final tasks = session.audioGainPreview;
|
||||
final removals = session.view(
|
||||
first.defaultSequenceId ?? first.sequences.first.id,
|
||||
);
|
||||
|
||||
final added = await workspace.createTimeline('Second');
|
||||
final secondId = added.singleWhere((item) => item.id != first.id).id;
|
||||
await workspace.loadTimeline(id, secondId);
|
||||
|
||||
expect(session.acceptsEdits, isTrue);
|
||||
void listener() {}
|
||||
expect(() => tasks.addListener(listener), returnsNormally);
|
||||
expect(() => removals.addListener(listener), returnsNormally);
|
||||
tasks.removeListener(listener);
|
||||
removals.removeListener(listener);
|
||||
releaseViews();
|
||||
expect(() => tasks.addListener(listener), returnsNormally);
|
||||
tasks.removeListener(listener);
|
||||
await workspace.open('${root.path}/Other.cutdex', name: 'Other');
|
||||
expect(session.acceptsEdits, isTrue);
|
||||
await workspace.close();
|
||||
expect(session.acceptsEdits, isFalse);
|
||||
expect(() => tasks.addListener(listener), throwsAssertionError);
|
||||
expect(() => removals.addListener(listener), throwsAssertionError);
|
||||
},
|
||||
);
|
||||
|
||||
test('unleased sessions stay warm until workspace close', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-session-owner-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final timelines = await workspace.open(
|
||||
'${root.path}/First.cutdex',
|
||||
name: 'First',
|
||||
);
|
||||
final id = workspace.project!.info.id;
|
||||
final first = await workspace.loadTimeline(id, timelines.single.id);
|
||||
final firstSession = await workspace.openTimelineSession(id, first);
|
||||
final added = await workspace.createTimeline('Second');
|
||||
final secondId = added.singleWhere((item) => item.id != first.id).id;
|
||||
final second = await workspace.loadTimeline(id, secondId);
|
||||
final secondSession = await workspace.openTimelineSession(id, second);
|
||||
|
||||
await workspace.open('${root.path}/Other.cutdex', name: 'Other');
|
||||
expect(firstSession.acceptsEdits, isTrue);
|
||||
await workspace.close();
|
||||
expect(firstSession.acceptsEdits, isFalse);
|
||||
expect(secondSession.acceptsEdits, isFalse);
|
||||
});
|
||||
|
||||
test('failed timeline selection leaves cached sessions usable', () async {
|
||||
final root = await Directory.systemTemp.createTemp('cutdex-timeline-fail-');
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
addTearDown(() async {
|
||||
await workspace.close();
|
||||
await root.delete(recursive: true);
|
||||
});
|
||||
final timelines = await workspace.open(
|
||||
'${root.path}/Project.cutdex',
|
||||
name: 'Project',
|
||||
);
|
||||
final id = workspace.project!.info.id;
|
||||
final document = await workspace.loadTimeline(id, timelines.single.id);
|
||||
final session = await workspace.openTimelineSession(id, document);
|
||||
|
||||
await expectLater(
|
||||
workspace.loadTimeline(id, 'missing'),
|
||||
throwsA(isA<ProjectFileException>()),
|
||||
);
|
||||
expect(session.acceptsEdits, isTrue);
|
||||
final selected = await workspace.loadTimeline(id, document.id);
|
||||
expect(
|
||||
identical(await workspace.openTimelineSession(id, selected), session),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/properties/audio_properties.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime/contracts.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'support/preview_fixture.dart';
|
||||
|
||||
void main() {
|
||||
for (final mode in [
|
||||
'seek',
|
||||
'draft seek',
|
||||
'key',
|
||||
'invalid key',
|
||||
'precision',
|
||||
]) {
|
||||
testWidgets('audio property consistency: $mode', (tester) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true),
|
||||
))!;
|
||||
final seq = SequenceId('one');
|
||||
final id = ElementId('clip');
|
||||
final view = f.timeline.view(seq);
|
||||
ElementRecord record() {
|
||||
final q = view.version.kernelVersion.query();
|
||||
return q.element(q.elementById(id)!);
|
||||
}
|
||||
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penLight,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 225,
|
||||
child: AudioProperties(
|
||||
session: f.timeline,
|
||||
sequence: seq,
|
||||
clip: record(),
|
||||
hasAudio: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (mode == 'seek') {
|
||||
await tester.tap(find.byKey(const Key('audio-key')));
|
||||
await tester.pump();
|
||||
final slider = tester.widget<AppSlider>(find.byType(AppSlider));
|
||||
slider.onChangeStart!(.5);
|
||||
slider.onChanged!(.8);
|
||||
final before = view.version.kernelVersion;
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
expect(
|
||||
tester.widget<TextField>(find.byType(TextField)).controller!.text,
|
||||
'0.0',
|
||||
);
|
||||
tester.widget<AppSlider>(find.byType(AppSlider)).onChanged!(.9);
|
||||
tester.widget<AppSlider>(find.byType(AppSlider)).onChangeEnd!(.8);
|
||||
await tester.pump();
|
||||
final curve = record().parameters![ClipAudioGain.gainId]!;
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(f.timeline.audioGainPreview.value, isNull);
|
||||
expect(curve.keyframeAt(TimelineClock.ticksPerSecond), isNull);
|
||||
expect(curve.keyframeAt(0)?.value, 0);
|
||||
} else if (mode == 'draft seek') {
|
||||
final before = view.version.kernelVersion;
|
||||
await tester.enterText(find.byType(TextField), '-12');
|
||||
view.seekTo(TimelineClock.ticksPerSecond);
|
||||
await tester.pump();
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await tester.pump();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(ClipAudioGain.fromRecord(record()).db, 0);
|
||||
} else if (mode == 'invalid key') {
|
||||
final before = view.version.kernelVersion;
|
||||
await tester.enterText(find.byType(TextField), '13');
|
||||
await tester.tap(find.byKey(const Key('audio-key')));
|
||||
await tester.pump();
|
||||
expect(view.version.kernelVersion, same(before));
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length ?? 0, 0);
|
||||
} else if (mode == 'key') {
|
||||
await tester.enterText(find.byType(TextField), '-12');
|
||||
await tester.tap(find.byKey(const Key('audio-key')));
|
||||
await tester.pump();
|
||||
final curve = record().parameters![ClipAudioGain.gainId]!;
|
||||
expect(curve.keyframeAt(0)?.value, -12);
|
||||
expect(
|
||||
tester.widget<TextField>(find.byType(TextField)).controller!.text,
|
||||
'-12.0',
|
||||
);
|
||||
view.undo();
|
||||
await tester.pump();
|
||||
expect(record().parameters?[ClipAudioGain.gainId]?.length, 0);
|
||||
expect(ClipAudioGain.fromRecord(record()).db, -12);
|
||||
view.undo();
|
||||
await tester.pump();
|
||||
expect(ClipAudioGain.fromRecord(record()).db, 0);
|
||||
} else {
|
||||
for (final (input, expected) in [
|
||||
('0.04', 0.0),
|
||||
('-0.04', 0.0),
|
||||
('0.06', .1),
|
||||
('-0.06', -.1),
|
||||
('12', 12.0),
|
||||
('-90', -90.0),
|
||||
]) {
|
||||
await tester.enterText(find.byType(TextField), input);
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await tester.pump();
|
||||
expect(ClipAudioGain.fromRecord(record()).db, expected);
|
||||
expect(
|
||||
tester.widget<TextField>(find.byType(TextField)).controller!.text,
|
||||
expected.toStringAsFixed(1),
|
||||
);
|
||||
}
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
});
|
||||
}
|
||||
testWidgets('canvas entry points share integer bounds and undo', (
|
||||
tester,
|
||||
) async {
|
||||
final f = (await tester.runAsync(
|
||||
() => createPreviewFixture(Uri.file('/test/video.mov')),
|
||||
))!;
|
||||
final seq = SequenceId('one');
|
||||
final before = f.timeline.version;
|
||||
for (final size in [
|
||||
const ProjectCanvas(0, 1080),
|
||||
const ProjectCanvas(16385, 1080),
|
||||
const ProjectCanvas(1920, 1080.5),
|
||||
const ProjectCanvas(double.infinity, 1080),
|
||||
]) {
|
||||
expect(
|
||||
() => f.timeline.commands.setCanvas(size),
|
||||
throwsA(isA<CommandRejected>()),
|
||||
);
|
||||
expect(
|
||||
() => f.timeline.setProjectProperties(
|
||||
sequence: seq,
|
||||
canvas: size,
|
||||
frameDuration: TimelineFormat.fps24.frameDuration,
|
||||
colorSpace: RenderColorSpace.rec709,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
expect(f.timeline.version, before);
|
||||
}
|
||||
final original = f.timeline.canvas;
|
||||
f.timeline.commands.setCanvas(const ProjectCanvas(1, 16384));
|
||||
expect(f.timeline.canvas, const ProjectCanvas(1, 16384));
|
||||
f.timeline.view(seq).undo();
|
||||
expect(f.timeline.canvas, original);
|
||||
await tester.runAsync(() async {
|
||||
await f.workspace.close();
|
||||
await f.directory.delete(recursive: true);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import '../integration_test/support/saved_edit_validation.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
for (final changed in [false, true]) {
|
||||
test(
|
||||
'public reopen validation ${changed ? 'detects changed edits' : 'retains saved edits'}',
|
||||
() async {
|
||||
final root = await Directory.systemTemp.createTemp(
|
||||
'cutdex-saved-edits-',
|
||||
);
|
||||
addTearDown(() => root.delete(recursive: true));
|
||||
final directory = Directory('${root.path}/Test.cutdex');
|
||||
final sequence = SequenceId('sequence');
|
||||
final project = await ProjectFile.create(
|
||||
directory,
|
||||
name: 'Test',
|
||||
initialTimeline: TimelineDocument(
|
||||
id: 'timeline',
|
||||
name: 'Timeline',
|
||||
defaultSequenceId: sequence,
|
||||
sequences: [
|
||||
TimelineDto(
|
||||
id: sequence,
|
||||
format: TimelineFormat.fps24,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(
|
||||
id: StorylineId('primary'),
|
||||
elementIds: const [],
|
||||
),
|
||||
],
|
||||
elements: const [],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
final session = EditorSession(
|
||||
document: await project.loadTimeline('timeline'),
|
||||
persistence: await project.openTimelineSaveSession('timeline'),
|
||||
);
|
||||
addTearDown(project.close);
|
||||
addTearDown(session.close);
|
||||
session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!);
|
||||
await session.flush();
|
||||
final validation = SavedEditValidation();
|
||||
await validation.capture(directory.path, 'timeline', session, sequence);
|
||||
if (changed) {
|
||||
session.commands.setCanvas(ProjectCanvasPresets.values['16:9']!);
|
||||
}
|
||||
await session.close();
|
||||
await project.close();
|
||||
var verified = 0;
|
||||
final check = validation.verify(
|
||||
wait: Future<void>.delayed,
|
||||
onVerified: (path, id, edits) {
|
||||
expect(path, directory.path);
|
||||
expect(id, 'timeline');
|
||||
expect(edits['canvas'], containsPair('width', 1440));
|
||||
verified++;
|
||||
},
|
||||
);
|
||||
if (changed) {
|
||||
await expectLater(check, throwsA(isA<TestFailure>()));
|
||||
expect(verified, 0);
|
||||
} else {
|
||||
await check;
|
||||
expect(verified, 1);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/settings/settings_operation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'duplicate submissions are suppressed and failures permit a retry',
|
||||
() async {
|
||||
final container = ProviderContainer();
|
||||
addTearDown(container.dispose);
|
||||
final provider = settingsOperationProvider('save');
|
||||
final subscription = container.listen(provider, (_, _) {});
|
||||
addTearDown(subscription.close);
|
||||
final operation = container.read(provider.notifier);
|
||||
final release = Completer<void>();
|
||||
var calls = 0;
|
||||
final first = operation.run(() async {
|
||||
calls++;
|
||||
await release.future;
|
||||
throw StateError('write failed');
|
||||
});
|
||||
expect(container.read(provider).isLoading, isTrue);
|
||||
expect(
|
||||
await operation.run(() async {
|
||||
calls++;
|
||||
}),
|
||||
isFalse,
|
||||
);
|
||||
release.complete();
|
||||
expect(await first, isFalse);
|
||||
expect(container.read(provider).hasError, isTrue);
|
||||
expect(calls, 1);
|
||||
expect(
|
||||
await operation.run(() async {
|
||||
calls++;
|
||||
}),
|
||||
isTrue,
|
||||
);
|
||||
expect(container.read(provider).hasError, isFalse);
|
||||
expect(calls, 2);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/settings/appearance_settings.dart';
|
||||
import 'package:cutdex/features/settings/language_settings.dart';
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
_testSettings<AppAppearance>(
|
||||
name: 'appearance',
|
||||
initial: AppAppearance.system,
|
||||
first: AppAppearance.penLight,
|
||||
second: AppAppearance.penDark,
|
||||
container: (store) => ProviderContainer(
|
||||
overrides: [
|
||||
appearanceSettingsRepositoryProvider.overrideWithValue(
|
||||
_AppearanceRepository(store),
|
||||
),
|
||||
],
|
||||
),
|
||||
load: (container) => container.read(appearanceSettingsProvider.future),
|
||||
value: (container) =>
|
||||
container.read(appearanceSettingsProvider).requireValue,
|
||||
save: (container, value) =>
|
||||
container.read(appearanceSettingsProvider.notifier).setMode(value),
|
||||
);
|
||||
_testSettings<AppLanguage>(
|
||||
name: 'language',
|
||||
initial: AppLanguage.system,
|
||||
first: AppLanguage.english,
|
||||
second: AppLanguage.simplifiedChinese,
|
||||
container: (store) => ProviderContainer(
|
||||
overrides: [
|
||||
languageSettingsRepositoryProvider.overrideWithValue(
|
||||
_LanguageRepository(store),
|
||||
),
|
||||
],
|
||||
),
|
||||
load: (container) => container.read(languageSettingsProvider.future),
|
||||
value: (container) => container.read(languageSettingsProvider).requireValue,
|
||||
save: (container, value) =>
|
||||
container.read(languageSettingsProvider.notifier).setLanguage(value),
|
||||
);
|
||||
}
|
||||
|
||||
void _testSettings<T>({
|
||||
required String name,
|
||||
required T initial,
|
||||
required T first,
|
||||
required T second,
|
||||
required ProviderContainer Function(_Store<T>) container,
|
||||
required Future<T> Function(ProviderContainer) load,
|
||||
required T Function(ProviderContainer) value,
|
||||
required Future<void> Function(ProviderContainer, T) save,
|
||||
}) {
|
||||
test('$name saves in order and publishes only committed values', () async {
|
||||
final store = _Store(initial)..writeGate = Completer<void>();
|
||||
final scope = container(store);
|
||||
addTearDown(scope.dispose);
|
||||
await load(scope);
|
||||
final firstSave = save(scope, first);
|
||||
await store.started.future;
|
||||
final secondSave = save(scope, second);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(store.writes, [first]);
|
||||
expect(value(scope), initial);
|
||||
store.writeGate!.complete();
|
||||
await Future.wait([firstSave, secondSave]);
|
||||
expect(store.writes, [first, second]);
|
||||
expect(store.value, second);
|
||||
expect(value(scope), second);
|
||||
});
|
||||
|
||||
test('$name can save again after a failed write', () async {
|
||||
final store = _Store(initial)..failWrites = true;
|
||||
final scope = container(store);
|
||||
addTearDown(scope.dispose);
|
||||
await load(scope);
|
||||
await expectLater(save(scope, first), throwsStateError);
|
||||
expect(value(scope), initial);
|
||||
expect(store.value, initial);
|
||||
store.failWrites = false;
|
||||
await save(scope, second);
|
||||
expect(value(scope), second);
|
||||
expect(store.value, second);
|
||||
});
|
||||
|
||||
test('$name waits for initial load before saving', () async {
|
||||
final store = _Store(initial)..loadGate = Completer<void>();
|
||||
final scope = container(store);
|
||||
addTearDown(scope.dispose);
|
||||
final initialLoad = load(scope);
|
||||
final pending = save(scope, first);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(store.writes, isEmpty);
|
||||
store.loadGate!.complete();
|
||||
await initialLoad;
|
||||
await pending;
|
||||
expect(value(scope), first);
|
||||
expect(store.value, first);
|
||||
});
|
||||
|
||||
test('$name finishes an in-flight save safely after disposal', () async {
|
||||
final store = _Store(initial)..writeGate = Completer<void>();
|
||||
final scope = container(store);
|
||||
await load(scope);
|
||||
final firstSave = save(scope, first);
|
||||
await store.started.future;
|
||||
final queuedSave = save(scope, second);
|
||||
scope.dispose();
|
||||
store.writeGate!.complete();
|
||||
await Future.wait([firstSave, queuedSave]);
|
||||
expect(store.writes, [first]);
|
||||
expect(store.value, first);
|
||||
});
|
||||
}
|
||||
|
||||
class _Store<T> {
|
||||
_Store(this.value);
|
||||
|
||||
T value;
|
||||
final writes = <T>[];
|
||||
final started = Completer<void>();
|
||||
Completer<void>? loadGate;
|
||||
Completer<void>? writeGate;
|
||||
bool failWrites = false;
|
||||
|
||||
Future<T> load() async {
|
||||
final snapshot = value;
|
||||
await loadGate?.future;
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
Future<void> save(T next) async {
|
||||
writes.add(next);
|
||||
if (!started.isCompleted) started.complete();
|
||||
await writeGate?.future;
|
||||
if (failWrites) throw StateError('Storage unavailable');
|
||||
value = next;
|
||||
}
|
||||
}
|
||||
|
||||
class _AppearanceRepository implements AppearanceSettingsRepository {
|
||||
_AppearanceRepository(this.store);
|
||||
final _Store<AppAppearance> store;
|
||||
|
||||
@override
|
||||
Future<AppAppearance> load() => store.load();
|
||||
@override
|
||||
Future<void> save(AppAppearance value) => store.save(value);
|
||||
}
|
||||
|
||||
class _LanguageRepository implements LanguageSettingsRepository {
|
||||
_LanguageRepository(this.store);
|
||||
final _Store<AppLanguage> store;
|
||||
|
||||
@override
|
||||
Future<AppLanguage> load() => store.load();
|
||||
@override
|
||||
Future<void> save(AppLanguage value) => store.save(value);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
final asset = AssetDocument(
|
||||
id: 'source',
|
||||
name: 'portrait.mov',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///source.mov',
|
||||
);
|
||||
test('returning to timeline keeps the source position without editing timeline state', () {
|
||||
final target = PreviewTarget();
|
||||
target.showAsset(asset);
|
||||
target.positions[asset.id] = 42;
|
||||
target.showTimeline();
|
||||
expect(target.asset, isNull);
|
||||
target.showAsset(asset);
|
||||
expect(target.positions[asset.id], 42);
|
||||
target.dispose();
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,7 @@
|
||||
import 'package:cutdex/workspace/persistence/timeline_creation_names.dart';
|
||||
|
||||
const testCreationNames = TimelineCreationNames(
|
||||
timeline: 'Timeline 1',
|
||||
sequence: 'Main sequence',
|
||||
storyline: 'Main storyline',
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
|
||||
class EmptyConversationRepository extends ConversationRepository {
|
||||
EmptyConversationRepository() : super(Directory('/unused'));
|
||||
|
||||
@override
|
||||
Future<List<ConversationMetadata>> list(
|
||||
String projectId, {
|
||||
bool trash = false,
|
||||
}) async => [];
|
||||
|
||||
@override
|
||||
Future<String?> selected(String projectId) async => null;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/persistence/recent_projects.dart';
|
||||
|
||||
class MemoryProjectLocationSettingsRepository
|
||||
implements ProjectLocationSettingsRepository {
|
||||
MemoryProjectLocationSettingsRepository([this.value]);
|
||||
|
||||
String? value;
|
||||
|
||||
@override
|
||||
Future<String?> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(String directory) async => value = directory;
|
||||
}
|
||||
|
||||
class MemoryResourceLocationSettingsRepository
|
||||
implements ResourceLocationSettingsRepository {
|
||||
MemoryResourceLocationSettingsRepository(this.value);
|
||||
|
||||
String? value;
|
||||
|
||||
@override
|
||||
Future<String?> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(String directory) async => value = directory;
|
||||
}
|
||||
|
||||
class MemoryMcpSettingsRepository implements McpSettingsRepository {
|
||||
McpSettingsValue? value;
|
||||
bool failWrites = false;
|
||||
|
||||
@override
|
||||
Future<McpSettingsValue?> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(McpSettingsValue configuration) async {
|
||||
if (failWrites) throw StateError('write failed');
|
||||
value = configuration;
|
||||
}
|
||||
}
|
||||
|
||||
class MemoryAppearanceSettingsRepository
|
||||
implements AppearanceSettingsRepository {
|
||||
AppAppearance value = AppAppearance.system;
|
||||
bool failWrites = false;
|
||||
|
||||
@override
|
||||
Future<AppAppearance> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(AppAppearance mode) async {
|
||||
if (failWrites) throw StateError('write failed');
|
||||
value = mode;
|
||||
}
|
||||
}
|
||||
|
||||
class MemoryRecentProjectsRepository implements RecentProjectsRepository {
|
||||
List<RecentProject> recent = [];
|
||||
final projects = <String, String>{};
|
||||
|
||||
@override
|
||||
Future<List<RecentProject>> load() async => List.of(recent);
|
||||
|
||||
@override
|
||||
Future<void> save(List<RecentProject> projects) async {
|
||||
recent = List.of(projects);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String?> lastTimeline(String projectId) async => projects[projectId];
|
||||
|
||||
@override
|
||||
Future<void> rememberTimeline(String projectId, String timelineId) async {
|
||||
projects[projectId] = timelineId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import 'creation_names.dart';
|
||||
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
|
||||
Future<
|
||||
({
|
||||
Directory directory,
|
||||
ProjectWorkspace workspace,
|
||||
EditorTimelineSession timeline,
|
||||
})
|
||||
>
|
||||
createPreviewFixture(
|
||||
Uri source, {
|
||||
Map<String, Object?>? toneMapping,
|
||||
bool hasAudio = false,
|
||||
String mediaType = 'video',
|
||||
RationalTime? clipDuration,
|
||||
TimelineDto? timelineOverride,
|
||||
Map<String, Object>? renderSize,
|
||||
List<PayloadDocument>? payloads,
|
||||
}) async {
|
||||
final duration = clipDuration ?? RationalTime.seconds(2);
|
||||
final directory = await Directory.systemTemp.createTemp(
|
||||
'cutdex-preview-test-',
|
||||
);
|
||||
final workspace = ProjectWorkspace(creationNames: testCreationNames);
|
||||
try {
|
||||
await workspace.open(
|
||||
'${directory.path}/Preview.cutdex',
|
||||
name: 'Preview test',
|
||||
);
|
||||
await workspace.project!.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'media',
|
||||
name: 'Test media',
|
||||
storage: AssetStorage.external,
|
||||
location: source.toString(),
|
||||
),
|
||||
);
|
||||
TimelineDto sequence(String id, {bool empty = false}) => TimelineDto(
|
||||
id: SequenceId(id),
|
||||
name: id,
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(
|
||||
id: StorylineId('primary'),
|
||||
elementIds: [if (!empty) ElementId('clip')],
|
||||
),
|
||||
],
|
||||
elements: [
|
||||
if (!empty)
|
||||
ElementDto(
|
||||
id: ElementId('clip'),
|
||||
name: 'Preview clip',
|
||||
structure: ElementStructure.content,
|
||||
payloadRef: PayloadRef('source'),
|
||||
duration: duration,
|
||||
sourceRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: duration,
|
||||
),
|
||||
mediaRange: TimeRange(start: RationalTime.zero, duration: duration),
|
||||
),
|
||||
],
|
||||
);
|
||||
await workspace.project!.saveTimeline(
|
||||
TimelineDocument(
|
||||
id: 'project',
|
||||
name: 'Preview test',
|
||||
sequences: [
|
||||
timelineOverride ?? sequence('one'),
|
||||
sequence('empty', empty: true),
|
||||
],
|
||||
defaultSequenceId: SequenceId('one'),
|
||||
payloads:
|
||||
payloads ??
|
||||
[
|
||||
PayloadDocument(
|
||||
id: 'source',
|
||||
type: mediaType,
|
||||
assetIds: ['media'],
|
||||
data: {
|
||||
'videoTrackIndex': 0,
|
||||
if (hasAudio) 'audioTrackIndex': 0,
|
||||
},
|
||||
),
|
||||
],
|
||||
settings: {
|
||||
'renderSize': renderSize ?? {'width': 1080, 'height': 1920},
|
||||
'toneMapping': ?toneMapping,
|
||||
},
|
||||
),
|
||||
);
|
||||
final document = await workspace.loadTimeline(
|
||||
workspace.project!.info.id,
|
||||
'project',
|
||||
);
|
||||
final timeline = await workspace.openTimelineSession(
|
||||
workspace.project!.info.id,
|
||||
document,
|
||||
);
|
||||
return (directory: directory, workspace: workspace, timeline: timeline);
|
||||
} catch (_) {
|
||||
await workspace.close();
|
||||
await directory.delete(recursive: true);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
|
||||
/// File-presence fixture only: no worker is run and no model is downloaded.
|
||||
Future<ProcessingConfiguration> processingFixture(
|
||||
Directory root,
|
||||
int capabilities, {
|
||||
bool stale = false,
|
||||
}) async {
|
||||
final suffix = Platform.isWindows ? '.exe' : '';
|
||||
final paths = [
|
||||
'runtime/bin/cutdex-processing-worker$suffix',
|
||||
if (capabilities & 13 != 0) 'runtime/bin/ffmpeg$suffix',
|
||||
if (capabilities & 1 != 0) ...[
|
||||
'runtime/workers/asr/cutdex-asr-worker$suffix',
|
||||
'asr/ggml-model.bin',
|
||||
'asr/silero_vad.onnx',
|
||||
],
|
||||
if (capabilities & 2 != 0) ...[
|
||||
'runtime/workers/translation/cutdex-m2m100-worker$suffix',
|
||||
'translation/model.bin',
|
||||
'translation/config.json',
|
||||
'translation/shared_vocabulary.json',
|
||||
'translation/sentencepiece.bpe.model',
|
||||
],
|
||||
if (capabilities & 4 != 0) ...[
|
||||
'runtime/workers/audio/cutdex-audio-worker$suffix',
|
||||
'audio/melband.pt',
|
||||
],
|
||||
if (capabilities & 8 != 0) 'background/model.onnx',
|
||||
];
|
||||
for (final path in paths) {
|
||||
final file = File('${root.path}/$path');
|
||||
await file.parent.create(recursive: true);
|
||||
await file.writeAsString('fixture');
|
||||
}
|
||||
final base = stale ? '${root.path}/missing' : root.path;
|
||||
return ProcessingConfiguration.fromPaths(
|
||||
root: '${root.path}/runtime',
|
||||
transcriptionPath: '$base/asr',
|
||||
translationPath: '$base/translation',
|
||||
vocalPath: '$base/audio/melband.pt',
|
||||
backgroundRemovalPath: '$base/background/model.onnx',
|
||||
)!;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:sqlite3/sqlite3.dart';
|
||||
|
||||
/// Holds a competing writer without depending on the SDK's table layout.
|
||||
void Function() blockProjectWrites(String projectPath) {
|
||||
final database = sqlite3.open(p.join(projectPath, 'project.sqlite'));
|
||||
try {
|
||||
database.execute('BEGIN IMMEDIATE');
|
||||
} catch (_) {
|
||||
database.close();
|
||||
rethrow;
|
||||
}
|
||||
var released = false;
|
||||
return () {
|
||||
if (released) return;
|
||||
released = true;
|
||||
try {
|
||||
database.execute('ROLLBACK');
|
||||
} finally {
|
||||
database.close();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'theme switches preserve combobox query, focus and control styles',
|
||||
(tester) async {
|
||||
var selected = 0;
|
||||
Future<void> mount(ThemeData theme) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
theme: theme,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
home: Scaffold(
|
||||
body: SizedBox(
|
||||
width: 300,
|
||||
child: Column(
|
||||
children: [
|
||||
AppTabs<int>(
|
||||
tabs: const [AppTab(0, 'General'), AppTab(1, 'Other')],
|
||||
value: 0,
|
||||
onChanged: (_) {},
|
||||
),
|
||||
AppCombobox<int>(
|
||||
emptyLabel: 'No matching options',
|
||||
searchHint: 'Search options',
|
||||
label: 'Choice',
|
||||
value: selected,
|
||||
options: const [
|
||||
AppSelectOption(0, 'Alpha'),
|
||||
AppSelectOption(1, 'Beta'),
|
||||
],
|
||||
onChanged: (value) => selected = value,
|
||||
),
|
||||
AppSwitch(value: false, onChanged: (_) {}),
|
||||
const ResourceDownloadProgress(
|
||||
downloadedBytes: 0,
|
||||
totalBytes: 1000,
|
||||
status: '',
|
||||
),
|
||||
const SizedBox(height: 40, child: DropToAddOverlay()),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
}
|
||||
|
||||
await mount(EditorTheme.penLight);
|
||||
final combo = find.byType(AppCombobox<int>);
|
||||
final initialState = tester.state(combo);
|
||||
final input = find.descendant(
|
||||
of: combo,
|
||||
matching: find.byType(TextField),
|
||||
);
|
||||
await tester.tap(input);
|
||||
await tester.enterText(input, 'Bet');
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
for (final (theme, background, border, label, scrim, track, thumb) in [
|
||||
(
|
||||
EditorTheme.penDark,
|
||||
const Color(0xFF3F3F46).withValues(alpha: .3),
|
||||
const Color(0xFFFCFCFC).withValues(alpha: .084),
|
||||
const Color(0xFFFCFCFC).withValues(alpha: .55),
|
||||
Colors.black.withValues(alpha: .62),
|
||||
const Color(0x1AC8C8C8),
|
||||
const Color(0xFFFCFCFC),
|
||||
),
|
||||
(
|
||||
EditorTheme.penLight,
|
||||
Colors.transparent,
|
||||
Colors.transparent,
|
||||
const Color(0xFF71717A),
|
||||
Colors.black.withValues(alpha: .38),
|
||||
const Color(0x0A020202),
|
||||
const Color(0xFF020202),
|
||||
),
|
||||
]) {
|
||||
await mount(theme);
|
||||
expect(tester.state(combo), same(initialState));
|
||||
final field = tester.widget<TextField>(input);
|
||||
expect(field.controller!.text, 'Bet');
|
||||
expect(field.focusNode!.hasFocus, isTrue);
|
||||
expect(find.text('Beta'), findsOneWidget);
|
||||
|
||||
final container = tester.widget<Container>(
|
||||
find.descendant(of: combo, matching: find.byType(Container)).first,
|
||||
);
|
||||
expect((container.decoration! as BoxDecoration).color, background);
|
||||
final tab = tester.widget<TextButton>(
|
||||
find.widgetWithText(TextButton, 'General'),
|
||||
);
|
||||
expect(tab.style!.side!.resolve({})!.color, border);
|
||||
final progressLabel = tester.widget<Text>(
|
||||
find.descendant(
|
||||
of: find.byType(ResourceDownloadProgress),
|
||||
matching: find.byType(Text),
|
||||
),
|
||||
);
|
||||
expect(progressLabel.style!.color, label);
|
||||
final overlay = tester.widget<ColoredBox>(
|
||||
find.descendant(
|
||||
of: find.byType(DropToAddOverlay),
|
||||
matching: find.byType(ColoredBox),
|
||||
),
|
||||
);
|
||||
expect(overlay.color, scrim);
|
||||
final switchTrack = tester.widget<AnimatedContainer>(
|
||||
find
|
||||
.descendant(
|
||||
of: find.byType(AppSwitch),
|
||||
matching: find.byType(AnimatedContainer),
|
||||
)
|
||||
.first,
|
||||
);
|
||||
expect((switchTrack.decoration! as BoxDecoration).color, track);
|
||||
final switchThumb = tester
|
||||
.widgetList<DecoratedBox>(
|
||||
find.descendant(
|
||||
of: find.byType(AppSwitch),
|
||||
matching: find.byType(DecoratedBox),
|
||||
),
|
||||
)
|
||||
.firstWhere(
|
||||
(box) =>
|
||||
(box.decoration as BoxDecoration).shape == BoxShape.circle,
|
||||
);
|
||||
expect((switchThumb.decoration as BoxDecoration).color, thumb);
|
||||
expect(tester.takeException(), isNull);
|
||||
}
|
||||
|
||||
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
|
||||
await tester.pumpAndSettle();
|
||||
expect(selected, 1);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('timeline empty state matches the wide drop-zone layout', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
locale: const Locale('zh'),
|
||||
theme: EditorTheme.penDark,
|
||||
home: const Scaffold(
|
||||
body: SizedBox(
|
||||
width: 800,
|
||||
height: 300,
|
||||
child: TimelineEmptyDropZone(
|
||||
primaryTop: 48,
|
||||
primaryHeight: 72,
|
||||
verticalOffset: 20,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final zone = find.byKey(const ValueKey('timeline-empty-drop-zone'));
|
||||
expect(find.text('将媒体拖到此处以开始。'), findsOneWidget);
|
||||
expect(tester.getSize(zone), const Size(768, 72));
|
||||
expect(tester.getTopLeft(zone), const Offset(16, 28));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,63 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex/features/timeline/timeline_speed_layout.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'zoomed segment hit targets remain inside their painted clip header',
|
||||
() {
|
||||
final segments = [
|
||||
for (var i = 0; i < 3; i++)
|
||||
ClipSpeedSegment(
|
||||
index: i,
|
||||
projectStart: i,
|
||||
projectDuration: 1,
|
||||
sourceDuration: 2,
|
||||
),
|
||||
];
|
||||
for (final pixelsPerTick in [.1, .5, 2.0, 20.0]) {
|
||||
final clip = TimelineClipLayout(
|
||||
bounds: Rect.fromLTWH(120, 48, 3 * pixelsPerTick, 92),
|
||||
headerHeight: 16,
|
||||
);
|
||||
final layout = TimelineSpeedLayout(
|
||||
clip: clip,
|
||||
segments: segments,
|
||||
pixelsPerTick: pixelsPerTick,
|
||||
);
|
||||
expect(layout.bounds.height, 14);
|
||||
for (final segment in layout.segments) {
|
||||
expect(segment.cell.right, lessThanOrEqualTo(layout.bounds.right));
|
||||
expect(segment.cell.left, greaterThanOrEqualTo(layout.bounds.left));
|
||||
for (final region in [
|
||||
segment.bar,
|
||||
segment.handle,
|
||||
segment.handleHit,
|
||||
]) {
|
||||
expect(region.left, greaterThanOrEqualTo(segment.cell.left));
|
||||
expect(region.right, lessThanOrEqualTo(segment.cell.right));
|
||||
expect(region.top, greaterThanOrEqualTo(layout.bounds.top));
|
||||
expect(region.bottom, lessThanOrEqualTo(layout.bounds.bottom));
|
||||
}
|
||||
expect(segment.handleHit.top, segment.bar.top);
|
||||
expect(segment.handleHit.bottom, segment.bar.bottom);
|
||||
expect(
|
||||
segment.handleHit.left,
|
||||
greaterThanOrEqualTo(segment.bar.left),
|
||||
);
|
||||
expect(segment.handleHit.right, lessThanOrEqualTo(segment.bar.right));
|
||||
expect(
|
||||
segment.handleHit.width,
|
||||
lessThanOrEqualTo(TimelineSpeedSegmentLayout.handleHitWidth),
|
||||
);
|
||||
if (!segment.handle.isEmpty) {
|
||||
expect(segment.handleHit.contains(segment.handle.center), isTrue);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,774 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final element = ElementRecord(
|
||||
id: ElementId('clip'),
|
||||
structure: ElementStructure.content,
|
||||
sourceStart: 0,
|
||||
sourceDuration: TimelineClock.ticksPerSecond * 10,
|
||||
duration: TimelineClock.ticksPerSecond * 10,
|
||||
enabled: true,
|
||||
payloadRef: PayloadRef('payload'),
|
||||
);
|
||||
RuntimeTimelineThumbnails create({
|
||||
int limit = 256,
|
||||
int concurrency = 2,
|
||||
int batchSize = 4,
|
||||
}) => RuntimeTimelineThumbnails(
|
||||
resolveMedia: (_) =>
|
||||
MediaReference(id: 'source', uri: Uri.file('/source.mov')),
|
||||
maximumEntries: limit,
|
||||
maximumConcurrent: concurrency,
|
||||
maximumBatchSize: batchSize,
|
||||
);
|
||||
ui.Image? demand(
|
||||
RuntimeTimelineThumbnails frames,
|
||||
int tick, {
|
||||
int sourceSpanTicks = 1,
|
||||
ui.Size logicalSize = const ui.Size(80, 40),
|
||||
double devicePixelRatio = 2,
|
||||
}) => frames.imageFor(
|
||||
element,
|
||||
tick,
|
||||
sourceSpanTicks: sourceSpanTicks,
|
||||
logicalSize: logicalSize,
|
||||
devicePixelRatio: devicePixelRatio,
|
||||
);
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
test('sampling uses finite media bounds or an uncapped source grid', () {
|
||||
int sample(int tick, int? end) => RuntimeTimelineThumbnails.sampledTickFor(
|
||||
sourceTick: tick,
|
||||
sourceSpanTicks: 8,
|
||||
minimumTick: 3,
|
||||
maximumTickExclusive: end,
|
||||
);
|
||||
expect(sample(0, 22), 3);
|
||||
expect(sample(35, 22), 16);
|
||||
expect(sample(0, null), 3);
|
||||
expect(sample(21, null), 24);
|
||||
});
|
||||
|
||||
testWidgets('a freeze frame with zero source span still requests its image', (
|
||||
tester,
|
||||
) async {
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
calls++;
|
||||
throw PlatformException(code: 'unavailable');
|
||||
});
|
||||
final frames = create();
|
||||
addTearDown(frames.dispose);
|
||||
final tick = 10 * TimelineClock.ticksPerSecond;
|
||||
final frozen = element.copyWith(
|
||||
sourceStart: tick,
|
||||
sourceDuration: 0,
|
||||
mediaStart: 0,
|
||||
mediaDuration: 30 * TimelineClock.ticksPerSecond,
|
||||
retime: RetimeMapRecord([
|
||||
RetimeSegmentRecord(
|
||||
projectDuration: element.duration,
|
||||
sourceStart: tick,
|
||||
sourceDelta: 0,
|
||||
),
|
||||
]),
|
||||
);
|
||||
frames.beginFrame();
|
||||
frames.imageFor(
|
||||
frozen,
|
||||
tick,
|
||||
sourceSpanTicks: 1,
|
||||
logicalSize: const Size(80, 40),
|
||||
devicePixelRatio: 2,
|
||||
);
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, 1);
|
||||
});
|
||||
|
||||
for (final leading in [true, false]) {
|
||||
testWidgets('trimmed media keeps the same cached cell: leading $leading', (
|
||||
tester,
|
||||
) async {
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
calls++;
|
||||
throw PlatformException(code: 'unavailable');
|
||||
});
|
||||
final frames = create();
|
||||
addTearDown(frames.dispose);
|
||||
final clip = element.copyWith(
|
||||
sourceStart: 5 * TimelineClock.ticksPerSecond,
|
||||
sourceDuration: 10 * TimelineClock.ticksPerSecond,
|
||||
mediaStart: 0,
|
||||
mediaDuration: 30 * TimelineClock.ticksPerSecond,
|
||||
);
|
||||
final tick = ((leading ? 5.25 : 14.75) * TimelineClock.ticksPerSecond)
|
||||
.round();
|
||||
void paint(ElementRecord record) {
|
||||
frames.beginFrame();
|
||||
frames.imageFor(
|
||||
record,
|
||||
tick,
|
||||
sourceSpanTicks: TimelineClock.ticksPerSecond,
|
||||
logicalSize: const Size(80, 40),
|
||||
devicePixelRatio: 2,
|
||||
);
|
||||
frames.endFrame();
|
||||
}
|
||||
|
||||
paint(clip);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(calls, 1);
|
||||
for (final removed in [0.5, 1.0, 1.5]) {
|
||||
final delta = (removed * TimelineClock.ticksPerSecond).round();
|
||||
paint(
|
||||
clip.copyWith(
|
||||
sourceStart: clip.sourceStart + (leading ? delta : 0),
|
||||
sourceDuration: clip.sourceDuration - delta,
|
||||
duration: clip.duration - delta,
|
||||
),
|
||||
);
|
||||
await tester.pump();
|
||||
await tester.pump();
|
||||
expect(
|
||||
calls,
|
||||
1,
|
||||
reason: 'Cropping a cell must not change its cache key',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test(
|
||||
'thumbnail requests and cached failures are isolated by selected track',
|
||||
() async {
|
||||
var index = 0;
|
||||
final indices = <int>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.trackSelection': 'available'},
|
||||
};
|
||||
}
|
||||
indices.add(
|
||||
((call.arguments as Map)['trackSelection'] as Map)['index'] as int,
|
||||
);
|
||||
throw PlatformException(code: 'unavailable');
|
||||
});
|
||||
final frames = RuntimeTimelineThumbnails(
|
||||
resolveMedia: (_) =>
|
||||
MediaReference(id: 'shared', uri: Uri.file('/shared.mov')),
|
||||
resolveTrackSelection: (_) => TrackSelection.index(index),
|
||||
);
|
||||
addTearDown(frames.dispose);
|
||||
for (index = 0; index < 2; index++) {
|
||||
frames.beginFrame();
|
||||
demand(frames, 0);
|
||||
frames.endFrame();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
expect(indices, [0, 1]);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('still image tiles share one source-time request', (
|
||||
tester,
|
||||
) async {
|
||||
final calls = <List<Object?>>[];
|
||||
final media = <Object?>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
media.add((call.arguments as Map)['media']);
|
||||
calls.add((call.arguments as Map)['times'] as List<Object?>);
|
||||
throw PlatformException(code: 'unavailable');
|
||||
});
|
||||
final frames = RuntimeTimelineThumbnails(
|
||||
resolveMedia: (_) => MediaReference(
|
||||
id: 'still',
|
||||
uri: Uri.file('/still.heic'),
|
||||
isImage: true,
|
||||
),
|
||||
);
|
||||
frames.beginFrame();
|
||||
for (final tick in [0, 100, TimelineClock.ticksPerSecond * 9]) {
|
||||
demand(frames, tick);
|
||||
}
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[MediaTime(0, TimelineClock.ticksPerSecond).toMap()],
|
||||
]);
|
||||
expect(media.single, containsPair('isImage', true));
|
||||
frames.dispose();
|
||||
});
|
||||
|
||||
test('painted device pixels are quantized to stable resolution tiers', () {
|
||||
expect(
|
||||
RuntimeTimelineThumbnails.maximumEdgeFor(
|
||||
logicalSize: const ui.Size(82, 46),
|
||||
devicePixelRatio: 2,
|
||||
),
|
||||
192,
|
||||
);
|
||||
expect(
|
||||
RuntimeTimelineThumbnails.maximumEdgeFor(
|
||||
logicalSize: const ui.Size(26, 46),
|
||||
devicePixelRatio: 2,
|
||||
),
|
||||
128,
|
||||
);
|
||||
expect(
|
||||
() => RuntimeTimelineThumbnails.maximumEdgeFor(
|
||||
logicalSize: ui.Size.zero,
|
||||
devicePixelRatio: 2,
|
||||
),
|
||||
throwsArgumentError,
|
||||
);
|
||||
});
|
||||
|
||||
test('nearby zoom centers snap to a stable source-time pyramid', () {
|
||||
final frames = create();
|
||||
addTearDown(frames.dispose);
|
||||
expect(frames.maximumBatchSize, 4);
|
||||
final span = TimelineClock.ticksPerSecond * 3 ~/ 5;
|
||||
final interval = RuntimeTimelineThumbnails.samplingIntervalFor(span);
|
||||
expect(interval, lessThanOrEqualTo(span));
|
||||
expect(interval * 2, greaterThan(span));
|
||||
final first = RuntimeTimelineThumbnails.sampledTickFor(
|
||||
sourceTick: TimelineClock.ticksPerSecond * 3,
|
||||
sourceSpanTicks: span,
|
||||
minimumTick: 0,
|
||||
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
|
||||
);
|
||||
final nearby = RuntimeTimelineThumbnails.sampledTickFor(
|
||||
sourceTick: TimelineClock.ticksPerSecond * 3 + interval ~/ 16,
|
||||
sourceSpanTicks: span - 1,
|
||||
minimumTick: 0,
|
||||
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
|
||||
);
|
||||
expect(nearby, first);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'visible requests are bounded, old pending work is discarded, and late disposal is safe',
|
||||
(tester) async {
|
||||
final calls = <List<int>>[];
|
||||
final waiting = <Completer<Object?>>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) {
|
||||
expectSync(call.method, 'thumbnails');
|
||||
final args = call.arguments as Map;
|
||||
calls.add([
|
||||
for (final time in args['times'] as List)
|
||||
int.parse((time as Map)['numerator'] as String),
|
||||
]);
|
||||
expectSync(args['maximumWidth'], 192);
|
||||
expectSync(args['maximumHeight'], 192);
|
||||
expectSync(args['tolerance'], MediaTime(1, 4).toMap());
|
||||
final result = Completer<Object?>();
|
||||
waiting.add(result);
|
||||
return result.future;
|
||||
});
|
||||
final frames = create(limit: 3, concurrency: 1);
|
||||
frames.beginFrame();
|
||||
for (var i = 0; i < 6; i++) {
|
||||
demand(frames, i);
|
||||
}
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[0],
|
||||
]);
|
||||
frames.beginFrame();
|
||||
demand(frames, 50);
|
||||
frames.endFrame();
|
||||
waiting.first.completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[0],
|
||||
[50],
|
||||
]);
|
||||
frames.dispose();
|
||||
waiting.last.completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[0],
|
||||
[50],
|
||||
]);
|
||||
expect(tester.takeException(), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('large visible ranges load in small progressive batches', (
|
||||
tester,
|
||||
) async {
|
||||
final calls = <List<int>>[];
|
||||
final waiting = <Completer<Object?>>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) {
|
||||
final args = call.arguments as Map;
|
||||
calls.add([
|
||||
for (final time in args['times'] as List)
|
||||
int.parse((time as Map)['numerator'] as String),
|
||||
]);
|
||||
final result = Completer<Object?>();
|
||||
waiting.add(result);
|
||||
return result.future;
|
||||
});
|
||||
final frames = create(limit: 32, concurrency: 1);
|
||||
addTearDown(frames.dispose);
|
||||
frames.beginFrame();
|
||||
for (var tick = 0; tick < 17; tick++) {
|
||||
demand(frames, tick);
|
||||
}
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls.map((batch) => batch.length), [1]);
|
||||
|
||||
waiting[0].completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls.map((batch) => batch.length), [1, 4]);
|
||||
|
||||
waiting[1].completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls.map((batch) => batch.length), [1, 4, 4]);
|
||||
|
||||
waiting[2].completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls.map((batch) => batch.length), [1, 4, 4, 4]);
|
||||
|
||||
waiting[3].completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(calls.map((batch) => batch.length), [1, 4, 4, 4, 4]);
|
||||
|
||||
waiting[4].completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('first visible tile is requested ahead of its batch', (
|
||||
tester,
|
||||
) async {
|
||||
final calls = <List<int>>[];
|
||||
final pending = <Completer<Object?>>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) {
|
||||
final times = (call.arguments as Map)['times'] as List;
|
||||
calls.add([
|
||||
for (final time in times)
|
||||
int.parse((time as Map)['numerator'] as String),
|
||||
]);
|
||||
final completion = Completer<Object?>();
|
||||
pending.add(completion);
|
||||
return completion.future;
|
||||
});
|
||||
final frames = create(concurrency: 2);
|
||||
addTearDown(frames.dispose);
|
||||
frames.beginFrame();
|
||||
for (var tick = 0; tick < 6; tick++) {
|
||||
demand(frames, tick);
|
||||
}
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[0],
|
||||
[1, 2, 3, 4],
|
||||
]);
|
||||
for (final completion in List.of(pending)) {
|
||||
completion.completeError(PlatformException(code: 'unavailable'));
|
||||
}
|
||||
await tester.pump();
|
||||
expect(calls, [
|
||||
[0],
|
||||
[1, 2, 3, 4],
|
||||
[5],
|
||||
]);
|
||||
pending.last.completeError(PlatformException(code: 'unavailable'));
|
||||
await tester.pump();
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'decoded images repaint once, retain aspect ratio and are reused until eviction',
|
||||
(tester) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.green, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(9, 16);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!
|
||||
.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls++;
|
||||
final times = (call.arguments as Map)['times'] as List;
|
||||
return [
|
||||
for (final time in times)
|
||||
{
|
||||
'requestedTime': time,
|
||||
'actualTime': time,
|
||||
'width': 9,
|
||||
'height': 16,
|
||||
'format': 'jpeg',
|
||||
'data': bytes,
|
||||
},
|
||||
];
|
||||
});
|
||||
final frames = create(limit: 1);
|
||||
var repaints = 0;
|
||||
Completer<void>? ready;
|
||||
frames.addListener(() {
|
||||
repaints++;
|
||||
ready?.complete();
|
||||
});
|
||||
addTearDown(frames.dispose);
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, 123);
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
frames.beginFrame();
|
||||
final first = demand(frames, 123)!;
|
||||
expect(first.width, 9);
|
||||
expect(first.height, 16);
|
||||
expect(frames.aspectRatioFor(element), 9 / 16);
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, 1);
|
||||
expect(repaints, 1);
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, 456);
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
expect(calls, 2);
|
||||
expect(first.debugDisposed, isTrue);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('imported media keeps preview frames and aspect ratio', (
|
||||
tester,
|
||||
) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.blue, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(16, 9);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls++;
|
||||
return [
|
||||
for (final time in (call.arguments as Map)['times'] as List)
|
||||
{
|
||||
'requestedTime': time,
|
||||
'actualTime': time,
|
||||
'width': 16,
|
||||
'height': 9,
|
||||
'format': 'jpeg',
|
||||
'data': bytes,
|
||||
},
|
||||
];
|
||||
});
|
||||
var media = MediaReference(id: '/source.mov', uri: Uri.file('/source.mov'));
|
||||
final frames = RuntimeTimelineThumbnails(resolveMedia: (_) => media);
|
||||
addTearDown(frames.dispose);
|
||||
late Completer<void> ready;
|
||||
frames.addListener(() {
|
||||
if (!ready.isCompleted) ready.complete();
|
||||
});
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, 123);
|
||||
frames.endFrame();
|
||||
await ready.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
frames.beginFrame();
|
||||
final preview = demand(frames, 123);
|
||||
expect(preview, isNotNull);
|
||||
frames.endFrame();
|
||||
media = MediaReference(id: 'imported-asset', uri: media.uri);
|
||||
frames.beginFrame();
|
||||
expect(demand(frames, 123), same(preview));
|
||||
expect(frames.aspectRatioFor(element), 16 / 9);
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, 1);
|
||||
// Reusing an asset ID for a different file must still invalidate the cache.
|
||||
media = MediaReference(id: media.id, uri: Uri.file('/other.mov'));
|
||||
frames.beginFrame();
|
||||
expect(demand(frames, 123), isNull);
|
||||
expect(frames.aspectRatioFor(element), isNull);
|
||||
});
|
||||
|
||||
testWidgets('a lower tier stays visible while a higher DPR tier loads', (
|
||||
tester,
|
||||
) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.blue, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(16, 9);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
final edges = <int>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
final args = call.arguments as Map;
|
||||
edges.add(args['maximumWidth'] as int);
|
||||
return [
|
||||
for (final time in args['times'] as List)
|
||||
{
|
||||
'requestedTime': time,
|
||||
'actualTime': time,
|
||||
'width': 16,
|
||||
'height': 9,
|
||||
'format': 'jpeg',
|
||||
'data': bytes,
|
||||
},
|
||||
];
|
||||
});
|
||||
final frames = create(limit: 2);
|
||||
addTearDown(frames.dispose);
|
||||
Completer<void>? ready;
|
||||
frames.addListener(() => ready?.complete());
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, 123, logicalSize: const ui.Size(20, 20));
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
frames.beginFrame();
|
||||
final low = demand(frames, 123, logicalSize: const ui.Size(80, 40));
|
||||
frames.endFrame();
|
||||
expect(
|
||||
low,
|
||||
isNotNull,
|
||||
reason: 'The loaded lower tier should be a fallback',
|
||||
);
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
frames.beginFrame();
|
||||
final high = demand(frames, 123, logicalSize: const ui.Size(80, 40));
|
||||
frames.endFrame();
|
||||
expect(edges, [64, 192]);
|
||||
expect(high, isNotNull);
|
||||
expect(identical(high, low), isFalse);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'a nearby cached sample stays visible across pyramid level changes',
|
||||
(tester) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.purple, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(16, 9);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!
|
||||
.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
final requestedTicks = <int>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
final args = call.arguments as Map;
|
||||
expect(args['tolerance'], MediaTime(1, 4).toMap());
|
||||
final times = args['times'] as List;
|
||||
requestedTicks.addAll([
|
||||
for (final time in times)
|
||||
int.parse((time as Map)['numerator'] as String),
|
||||
]);
|
||||
return [
|
||||
for (final time in times)
|
||||
{
|
||||
'requestedTime': time,
|
||||
'actualTime': time,
|
||||
'width': 16,
|
||||
'height': 9,
|
||||
'format': 'jpeg',
|
||||
'data': bytes,
|
||||
},
|
||||
];
|
||||
});
|
||||
final frames = create(concurrency: 1);
|
||||
addTearDown(frames.dispose);
|
||||
Completer<void>? ready;
|
||||
frames.addListener(() {
|
||||
if (ready case final pending? when !pending.isCompleted) {
|
||||
pending.complete();
|
||||
}
|
||||
});
|
||||
final coarseSpan = TimelineClock.ticksPerSecond;
|
||||
final coarseTick = RuntimeTimelineThumbnails.sampledTickFor(
|
||||
sourceTick: TimelineClock.ticksPerSecond * 3,
|
||||
sourceSpanTicks: coarseSpan,
|
||||
minimumTick: 0,
|
||||
maximumTickExclusive: TimelineClock.ticksPerSecond * 10,
|
||||
);
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, coarseTick, sourceSpanTicks: coarseSpan);
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
|
||||
final fineSpan = coarseSpan ~/ 2;
|
||||
final fineTick =
|
||||
coarseTick + RuntimeTimelineThumbnails.samplingIntervalFor(fineSpan);
|
||||
ui.Image? fallback;
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
fallback = demand(frames, fineTick, sourceSpanTicks: fineSpan);
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
expect(
|
||||
fallback,
|
||||
isNotNull,
|
||||
reason: 'A pyramid transition must not expose an empty tile',
|
||||
);
|
||||
frames.beginFrame();
|
||||
final replacement = demand(frames, fineTick, sourceSpanTicks: fineSpan);
|
||||
frames.endFrame();
|
||||
expect(requestedTicks, [coarseTick, fineTick]);
|
||||
expect(replacement, isNotNull);
|
||||
expect(identical(replacement, fallback), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'completed batches retain frames that just moved outside the viewport',
|
||||
(tester) async {
|
||||
final recorder = ui.PictureRecorder();
|
||||
Canvas(recorder).drawColor(Colors.orange, BlendMode.src);
|
||||
final picture = recorder.endRecording();
|
||||
final bytes = await tester.runAsync(() async {
|
||||
final image = await picture.toImage(16, 9);
|
||||
try {
|
||||
return (await image.toByteData(format: ui.ImageByteFormat.png))!
|
||||
.buffer
|
||||
.asUint8List();
|
||||
} finally {
|
||||
image.dispose();
|
||||
picture.dispose();
|
||||
}
|
||||
});
|
||||
var calls = 0;
|
||||
late final RuntimeTimelineThumbnails frames;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls++;
|
||||
final requestedTimes = (call.arguments as Map)['times'] as List;
|
||||
|
||||
// Simulate a pan while this native request is in flight.
|
||||
frames.beginFrame();
|
||||
demand(frames, 20);
|
||||
frames.endFrame();
|
||||
return [
|
||||
for (final time in requestedTimes)
|
||||
{
|
||||
'requestedTime': time,
|
||||
'actualTime': time,
|
||||
'width': 16,
|
||||
'height': 9,
|
||||
'format': 'jpeg',
|
||||
'data': bytes,
|
||||
},
|
||||
];
|
||||
});
|
||||
frames = create(limit: 4, concurrency: 1);
|
||||
addTearDown(frames.dispose);
|
||||
Completer<void>? ready;
|
||||
frames.addListener(() {
|
||||
if (ready case final pending? when !pending.isCompleted) {
|
||||
pending.complete();
|
||||
}
|
||||
});
|
||||
|
||||
await tester.runAsync(() async {
|
||||
ready = Completer<void>();
|
||||
frames.beginFrame();
|
||||
demand(frames, 10);
|
||||
demand(frames, 20);
|
||||
frames.endFrame();
|
||||
await ready!.future.timeout(const Duration(seconds: 5));
|
||||
});
|
||||
expect(calls, 2);
|
||||
|
||||
frames.beginFrame();
|
||||
expect(
|
||||
demand(frames, 10),
|
||||
isNotNull,
|
||||
reason: 'A completed neighboring frame should remain in the LRU cache',
|
||||
);
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
expect(calls, 2);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'failed frames do not trigger repeated native requests on repaint',
|
||||
(tester) async {
|
||||
var calls = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (_) async {
|
||||
calls++;
|
||||
throw PlatformException(code: 'unsupported');
|
||||
});
|
||||
final frames = create();
|
||||
addTearDown(frames.dispose);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
frames.beginFrame();
|
||||
demand(frames, 12);
|
||||
frames.endFrame();
|
||||
await tester.pump();
|
||||
}
|
||||
expect(calls, 1);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,393 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/timeline_waveforms.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
ElementRecord element(String id) => ElementRecord(
|
||||
id: ElementId(id),
|
||||
structure: ElementStructure.content,
|
||||
duration: TimelineClock.ticksPerSecond,
|
||||
sourceStart: 0,
|
||||
sourceDuration: TimelineClock.ticksPerSecond,
|
||||
enabled: true,
|
||||
payloadRef: PayloadRef(id),
|
||||
);
|
||||
Map<String, Object> response() => {
|
||||
'sampleRate': 4.0,
|
||||
'sourceStartSeconds': 0.0,
|
||||
'frameCount': 4,
|
||||
'trackId': 1,
|
||||
'channelCount': 1,
|
||||
'levels': [
|
||||
{
|
||||
'samplesPerBucket': 2,
|
||||
'channels': [
|
||||
[-0.5, 0.5, 0.25, -1.0, 1.0, 0.7],
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
Future<void> flush() => Future<void>.delayed(Duration.zero);
|
||||
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
|
||||
|
||||
test(
|
||||
'audio presence follows the binding before loading and after separation',
|
||||
() {
|
||||
var bound = true;
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (ref) => bound && ref.value == 'video'
|
||||
? MediaReference(id: 'video', uri: Uri.file('/movie.mov'))
|
||||
: null,
|
||||
);
|
||||
expect(source.hasAudioFor(element('video')), isTrue);
|
||||
expect(source.hasAudioFor(element('silent-video')), isFalse);
|
||||
expect(source.hasAudioFor(element('image')), isFalse);
|
||||
bound = false;
|
||||
expect(source.hasAudioFor(element('video')), isFalse);
|
||||
source.dispose();
|
||||
expect(source.hasAudioFor(element('video')), isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'different selected tracks never share a waveform cache entry',
|
||||
() async {
|
||||
final indices = <int>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {
|
||||
'media.waveform': 'available',
|
||||
'media.trackSelection': 'available',
|
||||
},
|
||||
};
|
||||
}
|
||||
indices.add(
|
||||
((call.arguments as Map)['trackSelection'] as Map)['index'] as int,
|
||||
);
|
||||
return response();
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) =>
|
||||
MediaReference(id: 'shared', uri: Uri.file('/shared.mov')),
|
||||
resolveTrackSelection: (ref) =>
|
||||
TrackSelection.index(ref.value == 'a' ? 0 : 1),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.waveformFor(element('b'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
await flush();
|
||||
expect(indices, unorderedEquals([0, 1]));
|
||||
expect(source.waveformFor(element('a')), isNotNull);
|
||||
expect(source.waveformFor(element('b')), isNotNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'gain changes repaint shared envelopes without decoding again',
|
||||
() async {
|
||||
var loads = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
loads++;
|
||||
return response();
|
||||
});
|
||||
final gain = ValueNotifier(1.0);
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) =>
|
||||
MediaReference(id: 'shared', uri: Uri.file('/shared.wav')),
|
||||
resolveGain: (clip) => clip.id == ElementId('a') ? gain.value : 1,
|
||||
gainChanges: gain,
|
||||
);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
final original = source.waveformFor(element('a'))!;
|
||||
var repaints = 0;
|
||||
source.addListener(() => repaints++);
|
||||
gain.value = 2;
|
||||
final amplified = source.waveformFor(element('a'))!;
|
||||
expect(amplified.amplitudeScale, 2);
|
||||
expect(amplified.levels, same(original.levels));
|
||||
expect(source.waveformFor(element('b'))!.amplitudeScale, 1);
|
||||
gain.value = 0;
|
||||
expect(source.waveformFor(element('a'))!.amplitudeScale, 0);
|
||||
expect(repaints, 2);
|
||||
expect(loads, 1);
|
||||
source.dispose();
|
||||
gain.value = 1;
|
||||
expect(repaints, 2);
|
||||
gain.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'requests after paint, deduplicates and stops notifying after disposal',
|
||||
() async {
|
||||
final pending = Completer<Object>();
|
||||
var loads = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
loads++;
|
||||
return pending.future;
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) =>
|
||||
MediaReference(id: 'shared', uri: Uri.file('/shared.wav')),
|
||||
);
|
||||
var notifications = 0;
|
||||
source.addListener(() => notifications++);
|
||||
source.beginFrame();
|
||||
expect(source.waveformFor(element('a')), isNull);
|
||||
source.waveformFor(element('b'));
|
||||
expect(loads, 0);
|
||||
source.endFrame();
|
||||
await flush();
|
||||
expect(loads, 1);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
expect(loads, 1);
|
||||
source.dispose();
|
||||
pending.complete(response());
|
||||
await flush();
|
||||
expect(notifications, 0);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'limits concurrency, caches ready data and evicts old sources',
|
||||
() async {
|
||||
final pending = <Completer<Object>>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
final completer = Completer<Object>();
|
||||
pending.add(completer);
|
||||
return completer.future;
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
maximumEntries: 2,
|
||||
maximumConcurrent: 1,
|
||||
resolveMedia: (ref) =>
|
||||
MediaReference(id: ref.value, uri: Uri.file('/${ref.value}.wav')),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.waveformFor(element('b'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
expect(pending.length, 1);
|
||||
pending[0].complete(response());
|
||||
await flush();
|
||||
expect(pending.length, 2);
|
||||
pending[1].complete(response());
|
||||
await flush();
|
||||
expect(source.waveformFor(element('a')), isNotNull);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('c'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
pending[2].complete(response());
|
||||
await flush();
|
||||
expect(source.waveformFor(element('c')), isNotNull);
|
||||
expect(source.waveformFor(element('b')), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test('unsupported platforms do not issue waveform requests', () async {
|
||||
final calls = <String>[];
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call.method);
|
||||
return {'contractVersion': 1, 'features': <String, String>{}};
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
}
|
||||
expect(calls, ['capabilities']);
|
||||
});
|
||||
|
||||
test(
|
||||
'all visible sources load even when they exceed the warm cache limit',
|
||||
() async {
|
||||
var loads = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
loads++;
|
||||
return response();
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
maximumEntries: 2,
|
||||
resolveMedia: (ref) =>
|
||||
MediaReference(id: ref.value, uri: Uri.file('/${ref.value}.wav')),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
source.beginFrame();
|
||||
for (final id in ['a', 'b', 'c']) {
|
||||
source.waveformFor(element(id));
|
||||
}
|
||||
source.endFrame();
|
||||
for (var i = 0; i < 6; i++) {
|
||||
await flush();
|
||||
}
|
||||
expect(loads, 3);
|
||||
for (final id in ['a', 'b', 'c']) {
|
||||
expect(source.waveformFor(element(id)), isNotNull);
|
||||
}
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('c'));
|
||||
source.endFrame();
|
||||
await flush();
|
||||
expect(source.waveformFor(element('a')), isNull);
|
||||
},
|
||||
);
|
||||
|
||||
for (final failingMethod in ['capabilities', 'waveform']) {
|
||||
testWidgets(
|
||||
'transient $failingMethod failure recovers without reopening the timeline',
|
||||
(tester) async {
|
||||
var failures = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == failingMethod && failures++ == 0) {
|
||||
throw PlatformException(
|
||||
code: 'unavailable',
|
||||
details: {'retryable': true},
|
||||
);
|
||||
}
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
return response();
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await tester.pump();
|
||||
expect(source.waveformFor(element('a')), isNull);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
await tester.pump();
|
||||
expect(source.waveformFor(element('a')), isNotNull);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('persistent transient errors have a finite retry budget', (
|
||||
tester,
|
||||
) async {
|
||||
var loads = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
loads++;
|
||||
throw PlatformException(
|
||||
code: 'unavailable',
|
||||
details: {'retryable': true},
|
||||
);
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')),
|
||||
);
|
||||
addTearDown(source.dispose);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await tester.pump();
|
||||
expect(loads, 1);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
expect(loads, 2);
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
expect(loads, 3);
|
||||
await tester.pump(const Duration(minutes: 1));
|
||||
expect(loads, 3);
|
||||
});
|
||||
|
||||
testWidgets('leaving the viewport cancels pending retries', (tester) async {
|
||||
var loads = 0;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
if (call.method == 'capabilities') {
|
||||
return {
|
||||
'contractVersion': 1,
|
||||
'features': {'media.waveform': 'available'},
|
||||
};
|
||||
}
|
||||
loads++;
|
||||
throw PlatformException(
|
||||
code: 'unavailable',
|
||||
details: {'retryable': true},
|
||||
);
|
||||
});
|
||||
final source = RuntimeTimelineWaveforms(
|
||||
resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')),
|
||||
);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await tester.pump();
|
||||
source.beginFrame();
|
||||
source.endFrame();
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
expect(loads, 1);
|
||||
source.beginFrame();
|
||||
source.waveformFor(element('a'));
|
||||
source.endFrame();
|
||||
await tester.pump();
|
||||
expect(loads, 2);
|
||||
source.dispose();
|
||||
await tester.pump(const Duration(seconds: 5));
|
||||
expect(loads, 2);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,145 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/persistence/app_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/view_settings.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class _WorkspaceRepository implements WorkspaceViewSettingsRepository {
|
||||
WorkspaceViewSettingsData value = const WorkspaceViewSettingsData();
|
||||
final writes = <WorkspaceViewSettingsData>[];
|
||||
Completer<void>? gate;
|
||||
bool failWrites = false;
|
||||
|
||||
@override
|
||||
Future<WorkspaceViewSettingsData> load() async => value;
|
||||
|
||||
@override
|
||||
Future<void> save(WorkspaceViewSettingsData settings) async {
|
||||
writes.add(settings);
|
||||
await gate?.future;
|
||||
if (failWrites) throw StateError('write failed');
|
||||
value = settings;
|
||||
}
|
||||
}
|
||||
|
||||
class _ProjectRepository implements ProjectViewSettingsRepository {
|
||||
final values = <String, ProjectViewSettingsData>{};
|
||||
final writes = <String>[];
|
||||
bool failLoads = false;
|
||||
|
||||
@override
|
||||
Future<ProjectViewSettingsData> load(String projectId) async {
|
||||
if (failLoads) throw StateError('unavailable');
|
||||
return values[projectId] ?? const ProjectViewSettingsData();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> save(String projectId, ProjectViewSettingsData settings) async {
|
||||
writes.add(projectId);
|
||||
values[projectId] = settings;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'workspace saves remain ordered while a previous write is pending',
|
||||
() async {
|
||||
final repository = _WorkspaceRepository()..gate = Completer<void>();
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
workspaceViewSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
await container.read(workspaceViewSettingsProvider.future);
|
||||
final controller = container.read(workspaceViewSettingsProvider.notifier);
|
||||
controller.setSidebarWidth(220);
|
||||
final first = controller.save(activeProjectId: 'first');
|
||||
controller.setSidebarWidth(300);
|
||||
final second = controller.save(activeProjectId: 'second');
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(repository.writes, hasLength(1));
|
||||
expect(repository.writes.single.sidebarWidth, 220);
|
||||
expect(
|
||||
container.read(workspaceViewSettingsProvider).requireValue.sidebarWidth,
|
||||
300,
|
||||
);
|
||||
repository.gate!.complete();
|
||||
await Future.wait([first, second]);
|
||||
expect(repository.writes.map((value) => value.activeProjectId), [
|
||||
'first',
|
||||
'second',
|
||||
]);
|
||||
expect(repository.value.sidebarWidth, 300);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'workspace can clear the active project and save after a failed write',
|
||||
() async {
|
||||
final repository = _WorkspaceRepository();
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
workspaceViewSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
await container.read(workspaceViewSettingsProvider.future);
|
||||
final controller = container.read(workspaceViewSettingsProvider.notifier);
|
||||
await controller.save(activeProjectId: 'project');
|
||||
repository.failWrites = true;
|
||||
await expectLater(
|
||||
controller.save(activeProjectId: null),
|
||||
throwsStateError,
|
||||
);
|
||||
repository.failWrites = false;
|
||||
await controller.save(activeProjectId: null);
|
||||
expect(repository.value.activeProjectId, isNull);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'project view settings survive subscription changes and stay isolated',
|
||||
() async {
|
||||
final repository = _ProjectRepository();
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectViewSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
final firstProvider = projectViewSettingsProvider('first');
|
||||
final subscription = container.listen(firstProvider, (_, _) {});
|
||||
await container.read(firstProvider.future);
|
||||
final first = container.read(firstProvider.notifier);
|
||||
first.setPropertiesOpen(true);
|
||||
first.setTimelineHeight(240);
|
||||
await first.save();
|
||||
subscription.close();
|
||||
await container.pump();
|
||||
expect(container.read(firstProvider).requireValue.propertiesOpen, isTrue);
|
||||
expect(
|
||||
await container.read(projectViewSettingsProvider('second').future),
|
||||
const ProjectViewSettingsData(),
|
||||
);
|
||||
final restored = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectViewSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
expect((await restored.read(firstProvider.future)).timelineHeight, 240);
|
||||
expect(repository.writes, ['first']);
|
||||
},
|
||||
);
|
||||
|
||||
test('unavailable project preferences do not prevent editing', () async {
|
||||
final repository = _ProjectRepository()..failLoads = true;
|
||||
final container = ProviderContainer.test(
|
||||
overrides: [
|
||||
projectViewSettingsRepositoryProvider.overrideWithValue(repository),
|
||||
],
|
||||
);
|
||||
expect(
|
||||
await container.read(projectViewSettingsProvider('project').future),
|
||||
const ProjectViewSettingsData(),
|
||||
);
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Loaded 100 of 718 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user