feat: initial Cutdex application
Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,51 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'agent_credentials.g.dart';
|
||||
|
||||
abstract interface class AgentCredentialStore {
|
||||
Future<String?> read(String id);
|
||||
Future<void> write(String id, String value);
|
||||
Future<void> delete(String id);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentCredentialStore agentCredentialStore(Ref ref) {
|
||||
final storage = Platform.isMacOS
|
||||
? const FlutterSecureStorage(
|
||||
mOptions: MacOsOptions(usesDataProtectionKeychain: false),
|
||||
)
|
||||
: const FlutterSecureStorage();
|
||||
return FlutterSecureAgentCredentialStore(storage);
|
||||
}
|
||||
|
||||
class FlutterSecureAgentCredentialStore implements AgentCredentialStore {
|
||||
FlutterSecureAgentCredentialStore(this._storage);
|
||||
|
||||
final FlutterSecureStorage _storage;
|
||||
|
||||
@override
|
||||
Future<String?> read(String id) => _storage.read(key: id);
|
||||
|
||||
@override
|
||||
Future<void> write(String id, String value) =>
|
||||
_storage.write(key: id, value: value);
|
||||
|
||||
@override
|
||||
Future<void> delete(String id) => _storage.delete(key: id);
|
||||
}
|
||||
|
||||
class MemoryAgentCredentialStore implements AgentCredentialStore {
|
||||
final Map<String, String> _values = {};
|
||||
|
||||
@override
|
||||
Future<String?> read(String id) async => _values[id];
|
||||
|
||||
@override
|
||||
Future<void> write(String id, String value) async => _values[id] = value;
|
||||
|
||||
@override
|
||||
Future<void> delete(String id) async => _values.remove(id);
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_credentials.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentCredentialStore)
|
||||
final agentCredentialStoreProvider = AgentCredentialStoreProvider._();
|
||||
|
||||
final class AgentCredentialStoreProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentCredentialStore,
|
||||
AgentCredentialStore,
|
||||
AgentCredentialStore
|
||||
>
|
||||
with $Provider<AgentCredentialStore> {
|
||||
AgentCredentialStoreProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentCredentialStoreProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentCredentialStoreHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentCredentialStore> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentCredentialStore create(Ref ref) {
|
||||
return agentCredentialStore(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentCredentialStore value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentCredentialStore>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentCredentialStoreHash() =>
|
||||
r'5905f9d4740138df60d6f32dd3fde66489be97c3';
|
||||
@@ -0,0 +1,69 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'agent_prompt_policy.dart';
|
||||
|
||||
part 'agent_models.freezed.dart';
|
||||
|
||||
enum AgentApiType { openAiChatCompletions, openAiResponses, anthropicMessages }
|
||||
|
||||
@freezed
|
||||
abstract class AgentModelSettings with _$AgentModelSettings {
|
||||
const AgentModelSettings._();
|
||||
|
||||
const factory AgentModelSettings({
|
||||
required String id,
|
||||
int? contextWindow,
|
||||
int? maxOutputTokens,
|
||||
}) = _AgentModelSettings;
|
||||
|
||||
/// Reserve at most half of a small window when output is unspecified.
|
||||
int get effectiveMaxOutputTokens =>
|
||||
maxOutputTokens ??
|
||||
(contextWindow == null || contextWindow! >= 8192
|
||||
? 4096
|
||||
: contextWindow! ~/ 2);
|
||||
|
||||
int get effectiveMaxInputTokens =>
|
||||
contextWindow == null ? 32000 : contextWindow! - effectiveMaxOutputTokens;
|
||||
|
||||
bool get hasInstructionBudget =>
|
||||
effectiveMaxInputTokens >=
|
||||
ContextBuilder().measureInput(system: AgentPromptPolicy.editorAssistant);
|
||||
|
||||
bool get hasValidTokenBudget =>
|
||||
effectiveMaxInputTokens > 0 && effectiveMaxOutputTokens > 0;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentProviderSettings with _$AgentProviderSettings {
|
||||
const AgentProviderSettings._();
|
||||
|
||||
const factory AgentProviderSettings({
|
||||
required String id,
|
||||
required String name,
|
||||
required String apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? credentialId,
|
||||
@Default(true) bool enabled,
|
||||
}) = _AgentProviderSettings;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentSettingsState with _$AgentSettingsState {
|
||||
const AgentSettingsState._();
|
||||
|
||||
const factory AgentSettingsState({
|
||||
@Default(false) bool enabled,
|
||||
@Default([]) List<AgentProviderSettings> providers,
|
||||
String? selectedProviderId,
|
||||
String? selectedModelId,
|
||||
@Default(0) int revision,
|
||||
}) = _AgentSettingsState;
|
||||
}
|
||||
|
||||
abstract interface class AgentSettingsRepository {
|
||||
Future<AgentSettingsState> load();
|
||||
Future<void> save(AgentSettingsState settings);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
import 'dart:convert';
|
||||
|
||||
abstract final class AgentPromptPolicy {
|
||||
static String forTimeline(String projectId, String timelineId) =>
|
||||
'$editorAssistant\n'
|
||||
'当前界面编辑目标(用户明确指定其他目标时,以用户要求为准):${jsonEncode({'projectId': projectId, 'timelineId': timelineId})}。'
|
||||
'已有适用于当前目标的成功工具结果时复用其 workspaceId。仅首次没有目标 ID、切换目标或工作区失效时调用 cutdex_workspaces;toolSetId 引用同一返回中的 toolSets。当前任务内复用已确认的 ID,不要在每次模型回复、工具调用或上下文压缩后重复发现工作区;仅在目标切换或工作区失效时重新查询。'
|
||||
'application 工作区只处理项目管理;时间线查询和片段编辑必须使用对应的时间线工作区。';
|
||||
static const editorAssistant =
|
||||
'你是 Cutdex 视频剪辑助手,请使用用户的语言回答。'
|
||||
'音频分析使用 audio_analyze,先从 timeline_query 确定音频 clipId 和 sourceRange;startSeconds/durationSeconds 是素材时间,单次最多120秒,长素材按区间读取。波形峰值、RMS和高能量片段只是高潮候选,不等于语义高潮;重音候选不等于已识别小节强拍。置信度或分辨率不足时明确说明,不要编造节拍。'
|
||||
'用户要求实际卡点剪辑时,调用 timeline_planBeatCuts 并设置 requireCuts:true;仅查看方案时为false。指定音频参考片段和要剪切的主时间线片段,每拍every:1、两拍every:2,phase小于every。工具负责裁剪/变速时间映射和帧对齐,严格按返回actions顺序逐一调用timeline_split,使用每次成功操作返回的最新expectedVersion。不要对剪辑后的项目重算或替换原计划,不要擅自切割音频参考。完成后project_save,结束前程序会按原计划核验切点和素材范围。mode:split保留内容只做分割;用户要求多个镜头卡点切换且允许裁剪时,用mode:fitClips,把全部主时间线素材按现有顺序缩短到连续节拍,严格执行返回的timeline_trim操作。工具不会自动选素材或重排;需要选材时先安排素材再制定卡点计划,不能把单纯分割称为已经换镜头。'
|
||||
'修改片段名称或静态参数前,调用 editor_expect_clips 登记用户要求的全部目标、最终名称和参数默认值;未要求调整结构时保留 preserveLayout:true。音量参数 ID 为 cutdex.audio.gainDb。新建翻译轨道后、写入译文前调用 editor_expect_translation,登记源和目标 roleId。结束时程序会重新读取工程核验数量、身份、时间和已声明参数;有差异时按具体问题修正,不要重新登记来降低原标准。先完成 project_save,再报告保存完成。声明范围之外的要求不能声称已由程序核验。'
|
||||
'语义检查只提供带原文、译文和疑点的复核建议;不能仅凭一次语义评分自动改写正确译文。结构通过不等于翻译准确、自然或适合交付。遇到原文不清楚要明确列出待复核项,不能猜测事实,也不能把占位或省略号当作已完成翻译。'
|
||||
'字幕翻译可使用内置 subtitle_translate(需要支持的字幕文件和可用模型),也可读取 caption_query 的原文由你直接翻译。用户要求新增字幕轨道时,保留原字幕,用 captionTrack_create 创建目标语言轨道,再用 caption_addTranslations 按返回的 roleId 逐条或分批添加译文。翻译时每条只提供 text 和 sourceCaptionId(原字幕 captionId),由工具复制精确时间,避免抄写或计算时间数字。翻译风格未指定时使用自然准确的译文,不必为可选风格偏好暂停执行。'
|
||||
'批量字幕任务优先 caption_list:不传 roleId 先列轨道,再指定源 roleId 每页读取 20 条,翻译并用 caption_addTranslations 写入后才读取下一页。通过 update_plan checkpoint 记录源 roleId、目标 roleId、nextOffset 和最新版本;上下文压缩后从 nextOffset 继续,不能重新全量查询或重复写入。caption_list 已完成字幕编辑前的状态查询,字幕任务不需要全量 timeline_query;结束时用 caption_list 核对轨道数量和保存状态。'
|
||||
'同一时间线的写操作必须逐次调用并等待返回,再使用更新后的版本;不要在同一条模型回复中批量发出共享同一个 expectedVersion 的独立写操作。只有专用批量工具才能原子批量编辑。'
|
||||
'上下文压缩本身不会改变工程状态,也不会使已确认的工作区和版本失效。即使摘要泛称版本可能过时,也应复用本轮最近一次成功查询或提交的版本;不要陷入压缩后重新查询、查询后再次压缩的循环。'
|
||||
'编辑前查询时间线;只核对少量片段时使用 clipIds 和 parameterIds,结构查询用 includeParameters:false;连续编辑可使用上一次成功提交返回的最新 expectedVersion。无状态变化时不要重复查询同一时间线;发生版本冲突或结果未知时重新查询。'
|
||||
'clip_setTransform 的画面位置使用相对画布中心的像素坐标;'
|
||||
'keyframe_edit/keyframe_editMany 的 canvas.position.x/y 则使用归一化值,x 向右为正、y 向上为正,必须将像素除以画布宽高,不能直接传像素。'
|
||||
'编辑时间使用时间线时间;查询关键帧的 sourceTime 是素材时间,需结合片段起点和 sourceRange 换算。'
|
||||
'仅报告工具确认的结果;预览异步同步,提交成功不等于预览或导出完成。'
|
||||
'结果未知时先核对状态,不要重复执行编辑。'
|
||||
'完成编辑后按修改过的片段和参数查询时间线,核对实际结果与 saveState,再报告最新的保存状态。'
|
||||
'总时长以时间线查询的 duration 为准,不能沿用编辑前的时长或把重叠 lane 时长相加。'
|
||||
'查询结果中的 preview:notRequested 仅指该次查询未请求预览,不表示实际预览未同步;需要报告预览时调用 preview_query。';
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export 'agent_models.dart';
|
||||
export 'agent_runtime.dart';
|
||||
export 'agent_settings.dart';
|
||||
export 'agent_session_store.dart';
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
|
||||
/// Runtime-only dependencies for one selected provider/model.
|
||||
class AgentRuntime {
|
||||
const AgentRuntime({
|
||||
required this.model,
|
||||
required this.contextBuilder,
|
||||
required this.revision,
|
||||
required this.sessionIdentity,
|
||||
this.providerId,
|
||||
this.modelId,
|
||||
});
|
||||
|
||||
final ModelAdapter model;
|
||||
final ContextBuilder contextBuilder;
|
||||
final int revision;
|
||||
final String sessionIdentity;
|
||||
final String? providerId;
|
||||
final String? modelId;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'agent_credentials.dart';
|
||||
import 'agent_models.dart';
|
||||
import 'agent_runtime.dart';
|
||||
|
||||
part 'agent_runtime_factory.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentRuntimeFactory agentRuntimeFactory(Ref ref) {
|
||||
return AgentRuntimeFactory(ref.watch(agentCredentialStoreProvider));
|
||||
}
|
||||
|
||||
/// Converts persisted provider metadata into runtime-only Agent dependencies.
|
||||
class AgentRuntimeFactory {
|
||||
const AgentRuntimeFactory(this._credentials);
|
||||
|
||||
final AgentCredentialStore _credentials;
|
||||
|
||||
Future<AgentRuntime?> create(AgentSettingsState settings) async {
|
||||
if (!settings.enabled) return null;
|
||||
return createFor(
|
||||
settings,
|
||||
providerId: settings.selectedProviderId,
|
||||
modelId: settings.selectedModelId,
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentRuntime?> createFor(
|
||||
AgentSettingsState settings, {
|
||||
required String? providerId,
|
||||
required String? modelId,
|
||||
}) async {
|
||||
if (!settings.enabled) return null;
|
||||
final provider = settings.providers
|
||||
.where((candidate) => candidate.id == providerId)
|
||||
.firstOrNull;
|
||||
final model = provider?.models
|
||||
.where((candidate) => candidate.id == modelId)
|
||||
.firstOrNull;
|
||||
if (provider == null || !provider.enabled || model == null) return null;
|
||||
final apiType = AgentApiType.values
|
||||
.where((candidate) => candidate.name == provider.apiType)
|
||||
.firstOrNull;
|
||||
if (apiType == null) return null;
|
||||
|
||||
final credentialId = provider.credentialId;
|
||||
final apiKey = credentialId == null
|
||||
? ''
|
||||
: await _credentials.read(credentialId) ?? '';
|
||||
final adapter = switch (apiType) {
|
||||
AgentApiType.openAiChatCompletions => OpenAiChatAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
AgentApiType.openAiResponses => OpenAiResponsesAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
AgentApiType.anthropicMessages => AnthropicMessagesAdapter(
|
||||
baseUrl: Uri.parse(provider.baseUrl),
|
||||
model: model.id,
|
||||
apiKey: apiKey,
|
||||
),
|
||||
};
|
||||
return AgentRuntime(
|
||||
model: adapter,
|
||||
contextBuilder: HarnessContextBuilder(
|
||||
directTools: const {'cutdex_workspaces'},
|
||||
summarizer: ModelContextSummarizer(
|
||||
model: adapter,
|
||||
budget: ContextBuilder(
|
||||
maxInputTokens: model.effectiveMaxInputTokens,
|
||||
maxOutputTokens: model.effectiveMaxOutputTokens,
|
||||
),
|
||||
instructions:
|
||||
'For video editing preserve project, timeline, sequence '
|
||||
'and clip IDs, lane relationships, source versus timeline time, '
|
||||
'keyframe units, mask identifiers, committed edits and unsaved '
|
||||
'or uncertain results. Preserve user constraints and pending edits. '
|
||||
'Preserve the latest confirmed workspace and version IDs and '
|
||||
'whether any later edit or error invalidated them. Compaction '
|
||||
'alone does not invalidate a successful query or commit. Reuse '
|
||||
'its version for the next sequential write; do not add a pending '
|
||||
'query merely because a summary was created. Requery only when '
|
||||
'the target changes or a stale/uncertain '
|
||||
'result requires reconciliation. Preserve durable resultId references and cursors needed for pending reads. Do not copy full curves or unrelated tool call IDs. Keep the summary concise: group completed edits by target, retain only latest valid version, exact pending actions and user constraints. Do not repeat the same IDs under multiple headings.',
|
||||
),
|
||||
maxInputTokens: model.effectiveMaxInputTokens,
|
||||
maxOutputTokens: model.effectiveMaxOutputTokens,
|
||||
),
|
||||
revision: settings.revision,
|
||||
sessionIdentity: '${provider.id}\u0000${model.id}',
|
||||
providerId: provider.id,
|
||||
modelId: model.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_runtime_factory.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentRuntimeFactory)
|
||||
final agentRuntimeFactoryProvider = AgentRuntimeFactoryProvider._();
|
||||
|
||||
final class AgentRuntimeFactoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentRuntimeFactory,
|
||||
AgentRuntimeFactory,
|
||||
AgentRuntimeFactory
|
||||
>
|
||||
with $Provider<AgentRuntimeFactory> {
|
||||
AgentRuntimeFactoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentRuntimeFactoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentRuntimeFactoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentRuntimeFactory> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentRuntimeFactory create(Ref ref) {
|
||||
return agentRuntimeFactory(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentRuntimeFactory value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentRuntimeFactory>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentRuntimeFactoryHash() =>
|
||||
r'e937512aa2ab3c32b8270bedac59ae179639377a';
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'agent_session_store.g.dart';
|
||||
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<SessionStore> agentSessionStore(Ref ref) async {
|
||||
final support = await getApplicationSupportDirectory();
|
||||
return FileSessionStore(
|
||||
Directory(p.join(support.path, 'Cutdex', 'Agent', 'Sessions')),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_session_store.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
|
||||
@ProviderFor(agentSessionStore)
|
||||
final agentSessionStoreProvider = AgentSessionStoreProvider._();
|
||||
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
|
||||
final class AgentSessionStoreProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<SessionStore>,
|
||||
SessionStore,
|
||||
FutureOr<SessionStore>
|
||||
>
|
||||
with $FutureModifier<SessionStore>, $FutureProvider<SessionStore> {
|
||||
/// Owns the durable Agent checkpoint journal for the lifetime of the app.
|
||||
AgentSessionStoreProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSessionStoreProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSessionStoreHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<SessionStore> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<SessionStore> create(Ref ref) {
|
||||
return agentSessionStore(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentSessionStoreHash() => r'9a27b793eb8891e72040a71e9900d074ae069da4';
|
||||
@@ -0,0 +1,80 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
import 'agent_models.dart';
|
||||
import 'agent_runtime.dart';
|
||||
import 'agent_runtime_factory.dart';
|
||||
import 'agent_settings_service.dart';
|
||||
|
||||
part 'agent_settings.g.dart';
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
@Riverpod(keepAlive: true)
|
||||
class AgentSettings extends _$AgentSettings {
|
||||
late AgentSettingsService _service;
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
Future<AgentSettingsState> build() async {
|
||||
_service = ref.watch(agentSettingsServiceProvider);
|
||||
return _service.load();
|
||||
}
|
||||
|
||||
Future<void> setEnabled(bool enabled) =>
|
||||
_replace((current) => _service.setEnabled(current, enabled));
|
||||
|
||||
Future<void> setProviderEnabled(String providerId, bool enabled) => _replace(
|
||||
(current) => _service.setProviderEnabled(current, providerId, enabled),
|
||||
);
|
||||
|
||||
Future<void> selectModel(String providerId, String modelId) =>
|
||||
_replace((current) => _service.selectModel(current, providerId, modelId));
|
||||
|
||||
Future<void> upsertProvider({
|
||||
String? id,
|
||||
required String name,
|
||||
required AgentApiType apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey = false,
|
||||
}) => _replace(
|
||||
(current) => _service.upsertProvider(
|
||||
current,
|
||||
id: id,
|
||||
name: name,
|
||||
apiType: apiType,
|
||||
baseUrl: baseUrl,
|
||||
models: models,
|
||||
apiKey: apiKey,
|
||||
clearApiKey: clearApiKey,
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> deleteProvider(String providerId) =>
|
||||
_replace((current) => _service.deleteProvider(current, providerId));
|
||||
|
||||
Future<void> _replace(
|
||||
Future<AgentSettingsState> Function(AgentSettingsState) update,
|
||||
) {
|
||||
return _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
final current = await future;
|
||||
if (!ref.mounted) return;
|
||||
final next = await update(current);
|
||||
if (ref.mounted) state = AsyncData(next);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<AgentRuntime?> agentRuntime(Ref ref) async {
|
||||
final factory = ref.watch(agentRuntimeFactoryProvider);
|
||||
final settings = ref.watch(agentSettingsProvider);
|
||||
final value = settings.asData?.value;
|
||||
if (value != null) return factory.create(value);
|
||||
return factory.create(await ref.watch(agentSettingsProvider.future));
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
|
||||
@ProviderFor(AgentSettings)
|
||||
final agentSettingsProvider = AgentSettingsProvider._();
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
final class AgentSettingsProvider
|
||||
extends $AsyncNotifierProvider<AgentSettings, AgentSettingsState> {
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
AgentSettingsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSettingsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSettingsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AgentSettings create() => AgentSettings();
|
||||
}
|
||||
|
||||
String _$agentSettingsHash() => r'484af184c2ccf373b8d0955d737ce64b5a085c54';
|
||||
|
||||
/// Presentation-facing state holder. Persistence and credentials are delegated
|
||||
/// to [AgentSettingsService].
|
||||
|
||||
abstract class _$AgentSettings extends $AsyncNotifier<AgentSettingsState> {
|
||||
FutureOr<AgentSettingsState> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<AgentSettingsState>, AgentSettingsState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<AgentSettingsState>, AgentSettingsState>,
|
||||
AsyncValue<AgentSettingsState>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(agentRuntime)
|
||||
final agentRuntimeProvider = AgentRuntimeProvider._();
|
||||
|
||||
final class AgentRuntimeProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<AgentRuntime?>,
|
||||
AgentRuntime?,
|
||||
FutureOr<AgentRuntime?>
|
||||
>
|
||||
with $FutureModifier<AgentRuntime?>, $FutureProvider<AgentRuntime?> {
|
||||
AgentRuntimeProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentRuntimeProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentRuntimeHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<AgentRuntime?> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<AgentRuntime?> create(Ref ref) {
|
||||
return agentRuntime(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentRuntimeHash() => r'fa5447ca986924e6f1fe82ee20f6b7c3b41a96c4';
|
||||
@@ -0,0 +1,259 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import 'agent_credentials.dart';
|
||||
import 'agent_models.dart';
|
||||
|
||||
part 'agent_settings_service.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentSettingsService agentSettingsService(Ref ref) {
|
||||
return AgentSettingsService(
|
||||
repository: ref.watch(agentSettingsRepositoryProvider),
|
||||
credentials: ref.watch(agentCredentialStoreProvider),
|
||||
);
|
||||
}
|
||||
|
||||
/// Owns validation and consistency across settings storage and secure storage.
|
||||
class AgentSettingsService {
|
||||
const AgentSettingsService({
|
||||
required this._repository,
|
||||
required this._credentials,
|
||||
});
|
||||
|
||||
final AgentSettingsRepository _repository;
|
||||
final AgentCredentialStore _credentials;
|
||||
|
||||
Future<AgentSettingsState> load() => _repository.load();
|
||||
|
||||
Future<AgentSettingsState> setEnabled(
|
||||
AgentSettingsState current,
|
||||
bool enabled,
|
||||
) => _save(current, current.copyWith(enabled: enabled));
|
||||
|
||||
Future<AgentSettingsState> setProviderEnabled(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
bool enabled,
|
||||
) {
|
||||
if (!current.providers.any((provider) => provider.id == providerId)) {
|
||||
throw ArgumentError('Unknown Agent provider');
|
||||
}
|
||||
final providers = [
|
||||
for (final provider in current.providers)
|
||||
if (provider.id == providerId)
|
||||
provider.copyWith(enabled: enabled)
|
||||
else
|
||||
provider,
|
||||
];
|
||||
return _save(
|
||||
current,
|
||||
_normalizeSelection(
|
||||
current.copyWith(
|
||||
providers: providers,
|
||||
enabled: enabled ? true : current.enabled,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> selectModel(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
String modelId,
|
||||
) async {
|
||||
final provider = current.providers
|
||||
.where((candidate) => candidate.id == providerId)
|
||||
.firstOrNull;
|
||||
if (provider == null ||
|
||||
!provider.enabled ||
|
||||
!provider.models.any((candidate) => candidate.id == modelId)) {
|
||||
throw ArgumentError('Unknown Agent model selection');
|
||||
}
|
||||
return _save(
|
||||
current,
|
||||
current.copyWith(
|
||||
enabled: true,
|
||||
selectedProviderId: providerId,
|
||||
selectedModelId: modelId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> upsertProvider(
|
||||
AgentSettingsState current, {
|
||||
String? id,
|
||||
required String name,
|
||||
required AgentApiType apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey = false,
|
||||
}) async {
|
||||
final providerId = id ?? const Uuid().v4();
|
||||
final existing = current.providers
|
||||
.where((provider) => provider.id == providerId)
|
||||
.firstOrNull;
|
||||
_validateProvider(name, baseUrl, models, apiKey);
|
||||
|
||||
var credentialId = existing?.credentialId;
|
||||
var credentialWriteAttempted = false;
|
||||
String? previousSecret;
|
||||
String? credentialToDelete;
|
||||
if (clearApiKey && credentialId != null) {
|
||||
credentialToDelete = credentialId;
|
||||
credentialId = null;
|
||||
} else if (apiKey != null && apiKey.isNotEmpty) {
|
||||
credentialId ??= 'cutdex-agent-provider-$providerId';
|
||||
if (existing?.credentialId != null) {
|
||||
previousSecret = await _credentials.read(credentialId);
|
||||
}
|
||||
credentialWriteAttempted = true;
|
||||
try {
|
||||
await _credentials.write(credentialId, apiKey);
|
||||
} catch (error, stackTrace) {
|
||||
await _restoreCredential(credentialId, previousSecret);
|
||||
Error.throwWithStackTrace(error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
final normalizedModels = [
|
||||
for (final model in models) model.copyWith(id: model.id.trim()),
|
||||
];
|
||||
final provider = AgentProviderSettings(
|
||||
id: providerId,
|
||||
name: name.trim(),
|
||||
apiType: apiType.name,
|
||||
baseUrl: baseUrl.trim(),
|
||||
credentialId: credentialId,
|
||||
enabled: existing?.enabled ?? true,
|
||||
models: List.unmodifiable(normalizedModels),
|
||||
);
|
||||
final providers = [
|
||||
for (final candidate in current.providers)
|
||||
if (candidate.id != providerId) candidate,
|
||||
provider,
|
||||
];
|
||||
|
||||
try {
|
||||
final saved = await _save(
|
||||
current,
|
||||
_normalizeSelection(
|
||||
current.copyWith(
|
||||
providers: providers,
|
||||
enabled: (existing?.enabled ?? true) ? true : current.enabled,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (credentialToDelete != null) {
|
||||
await _deleteOrphan(credentialToDelete);
|
||||
}
|
||||
return saved;
|
||||
} catch (error, stackTrace) {
|
||||
if (credentialWriteAttempted && credentialId != null) {
|
||||
await _restoreCredential(credentialId, previousSecret);
|
||||
}
|
||||
Error.throwWithStackTrace(error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> deleteProvider(
|
||||
AgentSettingsState current,
|
||||
String providerId,
|
||||
) async {
|
||||
final removed = current.providers
|
||||
.where((provider) => provider.id == providerId)
|
||||
.firstOrNull;
|
||||
if (removed == null) return current;
|
||||
final providers = current.providers
|
||||
.where((provider) => provider.id != providerId)
|
||||
.toList();
|
||||
final saved = await _save(
|
||||
current,
|
||||
_normalizeSelection(current.copyWith(providers: providers)),
|
||||
);
|
||||
if (removed.credentialId case final credentialId?) {
|
||||
await _deleteOrphan(credentialId);
|
||||
}
|
||||
return saved;
|
||||
}
|
||||
|
||||
Future<AgentSettingsState> _save(
|
||||
AgentSettingsState current,
|
||||
AgentSettingsState next,
|
||||
) async {
|
||||
final revised = next.copyWith(revision: current.revision + 1);
|
||||
await _repository.save(revised);
|
||||
return revised;
|
||||
}
|
||||
|
||||
Future<void> _deleteOrphan(String credentialId) async {
|
||||
try {
|
||||
await _credentials.delete(credentialId);
|
||||
} catch (_) {
|
||||
// Metadata is authoritative. An inaccessible orphan can be cleaned later.
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _restoreCredential(
|
||||
String credentialId,
|
||||
String? previousSecret,
|
||||
) async {
|
||||
try {
|
||||
if (previousSecret == null) {
|
||||
await _credentials.delete(credentialId);
|
||||
} else {
|
||||
await _credentials.write(credentialId, previousSecret);
|
||||
}
|
||||
} catch (_) {
|
||||
// Preserve the original storage or repository failure for the caller.
|
||||
}
|
||||
}
|
||||
|
||||
static AgentSettingsState _normalizeSelection(AgentSettingsState settings) {
|
||||
final available = settings.providers.where(
|
||||
(provider) => provider.enabled && provider.models.isNotEmpty,
|
||||
);
|
||||
final selected = available
|
||||
.where((provider) => provider.id == settings.selectedProviderId)
|
||||
.firstOrNull;
|
||||
final provider = selected ?? available.firstOrNull;
|
||||
final model =
|
||||
provider?.models
|
||||
.where((model) => model.id == settings.selectedModelId)
|
||||
.firstOrNull ??
|
||||
provider?.models.firstOrNull;
|
||||
return settings.copyWith(
|
||||
selectedProviderId: provider?.id,
|
||||
selectedModelId: model?.id,
|
||||
);
|
||||
}
|
||||
|
||||
static void _validateProvider(
|
||||
String name,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
) {
|
||||
final uri = Uri.tryParse(baseUrl.trim());
|
||||
if (name.trim().isEmpty ||
|
||||
uri == null ||
|
||||
!uri.hasAuthority ||
|
||||
!['http', 'https'].contains(uri.scheme) ||
|
||||
uri.userInfo.isNotEmpty ||
|
||||
uri.hasQuery ||
|
||||
uri.hasFragment ||
|
||||
models.isEmpty ||
|
||||
models.any((model) => model.id.trim().isEmpty) ||
|
||||
models.map((model) => model.id.trim()).toSet().length !=
|
||||
models.length ||
|
||||
models.any(
|
||||
(model) => !model.hasValidTokenBudget || !model.hasInstructionBudget,
|
||||
) ||
|
||||
(apiKey?.contains('\n') ?? false) ||
|
||||
(apiKey?.contains('\r') ?? false)) {
|
||||
throw ArgumentError('Invalid Agent provider configuration');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_settings_service.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentSettingsService)
|
||||
final agentSettingsServiceProvider = AgentSettingsServiceProvider._();
|
||||
|
||||
final class AgentSettingsServiceProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentSettingsService,
|
||||
AgentSettingsService,
|
||||
AgentSettingsService
|
||||
>
|
||||
with $Provider<AgentSettingsService> {
|
||||
AgentSettingsServiceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentSettingsServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentSettingsServiceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentSettingsService> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentSettingsService create(Ref ref) {
|
||||
return agentSettingsService(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentSettingsService value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentSettingsService>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentSettingsServiceHash() =>
|
||||
r'76935437a9221e7add0706e92634ae8a21496fa2';
|
||||
@@ -0,0 +1,389 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_agent/io.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:path_provider/path_provider.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../errors/app_failure.dart';
|
||||
|
||||
part 'conversation_repository.g.dart';
|
||||
part 'conversation_repository.freezed.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
ConversationLocation conversationLocation(Ref ref) => ConversationLocation(
|
||||
ref.watch(conversationLocationSettingsRepositoryProvider),
|
||||
);
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<ConversationRepository> conversationRepository(Ref ref) async =>
|
||||
ConversationRepository(
|
||||
await ref.watch(conversationLocationProvider).load(),
|
||||
);
|
||||
|
||||
/// The location pointer is replaceable; the conversation files are not app data.
|
||||
class ConversationLocation {
|
||||
ConversationLocation(
|
||||
this._settings, {
|
||||
Future<Directory> Function()? documentsDirectory,
|
||||
}) : _documentsDirectory =
|
||||
documentsDirectory ?? getApplicationDocumentsDirectory;
|
||||
|
||||
final ConversationLocationSettingsRepository _settings;
|
||||
final Future<Directory> Function() _documentsDirectory;
|
||||
|
||||
Future<Directory> load() async {
|
||||
final configured = await _settings.load();
|
||||
if (configured != null) {
|
||||
final root = Directory(configured);
|
||||
if (!root.isAbsolute || !await root.exists()) {
|
||||
throw AppException(
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
diagnostic: root.path,
|
||||
);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
final documents = await _documentsDirectory();
|
||||
return Directory(p.join(documents.path, 'Cutdex', 'Conversations'));
|
||||
}
|
||||
|
||||
Future<void> useExisting(Directory root) async {
|
||||
if (!root.isAbsolute || !await root.exists()) {
|
||||
throw AppException(
|
||||
AppErrorCode.agentLocationUnavailable,
|
||||
diagnostic: root.path,
|
||||
);
|
||||
}
|
||||
if (!await ConversationRepository(root).verify()) {
|
||||
throw const FormatException('Invalid conversation directory');
|
||||
}
|
||||
await _settings.save(root.path);
|
||||
}
|
||||
|
||||
Future<void> relocate(Directory source, Directory target) async {
|
||||
if (!target.isAbsolute || await target.exists()) {
|
||||
throw const FileSystemException(
|
||||
'Destination must be an unused directory',
|
||||
);
|
||||
}
|
||||
final sourcePath = p.normalize(source.absolute.path);
|
||||
final targetPath = p.normalize(target.absolute.path);
|
||||
if (targetPath == sourcePath || p.isWithin(sourcePath, targetPath)) {
|
||||
throw const FileSystemException(
|
||||
'Destination cannot be inside the current conversations directory',
|
||||
);
|
||||
}
|
||||
final staging = await target.parent.createTemp('.cutdex-conversations-');
|
||||
try {
|
||||
await _copyDirectory(source, staging);
|
||||
if (!(await ConversationRepository(staging).verify())) {
|
||||
throw const FormatException('Copied conversations failed validation');
|
||||
}
|
||||
await staging.rename(target.path);
|
||||
await _settings.save(target.path);
|
||||
} finally {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
static Future<void> _copyDirectory(Directory source, Directory target) async {
|
||||
if (!await source.exists()) return;
|
||||
await for (final entry in source.list(followLinks: false)) {
|
||||
final destination = p.join(target.path, p.basename(entry.path));
|
||||
if (entry is Directory) {
|
||||
final child = await Directory(destination).create();
|
||||
await _copyDirectory(entry, child);
|
||||
} else if (entry is File) {
|
||||
await entry.copy(destination);
|
||||
} else {
|
||||
throw const FileSystemException('Unsupported conversation entry');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ConversationMetadata with _$ConversationMetadata {
|
||||
const factory ConversationMetadata({
|
||||
required String id,
|
||||
required String projectId,
|
||||
required String title,
|
||||
required DateTime createdAt,
|
||||
required DateTime updatedAt,
|
||||
required String providerId,
|
||||
required String modelId,
|
||||
required String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) required bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
required List<int?> responseDurationsMs,
|
||||
}) = _ConversationMetadata;
|
||||
|
||||
factory ConversationMetadata.fromJson(Map<String, Object?> json) =>
|
||||
_$ConversationMetadataFromJson(json);
|
||||
}
|
||||
|
||||
/// Owns project-to-conversation membership; the Agent owns journal contents.
|
||||
class ConversationRepository {
|
||||
ConversationRepository(this.root);
|
||||
|
||||
final Directory root;
|
||||
static const _uuid = Uuid();
|
||||
final Set<String> _pendingInProcess = {};
|
||||
|
||||
String _projectName(String id) =>
|
||||
base64Url.encode(utf8.encode(id)).replaceAll('=', '');
|
||||
|
||||
Directory _project(String id, {bool trash = false}) =>
|
||||
Directory(p.joinAll([root.path, if (trash) 'Trash', _projectName(id)]));
|
||||
|
||||
Directory directory(
|
||||
String projectId,
|
||||
String conversationId, {
|
||||
bool trash = false,
|
||||
}) {
|
||||
if (!Uuid.isValidUUID(fromString: conversationId)) {
|
||||
throw ArgumentError.value(conversationId, 'conversationId');
|
||||
}
|
||||
return Directory(
|
||||
p.join(_project(projectId, trash: trash).path, conversationId),
|
||||
);
|
||||
}
|
||||
|
||||
FileSessionStore store(ConversationMetadata conversation) =>
|
||||
FileSessionStore(directory(conversation.projectId, conversation.id));
|
||||
|
||||
Future<ConversationMetadata> begin({
|
||||
required String projectId,
|
||||
required String timelineId,
|
||||
required String providerId,
|
||||
required String modelId,
|
||||
required String title,
|
||||
}) async {
|
||||
final now = DateTime.now().toUtc();
|
||||
final item = ConversationMetadata(
|
||||
id: _uuid.v4(),
|
||||
projectId: projectId,
|
||||
title: title.trim(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
providerId: providerId,
|
||||
modelId: modelId,
|
||||
timelineId: timelineId,
|
||||
pending: true,
|
||||
responseDurationsMs: const [],
|
||||
);
|
||||
await directory(projectId, item.id).create(recursive: true);
|
||||
await _write(item);
|
||||
_pendingInProcess.add(item.id);
|
||||
return item;
|
||||
}
|
||||
|
||||
Future<ConversationMetadata> publish(ConversationMetadata item) async {
|
||||
final snapshot = await store(item).read(item.id);
|
||||
if (snapshot == null ||
|
||||
!snapshot.history.any((message) => message.role == MessageRole.user)) {
|
||||
throw StateError('Conversation has no saved user message');
|
||||
}
|
||||
final published = item.copyWith(
|
||||
pending: false,
|
||||
updatedAt: DateTime.now().toUtc(),
|
||||
);
|
||||
await _write(published);
|
||||
_pendingInProcess.remove(item.id);
|
||||
return published;
|
||||
}
|
||||
|
||||
Future<ConversationMetadata?> read(
|
||||
String projectId,
|
||||
String id, {
|
||||
bool trash = false,
|
||||
}) async {
|
||||
final file = File(
|
||||
p.join(directory(projectId, id, trash: trash).path, 'metadata.json'),
|
||||
);
|
||||
if (!await file.exists()) return null;
|
||||
final json = (jsonDecode(await file.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
final item = ConversationMetadata.fromJson(json);
|
||||
if (item.id != id || item.projectId != projectId) {
|
||||
throw const FormatException('Conversation identity mismatch');
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
Future<List<ConversationMetadata>> list(
|
||||
String projectId, {
|
||||
bool trash = false,
|
||||
}) async {
|
||||
final parent = _project(projectId, trash: trash);
|
||||
if (!await parent.exists()) return [];
|
||||
final result = <ConversationMetadata>[];
|
||||
await for (final entry in parent.list(followLinks: false)) {
|
||||
if (entry is! Directory) continue;
|
||||
try {
|
||||
final item = await read(
|
||||
projectId,
|
||||
p.basename(entry.path),
|
||||
trash: trash,
|
||||
);
|
||||
if (item == null) {
|
||||
continue;
|
||||
}
|
||||
if (item.pending && !trash) {
|
||||
if (_pendingInProcess.contains(item.id)) continue;
|
||||
final snapshot = await store(item).read(item.id);
|
||||
if (snapshot?.history.any(
|
||||
(message) => message.role == MessageRole.user,
|
||||
) ==
|
||||
true) {
|
||||
result.add(await publish(item));
|
||||
} else {
|
||||
await entry.delete(recursive: true);
|
||||
}
|
||||
} else {
|
||||
result.add(item);
|
||||
}
|
||||
} on FormatException {
|
||||
// One corrupt metadata file must not hide the remaining conversations.
|
||||
} on BadKeyException {
|
||||
// Entries outside the current metadata contract stay untouched.
|
||||
} on TypeError {
|
||||
// Malformed field types are isolated to the affected conversation.
|
||||
} on FileSystemException {
|
||||
// A damaged or inaccessible entry does not hide its siblings.
|
||||
} on ArgumentError {
|
||||
// Ignore unrelated folders without treating them as conversations.
|
||||
}
|
||||
}
|
||||
result.sort((a, b) => b.updatedAt.compareTo(a.updatedAt));
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<String?> selected(String projectId) async {
|
||||
final state = File(p.join(_project(projectId).path, 'state.json'));
|
||||
try {
|
||||
final json = (jsonDecode(await state.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
if (json['version'] != 1) {
|
||||
throw const FormatException('Unsupported conversation state');
|
||||
}
|
||||
final id = json['conversationId'] as String?;
|
||||
if (id != null && await read(projectId, id) != null) return id;
|
||||
} on FileSystemException {
|
||||
// Missing selection is recovered from the conversation list.
|
||||
} on FormatException {
|
||||
// The selection is disposable view state.
|
||||
} on BadKeyException {
|
||||
// Select only conversations that satisfy the current metadata contract.
|
||||
} on TypeError {
|
||||
// A malformed selection is disposable view state.
|
||||
} on ArgumentError {
|
||||
// An invalid UUID is disposable view state.
|
||||
}
|
||||
return (await list(projectId)).firstOrNull?.id;
|
||||
}
|
||||
|
||||
Future<void> select(String projectId, String? id) async {
|
||||
if (id != null && await read(projectId, id) == null) {
|
||||
throw ArgumentError.value(id, 'conversationId');
|
||||
}
|
||||
final parent = _project(projectId);
|
||||
await parent.create(recursive: true);
|
||||
await _writeJson(File(p.join(parent.path, 'state.json')), {
|
||||
'version': 1,
|
||||
'conversationId': id,
|
||||
});
|
||||
}
|
||||
|
||||
Future<ConversationMetadata> update(ConversationMetadata item) async {
|
||||
if (await read(item.projectId, item.id) == null) {
|
||||
throw StateError('Conversation no longer exists');
|
||||
}
|
||||
final updated = item.copyWith(updatedAt: DateTime.now().toUtc());
|
||||
await _write(updated);
|
||||
return updated;
|
||||
}
|
||||
|
||||
Future<void> trash(String projectId, String id) async {
|
||||
final source = directory(projectId, id);
|
||||
if (!await source.exists()) return;
|
||||
final wasSelected = await selected(projectId) == id;
|
||||
final destination = directory(projectId, id, trash: true);
|
||||
await destination.parent.create(recursive: true);
|
||||
await source.rename(destination.path);
|
||||
if (wasSelected) await select(projectId, null);
|
||||
}
|
||||
|
||||
Future<void> restore(String projectId, String id) async {
|
||||
final source = directory(projectId, id, trash: true);
|
||||
if (!await source.exists()) throw ArgumentError.value(id, 'conversationId');
|
||||
final target = directory(projectId, id);
|
||||
if (await target.exists()) throw StateError('Conversation already exists');
|
||||
await target.parent.create(recursive: true);
|
||||
await source.rename(target.path);
|
||||
}
|
||||
|
||||
Future<void> deletePermanently(String projectId, String id) async {
|
||||
if (await selected(projectId) == id) await select(projectId, null);
|
||||
for (final trash in [false, true]) {
|
||||
final target = directory(projectId, id, trash: trash);
|
||||
if (await target.exists()) await target.delete(recursive: true);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> verify() async {
|
||||
if (!await root.exists()) return true;
|
||||
if (!await _verifyProjects(root)) return false;
|
||||
final trash = Directory(p.join(root.path, 'Trash'));
|
||||
if (await trash.exists() && !await _verifyProjects(trash)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<bool> _verifyProjects(Directory parent) async {
|
||||
await for (final project in parent.list(followLinks: false)) {
|
||||
if (project is! Directory || p.basename(project.path) == 'Trash') {
|
||||
continue;
|
||||
}
|
||||
await for (final entry in project.list(followLinks: false)) {
|
||||
if (entry is! Directory) continue;
|
||||
try {
|
||||
final file = File(p.join(entry.path, 'metadata.json'));
|
||||
final json = (jsonDecode(await file.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
final item = ConversationMetadata.fromJson(json);
|
||||
if (item.id != p.basename(entry.path) ||
|
||||
_projectName(item.projectId) != p.basename(project.path)) {
|
||||
return false;
|
||||
}
|
||||
await FileSessionStore(entry).verify(item.id);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Future<void> _write(ConversationMetadata item) => _writeJson(
|
||||
File(p.join(directory(item.projectId, item.id).path, 'metadata.json')),
|
||||
item.toJson(),
|
||||
);
|
||||
|
||||
Future<void> _writeJson(File target, Map<String, Object?> json) async {
|
||||
await target.parent.create(recursive: true);
|
||||
final temp = File('${target.path}.${_uuid.v4()}.tmp');
|
||||
try {
|
||||
await temp.writeAsString(jsonEncode(json), flush: true);
|
||||
await temp.rename(target.path);
|
||||
} finally {
|
||||
if (await temp.exists()) await temp.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,626 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'conversation_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ConversationMetadata {
|
||||
String get id;
|
||||
String get projectId;
|
||||
String get title;
|
||||
DateTime get createdAt;
|
||||
DateTime get updatedAt;
|
||||
String get providerId;
|
||||
String get modelId;
|
||||
String get timelineId;
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
bool get pending;
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> get responseDurationsMs;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<ConversationMetadata> get copyWith =>
|
||||
_$ConversationMetadataCopyWithImpl<ConversationMetadata>(
|
||||
this as ConversationMetadata,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this ConversationMetadata to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ConversationMetadata;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ConversationMetadata &&
|
||||
(identical(other.id, _this.id) || other.id == _this.id) &&
|
||||
(identical(other.projectId, _this.projectId) ||
|
||||
other.projectId == _this.projectId) &&
|
||||
(identical(other.title, _this.title) ||
|
||||
other.title == _this.title) &&
|
||||
(identical(other.createdAt, _this.createdAt) ||
|
||||
other.createdAt == _this.createdAt) &&
|
||||
(identical(other.updatedAt, _this.updatedAt) ||
|
||||
other.updatedAt == _this.updatedAt) &&
|
||||
(identical(other.providerId, _this.providerId) ||
|
||||
other.providerId == _this.providerId) &&
|
||||
(identical(other.modelId, _this.modelId) ||
|
||||
other.modelId == _this.modelId) &&
|
||||
(identical(other.timelineId, _this.timelineId) ||
|
||||
other.timelineId == _this.timelineId) &&
|
||||
(identical(other.pending, _this.pending) ||
|
||||
other.pending == _this.pending) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.responseDurationsMs,
|
||||
_this.responseDurationsMs,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ConversationMetadata;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.id,
|
||||
_this.projectId,
|
||||
_this.title,
|
||||
_this.createdAt,
|
||||
_this.updatedAt,
|
||||
_this.providerId,
|
||||
_this.modelId,
|
||||
_this.timelineId,
|
||||
_this.pending,
|
||||
const DeepCollectionEquality().hash(_this.responseDurationsMs),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ConversationMetadata;
|
||||
return 'ConversationMetadata(id: ${_this.id}, projectId: ${_this.projectId}, title: ${_this.title}, createdAt: ${_this.createdAt}, updatedAt: ${_this.updatedAt}, providerId: ${_this.providerId}, modelId: ${_this.modelId}, timelineId: ${_this.timelineId}, pending: ${_this.pending}, responseDurationsMs: ${_this.responseDurationsMs})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ConversationMetadataCopyWith<$Res> {
|
||||
factory $ConversationMetadataCopyWith(
|
||||
ConversationMetadata value,
|
||||
$Res Function(ConversationMetadata) _then,
|
||||
) = _$ConversationMetadataCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ConversationMetadataCopyWithImpl<$Res>
|
||||
implements $ConversationMetadataCopyWith<$Res> {
|
||||
_$ConversationMetadataCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ConversationMetadata _self;
|
||||
final $Res Function(ConversationMetadata) _then;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? id = null,
|
||||
Object? projectId = null,
|
||||
Object? title = null,
|
||||
Object? createdAt = null,
|
||||
Object? updatedAt = null,
|
||||
Object? providerId = null,
|
||||
Object? modelId = null,
|
||||
Object? timelineId = null,
|
||||
Object? pending = null,
|
||||
Object? responseDurationsMs = null,
|
||||
}) {
|
||||
return _then(
|
||||
ConversationMetadata(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
projectId: null == projectId
|
||||
? _self.projectId
|
||||
: projectId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
title: null == title
|
||||
? _self.title
|
||||
: title // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
createdAt: null == createdAt
|
||||
? _self.createdAt
|
||||
: createdAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
updatedAt: null == updatedAt
|
||||
? _self.updatedAt
|
||||
: updatedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
providerId: null == providerId
|
||||
? _self.providerId
|
||||
: providerId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
modelId: null == modelId
|
||||
? _self.modelId
|
||||
: modelId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
timelineId: null == timelineId
|
||||
? _self.timelineId
|
||||
: timelineId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
pending: null == pending
|
||||
? _self.pending
|
||||
: pending // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
responseDurationsMs: null == responseDurationsMs
|
||||
? _self.responseDurationsMs
|
||||
: responseDurationsMs // ignore: cast_nullable_to_non_nullable
|
||||
as List<int?>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ConversationMetadata].
|
||||
extension ConversationMetadataPatterns on ConversationMetadata {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ConversationMetadata value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ConversationMetadata value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ConversationMetadata value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata():
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ConversationMetadata() when $default != null:
|
||||
return $default(
|
||||
_that.id,
|
||||
_that.projectId,
|
||||
_that.title,
|
||||
_that.createdAt,
|
||||
_that.updatedAt,
|
||||
_that.providerId,
|
||||
_that.modelId,
|
||||
_that.timelineId,
|
||||
_that.pending,
|
||||
_that.responseDurationsMs,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _ConversationMetadata implements ConversationMetadata {
|
||||
const _ConversationMetadata({
|
||||
required this.id,
|
||||
required this.projectId,
|
||||
required this.title,
|
||||
required this.createdAt,
|
||||
required this.updatedAt,
|
||||
required this.providerId,
|
||||
required this.modelId,
|
||||
required this.timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) required this.pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
required List<int?> responseDurationsMs,
|
||||
}) : _responseDurationsMs = responseDurationsMs;
|
||||
factory _ConversationMetadata.fromJson(Map<String, dynamic> json) =>
|
||||
_$ConversationMetadataFromJson(json);
|
||||
|
||||
@override
|
||||
final String id;
|
||||
@override
|
||||
final String projectId;
|
||||
@override
|
||||
final String title;
|
||||
@override
|
||||
final DateTime createdAt;
|
||||
@override
|
||||
final DateTime updatedAt;
|
||||
@override
|
||||
final String providerId;
|
||||
@override
|
||||
final String modelId;
|
||||
@override
|
||||
final String timelineId;
|
||||
@override
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
final bool pending;
|
||||
final List<int?> _responseDurationsMs;
|
||||
@override
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> get responseDurationsMs {
|
||||
if (_responseDurationsMs is EqualUnmodifiableListView)
|
||||
return _responseDurationsMs;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_responseDurationsMs);
|
||||
}
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ConversationMetadataCopyWith<_ConversationMetadata> get copyWith =>
|
||||
__$ConversationMetadataCopyWithImpl<_ConversationMetadata>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$ConversationMetadataToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ConversationMetadata &&
|
||||
(identical(other.id, id) || other.id == id) &&
|
||||
(identical(other.projectId, projectId) ||
|
||||
other.projectId == projectId) &&
|
||||
(identical(other.title, title) || other.title == title) &&
|
||||
(identical(other.createdAt, createdAt) ||
|
||||
other.createdAt == createdAt) &&
|
||||
(identical(other.updatedAt, updatedAt) ||
|
||||
other.updatedAt == updatedAt) &&
|
||||
(identical(other.providerId, providerId) ||
|
||||
other.providerId == providerId) &&
|
||||
(identical(other.modelId, modelId) || other.modelId == modelId) &&
|
||||
(identical(other.timelineId, timelineId) ||
|
||||
other.timelineId == timelineId) &&
|
||||
(identical(other.pending, pending) || other.pending == pending) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.responseDurationsMs,
|
||||
_responseDurationsMs,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
id,
|
||||
projectId,
|
||||
title,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
providerId,
|
||||
modelId,
|
||||
timelineId,
|
||||
pending,
|
||||
const DeepCollectionEquality().hash(_responseDurationsMs),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ConversationMetadata(id: $id, projectId: $projectId, title: $title, createdAt: $createdAt, updatedAt: $updatedAt, providerId: $providerId, modelId: $modelId, timelineId: $timelineId, pending: $pending, responseDurationsMs: $responseDurationsMs)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ConversationMetadataCopyWith<$Res>
|
||||
implements $ConversationMetadataCopyWith<$Res> {
|
||||
factory _$ConversationMetadataCopyWith(
|
||||
_ConversationMetadata value,
|
||||
$Res Function(_ConversationMetadata) _then,
|
||||
) = __$ConversationMetadataCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String id,
|
||||
String projectId,
|
||||
String title,
|
||||
DateTime createdAt,
|
||||
DateTime updatedAt,
|
||||
String providerId,
|
||||
String modelId,
|
||||
String timelineId,
|
||||
@JsonKey(required: true, disallowNullValue: true) bool pending,
|
||||
@JsonKey(required: true, disallowNullValue: true)
|
||||
List<int?> responseDurationsMs,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ConversationMetadataCopyWithImpl<$Res>
|
||||
implements _$ConversationMetadataCopyWith<$Res> {
|
||||
__$ConversationMetadataCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ConversationMetadata _self;
|
||||
final $Res Function(_ConversationMetadata) _then;
|
||||
|
||||
/// Create a copy of ConversationMetadata
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? id = null,
|
||||
Object? projectId = null,
|
||||
Object? title = null,
|
||||
Object? createdAt = null,
|
||||
Object? updatedAt = null,
|
||||
Object? providerId = null,
|
||||
Object? modelId = null,
|
||||
Object? timelineId = null,
|
||||
Object? pending = null,
|
||||
Object? responseDurationsMs = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ConversationMetadata(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
projectId: null == projectId
|
||||
? _self.projectId
|
||||
: projectId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
title: null == title
|
||||
? _self.title
|
||||
: title // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
createdAt: null == createdAt
|
||||
? _self.createdAt
|
||||
: createdAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
updatedAt: null == updatedAt
|
||||
? _self.updatedAt
|
||||
: updatedAt // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime,
|
||||
providerId: null == providerId
|
||||
? _self.providerId
|
||||
: providerId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
modelId: null == modelId
|
||||
? _self.modelId
|
||||
: modelId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
timelineId: null == timelineId
|
||||
? _self.timelineId
|
||||
: timelineId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
pending: null == pending
|
||||
? _self.pending
|
||||
: pending // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
responseDurationsMs: null == responseDurationsMs
|
||||
? _self._responseDurationsMs
|
||||
: responseDurationsMs // ignore: cast_nullable_to_non_nullable
|
||||
as List<int?>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'conversation_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_ConversationMetadata _$ConversationMetadataFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) {
|
||||
$checkKeys(
|
||||
json,
|
||||
requiredKeys: const ['pending', 'responseDurationsMs'],
|
||||
disallowNullValues: const ['pending', 'responseDurationsMs'],
|
||||
);
|
||||
return _ConversationMetadata(
|
||||
id: json['id'] as String,
|
||||
projectId: json['projectId'] as String,
|
||||
title: json['title'] as String,
|
||||
createdAt: DateTime.parse(json['createdAt'] as String),
|
||||
updatedAt: DateTime.parse(json['updatedAt'] as String),
|
||||
providerId: json['providerId'] as String,
|
||||
modelId: json['modelId'] as String,
|
||||
timelineId: json['timelineId'] as String,
|
||||
pending: json['pending'] as bool,
|
||||
responseDurationsMs: (json['responseDurationsMs'] as List<dynamic>)
|
||||
.map((e) => (e as num?)?.toInt())
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> _$ConversationMetadataToJson(
|
||||
_ConversationMetadata instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'projectId': instance.projectId,
|
||||
'title': instance.title,
|
||||
'createdAt': instance.createdAt.toIso8601String(),
|
||||
'updatedAt': instance.updatedAt.toIso8601String(),
|
||||
'providerId': instance.providerId,
|
||||
'modelId': instance.modelId,
|
||||
'timelineId': instance.timelineId,
|
||||
'pending': instance.pending,
|
||||
'responseDurationsMs': instance.responseDurationsMs,
|
||||
};
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(conversationLocation)
|
||||
final conversationLocationProvider = ConversationLocationProvider._();
|
||||
|
||||
final class ConversationLocationProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
ConversationLocation,
|
||||
ConversationLocation,
|
||||
ConversationLocation
|
||||
>
|
||||
with $Provider<ConversationLocation> {
|
||||
ConversationLocationProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'conversationLocationProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationLocationHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<ConversationLocation> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
ConversationLocation create(Ref ref) {
|
||||
return conversationLocation(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ConversationLocation value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ConversationLocation>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$conversationLocationHash() =>
|
||||
r'f087694520af1c0f37a5311284768415a95b3811';
|
||||
|
||||
@ProviderFor(conversationRepository)
|
||||
final conversationRepositoryProvider = ConversationRepositoryProvider._();
|
||||
|
||||
final class ConversationRepositoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<ConversationRepository>,
|
||||
ConversationRepository,
|
||||
FutureOr<ConversationRepository>
|
||||
>
|
||||
with
|
||||
$FutureModifier<ConversationRepository>,
|
||||
$FutureProvider<ConversationRepository> {
|
||||
ConversationRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'conversationRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<ConversationRepository> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<ConversationRepository> create(Ref ref) {
|
||||
return conversationRepository(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$conversationRepositoryHash() =>
|
||||
r'674fa602f63c49495d4c9c6773dd98ebd0bf30b2';
|
||||
@@ -0,0 +1,448 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
|
||||
/// Deterministic, read-only acceptance for explicitly declared editor outcomes.
|
||||
/// Contracts live in successful tool results, so compaction and restart cannot
|
||||
/// erase or silently weaken them. Semantic quality is deliberately out of scope.
|
||||
class EditorAcceptance {
|
||||
EditorAcceptance(Iterable<AgentTool> tools)
|
||||
: _tools = {for (final tool in tools) tool.name: tool};
|
||||
|
||||
final Map<String, AgentTool> _tools;
|
||||
static const _registration = {
|
||||
'editor_expect_clips',
|
||||
'editor_expect_translation',
|
||||
'timeline_planBeatCuts',
|
||||
};
|
||||
static const _coveredWrites = {'clip_setAudio', 'caption_addTranslations'};
|
||||
|
||||
List<AgentTool> get tools => [
|
||||
AgentTool(
|
||||
name: 'editor_expect_clips',
|
||||
description: 'Before changing clips, declare expected final names and static parameter default values. Captures exact clip count, ordering, timing and connections to preserve. Every declared clip is checked from CURRENT project state before completion. Register all requested targets, not only those already edited. Re-registering cannot weaken an earlier contract in the same user task. Animated keyframe values are not checked by this tool.',
|
||||
parameters: {
|
||||
'type': 'object',
|
||||
'properties': {
|
||||
'workspaceId': {'type': 'string'},
|
||||
'preserveLayout': {
|
||||
'type': 'boolean',
|
||||
'description': 'Default true; false only when the user also requests layout or timing changes.',
|
||||
},
|
||||
'clips': {
|
||||
'type': 'array',
|
||||
'minItems': 1,
|
||||
'maxItems': 200,
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
'clipId': {'type': 'string'},
|
||||
'name': {'type': 'string'},
|
||||
'parameters': {
|
||||
'type': 'array',
|
||||
'maxItems': 32,
|
||||
'items': {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
'parameterId': {'type': 'string'},
|
||||
'value': {'type': 'number'},
|
||||
},
|
||||
'required': ['parameterId', 'value'],
|
||||
},
|
||||
},
|
||||
},
|
||||
'required': ['clipId'],
|
||||
},
|
||||
},
|
||||
},
|
||||
'required': ['workspaceId', 'clips'],
|
||||
'additionalProperties': false,
|
||||
},
|
||||
validate: _validateClips,
|
||||
execute: (call, context) async {
|
||||
final args = call.arguments;
|
||||
final view = await _read('timeline_query', {
|
||||
'workspaceId': args['workspaceId'],
|
||||
'includeParameters': false,
|
||||
}, context);
|
||||
final ids = (view.data['clips'] as List)
|
||||
.map((c) => (c as Map)['clipId'])
|
||||
.toSet();
|
||||
final contracts = <Object?>[];
|
||||
for (final row in args['clips'] as List) {
|
||||
if (!ids.contains(row['clipId'])) {
|
||||
return ToolResult('Unknown clipId ${row['clipId']}', isError: true);
|
||||
}
|
||||
contracts.add({
|
||||
'kind': 'clip',
|
||||
'workspaceId': args['workspaceId'],
|
||||
'expected': row,
|
||||
if (args['preserveLayout'] != false)
|
||||
'layoutHash': editorEvidenceHash(editorLayout(view.data)),
|
||||
});
|
||||
}
|
||||
return ToolResult(
|
||||
'Registered deterministic clip outcomes; semantic quality is not certified',
|
||||
data: {'contracts': contracts, 'version': view.version},
|
||||
);
|
||||
},
|
||||
// A started registration with no durable result must not recapture a new
|
||||
// baseline after concurrent edits. The normal unknown-outcome path applies.
|
||||
),
|
||||
AgentTool(
|
||||
name: 'editor_expect_translation',
|
||||
description: 'After creating the new target track and BEFORE writing translations, register sourceRoleId and targetRoleId. Reads all source pages at one version. Completion checks source unchanged, track identities/count unchanged, target cue count and timing multiset equal source, unique target IDs and nonempty text. This does NOT certify translation meaning or fluency; semantic concerns are review suggestions, never automatic rewrite instructions.',
|
||||
parameters: {
|
||||
'type': 'object',
|
||||
'additionalProperties': false,
|
||||
'properties': {
|
||||
for (final key in ['workspaceId', 'sourceRoleId', 'targetRoleId'])
|
||||
key: {'type': 'string'},
|
||||
},
|
||||
'required': ['workspaceId', 'sourceRoleId', 'targetRoleId'],
|
||||
},
|
||||
validate: (a) =>
|
||||
[
|
||||
'workspaceId',
|
||||
'sourceRoleId',
|
||||
'targetRoleId',
|
||||
].any((k) => a[k] is! String || (a[k] as String).isEmpty) ||
|
||||
a['sourceRoleId'] == a['targetRoleId']
|
||||
? 'Supply distinct source and target tracks and a workspace'
|
||||
: null,
|
||||
execute: (call, context) async {
|
||||
final a = call.arguments;
|
||||
final tracks = await _read('caption_list', {
|
||||
'workspaceId': a['workspaceId'],
|
||||
}, context);
|
||||
final ids = editorTrackIds(tracks.data);
|
||||
if (!ids.contains(a['sourceRoleId']) ||
|
||||
!ids.contains(a['targetRoleId'])) {
|
||||
return ToolResult(
|
||||
'Source or target track does not exist',
|
||||
isError: true,
|
||||
);
|
||||
}
|
||||
final source = await _cues(
|
||||
a['workspaceId'] as String,
|
||||
a['sourceRoleId'] as String,
|
||||
context,
|
||||
tracks.version,
|
||||
);
|
||||
return ToolResult(
|
||||
'Registered translation structure; semantic quality remains unverified',
|
||||
data: {
|
||||
'contracts': [
|
||||
{
|
||||
'kind': 'translation',
|
||||
...a,
|
||||
'trackIds': ids,
|
||||
'sourceHash': editorEvidenceHash(source),
|
||||
'sourceCount': source.length,
|
||||
},
|
||||
],
|
||||
'version': tracks.version,
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
String? _validateClips(Map<String, Object?> a) {
|
||||
if (a['workspaceId'] is! String ||
|
||||
(a['workspaceId'] as String).isEmpty ||
|
||||
a['clips'] is! List ||
|
||||
(a['clips'] as List).isEmpty ||
|
||||
(a['clips'] as List).length > 200 ||
|
||||
(a['preserveLayout'] != null && a['preserveLayout'] is! bool)) {
|
||||
return 'Invalid clip expectations';
|
||||
}
|
||||
final ids = <String>{};
|
||||
for (final row in a['clips'] as List) {
|
||||
if (row is! Map ||
|
||||
row['clipId'] is! String ||
|
||||
!ids.add(row['clipId'] as String) ||
|
||||
(row['name'] != null && row['name'] is! String)) {
|
||||
return 'Supply unique clip IDs and valid names';
|
||||
}
|
||||
final parameters = row['parameters'];
|
||||
if (parameters != null && parameters is! List) {
|
||||
return 'parameters must be an array';
|
||||
}
|
||||
if (row['name'] == null &&
|
||||
(parameters == null || (parameters as List).isEmpty)) {
|
||||
return 'Declare a name or parameter value';
|
||||
}
|
||||
final params = <String>{};
|
||||
for (final p in parameters as List? ?? const []) {
|
||||
if (p is! Map ||
|
||||
p['parameterId'] is! String ||
|
||||
!params.add(p['parameterId'] as String) ||
|
||||
p['value'] is! num ||
|
||||
!(p['value'] as num).isFinite) {
|
||||
return 'Supply unique parameter IDs and finite values';
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
Future<ToolResult> check(
|
||||
SessionSnapshot snapshot,
|
||||
CancellationToken token,
|
||||
) async {
|
||||
final calls = <String, ToolCall>{};
|
||||
final contracts = <String, Map<String, Object?>>{};
|
||||
final issues = <Map<String, Object?>>[];
|
||||
final writes = <ToolCall>[];
|
||||
for (final message in snapshot.history.skip(snapshot.runStart)) {
|
||||
for (final call in message.calls) {
|
||||
calls[call.id] = call;
|
||||
}
|
||||
if (message.role != MessageRole.tool || message.isError) continue;
|
||||
final call = calls[message.callId];
|
||||
if (call == null) continue;
|
||||
if (_coveredWrites.contains(call.name)) writes.add(call);
|
||||
if (!_registration.contains(call.name)) continue;
|
||||
final result = jsonDecode(message.text) as Map;
|
||||
final payload = result['data'] as Map;
|
||||
final List<dynamic> registrations;
|
||||
if (call.name == 'timeline_planBeatCuts') {
|
||||
final plan = payload['data'] as Map;
|
||||
if (plan['requireCuts'] != true) continue;
|
||||
registrations = [
|
||||
{
|
||||
...(plan['contract'] as Map),
|
||||
'workspaceId': call.arguments['workspaceId'],
|
||||
},
|
||||
];
|
||||
} else {
|
||||
registrations = payload['contracts'] as List;
|
||||
}
|
||||
for (final raw in registrations) {
|
||||
final c = (raw as Map).cast<String, Object?>();
|
||||
final key =
|
||||
'${c['workspaceId']}:${c['kind']}:${c['kind'] == 'clip' ? (c['expected'] as Map)['clipId'] : c['targetRoleId']}';
|
||||
if (contracts.containsKey(key) &&
|
||||
editorEvidenceHash(contracts[key]) != editorEvidenceHash(c)) {
|
||||
issues.add({
|
||||
'kind': 'contractChanged',
|
||||
'target': key,
|
||||
'reason': 'Earlier acceptance criteria cannot be replaced within this task.',
|
||||
});
|
||||
} else {
|
||||
contracts[key] = c;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Never infer a complete user goal from writes alone. Require explicit
|
||||
// expectations for supported editing operations and disclose coverage.
|
||||
for (final call in writes) {
|
||||
final workspace = call.arguments['workspaceId'];
|
||||
final covered = contracts.values.any((c) {
|
||||
if (c['workspaceId'] != workspace) return false;
|
||||
if (call.name == 'clip_setAudio') {
|
||||
if (c['kind'] != 'clip') return false;
|
||||
final expected = c['expected'] as Map;
|
||||
if (expected['clipId'] != call.arguments['clipId']) return false;
|
||||
final parameters = (expected['parameters'] as List? ?? const [])
|
||||
.map((p) => (p as Map)['parameterId'])
|
||||
.toSet();
|
||||
return (!call.arguments.containsKey('db') ||
|
||||
parameters.contains('cutdex.audio.gainDb')) &&
|
||||
(!call.arguments.containsKey('muted') ||
|
||||
parameters.contains('cutdex.audio.mute'));
|
||||
}
|
||||
return c['kind'] == 'translation' &&
|
||||
c['targetRoleId'] == call.arguments['roleId'];
|
||||
});
|
||||
if (!covered) {
|
||||
issues.add({
|
||||
'kind': 'missingExpectation',
|
||||
'tool': call.name,
|
||||
'arguments': call.arguments,
|
||||
'reason': 'Declare the original requested outcomes with editor_expect_clips or editor_expect_translation. Include every requested target, not just successful writes.',
|
||||
});
|
||||
}
|
||||
}
|
||||
if (issues.isNotEmpty) {
|
||||
return ToolResult(
|
||||
'Acceptance requirements are unresolved',
|
||||
isError: true,
|
||||
data: {'issues': issues},
|
||||
);
|
||||
}
|
||||
final context = ToolContext(
|
||||
sessionId: snapshot.id,
|
||||
runId: snapshot.runId!,
|
||||
operationId:
|
||||
'verification:${snapshot.id}:${snapshot.runId}:${snapshot.turns}',
|
||||
cancellation: token,
|
||||
onProgress: (_) {},
|
||||
);
|
||||
final versions = <String, String>{};
|
||||
final views = <String, _View>{};
|
||||
try {
|
||||
for (final c in contracts.values) {
|
||||
token.throwIfCancelled();
|
||||
final workspace = c['workspaceId'] as String;
|
||||
final view = views[workspace] ??= await _read('timeline_query', {
|
||||
'workspaceId': workspace,
|
||||
}, context);
|
||||
versions[workspace] = view.version;
|
||||
if (view.data['saveState'] != 'saved') {
|
||||
issues.add({
|
||||
'kind': 'saveState',
|
||||
'workspaceId': workspace,
|
||||
'actual': view.data['saveState'],
|
||||
'expected': 'saved',
|
||||
'action': 'Use project_save, then recheck.',
|
||||
});
|
||||
}
|
||||
Map<String, Object?>? tracks;
|
||||
List<Map<String, Object?>> source = const [], target = const [];
|
||||
final expectation = EditorExpectation.fromJson(c);
|
||||
if (expectation.needsCaptions) {
|
||||
final page = await _read('caption_list', {
|
||||
'workspaceId': workspace,
|
||||
}, context);
|
||||
_sameVersion(page.version, view.version);
|
||||
tracks = page.data;
|
||||
source = await _cues(
|
||||
workspace,
|
||||
c['sourceRoleId'] as String,
|
||||
context,
|
||||
view.version,
|
||||
);
|
||||
target = await _cues(
|
||||
workspace,
|
||||
c['targetRoleId'] as String,
|
||||
context,
|
||||
view.version,
|
||||
);
|
||||
}
|
||||
issues.addAll(
|
||||
verifyEditorOutcome(
|
||||
expectation,
|
||||
EditorOutcomeEvidence(
|
||||
timeline: view.data,
|
||||
tracks: tracks,
|
||||
sourceCues: source,
|
||||
targetCues: target,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
// No receipt is reused as current evidence. Catch edits during multi-page
|
||||
// reads as well as changes between workspaces while verification runs.
|
||||
for (final entry in versions.entries) {
|
||||
final current = await _read('timeline_query', {
|
||||
'workspaceId': entry.key,
|
||||
'includeParameters': false,
|
||||
}, context);
|
||||
_sameVersion(current.version, entry.value);
|
||||
}
|
||||
} on AgentCancelled {
|
||||
rethrow;
|
||||
} catch (_) {
|
||||
return ToolResult(
|
||||
'Current project evidence unavailable or changed during verification; query current state and retry. No acceptance granted.',
|
||||
isError: true,
|
||||
data: {
|
||||
'issues': [
|
||||
...issues,
|
||||
{'kind': 'unavailableEvidence'},
|
||||
],
|
||||
},
|
||||
);
|
||||
}
|
||||
return ToolResult(
|
||||
issues.isEmpty
|
||||
? 'Declared deterministic outcomes verified from current project state; semantic quality is not certified.'
|
||||
: 'Current project differs from the requested outcomes. Repair these specific differences and recheck.',
|
||||
isError: issues.isNotEmpty,
|
||||
data: {
|
||||
'scope': 'declaredDeterministicOutcomes',
|
||||
'semanticQuality': 'unverified',
|
||||
'contracts': contracts.length,
|
||||
'versions': versions,
|
||||
'issues': issues,
|
||||
'artifactHashes': {
|
||||
for (final e in views.entries)
|
||||
e.key: editorEvidenceHash(e.value.data),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Future<_View> _read(
|
||||
String name,
|
||||
Map<String, Object?> arguments,
|
||||
ToolContext context,
|
||||
) async {
|
||||
context.cancellation.throwIfCancelled();
|
||||
final tool = _tools[name];
|
||||
if (tool == null || tool.validate(arguments) != null) {
|
||||
throw StateError('Query unavailable');
|
||||
}
|
||||
final result = await tool.execute(
|
||||
ToolCall(id: context.operationId, name: name, arguments: arguments),
|
||||
context,
|
||||
);
|
||||
context.cancellation.throwIfCancelled();
|
||||
final version = result.data['version'];
|
||||
final data = result.data['data'];
|
||||
if (result.isError || version is! String || data is! Map) {
|
||||
throw StateError('Invalid current state');
|
||||
}
|
||||
return _View(data.cast<String, Object?>(), version);
|
||||
}
|
||||
|
||||
Future<List<Map<String, Object?>>> _cues(
|
||||
String workspace,
|
||||
String role,
|
||||
ToolContext context,
|
||||
String version,
|
||||
) async {
|
||||
final cues = <Map<String, Object?>>[];
|
||||
var offset = 0;
|
||||
while (true) {
|
||||
final page = await _read('caption_list', {
|
||||
'workspaceId': workspace,
|
||||
'roleId': role,
|
||||
'offset': offset,
|
||||
'limit': 100,
|
||||
}, context);
|
||||
_sameVersion(page.version, version);
|
||||
final rows = (page.data['cues'] as List)
|
||||
.map((e) => (e as Map).cast<String, Object?>())
|
||||
.toList();
|
||||
cues.addAll(rows);
|
||||
if (cues.length > 20000) throw StateError('Caption verification limit');
|
||||
final next = page.data['nextOffset'];
|
||||
if (next == null) {
|
||||
if (cues.length != page.data['total']) {
|
||||
throw StateError('Incomplete caption read');
|
||||
}
|
||||
return cues;
|
||||
}
|
||||
if (next is! int || next <= offset || rows.isEmpty) {
|
||||
throw StateError('Invalid cursor');
|
||||
}
|
||||
offset = next;
|
||||
}
|
||||
}
|
||||
|
||||
static void _sameVersion(String a, String b) {
|
||||
if (a != b) throw StateError('State changed during verification');
|
||||
}
|
||||
}
|
||||
|
||||
class _View {
|
||||
const _View(this.data, this.version);
|
||||
final Map<String, Object?> data;
|
||||
final String version;
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
/// Protocol adaptation only. The dispatchers belong to the open project.
|
||||
List<AgentTool> editorAgentTools(
|
||||
Map<String, EditorToolDispatcher> workspaces, {
|
||||
bool dynamicWorkspaces = false,
|
||||
Future<void> Function(ToolContext)? beforeInvoke,
|
||||
Future<void> Function(ToolCall, ToolContext, CommandResult)? afterInvoke,
|
||||
}) {
|
||||
ToolResult result(CommandResult value) {
|
||||
final data = value.toJson();
|
||||
final payload = data['data'];
|
||||
if (payload is Map<String, Object?>) {
|
||||
data['data'] = {
|
||||
...payload,
|
||||
if (payload['clips'] is List)
|
||||
'clips': (payload['clips']! as List).map(_compactClip).toList(),
|
||||
// Full schemas are loaded on demand through runtime tool discovery.
|
||||
if (payload['tools'] is List)
|
||||
'tools': [
|
||||
for (final tool in payload['tools']! as List)
|
||||
if (tool is Map<String, Object?>)
|
||||
{'name': tool['name'], 'readOnly': tool['readOnly']}
|
||||
else
|
||||
tool,
|
||||
],
|
||||
};
|
||||
}
|
||||
return ToolResult(value.message, isError: value.isError, data: data);
|
||||
}
|
||||
|
||||
(EditorToolDispatcher, Map<String, Object?>) resolve(
|
||||
Map<String, Object?> args,
|
||||
) {
|
||||
final dispatcher = workspaces[args['workspaceId']];
|
||||
if (dispatcher == null) {
|
||||
throw CommandRejected(
|
||||
'missingWorkspace',
|
||||
'Unknown workspaceId. Copy an exact ID from ${jsonEncode(workspaces.keys.toList())}. '
|
||||
'Call cutdex_workspaces for supported tools.',
|
||||
);
|
||||
}
|
||||
return (dispatcher, {...args}..remove('workspaceId'));
|
||||
}
|
||||
|
||||
String operation(ToolContext context) =>
|
||||
jsonEncode(['agent', context.operationId]);
|
||||
final definitions = {
|
||||
if (dynamicWorkspaces)
|
||||
for (final definition in editorToolDefinitions)
|
||||
definition.name: definition,
|
||||
for (final tools in workspaces.values)
|
||||
for (final definition in tools.definitions) definition.name: definition,
|
||||
};
|
||||
Future<ToolResult> listWorkspaces(ToolContext context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final toolSets = <String, List<String>>{};
|
||||
final ids = <String, String>{};
|
||||
final targets = <Map<String, Object?>>[];
|
||||
for (final entry in workspaces.entries) {
|
||||
final names = [
|
||||
for (final tool in entry.value.definitions)
|
||||
tool.name.replaceAll('.', '_'),
|
||||
]..sort();
|
||||
final key = jsonEncode(names);
|
||||
final id = ids.putIfAbsent(key, () => 'tools${ids.length}');
|
||||
toolSets[id] = names;
|
||||
targets.add({'workspaceId': entry.key, 'toolSetId': id});
|
||||
}
|
||||
return ToolResult(jsonEncode({'targets': targets, 'toolSets': toolSets}));
|
||||
}
|
||||
|
||||
return [
|
||||
AgentTool(
|
||||
name: 'cutdex_workspaces',
|
||||
description: 'List workspace IDs and their supported tools. application manages projects; use a timeline workspace for timeline queries and clip edits. Every call requires an explicit workspaceId from this list.',
|
||||
parameters: const {
|
||||
'type': 'object',
|
||||
'properties': <String, Object?>{},
|
||||
'additionalProperties': false,
|
||||
},
|
||||
validate: (args) => args.isEmpty ? null : 'No arguments expected',
|
||||
execute: (_, context) => listWorkspaces(context),
|
||||
// Discovery is read-only: obtain fresh data after an interrupted call.
|
||||
recover: (_, context) async =>
|
||||
ToolRecovery.completed(await listWorkspaces(context)),
|
||||
),
|
||||
for (final definition in definitions.values)
|
||||
AgentTool(
|
||||
name: definition.name.replaceAll('.', '_'),
|
||||
description: definition.description,
|
||||
parameters: {
|
||||
...definition.inputSchema,
|
||||
'properties': {
|
||||
...definition.inputSchema['properties']! as Map<String, Object?>,
|
||||
'workspaceId': {'type': 'string'},
|
||||
},
|
||||
'required': [
|
||||
...definition.inputSchema['required']! as List,
|
||||
'workspaceId',
|
||||
],
|
||||
},
|
||||
validate: (args) {
|
||||
try {
|
||||
final (dispatcher, arguments) = resolve(args);
|
||||
if (!dispatcher.definitions.any(
|
||||
(tool) => tool.name == definition.name,
|
||||
)) {
|
||||
final available = [
|
||||
for (final entry in workspaces.entries)
|
||||
if (entry.value.definitions.any(
|
||||
(tool) => tool.name == definition.name,
|
||||
))
|
||||
entry.key,
|
||||
];
|
||||
return 'This workspace does not support ${definition.name}. '
|
||||
'Use a workspaceId from ${jsonEncode(available)}. '
|
||||
'Call cutdex_workspaces to inspect workspace tools.';
|
||||
}
|
||||
decodeEditorCommand(definition.name, arguments);
|
||||
return null;
|
||||
} on CommandRejected catch (error) {
|
||||
return error.message;
|
||||
} catch (_) {
|
||||
return 'Invalid arguments';
|
||||
}
|
||||
},
|
||||
execute: (call, context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final (dispatcher, arguments) = resolve(call.arguments);
|
||||
final value = await dispatcher.invoke(
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
context: CommandContext(
|
||||
operationId: operation(context),
|
||||
isCancelled: () => context.cancellation.isCancelled,
|
||||
),
|
||||
);
|
||||
if (value.status == CommandStatus.unknown) {
|
||||
throw StateError(
|
||||
'Reconcile the original operation before retrying',
|
||||
);
|
||||
}
|
||||
if (!value.isError) await afterInvoke?.call(call, context, value);
|
||||
return result(value);
|
||||
},
|
||||
recover: (call, context) async {
|
||||
await beforeInvoke?.call(context);
|
||||
final (dispatcher, arguments) = resolve(call.arguments);
|
||||
if (definition.readOnly) {
|
||||
// Read-only dispatches deliberately have no operation receipt.
|
||||
// Re-query current state; never apply this rule to edits.
|
||||
final value = await dispatcher.invoke(
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
context: CommandContext(
|
||||
operationId: operation(context),
|
||||
isCancelled: () => context.cancellation.isCancelled,
|
||||
),
|
||||
);
|
||||
return value.status == CommandStatus.unknown
|
||||
? const ToolRecovery.unknown()
|
||||
: ToolRecovery.completed(result(value));
|
||||
}
|
||||
final OperationReceipt receipt;
|
||||
try {
|
||||
receipt = await dispatcher.recoverInvocation(
|
||||
operationId: operation(context),
|
||||
name: definition.name,
|
||||
arguments: arguments,
|
||||
);
|
||||
} on CommandRejected {
|
||||
return const ToolRecovery.unknown();
|
||||
}
|
||||
return switch (receipt.state) {
|
||||
OperationState.notStarted => const ToolRecovery.notStarted(),
|
||||
OperationState.running => const ToolRecovery.running(),
|
||||
OperationState.completed
|
||||
when receipt.result!.status != CommandStatus.unknown =>
|
||||
ToolRecovery.completed(result(receipt.result!)),
|
||||
_ => const ToolRecovery.unknown(),
|
||||
};
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
// Keep authored values and keys intact; omit repetitive empty/default metadata
|
||||
// only in the Agent projection. MCP and the authoritative command result retain
|
||||
// the full parameter definitions.
|
||||
Object? _compactClip(Object? value) {
|
||||
if (value is! Map<String, Object?> || value['parameters'] is! List) {
|
||||
return value;
|
||||
}
|
||||
return {
|
||||
...value,
|
||||
'parameters': [
|
||||
for (final parameter in value['parameters']! as List)
|
||||
if (parameter is Map<String, Object?>)
|
||||
Map<String, Object?>.from(parameter)..removeWhere(
|
||||
(key, value) =>
|
||||
(key == 'unit' && value == '') ||
|
||||
(key == 'keyframes' && value is List && value.isEmpty) ||
|
||||
(key == 'minimum' && value == -1000000) ||
|
||||
(key == 'maximum' && value == 1000000),
|
||||
)
|
||||
else
|
||||
parameter,
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
|
||||
import '../errors/app_failure.dart';
|
||||
|
||||
/// Adapts SDK errors by code. Unknown errors retain their complete diagnostics.
|
||||
AppFailure appFailureFromError(Object error) {
|
||||
if (error is AppException) return error.failure;
|
||||
if (error is AppFailure) return error;
|
||||
final AppErrorCode code;
|
||||
switch (error) {
|
||||
case CommandRejected(:final code):
|
||||
final mapped = switch (code) {
|
||||
'missingMedia' => AppErrorCode.mediaNoLongerExists,
|
||||
'staleVersion' ||
|
||||
'invalidSelection' ||
|
||||
'missingClip' => AppErrorCode.timelineChanged,
|
||||
'missingTimeline' ||
|
||||
'timelineNotOpen' => AppErrorCode.openTimelineFailed,
|
||||
'projectNotOpen' => AppErrorCode.openMatchingProject,
|
||||
'missingProject' => AppErrorCode.openProjectFirst,
|
||||
'projectIdMismatch' => AppErrorCode.projectMismatch,
|
||||
'unsupported' ||
|
||||
'unavailable' ||
|
||||
'busy' ||
|
||||
'cancelled' ||
|
||||
'workspaceBusy' ||
|
||||
'projectCreationFailed' ||
|
||||
'invalidArguments' => AppErrorCode.operationFailed,
|
||||
_ => AppErrorCode.diagnostic,
|
||||
};
|
||||
return AppFailure(mapped, diagnostic: error.toString());
|
||||
case ProjectFileException(:final code):
|
||||
final mapped = switch (code) {
|
||||
ProjectFileError.notFound => AppErrorCode.projectMissingDirectory,
|
||||
ProjectFileError.closed => AppErrorCode.projectSessionClosed,
|
||||
ProjectFileError.conflict => AppErrorCode.projectMismatch,
|
||||
_ => AppErrorCode.projectAccessFailed,
|
||||
};
|
||||
return AppFailure(mapped, diagnostic: error.toString());
|
||||
default:
|
||||
code = AppErrorCode.diagnostic;
|
||||
}
|
||||
return AppFailure(code, diagnostic: error.toString());
|
||||
}
|
||||
|
||||
/// Project operations provide context for otherwise unclassified I/O failures.
|
||||
AppFailure projectFailureFromError(Object error) => switch (error) {
|
||||
FileSystemException() => AppFailure(
|
||||
AppErrorCode.projectAccessFailed,
|
||||
diagnostic: error.toString(),
|
||||
),
|
||||
AppException() ||
|
||||
CommandRejected() ||
|
||||
ProjectFileException() ||
|
||||
StateError() => appFailureFromError(error),
|
||||
_ => AppFailure(AppErrorCode.operationFailed, diagnostic: error.toString()),
|
||||
};
|
||||
@@ -0,0 +1,81 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../diagnostics/app_diagnostics.dart';
|
||||
|
||||
import 'package:deskup/deskup.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
export 'package:deskup/deskup.dart' show UpdateStatus, UpdatePhase;
|
||||
|
||||
part 'app_update_bridge.g.dart';
|
||||
|
||||
const appUpdatesChannel = MethodChannel('deskup');
|
||||
const appLifecycleChannel = MethodChannel('cutdex/lifecycle');
|
||||
|
||||
bool get supportsAppUpdates => Deskup.isSupported;
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AppUpdateBridge appUpdateBridge(Ref ref) {
|
||||
final bridge = AppUpdateBridge();
|
||||
ref.onDispose(bridge.dispose);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
// Application adapter: Riverpod ownership and the macOS workspace quit gate.
|
||||
class AppUpdateBridge {
|
||||
AppUpdateBridge([MethodChannel channel = appUpdatesChannel])
|
||||
: _updater = Deskup(channel: channel);
|
||||
|
||||
final Deskup _updater;
|
||||
Stream<UpdateStatus> get events => _updater.events;
|
||||
bool _started = false;
|
||||
bool _disposed = false;
|
||||
Future<void> Function()? _prepareToQuit;
|
||||
|
||||
void start(Future<void> Function() prepareToQuit) {
|
||||
if (_disposed) return;
|
||||
_prepareToQuit = prepareToQuit;
|
||||
if (_started) return;
|
||||
_started = true;
|
||||
if (defaultTargetPlatform == TargetPlatform.macOS) {
|
||||
appLifecycleChannel.setMethodCallHandler((call) async {
|
||||
if (_disposed) return null;
|
||||
if (call.method != 'prepareToQuit') throw MissingPluginException();
|
||||
await _prepareToQuit!();
|
||||
return true;
|
||||
});
|
||||
unawaited(
|
||||
appLifecycleChannel
|
||||
.invokeMethod<void>('ready')
|
||||
.catchError(_initializationError),
|
||||
);
|
||||
}
|
||||
unawaited(_updater.initialize().catchError(_initializationError));
|
||||
}
|
||||
|
||||
void _initializationError(Object error, StackTrace stack) {
|
||||
if (!_disposed && error is! MissingPluginException) {
|
||||
AppDiagnostics.failure('updates', 'initialize', error, stack);
|
||||
}
|
||||
}
|
||||
|
||||
Future<UpdateStatus> status() => _updater.status();
|
||||
Future<void> check() => _updater.check();
|
||||
Future<void> download() => _updater.download();
|
||||
Future<void> validateInstall() => _updater.validateInstall();
|
||||
Future<void> install() => _updater.install();
|
||||
Future<void> setAutomaticChecks(bool enabled) =>
|
||||
_updater.setAutomaticChecks(enabled);
|
||||
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_prepareToQuit = null;
|
||||
if (_started && defaultTargetPlatform == TargetPlatform.macOS) {
|
||||
appLifecycleChannel.setMethodCallHandler(null);
|
||||
}
|
||||
_updater.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'app_update_bridge.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(appUpdateBridge)
|
||||
final appUpdateBridgeProvider = AppUpdateBridgeProvider._();
|
||||
|
||||
final class AppUpdateBridgeProvider
|
||||
extends
|
||||
$FunctionalProvider<AppUpdateBridge, AppUpdateBridge, AppUpdateBridge>
|
||||
with $Provider<AppUpdateBridge> {
|
||||
AppUpdateBridgeProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'appUpdateBridgeProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$appUpdateBridgeHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AppUpdateBridge> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AppUpdateBridge create(Ref ref) {
|
||||
return appUpdateBridge(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AppUpdateBridge value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AppUpdateBridge>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$appUpdateBridgeHash() => r'f119181b32e1785027092937071c1bfc59b7ed7e';
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../features/assistant/agent_conversation_service.dart';
|
||||
import '../workspace/projects.dart';
|
||||
import 'app_update_bridge.dart';
|
||||
|
||||
Future<void> prepareForAppUpdateQuit(Ref ref) async {
|
||||
await ref.read(agentConversationRegistryProvider).cancelAll();
|
||||
await ref.read(projectsProvider.notifier).prepareToQuit();
|
||||
}
|
||||
|
||||
// Keep the saved workspace recoverable if the updater cannot be launched.
|
||||
Future<void> installWindowsUpdate(Ref ref) async {
|
||||
final bridge = ref.read(appUpdateBridgeProvider);
|
||||
await bridge.validateInstall();
|
||||
final registry = ref.read(agentConversationRegistryProvider);
|
||||
await registry.cancelAll();
|
||||
await registry.whilePaused(() async {
|
||||
final projects = ref.read(projectsProvider.notifier);
|
||||
await ref.read(projectsProvider.future);
|
||||
final snapshot = ref.read(projectsProvider).requireValue;
|
||||
await projects.prepareToQuit();
|
||||
try {
|
||||
await bridge.install();
|
||||
} catch (_) {
|
||||
ref.invalidate(projectsProvider);
|
||||
if (snapshot.activeProject case final project?) {
|
||||
await ref
|
||||
.read(projectsProvider.notifier)
|
||||
.open(
|
||||
project.path,
|
||||
expectedId: project.id,
|
||||
timelineId: snapshot.timeline?.id,
|
||||
);
|
||||
}
|
||||
rethrow;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'app_update_bridge.dart';
|
||||
import 'app_update_coordinator.dart';
|
||||
|
||||
export 'app_update_bridge.dart';
|
||||
|
||||
part 'app_updates.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
void appUpdateLifecycle(Ref ref) {
|
||||
if (!supportsAppUpdates) return;
|
||||
ref.watch(appUpdateBridgeProvider).start(() => prepareForAppUpdateQuit(ref));
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'app_updates.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(appUpdateLifecycle)
|
||||
final appUpdateLifecycleProvider = AppUpdateLifecycleProvider._();
|
||||
|
||||
final class AppUpdateLifecycleProvider
|
||||
extends $FunctionalProvider<void, void, void>
|
||||
with $Provider<void> {
|
||||
AppUpdateLifecycleProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'appUpdateLifecycleProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$appUpdateLifecycleHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<void> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
void create(Ref ref) {
|
||||
return appUpdateLifecycle(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(void value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<void>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$appUpdateLifecycleHash() =>
|
||||
r'df3b0fe12a77300a414051e87149de36b0d8b977';
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../features/settings/language_settings.dart';
|
||||
import '../l10n/app_localizations.dart';
|
||||
import '../workspace/project_state.dart';
|
||||
import '../workspace/projects.dart';
|
||||
import '../workspace/preview_target.dart';
|
||||
import '../workspace/timeline_provider.dart';
|
||||
import '../workspace/timeline_session.dart';
|
||||
|
||||
abstract interface class ApplicationCommandDependencies {
|
||||
Future<ProjectState> projectState();
|
||||
Future<bool> createProject(String name);
|
||||
Future<bool> openProject(String path, {String? expectedId});
|
||||
Future<bool> createTimeline(String name);
|
||||
Future<bool> openTimeline(String projectId, String timelineId);
|
||||
Future<EditorTimelineSession> timeline(String projectId, String timelineId);
|
||||
PreviewTarget preview(String projectId, String timelineId);
|
||||
}
|
||||
|
||||
/// Riverpod is confined to the composition adapter, not the command host.
|
||||
class RiverpodApplicationCommandDependencies
|
||||
implements ApplicationCommandDependencies {
|
||||
const RiverpodApplicationCommandDependencies(this._ref);
|
||||
|
||||
final Ref _ref;
|
||||
|
||||
Projects get _projects => _ref.read(projectsProvider.notifier);
|
||||
|
||||
@override
|
||||
Future<ProjectState> projectState() => _ref.read(projectsProvider.future);
|
||||
|
||||
@override
|
||||
Future<bool> createProject(String name) {
|
||||
final configured = _ref.read(languageSettingsProvider).asData?.value;
|
||||
final locale =
|
||||
configured?.locale ??
|
||||
resolveAppLocale(
|
||||
PlatformDispatcher.instance.locales,
|
||||
AppLocalizations.supportedLocales,
|
||||
);
|
||||
return _projects.createProject(
|
||||
name,
|
||||
initialTimelineName: lookupAppLocalizations(locale)
|
||||
.defaultTimelineName(1),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> openProject(String path, {String? expectedId}) =>
|
||||
_projects.open(path, expectedId: expectedId);
|
||||
|
||||
@override
|
||||
Future<bool> createTimeline(String name) =>
|
||||
_projects.createTimeline(name: name);
|
||||
|
||||
@override
|
||||
Future<bool> openTimeline(String projectId, String timelineId) =>
|
||||
_projects.openTimeline(projectId, timelineId);
|
||||
|
||||
@override
|
||||
Future<EditorTimelineSession> timeline(String projectId, String timelineId) =>
|
||||
_ref.read(editorTimelineProvider(projectId, timelineId).future);
|
||||
|
||||
@override
|
||||
PreviewTarget preview(String projectId, String timelineId) =>
|
||||
_ref.read(previewTargetProvider(projectId, timelineId));
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
import '../workspace/project_state.dart';
|
||||
import 'application_command_dependencies.dart';
|
||||
|
||||
/// Application navigation adapter; project persistence and playback stay with owners.
|
||||
class ApplicationCommandHost implements EditorCommandHost {
|
||||
ApplicationCommandHost(this.dependencies, {required this.refresh});
|
||||
final ApplicationCommandDependencies dependencies;
|
||||
final Future<void> Function() refresh;
|
||||
@override
|
||||
Set<EditorOperation> get supportedOperations => applicationOperations;
|
||||
|
||||
@override
|
||||
Future<CommandResult> execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) async {
|
||||
final state = await dependencies.projectState();
|
||||
if (context.isCancelled()) {
|
||||
throw const CommandRejected('cancelled', 'Cancelled before execution');
|
||||
}
|
||||
if (!supportedOperations.contains(command.operation)) {
|
||||
throw const CommandRejected(
|
||||
'unsupported',
|
||||
'Choose a sequence workspace for editing',
|
||||
);
|
||||
}
|
||||
if (!applicationReadOperations.contains(command.operation) &&
|
||||
state.projectBusy) {
|
||||
throw const CommandRejected(
|
||||
'workspaceBusy',
|
||||
'Another workspace operation is running',
|
||||
);
|
||||
}
|
||||
void requireProject(String id) {
|
||||
if (state.activeProject?.id != id) {
|
||||
throw const CommandRejected(
|
||||
'missingProject',
|
||||
'Open the addressed project first',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void requireTimeline(String projectId, String timelineId) {
|
||||
requireProject(projectId);
|
||||
if (state.timeline?.id != timelineId) {
|
||||
throw const CommandRejected(
|
||||
'missingTimeline',
|
||||
'Open the addressed timeline first',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object?> projectData(RecentProject project) => {
|
||||
'projectId': project.id,
|
||||
'name': project.name,
|
||||
'path': project.path,
|
||||
};
|
||||
CommandResult result(Map<String, Object?> data) => CommandResult(
|
||||
status: CommandStatus.succeeded,
|
||||
message: 'Workspace state',
|
||||
data: data,
|
||||
);
|
||||
switch (command) {
|
||||
case QueryProjects():
|
||||
return result({
|
||||
'active': state.activeProject == null
|
||||
? null
|
||||
: projectData(state.activeProject!),
|
||||
'recent': state.recent.map(projectData).toList(),
|
||||
'busy': state.projectBusy,
|
||||
});
|
||||
case ListTimelines():
|
||||
requireProject(command.projectId);
|
||||
return result({
|
||||
'projectId': command.projectId,
|
||||
'activeTimelineId': state.timeline?.id,
|
||||
'timelines': [
|
||||
for (final timeline in state.timelines)
|
||||
{'timelineId': timeline.id, 'name': timeline.name},
|
||||
],
|
||||
'sequences': [
|
||||
for (final sequence in state.timeline?.sequences ?? [])
|
||||
{'sequenceId': sequence.id.value, 'name': sequence.name},
|
||||
],
|
||||
});
|
||||
case CreateProject():
|
||||
if (command.name.trim().isEmpty) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Use a nonempty project name',
|
||||
);
|
||||
}
|
||||
if (!await dependencies.createProject(command.name)) {
|
||||
final current = await dependencies.projectState();
|
||||
throw CommandRejected(
|
||||
'projectCreationFailed',
|
||||
current.error?.toString() ?? 'Project creation did not complete',
|
||||
);
|
||||
}
|
||||
await refresh();
|
||||
final current = await dependencies.projectState();
|
||||
return result({
|
||||
'project': projectData(current.activeProject!),
|
||||
'activeTimelineId': current.timeline?.id,
|
||||
});
|
||||
case OpenProject():
|
||||
if (!File(command.path).isAbsolute) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Use an absolute project path',
|
||||
);
|
||||
}
|
||||
final String canonicalPath;
|
||||
try {
|
||||
canonicalPath = await Directory(command.path).resolveSymbolicLinks();
|
||||
} on FileSystemException {
|
||||
throw const CommandRejected(
|
||||
'missingProject',
|
||||
'Project path is not readable',
|
||||
);
|
||||
}
|
||||
final known = [
|
||||
?state.activeProject,
|
||||
...state.recent,
|
||||
].where((project) => project.path == canonicalPath).firstOrNull;
|
||||
if (known != null &&
|
||||
command.projectId != null &&
|
||||
known.id != command.projectId) {
|
||||
throw CommandRejected(
|
||||
'projectIdMismatch',
|
||||
'This path belongs to project ${known.id}. Use project.query to read the current project.',
|
||||
);
|
||||
}
|
||||
final opened = await dependencies.openProject(
|
||||
command.path,
|
||||
expectedId: command.projectId,
|
||||
);
|
||||
if (!opened) throw StateError('Project open did not complete');
|
||||
await refresh();
|
||||
final current = await dependencies.projectState();
|
||||
return result({
|
||||
'project': projectData(current.activeProject!),
|
||||
'activeTimelineId': current.timeline?.id,
|
||||
});
|
||||
case CreateTimeline():
|
||||
requireProject(command.projectId);
|
||||
if (command.name.trim().isEmpty) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Timeline name is empty',
|
||||
);
|
||||
}
|
||||
final before = state.timelines.map((timeline) => timeline.id).toSet();
|
||||
if (!await dependencies.createTimeline(command.name)) {
|
||||
throw StateError('Timeline creation did not complete');
|
||||
}
|
||||
await refresh();
|
||||
final current = await dependencies.projectState();
|
||||
final created = current.timelines
|
||||
.where((timeline) => !before.contains(timeline.id))
|
||||
.single;
|
||||
return result({
|
||||
'projectId': command.projectId,
|
||||
'timelineId': created.id,
|
||||
'name': created.name,
|
||||
'activeTimelineId': current.timeline?.id,
|
||||
});
|
||||
case OpenTimeline():
|
||||
requireProject(command.projectId);
|
||||
if (!state.timelines.any(
|
||||
(timeline) => timeline.id == command.timelineId,
|
||||
)) {
|
||||
throw const CommandRejected(
|
||||
'missingTimeline',
|
||||
'Timeline does not exist',
|
||||
);
|
||||
}
|
||||
if (state.timeline?.id != command.timelineId &&
|
||||
!await dependencies.openTimeline(
|
||||
command.projectId,
|
||||
command.timelineId,
|
||||
)) {
|
||||
throw StateError('Timeline open did not complete');
|
||||
}
|
||||
await refresh();
|
||||
return result({
|
||||
'projectId': command.projectId,
|
||||
'timelineId': command.timelineId,
|
||||
'activeTimelineId': command.timelineId,
|
||||
'sequences': [
|
||||
for (final sequence
|
||||
in (await dependencies.projectState()).timeline!.sequences)
|
||||
{'sequenceId': sequence.id.value, 'name': sequence.name},
|
||||
],
|
||||
});
|
||||
case SelectSequence():
|
||||
requireTimeline(command.projectId, command.timelineId);
|
||||
if (!state.timeline!.sequences.any(
|
||||
(s) => s.id.value == command.sequenceId,
|
||||
)) {
|
||||
throw const CommandRejected(
|
||||
'missingSequence',
|
||||
'Sequence does not exist',
|
||||
);
|
||||
}
|
||||
final session = await dependencies.timeline(
|
||||
command.projectId,
|
||||
command.timelineId,
|
||||
);
|
||||
if (context.isCancelled()) {
|
||||
throw const CommandRejected(
|
||||
'cancelled',
|
||||
'Cancelled before selection',
|
||||
);
|
||||
}
|
||||
session.commands.ensureOpen(null);
|
||||
await dependencies
|
||||
.preview(command.projectId, command.timelineId)
|
||||
.closeSource();
|
||||
session.commands.ensureOpen(null);
|
||||
session.selectSequence(SequenceId(command.sequenceId));
|
||||
return result({'sequenceId': command.sequenceId});
|
||||
case SourcePreviewCommand():
|
||||
requireTimeline(command.projectId, command.timelineId);
|
||||
final target = dependencies.preview(
|
||||
command.projectId,
|
||||
command.timelineId,
|
||||
);
|
||||
switch (command.action) {
|
||||
case SourcePreviewAction.query:
|
||||
break;
|
||||
case SourcePreviewAction.open:
|
||||
final asset = state.assets
|
||||
.where((a) => a.id == command.mediaId)
|
||||
.firstOrNull;
|
||||
if (asset == null) {
|
||||
throw const CommandRejected(
|
||||
'missingMedia',
|
||||
'Media is not in the current project',
|
||||
);
|
||||
}
|
||||
await target.openSource(asset);
|
||||
case SourcePreviewAction.close:
|
||||
await target.closeSource();
|
||||
case SourcePreviewAction.play ||
|
||||
SourcePreviewAction.pause ||
|
||||
SourcePreviewAction.seek:
|
||||
if (command.mediaId == null) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Source media ID is required',
|
||||
);
|
||||
}
|
||||
await target.control(
|
||||
command.mediaId!,
|
||||
command.action,
|
||||
at: command.at,
|
||||
);
|
||||
}
|
||||
final source = target.source;
|
||||
return result({
|
||||
'mediaId': target.asset?.id,
|
||||
'available': source != null,
|
||||
'ready': source != null && !source.busy && source.error == null,
|
||||
'playing': source?.playing ?? false,
|
||||
'failed': source?.error != null,
|
||||
'position': CommandTime(
|
||||
source?.positionTick ?? 0,
|
||||
TimelineClock.ticksPerSecond,
|
||||
).toJson(),
|
||||
'duration': CommandTime(
|
||||
source?.durationTick ?? 0,
|
||||
TimelineClock.ticksPerSecond,
|
||||
).toJson(),
|
||||
});
|
||||
default:
|
||||
throw const CommandRejected(
|
||||
'unsupported',
|
||||
'Unsupported application operation',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/layout.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
import '../workspace/timeline_session.dart';
|
||||
|
||||
final _sessionTools = Expando<Map<SequenceId, EditorToolDispatcher>>();
|
||||
final _toolReferences = Expando<Map<EditorToolDispatcher, int>>();
|
||||
|
||||
/// Remove a dispatcher from its session cache before closing admission.
|
||||
Future<void> releaseEditorTools(
|
||||
EditorSession session,
|
||||
EditorToolDispatcher dispatcher,
|
||||
) async {
|
||||
final references = _toolReferences[session];
|
||||
final remaining = (references?[dispatcher] ?? 1) - 1;
|
||||
if (remaining > 0) {
|
||||
references![dispatcher] = remaining;
|
||||
return;
|
||||
}
|
||||
references?.remove(dispatcher);
|
||||
_sessionTools[session]?.removeWhere(
|
||||
(_, value) => identical(value, dispatcher),
|
||||
);
|
||||
await dispatcher.dispose();
|
||||
}
|
||||
|
||||
EditorToolDispatcher editorToolsFor(
|
||||
EditorSession session,
|
||||
SequenceId sequence,
|
||||
) {
|
||||
session.commands.ensureOpen(sequence);
|
||||
var tools = _sessionTools[session];
|
||||
if (tools == null) {
|
||||
final owned = <SequenceId, EditorToolDispatcher>{};
|
||||
_sessionTools[session] = tools = owned;
|
||||
session.onDispose(() {
|
||||
for (final dispatcher in owned.values) {
|
||||
unawaited(dispatcher.dispose());
|
||||
}
|
||||
});
|
||||
}
|
||||
final dispatcher = tools.putIfAbsent(
|
||||
sequence,
|
||||
() => EditorToolDispatcher(host: _EditorCommandHost(session, sequence)),
|
||||
);
|
||||
final references = _toolReferences[session] ??= {};
|
||||
references[dispatcher] = (references[dispatcher] ?? 0) + 1;
|
||||
return dispatcher;
|
||||
}
|
||||
|
||||
/// Maps SDK command outcomes to tools and adapts the app-owned UI selection.
|
||||
final class _EditorCommandHost extends EditorSessionCommandHost {
|
||||
const _EditorCommandHost(super.session, super.sequence);
|
||||
|
||||
@override
|
||||
Set<EditorOperation> get supportedOperations => {
|
||||
...session.supportedCommandOperations.where(
|
||||
(operation) => operation != EditorOperation.startVocalSeparation,
|
||||
),
|
||||
if (session is EditorTimelineSession) ...{
|
||||
EditorOperation.querySelection,
|
||||
EditorOperation.setSelection,
|
||||
},
|
||||
};
|
||||
|
||||
@override
|
||||
Future<CommandResult> execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) async {
|
||||
if (command is StartVocalSeparation) {
|
||||
throw const CommandRejected(
|
||||
'unsupported',
|
||||
'Vocal separation is temporarily unavailable',
|
||||
);
|
||||
}
|
||||
return _execute(command, context);
|
||||
}
|
||||
|
||||
Future<CommandResult> _execute(
|
||||
EditorCommand command,
|
||||
CommandContext context,
|
||||
) async {
|
||||
if (command is QuerySelection || command is SetSelection) {
|
||||
session.commands.ensureOpen(sequence);
|
||||
if (context.isCancelled()) {
|
||||
throw const CommandRejected('cancelled', 'Cancelled before execution');
|
||||
}
|
||||
if (!supportedOperations.contains(command.operation)) {
|
||||
throw const CommandRejected(
|
||||
'unsupported',
|
||||
'Operation is not available',
|
||||
);
|
||||
}
|
||||
if (command.expectedVersion != null &&
|
||||
command.expectedVersion != session.version) {
|
||||
throw const CommandRejected(
|
||||
'staleVersion',
|
||||
'Read the current state before editing',
|
||||
);
|
||||
}
|
||||
return _selection(command);
|
||||
}
|
||||
return super.execute(command, context);
|
||||
}
|
||||
|
||||
CommandResult _selection(EditorCommand command) {
|
||||
final ui = session as EditorTimelineSession;
|
||||
final view = ui.view(sequence);
|
||||
final query = view.version.kernelVersion.query();
|
||||
if (command is SetSelection) {
|
||||
if (view.isDragging) {
|
||||
throw const CommandRejected('busy', 'Finish the current gesture first');
|
||||
}
|
||||
if (command.clipIds.length > 1024 ||
|
||||
command.clipIds.toSet().length != command.clipIds.length) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Invalid clip selection',
|
||||
);
|
||||
}
|
||||
final handles = <ElementHandle>[];
|
||||
for (final id in command.clipIds) {
|
||||
final handle = query.elementById(ElementId(id));
|
||||
if (handle == null || query.ownerOf(handle) == null) {
|
||||
throw const CommandRejected(
|
||||
'missingClip',
|
||||
'Selected clip does not exist',
|
||||
);
|
||||
}
|
||||
handles.add(handle);
|
||||
}
|
||||
view.setSelection([
|
||||
for (final handle in handles)
|
||||
session.captionComponentFor(sequence, handle) ??
|
||||
(query.connectionForTarget(handle) == null
|
||||
? handle
|
||||
: LayoutBodyId.element(handle)),
|
||||
]);
|
||||
}
|
||||
final selected = <String>{};
|
||||
for (final identity in view.selectedIdentities) {
|
||||
final handle = switch (identity) {
|
||||
ElementHandle value => value,
|
||||
LayoutBodyId value => view.elementForIdentity(value),
|
||||
_ => null,
|
||||
};
|
||||
if (handle != null && query.ownerOf(handle) != null) {
|
||||
selected.add(query.element(handle).id.value);
|
||||
}
|
||||
}
|
||||
final keyframe = view.selectedKeyframe;
|
||||
return CommandResult(
|
||||
status: CommandStatus.succeeded,
|
||||
message: 'UI selection',
|
||||
version: session.version,
|
||||
data: {
|
||||
'sequenceId': sequence.value,
|
||||
'active': ui.activeSequenceId == sequence,
|
||||
'clipIds': selected.toList(),
|
||||
'keyframe': keyframe == null
|
||||
? null
|
||||
: {
|
||||
'clipId': query.element(keyframe.element).id.value,
|
||||
'offset': _time(keyframe.offset),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object?> _time(int ticks) {
|
||||
final value = TimelineClock.standard.fromTicks(ticks);
|
||||
return {'numerator': '${value.numerator}', 'denominator': value.denominator};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/mcp.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
import 'agent/editor_agent_tools.dart';
|
||||
import 'tool_workspace_registry.dart';
|
||||
|
||||
/// Immutable composition result exposing protocol projections of one registry.
|
||||
class EditorToolAccess {
|
||||
EditorToolAccess(EditorSession session) : this._(EditorToolRegistry(session));
|
||||
|
||||
EditorToolAccess.application(EditorCommandHost host)
|
||||
: this._(EditorToolRegistry.application(host));
|
||||
|
||||
EditorToolAccess._(this.registry);
|
||||
|
||||
final EditorToolRegistry registry;
|
||||
|
||||
Object get owner => registry.owner;
|
||||
Map<String, EditorToolDispatcher> get workspaces => registry.workspaces;
|
||||
|
||||
void attach(EditorSession? session, {String? projectId}) =>
|
||||
registry.attach(session, projectId: projectId);
|
||||
|
||||
Future<void> dispose() => registry.dispose();
|
||||
|
||||
late final List<AgentTool> agentTools = editorAgentTools(
|
||||
registry.workspaces,
|
||||
dynamicWorkspaces: registry.dynamicWorkspaces,
|
||||
);
|
||||
|
||||
late final server = CutdexMcpServer(
|
||||
resolveWorkspaces: registry.dynamicWorkspaces
|
||||
? () => [
|
||||
for (final entry in registry.workspaces.entries)
|
||||
McpWorkspace(id: entry.key, title: entry.key, tools: entry.value),
|
||||
]
|
||||
: null,
|
||||
workspaces: [
|
||||
for (final entry in registry.workspaces.entries)
|
||||
McpWorkspace(id: entry.key, title: entry.key, tools: entry.value),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../workspace/projects.dart';
|
||||
import '../workspace/timeline_provider.dart';
|
||||
import 'agent/editor_acceptance.dart';
|
||||
import 'agent/editor_agent_tools.dart';
|
||||
import 'application_command_dependencies.dart';
|
||||
import 'application_command_host.dart';
|
||||
import 'editor_command_host.dart';
|
||||
import 'editor_tool_access.dart';
|
||||
import 'mcp/mcp_endpoint_controller.dart';
|
||||
import 'mcp/mcp_settings.dart';
|
||||
|
||||
export 'mcp/mcp_endpoint_controller.dart' show EditorMcpEndpoint;
|
||||
export 'editor_tool_access.dart' show EditorToolAccess;
|
||||
|
||||
part 'editor_tools.g.dart';
|
||||
part 'editor_tools.freezed.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
EditorMcpEndpoint _editorMcpEndpoint(Ref ref) {
|
||||
final endpoint = EditorMcpEndpoint();
|
||||
ref.onDispose(() {
|
||||
unawaited(endpoint.close());
|
||||
});
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class EditorMcpConfiguration with _$EditorMcpConfiguration {
|
||||
const factory EditorMcpConfiguration({
|
||||
required int port,
|
||||
required String token,
|
||||
}) = _EditorMcpConfiguration;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
EditorMcpConfiguration editorMcpConfiguration(Ref ref) {
|
||||
final settings = ref.watch(mcpSettingsProvider).asData?.value;
|
||||
return EditorMcpConfiguration(
|
||||
port: settings?.enabled == true ? settings!.port : 0,
|
||||
token: settings?.token ?? '',
|
||||
);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
EditorToolAccess applicationToolAccess(Ref ref) {
|
||||
late final EditorToolAccess access;
|
||||
(String, String)? timelineIds;
|
||||
void Function()? releaseTimeline;
|
||||
Future<void> refresh() async {
|
||||
final current = await ref.read(projectsProvider.future);
|
||||
if (!ref.mounted) return;
|
||||
final projectId = current.activeProject?.id;
|
||||
final timelineId = current.timeline?.id;
|
||||
if (projectId == null || timelineId == null) {
|
||||
releaseTimeline?.call();
|
||||
releaseTimeline = null;
|
||||
timelineIds = null;
|
||||
access.attach(null);
|
||||
return;
|
||||
}
|
||||
final ids = (projectId, timelineId);
|
||||
final provider = editorTimelineProvider(ids.$1, ids.$2);
|
||||
if (timelineIds != ids) {
|
||||
releaseTimeline?.call();
|
||||
// Tools own an active timeline even when no editor widget is watching it.
|
||||
final subscription = ref.listen(provider, (_, _) {});
|
||||
releaseTimeline = subscription.close;
|
||||
timelineIds = ids;
|
||||
}
|
||||
var session = await ref.read(provider.future);
|
||||
if (!ref.mounted) return;
|
||||
if (!session.acceptsEdits) {
|
||||
ref.invalidate(provider);
|
||||
session = await ref.read(provider.future);
|
||||
}
|
||||
if (!ref.mounted) return;
|
||||
final latest = ref.read(projectsProvider).asData?.value;
|
||||
if (ref.mounted &&
|
||||
latest?.activeProject?.id == projectId &&
|
||||
latest?.timeline?.id == timelineId) {
|
||||
access.attach(session, projectId: projectId);
|
||||
}
|
||||
}
|
||||
|
||||
access = EditorToolAccess.application(
|
||||
ApplicationCommandHost(
|
||||
RiverpodApplicationCommandDependencies(ref),
|
||||
refresh: refresh,
|
||||
),
|
||||
);
|
||||
ref.listen(projectsProvider, (_, next) {
|
||||
if (next.asData?.value.projectBusy == false) {
|
||||
unawaited(refresh().catchError((Object _) {}));
|
||||
}
|
||||
});
|
||||
ref.onDispose(() {
|
||||
releaseTimeline?.call();
|
||||
unawaited(access.dispose());
|
||||
});
|
||||
unawaited(refresh().catchError((Object _) {}));
|
||||
return access;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
FutureOr<EditorToolAccess> editorToolAccess(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String timelineId,
|
||||
) async {
|
||||
final session = await ref.watch(
|
||||
editorTimelineProvider(projectId, timelineId).future,
|
||||
);
|
||||
final access = ref.watch(applicationToolAccessProvider);
|
||||
final current = ref.read(projectsProvider).asData?.value;
|
||||
if (current?.activeProject?.id == projectId &&
|
||||
current?.timeline?.id == timelineId &&
|
||||
session.acceptsEdits) {
|
||||
access.attach(session, projectId: projectId);
|
||||
}
|
||||
return access;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<void> applicationMcpConnection(Ref ref) async {
|
||||
final configuration = ref.watch(editorMcpConfigurationProvider);
|
||||
final endpoint = ref.watch(_editorMcpEndpointProvider);
|
||||
if (configuration.port == 0) {
|
||||
await endpoint.stop();
|
||||
return;
|
||||
}
|
||||
final access = ref.watch(applicationToolAccessProvider);
|
||||
var disposed = false;
|
||||
ref.onDispose(() {
|
||||
disposed = true;
|
||||
});
|
||||
final bridge = await endpoint.open(
|
||||
access.server,
|
||||
port: configuration.port,
|
||||
token: configuration.token,
|
||||
);
|
||||
if (disposed) {
|
||||
await endpoint.release(bridge);
|
||||
return;
|
||||
}
|
||||
ref.onDispose(() => unawaited(endpoint.release(bridge)));
|
||||
}
|
||||
|
||||
@riverpod
|
||||
FutureOr<void> editorMcpConnection(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String timelineId,
|
||||
) async {
|
||||
await ref.watch(editorToolAccessProvider(projectId, timelineId).future);
|
||||
await ref.watch(applicationMcpConnectionProvider.future);
|
||||
}
|
||||
|
||||
class EditorAgentBinding {
|
||||
const EditorAgentBinding({
|
||||
required this.owner,
|
||||
required this.tools,
|
||||
this.release,
|
||||
this.completionCheck,
|
||||
this.ensureTimeline,
|
||||
});
|
||||
final Object owner;
|
||||
final List<AgentTool> tools;
|
||||
final Future<void> Function()? release;
|
||||
final CompletionCheck? completionCheck;
|
||||
final Future<void> Function(String timelineId)? ensureTimeline;
|
||||
}
|
||||
|
||||
/// Leases explicit run targets; opening another timeline adds that target.
|
||||
Future<EditorAgentBinding> createEditorAgentBinding(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String timelineId,
|
||||
) async {
|
||||
await ref.read(editorTimelineProvider(projectId, timelineId).future);
|
||||
final lease = await ref
|
||||
.read(projectsProvider.notifier)
|
||||
.leaseTimeline(projectId, timelineId);
|
||||
final leases = {timelineId: lease};
|
||||
try {
|
||||
final session = lease.session;
|
||||
final dispatchers = <String, EditorToolDispatcher>{};
|
||||
final application = ref.read(applicationToolAccessProvider);
|
||||
if (application.workspaces['application'] case final dispatcher?) {
|
||||
dispatchers['application'] = dispatcher;
|
||||
}
|
||||
for (final sequence in session.document.sequences) {
|
||||
dispatchers['sequence:${sequence.id.value}'] = editorToolsFor(
|
||||
session,
|
||||
sequence.id,
|
||||
);
|
||||
}
|
||||
Future<void> ensureTimeline(String target) async {
|
||||
if (leases.containsKey(target)) return;
|
||||
final added = await ref
|
||||
.read(projectsProvider.notifier)
|
||||
.leaseTimeline(projectId, target);
|
||||
leases[target] = added;
|
||||
for (final sequence in added.session.document.sequences) {
|
||||
dispatchers['sequence:${sequence.id.value}'] = editorToolsFor(
|
||||
added.session,
|
||||
sequence.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final tools = editorAgentTools(
|
||||
dispatchers,
|
||||
dynamicWorkspaces: true,
|
||||
afterInvoke: (call, context, result) async {
|
||||
if (!{
|
||||
'timeline_create',
|
||||
'timeline_open',
|
||||
'sequence_select',
|
||||
}.contains(call.name)) {
|
||||
return;
|
||||
}
|
||||
if (call.arguments['projectId'] != projectId) return;
|
||||
final target = call.name == 'timeline_create'
|
||||
? result.data['timelineId']
|
||||
: call.arguments['timelineId'];
|
||||
if (target is! String) return;
|
||||
await ensureTimeline(target);
|
||||
},
|
||||
beforeInvoke: (context) async {
|
||||
try {
|
||||
for (final owned in leases.values) {
|
||||
await owned.validate();
|
||||
}
|
||||
} catch (_) {
|
||||
context.cancellation.cancel();
|
||||
rethrow;
|
||||
}
|
||||
},
|
||||
);
|
||||
final acceptance = EditorAcceptance(tools);
|
||||
return EditorAgentBinding(
|
||||
owner: session,
|
||||
tools: [...tools, ...acceptance.tools],
|
||||
completionCheck: acceptance.check,
|
||||
ensureTimeline: ensureTimeline,
|
||||
release: () async {
|
||||
try {
|
||||
for (final owned in leases.values) {
|
||||
for (final sequence in owned.session.document.sequences) {
|
||||
final dispatcher = dispatchers['sequence:${sequence.id.value}'];
|
||||
if (dispatcher != null) {
|
||||
await releaseEditorTools(owned.session, dispatcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
for (final owned in leases.values) {
|
||||
await owned.release();
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
} catch (_) {
|
||||
await lease.release();
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(name: 'editorAgentToolsProvider')
|
||||
FutureOr<EditorAgentBinding> editorAgentToolsBinding(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String timelineId,
|
||||
) async {
|
||||
final access = await ref.watch(
|
||||
editorToolAccessProvider(projectId, timelineId).future,
|
||||
);
|
||||
return EditorAgentBinding(owner: access.owner, tools: access.agentTools);
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'editor_tools.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$EditorMcpConfiguration {
|
||||
int get port;
|
||||
String get token;
|
||||
|
||||
/// Create a copy of EditorMcpConfiguration
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$EditorMcpConfigurationCopyWith<EditorMcpConfiguration> get copyWith =>
|
||||
_$EditorMcpConfigurationCopyWithImpl<EditorMcpConfiguration>(
|
||||
this as EditorMcpConfiguration,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as EditorMcpConfiguration;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is EditorMcpConfiguration &&
|
||||
(identical(other.port, _this.port) || other.port == _this.port) &&
|
||||
(identical(other.token, _this.token) ||
|
||||
other.token == _this.token));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as EditorMcpConfiguration;
|
||||
return Object.hash(runtimeType, _this.port, _this.token);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as EditorMcpConfiguration;
|
||||
return 'EditorMcpConfiguration(port: ${_this.port}, token: ${_this.token})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $EditorMcpConfigurationCopyWith<$Res> {
|
||||
factory $EditorMcpConfigurationCopyWith(
|
||||
EditorMcpConfiguration value,
|
||||
$Res Function(EditorMcpConfiguration) _then,
|
||||
) = _$EditorMcpConfigurationCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({int port, String token});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$EditorMcpConfigurationCopyWithImpl<$Res>
|
||||
implements $EditorMcpConfigurationCopyWith<$Res> {
|
||||
_$EditorMcpConfigurationCopyWithImpl(this._self, this._then);
|
||||
|
||||
final EditorMcpConfiguration _self;
|
||||
final $Res Function(EditorMcpConfiguration) _then;
|
||||
|
||||
/// Create a copy of EditorMcpConfiguration
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? port = null, Object? token = null}) {
|
||||
return _then(
|
||||
EditorMcpConfiguration(
|
||||
port: null == port
|
||||
? _self.port
|
||||
: port // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
token: null == token
|
||||
? _self.token
|
||||
: token // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [EditorMcpConfiguration].
|
||||
extension EditorMcpConfigurationPatterns on EditorMcpConfiguration {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_EditorMcpConfiguration value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_EditorMcpConfiguration value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_EditorMcpConfiguration value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(int port, String token)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration() when $default != null:
|
||||
return $default(_that.port, _that.token);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(int port, String token) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration():
|
||||
return $default(_that.port, _that.token);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(int port, String token)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _EditorMcpConfiguration() when $default != null:
|
||||
return $default(_that.port, _that.token);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _EditorMcpConfiguration implements EditorMcpConfiguration {
|
||||
const _EditorMcpConfiguration({required this.port, required this.token});
|
||||
|
||||
@override
|
||||
final int port;
|
||||
@override
|
||||
final String token;
|
||||
|
||||
/// Create a copy of EditorMcpConfiguration
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$EditorMcpConfigurationCopyWith<_EditorMcpConfiguration> get copyWith =>
|
||||
__$EditorMcpConfigurationCopyWithImpl<_EditorMcpConfiguration>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _EditorMcpConfiguration &&
|
||||
(identical(other.port, port) || other.port == port) &&
|
||||
(identical(other.token, token) || other.token == token));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, port, token);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'EditorMcpConfiguration(port: $port, token: $token)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$EditorMcpConfigurationCopyWith<$Res>
|
||||
implements $EditorMcpConfigurationCopyWith<$Res> {
|
||||
factory _$EditorMcpConfigurationCopyWith(
|
||||
_EditorMcpConfiguration value,
|
||||
$Res Function(_EditorMcpConfiguration) _then,
|
||||
) = __$EditorMcpConfigurationCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({int port, String token});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$EditorMcpConfigurationCopyWithImpl<$Res>
|
||||
implements _$EditorMcpConfigurationCopyWith<$Res> {
|
||||
__$EditorMcpConfigurationCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _EditorMcpConfiguration _self;
|
||||
final $Res Function(_EditorMcpConfiguration) _then;
|
||||
|
||||
/// Create a copy of EditorMcpConfiguration
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? port = null, Object? token = null}) {
|
||||
return _then(
|
||||
_EditorMcpConfiguration(
|
||||
port: null == port
|
||||
? _self.port
|
||||
: port // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
token: null == token
|
||||
? _self.token
|
||||
: token // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'editor_tools.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(_editorMcpEndpoint)
|
||||
final _editorMcpEndpointProvider = _EditorMcpEndpointProvider._();
|
||||
|
||||
final class _EditorMcpEndpointProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
EditorMcpEndpoint,
|
||||
EditorMcpEndpoint,
|
||||
EditorMcpEndpoint
|
||||
>
|
||||
with $Provider<EditorMcpEndpoint> {
|
||||
_EditorMcpEndpointProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'_editorMcpEndpointProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$_editorMcpEndpointHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<EditorMcpEndpoint> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
EditorMcpEndpoint create(Ref ref) {
|
||||
return _editorMcpEndpoint(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(EditorMcpEndpoint value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<EditorMcpEndpoint>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$_editorMcpEndpointHash() =>
|
||||
r'cc4a1bf7bdbbbf2e4762f5c4068e8f305ac569d5';
|
||||
|
||||
@ProviderFor(editorMcpConfiguration)
|
||||
final editorMcpConfigurationProvider = EditorMcpConfigurationProvider._();
|
||||
|
||||
final class EditorMcpConfigurationProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
EditorMcpConfiguration,
|
||||
EditorMcpConfiguration,
|
||||
EditorMcpConfiguration
|
||||
>
|
||||
with $Provider<EditorMcpConfiguration> {
|
||||
EditorMcpConfigurationProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'editorMcpConfigurationProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$editorMcpConfigurationHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<EditorMcpConfiguration> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
EditorMcpConfiguration create(Ref ref) {
|
||||
return editorMcpConfiguration(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(EditorMcpConfiguration value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<EditorMcpConfiguration>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$editorMcpConfigurationHash() =>
|
||||
r'0ccb0b48d75534620d5e4abe40008c94b1007341';
|
||||
|
||||
@ProviderFor(applicationToolAccess)
|
||||
final applicationToolAccessProvider = ApplicationToolAccessProvider._();
|
||||
|
||||
final class ApplicationToolAccessProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
EditorToolAccess,
|
||||
EditorToolAccess,
|
||||
EditorToolAccess
|
||||
>
|
||||
with $Provider<EditorToolAccess> {
|
||||
ApplicationToolAccessProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'applicationToolAccessProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$applicationToolAccessHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<EditorToolAccess> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
EditorToolAccess create(Ref ref) {
|
||||
return applicationToolAccess(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(EditorToolAccess value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<EditorToolAccess>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$applicationToolAccessHash() =>
|
||||
r'93564d9cdcbdc3247fef6c9f5fd24dd833f8aca5';
|
||||
|
||||
@ProviderFor(editorToolAccess)
|
||||
final editorToolAccessProvider = EditorToolAccessFamily._();
|
||||
|
||||
final class EditorToolAccessProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<EditorToolAccess>,
|
||||
EditorToolAccess,
|
||||
FutureOr<EditorToolAccess>
|
||||
>
|
||||
with $FutureModifier<EditorToolAccess>, $FutureProvider<EditorToolAccess> {
|
||||
EditorToolAccessProvider._({
|
||||
required EditorToolAccessFamily super.from,
|
||||
required (String, String) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'editorToolAccessProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$editorToolAccessHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'editorToolAccessProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<EditorToolAccess> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<EditorToolAccess> create(Ref ref) {
|
||||
final argument = this.argument as (String, String);
|
||||
return editorToolAccess(ref, argument.$1, argument.$2);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is EditorToolAccessProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$editorToolAccessHash() => r'af03c156e8533b9f2535235df32cb086eceb86be';
|
||||
|
||||
final class EditorToolAccessFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
FutureOr<EditorToolAccess>,
|
||||
(String, String)
|
||||
> {
|
||||
EditorToolAccessFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'editorToolAccessProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
EditorToolAccessProvider call(String projectId, String timelineId) =>
|
||||
EditorToolAccessProvider._(argument: (projectId, timelineId), from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'editorToolAccessProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(applicationMcpConnection)
|
||||
final applicationMcpConnectionProvider = ApplicationMcpConnectionProvider._();
|
||||
|
||||
final class ApplicationMcpConnectionProvider
|
||||
extends $FunctionalProvider<AsyncValue<void>, void, FutureOr<void>>
|
||||
with $FutureModifier<void>, $FutureProvider<void> {
|
||||
ApplicationMcpConnectionProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'applicationMcpConnectionProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$applicationMcpConnectionHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<void> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<void> create(Ref ref) {
|
||||
return applicationMcpConnection(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$applicationMcpConnectionHash() =>
|
||||
r'1ee22c117137a4f6264e3e17404c554855594ed7';
|
||||
|
||||
@ProviderFor(editorMcpConnection)
|
||||
final editorMcpConnectionProvider = EditorMcpConnectionFamily._();
|
||||
|
||||
final class EditorMcpConnectionProvider
|
||||
extends $FunctionalProvider<AsyncValue<void>, void, FutureOr<void>>
|
||||
with $FutureModifier<void>, $FutureProvider<void> {
|
||||
EditorMcpConnectionProvider._({
|
||||
required EditorMcpConnectionFamily super.from,
|
||||
required (String, String) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'editorMcpConnectionProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$editorMcpConnectionHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'editorMcpConnectionProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<void> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<void> create(Ref ref) {
|
||||
final argument = this.argument as (String, String);
|
||||
return editorMcpConnection(ref, argument.$1, argument.$2);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is EditorMcpConnectionProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$editorMcpConnectionHash() =>
|
||||
r'990ea2ef5c40b8a2230af24f39cfb6a3a30ca09d';
|
||||
|
||||
final class EditorMcpConnectionFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<void>, (String, String)> {
|
||||
EditorMcpConnectionFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'editorMcpConnectionProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
EditorMcpConnectionProvider call(String projectId, String timelineId) =>
|
||||
EditorMcpConnectionProvider._(
|
||||
argument: (projectId, timelineId),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'editorMcpConnectionProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(editorAgentToolsBinding)
|
||||
final editorAgentToolsProvider = EditorAgentToolsBindingFamily._();
|
||||
|
||||
final class EditorAgentToolsBindingProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<EditorAgentBinding>,
|
||||
EditorAgentBinding,
|
||||
FutureOr<EditorAgentBinding>
|
||||
>
|
||||
with
|
||||
$FutureModifier<EditorAgentBinding>,
|
||||
$FutureProvider<EditorAgentBinding> {
|
||||
EditorAgentToolsBindingProvider._({
|
||||
required EditorAgentToolsBindingFamily super.from,
|
||||
required (String, String) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'editorAgentToolsProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$editorAgentToolsBindingHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'editorAgentToolsProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<EditorAgentBinding> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<EditorAgentBinding> create(Ref ref) {
|
||||
final argument = this.argument as (String, String);
|
||||
return editorAgentToolsBinding(ref, argument.$1, argument.$2);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is EditorAgentToolsBindingProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$editorAgentToolsBindingHash() =>
|
||||
r'c38d5aeae513a8cfa744e03b6cba34a000cd6db6';
|
||||
|
||||
final class EditorAgentToolsBindingFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
FutureOr<EditorAgentBinding>,
|
||||
(String, String)
|
||||
> {
|
||||
EditorAgentToolsBindingFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'editorAgentToolsProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
EditorAgentToolsBindingProvider call(String projectId, String timelineId) =>
|
||||
EditorAgentToolsBindingProvider._(
|
||||
argument: (projectId, timelineId),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'editorAgentToolsProvider';
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/mcp.dart';
|
||||
|
||||
/// Private loopback transport for the stdio launcher. This is not an MCP HTTP
|
||||
/// endpoint. The first line authenticates; remaining bytes are MCP stdio frames.
|
||||
class LocalMcpBridge {
|
||||
LocalMcpBridge._(this._listener, this._server, this._token) {
|
||||
_listener.listen(_accept);
|
||||
}
|
||||
final ServerSocket _listener;
|
||||
final CutdexMcpServer _server;
|
||||
final String _token;
|
||||
final _sockets = <Socket>{};
|
||||
final _sessions = <Future<void>>{};
|
||||
bool _closed = false;
|
||||
int get port => _listener.port;
|
||||
|
||||
static Future<LocalMcpBridge> start(
|
||||
CutdexMcpServer server, {
|
||||
required int port,
|
||||
required String token,
|
||||
}) async {
|
||||
if (port < 0 ||
|
||||
port > 65535 ||
|
||||
token.length < 32 ||
|
||||
token.length > 1024 ||
|
||||
token.contains('\n') ||
|
||||
token.contains('\r')) {
|
||||
throw ArgumentError(
|
||||
'MCP requires a valid port and a 32-1024 character token',
|
||||
);
|
||||
}
|
||||
final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, port);
|
||||
return LocalMcpBridge._(socket, server, token);
|
||||
}
|
||||
|
||||
void _accept(Socket socket) {
|
||||
if (_closed || _sockets.length >= 32) {
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
_sockets.add(socket);
|
||||
final task = _serve(socket);
|
||||
_sessions.add(task);
|
||||
unawaited(
|
||||
task.whenComplete(() {
|
||||
_sessions.remove(task);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _serve(Socket socket) async {
|
||||
final input = StreamIterator<List<int>>(socket);
|
||||
try {
|
||||
final bytes = <int>[];
|
||||
final deadline = DateTime.now().add(const Duration(seconds: 5));
|
||||
while (await input.moveNext().timeout(
|
||||
deadline.difference(DateTime.now()),
|
||||
)) {
|
||||
final chunk = input.current;
|
||||
final newline = chunk.indexOf(10);
|
||||
final count = newline < 0 ? chunk.length : newline;
|
||||
if (bytes.length + count > 4096) return;
|
||||
bytes.addAll(chunk.take(count));
|
||||
if (newline < 0) continue;
|
||||
if (utf8.decode(bytes) != _token) return;
|
||||
Stream<List<int>> frames() async* {
|
||||
if (newline + 1 < chunk.length) yield chunk.sublist(newline + 1);
|
||||
while (await input.moveNext()) {
|
||||
yield input.current;
|
||||
}
|
||||
}
|
||||
|
||||
await serveMcpStdio(_server, input: frames(), output: socket);
|
||||
return;
|
||||
}
|
||||
} catch (_) {
|
||||
// Transport failures end this connection, not the project or other clients.
|
||||
} finally {
|
||||
socket.destroy();
|
||||
await input.cancel();
|
||||
_sockets.remove(socket);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> close() async {
|
||||
if (_closed) return;
|
||||
_closed = true;
|
||||
await _listener.close();
|
||||
for (final socket in _sockets.toList()) {
|
||||
socket.destroy();
|
||||
}
|
||||
await Future.wait(_sessions.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_sdk/mcp.dart';
|
||||
|
||||
import 'local_mcp_bridge.dart';
|
||||
|
||||
/// Serializes endpoint replacement so late cleanup cannot close its successor.
|
||||
class EditorMcpEndpoint {
|
||||
Future<void> _tail = Future.value();
|
||||
LocalMcpBridge? _current;
|
||||
bool _closed = false;
|
||||
|
||||
Future<T> _run<T>(Future<T> Function() action) {
|
||||
final result = _tail.then((_) => action());
|
||||
_tail = result.then<void>((_) {}, onError: (Object _, StackTrace _) {});
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<LocalMcpBridge> open(
|
||||
CutdexMcpServer server, {
|
||||
required int port,
|
||||
required String token,
|
||||
}) => _run(() async {
|
||||
if (_closed) throw StateError('MCP endpoint owner is closed');
|
||||
await _current?.close();
|
||||
_current = null;
|
||||
return _current = await LocalMcpBridge.start(
|
||||
server,
|
||||
port: port,
|
||||
token: token,
|
||||
);
|
||||
});
|
||||
|
||||
Future<void> release(LocalMcpBridge bridge) => _run(() async {
|
||||
if (!identical(_current, bridge)) return;
|
||||
await bridge.close();
|
||||
_current = null;
|
||||
});
|
||||
|
||||
Future<void> close() {
|
||||
_closed = true;
|
||||
return _run(() async {
|
||||
await _current?.close();
|
||||
_current = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> stop() => _run(() async {
|
||||
await _current?.close();
|
||||
_current = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../persistence/settings/mcp_settings_repository.dart';
|
||||
import '../../settings/mcp_settings_value.dart';
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
|
||||
export '../../settings/mcp_settings_value.dart';
|
||||
|
||||
part 'mcp_settings.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class McpSettings extends _$McpSettings {
|
||||
late McpSettingsRepository _repository;
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
Future<McpSettingsValue> build() async {
|
||||
_repository = ref.watch(mcpSettingsRepositoryProvider);
|
||||
final saved = await _repository.load();
|
||||
if (saved != null) {
|
||||
_validate(saved);
|
||||
return saved;
|
||||
}
|
||||
final random = Random.secure();
|
||||
final value = McpSettingsValue(
|
||||
enabled: false,
|
||||
port: 47831,
|
||||
token: base64UrlEncode(List.generate(32, (_) => random.nextInt(256))),
|
||||
);
|
||||
await _persist(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
Future<void> saveSettings({bool? enabled, int? port}) {
|
||||
return _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
final current = await future;
|
||||
if (!ref.mounted) return;
|
||||
final next = current.copyWith(
|
||||
enabled: enabled ?? current.enabled,
|
||||
port: port ?? current.port,
|
||||
);
|
||||
_validate(next);
|
||||
await _persist(next);
|
||||
if (ref.mounted) state = AsyncData(next);
|
||||
});
|
||||
}
|
||||
|
||||
void _validate(McpSettingsValue value) {
|
||||
if (value.port < 1 ||
|
||||
value.port > 65535 ||
|
||||
value.token.length < 32 ||
|
||||
value.token.length > 1024 ||
|
||||
value.token.contains('\r') ||
|
||||
value.token.contains('\n')) {
|
||||
throw ArgumentError('Invalid MCP configuration');
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _persist(McpSettingsValue value) => _repository.save(value);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'mcp_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(McpSettings)
|
||||
final mcpSettingsProvider = McpSettingsProvider._();
|
||||
|
||||
final class McpSettingsProvider
|
||||
extends $AsyncNotifierProvider<McpSettings, McpSettingsValue> {
|
||||
McpSettingsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'mcpSettingsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mcpSettingsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
McpSettings create() => McpSettings();
|
||||
}
|
||||
|
||||
String _$mcpSettingsHash() => r'122c5ad73d0eec5808c546eb66dde6c4b0f29a8a';
|
||||
|
||||
abstract class _$McpSettings extends $AsyncNotifier<McpSettingsValue> {
|
||||
FutureOr<McpSettingsValue> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<McpSettingsValue>, McpSettingsValue>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<McpSettingsValue>, McpSettingsValue>,
|
||||
AsyncValue<McpSettingsValue>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
/// A host/device experience, independent of window size and connected inputs.
|
||||
enum DeviceExperience { desktop, tablet, phone }
|
||||
|
||||
final deviceExperienceProvider = Provider<DeviceExperience>((ref) {
|
||||
final display = ui.PlatformDispatcher.instance.views.firstOrNull?.display;
|
||||
return DeviceExperienceDetector.fallback(
|
||||
platform: defaultTargetPlatform,
|
||||
displaySize: display?.size ?? ui.Size.zero,
|
||||
pixelRatio: display?.devicePixelRatio ?? 1,
|
||||
);
|
||||
});
|
||||
|
||||
/// Resolves once at startup; resizing, rotation and keyboard events do not run it.
|
||||
abstract final class DeviceExperienceDetector {
|
||||
static DeviceExperience fallback({
|
||||
required TargetPlatform platform,
|
||||
required ui.Size displaySize,
|
||||
required double pixelRatio,
|
||||
}) {
|
||||
if (platform != TargetPlatform.android && platform != TargetPlatform.iOS) {
|
||||
return DeviceExperience.desktop;
|
||||
}
|
||||
// This is the full display, never MediaQuery's application window.
|
||||
return pixelRatio > 0 && displaySize.shortestSide / pixelRatio >= 600
|
||||
? DeviceExperience.tablet
|
||||
: DeviceExperience.phone;
|
||||
}
|
||||
|
||||
static Future<DeviceExperience> detect({
|
||||
required TargetPlatform platform,
|
||||
required ui.Size displaySize,
|
||||
required double pixelRatio,
|
||||
bool web = false,
|
||||
}) async {
|
||||
final defaultExperience = fallback(
|
||||
platform: platform,
|
||||
displaySize: displaySize,
|
||||
pixelRatio: pixelRatio,
|
||||
);
|
||||
if (web ||
|
||||
(platform != TargetPlatform.android &&
|
||||
platform != TargetPlatform.iOS)) {
|
||||
return defaultExperience;
|
||||
}
|
||||
final info = await NativeDeviceInfo.read();
|
||||
if (platform == TargetPlatform.iOS) {
|
||||
return switch (info?.interfaceIdiom) {
|
||||
NativeInterfaceIdiom.pad => DeviceExperience.tablet,
|
||||
NativeInterfaceIdiom.mac => DeviceExperience.desktop,
|
||||
NativeInterfaceIdiom.phone => DeviceExperience.phone,
|
||||
null => defaultExperience,
|
||||
};
|
||||
}
|
||||
final shortestSide = info?.displayShortestSideDp;
|
||||
return shortestSide == null
|
||||
? defaultExperience
|
||||
: shortestSide >= 600
|
||||
? DeviceExperience.tablet
|
||||
: DeviceExperience.phone;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'window_caption_controls.dart';
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
/// Shared native titlebar layout; a close callback opts into editor navigation.
|
||||
class EditorWindowChrome extends StatefulWidget {
|
||||
const EditorWindowChrome({
|
||||
super.key,
|
||||
required this.headerHeight,
|
||||
this.onCloseRequested,
|
||||
required this.builder,
|
||||
});
|
||||
|
||||
static const trafficLightWidth = 88.0;
|
||||
static bool get isWindows => WindowChromeSession.isWindows;
|
||||
static double get leadingWidth => isWindows ? 0 : trafficLightWidth;
|
||||
final double headerHeight;
|
||||
final VoidCallback? onCloseRequested;
|
||||
final Widget Function(BuildContext context, bool integrated) builder;
|
||||
|
||||
@override
|
||||
State<EditorWindowChrome> createState() => _EditorWindowChromeState();
|
||||
}
|
||||
|
||||
class _EditorWindowChromeState extends State<EditorWindowChrome> {
|
||||
late final _session = WindowChromeSession(
|
||||
headerHeight: widget.headerHeight,
|
||||
onCloseRequested: widget.onCloseRequested,
|
||||
);
|
||||
bool _integrated = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_session.addListener(_integrationChanged);
|
||||
_session.attach();
|
||||
}
|
||||
|
||||
void _integrationChanged() {
|
||||
if (_integrated != _session.integrated) {
|
||||
setState(() => _integrated = _session.integrated);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_session.setInteractive(ModalRoute.of(context)?.isCurrent ?? true);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant EditorWindowChrome oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_session.configure(
|
||||
headerHeight: widget.headerHeight,
|
||||
onCloseRequested: widget.onCloseRequested,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (!_integrated || !EditorWindowChrome.isWindows) {
|
||||
return widget.builder(context, _integrated);
|
||||
}
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) => WindowHeaderLayout(
|
||||
captionBounds: Rect.fromLTWH(
|
||||
constraints.maxWidth - WindowCaptionControls.width,
|
||||
0,
|
||||
WindowCaptionControls.width,
|
||||
widget.headerHeight,
|
||||
),
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Builder(builder: (context) => widget.builder(context, true)),
|
||||
Positioned(
|
||||
top: 0,
|
||||
right: 0,
|
||||
width: WindowCaptionControls.width,
|
||||
height: widget.headerHeight,
|
||||
child: WindowCaptionControls(
|
||||
session: _session,
|
||||
height: widget.headerHeight,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'package:filegate/filegate.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/media_import.dart';
|
||||
|
||||
part 'file_picker.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AppFilePicker filePicker(Ref ref) => const AppFilePicker();
|
||||
|
||||
class AppFilePicker {
|
||||
const AppFilePicker();
|
||||
|
||||
Future<String?> pickDirectory({
|
||||
String? initialDirectory,
|
||||
String? confirmButtonText,
|
||||
}) async {
|
||||
final entry = await const Filegate().pickDirectory(
|
||||
initialDirectory: initialDirectory,
|
||||
confirmButtonText: confirmButtonText,
|
||||
);
|
||||
return entry == null ? null : _localPath(entry);
|
||||
}
|
||||
|
||||
Future<List<ExternalMediaFile>> pickFiles({
|
||||
required List<String> allowedExtensions,
|
||||
}) async {
|
||||
final entries = await const Filegate().pickFiles(
|
||||
allowMultiple: true,
|
||||
allowedExtensions: allowedExtensions,
|
||||
persistAccess: false,
|
||||
);
|
||||
return [
|
||||
for (final entry in entries ?? <PickedEntry>[])
|
||||
if (entry.isContentUri)
|
||||
ExternalMediaFile.content(
|
||||
uri: entry.uri!,
|
||||
name: entry.name,
|
||||
byteLength: entry.size,
|
||||
)
|
||||
else
|
||||
ExternalMediaFile(path: _localPath(entry)),
|
||||
];
|
||||
}
|
||||
|
||||
String _localPath(PickedEntry entry) {
|
||||
final path = entry.fileSystemPath;
|
||||
if (path == null) {
|
||||
throw PlatformException(
|
||||
code: 'unsupported_location',
|
||||
message: 'Cutdex requires a local file system path.',
|
||||
details: entry.path,
|
||||
);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'file_picker.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(filePicker)
|
||||
final filePickerProvider = FilePickerProvider._();
|
||||
|
||||
final class FilePickerProvider
|
||||
extends $FunctionalProvider<AppFilePicker, AppFilePicker, AppFilePicker>
|
||||
with $Provider<AppFilePicker> {
|
||||
FilePickerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'filePickerProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$filePickerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AppFilePicker> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AppFilePicker create(Ref ref) {
|
||||
return filePicker(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AppFilePicker value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AppFilePicker>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$filePickerHash() => r'8f869df0d25e7b43e434586c35e8e6aed225245d';
|
||||
@@ -0,0 +1,15 @@
|
||||
import 'package:filegate/filegate.dart';
|
||||
|
||||
/// Streams provider documents without exposing filegate to workspace logic.
|
||||
class MediaSourceReader {
|
||||
const MediaSourceReader();
|
||||
|
||||
Stream<List<int>> openRead(Uri uri) async* {
|
||||
final session = const Filegate().openRead(uri.toString());
|
||||
try {
|
||||
yield* session.stream;
|
||||
} finally {
|
||||
await session.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
import '../../workspace/media_file_extensions.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
|
||||
/// File acceptance shared by Flutter and the native drop destinations.
|
||||
enum NativeFileDropPolicy {
|
||||
mediaLibrary,
|
||||
timeline,
|
||||
attachments;
|
||||
|
||||
List<String>? get allowedExtensions => switch (this) {
|
||||
timeline => selectableTimelineFileExtensions,
|
||||
// Library imports validate each file so mixed batches retain valid media.
|
||||
mediaLibrary || attachments => null,
|
||||
};
|
||||
|
||||
int? get maximumFileCount => this == timeline ? 1 : null;
|
||||
|
||||
bool accepts(List<ExternalMediaFile> files) =>
|
||||
files.every((file) => file.localPath != null) &&
|
||||
configuration.accepts([for (final file in files) file.localPath!]);
|
||||
|
||||
NativeDropConfiguration get configuration => NativeDropConfiguration(
|
||||
allowedExtensions: allowedExtensions,
|
||||
maximumFileCount: maximumFileCount,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../workspace/media_import.dart';
|
||||
import 'native_file_drop_policy.dart';
|
||||
|
||||
/// Applies application media rules to a generic native file destination.
|
||||
class NativeProjectDropRegion extends StatelessWidget {
|
||||
const NativeProjectDropRegion({
|
||||
super.key,
|
||||
this.regionId = 'media-library',
|
||||
this.policy = NativeFileDropPolicy.mediaLibrary,
|
||||
required this.enabled,
|
||||
required this.onEnter,
|
||||
required this.onExit,
|
||||
required this.onDrop,
|
||||
required this.child,
|
||||
});
|
||||
final String regionId;
|
||||
final NativeFileDropPolicy policy;
|
||||
final bool enabled;
|
||||
final ValueChanged<List<ExternalMediaFile>> onEnter;
|
||||
final VoidCallback onExit;
|
||||
final Future<void> Function(List<ExternalMediaFile>) onDrop;
|
||||
final Widget child;
|
||||
|
||||
List<ExternalMediaFile> _files(List<String> paths) => [
|
||||
for (final path in paths) ExternalMediaFile(path: path),
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => NativeFileDropRegion(
|
||||
regionId: regionId,
|
||||
configuration: policy.configuration,
|
||||
enabled: enabled,
|
||||
onEnter: (paths) => onEnter(_files(paths)),
|
||||
onExit: onExit,
|
||||
onDrop: (paths) => onDrop(_files(paths)),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
final platformCapabilitiesProvider = Provider<PlatformCapabilities>(
|
||||
(ref) => PlatformCapabilities(
|
||||
localFileSelection: !kIsWeb,
|
||||
nativeFileDrop:
|
||||
!kIsWeb &&
|
||||
(defaultTargetPlatform == TargetPlatform.macOS ||
|
||||
defaultTargetPlatform == TargetPlatform.windows),
|
||||
),
|
||||
);
|
||||
|
||||
/// Describes supported integration paths, never a workspace size class.
|
||||
final class PlatformCapabilities {
|
||||
const PlatformCapabilities({
|
||||
required this.localFileSelection,
|
||||
required this.nativeFileDrop,
|
||||
});
|
||||
final bool localFileSelection;
|
||||
final bool nativeFileDrop;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
/// Windows caption buttons; native window state only rebuilds this strip.
|
||||
class WindowCaptionControls extends StatelessWidget {
|
||||
const WindowCaptionControls({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.height,
|
||||
});
|
||||
static const buttonWidth = 46.0;
|
||||
static const width = buttonWidth * 3;
|
||||
final WindowChromeSession session;
|
||||
final double height;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: session,
|
||||
builder: (context, _) => Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: Row(
|
||||
children: [
|
||||
_button(
|
||||
context,
|
||||
WindowCaptionCommand.minimize,
|
||||
Icons.remove,
|
||||
context.l10n.windowMinimize,
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
WindowCaptionCommand.toggleMaximize,
|
||||
session.maximized ? Icons.filter_none : Icons.crop_square,
|
||||
session.maximized
|
||||
? context.l10n.windowRestore
|
||||
: context.l10n.windowMaximize,
|
||||
role: HeaderControlRole.maximize,
|
||||
hovered: session.maximizeHovered,
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
WindowCaptionCommand.close,
|
||||
Icons.close,
|
||||
MaterialLocalizations.of(context).closeButtonTooltip,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Widget _button(
|
||||
BuildContext context,
|
||||
WindowCaptionCommand command,
|
||||
IconData icon,
|
||||
String label, {
|
||||
HeaderControlRole role = HeaderControlRole.control,
|
||||
bool hovered = false,
|
||||
}) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final close = command == WindowCaptionCommand.close;
|
||||
final key = command == WindowCaptionCommand.toggleMaximize
|
||||
? 'maximize'
|
||||
: command.name;
|
||||
return HeaderControlRegion(
|
||||
role: role,
|
||||
child: SizedBox(
|
||||
width: buttonWidth,
|
||||
height: height,
|
||||
child: IconButton(
|
||||
key: Key('window-$key'),
|
||||
tooltip: label,
|
||||
onPressed: () => unawaited(session.perform(command)),
|
||||
icon: Icon(icon, size: 16),
|
||||
style: ButtonStyle(
|
||||
padding: const WidgetStatePropertyAll(EdgeInsets.zero),
|
||||
shape: const WidgetStatePropertyAll(RoundedRectangleBorder()),
|
||||
backgroundColor: WidgetStateProperty.resolveWith(
|
||||
(states) => states.contains(WidgetState.hovered) || hovered
|
||||
? close
|
||||
? const Color(0xffc42b1c)
|
||||
: colors.onSurface.withValues(alpha: 0.08)
|
||||
: Colors.transparent,
|
||||
),
|
||||
foregroundColor: WidgetStateProperty.resolveWith(
|
||||
(states) => close && states.contains(WidgetState.hovered)
|
||||
? Colors.white
|
||||
: colors.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
import 'export_publication.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
|
||||
/// Native session and output-file adapter. Compilation belongs to editor.
|
||||
final class RuntimeEditorExport implements RecoverableEditorExportService {
|
||||
const RuntimeEditorExport(this.runtime);
|
||||
final CutdexRuntime runtime;
|
||||
|
||||
@override
|
||||
Future<MediaInfo?> probe(MediaReference media) => runtime.probe(media);
|
||||
|
||||
@override
|
||||
Future<EditorExportCapabilities> capabilities() async {
|
||||
final features = await runtime.capabilities();
|
||||
return EditorExportCapabilities(
|
||||
imageProbe:
|
||||
features.query('media.imageProbe') ==
|
||||
CapabilityAvailability.available,
|
||||
toneMapping:
|
||||
features.query('render.toneMapping') ==
|
||||
CapabilityAvailability.available,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Uri?> recoverExport(Uri destination, String operationId) =>
|
||||
ExportPublication(destination, operationId).recover();
|
||||
|
||||
@override
|
||||
Future<Uri> exportRecoverable(
|
||||
ExecutionPlan plan,
|
||||
Uri destination,
|
||||
String operationId,
|
||||
) => ExportPublication(destination, operationId).run(
|
||||
sha256.convert(utf8.encode(jsonEncode(plan.toMap()))).toString(),
|
||||
(staging) => export(plan, staging),
|
||||
);
|
||||
|
||||
@override
|
||||
Future<Uri> export(ExecutionPlan plan, Uri destination) async {
|
||||
if (await FileSystemEntity.type(
|
||||
destination.toFilePath(),
|
||||
followLinks: false,
|
||||
) !=
|
||||
FileSystemEntityType.notFound) {
|
||||
throw const CommandRejected(
|
||||
'destinationExists',
|
||||
'Destination already exists',
|
||||
);
|
||||
}
|
||||
if (!await File.fromUri(destination).parent.exists()) {
|
||||
throw const CommandRejected(
|
||||
'invalidDestination',
|
||||
'Destination directory does not exist',
|
||||
);
|
||||
}
|
||||
final session = await runtime.createSession();
|
||||
try {
|
||||
return await session.export(plan, destination);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// A completed staging file and its digest are durable before publication.
|
||||
/// Only this operation's recorded output is eligible for recovery.
|
||||
final class ExportPublication {
|
||||
ExportPublication(this.destination, this.operationId);
|
||||
final Uri destination;
|
||||
final String operationId;
|
||||
File get output => File.fromUri(destination);
|
||||
Directory get directory => Directory(
|
||||
p.join(
|
||||
output.parent.path,
|
||||
'.cutdex-export-${sha256.convert(utf8.encode('$operationId|$destination'))}',
|
||||
),
|
||||
);
|
||||
File get staged => File(p.join(directory.path, 'output.mp4'));
|
||||
File get receipt => File(p.join(directory.path, 'receipt.json'));
|
||||
|
||||
Future<String> _digest(File file) async =>
|
||||
(await sha256.bind(file.openRead()).first).toString();
|
||||
Future<void> _save(Map<String, Object?> value) async {
|
||||
final temporary = File('${receipt.path}.tmp');
|
||||
await temporary.writeAsString(jsonEncode(value), flush: true);
|
||||
await temporary.rename(receipt.path);
|
||||
}
|
||||
|
||||
Future<Uri?> recover() async {
|
||||
if (!await receipt.exists()) return null;
|
||||
final value = (jsonDecode(await receipt.readAsString()) as Map)
|
||||
.cast<String, Object?>();
|
||||
if (value['operationId'] != operationId ||
|
||||
value['destination'] != destination.toString()) {
|
||||
throw const CommandRejected(
|
||||
'operationIdConflict',
|
||||
'Export receipt belongs to another request',
|
||||
);
|
||||
}
|
||||
if (value['sha256'] == null) return null;
|
||||
final candidate = await output.exists() ? output : staged;
|
||||
if (!await candidate.exists() ||
|
||||
await candidate.length() != value['bytes'] ||
|
||||
await _digest(candidate) != value['sha256']) {
|
||||
throw const CommandRejected(
|
||||
'exportArtifactChanged',
|
||||
'Export output is missing or changed; choose a new destination to retry',
|
||||
);
|
||||
}
|
||||
if (candidate.path == staged.path) await staged.rename(output.path);
|
||||
return destination;
|
||||
}
|
||||
|
||||
Future<Uri> run(String fingerprint, Future<Uri> Function(Uri) encode) async {
|
||||
if (await receipt.exists()) {
|
||||
final value = jsonDecode(await receipt.readAsString()) as Map;
|
||||
if (value['fingerprint'] != fingerprint) {
|
||||
throw const CommandRejected(
|
||||
'operationIdConflict',
|
||||
'Export snapshot changed',
|
||||
);
|
||||
}
|
||||
}
|
||||
final recovered = await recover();
|
||||
if (recovered != null) return recovered;
|
||||
if (await output.exists()) {
|
||||
throw const CommandRejected(
|
||||
'destinationExists',
|
||||
'Destination already exists',
|
||||
);
|
||||
}
|
||||
if (!await output.parent.exists()) {
|
||||
throw const CommandRejected(
|
||||
'invalidDestination',
|
||||
'Destination directory does not exist',
|
||||
);
|
||||
}
|
||||
if (await receipt.exists()) {
|
||||
throw const CommandRejected(
|
||||
'exportInterrupted',
|
||||
'Export was interrupted before publication; explicitly retry with a new operation',
|
||||
);
|
||||
}
|
||||
await directory.create();
|
||||
final record = <String, Object?>{
|
||||
'operationId': operationId,
|
||||
'destination': destination.toString(),
|
||||
'fingerprint': fingerprint,
|
||||
};
|
||||
await _save(record);
|
||||
await encode(staged.uri);
|
||||
final handle = await staged.open(mode: FileMode.append);
|
||||
try {
|
||||
await handle.flush();
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
await _save({
|
||||
...record,
|
||||
'bytes': await staged.length(),
|
||||
'sha256': await _digest(staged),
|
||||
});
|
||||
return (await recover())!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'media_thumbnails.dart';
|
||||
import 'media_waveforms.dart';
|
||||
|
||||
part 'media_presentations.g.dart';
|
||||
|
||||
@riverpod
|
||||
Future<Uint8List?> mediaCover(
|
||||
Ref ref,
|
||||
AssetDocument asset, {
|
||||
int timeMilliseconds = 0,
|
||||
}) => ref
|
||||
.watch(mediaThumbnailsProvider)
|
||||
.load(asset, timeMilliseconds: timeMilliseconds);
|
||||
|
||||
@riverpod
|
||||
Future<double?> mediaDuration(Ref ref, AssetDocument asset) =>
|
||||
ref.watch(mediaThumbnailsProvider).duration(asset);
|
||||
|
||||
@riverpod
|
||||
Future<TimelineWaveform?> mediaWaveform(Ref ref, AssetDocument asset) =>
|
||||
ref.watch(mediaWaveformsProvider).load(asset);
|
||||
@@ -0,0 +1,241 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_presentations.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaCover)
|
||||
final mediaCoverProvider = MediaCoverFamily._();
|
||||
|
||||
final class MediaCoverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<Uint8List?>,
|
||||
Uint8List?,
|
||||
FutureOr<Uint8List?>
|
||||
>
|
||||
with $FutureModifier<Uint8List?>, $FutureProvider<Uint8List?> {
|
||||
MediaCoverProvider._({
|
||||
required MediaCoverFamily super.from,
|
||||
required (AssetDocument, {int timeMilliseconds}) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaCoverProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaCoverHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaCoverProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<Uint8List?> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<Uint8List?> create(Ref ref) {
|
||||
final argument = this.argument as (AssetDocument, {int timeMilliseconds});
|
||||
return mediaCover(
|
||||
ref,
|
||||
argument.$1,
|
||||
timeMilliseconds: argument.timeMilliseconds,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaCoverProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaCoverHash() => r'34b3ae0fa1106a3448028e34ca2f0c64838a3d6a';
|
||||
|
||||
final class MediaCoverFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
FutureOr<Uint8List?>,
|
||||
(AssetDocument, {int timeMilliseconds})
|
||||
> {
|
||||
MediaCoverFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaCoverProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaCoverProvider call(AssetDocument asset, {int timeMilliseconds = 0}) =>
|
||||
MediaCoverProvider._(
|
||||
argument: (asset, timeMilliseconds: timeMilliseconds),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaCoverProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(mediaDuration)
|
||||
final mediaDurationProvider = MediaDurationFamily._();
|
||||
|
||||
final class MediaDurationProvider
|
||||
extends $FunctionalProvider<AsyncValue<double?>, double?, FutureOr<double?>>
|
||||
with $FutureModifier<double?>, $FutureProvider<double?> {
|
||||
MediaDurationProvider._({
|
||||
required MediaDurationFamily super.from,
|
||||
required AssetDocument super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaDurationProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaDurationHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaDurationProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<double?> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<double?> create(Ref ref) {
|
||||
final argument = this.argument as AssetDocument;
|
||||
return mediaDuration(ref, argument);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaDurationProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaDurationHash() => r'065f3604e588f088d9fe4454a77a71a4eaed57b6';
|
||||
|
||||
final class MediaDurationFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<double?>, AssetDocument> {
|
||||
MediaDurationFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaDurationProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaDurationProvider call(AssetDocument asset) =>
|
||||
MediaDurationProvider._(argument: asset, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaDurationProvider';
|
||||
}
|
||||
|
||||
@ProviderFor(mediaWaveform)
|
||||
final mediaWaveformProvider = MediaWaveformFamily._();
|
||||
|
||||
final class MediaWaveformProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<TimelineWaveform?>,
|
||||
TimelineWaveform?,
|
||||
FutureOr<TimelineWaveform?>
|
||||
>
|
||||
with
|
||||
$FutureModifier<TimelineWaveform?>,
|
||||
$FutureProvider<TimelineWaveform?> {
|
||||
MediaWaveformProvider._({
|
||||
required MediaWaveformFamily super.from,
|
||||
required AssetDocument super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'mediaWaveformProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaWaveformHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'mediaWaveformProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<TimelineWaveform?> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<TimelineWaveform?> create(Ref ref) {
|
||||
final argument = this.argument as AssetDocument;
|
||||
return mediaWaveform(ref, argument);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is MediaWaveformProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaWaveformHash() => r'7556aade813f27763c5407b5decc65b20e5db616';
|
||||
|
||||
final class MediaWaveformFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<TimelineWaveform?>, AssetDocument> {
|
||||
MediaWaveformFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'mediaWaveformProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
MediaWaveformProvider call(AssetDocument asset) =>
|
||||
MediaWaveformProvider._(argument: asset, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'mediaWaveformProvider';
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/media_binding.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart'
|
||||
show ProviderListenableSelect;
|
||||
part 'media_thumbnails.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
MediaThumbnails mediaThumbnails(Ref ref) {
|
||||
final projectId = ref.watch(
|
||||
projectsProvider.select((s) => s.asData?.value.activeProject?.id),
|
||||
);
|
||||
return MediaThumbnails(
|
||||
loadMedia: <T>(asset, action) => ref
|
||||
.read(projectsProvider.notifier)
|
||||
.withAssetMedia(projectId, asset, action),
|
||||
);
|
||||
}
|
||||
|
||||
/// Small runtime-generated browser covers, kept outside the project document.
|
||||
class MediaThumbnails {
|
||||
MediaThumbnails({required this.loadMedia});
|
||||
final AssetMediaLoader loadMedia;
|
||||
final _runtime = CutdexRuntime();
|
||||
final _cache = <(String, int?, int), Future<Uint8List?>>{};
|
||||
final _durations = <(String, int?), Future<double?>>{};
|
||||
Future<void> _tail = Future.value();
|
||||
|
||||
Future<double?> duration(AssetDocument asset) {
|
||||
final key = (asset.location, asset.byteLength);
|
||||
if (_durations.containsKey(key)) return _durations[key]!;
|
||||
if (_durations.length >= 64) _durations.remove(_durations.keys.first);
|
||||
return _durations[key] = () async {
|
||||
try {
|
||||
final info = await loadMedia(asset, _runtime.probe);
|
||||
final seconds = info.duration.numerator / info.duration.denominator;
|
||||
return seconds.isFinite && seconds > 0 ? seconds : null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
Future<Uint8List?> load(AssetDocument asset, {int timeMilliseconds = 0}) {
|
||||
final key = (asset.location, asset.byteLength, timeMilliseconds);
|
||||
final cached = _cache.remove(key);
|
||||
if (cached != null) {
|
||||
_cache[key] = cached;
|
||||
return cached;
|
||||
}
|
||||
// Bound encoded cover retention and concurrent native generation.
|
||||
if (_cache.length >= 64) _cache.remove(_cache.keys.first);
|
||||
final future = _tail.then((_) async {
|
||||
if (asset.metadata['kind'] == 'image') {
|
||||
final image = await _imagePreview(asset);
|
||||
if (image != null) return image;
|
||||
}
|
||||
try {
|
||||
final thumbnail = await loadMedia(
|
||||
asset,
|
||||
(media) => _runtime.thumbnail(
|
||||
ThumbnailRequest(
|
||||
media: media,
|
||||
time: MediaTime(timeMilliseconds, 1000),
|
||||
),
|
||||
),
|
||||
);
|
||||
return thumbnail.data;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
_cache[key] = future;
|
||||
_tail = future.then((_) {});
|
||||
return future;
|
||||
}
|
||||
|
||||
Future<Uint8List?> _imagePreview(AssetDocument asset) async {
|
||||
if (kIsWeb) return null;
|
||||
try {
|
||||
return await loadMedia(asset, (media) async {
|
||||
if (media.uri.scheme != 'file') return null;
|
||||
final file = File.fromUri(media.uri);
|
||||
if (!file.existsSync()) return null;
|
||||
final bytes = await file.readAsBytes();
|
||||
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
|
||||
try {
|
||||
final descriptor = await ui.ImageDescriptor.encoded(buffer);
|
||||
try {
|
||||
final longestSide = descriptor.width > descriptor.height
|
||||
? descriptor.width
|
||||
: descriptor.height;
|
||||
final scale = longestSide > 320 ? 320 / longestSide : 1.0;
|
||||
final codec = await descriptor.instantiateCodec(
|
||||
targetWidth: (descriptor.width * scale).round(),
|
||||
targetHeight: (descriptor.height * scale).round(),
|
||||
);
|
||||
try {
|
||||
final frame = await codec.getNextFrame();
|
||||
try {
|
||||
return (await frame.image.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
))?.buffer.asUint8List();
|
||||
} finally {
|
||||
frame.image.dispose();
|
||||
}
|
||||
} finally {
|
||||
codec.dispose();
|
||||
}
|
||||
} finally {
|
||||
descriptor.dispose();
|
||||
}
|
||||
} finally {
|
||||
buffer.dispose();
|
||||
}
|
||||
});
|
||||
} catch (_) {
|
||||
// Formats not handled by Flutter can still use the native thumbnailer.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_thumbnails.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaThumbnails)
|
||||
final mediaThumbnailsProvider = MediaThumbnailsProvider._();
|
||||
|
||||
final class MediaThumbnailsProvider
|
||||
extends
|
||||
$FunctionalProvider<MediaThumbnails, MediaThumbnails, MediaThumbnails>
|
||||
with $Provider<MediaThumbnails> {
|
||||
MediaThumbnailsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'mediaThumbnailsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaThumbnailsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<MediaThumbnails> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
MediaThumbnails create(Ref ref) {
|
||||
return mediaThumbnails(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(MediaThumbnails value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<MediaThumbnails>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaThumbnailsHash() => r'80b7a58411b734ef13efcbd01eeef5ef125d06d4';
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/media_binding.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart'
|
||||
show ProviderListenableSelect;
|
||||
part 'media_waveforms.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
MediaWaveforms mediaWaveforms(Ref ref) {
|
||||
final projectId = ref.watch(
|
||||
projectsProvider.select((s) => s.asData?.value.activeProject?.id),
|
||||
);
|
||||
return MediaWaveforms(
|
||||
loadMedia: <T>(asset, action) => ref
|
||||
.read(projectsProvider.notifier)
|
||||
.withAssetMedia(projectId, asset, action),
|
||||
);
|
||||
}
|
||||
|
||||
/// Browser envelopes use the same native request/cache as timeline waveforms.
|
||||
class MediaWaveforms {
|
||||
MediaWaveforms({required this.loadMedia});
|
||||
final AssetMediaLoader loadMedia;
|
||||
final _runtime = CutdexRuntime();
|
||||
final _cache = <(String, int?), Future<TimelineWaveform?>>{};
|
||||
Future<void> _tail = Future.value();
|
||||
|
||||
Future<TimelineWaveform?> load(AssetDocument asset) {
|
||||
final key = (asset.location, asset.byteLength);
|
||||
final cached = _cache.remove(key);
|
||||
if (cached != null) {
|
||||
_cache[key] = cached;
|
||||
return cached;
|
||||
}
|
||||
if (_cache.length >= 16) _cache.remove(_cache.keys.first);
|
||||
final future = _tail.then((_) async {
|
||||
try {
|
||||
final waveform = await loadMedia(
|
||||
asset,
|
||||
(media) => _runtime.waveform(WaveformRequest(media: media)),
|
||||
);
|
||||
return TimelineWaveform(
|
||||
sampleRate: waveform.sampleRate,
|
||||
sourceStartSeconds: waveform.sourceStartSeconds,
|
||||
frameCount: waveform.frameCount,
|
||||
levels: List.unmodifiable([
|
||||
for (final level in waveform.levels)
|
||||
TimelineWaveformLevel(
|
||||
samplesPerBucket: level.samplesPerBucket,
|
||||
channels: level.channels,
|
||||
),
|
||||
]),
|
||||
);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
_cache[key] = future;
|
||||
_tail = future.then((_) {});
|
||||
return future;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'media_waveforms.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(mediaWaveforms)
|
||||
final mediaWaveformsProvider = MediaWaveformsProvider._();
|
||||
|
||||
final class MediaWaveformsProvider
|
||||
extends $FunctionalProvider<MediaWaveforms, MediaWaveforms, MediaWaveforms>
|
||||
with $Provider<MediaWaveforms> {
|
||||
MediaWaveformsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'mediaWaveformsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$mediaWaveformsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<MediaWaveforms> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
MediaWaveforms create(Ref ref) {
|
||||
return mediaWaveforms(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(MediaWaveforms value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<MediaWaveforms>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$mediaWaveformsHash() => r'0523a0e7fc9f29c37c23d7c17d77a167294bde54';
|
||||
@@ -0,0 +1,178 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/runtime/processing.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
/// App deployment configuration for non-realtime native processing.
|
||||
final class ProcessingConfiguration {
|
||||
const ProcessingConfiguration({
|
||||
required this.backend,
|
||||
this.transcriptionModel,
|
||||
this.translationModel,
|
||||
this.vocalSeparationModel,
|
||||
this.backgroundRemovalModel,
|
||||
});
|
||||
|
||||
final CutdexProcessing backend;
|
||||
final Uri? transcriptionModel;
|
||||
final Uri? translationModel;
|
||||
final Uri? vocalSeparationModel;
|
||||
final Uri? backgroundRemovalModel;
|
||||
|
||||
static String get _defaultResourcesRoot {
|
||||
if (Platform.isMacOS) {
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return p.join(
|
||||
Platform.environment['USERPROFILE'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Documents',
|
||||
'Cutdex',
|
||||
'Resources',
|
||||
);
|
||||
}
|
||||
|
||||
static String get _bundledRuntimeRoot {
|
||||
final executable = File(Platform.resolvedExecutable);
|
||||
if (Platform.isMacOS) {
|
||||
return p.normalize(
|
||||
p.join(executable.parent.path, '..', 'Resources', 'processing'),
|
||||
);
|
||||
}
|
||||
return p.join(executable.parent.path, 'processing');
|
||||
}
|
||||
|
||||
static ProcessingConfiguration? configured({
|
||||
String? resourcesRoot,
|
||||
DiagnosticSink? diagnostics,
|
||||
}) {
|
||||
const definedRoot = String.fromEnvironment('CUTDEX_PROCESSING_ROOT');
|
||||
final root = definedRoot.isNotEmpty
|
||||
? definedRoot
|
||||
: Platform.environment['CUTDEX_PROCESSING_ROOT'] ?? _bundledRuntimeRoot;
|
||||
final modelsRoot = p.join(
|
||||
resourcesRoot ?? _defaultResourcesRoot,
|
||||
'Processing',
|
||||
);
|
||||
final transcriptionPath = p.join(
|
||||
modelsRoot,
|
||||
'Transcription',
|
||||
'whisper-turbo',
|
||||
'1',
|
||||
);
|
||||
final vocalPath = p.join(
|
||||
modelsRoot,
|
||||
'VocalSeparation',
|
||||
'melband',
|
||||
'1',
|
||||
'melband.pt',
|
||||
);
|
||||
final translationPath = p.join(
|
||||
modelsRoot,
|
||||
'Translation',
|
||||
'm2m100-418m',
|
||||
'1',
|
||||
);
|
||||
final backgroundRemovalPath = p.join(
|
||||
modelsRoot,
|
||||
'BackgroundRemoval',
|
||||
'birefnet-matting',
|
||||
'1',
|
||||
'model.onnx',
|
||||
);
|
||||
return fromPaths(
|
||||
root: root,
|
||||
transcriptionPath: transcriptionPath,
|
||||
vocalPath: vocalPath,
|
||||
translationPath: translationPath,
|
||||
backgroundRemovalPath: backgroundRemovalPath,
|
||||
diagnostics: diagnostics,
|
||||
);
|
||||
}
|
||||
|
||||
/// Resolves each installed capability independently; absent files disable only that capability.
|
||||
static ProcessingConfiguration? fromPaths({
|
||||
required String root,
|
||||
required String transcriptionPath,
|
||||
required String vocalPath,
|
||||
required String translationPath,
|
||||
String? backgroundRemovalPath,
|
||||
DiagnosticSink? diagnostics,
|
||||
}) {
|
||||
if (!p.isAbsolute(root)) return null;
|
||||
final exe = Platform.isWindows ? '.exe' : '';
|
||||
final executable = p.join(root, 'bin', 'cutdex-processing-worker$exe');
|
||||
final ffmpeg = p.join(root, 'bin', 'ffmpeg$exe');
|
||||
if (!File(executable).existsSync()) {
|
||||
return null;
|
||||
}
|
||||
final asrWorker = p.join(root, 'workers', 'asr', 'cutdex-asr-worker$exe');
|
||||
final transcriptionModel =
|
||||
p.isAbsolute(transcriptionPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(asrWorker).existsSync() &&
|
||||
File(p.join(transcriptionPath, 'ggml-model.bin')).existsSync() &&
|
||||
File(p.join(transcriptionPath, 'silero_vad.onnx')).existsSync()
|
||||
? Uri.directory(transcriptionPath)
|
||||
: null;
|
||||
final audioWorker = p.join(
|
||||
root,
|
||||
'workers',
|
||||
'audio',
|
||||
'cutdex-audio-worker$exe',
|
||||
);
|
||||
final m2m100Worker = p.join(
|
||||
root,
|
||||
'workers',
|
||||
'translation',
|
||||
'cutdex-m2m100-worker$exe',
|
||||
);
|
||||
final translationModel =
|
||||
p.isAbsolute(translationPath) &&
|
||||
File(m2m100Worker).existsSync() &&
|
||||
File(p.join(translationPath, 'model.bin')).existsSync() &&
|
||||
File(p.join(translationPath, 'config.json')).existsSync() &&
|
||||
File(p.join(translationPath, 'shared_vocabulary.json'))
|
||||
.existsSync() &&
|
||||
File(p.join(translationPath, 'sentencepiece.bpe.model'))
|
||||
.existsSync()
|
||||
? Uri.directory(translationPath)
|
||||
: null;
|
||||
final vocalSeparationModel =
|
||||
p.isAbsolute(vocalPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(audioWorker).existsSync() &&
|
||||
File(vocalPath).existsSync()
|
||||
? Uri.file(vocalPath)
|
||||
: null;
|
||||
final backgroundRemovalModel =
|
||||
backgroundRemovalPath != null &&
|
||||
p.isAbsolute(backgroundRemovalPath) &&
|
||||
File(ffmpeg).existsSync() &&
|
||||
File(backgroundRemovalPath).existsSync()
|
||||
? Uri.file(backgroundRemovalPath)
|
||||
: null;
|
||||
return ProcessingConfiguration(
|
||||
backend: CutdexProcessing.fromPackage(
|
||||
Directory(root),
|
||||
diagnostics: diagnostics,
|
||||
),
|
||||
transcriptionModel: transcriptionModel,
|
||||
translationModel: translationModel,
|
||||
vocalSeparationModel: vocalSeparationModel,
|
||||
backgroundRemovalModel: backgroundRemovalModel,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,722 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:crypto/crypto.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../errors/app_failure.dart';
|
||||
import '../app_failure_adapter.dart';
|
||||
|
||||
part 'processing_resource_repository.g.dart';
|
||||
part 'processing_resource_repository.freezed.dart';
|
||||
|
||||
enum ProcessingResourceState { notInstalled, downloading, installed, failed }
|
||||
|
||||
enum ProcessingCapability {
|
||||
transcription,
|
||||
translation,
|
||||
vocalSeparation,
|
||||
backgroundRemoval,
|
||||
}
|
||||
|
||||
class ProcessingResourceCancelledException implements Exception {
|
||||
const ProcessingResourceCancelledException();
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourceArtifact with _$ProcessingResourceArtifact {
|
||||
const ProcessingResourceArtifact._();
|
||||
|
||||
const factory ProcessingResourceArtifact({
|
||||
required String path,
|
||||
required Uri url,
|
||||
required String sha256,
|
||||
required int bytes,
|
||||
}) = _ProcessingResourceArtifact;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourcePackage with _$ProcessingResourcePackage {
|
||||
const ProcessingResourcePackage._();
|
||||
|
||||
const factory ProcessingResourcePackage({
|
||||
required ProcessingCapability capability,
|
||||
required String id,
|
||||
required String version,
|
||||
required String name,
|
||||
required String description,
|
||||
required List<ProcessingResourceArtifact> artifacts,
|
||||
}) = _ProcessingResourcePackage;
|
||||
|
||||
int get bytes =>
|
||||
artifacts.fold(0, (total, artifact) => total + artifact.bytes);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourceInstall with _$ProcessingResourceInstall {
|
||||
const ProcessingResourceInstall._();
|
||||
|
||||
const factory ProcessingResourceInstall({
|
||||
required ProcessingResourcePackage package,
|
||||
required ProcessingResourceState state,
|
||||
@Default(0) int downloadedBytes,
|
||||
AppFailure? error,
|
||||
}) = _ProcessingResourceInstall;
|
||||
|
||||
double get progress =>
|
||||
package.bytes == 0 ? 0 : (downloadedBytes / package.bytes).clamp(0, 1);
|
||||
}
|
||||
|
||||
const _translationRevision = '18e406c615ef2991fa74d53734bf66b0a6b10cb4';
|
||||
|
||||
const _whisperRevision = '5359861c739e955e79d9a303bcbc70fb988958b1';
|
||||
|
||||
final defaultProcessingResourceCatalog = <ProcessingResourcePackage>[
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.transcription,
|
||||
id: 'whisper-turbo',
|
||||
version: '1',
|
||||
name: 'Whisper Large V3 Turbo',
|
||||
description: '语音识别与字幕生成',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'ggml-model.bin',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/ggerganov/whisper.cpp/resolve/'
|
||||
'$_whisperRevision/ggml-large-v3-turbo-q5_0.bin',
|
||||
),
|
||||
sha256:
|
||||
'394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2',
|
||||
bytes: 574041195,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'silero_vad.onnx',
|
||||
url: Uri.parse(
|
||||
'https://github.com/k2-fsa/sherpa-onnx/releases/download/'
|
||||
'asr-models/silero_vad.onnx',
|
||||
),
|
||||
sha256:
|
||||
'9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6',
|
||||
bytes: 643854,
|
||||
),
|
||||
],
|
||||
),
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.translation,
|
||||
id: 'm2m100-418m',
|
||||
version: '1',
|
||||
name: 'M2M100 418M',
|
||||
description: '字幕翻译',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'config.json',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/config.json',
|
||||
),
|
||||
sha256:
|
||||
'8f6496adfc930cbfecbe8281112197705c488fab47d34b4829b06d7f478909af',
|
||||
bytes: 223,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.bin',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/model.bin',
|
||||
),
|
||||
sha256:
|
||||
'a1826980fc5c037e69c7ac94fcb56c03001a66f380eb71863cc0a3879e71421b',
|
||||
bytes: 490667752,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'sentencepiece.bpe.model',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/sentencepiece.bpe.model',
|
||||
),
|
||||
sha256:
|
||||
'd8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a',
|
||||
bytes: 2423393,
|
||||
),
|
||||
ProcessingResourceArtifact(
|
||||
path: 'shared_vocabulary.json',
|
||||
url: Uri.parse(
|
||||
'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/shared_vocabulary.json',
|
||||
),
|
||||
sha256:
|
||||
'7eb5d0ff184c6095c7c10f9911c0aea492250abd12854f9c3d787c64b1c6397e',
|
||||
bytes: 2796509,
|
||||
),
|
||||
],
|
||||
),
|
||||
ProcessingResourcePackage(
|
||||
capability: ProcessingCapability.backgroundRemoval,
|
||||
id: 'birefnet-matting',
|
||||
version: '1',
|
||||
name: 'BiRefNet Matting',
|
||||
description: '图片与视频背景移除',
|
||||
artifacts: [
|
||||
ProcessingResourceArtifact(
|
||||
path: 'model.onnx',
|
||||
url: Uri.parse(
|
||||
'https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/'
|
||||
'BiRefNet-matting-epoch_100.onnx',
|
||||
),
|
||||
sha256:
|
||||
'6065d27c615ea27308f5b88598dd8db116eb07436c7a323ca40d13b2866c309e',
|
||||
bytes: 972667742,
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<Raw<ProcessingResourceRepository>> processingResourceRepository(
|
||||
Ref ref,
|
||||
) async {
|
||||
final resources = await ref
|
||||
.watch(resourceLocationSettingsRepositoryProvider)
|
||||
.load();
|
||||
final resourcesRoot = resources!;
|
||||
final repository = ProcessingResourceRepository(
|
||||
root: Directory(p.join(resourcesRoot, 'Processing')),
|
||||
downloadsRoot: Directory(p.join(resourcesRoot, 'Downloads')),
|
||||
);
|
||||
await repository.load();
|
||||
ref.onDispose(repository.dispose);
|
||||
return repository;
|
||||
}
|
||||
|
||||
/// Owns optional resources required by processing capabilities.
|
||||
/// Downloads never publish a partially installed
|
||||
/// version: verified files are assembled in staging and the directory is then
|
||||
/// atomically renamed into place.
|
||||
final class ProcessingResourceRepository extends ChangeNotifier {
|
||||
ProcessingResourceRepository({
|
||||
Directory? root,
|
||||
this.downloadsRoot,
|
||||
List<ProcessingResourcePackage>? catalog,
|
||||
}) : root = root ?? Directory(_defaultRoot()),
|
||||
catalog = List.unmodifiable(catalog ?? defaultProcessingResourceCatalog);
|
||||
|
||||
final Directory root;
|
||||
final Directory? downloadsRoot;
|
||||
final List<ProcessingResourcePackage> catalog;
|
||||
final Map<String, ProcessingResourceInstall> _installs = {};
|
||||
final Set<String> _cancelled = {};
|
||||
bool _loaded = false;
|
||||
bool _disposed = false;
|
||||
bool _subtitleDownloading = false;
|
||||
bool _subtitleCancelled = false;
|
||||
bool _subtitlePaused = false;
|
||||
Set<ProcessingCapability> _subtitleAvailable = const {};
|
||||
Completer<void>? _subtitleResume;
|
||||
final Map<String, HttpClient> _downloadClients = {};
|
||||
final Map<String, _DownloadRate> _downloadRates = {};
|
||||
final Map<String, Completer<void>> _pausedDownloads = {};
|
||||
|
||||
void _changed() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
_cancelled.addAll(
|
||||
_installs.values
|
||||
.where(
|
||||
(install) => install.state == ProcessingResourceState.downloading,
|
||||
)
|
||||
.map((install) => install.package.id),
|
||||
);
|
||||
for (final id in _downloadClients.keys.toList()) {
|
||||
_cancelled.add(id);
|
||||
_pausedDownloads.remove(id)?.complete();
|
||||
_downloadClients[id]?.close(force: true);
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
static const subtitleCapabilities = [
|
||||
ProcessingCapability.transcription,
|
||||
ProcessingCapability.translation,
|
||||
];
|
||||
|
||||
bool get subtitlePaused => _subtitlePaused;
|
||||
bool get subtitleDownloading => _subtitleDownloading;
|
||||
int get subtitleDownloadBytesPerSecond => _subtitlePaused
|
||||
? 0
|
||||
: subtitleCapabilities.fold(
|
||||
0,
|
||||
(total, capability) => total + downloadBytesPerSecondFor(capability),
|
||||
);
|
||||
int downloadBytesPerSecondFor(ProcessingCapability capability) {
|
||||
final package = packageFor(capability);
|
||||
if (installFor(capability).state != ProcessingResourceState.downloading) {
|
||||
return 0;
|
||||
}
|
||||
return _downloadRates[package.id]?.bytesPerSecond ?? 0;
|
||||
}
|
||||
|
||||
bool downloadPausedFor(ProcessingCapability capability) =>
|
||||
_pausedDownloads.containsKey(packageFor(capability).id);
|
||||
|
||||
void pauseDownload(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
if (installFor(capability).state != ProcessingResourceState.downloading ||
|
||||
_pausedDownloads.containsKey(id)) {
|
||||
return;
|
||||
}
|
||||
_pausedDownloads[id] = Completer<void>();
|
||||
_downloadRates[id]?.reset();
|
||||
_changed();
|
||||
}
|
||||
|
||||
void resumeDownload(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
final gate = _pausedDownloads.remove(id);
|
||||
if (gate == null) return;
|
||||
_downloadRates[id]?.reset();
|
||||
gate.complete();
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<void> _waitForDownloadResume(String packageId) async {
|
||||
while (_pausedDownloads.containsKey(packageId)) {
|
||||
await _pausedDownloads[packageId]!.future;
|
||||
}
|
||||
if (_cancelled.contains(packageId)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
}
|
||||
|
||||
int get subtitleTotalBytes => subtitleCapabilities.fold(
|
||||
0,
|
||||
(total, capability) => total + packageFor(capability).bytes,
|
||||
);
|
||||
int get subtitleDownloadedBytes => subtitleCapabilities.fold(0, (
|
||||
total,
|
||||
capability,
|
||||
) {
|
||||
final install = installFor(capability);
|
||||
return total +
|
||||
(_subtitleAvailable.contains(capability) ||
|
||||
install.state == ProcessingResourceState.installed
|
||||
? install.package.bytes
|
||||
: install.downloadedBytes.clamp(0, install.package.bytes).toInt());
|
||||
});
|
||||
|
||||
void pauseSubtitleResources() {
|
||||
if (!_subtitleDownloading || _subtitlePaused) return;
|
||||
_subtitlePaused = true;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
_downloadRates[packageFor(capability).id]?.reset();
|
||||
}
|
||||
_subtitleResume = Completer<void>();
|
||||
_changed();
|
||||
}
|
||||
|
||||
void resumeSubtitleResources() {
|
||||
if (!_subtitlePaused) return;
|
||||
_subtitlePaused = false;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
_downloadRates[packageFor(capability).id]?.reset();
|
||||
}
|
||||
_subtitleResume?.complete();
|
||||
_subtitleResume = null;
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<void> _waitForSubtitleResume(String packageId) async {
|
||||
if (!_subtitleDownloading ||
|
||||
!subtitleCapabilities.any(
|
||||
(capability) => packageFor(capability).id == packageId,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
while (_subtitlePaused && !_subtitleCancelled) {
|
||||
await _subtitleResume!.future;
|
||||
}
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
}
|
||||
|
||||
/// Installs both subtitle resources with one byte-weighted progress value.
|
||||
/// Already configured resources participate as completed bytes.
|
||||
Future<void> ensureSubtitleResources({
|
||||
Set<ProcessingCapability> available = const {},
|
||||
required void Function(ProcessingCapability stage, double progress)
|
||||
onProgress,
|
||||
}) async {
|
||||
if (_subtitleDownloading) {
|
||||
throw StateError('Subtitle download is already in progress');
|
||||
}
|
||||
var stage = ProcessingCapability.transcription;
|
||||
final total = subtitleTotalBytes;
|
||||
_subtitleDownloading = true;
|
||||
_subtitleCancelled = false;
|
||||
_subtitlePaused = false;
|
||||
_subtitleAvailable = Set.unmodifiable(available);
|
||||
_changed();
|
||||
void report() {
|
||||
final completed = subtitleDownloadedBytes;
|
||||
var installed = true;
|
||||
for (final capability in subtitleCapabilities) {
|
||||
final install = installFor(capability);
|
||||
final ready =
|
||||
available.contains(capability) ||
|
||||
install.state == ProcessingResourceState.installed;
|
||||
installed = installed && ready;
|
||||
}
|
||||
onProgress(
|
||||
stage,
|
||||
installed
|
||||
? 1.0
|
||||
: (total == 0 ? 0.0 : completed / total)
|
||||
.clamp(0.0, 0.99)
|
||||
.toDouble(),
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await load();
|
||||
addListener(report);
|
||||
for (final capability in subtitleCapabilities) {
|
||||
await _waitForSubtitleResume(packageFor(capability).id);
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
if (available.contains(capability) ||
|
||||
installFor(capability).state == ProcessingResourceState.installed) {
|
||||
continue;
|
||||
}
|
||||
stage = capability;
|
||||
report();
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
await ensureAvailable(capability);
|
||||
}
|
||||
if (_subtitleCancelled) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
report();
|
||||
} finally {
|
||||
removeListener(report);
|
||||
_subtitleDownloading = false;
|
||||
_subtitleAvailable = const {};
|
||||
resumeSubtitleResources();
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
void cancelSubtitleResources() {
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
for (final capability in subtitleCapabilities) {
|
||||
cancel(capability);
|
||||
}
|
||||
}
|
||||
|
||||
List<ProcessingResourceInstall> get installs => [
|
||||
for (final package in catalog)
|
||||
_installs[package.id] ??
|
||||
ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: ProcessingResourceState.notInstalled,
|
||||
),
|
||||
];
|
||||
|
||||
static String _defaultRoot() {
|
||||
if (Platform.isMacOS) {
|
||||
return p.join(
|
||||
Platform.environment['HOME'] ?? '',
|
||||
'Library',
|
||||
'Application Support',
|
||||
'Cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
if (Platform.isWindows) {
|
||||
return p.join(
|
||||
Platform.environment['LOCALAPPDATA'] ?? '',
|
||||
'Cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
return p.join(
|
||||
Platform.environment['XDG_DATA_HOME'] ??
|
||||
p.join(Platform.environment['HOME'] ?? '', '.local', 'share'),
|
||||
'cutdex',
|
||||
'models',
|
||||
);
|
||||
}
|
||||
|
||||
Directory directoryFor(ProcessingResourcePackage package) => Directory(
|
||||
p.join(
|
||||
root.path,
|
||||
switch (package.capability) {
|
||||
ProcessingCapability.transcription => 'Transcription',
|
||||
ProcessingCapability.translation => 'Translation',
|
||||
ProcessingCapability.vocalSeparation => 'VocalSeparation',
|
||||
ProcessingCapability.backgroundRemoval => 'BackgroundRemoval',
|
||||
},
|
||||
package.id,
|
||||
package.version,
|
||||
),
|
||||
);
|
||||
|
||||
ProcessingResourcePackage packageFor(ProcessingCapability capability) =>
|
||||
catalog.singleWhere((item) => item.capability == capability);
|
||||
|
||||
ProcessingResourceInstall installFor(ProcessingCapability capability) {
|
||||
final package = packageFor(capability);
|
||||
return _installs[package.id] ??
|
||||
ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: ProcessingResourceState.notInstalled,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> load() async {
|
||||
if (_loaded) return;
|
||||
_loaded = true;
|
||||
for (final package in catalog) {
|
||||
final installed = await _isValidInstall(package);
|
||||
_installs[package.id] = ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: installed
|
||||
? ProcessingResourceState.installed
|
||||
: ProcessingResourceState.notInstalled,
|
||||
);
|
||||
}
|
||||
_changed();
|
||||
}
|
||||
|
||||
Future<Directory> ensureAvailable(ProcessingCapability capability) async {
|
||||
await load();
|
||||
final package = packageFor(capability);
|
||||
final id = package.id;
|
||||
if (_installs[id]?.state == ProcessingResourceState.installed) {
|
||||
return directoryFor(package);
|
||||
}
|
||||
if (_installs[id]?.state == ProcessingResourceState.downloading) {
|
||||
throw StateError('Resource download is already in progress');
|
||||
}
|
||||
_cancelled.remove(id);
|
||||
_set(package, ProcessingResourceState.downloading);
|
||||
final destination = directoryFor(package);
|
||||
final staging = downloadsRoot == null
|
||||
? Directory('${destination.path}.download')
|
||||
: Directory(
|
||||
p.join(downloadsRoot!.path, '${package.id}-${package.version}'),
|
||||
);
|
||||
try {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
await staging.create(recursive: true);
|
||||
var completed = 0;
|
||||
for (final artifact in package.artifacts) {
|
||||
await _waitForSubtitleResume(id);
|
||||
if (_cancelled.contains(id)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
final target = File(p.join(staging.path, artifact.path));
|
||||
await target.parent.create(recursive: true);
|
||||
await _download(id, artifact, target, (received) {
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.downloading,
|
||||
downloadedBytes: completed + received,
|
||||
);
|
||||
});
|
||||
completed += artifact.bytes;
|
||||
}
|
||||
if (_cancelled.contains(id)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
await File(p.join(staging.path, '.installed.json')).writeAsString(
|
||||
jsonEncode({'id': package.id, 'version': package.version}),
|
||||
flush: true,
|
||||
);
|
||||
await destination.parent.create(recursive: true);
|
||||
if (await destination.exists()) await destination.delete(recursive: true);
|
||||
await staging.rename(destination.path);
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.installed,
|
||||
downloadedBytes: package.bytes,
|
||||
);
|
||||
return destination;
|
||||
} on ProcessingResourceCancelledException {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
throw const ProcessingResourceCancelledException();
|
||||
} catch (error) {
|
||||
if (await staging.exists()) await staging.delete(recursive: true);
|
||||
if (_cancelled.contains(id)) {
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
_set(
|
||||
package,
|
||||
ProcessingResourceState.failed,
|
||||
error: appFailureFromError(error),
|
||||
);
|
||||
rethrow;
|
||||
} finally {
|
||||
_pausedDownloads.remove(id)?.complete();
|
||||
_cancelled.remove(id);
|
||||
}
|
||||
}
|
||||
|
||||
void cancel(ProcessingCapability capability) {
|
||||
final id = packageFor(capability).id;
|
||||
if (_subtitleDownloading && subtitleCapabilities.contains(capability)) {
|
||||
_subtitleCancelled = true;
|
||||
resumeSubtitleResources();
|
||||
}
|
||||
_cancelled.add(id);
|
||||
resumeDownload(capability);
|
||||
_downloadClients[id]?.close(force: true);
|
||||
}
|
||||
|
||||
Future<void> remove(ProcessingCapability capability) async {
|
||||
await load();
|
||||
final package = packageFor(capability);
|
||||
cancel(capability);
|
||||
final directory = directoryFor(package);
|
||||
if (await directory.exists()) await directory.delete(recursive: true);
|
||||
_set(package, ProcessingResourceState.notInstalled);
|
||||
}
|
||||
|
||||
Future<bool> _isValidInstall(ProcessingResourcePackage package) async {
|
||||
final directory = directoryFor(package);
|
||||
final marker = File(p.join(directory.path, '.installed.json'));
|
||||
if (!await marker.exists()) return false;
|
||||
try {
|
||||
final value = jsonDecode(await marker.readAsString());
|
||||
if (value is! Map ||
|
||||
value['id'] != package.id ||
|
||||
value['version'] != package.version) {
|
||||
return false;
|
||||
}
|
||||
return package.artifacts.every(
|
||||
(artifact) => File(p.join(directory.path, artifact.path)).existsSync(),
|
||||
);
|
||||
} on FormatException {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _download(
|
||||
String packageId,
|
||||
ProcessingResourceArtifact artifact,
|
||||
File target,
|
||||
ValueChanged<int> onProgress,
|
||||
) async {
|
||||
if (_disposed) throw const ProcessingResourceCancelledException();
|
||||
final client = HttpClient();
|
||||
_downloadClients[packageId] = client;
|
||||
final rate = _DownloadRate();
|
||||
_downloadRates[packageId] = rate;
|
||||
try {
|
||||
await _waitForSubtitleResume(packageId);
|
||||
await _waitForDownloadResume(packageId);
|
||||
final request = await client.getUrl(artifact.url);
|
||||
request.headers.set(HttpHeaders.userAgentHeader, 'Cutdex/1');
|
||||
final response = await request.close();
|
||||
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||
throw AppException(
|
||||
AppErrorCode.resourceDownloadHttpFailed,
|
||||
httpStatusCode: response.statusCode,
|
||||
diagnostic: artifact.url.toString(),
|
||||
);
|
||||
}
|
||||
final output = target.openWrite();
|
||||
final digestOutput = _DigestSink();
|
||||
final digestInput = sha256.startChunkedConversion(digestOutput);
|
||||
var received = 0;
|
||||
try {
|
||||
await for (final chunk in response) {
|
||||
await _waitForSubtitleResume(packageId);
|
||||
await _waitForDownloadResume(packageId);
|
||||
if (_cancelled.contains(packageId)) {
|
||||
throw const ProcessingResourceCancelledException();
|
||||
}
|
||||
digestInput.add(chunk);
|
||||
output.add(chunk);
|
||||
received += chunk.length;
|
||||
rate.record(received);
|
||||
onProgress(received);
|
||||
}
|
||||
} finally {
|
||||
digestInput.close();
|
||||
await output.close();
|
||||
}
|
||||
final actual = digestOutput.value.toString();
|
||||
if (received != artifact.bytes || actual != artifact.sha256) {
|
||||
throw AppException(AppErrorCode.resourceChecksumFailed);
|
||||
}
|
||||
} finally {
|
||||
_downloadRates.remove(packageId);
|
||||
_downloadClients.remove(packageId);
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
void _set(
|
||||
ProcessingResourcePackage package,
|
||||
ProcessingResourceState state, {
|
||||
int downloadedBytes = 0,
|
||||
AppFailure? error,
|
||||
}) {
|
||||
_installs[package.id] = ProcessingResourceInstall(
|
||||
package: package,
|
||||
state: state,
|
||||
downloadedBytes: downloadedBytes,
|
||||
error: error,
|
||||
);
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
final class _DownloadRate {
|
||||
final Stopwatch _clock = Stopwatch()..start();
|
||||
int _sampleBytes = 0;
|
||||
int _sampleMilliseconds = 0;
|
||||
int _lastBytes = 0;
|
||||
int bytesPerSecond = 0;
|
||||
|
||||
void record(int receivedBytes) {
|
||||
_lastBytes = receivedBytes;
|
||||
final now = _clock.elapsedMilliseconds;
|
||||
final elapsed = now - _sampleMilliseconds;
|
||||
if (elapsed < 500) return;
|
||||
bytesPerSecond = ((receivedBytes - _sampleBytes) * 1000 / elapsed).round();
|
||||
_sampleBytes = receivedBytes;
|
||||
_sampleMilliseconds = now;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
_sampleBytes = _lastBytes;
|
||||
_sampleMilliseconds = _clock.elapsedMilliseconds;
|
||||
bytesPerSecond = 0;
|
||||
}
|
||||
}
|
||||
|
||||
final class _DigestSink implements Sink<Digest> {
|
||||
Digest? _digest;
|
||||
Digest get value => _digest ?? (throw StateError('Missing digest'));
|
||||
|
||||
@override
|
||||
void add(Digest data) => _digest = data;
|
||||
|
||||
@override
|
||||
void close() {}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,53 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'processing_resource_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(processingResourceRepository)
|
||||
final processingResourceRepositoryProvider =
|
||||
ProcessingResourceRepositoryProvider._();
|
||||
|
||||
final class ProcessingResourceRepositoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<Raw<ProcessingResourceRepository>>,
|
||||
Raw<ProcessingResourceRepository>,
|
||||
FutureOr<Raw<ProcessingResourceRepository>>
|
||||
>
|
||||
with
|
||||
$FutureModifier<Raw<ProcessingResourceRepository>>,
|
||||
$FutureProvider<Raw<ProcessingResourceRepository>> {
|
||||
ProcessingResourceRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'processingResourceRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$processingResourceRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<Raw<ProcessingResourceRepository>> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<Raw<ProcessingResourceRepository>> create(Ref ref) {
|
||||
return processingResourceRepository(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$processingResourceRepositoryHash() =>
|
||||
r'e96db5dd36cde4d619d1bc1236be27591d3794e1';
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'processing_resource_repository.dart';
|
||||
|
||||
part 'processing_resource_state.g.dart';
|
||||
part 'processing_resource_state.freezed.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ProcessingResourcesSnapshot with _$ProcessingResourcesSnapshot {
|
||||
const factory ProcessingResourcesSnapshot({
|
||||
@Default([]) List<ProcessingResourceInstall> installs,
|
||||
@Default({}) Set<ProcessingCapability> paused,
|
||||
@Default({}) Map<ProcessingCapability, int> rates,
|
||||
@Default(false) bool subtitleDownloading,
|
||||
@Default(false) bool subtitlePaused,
|
||||
@Default(0) int subtitleDownloadedBytes,
|
||||
@Default(0) int subtitleTotalBytes,
|
||||
@Default(0) int subtitleBytesPerSecond,
|
||||
}) = _ProcessingResourcesSnapshot;
|
||||
}
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
@riverpod
|
||||
class ProcessingResources extends _$ProcessingResources {
|
||||
@override
|
||||
ProcessingResourcesSnapshot build(ProcessingResourceRepository repository) {
|
||||
void changed() {
|
||||
if (ref.mounted) state = _snapshot();
|
||||
}
|
||||
|
||||
repository.addListener(changed);
|
||||
ref.onDispose(() => repository.removeListener(changed));
|
||||
return _snapshot();
|
||||
}
|
||||
|
||||
ProcessingResourcesSnapshot _snapshot() => ProcessingResourcesSnapshot(
|
||||
installs: List.of(repository.installs),
|
||||
paused: {
|
||||
for (final package in repository.catalog)
|
||||
if (repository.downloadPausedFor(package.capability))
|
||||
package.capability,
|
||||
},
|
||||
rates: {
|
||||
for (final package in repository.catalog)
|
||||
package.capability: repository.downloadBytesPerSecondFor(
|
||||
package.capability,
|
||||
),
|
||||
},
|
||||
subtitleDownloading: repository.subtitleDownloading,
|
||||
subtitlePaused: repository.subtitlePaused,
|
||||
subtitleDownloadedBytes:
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.transcription,
|
||||
) &&
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.translation,
|
||||
)
|
||||
? repository.subtitleDownloadedBytes
|
||||
: 0,
|
||||
subtitleTotalBytes: repository.catalog
|
||||
.where(
|
||||
(p) => ProcessingResourceRepository.subtitleCapabilities.contains(
|
||||
p.capability,
|
||||
),
|
||||
)
|
||||
.fold(0, (bytes, p) => bytes + p.bytes),
|
||||
subtitleBytesPerSecond:
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.transcription,
|
||||
) &&
|
||||
repository.catalog.any(
|
||||
(p) => p.capability == ProcessingCapability.translation,
|
||||
)
|
||||
? repository.subtitleDownloadBytesPerSecond
|
||||
: 0,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,580 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'processing_resource_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ProcessingResourcesSnapshot {
|
||||
List<ProcessingResourceInstall> get installs;
|
||||
Set<ProcessingCapability> get paused;
|
||||
Map<ProcessingCapability, int> get rates;
|
||||
bool get subtitleDownloading;
|
||||
bool get subtitlePaused;
|
||||
int get subtitleDownloadedBytes;
|
||||
int get subtitleTotalBytes;
|
||||
int get subtitleBytesPerSecond;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ProcessingResourcesSnapshotCopyWith<ProcessingResourcesSnapshot>
|
||||
get copyWith =>
|
||||
_$ProcessingResourcesSnapshotCopyWithImpl<ProcessingResourcesSnapshot>(
|
||||
this as ProcessingResourcesSnapshot,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ProcessingResourcesSnapshot &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.installs,
|
||||
_this.installs,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(other.paused, _this.paused) &&
|
||||
const DeepCollectionEquality().equals(other.rates, _this.rates) &&
|
||||
(identical(other.subtitleDownloading, _this.subtitleDownloading) ||
|
||||
other.subtitleDownloading == _this.subtitleDownloading) &&
|
||||
(identical(other.subtitlePaused, _this.subtitlePaused) ||
|
||||
other.subtitlePaused == _this.subtitlePaused) &&
|
||||
(identical(
|
||||
other.subtitleDownloadedBytes,
|
||||
_this.subtitleDownloadedBytes,
|
||||
) ||
|
||||
other.subtitleDownloadedBytes ==
|
||||
_this.subtitleDownloadedBytes) &&
|
||||
(identical(other.subtitleTotalBytes, _this.subtitleTotalBytes) ||
|
||||
other.subtitleTotalBytes == _this.subtitleTotalBytes) &&
|
||||
(identical(
|
||||
other.subtitleBytesPerSecond,
|
||||
_this.subtitleBytesPerSecond,
|
||||
) ||
|
||||
other.subtitleBytesPerSecond == _this.subtitleBytesPerSecond));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_this.installs),
|
||||
const DeepCollectionEquality().hash(_this.paused),
|
||||
const DeepCollectionEquality().hash(_this.rates),
|
||||
_this.subtitleDownloading,
|
||||
_this.subtitlePaused,
|
||||
_this.subtitleDownloadedBytes,
|
||||
_this.subtitleTotalBytes,
|
||||
_this.subtitleBytesPerSecond,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ProcessingResourcesSnapshot;
|
||||
return 'ProcessingResourcesSnapshot(installs: ${_this.installs}, paused: ${_this.paused}, rates: ${_this.rates}, subtitleDownloading: ${_this.subtitleDownloading}, subtitlePaused: ${_this.subtitlePaused}, subtitleDownloadedBytes: ${_this.subtitleDownloadedBytes}, subtitleTotalBytes: ${_this.subtitleTotalBytes}, subtitleBytesPerSecond: ${_this.subtitleBytesPerSecond})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
factory $ProcessingResourcesSnapshotCopyWith(
|
||||
ProcessingResourcesSnapshot value,
|
||||
$Res Function(ProcessingResourcesSnapshot) _then,
|
||||
) = _$ProcessingResourcesSnapshotCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ProcessingResourcesSnapshotCopyWithImpl<$Res>
|
||||
implements $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
_$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ProcessingResourcesSnapshot _self;
|
||||
final $Res Function(ProcessingResourcesSnapshot) _then;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? installs = null,
|
||||
Object? paused = null,
|
||||
Object? rates = null,
|
||||
Object? subtitleDownloading = null,
|
||||
Object? subtitlePaused = null,
|
||||
Object? subtitleDownloadedBytes = null,
|
||||
Object? subtitleTotalBytes = null,
|
||||
Object? subtitleBytesPerSecond = null,
|
||||
}) {
|
||||
return _then(
|
||||
ProcessingResourcesSnapshot(
|
||||
installs: null == installs
|
||||
? _self.installs
|
||||
: installs // ignore: cast_nullable_to_non_nullable
|
||||
as List<ProcessingResourceInstall>,
|
||||
paused: null == paused
|
||||
? _self.paused
|
||||
: paused // ignore: cast_nullable_to_non_nullable
|
||||
as Set<ProcessingCapability>,
|
||||
rates: null == rates
|
||||
? _self.rates
|
||||
: rates // ignore: cast_nullable_to_non_nullable
|
||||
as Map<ProcessingCapability, int>,
|
||||
subtitleDownloading: null == subtitleDownloading
|
||||
? _self.subtitleDownloading
|
||||
: subtitleDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitlePaused: null == subtitlePaused
|
||||
? _self.subtitlePaused
|
||||
: subtitlePaused // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitleDownloadedBytes: null == subtitleDownloadedBytes
|
||||
? _self.subtitleDownloadedBytes
|
||||
: subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleTotalBytes: null == subtitleTotalBytes
|
||||
? _self.subtitleTotalBytes
|
||||
: subtitleTotalBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleBytesPerSecond: null == subtitleBytesPerSecond
|
||||
? _self.subtitleBytesPerSecond
|
||||
: subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ProcessingResourcesSnapshot].
|
||||
extension ProcessingResourcesSnapshotPatterns on ProcessingResourcesSnapshot {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_ProcessingResourcesSnapshot value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_ProcessingResourcesSnapshot value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_ProcessingResourcesSnapshot value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot():
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProcessingResourcesSnapshot() when $default != null:
|
||||
return $default(
|
||||
_that.installs,
|
||||
_that.paused,
|
||||
_that.rates,
|
||||
_that.subtitleDownloading,
|
||||
_that.subtitlePaused,
|
||||
_that.subtitleDownloadedBytes,
|
||||
_that.subtitleTotalBytes,
|
||||
_that.subtitleBytesPerSecond,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ProcessingResourcesSnapshot implements ProcessingResourcesSnapshot {
|
||||
const _ProcessingResourcesSnapshot({
|
||||
List<ProcessingResourceInstall> installs = const [],
|
||||
Set<ProcessingCapability> paused = const {},
|
||||
Map<ProcessingCapability, int> rates = const {},
|
||||
this.subtitleDownloading = false,
|
||||
this.subtitlePaused = false,
|
||||
this.subtitleDownloadedBytes = 0,
|
||||
this.subtitleTotalBytes = 0,
|
||||
this.subtitleBytesPerSecond = 0,
|
||||
}) : _installs = installs,
|
||||
_paused = paused,
|
||||
_rates = rates;
|
||||
|
||||
final List<ProcessingResourceInstall> _installs;
|
||||
@override
|
||||
@JsonKey()
|
||||
List<ProcessingResourceInstall> get installs {
|
||||
if (_installs is EqualUnmodifiableListView) return _installs;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_installs);
|
||||
}
|
||||
|
||||
final Set<ProcessingCapability> _paused;
|
||||
@override
|
||||
@JsonKey()
|
||||
Set<ProcessingCapability> get paused {
|
||||
if (_paused is EqualUnmodifiableSetView) return _paused;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableSetView(_paused);
|
||||
}
|
||||
|
||||
final Map<ProcessingCapability, int> _rates;
|
||||
@override
|
||||
@JsonKey()
|
||||
Map<ProcessingCapability, int> get rates {
|
||||
if (_rates is EqualUnmodifiableMapView) return _rates;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableMapView(_rates);
|
||||
}
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool subtitleDownloading;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool subtitlePaused;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleDownloadedBytes;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleTotalBytes;
|
||||
@override
|
||||
@JsonKey()
|
||||
final int subtitleBytesPerSecond;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ProcessingResourcesSnapshotCopyWith<_ProcessingResourcesSnapshot>
|
||||
get copyWith =>
|
||||
__$ProcessingResourcesSnapshotCopyWithImpl<_ProcessingResourcesSnapshot>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ProcessingResourcesSnapshot &&
|
||||
const DeepCollectionEquality().equals(other.installs, _installs) &&
|
||||
const DeepCollectionEquality().equals(other.paused, _paused) &&
|
||||
const DeepCollectionEquality().equals(other.rates, _rates) &&
|
||||
(identical(other.subtitleDownloading, subtitleDownloading) ||
|
||||
other.subtitleDownloading == subtitleDownloading) &&
|
||||
(identical(other.subtitlePaused, subtitlePaused) ||
|
||||
other.subtitlePaused == subtitlePaused) &&
|
||||
(identical(
|
||||
other.subtitleDownloadedBytes,
|
||||
subtitleDownloadedBytes,
|
||||
) ||
|
||||
other.subtitleDownloadedBytes == subtitleDownloadedBytes) &&
|
||||
(identical(other.subtitleTotalBytes, subtitleTotalBytes) ||
|
||||
other.subtitleTotalBytes == subtitleTotalBytes) &&
|
||||
(identical(other.subtitleBytesPerSecond, subtitleBytesPerSecond) ||
|
||||
other.subtitleBytesPerSecond == subtitleBytesPerSecond));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_installs),
|
||||
const DeepCollectionEquality().hash(_paused),
|
||||
const DeepCollectionEquality().hash(_rates),
|
||||
subtitleDownloading,
|
||||
subtitlePaused,
|
||||
subtitleDownloadedBytes,
|
||||
subtitleTotalBytes,
|
||||
subtitleBytesPerSecond,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ProcessingResourcesSnapshot(installs: $installs, paused: $paused, rates: $rates, subtitleDownloading: $subtitleDownloading, subtitlePaused: $subtitlePaused, subtitleDownloadedBytes: $subtitleDownloadedBytes, subtitleTotalBytes: $subtitleTotalBytes, subtitleBytesPerSecond: $subtitleBytesPerSecond)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ProcessingResourcesSnapshotCopyWith<$Res>
|
||||
implements $ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
factory _$ProcessingResourcesSnapshotCopyWith(
|
||||
_ProcessingResourcesSnapshot value,
|
||||
$Res Function(_ProcessingResourcesSnapshot) _then,
|
||||
) = __$ProcessingResourcesSnapshotCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ProcessingResourceInstall> installs,
|
||||
Set<ProcessingCapability> paused,
|
||||
Map<ProcessingCapability, int> rates,
|
||||
bool subtitleDownloading,
|
||||
bool subtitlePaused,
|
||||
int subtitleDownloadedBytes,
|
||||
int subtitleTotalBytes,
|
||||
int subtitleBytesPerSecond,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ProcessingResourcesSnapshotCopyWithImpl<$Res>
|
||||
implements _$ProcessingResourcesSnapshotCopyWith<$Res> {
|
||||
__$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ProcessingResourcesSnapshot _self;
|
||||
final $Res Function(_ProcessingResourcesSnapshot) _then;
|
||||
|
||||
/// Create a copy of ProcessingResourcesSnapshot
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? installs = null,
|
||||
Object? paused = null,
|
||||
Object? rates = null,
|
||||
Object? subtitleDownloading = null,
|
||||
Object? subtitlePaused = null,
|
||||
Object? subtitleDownloadedBytes = null,
|
||||
Object? subtitleTotalBytes = null,
|
||||
Object? subtitleBytesPerSecond = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ProcessingResourcesSnapshot(
|
||||
installs: null == installs
|
||||
? _self._installs
|
||||
: installs // ignore: cast_nullable_to_non_nullable
|
||||
as List<ProcessingResourceInstall>,
|
||||
paused: null == paused
|
||||
? _self._paused
|
||||
: paused // ignore: cast_nullable_to_non_nullable
|
||||
as Set<ProcessingCapability>,
|
||||
rates: null == rates
|
||||
? _self._rates
|
||||
: rates // ignore: cast_nullable_to_non_nullable
|
||||
as Map<ProcessingCapability, int>,
|
||||
subtitleDownloading: null == subtitleDownloading
|
||||
? _self.subtitleDownloading
|
||||
: subtitleDownloading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitlePaused: null == subtitlePaused
|
||||
? _self.subtitlePaused
|
||||
: subtitlePaused // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
subtitleDownloadedBytes: null == subtitleDownloadedBytes
|
||||
? _self.subtitleDownloadedBytes
|
||||
: subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleTotalBytes: null == subtitleTotalBytes
|
||||
? _self.subtitleTotalBytes
|
||||
: subtitleTotalBytes // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
subtitleBytesPerSecond: null == subtitleBytesPerSecond
|
||||
? _self.subtitleBytesPerSecond
|
||||
: subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'processing_resource_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
@ProviderFor(ProcessingResources)
|
||||
final processingResourcesProvider = ProcessingResourcesFamily._();
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
final class ProcessingResourcesProvider
|
||||
extends
|
||||
$NotifierProvider<ProcessingResources, ProcessingResourcesSnapshot> {
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
ProcessingResourcesProvider._({
|
||||
required ProcessingResourcesFamily super.from,
|
||||
required ProcessingResourceRepository super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'processingResourcesProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$processingResourcesHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'processingResourcesProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ProcessingResources create() => ProcessingResources();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ProcessingResourcesSnapshot value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ProcessingResourcesSnapshot>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ProcessingResourcesProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$processingResourcesHash() =>
|
||||
r'd39d92ad2c74b9be524152b3e946e6f1b43de7b0';
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
final class ProcessingResourcesFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ProcessingResources,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourceRepository
|
||||
> {
|
||||
ProcessingResourcesFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'processingResourcesProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
ProcessingResourcesProvider call(ProcessingResourceRepository repository) =>
|
||||
ProcessingResourcesProvider._(argument: repository, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'processingResourcesProvider';
|
||||
}
|
||||
|
||||
/// Resource ownership stays in the repository; observers receive value snapshots.
|
||||
|
||||
abstract class _$ProcessingResources
|
||||
extends $Notifier<ProcessingResourcesSnapshot> {
|
||||
late final _$args = ref.$arg as ProcessingResourceRepository;
|
||||
ProcessingResourceRepository get repository => _$args;
|
||||
|
||||
ProcessingResourcesSnapshot build(ProcessingResourceRepository repository);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<ProcessingResourcesSnapshot, ProcessingResourcesSnapshot>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
ProcessingResourcesSnapshot,
|
||||
ProcessingResourcesSnapshot
|
||||
>,
|
||||
ProcessingResourcesSnapshot,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
typedef _MediaKey = ({Uri uri, TrackSelection? trackSelection, bool isImage});
|
||||
typedef _FrameKey = ({
|
||||
Uri uri,
|
||||
TrackSelection? trackSelection,
|
||||
bool isImage,
|
||||
int tick,
|
||||
int maximumEdge,
|
||||
});
|
||||
typedef _CachedFrame = ({_FrameKey key, ui.Image image});
|
||||
|
||||
/// One viewport's runtime requests and decoded-image cache; never project data.
|
||||
/// Source URIs identify frames across provisional and imported asset IDs.
|
||||
class RuntimeTimelineThumbnails extends ChangeNotifier
|
||||
implements TimelineThumbnails {
|
||||
RuntimeTimelineThumbnails({
|
||||
required this.resolveMedia,
|
||||
this.resolveTrackSelection,
|
||||
CutdexRuntime? runtime,
|
||||
this.maximumEntries = 256,
|
||||
this.maximumDecodedBytes = 64 * 1024 * 1024,
|
||||
this.maximumConcurrent = 2,
|
||||
this.maximumBatchSize = 4,
|
||||
}) : _runtime = runtime ?? CutdexRuntime() {
|
||||
if (maximumEntries <= 0 ||
|
||||
maximumDecodedBytes <= 0 ||
|
||||
maximumConcurrent <= 0 ||
|
||||
maximumBatchSize <= 0 ||
|
||||
maximumBatchSize > 128) {
|
||||
throw ArgumentError('Thumbnail limits must be positive and bounded');
|
||||
}
|
||||
}
|
||||
|
||||
static const _resolutionTiers = <int>[
|
||||
64,
|
||||
128,
|
||||
192,
|
||||
256,
|
||||
384,
|
||||
512,
|
||||
768,
|
||||
1024,
|
||||
1536,
|
||||
2048,
|
||||
];
|
||||
|
||||
/// Selects the largest power-of-two source-tick interval covered by a tile.
|
||||
static int samplingIntervalFor(int sourceSpanTicks) {
|
||||
if (sourceSpanTicks <= 0) {
|
||||
throw ArgumentError.value(sourceSpanTicks, 'sourceSpanTicks');
|
||||
}
|
||||
return 1 << (sourceSpanTicks.bitLength - 1);
|
||||
}
|
||||
|
||||
/// Snaps nearby layout centers onto a cache-stable source-time grid. Bounds
|
||||
/// describe the media asset, not its current edit window; an unknown upper
|
||||
/// media boundary leaves the grid uncapped.
|
||||
static int sampledTickFor({
|
||||
required int sourceTick,
|
||||
required int sourceSpanTicks,
|
||||
required int minimumTick,
|
||||
required int? maximumTickExclusive,
|
||||
}) {
|
||||
if (sourceTick < 0 ||
|
||||
sourceSpanTicks <= 0 ||
|
||||
minimumTick < 0 ||
|
||||
(maximumTickExclusive != null && maximumTickExclusive <= minimumTick)) {
|
||||
throw ArgumentError('Invalid thumbnail sampling range');
|
||||
}
|
||||
final interval = samplingIntervalFor(sourceSpanTicks);
|
||||
final desired = maximumTickExclusive == null
|
||||
? math.max(minimumTick, sourceTick)
|
||||
: sourceTick.clamp(minimumTick, maximumTickExclusive - 1);
|
||||
final lower = desired ~/ interval * interval;
|
||||
final upper = lower + interval;
|
||||
var sampled = desired - lower < upper - desired ? lower : upper;
|
||||
if (sampled < minimumTick) return minimumTick;
|
||||
if (maximumTickExclusive != null && sampled >= maximumTickExclusive) {
|
||||
final lastGridTick = (maximumTickExclusive - 1) ~/ interval * interval;
|
||||
sampled = lastGridTick >= minimumTick
|
||||
? lastGridTick
|
||||
: maximumTickExclusive - 1;
|
||||
}
|
||||
return sampled;
|
||||
}
|
||||
|
||||
/// Quantizes painted device pixels so tiny layout changes reuse cache data.
|
||||
static int maximumEdgeFor({
|
||||
required ui.Size logicalSize,
|
||||
required double devicePixelRatio,
|
||||
}) {
|
||||
if (!logicalSize.width.isFinite ||
|
||||
!logicalSize.height.isFinite ||
|
||||
logicalSize.width <= 0 ||
|
||||
logicalSize.height <= 0 ||
|
||||
!devicePixelRatio.isFinite ||
|
||||
devicePixelRatio <= 0) {
|
||||
throw ArgumentError(
|
||||
'Thumbnail paint geometry must be finite and positive',
|
||||
);
|
||||
}
|
||||
final requested =
|
||||
(math.max(logicalSize.width, logicalSize.height) * devicePixelRatio)
|
||||
.ceil();
|
||||
for (final tier in _resolutionTiers) {
|
||||
if (requested <= tier) return tier;
|
||||
}
|
||||
return _resolutionTiers.last;
|
||||
}
|
||||
|
||||
final MediaReference? Function(PayloadRef) resolveMedia;
|
||||
final TrackSelection? Function(PayloadRef)? resolveTrackSelection;
|
||||
final CutdexRuntime _runtime;
|
||||
final int maximumEntries;
|
||||
final int maximumDecodedBytes;
|
||||
final int maximumConcurrent;
|
||||
final int maximumBatchSize;
|
||||
final _cache = <_FrameKey, ui.Image?>{};
|
||||
final _mediaFrames = <_MediaKey, Set<_FrameKey>>{};
|
||||
|
||||
_MediaKey _mediaKey(_FrameKey key) =>
|
||||
(uri: key.uri, trackSelection: key.trackSelection, isImage: key.isImage);
|
||||
final _aspectRatios = <_MediaKey, double>{};
|
||||
final _wanted = <_FrameKey>{};
|
||||
final _used = <_FrameKey>{};
|
||||
final _inFlight = <_FrameKey>{};
|
||||
var _decodedBytes = 0;
|
||||
var _activeLoads = 0;
|
||||
var _scheduled = false;
|
||||
var _disposed = false;
|
||||
|
||||
@override
|
||||
void beginFrame() {
|
||||
_wanted.clear();
|
||||
_used.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
double? aspectRatioFor(ElementRecord element) {
|
||||
if (_disposed || element.payloadRef == null) return null;
|
||||
final media = resolveMedia(element.payloadRef!);
|
||||
if (media == null) return null;
|
||||
return _aspectRatios[(
|
||||
uri: media.uri,
|
||||
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
||||
isImage: media.isImage,
|
||||
)];
|
||||
}
|
||||
|
||||
@override
|
||||
ui.Image? imageFor(
|
||||
ElementRecord element,
|
||||
int sourceTick, {
|
||||
required int sourceSpanTicks,
|
||||
required ui.Size logicalSize,
|
||||
required double devicePixelRatio,
|
||||
}) {
|
||||
if (_disposed ||
|
||||
sourceTick < 0 ||
|
||||
sourceSpanTicks <= 0 ||
|
||||
element.sourceStart < 0 ||
|
||||
element.duration <= 0 ||
|
||||
element.payloadRef == null) {
|
||||
return null;
|
||||
}
|
||||
final media = resolveMedia(element.payloadRef!);
|
||||
if (media == null) return null;
|
||||
final sampledTick = media.isImage
|
||||
? 0
|
||||
: sampledTickFor(
|
||||
sourceTick: sourceTick,
|
||||
sourceSpanTicks: sourceSpanTicks,
|
||||
minimumTick: math.max(0, element.mediaStart ?? 0),
|
||||
maximumTickExclusive: element.mediaStart == null
|
||||
? null
|
||||
: element.mediaStart! + element.mediaDuration!,
|
||||
);
|
||||
final key = (
|
||||
uri: media.uri,
|
||||
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
||||
isImage: media.isImage,
|
||||
tick: sampledTick,
|
||||
maximumEdge: maximumEdgeFor(
|
||||
logicalSize: logicalSize,
|
||||
devicePixelRatio: devicePixelRatio,
|
||||
),
|
||||
);
|
||||
final fallback =
|
||||
_bestCached(key, touch: true) ??
|
||||
_nearestCached(
|
||||
key,
|
||||
maximumTickDistance: math.max(
|
||||
sourceSpanTicks,
|
||||
samplingIntervalFor(sourceSpanTicks),
|
||||
),
|
||||
touch: true,
|
||||
);
|
||||
if (!_wanted.contains(key) && _wanted.length >= maximumEntries) {
|
||||
if (fallback != null) _used.add(fallback.key);
|
||||
return fallback?.image;
|
||||
}
|
||||
_wanted.add(key);
|
||||
if (fallback != null) _used.add(fallback.key);
|
||||
return fallback?.image;
|
||||
}
|
||||
|
||||
@override
|
||||
void endFrame() {
|
||||
if (_disposed || _scheduled) return;
|
||||
_scheduled = true;
|
||||
scheduleMicrotask(() {
|
||||
_scheduled = false;
|
||||
_drain();
|
||||
});
|
||||
}
|
||||
|
||||
void _drain() {
|
||||
if (_disposed) return;
|
||||
while (_activeLoads < maximumConcurrent) {
|
||||
_FrameKey? seed;
|
||||
for (final key in _wanted) {
|
||||
if (_needsLoad(key)) {
|
||||
seed = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (seed == null) return;
|
||||
final batch = <_FrameKey>[];
|
||||
final mediaKey = _mediaKey(seed);
|
||||
final firstForMedia =
|
||||
!_mediaFrames.containsKey(mediaKey) &&
|
||||
!_inFlight.any((key) => _mediaKey(key) == mediaKey);
|
||||
final batchLimit = firstForMedia ? 1 : maximumBatchSize;
|
||||
for (final key in _wanted) {
|
||||
if (batch.length >= batchLimit) break;
|
||||
if (key.uri == seed.uri &&
|
||||
key.trackSelection == seed.trackSelection &&
|
||||
key.isImage == seed.isImage &&
|
||||
key.maximumEdge == seed.maximumEdge &&
|
||||
_needsLoad(key)) {
|
||||
batch.add(key);
|
||||
}
|
||||
}
|
||||
_inFlight.addAll(batch);
|
||||
_activeLoads++;
|
||||
unawaited(_loadBatch(batch));
|
||||
}
|
||||
}
|
||||
|
||||
bool _needsLoad(_FrameKey key) {
|
||||
if (_inFlight.contains(key) || _cache.containsKey(key)) return false;
|
||||
final cached = _bestCached(key);
|
||||
return cached == null || cached.key.maximumEdge < key.maximumEdge;
|
||||
}
|
||||
|
||||
Future<void> _loadBatch(List<_FrameKey> keys) async {
|
||||
final decoded = <_FrameKey, ui.Image?>{};
|
||||
var aspectChanged = false;
|
||||
var failed = false;
|
||||
try {
|
||||
final seed = keys.first;
|
||||
final thumbnails = await _runtime.thumbnails(
|
||||
ThumbnailBatchRequest(
|
||||
media: MediaReference(
|
||||
id: seed.uri.toString(),
|
||||
uri: seed.uri,
|
||||
isImage: seed.isImage,
|
||||
),
|
||||
trackSelection:
|
||||
seed.trackSelection ?? const TrackSelection.defaultTrack(),
|
||||
times: [
|
||||
for (final key in keys)
|
||||
MediaTime(key.tick, TimelineClock.ticksPerSecond),
|
||||
],
|
||||
maximumWidth: seed.maximumEdge,
|
||||
maximumHeight: seed.maximumEdge,
|
||||
tolerance: MediaTime(1, 4),
|
||||
quality: 0.72,
|
||||
),
|
||||
);
|
||||
final decodeOrder = <int>[
|
||||
for (var index = 0; index < keys.length; index++)
|
||||
if (_wanted.contains(keys[index])) index,
|
||||
for (var index = 0; index < keys.length; index++)
|
||||
if (!_wanted.contains(keys[index])) index,
|
||||
];
|
||||
for (final index in decodeOrder) {
|
||||
final key = keys[index];
|
||||
final thumbnail = thumbnails[index];
|
||||
if (_disposed) break;
|
||||
aspectChanged =
|
||||
_rememberAspect(key, thumbnail.width, thumbnail.height) ||
|
||||
aspectChanged;
|
||||
try {
|
||||
final codec = await ui.instantiateImageCodec(thumbnail.data);
|
||||
try {
|
||||
decoded[key] = (await codec.getNextFrame()).image;
|
||||
} finally {
|
||||
codec.dispose();
|
||||
}
|
||||
} catch (_) {
|
||||
decoded[key] = null;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
failed = true;
|
||||
} finally {
|
||||
_inFlight.removeAll(keys);
|
||||
_activeLoads--;
|
||||
if (_disposed) {
|
||||
for (final image in decoded.values) {
|
||||
image?.dispose();
|
||||
}
|
||||
} else {
|
||||
var hasNewImage = false;
|
||||
if (failed) {
|
||||
for (final image in decoded.values) {
|
||||
image?.dispose();
|
||||
}
|
||||
for (final key in keys) {
|
||||
if (_wanted.contains(key)) _store(key, null);
|
||||
}
|
||||
} else {
|
||||
for (final entry in decoded.entries) {
|
||||
_store(entry.key, entry.value);
|
||||
if (_wanted.contains(entry.key) && entry.value != null) {
|
||||
hasNewImage = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasNewImage || aspectChanged) notifyListeners();
|
||||
_drain();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _rememberAspect(_FrameKey key, int width, int height) {
|
||||
if (width <= 0 || height <= 0) return false;
|
||||
final media = (
|
||||
uri: key.uri,
|
||||
trackSelection: key.trackSelection,
|
||||
isImage: key.isImage,
|
||||
);
|
||||
final value = width / height;
|
||||
final previous = _aspectRatios[media];
|
||||
if (previous != null && (previous - value).abs() < 0.0001) return false;
|
||||
_aspectRatios[media] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
_CachedFrame? _bestCached(_FrameKey desired, {bool touch = false}) {
|
||||
final exact = _cache[desired];
|
||||
if (exact != null) {
|
||||
if (touch) _touch(desired);
|
||||
return (key: desired, image: exact);
|
||||
}
|
||||
_CachedFrame? adequate;
|
||||
_CachedFrame? fallback;
|
||||
for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) {
|
||||
final image = _cache[key];
|
||||
if (image == null ||
|
||||
key.uri != desired.uri ||
|
||||
key.trackSelection != desired.trackSelection ||
|
||||
key.isImage != desired.isImage ||
|
||||
key.tick != desired.tick) {
|
||||
continue;
|
||||
}
|
||||
final candidate = (key: key, image: image);
|
||||
if (key.maximumEdge >= desired.maximumEdge) {
|
||||
if (adequate == null || key.maximumEdge < adequate.key.maximumEdge) {
|
||||
adequate = candidate;
|
||||
}
|
||||
} else if (fallback == null ||
|
||||
key.maximumEdge > fallback.key.maximumEdge) {
|
||||
fallback = candidate;
|
||||
}
|
||||
}
|
||||
final result = adequate ?? fallback;
|
||||
if (touch && result != null) _touch(result.key);
|
||||
return result;
|
||||
}
|
||||
|
||||
_CachedFrame? _nearestCached(
|
||||
_FrameKey desired, {
|
||||
required int maximumTickDistance,
|
||||
bool touch = false,
|
||||
}) {
|
||||
_CachedFrame? result;
|
||||
var bestDistance = maximumTickDistance + 1;
|
||||
for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) {
|
||||
final image = _cache[key];
|
||||
if (image == null || key.uri != desired.uri) {
|
||||
continue;
|
||||
}
|
||||
if (key.trackSelection != desired.trackSelection ||
|
||||
key.isImage != desired.isImage) {
|
||||
continue;
|
||||
}
|
||||
final distance = (key.tick - desired.tick).abs();
|
||||
if (distance > maximumTickDistance || distance > bestDistance) continue;
|
||||
if (distance == bestDistance &&
|
||||
result != null &&
|
||||
key.maximumEdge <= result.key.maximumEdge) {
|
||||
continue;
|
||||
}
|
||||
result = (key: key, image: image);
|
||||
bestDistance = distance;
|
||||
}
|
||||
if (touch && result != null) _touch(result.key);
|
||||
return result;
|
||||
}
|
||||
|
||||
void _store(_FrameKey key, ui.Image? image) {
|
||||
if (_cache.containsKey(key)) {
|
||||
final previous = _cache.remove(key);
|
||||
if (previous != null) {
|
||||
_decodedBytes -= _imageBytes(previous);
|
||||
if (!identical(previous, image)) previous.dispose();
|
||||
}
|
||||
}
|
||||
_cache[key] = image;
|
||||
(_mediaFrames[_mediaKey(key)] ??= <_FrameKey>{}).add(key);
|
||||
if (image != null) _decodedBytes += _imageBytes(image);
|
||||
_trimCache();
|
||||
}
|
||||
|
||||
void _touch(_FrameKey key) {
|
||||
if (!_cache.containsKey(key)) return;
|
||||
final image = _cache.remove(key);
|
||||
_cache[key] = image;
|
||||
}
|
||||
|
||||
void _trimCache() {
|
||||
while ((_cache.length > maximumEntries ||
|
||||
_decodedBytes > maximumDecodedBytes) &&
|
||||
_cache.length > 1) {
|
||||
_FrameKey? victim;
|
||||
for (final key in _cache.keys) {
|
||||
if (!_wanted.contains(key) &&
|
||||
!_used.contains(key) &&
|
||||
!_inFlight.contains(key)) {
|
||||
victim = key;
|
||||
break;
|
||||
}
|
||||
}
|
||||
victim ??= _cache.keys.firstWhere(
|
||||
(key) => !_inFlight.contains(key),
|
||||
orElse: () => _cache.keys.first,
|
||||
);
|
||||
final image = _cache.remove(victim);
|
||||
final media = _mediaKey(victim);
|
||||
final frames = _mediaFrames[media]!;
|
||||
frames.remove(victim);
|
||||
if (frames.isEmpty) _mediaFrames.remove(media);
|
||||
if (image != null) {
|
||||
_decodedBytes -= _imageBytes(image);
|
||||
image.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int _imageBytes(ui.Image image) => image.width * image.height * 4;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_wanted.clear();
|
||||
_used.clear();
|
||||
_aspectRatios.clear();
|
||||
for (final image in _cache.values) {
|
||||
image?.dispose();
|
||||
}
|
||||
_cache.clear();
|
||||
_mediaFrames.clear();
|
||||
_decodedBytes = 0;
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart' show ClipAudioGain;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
typedef _WaveformKey = ({String id, Uri uri, TrackSelection? trackSelection});
|
||||
|
||||
/// Source-level cache shared by clips on one timeline, independent of zoom.
|
||||
class RuntimeTimelineWaveforms extends ChangeNotifier
|
||||
implements TimelineWaveforms {
|
||||
RuntimeTimelineWaveforms({
|
||||
required this.resolveMedia,
|
||||
this.resolveTrackSelection,
|
||||
this.resolveGain,
|
||||
this.gainChanges,
|
||||
CutdexRuntime? runtime,
|
||||
this.maximumEntries = 16,
|
||||
this.maximumConcurrent = 2,
|
||||
}) : _runtime = runtime ?? CutdexRuntime() {
|
||||
if (maximumEntries < 1 || maximumConcurrent < 1) {
|
||||
throw ArgumentError('Waveform limits must be positive');
|
||||
}
|
||||
gainChanges?.addListener(_gainChanged);
|
||||
}
|
||||
|
||||
final double Function(ElementRecord)? resolveGain;
|
||||
final Listenable? gainChanges;
|
||||
void _gainChanged() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
final MediaReference? Function(PayloadRef) resolveMedia;
|
||||
final TrackSelection? Function(PayloadRef)? resolveTrackSelection;
|
||||
final CutdexRuntime _runtime;
|
||||
|
||||
/// Warm-cache target. Visible sources remain pinned until they leave the view.
|
||||
final int maximumEntries;
|
||||
final int maximumConcurrent;
|
||||
final _cache = <_WaveformKey, TimelineWaveform?>{};
|
||||
final _wanted = <_WaveformKey>{};
|
||||
final _inFlight = <_WaveformKey>{};
|
||||
final _attempts = <_WaveformKey, int>{};
|
||||
final _retries = <_WaveformKey, Timer>{};
|
||||
Future<bool>? _supported;
|
||||
var _scheduled = false;
|
||||
var _disposed = false;
|
||||
|
||||
@override
|
||||
void beginFrame() => _wanted.clear();
|
||||
|
||||
@override
|
||||
bool hasAudioFor(ElementRecord element) =>
|
||||
!_disposed &&
|
||||
element.payloadRef != null &&
|
||||
resolveMedia(element.payloadRef!) != null;
|
||||
|
||||
@override
|
||||
TimelineWaveform? waveformFor(ElementRecord element) {
|
||||
if (_disposed ||
|
||||
element.payloadRef == null ||
|
||||
ClipAudioGain.isDetached(element)) {
|
||||
return null;
|
||||
}
|
||||
final media = resolveMedia(element.payloadRef!);
|
||||
if (media == null) return null;
|
||||
final key = (
|
||||
id: media.id,
|
||||
uri: media.uri,
|
||||
trackSelection: resolveTrackSelection?.call(element.payloadRef!),
|
||||
);
|
||||
_wanted.add(key);
|
||||
if (!_cache.containsKey(key)) return null;
|
||||
final value = _cache.remove(key);
|
||||
_cache[key] = value;
|
||||
if (value == null || resolveGain == null) return value;
|
||||
return TimelineWaveform(
|
||||
sampleRate: value.sampleRate,
|
||||
sourceStartSeconds: value.sourceStartSeconds,
|
||||
frameCount: value.frameCount,
|
||||
levels: value.levels,
|
||||
amplitudeScale: resolveGain!(element),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void endFrame() {
|
||||
if (_disposed || _scheduled) return;
|
||||
_scheduled = true;
|
||||
scheduleMicrotask(() {
|
||||
_scheduled = false;
|
||||
for (final key in _retries.keys.toList()) {
|
||||
if (!_wanted.contains(key)) {
|
||||
_retries.remove(key)!.cancel();
|
||||
_attempts.remove(key);
|
||||
}
|
||||
}
|
||||
_trimCache();
|
||||
_drain();
|
||||
});
|
||||
}
|
||||
|
||||
void _drain() {
|
||||
if (_disposed) return;
|
||||
for (final key in _wanted) {
|
||||
if (_inFlight.length >= maximumConcurrent) break;
|
||||
if (_cache.containsKey(key) ||
|
||||
_inFlight.contains(key) ||
|
||||
_retries.containsKey(key)) {
|
||||
continue;
|
||||
}
|
||||
_inFlight.add(key);
|
||||
unawaited(_load(key));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _load(_WaveformKey key) async {
|
||||
TimelineWaveform? value;
|
||||
final attempt = (_attempts[key] ?? 0) + 1;
|
||||
_attempts[key] = attempt;
|
||||
var retry = false;
|
||||
try {
|
||||
final supported = await (_supported ??= _checkSupport());
|
||||
if (supported && !_disposed) {
|
||||
final result = await _runtime.waveform(
|
||||
WaveformRequest(
|
||||
media: MediaReference(id: key.id, uri: key.uri),
|
||||
trackSelection:
|
||||
key.trackSelection ?? const TrackSelection.defaultTrack(),
|
||||
),
|
||||
);
|
||||
value = TimelineWaveform(
|
||||
sampleRate: result.sampleRate,
|
||||
sourceStartSeconds: result.sourceStartSeconds,
|
||||
frameCount: result.frameCount,
|
||||
levels: List.unmodifiable([
|
||||
for (final level in result.levels)
|
||||
TimelineWaveformLevel(
|
||||
samplesPerBucket: level.samplesPerBucket,
|
||||
channels: level.channels,
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
} on RuntimeException catch (error) {
|
||||
retry = error.retryable && attempt < 3;
|
||||
} catch (_) {
|
||||
// Permanent failures stay cached; malformed sources must not loop.
|
||||
} finally {
|
||||
_inFlight.remove(key);
|
||||
if (!_disposed) {
|
||||
if (retry && _wanted.contains(key)) {
|
||||
_retries[key] = Timer(Duration(seconds: 1 << (attempt - 1)), () {
|
||||
_retries.remove(key);
|
||||
_drain();
|
||||
});
|
||||
} else {
|
||||
_attempts.remove(key);
|
||||
if (!retry) _cache[key] = value;
|
||||
}
|
||||
_trimCache();
|
||||
if (value != null && _wanted.contains(key)) notifyListeners();
|
||||
_drain();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _checkSupport() async {
|
||||
try {
|
||||
final capabilities = await _runtime.capabilities();
|
||||
return capabilities.query('media.waveform') ==
|
||||
CapabilityAvailability.available;
|
||||
} catch (_) {
|
||||
_supported = null;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
void _trimCache() {
|
||||
for (final key in _cache.keys.toList()) {
|
||||
if (_cache.length <= maximumEntries) break;
|
||||
if (!_wanted.contains(key)) _cache.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
gainChanges?.removeListener(_gainChanged);
|
||||
_wanted.clear();
|
||||
_cache.clear();
|
||||
for (final timer in _retries.values) {
|
||||
timer.cancel();
|
||||
}
|
||||
_retries.clear();
|
||||
_attempts.clear();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/tools.dart';
|
||||
|
||||
import 'editor_command_host.dart';
|
||||
|
||||
/// Owns the mutable workspace/dispatcher lifecycle without knowing any protocol.
|
||||
class EditorToolRegistry {
|
||||
EditorToolRegistry(EditorSession session)
|
||||
: owner = session,
|
||||
_session = session,
|
||||
dynamicWorkspaces = false,
|
||||
workspaces = Map.unmodifiable({
|
||||
for (final sequence in session.document.sequences)
|
||||
jsonEncode([session.document.id, sequence.id.value]): editorToolsFor(
|
||||
session,
|
||||
sequence.id,
|
||||
),
|
||||
});
|
||||
|
||||
EditorToolRegistry.application(EditorCommandHost host)
|
||||
: owner = Object(),
|
||||
dynamicWorkspaces = true,
|
||||
workspaces = {'application': EditorToolDispatcher(host: host)};
|
||||
|
||||
final bool dynamicWorkspaces;
|
||||
final Object owner;
|
||||
final Map<String, EditorToolDispatcher> workspaces;
|
||||
EditorSession? _session;
|
||||
int _generation = 0;
|
||||
|
||||
void attach(EditorSession? session, {String? projectId}) {
|
||||
if (!dynamicWorkspaces || identical(_session, session)) return;
|
||||
for (final id
|
||||
in workspaces.keys.where((id) => id != 'application').toList()) {
|
||||
unawaited(releaseEditorTools(_session!, workspaces.remove(id)!));
|
||||
}
|
||||
_session = session;
|
||||
if (session == null) return;
|
||||
final generation = ++_generation;
|
||||
for (final sequence in session.document.sequences) {
|
||||
workspaces[jsonEncode([
|
||||
projectId,
|
||||
session.document.id,
|
||||
sequence.id.value,
|
||||
generation,
|
||||
])] = editorToolsFor(
|
||||
session,
|
||||
sequence.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> dispose() async {
|
||||
for (final entry in workspaces.entries.toList()) {
|
||||
if (_session != null && entry.key != 'application') {
|
||||
await releaseEditorTools(_session!, entry.value);
|
||||
} else {
|
||||
await entry.value.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user