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 records = []; final projects = {}; @override Future> load() async => records; @override Future save(List projects) async { records = projects; } @override Future lastTimeline(String projectId) async => projects[projectId]; @override Future 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 = []; Completer? 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': [], 'audioTracks': [], '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.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( (ref) => createEditorAgentBinding(ref, projectId, state.timeline!.id), ).future, ); addTearDown(() async => binding.release?.call()); Future call(String name, Map 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( (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()), ); 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>() .transform(utf8.decoder) .transform(const LineSplitter()), ); addTearDown(() async { socket.destroy(); await lines.cancel(); }); socket.writeln(token); var requestId = 0; Future> invoke( String name, Map 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': {}, }, '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()); 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 invoke(String name, Map 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(); 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.delayed(const Duration(milliseconds: 2)); } target.showTimeline(); blockedProbe!.complete(); expect((await opening).status.name, 'unknown'); await target.closeSource(); expect(target.source, isNull); }, ); }