Gitea CI / Check code and tests (pull_request) Failing after 8s
Gitea CI / Build Android APK (pull_request) Skipped
Gitea CI / Build Windows x64 app (pull_request) Skipped
Gitea CI / Audit and package Windows x64 (pull_request) Skipped
Gitea CI / Assemble and validate CI artifacts (pull_request) Skipped
Gitea CI / Gitea CI passed (pull_request) Failing after 1s
528 lines
17 KiB
Dart
528 lines
17 KiB
Dart
import 'dart:convert';
|
|
import 'dart:io';
|
|
|
|
import 'package:cutdex/integrations/agent/editor_acceptance.dart';
|
|
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
|
|
import 'package:cutdex/integrations/editor_command_host.dart';
|
|
import 'package:cutdex/workspace/timeline_session.dart';
|
|
import 'package:cutdex_agent/cutdex_agent.dart';
|
|
import 'package:cutdex_agent/io.dart';
|
|
import 'package:cutdex/integrations/agent/agent_prompt_policy.dart';
|
|
import 'package:cutdex_core/editor.dart';
|
|
import 'package:cutdex_core/project.dart';
|
|
import 'package:cutdex_native_flutter/contracts.dart';
|
|
import 'package:cutdex_core/timeline/model.dart';
|
|
import 'package:flutter_test/flutter_test.dart';
|
|
|
|
class _AudioMedia implements EditorMediaService, EditorAudioSource {
|
|
_AudioMedia(this.source);
|
|
final Uri source;
|
|
bool silent = false;
|
|
void Function()? onRead;
|
|
@override
|
|
Future<List<EditorMediaAsset>> query() async => [
|
|
EditorMediaAsset(id: 'source', name: 'Original'),
|
|
];
|
|
@override
|
|
Future<PreparedEditorMedia> prepare(String id) async => PreparedEditorMedia(
|
|
asset: EditorMediaAsset(id: id, name: 'Original'),
|
|
uri: source,
|
|
duration: RationalTime.seconds(12),
|
|
kind: EditorMediaKind.audio,
|
|
hasAudio: true,
|
|
);
|
|
@override
|
|
Future<EditorMediaImportResult> importFile(
|
|
String path, {
|
|
bool Function()? isCancelled,
|
|
}) => throw UnimplementedError();
|
|
@override
|
|
Future<MediaWaveform> waveform(String id, int track) async {
|
|
onRead?.call();
|
|
final nativePath = Platform.environment['CUTDEX_BEAT_NATIVE_WAVEFORM'];
|
|
if (nativePath != null && !silent) {
|
|
return MediaWaveform.fromMap(
|
|
jsonDecode(await File(nativePath).readAsString()) as Map,
|
|
);
|
|
}
|
|
|
|
final values = <double>[];
|
|
for (var i = 0; i < 1200; i++) {
|
|
final v = silent
|
|
? 0.0
|
|
: i % 50 == 10
|
|
? (i % 200 == 10 ? .9 : .4)
|
|
: .01;
|
|
values.addAll([-v, v, v]);
|
|
}
|
|
return MediaWaveform.fromMap({
|
|
'sampleRate': 1000,
|
|
'sourceStartSeconds': 0,
|
|
'frameCount': 12000,
|
|
'trackId': track,
|
|
'channelCount': 1,
|
|
'levels': [
|
|
{
|
|
'samplesPerBucket': 10,
|
|
'channels': [values],
|
|
},
|
|
],
|
|
});
|
|
}
|
|
}
|
|
|
|
void main() {
|
|
TestWidgetsFlutterBinding.ensureInitialized();
|
|
late Directory root;
|
|
late ProjectFile project;
|
|
late EditorTimelineSession session;
|
|
late List<AgentTool> originals;
|
|
late EditorAcceptance acceptance;
|
|
late Map<String, AgentTool> tools;
|
|
final sequence = SequenceId('main');
|
|
var serial = 0;
|
|
final history = <AgentMessage>[];
|
|
ToolContext context() => ToolContext(
|
|
sessionId: 'trial',
|
|
runId: 'run',
|
|
operationId: 'op-${serial++}',
|
|
cancellation: CancellationToken(),
|
|
onProgress: (_) {},
|
|
);
|
|
Future<ToolResult> invoke(
|
|
String name,
|
|
Map<String, Object?> args, {
|
|
bool record = true,
|
|
}) async {
|
|
final call = ToolCall(
|
|
id: 'call-${serial++}',
|
|
name: name,
|
|
arguments: {'workspaceId': 'timeline', ...args},
|
|
);
|
|
final t = tools[name]!;
|
|
expect(t.validate(call.arguments), isNull);
|
|
final result = await t.execute(call, context());
|
|
if (record) {
|
|
history.add(AgentMessage(role: MessageRole.assistant, calls: [call]));
|
|
history.add(
|
|
AgentMessage(
|
|
role: MessageRole.tool,
|
|
callId: call.id,
|
|
text: jsonEncode(result.toJson()),
|
|
isError: result.isError,
|
|
),
|
|
);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
Future<String> version() async =>
|
|
(await invoke('timeline_query', {}, record: false)).data['version']
|
|
as String;
|
|
Future<void> save() async {
|
|
expect(
|
|
(await invoke('project_save', {
|
|
'expectedVersion': await version(),
|
|
}, record: false)).isError,
|
|
false,
|
|
);
|
|
}
|
|
|
|
Future<ToolResult> check() => acceptance.check(
|
|
SessionSnapshot(id: 'trial', runId: 'run', history: history),
|
|
CancellationToken(),
|
|
);
|
|
setUp(() async {
|
|
history.clear();
|
|
serial = 0;
|
|
root = await Directory.systemTemp.createTemp('cutdex-acceptance-');
|
|
project = await ProjectFile.create(
|
|
Directory('${root.path}/acceptance.cutdex'),
|
|
name: 'Acceptance',
|
|
);
|
|
await project.saveAsset(
|
|
AssetDocument(
|
|
id: 'source',
|
|
name: 'Original',
|
|
storage: AssetStorage.external,
|
|
location: Uri.file('${root.path}/source.wav').toString(),
|
|
),
|
|
);
|
|
final document = TimelineDocument(
|
|
id: 'p',
|
|
name: 'Acceptance',
|
|
sequences: [
|
|
TimelineDto(
|
|
id: sequence,
|
|
format: TimelineFormat.fps30,
|
|
primaryStorylineId: StorylineId('primary'),
|
|
storylines: [
|
|
StorylineDto(id: StorylineId('primary'), elementIds: []),
|
|
],
|
|
elements: [],
|
|
),
|
|
],
|
|
);
|
|
await project.saveTimeline(document);
|
|
session = EditorTimelineSession(
|
|
document: await project.loadTimeline('p'),
|
|
persistence: await project.openTimelineSaveSession('p'),
|
|
media: _AudioMedia(Uri.file('${root.path}/source.wav')),
|
|
);
|
|
session.insertAsset(
|
|
sequenceId: sequence,
|
|
assetId: 'source',
|
|
assetName: 'Original',
|
|
uri: Uri.file('${root.path}/source.wav'),
|
|
duration: RationalTime.seconds(12),
|
|
position: 0,
|
|
kind: 'audio',
|
|
hasAudio: true,
|
|
clipId: ElementId('clip'),
|
|
);
|
|
session.insertAsset(
|
|
sequenceId: sequence,
|
|
assetId: 'source',
|
|
assetName: 'Reference',
|
|
uri: Uri.file('${root.path}/source.wav'),
|
|
duration: RationalTime.seconds(12),
|
|
position: 12 * TimelineClock.ticksPerSecond,
|
|
kind: 'audio',
|
|
hasAudio: true,
|
|
clipId: ElementId('music'),
|
|
);
|
|
session.commands.applyEdit(
|
|
sequence,
|
|
PlaceClip(
|
|
clipId: 'music',
|
|
at: CommandTime(0, 1),
|
|
side: ClipPlacement.above,
|
|
),
|
|
);
|
|
originals = editorAgentTools({
|
|
'timeline': editorToolsFor(session, sequence),
|
|
});
|
|
acceptance = EditorAcceptance(originals);
|
|
tools = {
|
|
for (final t in [...originals, ...acceptance.tools]) t.name: t,
|
|
};
|
|
});
|
|
tearDown(() async {
|
|
await session.close();
|
|
await project.close();
|
|
await root.delete(recursive: true);
|
|
});
|
|
|
|
test(
|
|
'real tool chain plans, cuts, saves and verifies every second beat',
|
|
() async {
|
|
final plan = await invoke('timeline_planBeatCuts', {
|
|
'audioClipId': 'music',
|
|
'clipIds': ['clip'],
|
|
'durationSeconds': 12,
|
|
'every': 2,
|
|
'requireCuts': true,
|
|
});
|
|
expect(plan.isError, false, reason: plan.text);
|
|
final data = plan.data['data'] as Map;
|
|
final actions = data['actions'] as List;
|
|
expect(actions.length, 12);
|
|
expect((await check()).isError, true);
|
|
for (final action in actions) {
|
|
final result = await invoke(action['tool'] as String, {
|
|
...(action['arguments'] as Map).cast<String, Object?>(),
|
|
'expectedVersion': await version(),
|
|
});
|
|
expect(result.isError, false, reason: result.text);
|
|
}
|
|
await save();
|
|
final verified = await check();
|
|
expect(verified.isError, false, reason: jsonEncode(verified.toJson()));
|
|
final stored = await project.loadTimeline('p');
|
|
expect(stored.sequences.single.elements.length, 14);
|
|
// An extra off-beat split must invalidate the old receipt.
|
|
final extra = await invoke('timeline_split', {
|
|
'clipId': 'clip',
|
|
'at': {'numerator': '1', 'denominator': 30},
|
|
'expectedVersion': await version(),
|
|
});
|
|
expect(extra.isError, false, reason: extra.text);
|
|
await save();
|
|
expect((await check()).isError, true);
|
|
},
|
|
);
|
|
test(
|
|
'read-only plans do not demand edits; source trim and speed map beats',
|
|
() async {
|
|
await invoke('clip_setSpeed', {
|
|
'clipId': 'music',
|
|
'speed': 2,
|
|
'expectedVersion': await version(),
|
|
});
|
|
final plan = await invoke('timeline_planBeatCuts', {
|
|
'audioClipId': 'music',
|
|
'clipIds': ['clip'],
|
|
'durationSeconds': 12,
|
|
'every': 2,
|
|
});
|
|
expect(plan.isError, false, reason: plan.text);
|
|
final data = plan.data['data'] as Map;
|
|
final actions = data['actions'] as List;
|
|
final last = (actions.last['arguments'] as Map)['at'] as Map;
|
|
final t =
|
|
double.parse(last['numerator'] as String) /
|
|
(last['denominator'] as int);
|
|
expect(t, closeTo(2 / 30, 0.000001));
|
|
await save();
|
|
expect((await check()).isError, false);
|
|
},
|
|
);
|
|
|
|
test(
|
|
'low-confidence audio and concurrent timeline edits cannot authorize cuts',
|
|
() async {
|
|
final media = session.media as _AudioMedia;
|
|
media.silent = true;
|
|
final silent = await invoke('timeline_planBeatCuts', {
|
|
'audioClipId': 'music',
|
|
'clipIds': ['clip'],
|
|
'durationSeconds': 12,
|
|
'requireCuts': true,
|
|
});
|
|
expect(silent.isError, true);
|
|
expect(silent.data['code'], 'uncertainBeat');
|
|
media.silent = false;
|
|
media.onRead = () => session.commands.applyEdit(
|
|
sequence,
|
|
const SetClipAudio(clipId: 'clip', db: -3),
|
|
);
|
|
final stale = await invoke('audio_analyze', {
|
|
'clipId': 'music',
|
|
'durationSeconds': 12,
|
|
});
|
|
expect(stale.isError, true);
|
|
expect(stale.data['code'], 'staleVersion');
|
|
},
|
|
);
|
|
test(
|
|
'trimmed reference maps only beats inside the retained source range',
|
|
() async {
|
|
final trim = await invoke('timeline_trim', {
|
|
'clipId': 'music',
|
|
'duration': {'numerator': '10', 'denominator': 1},
|
|
'leading': true,
|
|
'expectedVersion': await version(),
|
|
});
|
|
expect(trim.isError, false, reason: trim.text);
|
|
final plan = await invoke('timeline_planBeatCuts', {
|
|
'audioClipId': 'music',
|
|
'clipIds': ['clip'],
|
|
'durationSeconds': 12,
|
|
'every': 2,
|
|
});
|
|
expect(plan.isError, false, reason: plan.text);
|
|
final actions = (plan.data['data'] as Map)['actions'] as List;
|
|
expect(actions.length, 10);
|
|
final time = actions.last['arguments']['at'] as Map;
|
|
expect(
|
|
double.parse(time['numerator'] as String) /
|
|
(time['denominator'] as num),
|
|
closeTo(2.1, 0.000001),
|
|
);
|
|
},
|
|
);
|
|
|
|
test('montage mode trims three shots to successive beats and verifies saved ranges', () async {
|
|
for (var i = 2; i <= 3; i++) {
|
|
session.insertAsset(
|
|
sequenceId: sequence,
|
|
assetId: 'source',
|
|
assetName: 'Shot $i',
|
|
uri: Uri.file('${root.path}/source.wav'),
|
|
duration: RationalTime.seconds(12),
|
|
position: (i - 1) * 12 * TimelineClock.ticksPerSecond,
|
|
kind: 'video',
|
|
hasAudio: false,
|
|
clipId: ElementId('shot$i'),
|
|
);
|
|
}
|
|
final plan = await invoke('timeline_planBeatCuts', {
|
|
'audioClipId': 'music',
|
|
'clipIds': ['clip', 'shot2', 'shot3'],
|
|
'durationSeconds': 4,
|
|
'every': 2,
|
|
'phase': 1,
|
|
'mode': 'fitClips',
|
|
'requireCuts': true,
|
|
});
|
|
expect(plan.isError, false, reason: plan.text);
|
|
expect((await check()).isError, true);
|
|
for (final action in (plan.data['data'] as Map)['actions'] as List) {
|
|
final result = await invoke(action['tool'] as String, {
|
|
...(action['arguments'] as Map).cast<String, Object?>(),
|
|
'expectedVersion': await version(),
|
|
});
|
|
expect(result.isError, false, reason: result.text);
|
|
}
|
|
await save();
|
|
final verified = await check();
|
|
expect(verified.isError, false, reason: jsonEncode(verified.toJson()));
|
|
final stored = (await project.loadTimeline('p')).sequences.single;
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('clip'))
|
|
.duration
|
|
.seconds,
|
|
closeTo(.6, .00001),
|
|
);
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('shot2'))
|
|
.duration
|
|
.seconds,
|
|
1,
|
|
);
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('shot3'))
|
|
.duration
|
|
.seconds,
|
|
1,
|
|
);
|
|
});
|
|
test(
|
|
'live agent discovers audio tools and completes beat editing',
|
|
() async {
|
|
final config =
|
|
jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map;
|
|
final overrides = HttpOverrides.current;
|
|
HttpOverrides.global = null;
|
|
addTearDown(() => HttpOverrides.global = overrides);
|
|
final model = OpenAiResponsesAdapter(
|
|
baseUrl: Uri.parse(config['baseUrl'] as String),
|
|
model: config['model'] as String,
|
|
apiKey: config['key'] as String,
|
|
);
|
|
final manager = SessionManager(
|
|
model: model,
|
|
store: InMemorySessionStore(),
|
|
tools: tools.values,
|
|
completionCheck: acceptance.check,
|
|
contextBuilder: HarnessContextBuilder(
|
|
directTools: const {'cutdex_workspaces'},
|
|
maxInputTokens: 32000,
|
|
summarizer: ModelContextSummarizer(
|
|
model: model,
|
|
budget: ContextBuilder(maxInputTokens: 32000),
|
|
),
|
|
),
|
|
);
|
|
final conversation = await manager.create(
|
|
system: AgentPromptPolicy.editorAssistant,
|
|
);
|
|
final end = await (await manager.prompt(
|
|
conversation.id,
|
|
'对timeline工作区的clip片段做音乐卡点,参考music音频素材前4秒,每两拍切一次;实际执行分割,保留全部画面内容和音频,保存并核验。',
|
|
maxTurns: 45,
|
|
)).done;
|
|
expect(end.status, RunStatus.completed, reason: end.error);
|
|
final evidence =
|
|
(end.completionEvidence!['result'] as Map)['data'] as Map;
|
|
expect(evidence['contracts'], 1);
|
|
expect(evidence['issues'], isEmpty);
|
|
final current = await invoke('timeline_query', {}, record: false);
|
|
expect(
|
|
((current.data['data'] as Map)['primaryClipIds'] as List).length,
|
|
5,
|
|
);
|
|
stdout.writeln(
|
|
'LIVE_BEAT_EDIT_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
|
|
);
|
|
},
|
|
skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null,
|
|
timeout: const Timeout(Duration(minutes: 5)),
|
|
);
|
|
test(
|
|
'live agent trims a montage to beat-aligned shot changes',
|
|
() async {
|
|
for (var i = 2; i <= 3; i++) {
|
|
session.insertAsset(
|
|
sequenceId: sequence,
|
|
assetId: 'source',
|
|
assetName: 'Shot $i',
|
|
uri: Uri.file('${root.path}/source.wav'),
|
|
duration: RationalTime.seconds(12),
|
|
position: (i - 1) * 12 * TimelineClock.ticksPerSecond,
|
|
kind: 'video',
|
|
hasAudio: false,
|
|
clipId: ElementId('shot$i'),
|
|
);
|
|
}
|
|
final config =
|
|
jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map;
|
|
final overrides = HttpOverrides.current;
|
|
HttpOverrides.global = null;
|
|
addTearDown(() => HttpOverrides.global = overrides);
|
|
final model = OpenAiResponsesAdapter(
|
|
baseUrl: Uri.parse(config['baseUrl'] as String),
|
|
model: config['model'] as String,
|
|
apiKey: config['key'] as String,
|
|
);
|
|
final manager = SessionManager(
|
|
model: model,
|
|
store: InMemorySessionStore(),
|
|
tools: tools.values,
|
|
completionCheck: acceptance.check,
|
|
contextBuilder: HarnessContextBuilder(
|
|
directTools: const {'cutdex_workspaces'},
|
|
maxInputTokens: 32000,
|
|
summarizer: ModelContextSummarizer(
|
|
model: model,
|
|
budget: ContextBuilder(maxInputTokens: 32000),
|
|
),
|
|
),
|
|
);
|
|
final conversation = await manager.create(
|
|
system: AgentPromptPolicy.editorAssistant,
|
|
);
|
|
final end = await (await manager.prompt(
|
|
conversation.id,
|
|
'在timeline工作区,把clip、shot2、shot3三个主时间线镜头按现有顺序做卡点换镜头。参考music音频素材前4秒,从第2个检测到的节拍开始每两拍一个切点,裁短每个镜头尾部来匹配连续切点;保留音乐,不要只把原片段分割,实际执行、保存并核验。',
|
|
maxTurns: 45,
|
|
)).done;
|
|
expect(end.status, RunStatus.completed, reason: end.error);
|
|
final evidence =
|
|
(end.completionEvidence!['result'] as Map)['data'] as Map;
|
|
expect(evidence['contracts'], 1);
|
|
expect(evidence['issues'], isEmpty);
|
|
final stored = (await project.loadTimeline('p')).sequences.single;
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('clip'))
|
|
.duration
|
|
.seconds,
|
|
closeTo(.6, .00001),
|
|
);
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('shot2'))
|
|
.duration
|
|
.seconds,
|
|
1,
|
|
);
|
|
expect(
|
|
stored.elements
|
|
.singleWhere((e) => e.id == ElementId('shot3'))
|
|
.duration
|
|
.seconds,
|
|
1,
|
|
);
|
|
stdout.writeln(
|
|
'LIVE_BEAT_MONTAGE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
|
|
);
|
|
},
|
|
skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null,
|
|
timeout: const Timeout(Duration(minutes: 5)),
|
|
);
|
|
}
|