Files
cutdex/test/agent_attachment_composer_test.dart
lingjhf 38ca180cf7
Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s
refactor(core): own editor UI and pin verified native releases
2026-10-12 03:20:29 +08:00

598 lines
21 KiB
Dart

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/icons.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_core/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: const ExternalMediaFile(path: '/tmp/片段.mov').sourceUri
.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, AppIcons.attachment);
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, AppIcons.timeline);
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));
}