Files
cutdex/test/editor_acceptance_test.dart
T
lingjhf 06f1c26681
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Move editor UI into the app and release verified Core dependencies (#14)
2026-10-11 19:59:40 +00:00

529 lines
17 KiB
Dart

import 'dart:convert';
import 'dart:io';
import 'package:cutdex/integrations/agent/editor_acceptance.dart';
import 'package:cutdex/integrations/agent/agent_prompt_policy.dart';
import 'package:cutdex/integrations/agent/editor_agent_tools.dart';
import 'package:cutdex/integrations/editor_command_host.dart';
import 'package:cutdex/workspace/timeline_session.dart';
import 'package:cutdex_agent/cutdex_agent.dart';
import 'package:cutdex_agent/io.dart';
import 'package:cutdex_core/project.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter_test/flutter_test.dart';
import 'transcription_tools_test.dart' show Media;
class _Model implements ModelAdapter {
_Model(this.action);
final Future<ModelResponse> Function(ModelRequest, int) action;
int requests = 0;
@override
Stream<ModelEvent> stream(ModelRequest request, CancellationToken c) async* {
yield await action(request, requests++);
}
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late Directory root;
late ProjectFile project;
late EditorTimelineSession session;
late List<AgentTool> originals;
late EditorAcceptance acceptance;
late Map<String, AgentTool> tools;
final sequence = SequenceId('main');
var serial = 0;
final history = <AgentMessage>[];
ToolContext context() => ToolContext(
sessionId: 'trial',
runId: 'run',
operationId: 'op-${serial++}',
cancellation: CancellationToken(),
onProgress: (_) {},
);
Future<ToolResult> invoke(
String name,
Map<String, Object?> args, {
bool record = true,
}) async {
final call = ToolCall(
id: 'call-${serial++}',
name: name,
arguments: {'workspaceId': 'timeline', ...args},
);
final t = tools[name]!;
expect(t.validate(call.arguments), isNull);
final result = await t.execute(call, context());
if (record) {
history.add(AgentMessage(role: MessageRole.assistant, calls: [call]));
history.add(
AgentMessage(
role: MessageRole.tool,
callId: call.id,
text: jsonEncode(result.toJson()),
isError: result.isError,
),
);
}
return result;
}
Future<String> version() async =>
(await invoke('timeline_query', {}, record: false)).data['version']
as String;
Future<void> save() async {
expect(
(await invoke('project_save', {
'expectedVersion': await version(),
}, record: false)).isError,
false,
);
}
Future<ToolResult> check() => acceptance.check(
SessionSnapshot(id: 'trial', runId: 'run', history: history),
CancellationToken(),
);
setUp(() async {
history.clear();
serial = 0;
root = await Directory.systemTemp.createTemp('cutdex-acceptance-');
project = await ProjectFile.create(
Directory('${root.path}/acceptance.cutdex'),
name: 'Acceptance',
);
await project.saveAsset(
AssetDocument(
id: 'source',
name: 'Original',
storage: AssetStorage.external,
location: Uri.file('${root.path}/source.wav').toString(),
),
);
final document = TimelineDocument(
id: 'p',
name: 'Acceptance',
sequences: [
TimelineDto(
id: sequence,
format: TimelineFormat.fps30,
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(id: StorylineId('primary'), elementIds: []),
],
elements: [],
),
],
);
await project.saveTimeline(document);
session = EditorTimelineSession(
document: await project.loadTimeline('p'),
persistence: await project.openTimelineSaveSession('p'),
media: Media(Uri.file('${root.path}/source.wav')),
);
session.insertAsset(
sequenceId: sequence,
assetId: 'source',
assetName: 'Original',
uri: Uri.file('${root.path}/source.wav'),
duration: RationalTime.seconds(5),
position: 0,
kind: 'audio',
hasAudio: true,
clipId: ElementId('clip'),
);
originals = editorAgentTools({
'timeline': editorToolsFor(session, sequence),
});
acceptance = EditorAcceptance(originals);
tools = {
for (final t in [...originals, ...acceptance.tools]) t.name: t,
};
});
tearDown(() async {
await session.close();
await project.close();
await root.delete(recursive: true);
});
test('real project readback detects wrong parameter and fresh edits invalidate success', () async {
final registered = await invoke('editor_expect_clips', {
'clips': [
{
'clipId': 'clip',
'name': 'Original',
'parameters': [
{'parameterId': 'cutdex.audio.gainDb', 'value': -12},
],
},
],
});
expect(registered.isError, false);
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': -6,
'expectedVersion': await version(),
});
await save();
final failed = await check();
expect(failed.isError, true);
expect(jsonEncode(failed.data), contains('cutdex.audio.gainDb'));
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': -12,
'expectedVersion': await version(),
});
await save();
expect((await check()).isError, false);
final persisted = (await project.loadTimeline('p'))
.sequences
.single
.elements
.singleWhere((e) => e.id == ElementId('clip'));
expect(
persisted.parameters
.singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb')
.definition
.defaultValue,
-12,
);
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': -3,
'expectedVersion': await version(),
}, record: false);
await save();
expect((await check()).isError, true);
});
test(
'saved contracts survive fresh verifier and cannot be weakened',
() async {
await invoke('editor_expect_clips', {
'clips': [
{'clipId': 'clip', 'name': 'Expected'},
],
});
acceptance = EditorAcceptance(originals);
expect((await check()).isError, true);
await invoke('editor_expect_clips', {
'clips': [
{'clipId': 'clip', 'name': 'Original'},
],
});
final result = await check();
expect(result.isError, true);
expect(jsonEncode(result.data), contains('contractChanged'));
},
);
test(
'audio edits require the edited field and honor implicit defaults',
() async {
await invoke('editor_expect_clips', {
'clips': [
{'clipId': 'clip', 'name': 'Original'},
],
});
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': -12,
'expectedVersion': await version(),
});
await save();
expect(jsonEncode((await check()).data), contains('missingExpectation'));
history.clear();
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': 0,
'muted': false,
'expectedVersion': await version(),
}, record: false);
await invoke('editor_expect_clips', {
'clips': [
{
'clipId': 'clip',
'parameters': [
{'parameterId': 'cutdex.audio.gainDb', 'value': 0},
{'parameterId': 'cutdex.audio.mute', 'value': 1},
],
},
],
});
await save();
expect((await check()).isError, false);
},
);
test('real captions check all pages and detect missing cues without semantic certification', () async {
final a = await invoke('captionTrack_create', {
'name': '日本語',
'language': 'ja',
'expectedVersion': await version(),
});
final source = ((a.data['data'] as Map)['roleId']) as String;
final b = await invoke('captionTrack_create', {
'name': '中文',
'language': 'zh',
'expectedVersion': await version(),
});
final target = ((b.data['data'] as Map)['roleId']) as String;
await invoke('caption_add', {
'roleId': source,
'cues': [
for (var i = 0; i < 101; i++)
{
'text': '字幕$i',
'start': {'numerator': '${i * 2}', 'denominator': 1},
'duration': {'numerator': '1', 'denominator': 1},
},
],
'expectedVersion': await version(),
});
expect(
(await invoke('editor_expect_translation', {
'sourceRoleId': source,
'targetRoleId': target,
})).isError,
false,
);
final page = await invoke('caption_list', {
'roleId': source,
'limit': 100,
}, record: false);
final cues = (page.data['data'] as Map)['cues'] as List;
await invoke('caption_addTranslations', {
'roleId': target,
'cues': [
for (final c in cues) {'sourceCaptionId': c['captionId'], 'text': '译文'},
],
'expectedVersion': await version(),
});
await save();
expect((await check()).isError, true);
final rest = await invoke('caption_list', {
'roleId': source,
'offset': 100,
'limit': 100,
}, record: false);
final last = ((rest.data['data'] as Map)['cues'] as List).single;
await invoke('caption_addTranslations', {
'roleId': target,
'cues': [
{'sourceCaptionId': last['captionId'], 'text': '译文'},
],
'expectedVersion': await version(),
});
await save();
final result = await check();
expect(result.isError, false);
expect(result.data['semanticQuality'], 'unverified');
var changed = false;
acceptance = EditorAcceptance(
originals.map(
(tool) => tool.name != 'caption_list'
? tool
: AgentTool(
name: tool.name,
description: tool.description,
parameters: tool.parameters,
validate: tool.validate,
execute: (call, context) async {
final result = await tool.execute(call, context);
if (!changed && call.arguments['roleId'] == source) {
changed = true;
await invoke('clip_setAudio', {
'clipId': 'clip',
'db': -3,
'expectedVersion': await version(),
}, record: false);
}
return result;
},
),
),
);
expect(jsonEncode((await check()).data), contains('unavailableEvidence'));
acceptance = EditorAcceptance(originals);
await invoke('caption_set', {
'captionId': cues.first['captionId'],
'text': '改变了原文',
'expectedVersion': await version(),
});
await save();
expect(jsonEncode((await check()).data), contains('sourceChanged'));
});
test(
'runtime repairs failed final verification through actual editor tools',
() async {
var repaired = false;
final model = _Model((request, step) async {
ModelResponse call(String name, Map<String, Object?> args) =>
ModelResponse(
calls: [
ToolCall(
id: 'model-$step',
name: name,
arguments: {'workspaceId': 'timeline', ...args},
),
],
);
if (step == 0) {
return call('editor_expect_clips', {
'clips': [
{
'clipId': 'clip',
'parameters': [
{'parameterId': 'cutdex.audio.gainDb', 'value': -12},
],
},
],
});
}
if (step == 1) return ModelResponse(text: '完成');
if (step == 2) {
expect(request.messages.last.runtimeNotice, true);
expect(request.messages.last.text, contains('cutdex.audio.gainDb'));
repaired = true;
return call('clip_setAudio', {
'clipId': 'clip',
'db': -12,
'expectedVersion': await version(),
});
}
if (step == 3) {
return call('project_save', {'expectedVersion': await version()});
}
return ModelResponse(text: '已修正并核验');
});
final manager = SessionManager(
model: model,
store: FileSessionStore(Directory('${root.path}/sessions')),
contextBuilder: ContextBuilder(),
tools: tools.values,
completionCheck: acceptance.check,
);
final s = await manager.create(id: 'agent');
final end = await (await manager.prompt(s.id, 'set volume')).done;
expect(repaired, true);
expect(end.status, RunStatus.completed);
expect((end.completionEvidence!['result'] as Map)['isError'], false);
},
);
test(
'live model verifies real persisted project through application tools',
() async {
final raw = Platform.environment['CUTDEX_ACCEPTANCE_LIVE'];
if (raw == null) return;
// This opt-in integration case uses the configured real provider.
final overrides = HttpOverrides.current;
HttpOverrides.global = null;
addTearDown(() => HttpOverrides.global = overrides);
final config = jsonDecode(raw) as Map;
final model = OpenAiResponsesAdapter(
baseUrl: Uri.parse(config['baseUrl'] as String),
model: config['model'] as String,
apiKey: config['key'] as String,
);
final manager = SessionManager(
model: model,
store: FileSessionStore(Directory('${root.path}/live')),
contextBuilder: HarnessContextBuilder(
maxInputTokens: 32000,
directTools: const {'cutdex_workspaces'},
summarizer: ModelContextSummarizer(
model: model,
budget: ContextBuilder(maxInputTokens: 32000),
),
),
tools: tools.values,
completionCheck: acceptance.check,
);
final s = await manager.create(system: AgentPromptPolicy.editorAssistant);
final end = await (await manager.prompt(
s.id,
'在timeline工作区把clip片段音量设为-12 dB,保持顺序、时间和其他内容。',
maxTurns: 35,
)).done;
if (end.status != RunStatus.completed) {
stdout.writeln(
'LIVE_FAILURE ${jsonEncode(end.history.map((m) => m.toJson()).toList())}',
);
}
expect(end.status, RunStatus.completed, reason: end.error);
expect(end.completionEvidence, isNotNull);
final query = await invoke('timeline_query', {}, record: false);
final clip = ((query.data['data'] as Map)['clips'] as List).firstWhere(
(c) => c['clipId'] == 'clip',
);
expect(clip['name'], 'Original');
expect(
(clip['parameters'] as List).firstWhere(
(p) => p['id'] == 'cutdex.audio.gainDb',
)['defaultValue'],
-12,
);
final persistedClip = (await project.loadTimeline('p'))
.sequences
.single
.elements
.singleWhere((e) => e.id == ElementId('clip'));
expect(
persistedClip.parameters
.singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb')
.definition
.defaultValue,
-12,
);
stdout.writeln(
'LIVE_ACCEPTANCE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}',
);
final sourceResult = await invoke('captionTrack_create', {
'name': '日本語',
'language': 'ja',
'expectedVersion': await version(),
});
final source = (sourceResult.data['data'] as Map)['roleId'];
const japanese = [
'こんにちは。',
'ここで待ってください。',
'彼はまだ来ていません。',
'会議は午後三時に始まります。',
];
await invoke('caption_add', {
'roleId': source,
'cues': [
for (var i = 0; i < japanese.length; i++)
{
'text': japanese[i],
'start': {'numerator': '$i', 'denominator': 1},
'duration': {'numerator': '1', 'denominator': 1},
},
],
'expectedVersion': await version(),
});
await save();
final translated = await (await manager.prompt(
s.id,
'把timeline工作区日本語轨道的全部字幕由你翻译成简体中文,新增中文轨道并保留原字幕和时间,完成后保存。',
maxTurns: 45,
)).done;
expect(translated.status, RunStatus.completed, reason: translated.error);
expect(
(translated.completionEvidence!['result'] as Map)['isError'],
false,
);
final tracks = await invoke('caption_list', {}, record: false);
final target = ((tracks.data['data'] as Map)['tracks'] as List)
.singleWhere((t) => t['roleId'] != source);
final captions = await invoke('caption_list', {
'roleId': target['roleId'],
}, record: false);
final cues = (captions.data['data'] as Map)['cues'] as List;
expect(cues.length, japanese.length);
stdout.writeln(
'LIVE_TRANSLATION_VERIFIED turns=${translated.turns} cues=${jsonEncode(cues)} evidence=${jsonEncode(translated.completionEvidence)}',
);
},
timeout: const Timeout(Duration(minutes: 5)),
skip: Platform.environment['CUTDEX_ACCEPTANCE_LIVE'] == null,
);
}