3419 lines
120 KiB
Dart
3419 lines
120 KiB
Dart
import 'package:cutdex/app/editor_theme.dart';
|
||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
||
import 'package:crypto/crypto.dart';
|
||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||
import 'package:cutdex/integrations/runtime/processing_resource_repository.dart';
|
||
import 'package:cutdex/l10n/app_localizations.dart';
|
||
import 'package:cutdex_ui/icons.dart';
|
||
import 'package:cutdex_ui/theme.dart';
|
||
import 'package:cutdex_ui/widgets.dart';
|
||
|
||
import 'dart:async';
|
||
import 'dart:io';
|
||
import 'dart:convert';
|
||
|
||
import 'package:cutdex/integrations/editor_command_host.dart';
|
||
import 'package:cutdex/integrations/editor_tools.dart';
|
||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||
import 'package:cutdex/workspace/timeline_session.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:cutdex_sdk/timeline/layout.dart';
|
||
import 'package:cutdex_sdk/runtime/execution.dart';
|
||
import 'package:cutdex_sdk/tools.dart';
|
||
import 'package:flutter_test/flutter_test.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import 'package:cutdex/features/media/transcription_dialog.dart';
|
||
import 'package:cutdex/features/media/background_tasks_dialog.dart';
|
||
import 'package:cutdex/workspace/background_task_registry.dart';
|
||
import 'package:cutdex/workspace/background_task_state.dart';
|
||
import 'package:cutdex/features/media/subtitle_task_actions.dart';
|
||
import 'package:cutdex/features/properties/caption_properties.dart';
|
||
|
||
class Media implements EditorMediaService {
|
||
Media(this.source);
|
||
final Uri source;
|
||
MediaTime audioStart = MediaTime(0, 1);
|
||
Completer<PreparedEditorMedia>? pending;
|
||
bool audio = true;
|
||
@override
|
||
Future<PreparedEditorMedia> prepare(String id) async {
|
||
if (id != 'source') throw StateError('missing media');
|
||
if (pending != null) return pending!.future;
|
||
return PreparedEditorMedia(
|
||
asset: EditorMediaAsset(id: id, name: 'Speech'),
|
||
uri: source,
|
||
duration: RationalTime.seconds(5),
|
||
kind: EditorMediaKind.audio,
|
||
hasAudio: audio,
|
||
audioTracks: [
|
||
MediaTrackTiming(start: audioStart, duration: MediaTime(5, 1)),
|
||
],
|
||
);
|
||
}
|
||
|
||
@override
|
||
Future<List<EditorMediaAsset>> query() async => [
|
||
EditorMediaAsset(id: 'source', name: 'Speech'),
|
||
];
|
||
@override
|
||
Future<EditorMediaImportResult> importFile(
|
||
String path, {
|
||
bool Function()? isCancelled,
|
||
}) => throw UnimplementedError();
|
||
}
|
||
|
||
class Backend implements AudioTranscriptionBackend {
|
||
int calls = 0;
|
||
AudioTranscriptionRequest? lastRequest;
|
||
final gate = Completer<void>();
|
||
final started = Completer<void>();
|
||
bool fail = false;
|
||
bool mismatch = false;
|
||
bool emitAfterCancellation = false;
|
||
bool publishAfterCancellation = false;
|
||
@override
|
||
Future<AudioTranscriptionResult> transcribe(
|
||
AudioTranscriptionRequest request, {
|
||
required void Function(TranscriptionProgress) onProgress,
|
||
required void Function(TranscriptionCue) onCue,
|
||
required ProcessingTaskSignal Function() taskSignal,
|
||
}) async {
|
||
calls++;
|
||
lastRequest = request;
|
||
if (!started.isCompleted) started.complete();
|
||
onProgress(const TranscriptionProgress('ASRInference', 0, 1));
|
||
onCue(const TranscriptionCue(200, 1200, '测试字幕'));
|
||
while (!gate.isCompleted && taskSignal() == ProcessingTaskSignal.none) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||
}
|
||
if (taskSignal() != ProcessingTaskSignal.none) {
|
||
if (emitAfterCancellation) {
|
||
onCue(const TranscriptionCue(1400, 1800, '迟到字幕'));
|
||
}
|
||
if (!publishAfterCancellation) {
|
||
throw ProcessingException(
|
||
taskSignal() == ProcessingTaskSignal.cancel
|
||
? 'cancelled'
|
||
: 'interrupted',
|
||
'Stopped',
|
||
);
|
||
}
|
||
}
|
||
if (fail) throw const ProcessingException('processingFailed', 'Failed');
|
||
final document = SubtitleDocument(
|
||
cues: [
|
||
SubtitleCue(200, 1200, mismatch ? '不一致' : '测试字幕'),
|
||
if (publishAfterCancellation) const SubtitleCue(1400, 1800, '迟到字幕'),
|
||
],
|
||
);
|
||
final subtitles = File.fromUri(
|
||
request.destination.resolve('subtitles.json'),
|
||
);
|
||
await subtitles.parent.create(recursive: true);
|
||
await subtitles.writeAsString(jsonEncode(document.toJson()));
|
||
await File.fromUri(request.destination.resolve('transcript.json'))
|
||
.writeAsString(
|
||
jsonEncode({
|
||
'schemaVersion': 1,
|
||
'sourceStartMs': request.sourceStartMs,
|
||
'sourcePath': request.source.toFilePath(),
|
||
'audioStream': request.audioStream,
|
||
'durationMs': 5000,
|
||
'detectedLanguages': ['zh'],
|
||
'cues': document.cues.map((c) => c.toJson()).toList(),
|
||
}),
|
||
);
|
||
for (final name in ['subtitles.srt', 'subtitles.vtt']) {
|
||
final file = File.fromUri(request.destination.resolve(name));
|
||
if (!await file.exists()) await file.writeAsString('测试字幕');
|
||
}
|
||
return AudioTranscriptionResult(
|
||
directory: request.destination,
|
||
durationMs: 5000,
|
||
document: document,
|
||
cues: [
|
||
TranscriptionCue(200, 1200, mismatch ? '不一致' : '测试字幕'),
|
||
if (publishAfterCancellation)
|
||
const TranscriptionCue(1400, 1800, '迟到字幕'),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
class TranslationBackend implements SubtitleTranslationBackend {
|
||
int calls = 0;
|
||
SubtitleTranslationRequest? lastRequest;
|
||
|
||
@override
|
||
Future<SubtitleTranslationResult> translateSubtitles(
|
||
SubtitleTranslationRequest request, {
|
||
required void Function(ProcessingProgress) onProgress,
|
||
required ProcessingTaskSignal Function() taskSignal,
|
||
}) async {
|
||
final sourceDocument = await SubtitleDocument.read(request.source);
|
||
calls++;
|
||
lastRequest = request;
|
||
onProgress(const ProcessingProgress('translation', 1, 1));
|
||
final directory = Directory.fromUri(request.destination);
|
||
await directory.create(recursive: true);
|
||
final translated = SubtitleDocument(
|
||
language: request.targetLanguage,
|
||
cues: const [SubtitleCue(200, 1200, '你好')],
|
||
);
|
||
await File('${directory.path}/subtitles.json')
|
||
.writeAsString(jsonEncode(translated.toJson()));
|
||
await File('${directory.path}/translation.json').writeAsString(
|
||
jsonEncode({
|
||
'schemaVersion': 1,
|
||
'provider': 'm2m100418m',
|
||
'sourceLanguage': request.sourceLanguage,
|
||
'targetLanguage': request.targetLanguage,
|
||
'cues': [
|
||
{
|
||
'startMs': 200,
|
||
'endMs': 1200,
|
||
'sourceText': sourceDocument.cues.single.text,
|
||
'text': '你好',
|
||
},
|
||
],
|
||
}),
|
||
);
|
||
for (final name in ['subtitles.srt', 'subtitles.vtt']) {
|
||
await File('${directory.path}/$name').writeAsString('你好');
|
||
}
|
||
return SubtitleTranslationResult(
|
||
directory: request.destination,
|
||
document: SubtitleDocument(
|
||
language: request.targetLanguage,
|
||
cues: const [SubtitleCue(200, 1200, '你好')],
|
||
),
|
||
sourceLanguage: request.sourceLanguage,
|
||
targetLanguage: request.targetLanguage,
|
||
cues: const [
|
||
TranslatedSubtitleCue(
|
||
startMs: 200,
|
||
endMs: 1200,
|
||
sourceText: 'こんにちは',
|
||
text: '你好',
|
||
),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
class CaptionBackend implements CaptionFileBackend {
|
||
CaptionFileDocument document = CaptionFileDocument(
|
||
format: CaptionFileFormat.srt,
|
||
languageTag: 'en-US',
|
||
cues: [
|
||
CaptionFileCue(
|
||
start: MediaTime(1, 2),
|
||
duration: MediaTime(1, 1),
|
||
text: 'Imported caption',
|
||
),
|
||
],
|
||
);
|
||
CaptionFileFormat? writtenFormat;
|
||
String? writtenLanguage;
|
||
MediaTime? writtenFrameDuration;
|
||
bool? writtenAllowChanges;
|
||
List<CaptionFileCue>? writtenCues;
|
||
bool failRead = false;
|
||
|
||
@override
|
||
Future<CaptionFileDocument> readCaptionFile(
|
||
Uri source,
|
||
CaptionFileFormat format,
|
||
) async {
|
||
if (failRead) throw const FormatException('invalid caption fixture');
|
||
return document;
|
||
}
|
||
|
||
@override
|
||
Future<CaptionFileWriteResult> writeCaptionFile({
|
||
required Uri destination,
|
||
required CaptionFileFormat format,
|
||
required List<CaptionFileCue> cues,
|
||
String languageTag = 'und',
|
||
MediaTime? frameDuration,
|
||
bool dropFrame = false,
|
||
bool allowChanges = false,
|
||
MediaTime? mediaDuration,
|
||
CaptionTimeRounding rounding = CaptionTimeRounding.exact,
|
||
}) async {
|
||
writtenFormat = format;
|
||
writtenLanguage = languageTag;
|
||
writtenFrameDuration = frameDuration;
|
||
writtenAllowChanges = allowChanges;
|
||
writtenCues = cues;
|
||
return CaptionFileWriteResult(
|
||
destination: destination,
|
||
cues: cues,
|
||
changes: const [],
|
||
);
|
||
}
|
||
}
|
||
|
||
Future<void> settle(EditorTimelineSession session) async {
|
||
for (
|
||
var i = 0;
|
||
i < 2000 && session.transcriptions!.tasks.any((task) => !task.terminal);
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
expect(session.transcriptions!.tasks.every((task) => task.terminal), true);
|
||
}
|
||
|
||
void main() {
|
||
TestWidgetsFlutterBinding.ensureInitialized();
|
||
final sequence = SequenceId('main');
|
||
late Directory root;
|
||
late ProjectFile project;
|
||
late EditorTimelineSession session;
|
||
late Media media;
|
||
late Backend backend;
|
||
late TranslationBackend translationBackend;
|
||
late CaptionBackend captionBackend;
|
||
|
||
setUp(() async {
|
||
root = await Directory.systemTemp.createTemp('cutdex-transcription-');
|
||
project = await ProjectFile.create(
|
||
Directory('${root.path}/test.cutdex'),
|
||
name: 'Test',
|
||
);
|
||
final document = TimelineDocument(
|
||
id: 'p',
|
||
name: 'Speech',
|
||
sequences: [
|
||
TimelineDto(
|
||
id: sequence,
|
||
format: TimelineFormat.fps30,
|
||
primaryStorylineId: StorylineId('primary'),
|
||
storylines: [
|
||
StorylineDto(id: StorylineId('primary'), elementIds: []),
|
||
],
|
||
elements: [],
|
||
),
|
||
],
|
||
);
|
||
await project.saveTimeline(document);
|
||
media = Media(Uri.file('${root.path}/speech.wav'));
|
||
backend = Backend();
|
||
translationBackend = TranslationBackend();
|
||
captionBackend = CaptionBackend();
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
media: media,
|
||
transcriptionBackend: backend,
|
||
transcriptionModel: Uri.directory('${root.path}/model'),
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/m2m100'),
|
||
captionFiles: captionBackend,
|
||
);
|
||
});
|
||
tearDown(() async {
|
||
await session.close();
|
||
await project.close();
|
||
await root.delete(recursive: true);
|
||
});
|
||
|
||
Future<CommandResult> invoke(
|
||
String name,
|
||
String id,
|
||
Map<String, Object?> args,
|
||
) => editorToolsFor(session, sequence).invoke(
|
||
name: name,
|
||
arguments: args,
|
||
context: CommandContext(operationId: id),
|
||
);
|
||
Map<String, Object?> args() => {
|
||
'mediaId': 'source',
|
||
'destination': '${root.path}/captions',
|
||
};
|
||
|
||
Future<void> reopenSession() async {
|
||
await session.close();
|
||
await project.close();
|
||
project = await ProjectFile.open(Directory('${root.path}/test.cutdex'));
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
media: media,
|
||
transcriptionBackend: backend,
|
||
transcriptionModel: Uri.directory('${root.path}/model'),
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/m2m100'),
|
||
captionFiles: captionBackend,
|
||
);
|
||
await session.restoreProcessingTasks();
|
||
}
|
||
|
||
test('published recognition survives missing terminal checkpoint and repeated reopen', () async {
|
||
backend.gate.complete();
|
||
final result = await invoke('media.transcribe', 'durable-asr', args());
|
||
await settle(session);
|
||
final records = await session.persistence.readProcessingTasks();
|
||
final record = records.single;
|
||
await session.persistence.writeProcessingTask(record['id'] as String, {
|
||
...record,
|
||
'status': 'running',
|
||
});
|
||
for (var i = 0; i < 2; i++) {
|
||
await reopenSession();
|
||
final task = session.transcriptions!.task(
|
||
result.data['taskId'] as String,
|
||
);
|
||
expect(task.status, TranscriptionStatus.succeeded);
|
||
expect(task.result!.cues.single.text, '测试字幕');
|
||
await invoke('media.transcribe', 'same-request-$i', args());
|
||
expect(backend.calls, 1);
|
||
}
|
||
});
|
||
|
||
test('published subtitles remain usable when the model is not installed after restart', () async {
|
||
backend.gate.complete();
|
||
final first = await invoke('media.transcribe', 'model-removed', args());
|
||
await settle(session);
|
||
await session.close();
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
media: media,
|
||
);
|
||
await session.restoreProcessingTasks();
|
||
expect(session.transcriptions!.recognitionAvailable, false);
|
||
expect(
|
||
session.transcriptions!.task(first.data['taskId'] as String).status,
|
||
TranscriptionStatus.succeeded,
|
||
);
|
||
final status = await invoke('transcription.query', 'recovered-query', {
|
||
'taskId': first.data['taskId'],
|
||
});
|
||
expect(status.status, CommandStatus.succeeded);
|
||
expect(status.data['status'], 'succeeded');
|
||
expect(backend.calls, 1);
|
||
});
|
||
|
||
test(
|
||
'translation publication survives restart and does not rerun the backend',
|
||
() async {
|
||
backend.gate.complete();
|
||
await invoke('media.transcribe', 'source-asr', args());
|
||
await settle(session);
|
||
final source = session.transcriptions!.tasks.single.result!.subtitles
|
||
.toFilePath();
|
||
final arguments = {
|
||
'source': source,
|
||
'sourceLanguage': 'zh',
|
||
'targetLanguage': 'en',
|
||
};
|
||
final started = await invoke(
|
||
'subtitle.translate',
|
||
'translate-durable',
|
||
arguments,
|
||
);
|
||
final task = session.transcriptions!.translationTask(
|
||
started.data['taskId'] as String,
|
||
);
|
||
while (!task.terminal) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
expect(task.status, TranscriptionStatus.succeeded);
|
||
await reopenSession();
|
||
expect(
|
||
session.transcriptions!.translationTask(task.id).status,
|
||
TranscriptionStatus.succeeded,
|
||
);
|
||
await invoke('subtitle.translate', 'translate-again', arguments);
|
||
expect(translationBackend.calls, 1);
|
||
},
|
||
);
|
||
|
||
test('interrupted recognition stays idle on reopen and explicit retry reuses destination', () async {
|
||
final result = await invoke('media.transcribe', 'interrupted-asr', args());
|
||
await backend.started.future;
|
||
final destination = backend.lastRequest!.destination;
|
||
await reopenSession();
|
||
expect(
|
||
session.transcriptions!.task(result.data['taskId'] as String).status,
|
||
TranscriptionStatus.interrupted,
|
||
);
|
||
expect(backend.calls, 1);
|
||
backend.gate.complete();
|
||
await invoke('media.transcribe', 'explicit-retry', args());
|
||
await settle(session);
|
||
expect(backend.calls, 2);
|
||
expect(backend.lastRequest!.destination, destination);
|
||
});
|
||
|
||
test(
|
||
'reconfiguration retains task history and close still cancels active work',
|
||
() async {
|
||
final service = session.transcriptions!;
|
||
final result = await invoke('media.transcribe', 'lifecycle', args());
|
||
final task = service.task(result.data['taskId'] as String);
|
||
await backend.started.future;
|
||
expect(
|
||
() => session.configureProcessing(
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/changed'),
|
||
),
|
||
throwsA(isA<CommandRejected>()),
|
||
);
|
||
expect(session.transcriptions, same(service));
|
||
session.configureProcessing(
|
||
transcriptionBackend: backend,
|
||
transcriptionModel: service.modelDirectory,
|
||
);
|
||
await session.close();
|
||
expect(task.terminal, isTrue);
|
||
expect(
|
||
() => session.configureProcessing(
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/changed'),
|
||
),
|
||
throwsA(isA<CommandRejected>()),
|
||
);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'invalid optional configuration leaves all existing services unchanged',
|
||
() {
|
||
final service = session.transcriptions!;
|
||
final model = service.translationModel;
|
||
expect(
|
||
() => session.configureProcessing(
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/changed'),
|
||
vocalSeparationModel: Uri.file('${root.path}/unpaired.pt'),
|
||
),
|
||
throwsArgumentError,
|
||
);
|
||
expect(session.transcriptions, same(service));
|
||
expect(service.translationModel, model);
|
||
},
|
||
);
|
||
|
||
test('completed tasks survive later model installation', () async {
|
||
final service = session.transcriptions!;
|
||
final result = await invoke('media.transcribe', 'history', args());
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
final task = service.task(result.data['taskId'] as String);
|
||
session.configureProcessing(
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/changed'),
|
||
);
|
||
expect(session.transcriptions, same(service));
|
||
expect(session.transcriptions!.task(task.id), same(task));
|
||
expect(task.result, isNotNull);
|
||
});
|
||
|
||
test(
|
||
'installing translation separately preserves recognition availability',
|
||
() {
|
||
session.configureProcessing(
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/new-m2m100'),
|
||
);
|
||
expect(session.transcriptions!.recognitionAvailable, isTrue);
|
||
expect(session.transcriptions!.translationAvailable, isTrue);
|
||
expect(session.transcriptions!.backend, same(backend));
|
||
expect(
|
||
session.transcriptions!.translationModel,
|
||
Uri.directory('${root.path}/new-m2m100'),
|
||
);
|
||
},
|
||
);
|
||
|
||
test('translation tool reads the portable subtitle document without editing captions', () async {
|
||
final start = await invoke('media.transcribe', 'recognize-ja', {
|
||
'mediaId': 'source',
|
||
'language': 'ja',
|
||
'destination': '${root.path}/recognized',
|
||
});
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
final subtitles = session.transcriptions!
|
||
.task(start.data['taskId'] as String)
|
||
.result!
|
||
.subtitles;
|
||
|
||
await session.close();
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
media: media,
|
||
translationBackend: translationBackend,
|
||
translationModel: Uri.directory('${root.path}/m2m100'),
|
||
);
|
||
expect(session.transcriptions!.recognitionAvailable, isFalse);
|
||
expect(
|
||
session.supportedCommandOperations,
|
||
isNot(contains(EditorOperation.startTranscription)),
|
||
);
|
||
final translated = await invoke('subtitle.translate', 'translate-ja', {
|
||
'source': subtitles.toFilePath(),
|
||
'sourceLanguage': 'ja',
|
||
'targetLanguage': 'en',
|
||
'threads': 4,
|
||
});
|
||
expect(translated.status, CommandStatus.succeeded);
|
||
final taskId = translated.data['taskId'] as String;
|
||
for (
|
||
var i = 0;
|
||
i < 100 && !session.transcriptions!.translationTask(taskId).terminal;
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||
}
|
||
final queried = await invoke('subtitleTranslation.query', 'query-ja', {
|
||
'taskId': taskId,
|
||
});
|
||
expect(queried.data['status'], 'succeeded');
|
||
expect((queried.data['result'] as Map)['cueCount'], 1);
|
||
expect(translationBackend.lastRequest!.source, subtitles);
|
||
expect(translationBackend.lastRequest!.targetLanguage, 'en');
|
||
expect(translationBackend.lastRequest!.execution.threads, 4);
|
||
expect(
|
||
session.persistence.timeline(sequence).exportDto().elements,
|
||
isEmpty,
|
||
);
|
||
});
|
||
|
||
test('caption role applies once, compiles text and restores content through undo and save', () async {
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final start = await invoke('media.transcribe', 'recognize', {
|
||
'mediaId': 'source',
|
||
'destination': '${root.path}/out',
|
||
});
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
final args = {
|
||
'taskId': start.data['taskId'],
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
};
|
||
final applied = await invoke('transcription.apply', 'apply', args);
|
||
expect(applied.status, CommandStatus.succeeded, reason: applied.message);
|
||
expect(applied.edit, EditOutcome.committed);
|
||
final repeated = await invoke('transcription.apply', 'apply', args);
|
||
expect(repeated.data, applied.data);
|
||
final id = (applied.data['captionIds'] as List).single as String;
|
||
final track = session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.elementById(ElementId(applied.data['roleId'] as String))!;
|
||
final owner = LayoutBodyId.element(track);
|
||
final components = session.layout(sequence).currentComponents!;
|
||
expect(components.isExpanded(owner), true);
|
||
final cueBody = components.componentBodies(owner).single;
|
||
expect(
|
||
components.scene.bodies[cueBody]!.height,
|
||
session.layoutConfiguration.captionHeight,
|
||
);
|
||
final controller = session.view(sequence);
|
||
final frame = controller.project(
|
||
TimelineViewportRect(width: 800, height: 400),
|
||
);
|
||
int indexOf(Object identity) => List.generate(
|
||
frame.length,
|
||
(index) => index,
|
||
).singleWhere((index) => frame.identityAt(index) == identity);
|
||
final roleBounds = controller.presentationBoundsAt(frame, indexOf(owner));
|
||
final cueBounds = controller.presentationBoundsAt(frame, indexOf(cueBody));
|
||
expect(roleBounds.top, cueBounds.top);
|
||
expect(roleBounds.height, cueBounds.height);
|
||
expect(roleBounds.height, session.layoutConfiguration.captionHeight);
|
||
final viewport = TimelineViewportRect(width: 800, height: 400);
|
||
expect(
|
||
controller
|
||
.hitTest(viewport: viewport, position: cueBounds.center)
|
||
?.identity,
|
||
cueBody,
|
||
);
|
||
expect(
|
||
controller
|
||
.hitTest(
|
||
viewport: viewport,
|
||
position: Offset(roleBounds.right - 1, roleBounds.center.dy),
|
||
)
|
||
?.identity,
|
||
isNull,
|
||
);
|
||
controller.setSelection([owner]);
|
||
expect(controller.selectedIdentities, isEmpty);
|
||
expect(
|
||
controller.hitTestRect(viewport: viewport, rectangle: roleBounds),
|
||
isNot(contains(owner)),
|
||
);
|
||
expect(session.resolveCaptionComponent(sequence, cueBody), isNotNull);
|
||
expect(session.caption(sequence, id).text, '测试字幕');
|
||
final transformed = await invoke('clip.setTransform', 'move-caption', {
|
||
'clipId': id,
|
||
'at': {'numerator': '1', 'denominator': 2},
|
||
'x': 192,
|
||
'y': 108,
|
||
'scaleX': 1.2,
|
||
'scaleY': .8,
|
||
'rotation': 15,
|
||
});
|
||
expect(transformed.status, CommandStatus.succeeded);
|
||
final transformedQuery = session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query();
|
||
final transformedCaption = transformedQuery.element(
|
||
transformedQuery.elementById(ElementId(id))!,
|
||
);
|
||
final captionTransform = ClipTransform.fromRecord(transformedCaption);
|
||
expect(captionTransform.x, closeTo(.1, 1e-9));
|
||
expect(captionTransform.y, closeTo(.1, 1e-9));
|
||
expect(captionTransform.scale, 1.2);
|
||
expect(captionTransform.scaleY, .8);
|
||
expect(captionTransform.rotation, 15);
|
||
session.undo(sequence);
|
||
final restoredQuery = session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query();
|
||
final restoredTransform = ClipTransform.fromRecord(
|
||
restoredQuery.element(restoredQuery.elementById(ElementId(id))!),
|
||
);
|
||
expect(restoredTransform.x, 0);
|
||
expect(restoredTransform.y, 0);
|
||
expect(restoredTransform.scale, 1);
|
||
expect(restoredTransform.scaleY, 1);
|
||
expect(restoredTransform.rotation, 0);
|
||
final unchanged = session.version;
|
||
session.setCaption(sequence, SetCaption(captionId: id, text: '测试字幕'));
|
||
expect(session.version, unchanged);
|
||
for (final invalid in [
|
||
SetCaption(captionId: id, text: 'bad\u0000text'),
|
||
SetCaption(captionId: id, color: 'red'),
|
||
SetCaption(captionId: id, duration: CommandTime(0, 1)),
|
||
SetCaption(captionId: id, start: CommandTime(1, 11)),
|
||
]) {
|
||
expect(
|
||
() => session.setCaption(sequence, invalid),
|
||
throwsA(isA<CommandRejected>()),
|
||
);
|
||
expect(session.version, unchanged);
|
||
}
|
||
final deleted = await invoke('timeline.delete', 'delete-cue', {
|
||
'clipId': id,
|
||
});
|
||
expect(deleted.status, CommandStatus.succeeded, reason: deleted.message);
|
||
expect(
|
||
() => session.caption(sequence, id),
|
||
throwsA(isA<CommandRejected>()),
|
||
);
|
||
session.undo(sequence);
|
||
final kernel = session.persistence.timeline(sequence);
|
||
final before = session.version;
|
||
final changed = await invoke('caption.set', 'edit-text', {
|
||
'captionId': id,
|
||
'text': '新字幕',
|
||
'fontSize': 36,
|
||
'start': {'numerator': '1', 'denominator': 2},
|
||
'duration': {'numerator': '2', 'denominator': 1},
|
||
});
|
||
expect(changed.status, CommandStatus.succeeded, reason: changed.message);
|
||
expect(session.version, isNot(before));
|
||
expect(session.caption(sequence, id).text, '新字幕');
|
||
final input = editorExecutionInput(
|
||
session,
|
||
sequence,
|
||
kernel.current,
|
||
EditorExecutionMedia(
|
||
bindings: {
|
||
for (final payload in session.payloads)
|
||
if (payload.type == 'audio')
|
||
PayloadRef(payload.id): ExecutionMediaBinding(
|
||
media: MediaReference(id: 'source', uri: media.source),
|
||
videoTrackSelection: null,
|
||
audioTrackSelection: TrackSelection.index(0),
|
||
),
|
||
},
|
||
),
|
||
settings: session.settings,
|
||
canvas: session.canvas,
|
||
payloads: session.payloads.toList(),
|
||
);
|
||
final compiled = const ExecutionCompiler().compile(input);
|
||
expect(compiled.plan.visualLayers.single.text!.text, '新字幕');
|
||
expect(compiled.plan.visualLayers.single.text!.canvas.width, 1728);
|
||
expect(compiled.plan.visualLayers.single.text!.canvas.height, 259);
|
||
expect(compiled.plan.visualLayers.single.text!.bottomAligned, isTrue);
|
||
expect(compiled.plan.visualLayers.single.text!.positionY, -0.30);
|
||
expect(compiled.plan.visualLayers.single.timelineRange.start.seconds, 0.5);
|
||
expect(compiled.plan.visualLayers.single.timelineRange.duration.seconds, 2);
|
||
session.undo(sequence);
|
||
expect(session.caption(sequence, id).text, '测试字幕');
|
||
session.undo(sequence);
|
||
expect(kernel.current.query().elementById(ElementId(id)), isNull);
|
||
session.redo(sequence);
|
||
session.redo(sequence);
|
||
await session.flush();
|
||
expect(session.dirty, false);
|
||
await session.close();
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
);
|
||
expect(session.caption(sequence, id).text, '新字幕');
|
||
final queried = await invoke('caption.query', 'after-reopen', {
|
||
'captionId': id,
|
||
});
|
||
expect(queried.data['text'], '新字幕');
|
||
expect(
|
||
session.caption(sequence, id).render(session.canvas).bottomAligned,
|
||
isTrue,
|
||
);
|
||
});
|
||
|
||
Future<String> applyFixture() async {
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final started = await invoke('media.transcribe', 'start-fixture', args());
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
return started.data['taskId'] as String;
|
||
}
|
||
|
||
test('clip transcription decodes only the trimmed source window', () async {
|
||
media.audioStart = MediaTime(1, 1);
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final trimmed = await invoke('timeline.trim', 'trim-for-asr', {
|
||
'clipId': 'clip',
|
||
'duration': {'numerator': '3', 'denominator': 1},
|
||
'leading': true,
|
||
});
|
||
expect(trimmed.status, CommandStatus.succeeded);
|
||
final started = await invoke('media.transcribe', 'clip-asr', {
|
||
'mediaId': 'source',
|
||
'clipId': 'clip',
|
||
'language': 'zh',
|
||
});
|
||
expect(started.status, CommandStatus.succeeded);
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
expect(backend.lastRequest?.sourceStartMs, 1000);
|
||
expect(backend.lastRequest?.sourceSeekMs, 2000);
|
||
expect(backend.lastRequest?.sourceDurationMs, 3000);
|
||
final applied = await invoke('transcription.apply', 'apply-clip-asr', {
|
||
'taskId': started.data['taskId'],
|
||
'clipId': 'clip',
|
||
});
|
||
expect(applied.status, CommandStatus.succeeded, reason: applied.message);
|
||
expect(applied.data['cueCount'], 1);
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
final clip = query.elementById(ElementId('clip'))!;
|
||
final caption = query.elementById(
|
||
ElementId((applied.data['captionIds'] as List).single as String),
|
||
)!;
|
||
expect(
|
||
query.absoluteStart(caption) - query.absoluteStart(clip),
|
||
200 * TimelineClock.ticksPerSecond ~/ 1000,
|
||
);
|
||
expect(query.element(caption).duration, TimelineClock.ticksPerSecond);
|
||
});
|
||
|
||
test(
|
||
'model-authored captions create distinct tracks and append atomically',
|
||
() async {
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final dispatcher = editorToolsFor(session, sequence);
|
||
final agentTools = editorAgentTools({'timeline': dispatcher});
|
||
expect(
|
||
agentTools.map((tool) => tool.name),
|
||
containsAll([
|
||
'captionTrack_create',
|
||
'caption_add',
|
||
'caption_query',
|
||
'subtitle_translate',
|
||
]),
|
||
);
|
||
Future<Map<String, Object?>> agentInvoke(
|
||
String name,
|
||
String id,
|
||
Map<String, Object?> args,
|
||
) async {
|
||
final tool = agentTools.singleWhere((tool) => tool.name == name);
|
||
final arguments = {'workspaceId': 'timeline', ...args};
|
||
expect(tool.validate(arguments), isNull);
|
||
final result = await tool.execute(
|
||
ToolCall(id: id, name: name, arguments: arguments),
|
||
ToolContext(
|
||
sessionId: 'test',
|
||
runId: 'test',
|
||
operationId: id,
|
||
cancellation: CancellationToken(),
|
||
onProgress: (_) {},
|
||
),
|
||
);
|
||
expect(result.isError, isFalse, reason: result.text);
|
||
return (result.data['data'] as Map).cast<String, Object?>();
|
||
}
|
||
|
||
Future<String> track(String id, String language) async {
|
||
final result = await agentInvoke('captionTrack_create', id, {
|
||
'name': id,
|
||
'language': language,
|
||
'expectedVersion': session.version,
|
||
});
|
||
return result['roleId'] as String;
|
||
}
|
||
|
||
Map<String, Object?> cue(String text, int start) => {
|
||
'text': text,
|
||
'start': {'numerator': '$start', 'denominator': 2},
|
||
'duration': {'numerator': '1', 'denominator': 2},
|
||
};
|
||
final ja = await track('Japanese', 'ja');
|
||
final original = await invoke('caption.add', 'original', {
|
||
'roleId': ja,
|
||
'cues': [cue('こんにちは', 1)],
|
||
});
|
||
expect(
|
||
original.status,
|
||
CommandStatus.succeeded,
|
||
reason: original.message,
|
||
);
|
||
final sourceId = (original.data['captionIds'] as List).single as String;
|
||
final tracks = await invoke('caption.list', 'list-tracks', {});
|
||
expect(tracks.status, CommandStatus.succeeded);
|
||
expect((tracks.data['tracks'] as List).single['cueCount'], 1);
|
||
expect(tracks.data.containsKey('cues'), isFalse);
|
||
|
||
final source = await invoke('caption.query', 'read-source', {
|
||
'captionId': sourceId,
|
||
});
|
||
expect(source.data['text'], 'こんにちは');
|
||
final zh = await track('Chinese', 'zh');
|
||
final otherZh = await track('Chinese alternative', 'zh');
|
||
expect(otherZh, isNot(zh));
|
||
final first = await invoke('caption.addTranslations', 'translated-one', {
|
||
'roleId': zh,
|
||
'cues': [
|
||
{'text': '你好', 'sourceCaptionId': sourceId},
|
||
],
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(first.status, CommandStatus.succeeded, reason: first.message);
|
||
final firstId = (first.data['captionIds'] as List).single as String;
|
||
expect(
|
||
session.queryCaption(sequence, firstId)['start'],
|
||
source.data['start'],
|
||
);
|
||
expect(
|
||
session.queryCaption(sequence, firstId)['duration'],
|
||
source.data['duration'],
|
||
);
|
||
final beforeBatch = session.version;
|
||
final batch = await invoke('caption.add', 'translated-batch', {
|
||
'roleId': zh,
|
||
'cues': [cue('再见', 6), cue('谢谢', 4)],
|
||
'expectedVersion': beforeBatch,
|
||
});
|
||
expect(batch.status, CommandStatus.succeeded, reason: batch.message);
|
||
expect(batch.data['cueCount'], 2);
|
||
final batchIds = (batch.data['captionIds'] as List).cast<String>();
|
||
expect(session.caption(sequence, batchIds.first).text, '谢谢');
|
||
expect(session.caption(sequence, sourceId).text, 'こんにちは');
|
||
final page = await invoke('caption.list', 'page-one', {
|
||
'roleId': zh,
|
||
'limit': 2,
|
||
});
|
||
expect(page.status, CommandStatus.succeeded, reason: page.message);
|
||
expect(page.data['total'], 3);
|
||
expect(page.data['nextOffset'], 2);
|
||
expect((page.data['cues'] as List).map((c) => c['text']), ['你好', '谢谢']);
|
||
final lastPage = await invoke('caption.list', 'page-two', {
|
||
'roleId': zh,
|
||
'offset': 2,
|
||
'limit': 2,
|
||
});
|
||
expect((lastPage.data['cues'] as List).single['text'], '再见');
|
||
expect(lastPage.data['nextOffset'], isNull);
|
||
expect(lastPage.data['saveState'], 'saved');
|
||
expect(
|
||
(await invoke('caption.list', 'bad-page', {'limit': 101})).status,
|
||
CommandStatus.rejected,
|
||
);
|
||
expect(
|
||
(await invoke('caption.list', 'missing-role', {
|
||
'roleId': 'missing',
|
||
})).status,
|
||
CommandStatus.rejected,
|
||
);
|
||
|
||
final version = session.version;
|
||
final invalidTranslation = await invoke(
|
||
'caption.addTranslations',
|
||
'invalid-translation-batch',
|
||
{
|
||
'roleId': zh,
|
||
'cues': [
|
||
{'sourceCaptionId': sourceId, 'text': 'valid'},
|
||
{'sourceCaptionId': 'missing', 'text': 'invalid'},
|
||
],
|
||
},
|
||
);
|
||
expect(invalidTranslation.status, CommandStatus.rejected);
|
||
expect(session.version, version);
|
||
for (final args in [
|
||
{
|
||
'roleId': zh,
|
||
'cues': [cue('valid', 0), cue(' ', 2)],
|
||
},
|
||
{
|
||
'roleId': 'clip',
|
||
'cues': [cue('invalid target', 0)],
|
||
},
|
||
{
|
||
'roleId': 'missing',
|
||
'cues': [cue('missing target', 0)],
|
||
},
|
||
{'roleId': zh, 'cues': <Object?>[]},
|
||
{
|
||
'roleId': zh,
|
||
'cues': [
|
||
{'text': 'x', 'sourceCaptionId': 'missing'},
|
||
],
|
||
},
|
||
{
|
||
'roleId': zh,
|
||
'cues': [
|
||
{...cue('x', 0), 'sourceCaptionId': sourceId},
|
||
],
|
||
},
|
||
{
|
||
'roleId': zh,
|
||
'cues': [cue('stale', 0)],
|
||
'expectedVersion': beforeBatch,
|
||
},
|
||
{
|
||
'roleId': zh,
|
||
'cues': [
|
||
{'text': 'missing timing'},
|
||
],
|
||
},
|
||
]) {
|
||
final rejected = await invoke(
|
||
'caption.add',
|
||
'invalid-${args.toString()}',
|
||
args,
|
||
);
|
||
expect(
|
||
rejected.status,
|
||
CommandStatus.rejected,
|
||
reason: rejected.message,
|
||
);
|
||
expect(session.version, version);
|
||
}
|
||
expect(
|
||
(await invoke('timeline.undo', 'undo-batch', {})).status,
|
||
CommandStatus.succeeded,
|
||
);
|
||
for (final id in batchIds) {
|
||
expect(
|
||
session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.elementById(ElementId(id)),
|
||
isNull,
|
||
);
|
||
}
|
||
expect(session.caption(sequence, firstId).text, '你好');
|
||
expect(
|
||
(await invoke('timeline.redo', 'redo-batch', {})).status,
|
||
CommandStatus.succeeded,
|
||
);
|
||
await reopenSession();
|
||
expect(session.caption(sequence, sourceId).text, 'こんにちは');
|
||
expect(session.caption(sequence, firstId).text, '你好');
|
||
expect(session.caption(sequence, batchIds.first).text, '谢谢');
|
||
},
|
||
);
|
||
|
||
test(
|
||
'translation applies to trimmed clip in its own role and undoes once',
|
||
() async {
|
||
media.audioStart = MediaTime(1, 1);
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
expect(
|
||
(await invoke('timeline.trim', 'trim-for-translation', {
|
||
'clipId': 'clip',
|
||
'duration': {'numerator': '3', 'denominator': 1},
|
||
'leading': true,
|
||
})).status,
|
||
CommandStatus.succeeded,
|
||
);
|
||
final recognized = await invoke('media.transcribe', 'recognize-ja', {
|
||
'mediaId': 'source',
|
||
'clipId': 'clip',
|
||
'language': 'ja',
|
||
});
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
final original = await invoke('transcription.apply', 'apply-ja', {
|
||
'taskId': recognized.data['taskId'],
|
||
'clipId': 'clip',
|
||
});
|
||
expect(
|
||
original.status,
|
||
CommandStatus.succeeded,
|
||
reason: original.message,
|
||
);
|
||
final started = await invoke('subtitle.translate', 'translate-zh', {
|
||
'source': session.transcriptions!
|
||
.task(recognized.data['taskId'] as String)
|
||
.result!
|
||
.subtitles
|
||
.toFilePath(),
|
||
'sourceLanguage': 'ja',
|
||
'targetLanguage': 'zh',
|
||
});
|
||
expect(started.status, CommandStatus.succeeded, reason: started.message);
|
||
for (
|
||
var i = 0;
|
||
i < 200 &&
|
||
session.transcriptions!.translationTasks.any((t) => !t.terminal);
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
final applied = await invoke('subtitleTranslation.apply', 'apply-zh', {
|
||
'taskId': started.data['taskId'],
|
||
'clipId': 'clip',
|
||
'source': media.source.toFilePath(),
|
||
'sourceStartMs': 1000,
|
||
});
|
||
expect(applied.status, CommandStatus.succeeded, reason: applied.message);
|
||
expect(applied.data['roleId'], isNot(original.data['roleId']));
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
final clip = query.elementById(ElementId('clip'))!;
|
||
final captionId = (applied.data['captionIds'] as List).single as String;
|
||
final caption = query.elementById(ElementId(captionId))!;
|
||
expect(
|
||
query.absoluteStart(caption) - query.absoluteStart(clip),
|
||
200 * TimelineClock.ticksPerSecond ~/ 1000,
|
||
);
|
||
expect(session.caption(sequence, captionId).text, '你好');
|
||
expect(
|
||
(await invoke('timeline.undo', 'undo-zh', {})).status,
|
||
CommandStatus.succeeded,
|
||
);
|
||
expect(
|
||
session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.elementById(ElementId(captionId)),
|
||
isNull,
|
||
);
|
||
expect(session.captionRole(sequence, language: 'ja'), isNotNull);
|
||
final mismatched = await invoke(
|
||
'subtitleTranslation.apply',
|
||
'wrong-clip',
|
||
{
|
||
'taskId': started.data['taskId'],
|
||
'clipId': 'missing',
|
||
'source': media.source.toFilePath(),
|
||
},
|
||
);
|
||
expect(mismatched.status, CommandStatus.rejected);
|
||
},
|
||
);
|
||
|
||
test('transcriptions reuse one sequence caption role', () async {
|
||
final task = await applyFixture();
|
||
final first = await invoke('transcription.apply', 'apply-role-1', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final second = await invoke('transcription.apply', 'apply-role-2', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(second.data['roleId'], first.data['roleId']);
|
||
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
final role = query.elementById(ElementId(first.data['roleId'] as String))!;
|
||
final rolePayload = session.payloadFor(query.element(role).payloadRef!);
|
||
expect(rolePayload?.type, 'caption-role');
|
||
expect(query.absoluteStart(role), 0);
|
||
final child = query.element(role).containerStoryline!;
|
||
expect(
|
||
query.storylineElements(child).where((handle) {
|
||
final ref = query.element(handle).payloadRef;
|
||
return ref != null && session.payloadFor(ref)?.type == 'caption';
|
||
}),
|
||
hasLength(2),
|
||
);
|
||
});
|
||
|
||
test(
|
||
'caption sidecar tools import and export through the runtime port',
|
||
() async {
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final imported = await invoke('caption.import', 'import-srt', {
|
||
'source': '${root.path}/captions.srt',
|
||
'format': 'srt',
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(
|
||
imported.status,
|
||
CommandStatus.succeeded,
|
||
reason: imported.message,
|
||
);
|
||
expect(imported.edit, EditOutcome.committed);
|
||
final id = (imported.data['captionIds'] as List).single as String;
|
||
expect(session.caption(sequence, id).text, 'Imported caption');
|
||
|
||
final exported = await invoke('caption.export', 'export-scc', {
|
||
'destination': '${root.path}/captions.scc',
|
||
'format': 'cea608',
|
||
'languageTag': 'en-US',
|
||
'frameDuration': {'numerator': '1001', 'denominator': 30000},
|
||
'allowChanges': true,
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(
|
||
exported.status,
|
||
CommandStatus.succeeded,
|
||
reason: exported.message,
|
||
);
|
||
expect(exported.edit, EditOutcome.notApplicable);
|
||
expect(captionBackend.writtenFormat, CaptionFileFormat.scenaristCea608);
|
||
expect(captionBackend.writtenLanguage, 'en-US');
|
||
expect(captionBackend.writtenFrameDuration!.numerator, 1001);
|
||
expect(captionBackend.writtenAllowChanges, true);
|
||
expect(captionBackend.writtenCues!.single.text, 'Imported caption');
|
||
},
|
||
);
|
||
|
||
test(
|
||
'caption import rejects an empty timeline without an unknown outcome',
|
||
() async {
|
||
final result = await invoke('caption.import', 'empty-timeline-srt', {
|
||
'source': '${root.path}/captions.srt',
|
||
'format': 'srt',
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(result.status, CommandStatus.rejected);
|
||
expect(result.code, 'missingCaptionAnchor');
|
||
expect(result.edit, EditOutcome.notCommitted);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'caption import reports decoder failures as a rejected command',
|
||
() async {
|
||
captionBackend.failRead = true;
|
||
final result = await invoke('caption.import', 'invalid-srt', {
|
||
'source': '${root.path}/invalid.srt',
|
||
'format': 'srt',
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(result.status, CommandStatus.rejected);
|
||
expect(result.code, 'captionImportFailed');
|
||
expect(result.edit, EditOutcome.notCommitted);
|
||
},
|
||
);
|
||
|
||
test('caption export rejects a role after its last cue is deleted', () async {
|
||
final task = await applyFixture();
|
||
final applied = await invoke('transcription.apply', 'apply-empty-role', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final captionId = (applied.data['captionIds'] as List).single as String;
|
||
await invoke('timeline.delete', 'delete-last-caption', {
|
||
'clipId': captionId,
|
||
'expectedVersion': session.version,
|
||
});
|
||
final result = await invoke('caption.export', 'export-empty-role', {
|
||
'destination': '${root.path}/empty.srt',
|
||
'format': 'srt',
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(result.status, CommandStatus.rejected);
|
||
expect(result.code, 'emptyCaptions');
|
||
expect(result.edit, EditOutcome.notApplicable);
|
||
});
|
||
|
||
for (final moveLeft in [false, true]) {
|
||
test('caption component drag expands role ${moveLeft ? "left" : "right"} '
|
||
'and preserves sibling times with undo', () async {
|
||
final task = await applyFixture();
|
||
final applied = await invoke('transcription.apply', 'apply-drag', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final captionId = (applied.data['captionIds'] as List).single as String;
|
||
session.splitCaption(
|
||
sequence,
|
||
SplitCaption(captionId: captionId, offset: CommandTime(1, 2)),
|
||
);
|
||
if (moveLeft) {
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Earlier speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(2),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('earlier'),
|
||
);
|
||
}
|
||
final kernel = session.persistence.timeline(sequence);
|
||
final before = kernel.current;
|
||
final q = before.query();
|
||
final cue = q.elementById(ElementId(captionId))!;
|
||
final parent = q.localContext(cue).storyline;
|
||
final sibling = q
|
||
.storylineElements(parent)
|
||
.firstWhere(
|
||
(candidate) =>
|
||
candidate != cue && q.element(candidate).payloadRef != null,
|
||
);
|
||
final siblingStart = q.absoluteStart(sibling);
|
||
final identity = session.captionComponentFor(sequence, cue)!;
|
||
final start = (moveLeft ? 0 : 6) * TimelineClock.ticksPerSecond;
|
||
final duration = 2 * TimelineClock.ticksPerSecond;
|
||
session.setCaptionComponentInterval(sequence, identity, start, duration);
|
||
final after = kernel.current;
|
||
final updated = after.query();
|
||
expect(updated.absoluteStart(cue), start);
|
||
expect(updated.element(cue).duration, duration);
|
||
expect(updated.absoluteStart(sibling), siblingStart);
|
||
final body = session
|
||
.layout(sequence)
|
||
.current!
|
||
.scene
|
||
.bodies[session.captionComponentFor(sequence, cue)!];
|
||
expect(body?.start, start);
|
||
expect(body?.end, start + duration);
|
||
await session.executeCommand(sequence, const UndoEdit());
|
||
expect(kernel.current, before);
|
||
await session.executeCommand(sequence, const RedoEdit());
|
||
expect(kernel.current, after);
|
||
});
|
||
}
|
||
|
||
test(
|
||
'caption commands expose sequence time after the connected role moves',
|
||
() async {
|
||
final task = await applyFixture();
|
||
final applied = await invoke('transcription.apply', 'apply-time-domain', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final captionId = (applied.data['captionIds'] as List).single as String;
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Earlier speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(2),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('earlier'),
|
||
);
|
||
final query = session.queryCaption(sequence, captionId);
|
||
expect(query['start'], {'numerator': '11', 'denominator': 5});
|
||
final beforeRole = await invoke(
|
||
'transcription.apply',
|
||
'apply-before-role',
|
||
{
|
||
'taskId': task,
|
||
'clipId': 'earlier',
|
||
'expectedVersion': session.version,
|
||
},
|
||
);
|
||
expect(beforeRole.code, 'captionBeforeRole');
|
||
|
||
session.setCaption(
|
||
sequence,
|
||
SetCaption(
|
||
captionId: captionId,
|
||
start: CommandTime(3, 1),
|
||
expectedVersion: session.version,
|
||
),
|
||
);
|
||
final timeline = session.persistence.timeline(sequence).current.query();
|
||
expect(
|
||
timeline.absoluteStart(timeline.elementById(ElementId(captionId))!),
|
||
TimelineClock.ticksPerSecond * 3,
|
||
);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'caption tools split and merge cues as one undoable edit each',
|
||
() async {
|
||
final task = await applyFixture();
|
||
final applied = await invoke('transcription.apply', 'apply-split', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final original = (applied.data['captionIds'] as List).single as String;
|
||
final styled = await invoke('caption.set', 'style-caption', {
|
||
'captionId': original,
|
||
'strokeColor': '#336699',
|
||
'strokeWidth': 2,
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(styled.status, CommandStatus.succeeded, reason: styled.message);
|
||
final split = await invoke('caption.split', 'split-caption', {
|
||
'captionId': original,
|
||
'offset': {'numerator': '1', 'denominator': 2},
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(split.status, CommandStatus.succeeded, reason: split.message);
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
final track = query.elementById(
|
||
ElementId(applied.data['roleId'] as String),
|
||
)!;
|
||
final child = query.element(track).containerStoryline!;
|
||
final cues = query
|
||
.storylineElements(child)
|
||
.where((handle) => query.element(handle).payloadRef != null)
|
||
.toList();
|
||
expect(cues, hasLength(2));
|
||
expect(
|
||
cues.map(
|
||
(handle) =>
|
||
session.caption(sequence, query.element(handle).id.value).text,
|
||
),
|
||
['测试', '字幕'],
|
||
);
|
||
for (final cue in cues) {
|
||
final caption = session.caption(sequence, query.element(cue).id.value);
|
||
expect(caption.render(session.canvas).bottomAligned, isTrue);
|
||
expect(caption.positionY, -0.30);
|
||
expect(caption.strokeColor, '#336699');
|
||
expect(caption.strokeWidth, 2);
|
||
}
|
||
final merged = await invoke('caption.merge', 'merge-captions', {
|
||
'captionIds': cues
|
||
.map((handle) => query.element(handle).id.value)
|
||
.toList(),
|
||
'expectedVersion': session.version,
|
||
});
|
||
expect(merged.status, CommandStatus.succeeded, reason: merged.message);
|
||
final after = session.persistence.timeline(sequence).current.query();
|
||
expect(
|
||
after
|
||
.storylineElements(child)
|
||
.where((handle) => after.element(handle).payloadRef != null),
|
||
hasLength(1),
|
||
);
|
||
expect(session.caption(sequence, original).text, '测试\n字幕');
|
||
expect(
|
||
session
|
||
.caption(sequence, original)
|
||
.render(session.canvas)
|
||
.bottomAligned,
|
||
isTrue,
|
||
);
|
||
expect(session.caption(sequence, original).positionY, -0.30);
|
||
expect(session.caption(sequence, original).strokeColor, '#336699');
|
||
expect(session.caption(sequence, original).strokeWidth, 2);
|
||
session.undo(sequence);
|
||
expect(
|
||
session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.storylineElements(child)
|
||
.where(
|
||
(handle) =>
|
||
session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.element(handle)
|
||
.payloadRef !=
|
||
null,
|
||
),
|
||
hasLength(2),
|
||
);
|
||
},
|
||
);
|
||
|
||
test('derived caption cue drag and trim commit authored timing', () async {
|
||
final task = await applyFixture();
|
||
final applied = await invoke('transcription.apply', 'apply-gesture', {
|
||
'taskId': task,
|
||
'clipId': 'clip',
|
||
'expectedVersion': session.version,
|
||
});
|
||
final cueId = (applied.data['captionIds'] as List).single as String;
|
||
final roleId = applied.data['roleId'] as String;
|
||
final controller = session.view(sequence);
|
||
final viewport = TimelineViewportRect(width: 800, height: 400);
|
||
|
||
LayoutBodyId cueBody() {
|
||
final query = controller.version.kernelVersion.query();
|
||
final track = query.elementById(ElementId(roleId))!;
|
||
return session
|
||
.layout(sequence)
|
||
.currentComponents!
|
||
.componentBodies(LayoutBodyId.element(track))
|
||
.single;
|
||
}
|
||
|
||
final selected = await invoke('selection.set', 'select-cue', {
|
||
'clipIds': [cueId],
|
||
});
|
||
expect(selected.status, CommandStatus.succeeded, reason: selected.message);
|
||
expect(controller.selectedIdentities.single, cueBody());
|
||
|
||
Rect boundsOf(LayoutBodyId body) {
|
||
final frame = controller.project(viewport);
|
||
final index = List.generate(
|
||
frame.length,
|
||
(i) => i,
|
||
).singleWhere((i) => frame.identityAt(i) == body);
|
||
return Rect.fromLTWH(
|
||
frame.screenLeftAt(index),
|
||
frame.screenTopAt(index),
|
||
frame.screenWidthAt(index),
|
||
frame.screenHeightAt(index),
|
||
);
|
||
}
|
||
|
||
var body = cueBody();
|
||
var bounds = boundsOf(body);
|
||
expect(
|
||
controller.hitTest(viewport: viewport, position: bounds.center)?.identity,
|
||
body,
|
||
reason: '$bounds',
|
||
);
|
||
expect(
|
||
controller.beginDrag(viewport: viewport, position: bounds.center),
|
||
true,
|
||
);
|
||
expect(
|
||
controller.finishDrag(
|
||
viewport: viewport,
|
||
position: bounds.center + const Offset(60, 0),
|
||
),
|
||
true,
|
||
);
|
||
var query = session.persistence.timeline(sequence).current.query();
|
||
var cue = query.elementById(ElementId(cueId))!;
|
||
expect(
|
||
query.localContext(cue).start,
|
||
TimelineClock.ticksPerSecond * 6 ~/ 5,
|
||
);
|
||
expect(query.element(cue).duration, TimelineClock.ticksPerSecond);
|
||
|
||
body = cueBody();
|
||
bounds = boundsOf(body);
|
||
expect(
|
||
controller.beginDrag(
|
||
viewport: viewport,
|
||
position: Offset(bounds.right - 1, bounds.center.dy),
|
||
trimHitExtent: 8,
|
||
),
|
||
true,
|
||
);
|
||
expect(
|
||
controller.finishDrag(
|
||
viewport: viewport,
|
||
position: Offset(bounds.right - 31, bounds.center.dy),
|
||
),
|
||
true,
|
||
);
|
||
query = session.persistence.timeline(sequence).current.query();
|
||
cue = query.elementById(ElementId(cueId))!;
|
||
expect(
|
||
query.localContext(cue).start,
|
||
TimelineClock.ticksPerSecond * 6 ~/ 5,
|
||
);
|
||
expect(query.element(cue).duration, TimelineClock.ticksPerSecond ~/ 2);
|
||
});
|
||
|
||
test('apply rejects stale, missing, mismatched and cancelled targets without changing history', () async {
|
||
final task = await applyFixture();
|
||
final version = session.version;
|
||
for (final (clip, expected, code) in [
|
||
('missing', version, 'missingClip'),
|
||
('clip', 'old', 'staleVersion'),
|
||
]) {
|
||
final result = await invoke('transcription.apply', code, {
|
||
'taskId': task,
|
||
'clipId': clip,
|
||
'expectedVersion': expected,
|
||
});
|
||
expect(result.code, code);
|
||
expect(session.version, version);
|
||
}
|
||
await expectLater(
|
||
session.applyTranscription(
|
||
sequence,
|
||
ApplyTranscription(taskId: task, clipId: 'clip'),
|
||
isCancelled: () => true,
|
||
),
|
||
throwsA(
|
||
isA<CommandRejected>().having((e) => e.code, 'code', 'cancelled'),
|
||
),
|
||
);
|
||
expect(session.version, version);
|
||
media.pending = Completer<PreparedEditorMedia>();
|
||
final applying = session.applyTranscription(
|
||
sequence,
|
||
ApplyTranscription(taskId: task, clipId: 'clip'),
|
||
);
|
||
session.commands.applyEdit(sequence, const DeleteClip('clip'));
|
||
media.pending!.complete(
|
||
PreparedEditorMedia(
|
||
asset: EditorMediaAsset(id: 'source', name: 'Speech'),
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
kind: EditorMediaKind.audio,
|
||
hasAudio: true,
|
||
),
|
||
);
|
||
await expectLater(
|
||
applying,
|
||
throwsA(
|
||
isA<CommandRejected>().having((e) => e.code, 'code', 'staleVersion'),
|
||
),
|
||
);
|
||
});
|
||
|
||
testWidgets(
|
||
'background task panel applies to its fixed target without a chooser',
|
||
(tester) async {
|
||
await tester.runAsync(() async {
|
||
await applyFixture();
|
||
await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(mediaId: 'source', clipId: 'clip'),
|
||
name: 'Speech',
|
||
);
|
||
await settle(session);
|
||
});
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
|
||
theme: EditorTheme.penDark,
|
||
home: Scaffold(body: BackgroundTasksDialog(session: session)),
|
||
),
|
||
),
|
||
);
|
||
session.view(sequence).clearSelection();
|
||
expect(find.text('应用原文字幕'), findsNothing);
|
||
await tester.tap(find.text('Speech'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('任务详情'), findsOneWidget);
|
||
await tester.ensureVisible(find.text('应用原文字幕').first);
|
||
await tester.runAsync(() async {
|
||
await tester.tap(find.text('应用原文字幕').first);
|
||
for (
|
||
var i = 0;
|
||
i < 100 &&
|
||
session.persistence.timeline(sequence).current.connectionCount ==
|
||
0;
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
});
|
||
await tester.pump();
|
||
expect(find.text('选择目标片段'), findsNothing);
|
||
expect(session.persistence.timeline(sequence).current.connectionCount, 1);
|
||
expect(find.text('已添加 1 条字幕,可在属性面板编辑。'), findsOneWidget);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
await tester.runAsync(session.flush);
|
||
},
|
||
);
|
||
|
||
for (final desktop in [false, true]) {
|
||
testWidgets(
|
||
'MCP caption edit desktop=$desktop updates visible fields and undo restores them',
|
||
(tester) async {
|
||
late String id;
|
||
await tester.runAsync(() async {
|
||
final task = await applyFixture();
|
||
final result = await session.applyTranscription(
|
||
sequence,
|
||
ApplyTranscription(taskId: task, clipId: 'clip'),
|
||
);
|
||
id = (result['captionIds'] as List).single as String;
|
||
});
|
||
await tester.pumpWidget(
|
||
MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
theme: desktop
|
||
? AppTheme.propertiesPanelTheme(
|
||
EditorTheme.desktop(EditorTheme.penDark),
|
||
)
|
||
: EditorTheme.penDark,
|
||
|
||
home: Scaffold(
|
||
body: Align(
|
||
alignment: Alignment.topRight,
|
||
child: SizedBox(
|
||
width: 280,
|
||
child: CaptionProperties(
|
||
session: session,
|
||
sequence: sequence,
|
||
clipId: id,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
expect(find.text('测试字幕'), findsOneWidget);
|
||
expect(
|
||
find.ancestor(
|
||
of: find.text('测试字幕'),
|
||
matching: find.byType(ShaderMask),
|
||
),
|
||
findsOneWidget,
|
||
);
|
||
expect(
|
||
find.byKey(const ValueKey('caption-property-tab-captions')),
|
||
findsOneWidget,
|
||
);
|
||
expect(
|
||
find.byKey(const ValueKey('caption-property-tab-text')),
|
||
findsOneWidget,
|
||
);
|
||
for (final key in const [
|
||
'caption-fontSize',
|
||
'caption-strokeWidth',
|
||
'caption-positionY',
|
||
'caption-start',
|
||
'caption-duration',
|
||
]) {
|
||
expect(find.byKey(Key(key)), findsOneWidget);
|
||
}
|
||
expect(find.text('描边颜色'), findsOneWidget);
|
||
await tester.runAsync(() async {
|
||
session.setCaption(
|
||
sequence,
|
||
SetCaption(
|
||
captionId: id,
|
||
start: CommandTime(1, 1000),
|
||
duration: CommandTime(1, 1000),
|
||
positionY: -.298,
|
||
),
|
||
);
|
||
await session.flush();
|
||
});
|
||
await tester.pump();
|
||
String fieldText(String key) => tester
|
||
.widget<TextField>(
|
||
find.descendant(
|
||
of: find.byKey(ValueKey(key)),
|
||
matching: find.byType(TextField),
|
||
),
|
||
)
|
||
.controller!
|
||
.text;
|
||
expect(fieldText('caption-start'), '0.001');
|
||
expect(fieldText('caption-duration'), '0.001');
|
||
expect(fieldText('caption-positionY'), '-0.298');
|
||
await tester.runAsync(() async => session.undo(sequence));
|
||
await tester.pump();
|
||
|
||
await tester.tap(
|
||
find.byKey(const ValueKey('caption-property-tab-captions')),
|
||
);
|
||
await tester.pump();
|
||
expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget);
|
||
expect(find.byKey(const Key('caption-fontSize')), findsNothing);
|
||
await tester.tap(find.byKey(ValueKey('caption-list-$id')));
|
||
await tester.pump();
|
||
expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget);
|
||
expect(find.byKey(const Key('caption-fontSize')), findsNothing);
|
||
await tester.tap(
|
||
find.byKey(const ValueKey('caption-property-tab-text')),
|
||
);
|
||
await tester.pump();
|
||
expect(find.byKey(const Key('caption-fontSize')), findsOneWidget);
|
||
final versionBeforeScrub = session.version;
|
||
await tester.drag(find.text('字号'), const Offset(50, 0));
|
||
await tester.pump();
|
||
expect(session.caption(sequence, id).fontSize, closeTo(58, 1e-9));
|
||
expect(session.version, isNot(versionBeforeScrub));
|
||
await tester.runAsync(() async => session.undo(sequence));
|
||
await tester.pump();
|
||
expect(session.caption(sequence, id).fontSize, 48);
|
||
final access = EditorToolAccess(session);
|
||
addTearDown(access.dispose);
|
||
final connection = access.server.connect();
|
||
addTearDown(connection.close);
|
||
final response = await tester.runAsync(
|
||
() => connection.handleJson(
|
||
jsonEncode({
|
||
'jsonrpc': '2.0',
|
||
'id': 1,
|
||
'method': 'tools/call',
|
||
'params': {
|
||
'_meta': {
|
||
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
||
'io.modelcontextprotocol/clientCapabilities':
|
||
<String, Object?>{},
|
||
},
|
||
'name': 'caption.set',
|
||
'arguments': {
|
||
'workspaceId': access.workspaces.keys.single,
|
||
'operationId': 'mcp-text',
|
||
'captionId': id,
|
||
'text': '来自 MCP 的字幕',
|
||
'strokeColor': '#FF0000',
|
||
'strokeWidth': 2,
|
||
},
|
||
},
|
||
}),
|
||
),
|
||
);
|
||
expect(response.toString(), contains('来自 MCP 的字幕'));
|
||
await tester.pump();
|
||
expect(find.text('来自 MCP 的字幕'), findsOneWidget);
|
||
expect(session.caption(sequence, id).strokeColor, '#FF0000');
|
||
expect(session.caption(sequence, id).strokeWidth, 2);
|
||
await tester.runAsync(() async {
|
||
session.undo(sequence);
|
||
});
|
||
await tester.pump();
|
||
expect(find.text('测试字幕'), findsOneWidget);
|
||
final role = session.captionRole(sequence)!;
|
||
await tester.pumpWidget(
|
||
MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
|
||
home: Scaffold(
|
||
body: SizedBox(
|
||
width: 280,
|
||
child: CaptionProperties(
|
||
session: session,
|
||
sequence: sequence,
|
||
clipId: session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.element(role)
|
||
.id
|
||
.value,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
expect(
|
||
find.byKey(const ValueKey('caption-property-tab-captions')),
|
||
findsOneWidget,
|
||
);
|
||
expect(
|
||
find.byKey(const ValueKey('caption-property-tab-text')),
|
||
findsNothing,
|
||
);
|
||
expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
},
|
||
);
|
||
}
|
||
|
||
for (final desktop in [false, true]) {
|
||
testWidgets(
|
||
'caption overview desktop=$desktop selects the chosen text cue',
|
||
(tester) async {
|
||
await tester.binding.setSurfaceSize(const Size(280, 240));
|
||
addTearDown(() => tester.binding.setSurfaceSize(null));
|
||
late String firstId;
|
||
late String secondId;
|
||
await tester.runAsync(() async {
|
||
final task = await applyFixture();
|
||
final first = await session.applyTranscription(
|
||
sequence,
|
||
ApplyTranscription(taskId: task, clipId: 'clip'),
|
||
);
|
||
final second = await session.applyTranscription(
|
||
sequence,
|
||
ApplyTranscription(taskId: task, clipId: 'clip'),
|
||
);
|
||
firstId = (first['captionIds'] as List).single as String;
|
||
secondId = (second['captionIds'] as List).single as String;
|
||
});
|
||
Widget panel(String clipId) => MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
theme: desktop
|
||
? AppTheme.propertiesPanelTheme(
|
||
EditorTheme.desktop(EditorTheme.penDark),
|
||
)
|
||
: EditorTheme.penDark,
|
||
|
||
home: Scaffold(
|
||
body: SizedBox(
|
||
width: 280,
|
||
child: CaptionProperties(
|
||
session: session,
|
||
sequence: sequence,
|
||
clipId: clipId,
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.pumpWidget(panel(firstId));
|
||
await tester.tap(
|
||
find.byKey(const ValueKey('caption-property-tab-captions')),
|
||
);
|
||
await tester.pump();
|
||
for (final id in [firstId, secondId]) {
|
||
final row = tester.getRect(find.byKey(ValueKey('caption-list-$id')));
|
||
final number = tester.getRect(
|
||
find.byKey(ValueKey('caption-number-$id')),
|
||
);
|
||
final content = tester.getRect(
|
||
find.byKey(ValueKey('caption-content-$id')),
|
||
);
|
||
final action = tester.getRect(
|
||
find.byKey(ValueKey('caption-action-$id')),
|
||
);
|
||
expect(row.height, 28);
|
||
final list = tester.getRect(
|
||
find.ancestor(
|
||
of: find.byKey(ValueKey('caption-list-$id')),
|
||
matching: find.byType(ListView),
|
||
),
|
||
);
|
||
expect(row.left - list.left, desktop ? 16 : 14);
|
||
expect(number.left - row.left, 0);
|
||
expect(content.left - number.right, 6);
|
||
expect(number.right, lessThan(content.left));
|
||
expect(content.right, lessThan(action.left));
|
||
expect(number.center.dy, closeTo(content.center.dy, 0.1));
|
||
expect(content.center.dy, closeTo(action.center.dy, 0.1));
|
||
expect(action.right, lessThanOrEqualTo(row.right));
|
||
}
|
||
await tester.runAsync(() async {
|
||
session.setCaption(
|
||
sequence,
|
||
SetCaption(captionId: secondId, text: 'Searchable CAPTION ' * 20),
|
||
);
|
||
await session.flush();
|
||
});
|
||
await tester.pump();
|
||
final search = find.byKey(const ValueKey('caption-search'));
|
||
final searchBounds = tester.getRect(search);
|
||
final wrapBounds = tester.getRect(
|
||
find.byKey(const ValueKey('caption-wrap-toggle')),
|
||
);
|
||
expect(searchBounds.height, desktop ? 24 : 28);
|
||
expect(wrapBounds.height, desktop ? 24 : 28);
|
||
expect(searchBounds.center.dy, wrapBounds.center.dy);
|
||
await tester.enterText(search, ' searchable ');
|
||
await tester.pump();
|
||
expect(find.byKey(ValueKey('caption-list-$firstId')), findsNothing);
|
||
expect(find.byKey(ValueKey('caption-list-$secondId')), findsOneWidget);
|
||
expect(
|
||
tester
|
||
.widget<Text>(find.byKey(ValueKey('caption-number-$secondId')))
|
||
.data,
|
||
'2',
|
||
);
|
||
expect(
|
||
tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height,
|
||
28,
|
||
);
|
||
await tester.enterText(search, 'no such caption');
|
||
await tester.pump();
|
||
expect(find.text('没有匹配的字幕'), findsOneWidget);
|
||
await tester.enterText(search, '');
|
||
await tester.pump();
|
||
expect(find.byKey(ValueKey('caption-list-$firstId')), findsOneWidget);
|
||
final toolbarPosition = tester.getTopLeft(search);
|
||
await tester.tap(find.byKey(const ValueKey('caption-wrap-toggle')));
|
||
await tester.pump();
|
||
expect(
|
||
tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height,
|
||
greaterThan(28),
|
||
);
|
||
expect(tester.getTopLeft(search), toolbarPosition);
|
||
final list = find.byKey(const ValueKey('caption-scroll-list'));
|
||
expect(list, findsOneWidget);
|
||
expect(
|
||
find.ancestor(of: search, matching: find.byType(ShaderMask)),
|
||
findsNothing,
|
||
);
|
||
expect(
|
||
find.ancestor(of: list, matching: find.byType(ShaderMask)),
|
||
findsOneWidget,
|
||
);
|
||
expect(
|
||
tester.widget<ListView>(list).physics,
|
||
isA<ClampingScrollPhysics>(),
|
||
);
|
||
final scroll = tester
|
||
.state<ScrollableState>(
|
||
find.descendant(of: list, matching: find.byType(Scrollable)),
|
||
)
|
||
.position;
|
||
expect(scroll.extentBefore, 0);
|
||
expect(scroll.extentAfter, greaterThan(24));
|
||
await tester.drag(list, const Offset(0, -60));
|
||
await tester.pumpAndSettle();
|
||
expect(scroll.pixels, greaterThan(0));
|
||
scroll.jumpTo(scroll.maxScrollExtent / 2);
|
||
await tester.pumpAndSettle();
|
||
expect(scroll.extentBefore, greaterThan(0));
|
||
expect(scroll.extentAfter, greaterThan(0));
|
||
scroll.jumpTo(scroll.maxScrollExtent);
|
||
await tester.pumpAndSettle();
|
||
expect(scroll.extentAfter, 0);
|
||
expect(tester.getTopLeft(search), toolbarPosition);
|
||
expect(tester.takeException(), isNull);
|
||
await tester.tap(find.byKey(const ValueKey('caption-wrap-toggle')));
|
||
await tester.pump();
|
||
expect(
|
||
tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height,
|
||
28,
|
||
);
|
||
await tester.pumpAndSettle();
|
||
expect(scroll.extentAfter, 0);
|
||
expect(scroll.extentBefore, 0);
|
||
await tester.tap(find.byKey(ValueKey('caption-action-$secondId')));
|
||
await tester.pump();
|
||
|
||
final identity = session.view(sequence).selectedIdentities.single;
|
||
expect(identity, isA<LayoutBodyId>());
|
||
final selected = session.resolveCaptionComponent(
|
||
sequence,
|
||
identity as LayoutBodyId,
|
||
);
|
||
expect(
|
||
session.persistence
|
||
.timeline(sequence)
|
||
.current
|
||
.query()
|
||
.element(selected!)
|
||
.id
|
||
.value,
|
||
secondId,
|
||
);
|
||
await tester.pumpWidget(panel(secondId));
|
||
await tester.pumpAndSettle();
|
||
final selectedRow = find.byKey(ValueKey('caption-list-$secondId'));
|
||
expect(selectedRow, findsOneWidget);
|
||
expect(find.byKey(const ValueKey('caption-search')), findsOneWidget);
|
||
expect(find.byKey(const Key('caption-fontSize')), findsNothing);
|
||
final selectedColor = Theme.of(tester.element(selectedRow))
|
||
.colorScheme
|
||
.onSurface
|
||
.withValues(alpha: .05);
|
||
expect(
|
||
find.ancestor(
|
||
of: selectedRow,
|
||
matching: find.byWidgetPredicate(
|
||
(widget) => widget is Material && widget.color == selectedColor,
|
||
),
|
||
),
|
||
findsOneWidget,
|
||
);
|
||
await tester.tap(selectedRow);
|
||
await tester.pump();
|
||
expect(selectedRow, findsOneWidget);
|
||
expect(find.byKey(const Key('caption-fontSize')), findsNothing);
|
||
},
|
||
);
|
||
}
|
||
|
||
test(
|
||
'completed transcription output is reused and persists inside the project',
|
||
() async {
|
||
final version = session.version;
|
||
final revision = session.persistence.revision;
|
||
final first = await invoke('media.transcribe', 'managed-first', {
|
||
'mediaId': 'source',
|
||
});
|
||
expect(first.status, CommandStatus.succeeded);
|
||
await backend.started.future;
|
||
final output = Directory.fromUri(backend.lastRequest!.destination);
|
||
expect(
|
||
output.uri.toString(),
|
||
startsWith(project.directory.uri.resolve('artifacts/').toString()),
|
||
);
|
||
expect(await output.exists(), false);
|
||
expect(await output.parent.exists(), true);
|
||
// Model publication writes into the reserved leaf, never an existing folder.
|
||
await output.create();
|
||
final caption = File('${output.path}/subtitles.srt');
|
||
await caption.writeAsString('测试字幕');
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
await invoke('media.transcribe', 'managed-second', {'mediaId': 'source'});
|
||
await settle(session);
|
||
expect(backend.lastRequest!.destination, output.uri);
|
||
expect(backend.calls, 1);
|
||
expect(session.version, version);
|
||
expect(session.persistence.revision, revision);
|
||
expect(session.dirty, false);
|
||
expect(session.canUndo(sequence), false);
|
||
await session.close();
|
||
await project.close();
|
||
project = await ProjectFile.open(project.directory);
|
||
expect(await caption.readAsString(), '测试字幕');
|
||
},
|
||
);
|
||
|
||
test('tool start is nonblocking, shares UI notifications and deduplicates requests', () async {
|
||
final version = session.version;
|
||
var notifications = 0;
|
||
session.addListener(() => notifications++);
|
||
final first = await invoke('media.transcribe', 'start', args());
|
||
expect(first.status, CommandStatus.succeeded);
|
||
expect(first.edit, EditOutcome.notApplicable);
|
||
await backend.started.future;
|
||
expect(
|
||
(await invoke('media.transcribe', 'start', args())).data['taskId'],
|
||
first.data['taskId'],
|
||
);
|
||
final state = await invoke('transcription.query', 'query', {
|
||
'taskId': first.data['taskId'],
|
||
});
|
||
expect(state.data['status'], 'running');
|
||
expect((state.data['progress'] as Map)['stage'], 'ASRInference');
|
||
expect(state.data['timelineCueCount'], 1);
|
||
expect(
|
||
(state.data['timelineCues'] as List).single,
|
||
containsPair('text', '测试字幕'),
|
||
);
|
||
expect((await invoke('media.transcribe', 'other', args())).code, 'busy');
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
final result = await invoke('transcription.query', 'query', {
|
||
'taskId': first.data['taskId'],
|
||
});
|
||
expect(result.data['status'], 'succeeded');
|
||
expect((result.data['result'] as Map)['cueCount'], 1);
|
||
expect(backend.calls, 1);
|
||
expect(notifications, greaterThan(2));
|
||
expect(session.version, version);
|
||
expect(session.dirty, false);
|
||
expect(session.canUndo(sequence), false);
|
||
});
|
||
|
||
test('cancel reaches the active backend and keeps the original operation receipt', () async {
|
||
final started = await invoke('media.transcribe', 'start', args());
|
||
await backend.started.future;
|
||
final id = started.data['taskId'];
|
||
expect(
|
||
(await invoke('transcription.cancel', 'cancel', {'taskId': id})).status,
|
||
CommandStatus.succeeded,
|
||
);
|
||
await settle(session);
|
||
expect(
|
||
session.transcriptions!.tasks.single.status,
|
||
TranscriptionStatus.cancelled,
|
||
);
|
||
await invoke('media.transcribe', 'start', args());
|
||
expect(backend.calls, 1);
|
||
expect(
|
||
(await invoke('transcription.cancel', 'missing', {
|
||
'taskId': 'missing',
|
||
})).code,
|
||
'missingTask',
|
||
);
|
||
});
|
||
|
||
test('cancelled transcription ignores late backend cues', () async {
|
||
backend.emitAfterCancellation = true;
|
||
final started = await invoke('media.transcribe', 'late-cue', args());
|
||
await backend.started.future;
|
||
await invoke('transcription.cancel', 'cancel-late-cue', {
|
||
'taskId': started.data['taskId'],
|
||
});
|
||
await settle(session);
|
||
|
||
final task = session.transcriptions!.tasks.single;
|
||
expect(task.status, TranscriptionStatus.cancelled);
|
||
expect(task.timelineCues.map((cue) => cue.text), ['测试字幕']);
|
||
});
|
||
|
||
test('published result can win a late transcription cancellation', () async {
|
||
backend.emitAfterCancellation = true;
|
||
backend.publishAfterCancellation = true;
|
||
final started = await invoke('media.transcribe', 'published-late', args());
|
||
await backend.started.future;
|
||
await invoke('transcription.cancel', 'cancel-published-late', {
|
||
'taskId': started.data['taskId'],
|
||
});
|
||
await settle(session);
|
||
|
||
final task = session.transcriptions!.tasks.single;
|
||
expect(task.status, TranscriptionStatus.succeeded);
|
||
expect(task.result!.cues.map((cue) => cue.text), ['测试字幕', '迟到字幕']);
|
||
expect(task.timelineCues.map((cue) => cue.text), ['测试字幕']);
|
||
});
|
||
|
||
test('close interrupts queued media preparation without waiting on workspace I/O', () async {
|
||
media.pending = Completer<PreparedEditorMedia>();
|
||
await invoke('media.transcribe', 'start', args());
|
||
await session.close().timeout(const Duration(seconds: 2));
|
||
expect(
|
||
session.transcriptions!.tasks.single.status,
|
||
TranscriptionStatus.interrupted,
|
||
);
|
||
expect(backend.calls, 0);
|
||
media.pending!.completeError(StateError('project switched'));
|
||
await Future<void>.delayed(Duration.zero);
|
||
});
|
||
|
||
test(
|
||
'invalid request and source without audio never invoke native recognition',
|
||
() async {
|
||
expect(
|
||
(await invoke('media.transcribe', 'bad-lang', {
|
||
...args(),
|
||
'language': 'invalid',
|
||
})).code,
|
||
'invalidArguments',
|
||
);
|
||
expect(
|
||
(await invoke('media.transcribe', 'removed-duration', {
|
||
...args(),
|
||
'maximumDurationSeconds': 60,
|
||
})).code,
|
||
'invalidArguments',
|
||
);
|
||
expect(
|
||
(await invoke('media.transcribe', 'version', {
|
||
...args(),
|
||
'expectedVersion': session.version,
|
||
})).code,
|
||
'invalidArguments',
|
||
);
|
||
media.audio = false;
|
||
await invoke('media.transcribe', 'no-audio', args());
|
||
await settle(session);
|
||
expect(session.transcriptions!.tasks.single.error, 'noAudio');
|
||
expect(backend.calls, 0);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'failed jobs can be retried with a new ID without replaying old requests',
|
||
() async {
|
||
backend.fail = true;
|
||
backend.gate.complete();
|
||
final first = await invoke('media.transcribe', 'failed', args());
|
||
await settle(session);
|
||
final firstDestination = backend.lastRequest!.destination;
|
||
expect(
|
||
session.transcriptions!.task(first.data['taskId'] as String).status,
|
||
TranscriptionStatus.failed,
|
||
);
|
||
backend.fail = false;
|
||
final retry = await invoke('media.transcribe', 'retry', args());
|
||
await settle(session);
|
||
expect(backend.lastRequest!.destination, firstDestination);
|
||
expect(
|
||
session.transcriptions!.task(retry.data['taskId'] as String).status,
|
||
TranscriptionStatus.succeeded,
|
||
);
|
||
expect(backend.calls, 2);
|
||
await invoke('media.transcribe', 'failed', args());
|
||
expect(backend.calls, 2);
|
||
},
|
||
);
|
||
|
||
test('a mismatched final artifact never becomes applicable', () async {
|
||
backend.mismatch = true;
|
||
backend.gate.complete();
|
||
await invoke('media.transcribe', 'mismatch', args());
|
||
await settle(session);
|
||
final task = session.transcriptions!.tasks.single;
|
||
expect(task.status, TranscriptionStatus.failed);
|
||
expect(task.error, 'invalidResult');
|
||
expect(task.result, isNull);
|
||
expect(task.timelineCues.single.text, '测试字幕');
|
||
});
|
||
|
||
test(
|
||
'completed task history stays bounded without disabling transcription',
|
||
() async {
|
||
backend.gate.complete();
|
||
for (var index = 0; index < 33; index++) {
|
||
final result = await invoke('media.transcribe', 'history-$index', {
|
||
...args(),
|
||
'destination': '${root.path}/captions-$index',
|
||
});
|
||
expect(result.status, CommandStatus.succeeded);
|
||
await settle(session);
|
||
}
|
||
|
||
expect(backend.calls, 33);
|
||
expect(session.transcriptions!.tasks, hasLength(32));
|
||
expect(
|
||
session.transcriptions!.tasks.every(
|
||
(task) => task.status == TranscriptionStatus.succeeded,
|
||
),
|
||
true,
|
||
);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'closing a project interrupts its active transcription before returning',
|
||
() async {
|
||
await invoke('media.transcribe', 'active', args());
|
||
await backend.started.future;
|
||
await session.close();
|
||
expect(
|
||
session.transcriptions!.tasks.single.status,
|
||
TranscriptionStatus.interrupted,
|
||
);
|
||
expect(session.acceptsEdits, false);
|
||
},
|
||
);
|
||
|
||
test('background task cancellation prevents automatic translation', () async {
|
||
final job = await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(mediaId: 'source', language: 'ja'),
|
||
name: 'Speech',
|
||
targetLanguage: 'zh',
|
||
);
|
||
await backend.started.future;
|
||
final completed = Completer<void>();
|
||
void checkCompletion() {
|
||
if (job.terminal && !completed.isCompleted) completed.complete();
|
||
}
|
||
|
||
session.addListener(checkCompletion);
|
||
addTearDown(() => session.removeListener(checkCompletion));
|
||
await session.subtitleWorkflows.cancel(job);
|
||
checkCompletion();
|
||
await completed.future.timeout(const Duration(seconds: 5));
|
||
expect(job.status, TranscriptionStatus.cancelled);
|
||
expect(job.terminal, true);
|
||
expect(session.subtitleWorkflows.runningCount, 0);
|
||
expect(translationBackend.lastRequest, isNull);
|
||
});
|
||
|
||
test(
|
||
'background failed task can be retried with a new recognition task',
|
||
() async {
|
||
backend.fail = true;
|
||
backend.gate.complete();
|
||
final first = await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(mediaId: 'source'),
|
||
name: 'Speech',
|
||
);
|
||
await settle(session);
|
||
expect(first.status, TranscriptionStatus.failed);
|
||
backend.fail = false;
|
||
await session.subtitleWorkflows.retry(first);
|
||
await settle(session);
|
||
final retry = session.subtitleWorkflows.tasks.last;
|
||
expect(retry.recognition.id, isNot(first.recognition.id));
|
||
expect(retry.status, TranscriptionStatus.succeeded);
|
||
expect(backend.calls, 2);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'task snapshots preserve prior status while the SDK task mutates',
|
||
() async {
|
||
final registry = BackgroundTaskRegistry();
|
||
final container = ProviderContainer();
|
||
addTearDown(() {
|
||
container.dispose();
|
||
registry.dispose();
|
||
});
|
||
registry.register(
|
||
projectId: 'project',
|
||
projectName: 'Project',
|
||
session: session,
|
||
);
|
||
final provider = backgroundTasksProvider(registry: registry);
|
||
final completedSnapshot = Completer<void>();
|
||
container.listen(provider, (_, snapshot) {
|
||
if (snapshot.runningCount == 0 &&
|
||
snapshot.subtitles.singleOrNull?.status ==
|
||
TranscriptionStatus.succeeded &&
|
||
!completedSnapshot.isCompleted) {
|
||
completedSnapshot.complete();
|
||
}
|
||
});
|
||
final job = await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(mediaId: 'source'),
|
||
name: 'Speech',
|
||
);
|
||
await backend.started.future;
|
||
final before = container.read(provider);
|
||
expect(before.runningCount, 1);
|
||
expect(before.subtitles.single.status, TranscriptionStatus.running);
|
||
expect(before.subtitles.single.recognizedCues, 1);
|
||
expect(before.subtitles.single.recentCues, ['测试字幕']);
|
||
expect(before.subtitles.single.resultCues, isEmpty);
|
||
expect(before.subtitles.single.recognitionAvailable, isFalse);
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
await session.flush();
|
||
await completedSnapshot.future.timeout(const Duration(seconds: 5));
|
||
final after = container.read(provider);
|
||
expect(job.status, TranscriptionStatus.succeeded);
|
||
expect(after.runningCount, 0);
|
||
expect(after.subtitles.single.status, TranscriptionStatus.succeeded);
|
||
expect(after.subtitles.single.resultCues, ['测试字幕']);
|
||
expect(after.subtitles.single.recognitionAvailable, isTrue);
|
||
expect(before.subtitles.single.status, TranscriptionStatus.running);
|
||
expect(before.subtitles.single.resultCues, isEmpty);
|
||
expect(before.subtitles.single.recognitionAvailable, isFalse);
|
||
},
|
||
);
|
||
|
||
test(
|
||
'subtitle application keeps the version captured before a target chooser',
|
||
() async {
|
||
await applyFixture();
|
||
final job = await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(mediaId: 'source', clipId: 'clip'),
|
||
name: 'Speech',
|
||
);
|
||
await settle(session);
|
||
final version = session.version;
|
||
session.commands.applyEdit(sequence, const DeleteClip('clip'));
|
||
final container = ProviderContainer();
|
||
addTearDown(container.dispose);
|
||
final provider = subtitleTaskActionsProvider(session, job.id);
|
||
container.listen(provider, (_, _) {});
|
||
await container
|
||
.read(provider.notifier)
|
||
.apply(job, 'clip', expectedVersion: version);
|
||
final failure = container.read(provider).error as SubtitleActionException;
|
||
expect(failure.kind, SubtitleActionKind.original);
|
||
expect(
|
||
failure.cause,
|
||
isA<CommandRejected>().having(
|
||
(value) => value.code,
|
||
'code',
|
||
'staleVersion',
|
||
),
|
||
);
|
||
expect(session.persistence.timeline(sequence).current.connectionCount, 0);
|
||
},
|
||
);
|
||
|
||
testWidgets('empty background tasks use menu row spacing', (tester) async {
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(body: BackgroundTasksContent(session: session)),
|
||
),
|
||
),
|
||
);
|
||
final row = find.byKey(const Key('background-tasks-empty-state'));
|
||
final label = find.text('暂无后台任务');
|
||
expect(tester.getSize(row).height, AppMenuMetrics.rowHeight);
|
||
expect(tester.getRect(label).left - tester.getRect(row).left, 8);
|
||
expect(find.text('后台任务'), findsNothing);
|
||
});
|
||
|
||
testWidgets('task popover shows results in a bounded scrolling list', (
|
||
tester,
|
||
) async {
|
||
await tester.runAsync(applyFixture);
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(
|
||
body: Align(
|
||
alignment: Alignment.topLeft,
|
||
child: AppPopover(
|
||
width: 384,
|
||
maxHeight: 180,
|
||
builder: (_, toggle) => IconButton(
|
||
onPressed: toggle,
|
||
icon: const Icon(AppIcons.success),
|
||
),
|
||
child: BackgroundTasksContent(session: session),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.tap(find.byType(IconButton));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('后台任务'), findsNothing);
|
||
expect(find.textContaining('字幕已生成'), findsOneWidget);
|
||
expect(find.text('应用原文字幕'), findsNothing);
|
||
expect(find.byIcon(AppIcons.chevronRight), findsNothing);
|
||
final taskRow = find
|
||
.ancestor(of: find.text('source'), matching: find.byType(InkWell))
|
||
.first;
|
||
expect(
|
||
tester.widget<InkWell>(taskRow).hoverColor,
|
||
AppSidebarColors.of(tester.element(taskRow)).hover,
|
||
);
|
||
await tester.tap(find.text('source'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('任务详情'), findsOneWidget);
|
||
await tester.ensureVisible(find.text('应用原文字幕'));
|
||
await tester.pumpAndSettle();
|
||
expect(tester.takeException(), isNull);
|
||
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('任务详情'), findsNothing);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
});
|
||
|
||
testWidgets(
|
||
'closing subtitle download keeps it in background until cancelled',
|
||
(tester) async {
|
||
session.transcriptions!.configure(
|
||
backend: null,
|
||
modelDirectory: null,
|
||
translationBackend: null,
|
||
translationModel: null,
|
||
);
|
||
late Completer<void> speechStarted;
|
||
late Completer<void> speechRelease;
|
||
late Completer<void> translationStarted;
|
||
late Completer<void> translationRelease;
|
||
late HttpServer server;
|
||
late ProcessingResourceRepository repository;
|
||
await tester.runAsync(() async {
|
||
speechStarted = Completer<void>();
|
||
speechRelease = Completer<void>();
|
||
translationStarted = Completer<void>();
|
||
translationRelease = Completer<void>();
|
||
server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
|
||
final payloads = {
|
||
ProcessingCapability.transcription: List.filled(20, 1),
|
||
ProcessingCapability.translation: List.filled(60, 2),
|
||
};
|
||
repository = ProcessingResourceRepository(
|
||
root: Directory('${root.path}/resources/Processing'),
|
||
catalog: [
|
||
for (final entry in payloads.entries)
|
||
ProcessingResourcePackage(
|
||
capability: entry.key,
|
||
id: entry.key.name,
|
||
version: '1',
|
||
name: 'Private model 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 capability = ProcessingCapability.values.byName(
|
||
request.uri.pathSegments.single,
|
||
);
|
||
if (capability == ProcessingCapability.transcription) {
|
||
speechStarted.complete();
|
||
await speechRelease.future;
|
||
} else {
|
||
translationStarted.complete();
|
||
await translationRelease.future;
|
||
}
|
||
try {
|
||
request.response.add(payloads[capability]!);
|
||
await request.response.close();
|
||
} on SocketException {
|
||
// The dialog cancelled the pending response.
|
||
} on HttpException {
|
||
// The dialog cancelled the pending response.
|
||
}
|
||
});
|
||
});
|
||
addTearDown(() async {
|
||
if (!speechRelease.isCompleted) speechRelease.complete();
|
||
if (!translationRelease.isCompleted) translationRelease.complete();
|
||
await server.close(force: true);
|
||
repository.dispose();
|
||
});
|
||
final container = ProviderContainer(
|
||
overrides: [
|
||
processingResourceRepositoryProvider.overrideWith(
|
||
(ref) async => repository,
|
||
),
|
||
],
|
||
);
|
||
addTearDown(container.dispose);
|
||
await tester.pumpWidget(
|
||
UncontrolledProviderScope(
|
||
container: container,
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(
|
||
body: Builder(
|
||
builder: (context) => TextButton(
|
||
onPressed: () => showAppDialog<void>(
|
||
context: context,
|
||
builder: (_) => TranscriptionDialog.forCurrentTask(
|
||
session: session,
|
||
asset: AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: '/speech.wav',
|
||
),
|
||
),
|
||
),
|
||
child: const Text('Open'),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.tap(find.text('Open'));
|
||
await tester.pumpAndSettle();
|
||
await tester.runAsync(() async {
|
||
await HttpOverrides.runWithHttpOverrides(() async {
|
||
await tester.tap(
|
||
find.byKey(const Key('download-transcription-resource')),
|
||
);
|
||
await speechStarted.future.timeout(const Duration(seconds: 5));
|
||
}, _LocalDownloadHttpOverrides());
|
||
});
|
||
await tester.pump();
|
||
expect(find.text('语音识别资源'), findsOneWidget);
|
||
expect(find.text('0%'), findsOneWidget);
|
||
expect(find.text('取消下载'), findsOneWidget);
|
||
expect(find.text('后台下载'), findsOneWidget);
|
||
expect(find.textContaining('正在下载…'), findsNothing);
|
||
expect(find.textContaining('下载资源大小'), findsNothing);
|
||
expect(find.text('暂停'), findsOneWidget);
|
||
expect(find.text('Private model name'), findsNothing);
|
||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||
expect(
|
||
tester
|
||
.widget<LinearProgressIndicator>(
|
||
find.byType(LinearProgressIndicator),
|
||
)
|
||
.value,
|
||
0,
|
||
);
|
||
await tester.tap(find.text('暂停'));
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isTrue);
|
||
expect(find.text('已暂停'), findsOneWidget);
|
||
expect(find.text('继续'), findsOneWidget);
|
||
await tester.tap(find.text('继续'));
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isFalse);
|
||
expect(find.text('暂停'), findsOneWidget);
|
||
await tester.runAsync(() async {
|
||
speechRelease.complete();
|
||
await translationStarted.future.timeout(const Duration(seconds: 5));
|
||
});
|
||
await tester.pump();
|
||
expect(find.text('语音识别资源'), findsNothing);
|
||
expect(find.text('翻译资源'), findsOneWidget);
|
||
expect(find.text('25%'), findsOneWidget);
|
||
expect(find.byType(LinearProgressIndicator), findsOneWidget);
|
||
expect(
|
||
tester
|
||
.widget<LinearProgressIndicator>(
|
||
find.byType(LinearProgressIndicator),
|
||
)
|
||
.value,
|
||
.25,
|
||
);
|
||
await tester.tap(
|
||
find.byKey(const Key('background-transcription-resource')),
|
||
);
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsNothing);
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.downloading,
|
||
);
|
||
await tester.tap(find.text('Open'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsOneWidget);
|
||
expect(find.text('翻译资源'), findsOneWidget);
|
||
expect(find.text('下载'), findsNothing);
|
||
expect(find.text('暂停'), findsOneWidget);
|
||
await tester.tap(find.byKey(const Key('app-dialog-close-button')));
|
||
await tester.pumpAndSettle();
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.downloading,
|
||
);
|
||
await tester.pumpWidget(
|
||
UncontrolledProviderScope(
|
||
container: container,
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(
|
||
body: BackgroundTasksContent(
|
||
session: session,
|
||
repository: repository,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
expect(find.text('Private model name'), findsNothing);
|
||
expect(find.text('下载语音与翻译资源'), findsOneWidget);
|
||
final backgroundProgress = tester.widget<ResourceDownloadProgress>(
|
||
find.byType(ResourceDownloadProgress),
|
||
);
|
||
expect(backgroundProgress.downloadedBytes, 20);
|
||
expect(backgroundProgress.totalBytes, 80);
|
||
expect(
|
||
find.byKey(const Key('background-download-pause-button')),
|
||
findsOneWidget,
|
||
);
|
||
await tester.tap(find.text('下载语音与翻译资源'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsOneWidget);
|
||
expect(find.text('任务详情'), findsNothing);
|
||
expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget);
|
||
expect(find.text('翻译资源'), findsOneWidget);
|
||
final resumedProgress = tester.widget<ResourceDownloadProgress>(
|
||
find.byType(ResourceDownloadProgress).last,
|
||
);
|
||
expect(resumedProgress.downloadedBytes, 20);
|
||
expect(resumedProgress.totalBytes, 80);
|
||
await tester.tap(
|
||
find.byKey(const Key('download-transcription-resource')),
|
||
);
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isTrue);
|
||
await tester.tap(
|
||
find.byKey(const Key('download-transcription-resource')),
|
||
);
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isFalse);
|
||
await tester.tap(
|
||
find.descendant(
|
||
of: find.byType(TranscriptionDialog),
|
||
matching: find.text('取消下载'),
|
||
),
|
||
);
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('取消下载?'), findsOneWidget);
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.downloading,
|
||
);
|
||
await tester.tap(find.text('继续下载'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsOneWidget);
|
||
await tester.tap(find.byKey(const Key('app-dialog-close-button')));
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsNothing);
|
||
await tester.tap(
|
||
find.byKey(const Key('background-download-pause-button')),
|
||
);
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isTrue);
|
||
expect(find.text('继续'), findsOneWidget);
|
||
await tester.tap(
|
||
find.byKey(const Key('background-download-pause-button')),
|
||
);
|
||
await tester.pump();
|
||
expect(repository.subtitlePaused, isFalse);
|
||
await tester.tap(find.text('取消'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('取消下载?'), findsOneWidget);
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.downloading,
|
||
);
|
||
await tester.tap(find.text('继续下载'));
|
||
await tester.pumpAndSettle();
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.downloading,
|
||
);
|
||
await tester.tap(find.text('取消'));
|
||
await tester.pumpAndSettle();
|
||
await tester.tap(
|
||
find.byKey(const Key('confirm-resource-download-cancel')),
|
||
);
|
||
await tester.pump();
|
||
await tester.runAsync(() async {
|
||
for (
|
||
var i = 0;
|
||
i < 100 &&
|
||
repository.installFor(ProcessingCapability.translation).state ==
|
||
ProcessingResourceState.downloading;
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
});
|
||
expect(
|
||
repository.installFor(ProcessingCapability.transcription).state,
|
||
ProcessingResourceState.installed,
|
||
);
|
||
expect(
|
||
repository.installFor(ProcessingCapability.translation).state,
|
||
ProcessingResourceState.notInstalled,
|
||
);
|
||
expect(find.byType(TranscriptionDialog), findsNothing);
|
||
expect(tester.takeException(), isNull);
|
||
},
|
||
);
|
||
|
||
testWidgets('missing subtitle resources show one download dialog', (
|
||
tester,
|
||
) async {
|
||
session.transcriptions!.configure(
|
||
backend: null,
|
||
modelDirectory: null,
|
||
translationBackend: null,
|
||
translationModel: null,
|
||
);
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(
|
||
body: Builder(
|
||
builder: (context) => TextButton(
|
||
onPressed: () => showAppDialog<void>(
|
||
context: context,
|
||
builder: (_) => TranscriptionDialog(
|
||
session: session,
|
||
asset: AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: '/speech.wav',
|
||
),
|
||
),
|
||
),
|
||
child: const Text('Open'),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.tap(find.text('Open'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('下载语音与翻译资源'), findsOneWidget);
|
||
expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget);
|
||
expect(find.text('需下载 1.1 GB'), findsOneWidget);
|
||
expect(find.textContaining('Whisper'), findsNothing);
|
||
expect(find.textContaining('M2M100'), findsNothing);
|
||
expect(find.text('下载'), findsOneWidget);
|
||
expect(find.byType(AppSelect<String>), findsNothing);
|
||
expect(find.text('后台下载'), findsNothing);
|
||
expect(find.textContaining('资源位置'), findsNothing);
|
||
await tester.tap(find.text('取消'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsNothing);
|
||
session.transcriptions!.configure(
|
||
backend: backend,
|
||
modelDirectory: Uri.directory('${root.path}/model'),
|
||
translationBackend: null,
|
||
translationModel: null,
|
||
);
|
||
await tester.tap(find.text('Open'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget);
|
||
expect(find.text('需下载 496 MB'), findsOneWidget);
|
||
expect(find.text('下载'), findsOneWidget);
|
||
expect(find.byType(AppSelect<String>), findsNothing);
|
||
await tester.tap(find.text('取消'));
|
||
await tester.pumpAndSettle();
|
||
expect(tester.takeException(), isNull);
|
||
});
|
||
|
||
testWidgets(
|
||
'generate button recognizes then translates without separate controls',
|
||
(tester) async {
|
||
await tester.runAsync(
|
||
() => project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
),
|
||
);
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
|
||
home: Scaffold(
|
||
body: Builder(
|
||
builder: (context) => TextButton(
|
||
onPressed: () => showAppDialog<void>(
|
||
context: context,
|
||
builder: (_) => TranscriptionDialog(
|
||
session: session,
|
||
asset: AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: '/speech.wav',
|
||
),
|
||
),
|
||
),
|
||
child: const Text('Open'),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
);
|
||
await tester.tap(find.text('Open'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('字幕翻译'), findsNothing);
|
||
expect(find.text('开始翻译'), findsNothing);
|
||
expect(find.text('选择识别文件'), findsNothing);
|
||
expect(find.text('关闭'), findsNothing);
|
||
final menus = tester
|
||
.widgetList<AppSelect<String>>(find.byType(AppSelect<String>))
|
||
.toList();
|
||
menus[0].onChanged!('ja');
|
||
menus[1].onChanged!('zh');
|
||
await tester.pump();
|
||
await tester.runAsync(() async {
|
||
await tester.tap(find.text('生成字幕'));
|
||
await backend.started.future.timeout(const Duration(seconds: 5));
|
||
});
|
||
await tester.pumpAndSettle();
|
||
expect(find.byType(TranscriptionDialog), findsNothing);
|
||
expect(session.subtitleWorkflows.runningCount, 1);
|
||
await tester.runAsync(() async {
|
||
await File.fromUri(
|
||
backend.lastRequest!.destination.resolve('subtitles.json'),
|
||
).create(recursive: true);
|
||
backend.gate.complete();
|
||
await settle(session);
|
||
});
|
||
await tester.pump();
|
||
await tester.runAsync(() async {
|
||
for (
|
||
var i = 0;
|
||
i < 100 && translationBackend.lastRequest == null;
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
});
|
||
expect(backend.lastRequest!.language, 'ja');
|
||
expect(translationBackend.lastRequest!.sourceLanguage, 'ja');
|
||
expect(translationBackend.lastRequest!.targetLanguage, 'zh');
|
||
expect(
|
||
translationBackend.lastRequest!.source,
|
||
session.subtitleWorkflows.tasks.single.recognition.result!.subtitles,
|
||
);
|
||
await tester.runAsync(() async {
|
||
for (
|
||
var i = 0;
|
||
i < 100 && !session.subtitleWorkflows.tasks.single.terminal;
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
});
|
||
expect(session.subtitleWorkflows.runningCount, 0);
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(body: BackgroundTasksDialog(session: session)),
|
||
),
|
||
),
|
||
);
|
||
await tester.pump();
|
||
expect(find.text('Speech'), findsAtLeastNWidgets(1));
|
||
await tester.tap(find.text('Speech'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('应用原文字幕'), findsOneWidget);
|
||
expect(find.text('应用翻译字幕'), findsOneWidget);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
},
|
||
);
|
||
|
||
testWidgets(
|
||
'task panel applies translated subtitles using the recognition window',
|
||
(tester) async {
|
||
await tester.runAsync(() async {
|
||
media.audioStart = MediaTime(1, 1);
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: media.source.toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: media.source,
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('clip'),
|
||
);
|
||
final trimmed = await invoke('timeline.trim', 'trim-ui-translation', {
|
||
'clipId': 'clip',
|
||
'duration': {'numerator': '3', 'denominator': 1},
|
||
'leading': true,
|
||
});
|
||
expect(trimmed.status, CommandStatus.succeeded);
|
||
final job = await session.subtitleWorkflows.start(
|
||
sequence: sequence,
|
||
command: const StartTranscription(
|
||
mediaId: 'source',
|
||
clipId: 'clip',
|
||
language: 'ja',
|
||
),
|
||
name: 'Speech',
|
||
targetLanguage: 'zh',
|
||
);
|
||
backend.gate.complete();
|
||
for (var i = 0; i < 200 && !job.terminal; i++) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
expect(job.status, TranscriptionStatus.succeeded);
|
||
expect(job.recognition.sourceStartMs, 1000);
|
||
expect(
|
||
job.translation!.command.source,
|
||
job.recognition.result!.subtitles.toFilePath(),
|
||
);
|
||
});
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
home: Scaffold(body: BackgroundTasksDialog(session: session)),
|
||
),
|
||
),
|
||
);
|
||
await tester.tap(find.text('Speech'));
|
||
await tester.pumpAndSettle();
|
||
await tester.ensureVisible(find.text('应用翻译字幕'));
|
||
await tester.runAsync(() async {
|
||
await tester.tap(find.text('应用翻译字幕'));
|
||
await session.flush();
|
||
});
|
||
await tester.pumpAndSettle();
|
||
final dto = session.persistence.timeline(sequence).exportDto();
|
||
final captionElement = dto.elements.singleWhere(
|
||
(e) =>
|
||
e.payloadRef != null &&
|
||
session.payloadFor(e.payloadRef!)?.type == 'caption',
|
||
);
|
||
expect(session.caption(sequence, captionElement.id.value).text, '你好');
|
||
final query = session.persistence.timeline(sequence).current.query();
|
||
expect(
|
||
query.absoluteStart(query.elementById(captionElement.id)!) -
|
||
query.absoluteStart(query.elementById(ElementId('clip'))!),
|
||
200 * TimelineClock.ticksPerSecond ~/ 1000,
|
||
);
|
||
expect(tester.takeException(), isNull);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
await tester.runAsync(session.flush);
|
||
},
|
||
);
|
||
|
||
testWidgets('MCP updates the background task panel', (tester) async {
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
|
||
home: Scaffold(body: BackgroundTasksDialog(session: session)),
|
||
),
|
||
),
|
||
);
|
||
final access = EditorToolAccess(session);
|
||
addTearDown(access.dispose);
|
||
final connection = access.server.connect();
|
||
addTearDown(connection.close);
|
||
final response = await tester.runAsync(
|
||
() => connection.handleJson(
|
||
jsonEncode({
|
||
'jsonrpc': '2.0',
|
||
'id': 1,
|
||
'method': 'tools/call',
|
||
'params': {
|
||
'_meta': {
|
||
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
|
||
'io.modelcontextprotocol/clientCapabilities': <String, Object?>{},
|
||
},
|
||
'name': 'media.transcribe',
|
||
'arguments': {
|
||
'workspaceId': access.workspaces.keys.single,
|
||
'operationId': 'mcp-start',
|
||
...args(),
|
||
},
|
||
},
|
||
}),
|
||
),
|
||
);
|
||
expect(response.toString(), contains('taskId'));
|
||
await tester.runAsync(() => backend.started.future);
|
||
await tester.pump();
|
||
expect(find.textContaining('正在识别…'), findsOneWidget);
|
||
expect(find.text('测试字幕'), findsNothing);
|
||
await tester.tap(find.text('source'));
|
||
await tester.pump();
|
||
await tester.pump(const Duration(milliseconds: 300));
|
||
expect(find.text('已识别 1 条'), findsOneWidget);
|
||
expect(find.text('测试字幕'), findsOneWidget);
|
||
expect(session.transcriptions!.tasks, hasLength(1));
|
||
await tester.runAsync(() async {
|
||
final completed = Completer<void>();
|
||
void onTaskUpdated() {
|
||
if (session.transcriptions!.tasks.single.terminal &&
|
||
!completed.isCompleted) {
|
||
completed.complete();
|
||
}
|
||
}
|
||
|
||
// Terminal status is assigned before persistence and the final UI notice.
|
||
session.addListener(onTaskUpdated);
|
||
try {
|
||
backend.gate.complete();
|
||
await completed.future.timeout(const Duration(seconds: 20));
|
||
} finally {
|
||
session.removeListener(onTaskUpdated);
|
||
}
|
||
});
|
||
await tester.pump();
|
||
expect(find.text('字幕已生成'), findsOneWidget);
|
||
expect(find.text('1 条字幕'), findsOneWidget);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
});
|
||
|
||
testWidgets('background task panel displays the concrete failure code', (
|
||
tester,
|
||
) async {
|
||
backend.fail = true;
|
||
backend.gate.complete();
|
||
await tester.runAsync(() async {
|
||
await invoke('media.transcribe', 'failed-dialog', args());
|
||
await settle(session);
|
||
});
|
||
await tester.pumpWidget(
|
||
ProviderScope(
|
||
child: MaterialApp(
|
||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||
supportedLocales: AppLocalizations.supportedLocales,
|
||
locale: const Locale('zh'),
|
||
|
||
home: Scaffold(body: BackgroundTasksDialog(session: session)),
|
||
),
|
||
),
|
||
);
|
||
expect(find.text('失败'), findsOneWidget);
|
||
expect(find.textContaining('processingFailed'), findsNothing);
|
||
await tester.tap(find.text('source'));
|
||
await tester.pumpAndSettle();
|
||
expect(find.text('识别失败:原生识别处理失败(processingFailed)'), findsOneWidget);
|
||
await tester.pumpWidget(const SizedBox.shrink());
|
||
});
|
||
|
||
final config = ProcessingConfiguration.configured();
|
||
test('configured M2M100 model exposes subtitle translation', () {
|
||
expect(config, isNotNull);
|
||
expect(config!.translationModel, isNotNull);
|
||
expect(
|
||
File.fromUri(config.translationModel!.resolve('model.bin')).existsSync(),
|
||
isTrue,
|
||
);
|
||
}, skip: config?.translationModel == null);
|
||
final fixture = Platform.environment['CUTDEX_ASR_FIXTURE'];
|
||
test('real Whisper Turbo through editor tools produces files and an editable track', () async {
|
||
await session.close();
|
||
session = EditorTimelineSession(
|
||
document: await project.loadTimeline('p'),
|
||
persistence: await project.openTimelineSaveSession('p'),
|
||
media: Media(Uri.file(fixture!)),
|
||
transcriptionBackend: config!.backend,
|
||
transcriptionModel: config.transcriptionModel!,
|
||
translationBackend: config.translationModel == null
|
||
? null
|
||
: config.backend,
|
||
translationModel: config.translationModel,
|
||
);
|
||
final result = await invoke('media.transcribe', 'real', {
|
||
'mediaId': 'source',
|
||
'language': 'auto',
|
||
});
|
||
expect(result.status, CommandStatus.succeeded);
|
||
for (
|
||
var i = 0;
|
||
i < 6000 && session.transcriptions!.tasks.any((t) => !t.terminal);
|
||
i++
|
||
) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||
}
|
||
final task = session.transcriptions!.tasks.single;
|
||
expect(task.status, TranscriptionStatus.succeeded, reason: task.error);
|
||
expect(task.result!.cues, isNotEmpty);
|
||
expect(
|
||
await File.fromUri(task.result!.srt).readAsString(),
|
||
contains(task.result!.cues.first.text),
|
||
);
|
||
final transcript = jsonDecode(
|
||
await File.fromUri(task.result!.transcript).readAsString(),
|
||
) as Map<String, dynamic>;
|
||
expect(transcript['sourcePath'], fixture);
|
||
expect(transcript['audioStream'], 0);
|
||
expect(transcript['sourceStartMs'], 0);
|
||
await project.saveAsset(
|
||
AssetDocument(
|
||
id: 'source',
|
||
name: 'Speech',
|
||
storage: AssetStorage.external,
|
||
location: Uri.file(fixture).toString(),
|
||
),
|
||
);
|
||
session.insertAsset(
|
||
sequenceId: sequence,
|
||
assetId: 'source',
|
||
assetName: 'Speech',
|
||
uri: Uri.file(fixture),
|
||
duration: RationalTime.seconds(5),
|
||
position: 0,
|
||
kind: 'audio',
|
||
hasAudio: true,
|
||
clipId: ElementId('real-clip'),
|
||
);
|
||
final applied = await invoke('transcription.apply', 'real-apply', {
|
||
'taskId': task.id,
|
||
'clipId': 'real-clip',
|
||
});
|
||
expect(applied.status, CommandStatus.succeeded, reason: applied.message);
|
||
final ids = (applied.data['captionIds'] as List).cast<String>();
|
||
expect(ids, hasLength(task.result!.cues.length));
|
||
final id = ids.first;
|
||
expect(session.caption(sequence, id).text, task.result!.cues.first.text);
|
||
if (config.translationModel != null) {
|
||
final translated = await invoke('subtitle.translate', 'real-translate', {
|
||
'source': task.result!.subtitles.toFilePath(),
|
||
'sourceLanguage': 'en',
|
||
'targetLanguage': 'zh',
|
||
});
|
||
expect(translated.status, CommandStatus.succeeded);
|
||
final translation = session.transcriptions!.translationTask(
|
||
translated.data['taskId'] as String,
|
||
);
|
||
for (var i = 0; i < 3000 && !translation.terminal; i++) {
|
||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||
}
|
||
expect(
|
||
translation.status,
|
||
TranscriptionStatus.succeeded,
|
||
reason: translation.error,
|
||
);
|
||
expect(translation.result!.document.cues, isNotEmpty);
|
||
final appliedTranslation = await invoke(
|
||
'subtitleTranslation.apply',
|
||
'real-apply-translation',
|
||
{
|
||
'taskId': translation.id,
|
||
'clipId': 'real-clip',
|
||
'source': fixture,
|
||
'audioStream': 0,
|
||
'sourceStartMs': 0,
|
||
},
|
||
);
|
||
expect(
|
||
appliedTranslation.status,
|
||
CommandStatus.succeeded,
|
||
reason: appliedTranslation.message,
|
||
);
|
||
final translatedId =
|
||
(appliedTranslation.data['captionIds'] as List).first as String;
|
||
expect(
|
||
session.caption(sequence, translatedId).text,
|
||
translation.result!.document.cues.first.text,
|
||
);
|
||
}
|
||
await session.flush();
|
||
}, skip: config?.transcriptionModel == null || fixture == null);
|
||
}
|
||
|
||
final class _LocalDownloadHttpOverrides extends HttpOverrides {}
|