From 54c28964186ad6f0e30d4e90047245c5308facf9 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Wed, 25 Nov 2026 18:47:56 +0800 Subject: [PATCH 1/3] [feat] character-replacement: Save and publish segment plans Signed-off-by: Weiming Liao --- .../application/creation_commands.py | 5 + .../creation_segment_run_publication.py | 162 +++ .../opendirector/domain/creation/canvas.py | 60 + .../opendirector/domain/creation/commands.py | 13 +- .../domain/creation/segment_run.py | 124 ++ .../domain/creation/validation.py | 32 +- .../infrastructure/creation_publication.py | 3 +- packages/core/src/opendirector/media/probe.py | 20 + src/contracts/creation.schema.json | 1256 ++++++++++++++++- src/contracts/generated.ts | 154 +- tests/test_creation_api.py | 76 + 11 files changed, 1861 insertions(+), 44 deletions(-) create mode 100644 packages/core/src/opendirector/application/creation_segment_run_publication.py create mode 100644 packages/core/src/opendirector/domain/creation/segment_run.py diff --git a/packages/core/src/opendirector/application/creation_commands.py b/packages/core/src/opendirector/application/creation_commands.py index e3d9bb72d..d0e79fc81 100644 --- a/packages/core/src/opendirector/application/creation_commands.py +++ b/packages/core/src/opendirector/application/creation_commands.py @@ -6,6 +6,7 @@ from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas from opendirector.application.creation_history import CreationHistory +from opendirector.application.creation_segment_run_publication import publish_segment_plan, save_segment_plan from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.projects import ProjectError, project_name from opendirector.ports.dispatch import register_command_dispatcher @@ -27,6 +28,10 @@ def execute(self, projects, command, *, session=None, source='ui', imported_from command, session=session, source=source, imported_from=imported_from) if imported_from is not None: raise ProjectError('只有素材导入可以声明归档来源。', 400, code='invalid_input') + if command.type == 'group.saveRunPlan': + return save_segment_plan(projects, command, session=session, source=source) + if command.type == 'group.publishRun': + return publish_segment_plan(projects, command, session=session, source=source) if command.type == 'project.create': return projects._create(command, source) if command.type in _HISTORY_COMMANDS: diff --git a/packages/core/src/opendirector/application/creation_segment_run_publication.py b/packages/core/src/opendirector/application/creation_segment_run_publication.py new file mode 100644 index 000000000..5692bcb69 --- /dev/null +++ b/packages/core/src/opendirector/application/creation_segment_run_publication.py @@ -0,0 +1,162 @@ +"""Save and publish segment plans on existing canvas groups.""" + +from pathlib import Path +from shutil import copyfileobj +from tempfile import TemporaryDirectory +from typing import TYPE_CHECKING +from uuid import uuid4, uuid5 + +from opendirector.application.creation_assets import CreationAssets +from opendirector.application.creation_canvas import asset_ref, visible_item_ids +from opendirector.domain.creation.assets import Asset, AssetProvenance +from opendirector.domain.creation.canvas import GroupCanvasItem, TextCanvasItem +from opendirector.domain.creation.commands import Command, CommandReceipt, GroupPlanDraft +from opendirector.domain.creation.project import ProjectSnapshot +from opendirector.domain.creation.validation import ContractError +from opendirector.domain.projects import ProjectError +from opendirector.media.probe import count_video_frames +from opendirector.ports.files import AssetFileWrite +from opendirector.ports.gateway import gateway + +if TYPE_CHECKING: + from opendirector.infrastructure.creation_projects import CreationProjects + + +def validate_plan(snapshot: ProjectSnapshot, payload: GroupPlanDraft) -> GroupCanvasItem: + items = {item.id: item for item in snapshot.canvasItems} + group = items.get(payload.groupId) + if not isinstance(group, GroupCanvasItem) or group.runPlan is not None or group.locked or group.parentId or not group.visible: + raise ContractError('role_restricted', '请选择可见且未锁定的草稿分组。', payload.groupId) + + source = next((asset for asset in snapshot.assets if asset.id == payload.plan.source.assetId), None) + if source is None or asset_ref(source) != payload.plan.source: + raise ContractError('reference_invalid', '计划源片已变更或无法读取。', payload.plan.source.assetId) + if source.metadata.frameRate is not None and source.metadata.frameRate != payload.plan.fps: + raise ContractError('reference_invalid', '计划帧率与源片不一致。', source.id) + + entries = payload.plan.by_item() + clips = payload.assembly.clips + if tuple(clip.itemId for clip in clips) != tuple(entries): + raise ContractError('invalid_input', '组装片段须按源片顺序与生成区间对应。', group.id) + visible = visible_item_ids(snapshot) + for clip in clips: + item = items.get(clip.itemId) + entry = entries[clip.itemId] + if (item is None or item.kind != 'video' or item.binding.role != 'generation' + or item.parentId != group.id or item.id not in visible): + raise ContractError('invalid_input', '生成区间须引用分组内可见的视频生成节点。', clip.itemId) + if clip.outFrame - clip.inFrame != entry.sourceEnd - entry.sourceStart: + raise ContractError('invalid_input', '保留帧数须与源片区间长度一致。', clip.itemId) + timeline = items.get(payload.assembly.timelineItemId) + if timeline is None or timeline.kind != 'timeline' or timeline.parentId != group.id or timeline.id not in visible: + raise ContractError('invalid_input', '计划须关联分组内可见的时间线。', group.id) + return group + + +def plan_markdown(group: GroupCanvasItem, snapshot: ProjectSnapshot, payload: GroupPlanDraft) -> str: + chinese = payload.planLocale == 'zh-CN' + titles = {item.id: item.title.replace('|', '/').replace('\n', ' ') for item in snapshot.canvasItems} + clips = {clip.itemId: clip for clip in payload.assembly.clips} + rows = [ + f'# {group.title}', '', + f'{payload.plan.frameCount} {"帧" if chinese else "frames"} · {payload.plan.fps} fps', '', + '| 源片帧区间 | 片段 | 导帧 | 保留区间 |' if chinese else '| Source frames | Segment | Guide | Retained frames |', + '| --- | --- | --- | --- |', + ] + for entry in payload.plan.entries: + interval = f'[{entry.sourceStart}, {entry.sourceEnd})' + if entry.kind == 'source': + original = '保留原片' if chinese else 'Original footage' + rows.append(f'| {interval} | {original} | — | {interval} |') + continue + clip = clips[entry.itemId] + guide = '锚点' if chinese else 'Anchor' + if entry.step.kind == 'continuation': + first, last = entry.step.sourceFrames + guide = f'{titles[entry.step.upstreamItemId]} · {first} / {last}' + direction = '' + if clip.reverse: + direction = ' · 反转后取帧' if chinese else ' · after reversal' + rows.append(f'| {interval} | {titles[entry.itemId]} | {guide} | [{clip.inFrame}, {clip.outFrame}){direction} |') + if payload.planNotes.strip(): + rows.extend(['', '## 编排说明' if chinese else '## Planning notes', '', payload.planNotes.strip()]) + return '\n'.join(rows) + '\n' + + +def save_segment_plan(projects: "CreationProjects", command: Command, *, session: str | None, source: str) -> CommandReceipt: + payload = command.payload + + def save(snapshot: ProjectSnapshot) -> ProjectSnapshot: + group = validate_plan(snapshot, payload) + if (group.draftRunPlan, group.assembly, group.runPlanLocale, group.runPlanNotes) == ( + payload.plan, payload.assembly, payload.planLocale, payload.planNotes): + return snapshot + updated = group.model_copy(update={ + 'draftRunPlan': payload.plan, 'assembly': payload.assembly, 'runPlanLocale': payload.planLocale, + 'runPlanNotes': payload.planNotes, 'revision': group.revision + 1, + }) + return snapshot.model_copy(update={'canvasItems': tuple( + updated if item.id == group.id else item for item in snapshot.canvasItems)}) + + return projects.commit(command, save, session=session, source=source) + + +def publish_segment_plan(projects: "CreationProjects", command: Command, *, session: str | None, source: str) -> CommandReceipt: + replay = projects.replay(command) + if replay is not None: + return replay + payload = command.payload + snapshot = projects.snapshot(command.projectId) + try: + group = validate_plan(snapshot, payload) + except ContractError as error: + def reject(_: ProjectSnapshot) -> ProjectSnapshot: + raise error + + return projects.commit(command, reject, session=session, source=source) + + assets = CreationAssets(projects) + handle = uuid4() + writer = assets.uploads.begin(command.projectId, handle, session, 'Run plan.md', expected_kind='text') + try: + with TemporaryDirectory(prefix='opendirector-segment-plan-') as folder: + path = Path(folder, 'source') + stream, _ = assets.open_media(command.projectId, payload.plan.source.assetId, snapshot=snapshot) + with stream, path.open('wb') as target: + copyfileobj(stream, target) + if count_video_frames(path, fps=payload.plan.fps) != payload.plan.frameCount: + raise ProjectError('计划帧数与实际源片不一致。', 409, code='reference_invalid') + writer.write(plan_markdown(group, snapshot, payload).encode('utf-8')) + upload = writer.finish() + finally: + writer.abort() + asset_id = gateway().upload_asset_id(command.projectId, handle) + asset = Asset(id=asset_id, projectId=command.projectId, kind='text', name='Run plan.md', + path=f'assets/{asset_id}', metadata=upload.metadata, fingerprint=upload.fingerprint, + provenance=AssetProvenance(source='manual')) + plan_id = uuid5(command.commandId, 'published-segment-plan') + card = TextCanvasItem(id=plan_id, projectId=command.projectId, kind='text', + title='运行计划' if payload.planLocale == 'zh-CN' else 'Run plan', + parentId=group.id, locked=True, position={'x': 32, 'y': 48}, width=640, height=400, + binding={'role': 'material', 'objectRef': asset_ref(asset)}) + published = group.model_copy(update={ + 'assembly': payload.assembly, 'runPlan': payload.plan, 'draftRunPlan': None, + 'runPlanItemId': plan_id, 'runDefinitionId': command.commandId, 'runPlanLocale': payload.planLocale, + 'runPlanNotes': payload.planNotes, 'revision': group.revision + 1, + }) + + def publish(before: ProjectSnapshot) -> ProjectSnapshot: + if before != snapshot: + raise ContractError('revision_conflict', '工程在发布前已更新,请重试。', group.id) + items = tuple(published if item.id == group.id else item for item in before.canvasItems) + return before.model_copy(update={'assets': (*before.assets, asset), 'canvasItems': (*items, card)}) + + write = AssetFileWrite(assetId=asset_id, uploadHandle=handle, fingerprint=asset.fingerprint, size=asset.metadata.size) + receipt = projects.commit(command, publish, session=session, source=source, files=(write,)) + if not any(version.id == asset_id for version in receipt.changed): + try: + assets.uploads.cancel(command.projectId, handle, session) + except ProjectError as error: + if error.code != 'session_expired': + raise + return receipt diff --git a/packages/core/src/opendirector/domain/creation/canvas.py b/packages/core/src/opendirector/domain/creation/canvas.py index 0ae7b7115..2ab10f021 100644 --- a/packages/core/src/opendirector/domain/creation/canvas.py +++ b/packages/core/src/opendirector/domain/creation/canvas.py @@ -10,6 +10,7 @@ from .base import CanvasColor, CanvasItemVersion, Contract, Identifier, Point, Positive, ProjectEntity, unique from .generation import FollowingSource, GenerationSpec, ResolvedReference, validate_generation from .models import ModelConfigPublic +from .segment_run import SegmentRunPlan class FollowingReferenceSource(Contract): @@ -189,12 +190,71 @@ class DirectorCanvasItem(EditorCanvasItem): kind: Literal['external'] = Field(description='Business object or media type.') +class WorkflowClip(Contract): + itemId: UUID = Field(description='Generation canvas node providing the raw video.') + inFrame: Annotated[int, Field(strict=True, ge=0, le=4095)] = Field(description='First retained frame in playback order.') + outFrame: Annotated[int, Field(strict=True, ge=1, le=4096)] = Field(description='Exclusive end of the retained frames.') + reverse: bool = Field(default=False, description='Reverse the raw window before keeping the selected frames.') + frameLimit: Annotated[int, Field(strict=True, ge=1, le=4096)] | None = Field( + default=None, description='Optional cap on the raw window before reversal.') + + @model_validator(mode='after') + def frame_window(self): + if self.outFrame <= self.inFrame or (self.frameLimit is not None and self.outFrame > self.frameLimit): + raise ValueError('Invalid workflow frame window') + return self + + +class GroupAssembly(Contract): + timelineItemId: UUID = Field(description='Timeline canvas node receiving the assembled clips.') + outputItemId: UUID = Field(description='Stable canvas node ID for the published video.') + clips: tuple[WorkflowClip, ...] = Field(min_length=1, max_length=50, description='Generated clips in assembly order.') + requireTimelineGuides: bool = Field(default=False, strict=True, exclude_if=lambda value: not value, + description='Required for H3 segmented plans. A confirmed plan keeps its guide requirement when its assembly is edited.') + guideExemptItemId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, + description='The only generation anchor that may omit a timeline guide. Omit this to require a guide on every clip.') + + @model_validator(mode='after') + def distinct_items(self): + clip_ids = {clip.itemId for clip in self.clips} + ids = {self.timelineItemId, self.outputItemId, *clip_ids} + if len(ids) != len(self.clips) + 2: + raise ValueError('Assembly nodes must have distinct identities') + if self.guideExemptItemId is not None and (not self.requireTimelineGuides or self.guideExemptItemId not in clip_ids): + raise ValueError('The guide-exempt anchor must be a clip in a guide-required assembly') + return self + + class GroupCanvasItem(CanvasItemBase): kind: Literal['group'] = Field(description='Business object or media type.') autoLayout: Literal['run'] | None = Field(default=None, exclude_if=lambda value: value is None, description='Set to run to opt this top-level group into shared Run layout. Put its plan, clips and timeline under this group ID.') + runPlan: SegmentRunPlan | None = Field(default=None, exclude_if=lambda value: value is None, + description='Frozen plan assigned only by the Run publication command.') + draftRunPlan: SegmentRunPlan | None = Field(default=None, exclude_if=lambda value: value is None, + description='Editable plan input from a published Run. Publish it before starting execution.') + runPlanItemId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, + description='Read-only canvas node showing the published plan.') + runDefinitionId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, + description='Publication command ID identifying this frozen Run definition.') + runPlanLocale: Literal['zh-CN', 'en-US'] | None = Field(default=None, exclude_if=lambda value: value is None, + description='Language of the visible Run plan.') + runPlanNotes: str | None = Field(default=None, exclude_if=lambda value: value is None, max_length=16000, + description='Editable notes accompanying the Run plan.') + assembly: GroupAssembly | None = Field(default=None, exclude_if=lambda value: value is None, + description='Optional frame-accurate assembly after the group generation run.') binding: ContainerBinding = Field(default_factory=lambda: ContainerBinding(role='container'), description='Business object displayed by this canvas item.') + @model_validator(mode='after') + def published_plan(self) -> 'GroupCanvasItem': + if self.runPlan is not None and ( + self.runPlanItemId is None or self.runDefinitionId is None or self.assembly is None + or self.draftRunPlan is not None): + raise ValueError('Published plans require a plan card, a definition ID and an assembly.') + if self.runPlan is None and (self.runPlanItemId is not None or self.runDefinitionId is not None): + raise ValueError('Only published plans can reference a plan card or definition ID.') + return self + CanvasItem = Annotated[TextCanvasItem | ImageCanvasItem | VideoCanvasItem | AudioCanvasItem | FileCanvasItem | SubjectCanvasItem | TimelineCanvasItem | StackCanvasItem | ToolCanvasItem | DirectorCanvasItem | GroupCanvasItem, diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 602b2b3aa..1f3ac0474 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -6,7 +6,8 @@ from .assets import AssetRef, MediaMetadata from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique -from .canvas import CanvasItem +from .segment_run import SegmentRunPlan +from .canvas import GroupAssembly, CanvasItem from .editors import EditorDocument from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH from .generation import GenerationSpec, Job, PromptPart, Reference @@ -64,6 +65,14 @@ def assets(self): return self +class GroupPlanDraft(Contract): + groupId: UUID = Field(description='Canvas group holding the draft.') + plan: SegmentRunPlan = Field(description='Segment intervals in source order.') + assembly: GroupAssembly = Field(description='Retained frames for the generated intervals.') + planLocale: Literal['zh-CN', 'en-US'] = Field(default='zh-CN', description='Language of the published plan.') + planNotes: str = Field(default='', max_length=16000, description='Notes accompanying the plan.') + + class CanvasShow(Contract): item: CanvasItem = Field(description='Canvas display item to create or restore.') @@ -338,6 +347,8 @@ def required_versions(self) -> list[tuple[str, UUID]]: ('AssetMetadataCommand', 'asset.updateMetadata', AssetMetadataUpdate, 'Rename an asset.'), ('AssetDeleteCommand', 'asset.delete', AssetDelete, 'Delete assets after an impact preview.'), ('CanvasCreateGenerationCommand', 'canvas.createGeneration', CanvasCreateGeneration, 'Create a visible generation node and references atomically, preserving canvas source connections, including pinned ones.'), + ('GroupSavePlanCommand', 'group.saveRunPlan', GroupPlanDraft, 'Save a draft segment plan.'), + ('GroupPublishRunCommand', 'group.publishRun', GroupPlanDraft, 'Publish the segment plan as a Markdown canvas node.'), ('CanvasShowCommand', 'canvas.show', CanvasShow, 'Create or restore a canvas display item.'), ('CanvasMoveCommand', 'canvas.move', CanvasMove, 'Move one or more canvas items.'), ('CanvasUpdateCommand', 'canvas.update', CanvasPresentationUpdate, 'Update canvas presentation, grouping or lock state.'), diff --git a/packages/core/src/opendirector/domain/creation/segment_run.py b/packages/core/src/opendirector/domain/creation/segment_run.py new file mode 100644 index 000000000..574b06e37 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/segment_run.py @@ -0,0 +1,124 @@ +"""Typed input and deterministic ordering for a full-source video run.""" + +from collections import defaultdict +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import Field, model_validator + +from .assets import AssetRef +from .base import Contract, Identifier, PositiveInt + +SourceFrame = Annotated[int, Field(strict=True, ge=0)] +GuideFrame = Annotated[int, Field(strict=True, ge=0, le=359)] + + +class SegmentRunAnchor(Contract): + kind: Literal['anchor'] = Field(description='One independent generation anchor in the declared source shot.') + + +class SegmentRunContinuation(Contract): + kind: Literal['continuation'] = Field(description='Generation requires the selected upstream result as a guide.') + upstreamItemId: UUID = Field(description='Generation node providing the raw guide frames.') + sourceFrames: tuple[GuideFrame, GuideFrame] = Field( + description='Two distinct indices into the raw upstream result for destination frames 0 and 21, in that order.') + + @model_validator(mode='after') + def distinct_frames(self): + if self.sourceFrames[0] == self.sourceFrames[1]: + raise ValueError('Run continuation requires two distinct guide frames.') + return self + + +class SegmentRunInterval(Contract): + sourceStart: SourceFrame = Field(description='First covered frame in the normalized working source.') + sourceEnd: PositiveInt = Field(description='Exclusive end of the covered interval in the normalized working source.') + + @model_validator(mode='after') + def nonempty(self): + if self.sourceEnd <= self.sourceStart: + raise ValueError('Run source intervals must contain at least one frame.') + return self + + +class SegmentRunSource(SegmentRunInterval): + kind: Literal['source'] = Field(description='Retain these frames from the frozen working source.') + + +class SegmentRunGenerated(SegmentRunInterval): + kind: Literal['generated'] = Field(description='Use the retained result from a generation step.') + itemId: UUID = Field(description='Generation canvas node that provides the result.') + shot: Identifier = Field(description='Identity of the inspected continuous shot used to determine guide dependencies.') + step: Annotated[SegmentRunAnchor | SegmentRunContinuation, Field(discriminator='kind')] = Field( + description='Independent anchor or guided continuation in this shot.') + + +SegmentRunEntry = Annotated[SegmentRunSource | SegmentRunGenerated, Field(discriminator='kind')] + + +class SegmentRunPlan(Contract): + source: AssetRef = Field(description='Exact normalized working video whose entire frame range is delivered.') + fps: PositiveInt = Field(description='Integer frames per second of the normalized working video.') + frameCount: PositiveInt = Field(description='Decoded frame count of the normalized working video.') + entries: tuple[SegmentRunEntry, ...] = Field( + min_length=1, max_length=101, description='Delivery intervals in source playback order.') + + def by_item(self) -> dict[UUID, SegmentRunGenerated]: + return {entry.itemId: entry for entry in self.entries if isinstance(entry, SegmentRunGenerated)} + + def execution_order(self) -> tuple[UUID, ...]: + """Stable topological order, independent of delivery order.""" + members = self.by_item() + visiting, completed = set(), set() + order = [] + + def visit(item_id): + if item_id in completed: + return + if item_id in visiting: + raise ValueError(f'Run guide dependencies contain a cycle at {item_id}.') + entry = members[item_id] + visiting.add(item_id) + if isinstance(entry.step, SegmentRunContinuation): + donor = members.get(entry.step.upstreamItemId) + if donor is None or donor.shot != entry.shot: + raise ValueError(f'Run step {item_id} must obtain guides from a member of shot {entry.shot!r}.') + visit(donor.itemId) + visiting.remove(item_id) + completed.add(item_id) + order.append(item_id) + + for item_id in members: + visit(item_id) + return tuple(order) + + @model_validator(mode='after') + def delivery(self): + if self.source.kind != 'video': + raise ValueError('Run source must be a video asset.') + cursor = 0 + shot_members = defaultdict(list) + members = set() + for entry in self.entries: + if entry.sourceStart != cursor: + lo, hi = sorted((cursor, entry.sourceStart)) + issue = 'gap' if entry.sourceStart > cursor else 'overlap or ordering error' + raise ValueError(f'Run source coverage has a {issue} at [{lo}, {hi}).') + cursor = entry.sourceEnd + if isinstance(entry, SegmentRunGenerated): + if entry.itemId in members: + raise ValueError(f'Run generation node {entry.itemId} occurs more than once.') + members.add(entry.itemId) + shot_members[entry.shot].append(entry.step) + + if cursor < self.frameCount: + raise ValueError(f'Run source coverage has a gap at [{cursor}, {self.frameCount}).') + if cursor > self.frameCount: + raise ValueError(f'Run source coverage exceeds the video at [{self.frameCount}, {cursor}).') + if not members: + raise ValueError('A segment run must contain at least one generation step.') + for shot, steps in shot_members.items(): + if sum(isinstance(step, SegmentRunAnchor) for step in steps) != 1: + raise ValueError(f'Run shot {shot!r} must have one anchor. Other members require continuation guides.') + self.execution_order() + return self diff --git a/packages/core/src/opendirector/domain/creation/validation.py b/packages/core/src/opendirector/domain/creation/validation.py index b8c9893b4..0582fc5a0 100644 --- a/packages/core/src/opendirector/domain/creation/validation.py +++ b/packages/core/src/opendirector/domain/creation/validation.py @@ -4,7 +4,7 @@ from opendirector.domain.projects import ProjectError -from .canvas import MediaCanvasItem, role_after +from .canvas import GroupCanvasItem, MediaCanvasItem, role_after from .commands import Command, ContractIssue, IssueCode from .project import ProjectSnapshot @@ -103,3 +103,33 @@ def get(kind, object_id): current = get('editor_document', payload.document.id) if current.kind != payload.document.kind: raise ContractError('invalid_input', 'Editor document kind cannot change', current.id) + + +def validate_published_plans(command: Command, before: ProjectSnapshot, after: ProjectSnapshot) -> None: + old_plans = {item.id: item for item in before.canvasItems if isinstance(item, GroupCanvasItem) and item.runPlan} + publication = command.payload.groupId if command.type == 'group.publishRun' else None + for item in after.canvasItems: + if isinstance(item, GroupCanvasItem) and item.runPlan is not None: + if item.id not in old_plans and item.id != publication: + raise ContractError('role_restricted', '请使用发布命令生成已发布计划。', item.id) + if not old_plans: + return + old_items = {item.id: item for item in before.canvasItems} + new_items = {item.id: item for item in after.canvasItems} + new_assets = {asset.id: asset for asset in after.assets} + for group in old_plans.values(): + updated = new_items.get(group.id) + if (not isinstance(updated, GroupCanvasItem) or not updated.visible + or updated.parentId != group.parentId or updated.runPlan != group.runPlan or updated.assembly != group.assembly + or updated.runPlanItemId != group.runPlanItemId or updated.runDefinitionId != group.runDefinitionId + or updated.runPlanLocale != group.runPlanLocale or updated.runPlanNotes != group.runPlanNotes): + raise ContractError('role_restricted', '已发布的计划定义为只读。', group.id) + card = old_items[group.runPlanItemId] + updated_card = new_items.get(card.id) + if (updated_card is None or updated_card.kind != 'text' or not updated_card.visible + or not updated_card.locked or updated_card.parentId != group.id + or updated_card.binding != card.binding): + raise ContractError('role_restricted', '已发布的计划卡为只读。', card.id) + source = new_assets.get(group.runPlan.source.assetId) + if source is None or source.revision != group.runPlan.source.revision: + raise ContractError('role_restricted', '已发布的计划仍引用此源片。', group.runPlan.source.assetId) diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index 205276d81..5d015841e 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -11,7 +11,7 @@ from opendirector.domain.creation.commands import Command, CommandReceipt, ProjectEvent, command_fingerprint from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.run_layout import reflow_runs -from opendirector.domain.creation.validation import ContractError, validate_command +from opendirector.domain.creation.validation import ContractError, validate_command, validate_published_plans from opendirector.domain.projects import ProjectError, identifier from opendirector.infrastructure.creation_files import cleanup_staging, delete_files, install_files from opendirector.infrastructure.creation_records import ( @@ -73,6 +73,7 @@ def commit(self, command: Command, raise ContractError('invalid_input', 'Services cannot replace project identity or event cursors') if snapshot.project.name != before.project.name and command.type != 'project.rename': raise ContractError('invalid_input', 'Only the rename command can rename a project') + validate_published_plans(command, before, snapshot) changed = object_changes(before, snapshot, command) operations = command.payload.operations if command.type == 'creation.batch' else (command,) organize_runs = any(operation.type == 'canvas.layoutRuns' for operation in operations) diff --git a/packages/core/src/opendirector/media/probe.py b/packages/core/src/opendirector/media/probe.py index 3ea8f02fe..27966424f 100644 --- a/packages/core/src/opendirector/media/probe.py +++ b/packages/core/src/opendirector/media/probe.py @@ -1,5 +1,6 @@ """Probe uploaded/generated media using a bounded local ffprobe process.""" +from fractions import Fraction import json import math from pathlib import Path @@ -88,3 +89,22 @@ def probe_file(file: Path, kind: str, *, include_container=False, include_codecs return {**common, "sampleRate": int(stream["sample_rate"]), "channels": stream["channels"]} except (subprocess.SubprocessError, ValueError, TypeError, KeyError, StopIteration, OverflowError): raise ProjectError("无法读取视频或音频,请检查文件格式及完整性。") from None + + + +def count_video_frames(path: Path, *, fps: int) -> int: + require_ffprobe() + try: + output = subprocess.run( + ['ffprobe', '-v', 'error', '-protocol_whitelist', 'file,pipe', + '-select_streams', 'v:0', '-count_frames', '-show_entries', + 'stream=avg_frame_rate,nb_read_frames', '-of', 'json', str(path)], + check=True, capture_output=True, timeout=90, + ) + stream = json.loads(output.stdout)['streams'][0] + count = int(stream['nb_read_frames']) + if Fraction(stream['avg_frame_rate']) == fps and count > 0: + return count + except (subprocess.CalledProcessError, subprocess.TimeoutExpired, KeyError, IndexError, ValueError, ZeroDivisionError): + raise ProjectError('无法核对源片的帧数或帧率。', 409, code='reference_invalid') from None + raise ProjectError('计划帧率与实际源片不一致。', 409, code='reference_invalid') diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index f22919af7..8d3301476 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4199,6 +4199,8 @@ "generationSpec.restore": "#/$defs/SpecRestoreCommand", "generationSpec.setPrompt": "#/$defs/SpecPromptCommand", "generationSpec.update": "#/$defs/SpecUpdateCommand", + "group.publishRun": "#/$defs/GroupPublishRunCommand", + "group.saveRunPlan": "#/$defs/GroupSavePlanCommand", "history.redo": "#/$defs/HistoryRedoCommand", "history.undo": "#/$defs/HistoryUndoCommand", "job.cancel": "#/$defs/JobCancelCommand", @@ -4248,6 +4250,12 @@ { "$ref": "#/$defs/CanvasCreateGenerationCommand" }, + { + "$ref": "#/$defs/GroupSavePlanCommand" + }, + { + "$ref": "#/$defs/GroupPublishRunCommand" + }, { "$ref": "#/$defs/CanvasShowCommand" }, @@ -6027,6 +6035,60 @@ "title": "GenerationSubmitCommand", "type": "object" }, + "GroupAssembly": { + "additionalProperties": false, + "properties": { + "timelineItemId": { + "description": "Timeline canvas node receiving the assembled clips.", + "format": "uuid", + "title": "Timelineitemid", + "type": "string" + }, + "outputItemId": { + "description": "Stable canvas node ID for the published video.", + "format": "uuid", + "title": "Outputitemid", + "type": "string" + }, + "clips": { + "description": "Generated clips in assembly order.", + "items": { + "$ref": "#/$defs/WorkflowClip" + }, + "maxItems": 50, + "minItems": 1, + "title": "Clips", + "type": "array" + }, + "requireTimelineGuides": { + "default": false, + "description": "Required for H3 segmented plans. A confirmed plan keeps its guide requirement when its assembly is edited.", + "title": "Requiretimelineguides", + "type": "boolean" + }, + "guideExemptItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The only generation anchor that may omit a timeline guide. Omit this to require a guide on every clip.", + "title": "Guideexemptitemid" + } + }, + "required": [ + "timelineItemId", + "outputItemId", + "clips" + ], + "title": "GroupAssembly", + "type": "object" + }, "GroupCanvasItem": { "additionalProperties": false, "properties": { @@ -6152,6 +6214,101 @@ "description": "Set to run to opt this top-level group into shared Run layout. Put its plan, clips and timeline under this group ID.", "title": "Autolayout" }, + "runPlan": { + "anyOf": [ + { + "$ref": "#/$defs/SegmentRunPlan" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Frozen plan assigned only by the Run publication command." + }, + "draftRunPlan": { + "anyOf": [ + { + "$ref": "#/$defs/SegmentRunPlan" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Editable plan input from a published Run. Publish it before starting execution." + }, + "runPlanItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Read-only canvas node showing the published plan.", + "title": "Runplanitemid" + }, + "runDefinitionId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Publication command ID identifying this frozen Run definition.", + "title": "Rundefinitionid" + }, + "runPlanLocale": { + "anyOf": [ + { + "enum": [ + "zh-CN", + "en-US" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Language of the visible Run plan.", + "title": "Runplanlocale" + }, + "runPlanNotes": { + "anyOf": [ + { + "maxLength": 16000, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Editable notes accompanying the Run plan.", + "title": "Runplannotes" + }, + "assembly": { + "anyOf": [ + { + "$ref": "#/$defs/GroupAssembly" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional frame-accurate assembly after the group generation run." + }, "binding": { "$ref": "#/$defs/ContainerBinding", "description": "Business object displayed by this canvas item." @@ -6165,6 +6322,167 @@ "title": "GroupCanvasItem", "type": "object" }, + "GroupPlanDraft": { + "additionalProperties": false, + "properties": { + "groupId": { + "description": "Canvas group holding the draft.", + "format": "uuid", + "title": "Groupid", + "type": "string" + }, + "plan": { + "$ref": "#/$defs/SegmentRunPlan", + "description": "Segment intervals in source order." + }, + "assembly": { + "$ref": "#/$defs/GroupAssembly", + "description": "Retained frames for the generated intervals." + }, + "planLocale": { + "default": "zh-CN", + "description": "Language of the published plan.", + "enum": [ + "zh-CN", + "en-US" + ], + "title": "Planlocale", + "type": "string" + }, + "planNotes": { + "default": "", + "description": "Notes accompanying the plan.", + "maxLength": 16000, + "title": "Plannotes", + "type": "string" + } + }, + "required": [ + "groupId", + "plan", + "assembly" + ], + "title": "GroupPlanDraft", + "type": "object" + }, + "GroupPublishRunCommand": { + "additionalProperties": false, + "description": "Publish the segment plan as a Markdown canvas node.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "group.publishRun", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/GroupPlanDraft", + "description": "Publish the segment plan as a Markdown canvas node." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "GroupPublishRunCommand", + "type": "object" + }, + "GroupSavePlanCommand": { + "additionalProperties": false, + "description": "Save a draft segment plan.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "group.saveRunPlan", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { + "anyOf": [ + { + "pattern": "^[0-9a-f]{64}$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" + }, + "payload": { + "$ref": "#/$defs/GroupPlanDraft", + "description": "Save a draft segment plan." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "payload" + ], + "title": "GroupSavePlanCommand", + "type": "object" + }, "HistoryRedoCommand": { "additionalProperties": false, "description": "Reapply an undone command.", @@ -11634,13 +11952,221 @@ "title": "ResultVersion", "type": "object" }, - "SelectionBox": { + "SegmentRunAnchor": { "additionalProperties": false, "properties": { - "x": { - "description": "Horizontal coordinate.", - "title": "X", - "type": "number" + "kind": { + "const": "anchor", + "description": "One independent generation anchor in the declared source shot.", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "SegmentRunAnchor", + "type": "object" + }, + "SegmentRunContinuation": { + "additionalProperties": false, + "properties": { + "kind": { + "const": "continuation", + "description": "Generation requires the selected upstream result as a guide.", + "title": "Kind", + "type": "string" + }, + "upstreamItemId": { + "description": "Generation node providing the raw guide frames.", + "format": "uuid", + "title": "Upstreamitemid", + "type": "string" + }, + "sourceFrames": { + "description": "Two distinct indices into the raw upstream result for destination frames 0 and 21, in that order.", + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "maximum": 359, + "minimum": 0, + "type": "integer" + }, + { + "maximum": 359, + "minimum": 0, + "type": "integer" + } + ], + "title": "Sourceframes", + "type": "array" + } + }, + "required": [ + "kind", + "upstreamItemId", + "sourceFrames" + ], + "title": "SegmentRunContinuation", + "type": "object" + }, + "SegmentRunGenerated": { + "additionalProperties": false, + "properties": { + "sourceStart": { + "description": "First covered frame in the normalized working source.", + "minimum": 0, + "title": "Sourcestart", + "type": "integer" + }, + "sourceEnd": { + "description": "Exclusive end of the covered interval in the normalized working source.", + "minimum": 1, + "title": "Sourceend", + "type": "integer" + }, + "kind": { + "const": "generated", + "description": "Use the retained result from a generation step.", + "title": "Kind", + "type": "string" + }, + "itemId": { + "description": "Generation canvas node that provides the result.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "shot": { + "description": "Identity of the inspected continuous shot used to determine guide dependencies.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Shot", + "type": "string" + }, + "step": { + "description": "Independent anchor or guided continuation in this shot.", + "discriminator": { + "mapping": { + "anchor": "#/$defs/SegmentRunAnchor", + "continuation": "#/$defs/SegmentRunContinuation" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/SegmentRunAnchor" + }, + { + "$ref": "#/$defs/SegmentRunContinuation" + } + ], + "title": "Step" + } + }, + "required": [ + "sourceStart", + "sourceEnd", + "kind", + "itemId", + "shot", + "step" + ], + "title": "SegmentRunGenerated", + "type": "object" + }, + "SegmentRunPlan": { + "additionalProperties": false, + "properties": { + "source": { + "$ref": "#/$defs/AssetRef", + "description": "Exact normalized working video whose entire frame range is delivered." + }, + "fps": { + "description": "Integer frames per second of the normalized working video.", + "minimum": 1, + "title": "Fps", + "type": "integer" + }, + "frameCount": { + "description": "Decoded frame count of the normalized working video.", + "minimum": 1, + "title": "Framecount", + "type": "integer" + }, + "entries": { + "description": "Delivery intervals in source playback order.", + "items": { + "discriminator": { + "mapping": { + "generated": "#/$defs/SegmentRunGenerated", + "source": "#/$defs/SegmentRunSource" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/SegmentRunSource" + }, + { + "$ref": "#/$defs/SegmentRunGenerated" + } + ] + }, + "maxItems": 101, + "minItems": 1, + "title": "Entries", + "type": "array" + } + }, + "required": [ + "source", + "fps", + "frameCount", + "entries" + ], + "title": "SegmentRunPlan", + "type": "object" + }, + "SegmentRunSource": { + "additionalProperties": false, + "properties": { + "sourceStart": { + "description": "First covered frame in the normalized working source.", + "minimum": 0, + "title": "Sourcestart", + "type": "integer" + }, + "sourceEnd": { + "description": "Exclusive end of the covered interval in the normalized working source.", + "minimum": 1, + "title": "Sourceend", + "type": "integer" + }, + "kind": { + "const": "source", + "description": "Retain these frames from the frozen working source.", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "sourceStart", + "sourceEnd", + "kind" + ], + "title": "SegmentRunSource", + "type": "object" + }, + "SelectionBox": { + "additionalProperties": false, + "properties": { + "x": { + "description": "Horizontal coordinate.", + "title": "X", + "type": "number" }, "y": { "description": "Vertical coordinate.", @@ -15701,6 +16227,59 @@ ], "title": "VoiceSelection", "type": "object" + }, + "WorkflowClip": { + "additionalProperties": false, + "properties": { + "itemId": { + "description": "Generation canvas node providing the raw video.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "inFrame": { + "description": "First retained frame in playback order.", + "maximum": 4095, + "minimum": 0, + "title": "Inframe", + "type": "integer" + }, + "outFrame": { + "description": "Exclusive end of the retained frames.", + "maximum": 4096, + "minimum": 1, + "title": "Outframe", + "type": "integer" + }, + "reverse": { + "default": false, + "description": "Reverse the raw window before keeping the selected frames.", + "title": "Reverse", + "type": "boolean" + }, + "frameLimit": { + "anyOf": [ + { + "maximum": 4096, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional cap on the raw window before reversal.", + "title": "Framelimit" + } + }, + "required": [ + "itemId", + "inFrame", + "outFrame" + ], + "title": "WorkflowClip", + "type": "object" } }, "additionalProperties": false, @@ -15883,6 +16462,8 @@ "generationSpec.restore": "#/$defs/SpecRestoreCommand", "generationSpec.setPrompt": "#/$defs/SpecPromptCommand", "generationSpec.update": "#/$defs/SpecUpdateCommand", + "group.publishRun": "#/$defs/GroupPublishRunCommand", + "group.saveRunPlan": "#/$defs/GroupSavePlanCommand", "history.redo": "#/$defs/HistoryRedoCommand", "history.undo": "#/$defs/HistoryUndoCommand", "job.cancel": "#/$defs/JobCancelCommand", @@ -15932,6 +16513,12 @@ { "$ref": "#/$defs/CanvasCreateGenerationCommand" }, + { + "$ref": "#/$defs/GroupSavePlanCommand" + }, + { + "$ref": "#/$defs/GroupPublishRunCommand" + }, { "$ref": "#/$defs/CanvasShowCommand" }, @@ -20519,6 +21106,8 @@ "generationSpec.restore": "#/$defs/SpecRestoreCommand", "generationSpec.setPrompt": "#/$defs/SpecPromptCommand", "generationSpec.update": "#/$defs/SpecUpdateCommand", + "group.publishRun": "#/$defs/GroupPublishRunCommand", + "group.saveRunPlan": "#/$defs/GroupSavePlanCommand", "history.redo": "#/$defs/HistoryRedoCommand", "history.undo": "#/$defs/HistoryUndoCommand", "job.cancel": "#/$defs/JobCancelCommand", @@ -20568,6 +21157,12 @@ { "$ref": "#/$defs/CanvasCreateGenerationCommand" }, + { + "$ref": "#/$defs/GroupSavePlanCommand" + }, + { + "$ref": "#/$defs/GroupPublishRunCommand" + }, { "$ref": "#/$defs/CanvasShowCommand" }, @@ -22417,6 +23012,60 @@ "title": "GenerationSubmitCommand", "type": "object" }, + "GroupAssembly": { + "additionalProperties": false, + "properties": { + "timelineItemId": { + "description": "Timeline canvas node receiving the assembled clips.", + "format": "uuid", + "title": "Timelineitemid", + "type": "string" + }, + "outputItemId": { + "description": "Stable canvas node ID for the published video.", + "format": "uuid", + "title": "Outputitemid", + "type": "string" + }, + "clips": { + "description": "Generated clips in assembly order.", + "items": { + "$ref": "#/$defs/WorkflowClip" + }, + "maxItems": 50, + "minItems": 1, + "title": "Clips", + "type": "array" + }, + "requireTimelineGuides": { + "default": false, + "description": "Required for H3 segmented plans. A confirmed plan keeps its guide requirement when its assembly is edited.", + "title": "Requiretimelineguides", + "type": "boolean" + }, + "guideExemptItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The only generation anchor that may omit a timeline guide. Omit this to require a guide on every clip.", + "title": "Guideexemptitemid" + } + }, + "required": [ + "timelineItemId", + "outputItemId", + "clips" + ], + "title": "GroupAssembly", + "type": "object" + }, "GroupCanvasItem": { "additionalProperties": false, "properties": { @@ -22502,10 +23151,245 @@ "title": "Visible", "type": "boolean" }, - "parentId": { + "parentId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Parent canvas group ID, or null for the root.", + "title": "Parentid" + }, + "tags": { + "default": [], + "description": "User-defined search tags.", + "items": { + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "type": "string" + }, + "title": "Tags", + "type": "array" + }, + "autoLayout": { + "anyOf": [ + { + "const": "run", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Set to run to opt this top-level group into shared Run layout. Put its plan, clips and timeline under this group ID.", + "title": "Autolayout" + }, + "runPlan": { + "anyOf": [ + { + "$ref": "#/$defs/SegmentRunPlan" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Frozen plan assigned only by the Run publication command." + }, + "draftRunPlan": { + "anyOf": [ + { + "$ref": "#/$defs/SegmentRunPlan" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Editable plan input from a published Run. Publish it before starting execution." + }, + "runPlanItemId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Read-only canvas node showing the published plan.", + "title": "Runplanitemid" + }, + "runDefinitionId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Publication command ID identifying this frozen Run definition.", + "title": "Rundefinitionid" + }, + "runPlanLocale": { + "anyOf": [ + { + "enum": [ + "zh-CN", + "en-US" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Language of the visible Run plan.", + "title": "Runplanlocale" + }, + "runPlanNotes": { + "anyOf": [ + { + "maxLength": 16000, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Editable notes accompanying the Run plan.", + "title": "Runplannotes" + }, + "assembly": { + "anyOf": [ + { + "$ref": "#/$defs/GroupAssembly" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional frame-accurate assembly after the group generation run." + }, + "binding": { + "$ref": "#/$defs/ContainerBinding", + "description": "Business object displayed by this canvas item." + } + }, + "required": [ + "id", + "projectId", + "revision", + "kind", + "title", + "position", + "width", + "height", + "zIndex", + "locked", + "visible", + "parentId", + "tags", + "binding" + ], + "title": "GroupCanvasItem", + "type": "object" + }, + "GroupPlanDraft": { + "additionalProperties": false, + "properties": { + "groupId": { + "description": "Canvas group holding the draft.", + "format": "uuid", + "title": "Groupid", + "type": "string" + }, + "plan": { + "$ref": "#/$defs/SegmentRunPlan", + "description": "Segment intervals in source order." + }, + "assembly": { + "$ref": "#/$defs/GroupAssembly", + "description": "Retained frames for the generated intervals." + }, + "planLocale": { + "default": "zh-CN", + "description": "Language of the published plan.", + "enum": [ + "zh-CN", + "en-US" + ], + "title": "Planlocale", + "type": "string" + }, + "planNotes": { + "default": "", + "description": "Notes accompanying the plan.", + "maxLength": 16000, + "title": "Plannotes", + "type": "string" + } + }, + "required": [ + "groupId", + "plan", + "assembly", + "planLocale", + "planNotes" + ], + "title": "GroupPlanDraft", + "type": "object" + }, + "GroupPublishRunCommand": { + "additionalProperties": false, + "description": "Publish the segment plan as a Markdown canvas node.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "group.publishRun", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { + "default": [], + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", + "items": { + "$ref": "#/$defs/ObjectVersion" + }, + "title": "Expectedversions", + "type": "array" + }, + "expectedPreview": { "anyOf": [ { - "format": "uuid", + "pattern": "^[0-9a-f]{64}$", "type": "string" }, { @@ -22513,25 +23397,60 @@ } ], "default": null, - "description": "Parent canvas group ID, or null for the root.", - "title": "Parentid" + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" }, - "tags": { + "payload": { + "$ref": "#/$defs/GroupPlanDraft", + "description": "Publish the segment plan as a Markdown canvas node." + } + }, + "required": [ + "commandId", + "projectId", + "type", + "expectedVersions", + "expectedPreview", + "payload" + ], + "title": "GroupPublishRunCommand", + "type": "object" + }, + "GroupSavePlanCommand": { + "additionalProperties": false, + "description": "Save a draft segment plan.", + "properties": { + "commandId": { + "description": "Stable command ID for idempotent replay.", + "format": "uuid", + "title": "Commandid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "group.saveRunPlan", + "description": "Command discriminator.", + "title": "Type", + "type": "string" + }, + "expectedVersions": { "default": [], - "description": "User-defined search tags.", + "description": "Current versions of mutated existing objects; payload revision fields do not replace these.", "items": { - "maxLength": 100, - "minLength": 1, - "pattern": "\\S", - "type": "string" + "$ref": "#/$defs/ObjectVersion" }, - "title": "Tags", + "title": "Expectedversions", "type": "array" }, - "autoLayout": { + "expectedPreview": { "anyOf": [ { - "const": "run", + "pattern": "^[0-9a-f]{64}$", "type": "string" }, { @@ -22539,31 +23458,23 @@ } ], "default": null, - "description": "Set to run to opt this top-level group into shared Run layout. Put its plan, clips and timeline under this group ID.", - "title": "Autolayout" + "description": "Fingerprint of the confirmed impact preview.", + "title": "Expectedpreview" }, - "binding": { - "$ref": "#/$defs/ContainerBinding", - "description": "Business object displayed by this canvas item." + "payload": { + "$ref": "#/$defs/GroupPlanDraft", + "description": "Save a draft segment plan." } }, "required": [ - "id", + "commandId", "projectId", - "revision", - "kind", - "title", - "position", - "width", - "height", - "zIndex", - "locked", - "visible", - "parentId", - "tags", - "binding" + "type", + "expectedVersions", + "expectedPreview", + "payload" ], - "title": "GroupCanvasItem", + "title": "GroupSavePlanCommand", "type": "object" }, "HistoryRedoCommand": { @@ -28228,6 +29139,214 @@ "title": "ResultVersion", "type": "object" }, + "SegmentRunAnchor": { + "additionalProperties": false, + "properties": { + "kind": { + "const": "anchor", + "description": "One independent generation anchor in the declared source shot.", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "kind" + ], + "title": "SegmentRunAnchor", + "type": "object" + }, + "SegmentRunContinuation": { + "additionalProperties": false, + "properties": { + "kind": { + "const": "continuation", + "description": "Generation requires the selected upstream result as a guide.", + "title": "Kind", + "type": "string" + }, + "upstreamItemId": { + "description": "Generation node providing the raw guide frames.", + "format": "uuid", + "title": "Upstreamitemid", + "type": "string" + }, + "sourceFrames": { + "description": "Two distinct indices into the raw upstream result for destination frames 0 and 21, in that order.", + "maxItems": 2, + "minItems": 2, + "prefixItems": [ + { + "maximum": 359, + "minimum": 0, + "type": "integer" + }, + { + "maximum": 359, + "minimum": 0, + "type": "integer" + } + ], + "title": "Sourceframes", + "type": "array" + } + }, + "required": [ + "kind", + "upstreamItemId", + "sourceFrames" + ], + "title": "SegmentRunContinuation", + "type": "object" + }, + "SegmentRunGenerated": { + "additionalProperties": false, + "properties": { + "sourceStart": { + "description": "First covered frame in the normalized working source.", + "minimum": 0, + "title": "Sourcestart", + "type": "integer" + }, + "sourceEnd": { + "description": "Exclusive end of the covered interval in the normalized working source.", + "minimum": 1, + "title": "Sourceend", + "type": "integer" + }, + "kind": { + "const": "generated", + "description": "Use the retained result from a generation step.", + "title": "Kind", + "type": "string" + }, + "itemId": { + "description": "Generation canvas node that provides the result.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "shot": { + "description": "Identity of the inspected continuous shot used to determine guide dependencies.", + "maxLength": 100, + "minLength": 1, + "pattern": "\\S", + "title": "Shot", + "type": "string" + }, + "step": { + "description": "Independent anchor or guided continuation in this shot.", + "discriminator": { + "mapping": { + "anchor": "#/$defs/SegmentRunAnchor", + "continuation": "#/$defs/SegmentRunContinuation" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/SegmentRunAnchor" + }, + { + "$ref": "#/$defs/SegmentRunContinuation" + } + ], + "title": "Step" + } + }, + "required": [ + "sourceStart", + "sourceEnd", + "kind", + "itemId", + "shot", + "step" + ], + "title": "SegmentRunGenerated", + "type": "object" + }, + "SegmentRunPlan": { + "additionalProperties": false, + "properties": { + "source": { + "$ref": "#/$defs/AssetRef", + "description": "Exact normalized working video whose entire frame range is delivered." + }, + "fps": { + "description": "Integer frames per second of the normalized working video.", + "minimum": 1, + "title": "Fps", + "type": "integer" + }, + "frameCount": { + "description": "Decoded frame count of the normalized working video.", + "minimum": 1, + "title": "Framecount", + "type": "integer" + }, + "entries": { + "description": "Delivery intervals in source playback order.", + "items": { + "discriminator": { + "mapping": { + "generated": "#/$defs/SegmentRunGenerated", + "source": "#/$defs/SegmentRunSource" + }, + "propertyName": "kind" + }, + "oneOf": [ + { + "$ref": "#/$defs/SegmentRunSource" + }, + { + "$ref": "#/$defs/SegmentRunGenerated" + } + ] + }, + "maxItems": 101, + "minItems": 1, + "title": "Entries", + "type": "array" + } + }, + "required": [ + "source", + "fps", + "frameCount", + "entries" + ], + "title": "SegmentRunPlan", + "type": "object" + }, + "SegmentRunSource": { + "additionalProperties": false, + "properties": { + "sourceStart": { + "description": "First covered frame in the normalized working source.", + "minimum": 0, + "title": "Sourcestart", + "type": "integer" + }, + "sourceEnd": { + "description": "Exclusive end of the covered interval in the normalized working source.", + "minimum": 1, + "title": "Sourceend", + "type": "integer" + }, + "kind": { + "const": "source", + "description": "Retain these frames from the frozen working source.", + "title": "Kind", + "type": "string" + } + }, + "required": [ + "sourceStart", + "sourceEnd", + "kind" + ], + "title": "SegmentRunSource", + "type": "object" + }, "SelectionBox": { "additionalProperties": false, "properties": { @@ -32482,6 +33601,61 @@ ], "title": "VoiceSelection", "type": "object" + }, + "WorkflowClip": { + "additionalProperties": false, + "properties": { + "itemId": { + "description": "Generation canvas node providing the raw video.", + "format": "uuid", + "title": "Itemid", + "type": "string" + }, + "inFrame": { + "description": "First retained frame in playback order.", + "maximum": 4095, + "minimum": 0, + "title": "Inframe", + "type": "integer" + }, + "outFrame": { + "description": "Exclusive end of the retained frames.", + "maximum": 4096, + "minimum": 1, + "title": "Outframe", + "type": "integer" + }, + "reverse": { + "default": false, + "description": "Reverse the raw window before keeping the selected frames.", + "title": "Reverse", + "type": "boolean" + }, + "frameLimit": { + "anyOf": [ + { + "maximum": 4096, + "minimum": 1, + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Optional cap on the raw window before reversal.", + "title": "Framelimit" + } + }, + "required": [ + "itemId", + "inFrame", + "outFrame", + "reverse", + "frameLimit" + ], + "title": "WorkflowClip", + "type": "object" } }, "additionalProperties": false, @@ -32664,6 +33838,8 @@ "generationSpec.restore": "#/$defs/SpecRestoreCommand", "generationSpec.setPrompt": "#/$defs/SpecPromptCommand", "generationSpec.update": "#/$defs/SpecUpdateCommand", + "group.publishRun": "#/$defs/GroupPublishRunCommand", + "group.saveRunPlan": "#/$defs/GroupSavePlanCommand", "history.redo": "#/$defs/HistoryRedoCommand", "history.undo": "#/$defs/HistoryUndoCommand", "job.cancel": "#/$defs/JobCancelCommand", @@ -32713,6 +33889,12 @@ { "$ref": "#/$defs/CanvasCreateGenerationCommand" }, + { + "$ref": "#/$defs/GroupSavePlanCommand" + }, + { + "$ref": "#/$defs/GroupPublishRunCommand" + }, { "$ref": "#/$defs/CanvasShowCommand" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index fdd595716..6310b2b51 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -445,7 +445,7 @@ export interface CreationContractsInput extends ContractInput { readonly generationSpec: TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput; readonly reference: PinnedReferenceInput | FollowingReferenceInput; readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; - readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; + readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | GroupSavePlanCommandInput | GroupPublishRunCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | JobStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; @@ -609,12 +609,45 @@ export interface GenerationSubmitCommandInput extends CommandBaseInput { readonly payload: GenerationSubmitInput; } +export interface GroupAssemblyInput extends ContractInput { + readonly timelineItemId: string; + readonly outputItemId: string; + readonly clips: ReadonlyArray; + readonly requireTimelineGuides?: boolean; + readonly guideExemptItemId?: string | null; +} + export interface GroupCanvasItemInput extends CanvasItemBaseInput { readonly kind: "group"; readonly autoLayout?: "run" | null; + readonly runPlan?: SegmentRunPlanInput | null; + readonly draftRunPlan?: SegmentRunPlanInput | null; + readonly runPlanItemId?: string | null; + readonly runDefinitionId?: string | null; + readonly runPlanLocale?: "zh-CN" | "en-US" | null; + readonly runPlanNotes?: string | null; + readonly assembly?: GroupAssemblyInput | null; readonly binding?: ContainerBindingInput; } +export interface GroupPlanDraftInput extends ContractInput { + readonly groupId: string; + readonly plan: SegmentRunPlanInput; + readonly assembly: GroupAssemblyInput; + readonly planLocale?: "zh-CN" | "en-US"; + readonly planNotes?: string; +} + +export interface GroupPublishRunCommandInput extends CommandBaseInput { + readonly type: "group.publishRun"; + readonly payload: GroupPlanDraftInput; +} + +export interface GroupSavePlanCommandInput extends CommandBaseInput { + readonly type: "group.saveRunPlan"; + readonly payload: GroupPlanDraftInput; +} + export interface HistoryRedoCommandInput extends CommandBaseInput { readonly type: "history.redo"; readonly payload: HistoryReplayInput; @@ -1200,6 +1233,38 @@ export interface ResultVersionInput extends ProjectEntityInput { readonly inputFingerprint: string; } +export interface SegmentRunAnchorInput { + readonly kind: "anchor"; +} + +export interface SegmentRunContinuationInput { + readonly kind: "continuation"; + readonly upstreamItemId: string; + readonly sourceFrames: readonly [number, number]; +} + +export interface SegmentRunGeneratedInput { + readonly sourceStart: number; + readonly sourceEnd: number; + readonly kind: "generated"; + readonly itemId: string; + readonly shot: string; + readonly step: SegmentRunAnchorInput | SegmentRunContinuationInput; +} + +export interface SegmentRunPlanInput extends ContractInput { + readonly source: AssetRefInput; + readonly fps: number; + readonly frameCount: number; + readonly entries: ReadonlyArray; +} + +export interface SegmentRunSourceInput { + readonly sourceStart: number; + readonly sourceEnd: number; + readonly kind: "source"; +} + export interface SelectionBoxInput extends ContractInput { readonly x: number; readonly y: number; @@ -1649,6 +1714,14 @@ export interface VoiceSelectionInput extends ContractInput { readonly refText?: string | null; } +export interface WorkflowClipInput extends ContractInput { + readonly itemId: string; + readonly inFrame: number; + readonly outFrame: number; + readonly reverse?: boolean; + readonly frameLimit?: number | null; +} + export type CanvasItemInput = TextCanvasItemInput | ImageCanvasItemInput | VideoCanvasItemInput | AudioCanvasItemInput | FileCanvasItemInput | SubjectCanvasItemInput | TimelineCanvasItemInput | StackCanvasItemInput | ToolCanvasItemInput | DirectorCanvasItemInput | GroupCanvasItemInput; export type GenerationSpecInput = TextGenerationSpecInput | ImageGenerationSpecInput | VideoGenerationSpecInput | AudioGenerationSpecInput; @@ -1657,7 +1730,7 @@ export type ReferenceInput = PinnedReferenceInput | FollowingReferenceInput; export type EditorDocumentInput = TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; -export type CommandInput = ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; +export type CommandInput = ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | GroupSavePlanCommandInput | GroupPublishRunCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; export type ExecutionParametersInput = TextExecutionInput | ImageExecutionInput | VideoExecutionInput | AudioExecutionInput; @@ -2114,7 +2187,7 @@ export interface CreationContracts extends Contract { readonly generationSpec: TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec; readonly reference: PinnedReference | FollowingReference; readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; - readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; + readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | GroupSavePlanCommand | GroupPublishRunCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; @@ -2278,12 +2351,45 @@ export interface GenerationSubmitCommand extends CommandBase { readonly payload: GenerationSubmit; } +export interface GroupAssembly extends Contract { + readonly timelineItemId: string; + readonly outputItemId: string; + readonly clips: ReadonlyArray; + readonly requireTimelineGuides?: boolean; + readonly guideExemptItemId?: string | null; +} + export interface GroupCanvasItem extends CanvasItemBase { readonly kind: "group"; readonly autoLayout?: "run" | null; + readonly runPlan?: SegmentRunPlan | null; + readonly draftRunPlan?: SegmentRunPlan | null; + readonly runPlanItemId?: string | null; + readonly runDefinitionId?: string | null; + readonly runPlanLocale?: "zh-CN" | "en-US" | null; + readonly runPlanNotes?: string | null; + readonly assembly?: GroupAssembly | null; readonly binding: ContainerBinding; } +export interface GroupPlanDraft extends Contract { + readonly groupId: string; + readonly plan: SegmentRunPlan; + readonly assembly: GroupAssembly; + readonly planLocale: "zh-CN" | "en-US"; + readonly planNotes: string; +} + +export interface GroupPublishRunCommand extends CommandBase { + readonly type: "group.publishRun"; + readonly payload: GroupPlanDraft; +} + +export interface GroupSavePlanCommand extends CommandBase { + readonly type: "group.saveRunPlan"; + readonly payload: GroupPlanDraft; +} + export interface HistoryRedoCommand extends CommandBase { readonly type: "history.redo"; readonly payload: HistoryReplay; @@ -2868,6 +2974,38 @@ export interface ResultVersion extends ProjectEntity { readonly inputFingerprint: string; } +export interface SegmentRunAnchor { + readonly kind: "anchor"; +} + +export interface SegmentRunContinuation { + readonly kind: "continuation"; + readonly upstreamItemId: string; + readonly sourceFrames: readonly [number, number]; +} + +export interface SegmentRunGenerated { + readonly sourceStart: number; + readonly sourceEnd: number; + readonly kind: "generated"; + readonly itemId: string; + readonly shot: string; + readonly step: SegmentRunAnchor | SegmentRunContinuation; +} + +export interface SegmentRunPlan extends Contract { + readonly source: AssetRef; + readonly fps: number; + readonly frameCount: number; + readonly entries: ReadonlyArray; +} + +export interface SegmentRunSource { + readonly sourceStart: number; + readonly sourceEnd: number; + readonly kind: "source"; +} + export interface SelectionBox extends Contract { readonly x: number; readonly y: number; @@ -3317,6 +3455,14 @@ export interface VoiceSelection extends Contract { readonly refText: string | null; } +export interface WorkflowClip extends Contract { + readonly itemId: string; + readonly inFrame: number; + readonly outFrame: number; + readonly reverse: boolean; + readonly frameLimit: number | null; +} + export type CanvasItem = TextCanvasItem | ImageCanvasItem | VideoCanvasItem | AudioCanvasItem | FileCanvasItem | SubjectCanvasItem | TimelineCanvasItem | StackCanvasItem | ToolCanvasItem | DirectorCanvasItem | GroupCanvasItem; export type GenerationSpec = TextGenerationSpec | ImageGenerationSpec | VideoGenerationSpec | AudioGenerationSpec; @@ -3325,7 +3471,7 @@ export type Reference = PinnedReference | FollowingReference; export type EditorDocument = TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; -export type Command = ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; +export type Command = ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | GroupSavePlanCommand | GroupPublishRunCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; export type ExecutionParameters = TextExecution | ImageExecution | VideoExecution | AudioExecution; diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py index 4bd390a93..ca873cce3 100644 --- a/tests/test_creation_api.py +++ b/tests/test_creation_api.py @@ -2,6 +2,7 @@ from legacy_fixtures import legacy_project from uuid import uuid4 import shutil +import subprocess from fastapi.testclient import TestClient import pytest @@ -539,3 +540,78 @@ def test_run_layout_rejects_unrepresentable_placement(api): assert receipt['status'] == 'rejected', receipt assert receipt['issues'][0]['code'] == 'canvas_run_layout_extent' assert client.get(path).json() == before + + +def test_publish_segment_plan_persists_a_read_only_card(api, tmp_path): + client, _ = api + path, created, _ = create(client, 'Segment plan') + project_id = created['projectId'] + assert client.post(path + '/open').is_success + source_path = tmp_path / 'source.mp4' + subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'color=s=64x64:r=24', + '-frames:v', '24', '-c:v', 'mpeg4', str(source_path)], check=True) + handle = str(uuid4()) + assert client.put(f'{path}/uploads/{handle}', content=source_path.read_bytes(), + headers={'X-Asset-Name': 'source.mp4'}).is_success + imported = _layout_command(client, path, project_id, 'asset.import', + dict(uploadHandle=handle, name='source.mp4', expectedKind='video')) + asset = client.get(f'{path}/assets/{imported["changed"][0]["id"]}').json() + source = dict(assetId=asset['id'], revision=asset['revision'], fingerprint=asset['fingerprint'], kind='video') + + group = _show_layout_item(project_id, 'group', title='Replacement') + group_id = _layout_item_id(group) + spec_id = str(uuid4()) + segment = _show_layout_item(project_id, 'video', title='First segment', parentId=group_id, + binding=dict(role='generation', objectRef=dict(id=spec_id))) + segment_id = _layout_item_id(segment) + timeline_id = str(uuid4()) + timeline = _show_layout_item(project_id, 'timeline', title='Timeline', parentId=group_id, + binding=dict(role='editor', objectRef=dict(id=timeline_id, kind='timeline'))) + operations = [ + group, + dict(type='generationSpec.create', payload=dict(spec=dict( + id=spec_id, projectId=project_id, kind='video', purpose='generation'))), + segment, + dict(type='editor.create', payload=dict(document=dict( + id=timeline_id, projectId=project_id, kind='timeline', + data=dict(fps=24, width=64, height=64, tracks=[dict(id='visual', kind='visual', title='Visual')])))), + timeline, + ] + _layout_command(client, path, project_id, 'creation.batch', dict(operations=operations)) + payload = dict(groupId=group_id, planLocale='en-US', planNotes='Keep the final half.', + plan=dict(source=source, fps=24, frameCount=24, entries=[ + dict(kind='generated', sourceStart=0, sourceEnd=12, itemId=segment_id, shot='first', + step=dict(kind='anchor')), + dict(kind='source', sourceStart=12, sourceEnd=24), + ]), + assembly=dict(timelineItemId=_layout_item_id(timeline), outputItemId=str(uuid4()), + clips=[dict(itemId=segment_id, inFrame=0, outFrame=12)])) + version = dict(objectType='canvas_item', id=group_id, revision=1) + _layout_command(client, path, project_id, 'group.saveRunPlan', payload, expected_versions=[version]) + saved = _canvas_items(client.get(path).json()) + assert saved[group_id]['draftRunPlan']['source'] == source + assert 'runPlanItemId' not in saved[group_id] + + publication = dict(type='group.publishRun', commandId=str(uuid4()), projectId=project_id, payload=payload, + expectedVersions=[dict(version, revision=saved[group_id]['revision'])]) + wrong_count = {**payload['plan'], 'frameCount': 25, 'entries': [ + payload['plan']['entries'][0], {'kind': 'source', 'sourceStart': 12, 'sourceEnd': 25}, + ]} + invalid = client.post(f'{path}/commands', json={**publication, 'commandId': str(uuid4()), + 'payload': {**payload, 'plan': wrong_count}}) + assert invalid.status_code == 409 and invalid.json()['code'] == 'reference_invalid' + assert 'runPlanItemId' not in _canvas_items(client.get(path).json())[group_id] + + response = client.post(f'{path}/commands', json=publication) + assert response.is_success and response.json()['status'] == 'applied', response.text + assert response.json()['jobIds'] == [] + assert client.post(f'{path}/commands', json=publication).json() == response.json() + published = _canvas_items(client.post(f'{path}/open').json()) + card = published[published[group_id]['runPlanItemId']] + assert card['locked'] and card['parentId'] == group_id + markdown = client.get(f'{path}/assets/{card["binding"]["objectRef"]["assetId"]}/content') + assert markdown.is_success and '| Source frames |' in markdown.text + assert 'First segment' in markdown.text and 'Keep the final half.' in markdown.text + _layout_command(client, path, project_id, 'canvas.update', dict(itemId=card['id'], locked=False), + expected_versions=[dict(objectType='canvas_item', id=card['id'], revision=card['revision'])], + status='rejected') From f0f0709ec8aaff38e77d829798c52891209dcc05 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Wed, 25 Nov 2026 20:34:45 +0800 Subject: [PATCH 2/3] [bugfix] cli: register segment plan commands ## summary Register the group CLI namespace and provide a valid segment plan example for command discovery. Signed-off-by: Weiming Liao --- packages/core/src/opendirector/cli.py | 1 + .../opendirector/domain/creation/commands.py | 26 +++++++ src/contracts/creation.schema.json | 76 +++++++++++++++++++ 3 files changed, 103 insertions(+) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index da77523b7..e6188cac4 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -58,6 +58,7 @@ "result": "Select a generated result for adoption.", "editor": "Create and save editable media documents.", "timeline": "Discover resources for editable timelines.", + "group": "Save and publish segment run plans.", "history": "Undo or redo reversible project operations.", "creation": "Apply multiple project operations atomically.", } diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 1f3ac0474..e628997a4 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -66,6 +66,30 @@ def assets(self): class GroupPlanDraft(Contract): + model_config = ConfigDict(json_schema_extra={'examples': [{ + 'groupId': '00000000-0000-0000-0000-000000000001', + 'plan': { + 'source': { + 'assetId': '00000000-0000-0000-0000-000000000002', + 'kind': 'video', 'revision': 1, 'fingerprint': 'sha256:' + '0' * 64, + }, + 'fps': 24, 'frameCount': 24, + 'entries': [{ + 'kind': 'generated', 'sourceStart': 0, 'sourceEnd': 24, + 'itemId': '00000000-0000-0000-0000-000000000003', + 'shot': 'opening', 'step': {'kind': 'anchor'}, + }], + }, + 'assembly': { + 'timelineItemId': '00000000-0000-0000-0000-000000000004', + 'outputItemId': '00000000-0000-0000-0000-000000000005', + 'clips': [{ + 'itemId': '00000000-0000-0000-0000-000000000003', + 'inFrame': 0, 'outFrame': 24, + }], + }, + }]}) + groupId: UUID = Field(description='Canvas group holding the draft.') plan: SegmentRunPlan = Field(description='Segment intervals in source order.') assembly: GroupAssembly = Field(description='Retained frames for the generated intervals.') @@ -302,6 +326,8 @@ def required_versions(self) -> list[tuple[str, UUID]]: required = [] if self.type in {'project.rename', 'project.trash', 'project.restore'}: required = [('project', self.projectId)] + elif self.type in {'group.saveRunPlan', 'group.publishRun'}: + required = [('canvas_item', payload.groupId)] elif self.type == 'canvas.publishMedia': required = [('canvas_item', payload.itemId), *[('asset', o.asset.assetId) for o in payload.outputs]] if payload.sourceEditorId: diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 8d3301476..53cdd1619 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -6324,6 +6324,44 @@ }, "GroupPlanDraft": { "additionalProperties": false, + "examples": [ + { + "assembly": { + "clips": [ + { + "inFrame": 0, + "itemId": "00000000-0000-0000-0000-000000000003", + "outFrame": 24 + } + ], + "outputItemId": "00000000-0000-0000-0000-000000000005", + "timelineItemId": "00000000-0000-0000-0000-000000000004" + }, + "groupId": "00000000-0000-0000-0000-000000000001", + "plan": { + "entries": [ + { + "itemId": "00000000-0000-0000-0000-000000000003", + "kind": "generated", + "shot": "opening", + "sourceEnd": 24, + "sourceStart": 0, + "step": { + "kind": "anchor" + } + } + ], + "fps": 24, + "frameCount": 24, + "source": { + "assetId": "00000000-0000-0000-0000-000000000002", + "fingerprint": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "kind": "video", + "revision": 1 + } + } + } + ], "properties": { "groupId": { "description": "Canvas group holding the draft.", @@ -23312,6 +23350,44 @@ }, "GroupPlanDraft": { "additionalProperties": false, + "examples": [ + { + "assembly": { + "clips": [ + { + "inFrame": 0, + "itemId": "00000000-0000-0000-0000-000000000003", + "outFrame": 24 + } + ], + "outputItemId": "00000000-0000-0000-0000-000000000005", + "timelineItemId": "00000000-0000-0000-0000-000000000004" + }, + "groupId": "00000000-0000-0000-0000-000000000001", + "plan": { + "entries": [ + { + "itemId": "00000000-0000-0000-0000-000000000003", + "kind": "generated", + "shot": "opening", + "sourceEnd": 24, + "sourceStart": 0, + "step": { + "kind": "anchor" + } + } + ], + "fps": 24, + "frameCount": 24, + "source": { + "assetId": "00000000-0000-0000-0000-000000000002", + "fingerprint": "sha256:0000000000000000000000000000000000000000000000000000000000000000", + "kind": "video", + "revision": 1 + } + } + } + ], "properties": { "groupId": { "description": "Canvas group holding the draft.", From 71754534bca4c3a43eeffb340c8bdfed3b4562ce Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Wed, 25 Nov 2026 21:10:14 +0800 Subject: [PATCH 3/3] [bugfix] workflow: keep segment publication within application boundary Signed-off-by: Weiming Liao --- .../application/creation_segment_run_publication.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_segment_run_publication.py b/packages/core/src/opendirector/application/creation_segment_run_publication.py index 5692bcb69..d7c02e736 100644 --- a/packages/core/src/opendirector/application/creation_segment_run_publication.py +++ b/packages/core/src/opendirector/application/creation_segment_run_publication.py @@ -3,7 +3,6 @@ from pathlib import Path from shutil import copyfileobj from tempfile import TemporaryDirectory -from typing import TYPE_CHECKING from uuid import uuid4, uuid5 from opendirector.application.creation_assets import CreationAssets @@ -18,9 +17,6 @@ from opendirector.ports.files import AssetFileWrite from opendirector.ports.gateway import gateway -if TYPE_CHECKING: - from opendirector.infrastructure.creation_projects import CreationProjects - def validate_plan(snapshot: ProjectSnapshot, payload: GroupPlanDraft) -> GroupCanvasItem: items = {item.id: item for item in snapshot.canvasItems} @@ -83,7 +79,7 @@ def plan_markdown(group: GroupCanvasItem, snapshot: ProjectSnapshot, payload: Gr return '\n'.join(rows) + '\n' -def save_segment_plan(projects: "CreationProjects", command: Command, *, session: str | None, source: str) -> CommandReceipt: +def save_segment_plan(projects, command: Command, *, session: str | None, source: str) -> CommandReceipt: payload = command.payload def save(snapshot: ProjectSnapshot) -> ProjectSnapshot: @@ -101,7 +97,7 @@ def save(snapshot: ProjectSnapshot) -> ProjectSnapshot: return projects.commit(command, save, session=session, source=source) -def publish_segment_plan(projects: "CreationProjects", command: Command, *, session: str | None, source: str) -> CommandReceipt: +def publish_segment_plan(projects, command: Command, *, session: str | None, source: str) -> CommandReceipt: replay = projects.replay(command) if replay is not None: return replay