diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index eb3efb1fd..02dd82004 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -98,6 +98,10 @@ "preview_expired": "The preview expired. Generate it again.", "reference_invalid": "A reference is no longer valid. Select it again and retry.", "role_restricted": "This item does not allow that operation.", + "canvas_run_layout_extent": "Canvas positions or dimensions are too large to arrange. Resize the affected items.", + "canvas_run_layout_group": "Run layout is only available for top-level groups.", + "canvas_run_layout_conflict": "Locked Run areas overlap. Unlock one of the groups and try again.", + "canvas_run_layout_shared_object": "Two Runs use the same editable object. Copy the configuration or editor document and try again.", "storage_unavailable": "A stored file is missing or has changed. Restore the file and try again.", "capability_unsupported": "This capability is not supported yet.", "model_list_http_error": "Could not load the model list from the service.", diff --git a/docs/guides/cli.md b/docs/guides/cli.md index e6dc88c10..3c6914137 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -25,6 +25,12 @@ opendirector --project PROJECT_UUID video create --model MODEL_CONFIG_UUID - `canvas add-material` 和 `video create` 通过必填的 `--x`、`--y` 明确创建位置。Agent 先读取画布对象的位置、尺寸及分组,再安排新元素布局。`video create` 创建可编辑的生成节点与参考关系,返回 `specId` 和 `itemId`。所有画布修改命令以及批量事务通过共用返回层提供 `canvasItems`,包含元素身份、版本、位置、尺寸、父级、坐标系及可见性。位置未变化的操作也返回目标元素的几何信息,供后续布局判断。几何信息读取失败时,回执保留已提交状态并返回 `geometryReadError`。模型可通过配置 UUID 或唯一匹配的完整模型名指定。重名配置返回候选 UUID 和端点,由调用者明确选择。模型的输入模式必须支持所选参数。`--reference-item` 支持重复指定参考节点。提交生成时使用创建回执中的对象版本,后台任务由服务端继续执行。 +### Run 自动布局 / Run auto-layout + +在画布中右键顶层分组,选择「加入 Run 自动布局」。通过 CLI 或 Agent 新建 Run 时,在 `canvas.show` 的 group 对象设置 `autoLayout: "run"`,并将本轮的计划、片段和时间线节点的 `parentId` 设为该分组 ID。同批新增或改变尺寸的节点会在保存时统一排布。各轮以稳定顺序换行,锁定的 Run 和普通顶层节点作为固定占位。不同 Run 可复用已登记素材,各自保存生成配置和编辑文档。要重新整理,右键画布空白处选择「整理 Run」,或运行 `opendirector canvas layout-runs`。通过 `canvas update --item-id ID --auto-layout free --expected-version canvas_item:ID:REV` 恢复手动布局。 + +On the canvas, right-click a top-level group and select **Include in Run layout**. From the CLI or Agent, set `autoLayout: "run"` on the group in `canvas.show`, then set `parentId` on its plan, clip, and timeline nodes to that group ID. New and resized nodes are arranged in the same save. Runs wrap in a stable order around locked Runs and ordinary top-level nodes. Runs can reuse registered assets, and each Run owns its own generation configurations and editor documents. To arrange Runs explicitly, right-click the canvas background or run `opendirector canvas layout-runs`. Use `canvas update --item-id ID --auto-layout free --expected-version canvas_item:ID:REV` to return a group to manual layout. + ```bash opendirector --project PROJECT_UUID generation submit --spec-id SPEC_UUID --expected-spec-revision 1 --origin-item-id ITEM_UUID --expected-version generation_spec:SPEC_UUID:1 --expected-version canvas_item:ITEM_UUID:1 opendirector --project PROJECT_UUID job show JOB_UUID diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index a93ed0c98..f97c6af96 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -523,8 +523,12 @@ def _mutate(self, data, kind, payload): if (ref and str(ref.get('id')) == str(obj['id'])) or attached: self._editable(data, item['id']) old.update(obj) + elif kind == 'canvas.layoutRuns': + pass # The commit arranges the authoritative canvas after validating edits. elif kind == 'canvas.show': obj = payload.item.model_dump(mode='json') + if obj.get('autoLayout') == 'run' and obj['parentId'] is not None: + raise ContractError('canvas_run_layout_group', '自动排列只适用于顶层分组。', payload.item.id) if str(obj['projectId']) != str(data['project']['id']): raise ContractError('invalid_input', '节点不属于当前工程。') old = next((o for o in data['canvasItems'] if o['id'] == obj['id']), None) @@ -556,7 +560,16 @@ def _mutate(self, data, kind, payload): self._editable(data, move.itemId)['position'] = move.position.model_dump() elif kind == 'canvas.update': item = self._editable(data, payload.itemId, unlocking=value.get('locked') is False) + layout = value.pop('autoLayout', None) + if layout is not None and item['kind'] != 'group': + raise ContractError('canvas_run_layout_group', '自动排列只适用于顶层分组。', payload.itemId) + if layout == 'run': + item['autoLayout'] = 'run' + elif layout == 'free': + item.pop('autoLayout', None) item.update({key: val for key, val in value.items() if key != 'itemId' and (val is not None or key == 'parentId')}) + if item.get('autoLayout') == 'run' and item['parentId'] is not None: + raise ContractError('canvas_run_layout_group', '自动排列只适用于顶层分组。', payload.itemId) if item.get('color') == '': item.pop('color') elif kind == 'canvas.hide': diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index a48f5a693..cc826923b 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -14,7 +14,7 @@ EDITABLE = {'canvasItems', 'generationSpecs', 'references', 'editorDocuments'} ABSENT = object() -UNDOABLE = {'canvas.createGeneration', 'creation.batch', 'canvas.show', 'canvas.hide', 'canvas.move', 'canvas.update', 'canvas.configure', +UNDOABLE = {'canvas.createGeneration', 'creation.batch', 'canvas.show', 'canvas.hide', 'canvas.move', 'canvas.update', 'canvas.layoutRuns', 'canvas.configure', 'canvas.materialize', 'canvas.applyEdit', 'timeline.publishRender', 'canvas.publishMedia', 'canvas.applyVersion', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.update', 'generationSpec.restore', 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'result.select', 'editor.save', 'generationSpec.setPrompt'} diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 7957db4a5..b424f2dfc 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -294,6 +294,7 @@ def execute(self, kind, payload, versions=(), preview=None, *, identity=None): value["canvasItems"].append({ **{field: item[field] for field in ("id", "kind", "revision", "parentId", "position", "width", "height", "visible")}, + **({"autoLayout": item["autoLayout"]} if item.get("autoLayout") else {}), "coordinateSpace": "canvas" if item["parentId"] is None else "parent", }) except (ProjectError, OSError, httpx.HTTPError) as error: @@ -395,6 +396,7 @@ def summarize(snapshot): for asset in snapshot.get("assets", ())], "canvasItems": [{"id": item["id"], "revision": item["revision"], "kind": item.get("kind"), "title": item.get("title"), "visible": item.get("visible", True), + **({"autoLayout": item["autoLayout"]} if item.get("autoLayout") else {}), "binding": {"role": item["binding"]["role"], "objectRef": item["binding"].get("objectRef", {}).get("id") or item["binding"].get("objectRef", {}).get("assetId")} } diff --git a/packages/core/src/opendirector/domain/creation/canvas.py b/packages/core/src/opendirector/domain/creation/canvas.py index 181a31f0e..0ae7b7115 100644 --- a/packages/core/src/opendirector/domain/creation/canvas.py +++ b/packages/core/src/opendirector/domain/creation/canvas.py @@ -191,6 +191,8 @@ class DirectorCanvasItem(EditorCanvasItem): 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.') binding: ContainerBinding = Field(default_factory=lambda: ContainerBinding(role='container'), description='Business object displayed by this canvas item.') diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 5f6d0f29b..602b2b3aa 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -113,6 +113,8 @@ class CanvasPresentationUpdate(Contract): color: CanvasColor | None = Field(default=None, exclude_if=lambda value: value is None, description="Group background color in #RRGGBB format, or '' for the default.") parentId: UUID | None = Field(default=None, description='Parent canvas group ID, or null for the root.') # Presence of parentId distinguishes retaining a group from ungrouping. + autoLayout: Literal['run', 'free'] | None = Field(default=None, exclude_if=lambda value: value is None, + description='Enable Run layout for a top-level group, or use free to return it to manual layout.') class CanvasHide(Contract): @@ -339,6 +341,7 @@ def required_versions(self) -> list[tuple[str, UUID]]: ('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.'), + ('CanvasLayoutRunsCommand', 'canvas.layoutRuns', EmptyPayload, 'Arrange the current canvas Run groups and their children without moving locked groups.'), ('CanvasHideCommand', 'canvas.hide', CanvasHide, 'Remove a canvas item; preserves project contents. Remove all visible items to clear the canvas.'), ('CanvasMaterializeCommand', 'canvas.materialize', CanvasMaterialize, 'Bind an asset to an empty or material canvas item.'), ('CanvasApplyEditCommand', 'canvas.applyEdit', CanvasApplyEdit, 'Apply an editor result to a canvas item.'), @@ -373,7 +376,7 @@ def required_versions(self) -> list[tuple[str, UUID]]: COMMAND_MODELS[_type] = _model globals()[_name] = _model -_BATCH_TYPES = {'canvas.show', 'canvas.move', 'canvas.update', 'canvas.hide', 'canvas.materialize', 'canvas.applyEdit', +_BATCH_TYPES = {'canvas.show', 'canvas.move', 'canvas.update', 'canvas.layoutRuns', 'canvas.hide', 'canvas.materialize', 'canvas.applyEdit', 'canvas.configure', 'canvas.attachEditor', 'canvas.detachEditor', 'generationSpec.create', 'generationSpec.update', 'reference.add', 'reference.update', 'reference.restore', 'reference.remove', 'editor.create', 'editor.save', 'result.select', 'generationSpec.setPrompt'} _OPERATIONS = tuple(create_model(name + 'Operation', __base__=Contract, @@ -407,7 +410,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode -IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'missing_object', 'reference_invalid', 'image_quality_unsupported', +IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'role_restricted', 'canvas_run_layout_group', 'canvas_run_layout_conflict', 'canvas_run_layout_extent', 'canvas_run_layout_shared_object', 'missing_object', 'reference_invalid', 'image_quality_unsupported', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', 'kling_model', 'kling_mode', 'kling_image', 'kling_frames', 'kling_prompt', 'kling_aspect', 'kling_output', 'kling_cancel', @@ -432,6 +435,8 @@ class ContractIssue(Contract): message: str = Field(min_length=1, max_length=500, description='Human-readable issue description.') objectId: UUID | None = Field(default=None, description='Target business object ID.') field: str | None = Field(default=None, max_length=200, description='Path of the field responsible for this issue.') + relatedObjectId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, + description='Other business object involved in the issue.') class CommandReceipt(Contract): diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index bd0de3c82..7f6f5e80c 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -87,6 +87,8 @@ def project_relations(self): parents = {} for item in self.canvasItems: if item.parentId: + if item.kind == 'group' and item.autoLayout == 'run': + raise ValueError('Run layout requires a top-level group') if item.parentId not in items or items[item.parentId].kind != 'group': raise ValueError('Parent must be a group in the same project') parents[item.id] = [item.parentId] diff --git a/packages/core/src/opendirector/domain/creation/run_layout.py b/packages/core/src/opendirector/domain/creation/run_layout.py new file mode 100644 index 000000000..7fca8d2f0 --- /dev/null +++ b/packages/core/src/opendirector/domain/creation/run_layout.py @@ -0,0 +1,197 @@ +"""Arrange opted-in Run groups and their contents on the saved canvas.""" + +from collections import defaultdict +from dataclasses import dataclass +from math import isfinite +from uuid import UUID + +from .project import ProjectSnapshot +from .validation import ContractError + + +_RUN_ROW_WIDTH = 3000 +_RUN_GAP = 80 +_CONTENT_GAP = 32 +_PADDING = 24 +_HEADER_HEIGHT = 40 + + +@dataclass(frozen=True) +class _Bounds: + left: float + top: float + right: float + bottom: float + + @property + def width(self): + return self.right - self.left + + @property + def height(self): + return self.bottom - self.top + + def translate(self, x, y): + return _Bounds(self.left + x, self.top + y, self.right + x, self.bottom + y) + + def union(self, other): + return _Bounds(min(self.left, other.left), min(self.top, other.top), + max(self.right, other.right), max(self.bottom, other.bottom)) + + def overlaps(self, other, gap): + return (self.left < other.right + gap and self.right + gap > other.left + and self.top < other.bottom + gap and self.bottom + gap > other.top) + + +def _footprint(item, children): + """Include descendant overflow in the footprint of a group moved as a unit.""" + bounds = _Bounds(0, 0, item['width'], item['height']) + pending = [item] + origins = {item['id']: (0, 0)} + while pending: + parent = pending.pop() + x, y = origins[parent['id']] + for child in children.get(parent['id'], ()): + child_x = x + child['position']['x'] + child_y = y + child['position']['y'] + origins[child['id']] = (child_x, child_y) + bounds = bounds.union(_Bounds(child_x, child_y, child_x + child['width'], child_y + child['height'])) + pending.append(child) + return bounds + + +def _pack(items, fixed, *, left, top, right, gap): + """Pack in input order around fixed bounds. A wide item gets its own row.""" + x, y, row_bottom = left, top, top + for item, footprint in items: + row_limit = max(right, left + footprint.width) + blocker_bottom = None + while True: + if x + footprint.width > row_limit: + # A nonempty row wraps below its tallest item. An empty row + # that hit fixed objects skips to the first possible opening. + bottom = row_bottom if row_bottom > y else blocker_bottom + if bottom is None or not isfinite(bottom + gap) or bottom + gap <= y: + raise ContractError('canvas_run_layout_extent', '坐标或尺寸超出可排列范围,请缩小相关节点。', UUID(item['id'])) + y = bottom + gap + x, row_bottom, blocker_bottom = left, y, None + candidate = _Bounds(x, y, x + footprint.width, y + footprint.height) + if (not isfinite(candidate.right) or not isfinite(candidate.bottom) + or candidate.right <= x or candidate.bottom <= y): + raise ContractError('canvas_run_layout_extent', '坐标或尺寸超出可排列范围,请缩小相关节点。', UUID(item['id'])) + blockers = [bounds for bounds in fixed if candidate.overlaps(bounds, gap)] + if not blockers: + break + x = max(bounds.right for bounds in blockers) + gap + nearest_bottom = min(bounds.bottom for bounds in blockers) + blocker_bottom = nearest_bottom if blocker_bottom is None else min(blocker_bottom, nearest_bottom) + item['position'] = {'x': x - footprint.left, 'y': y - footprint.top} + x = candidate.right + gap + row_bottom = max(row_bottom, candidate.bottom) + + +def _positioned(item, footprint): + position = item['position'] + return footprint.translate(position['x'], position['y']) + + +def _layout_contents(run, children): + items = [(child, _footprint(child, children)) for child in children.get(run['id'], ())] + fixed = [_positioned(child, bounds) for child, bounds in items if child['locked']] + movable = [(child, bounds) for child, bounds in items if not child['locked']] + # Decide width before packing. Widening afterwards would change wrapping + # the next time the same canvas is laid out. + run['width'] = max(run['width'], max((bounds.right + _PADDING for bounds in fixed), default=0), + max((bounds.width + 2 * _PADDING for _, bounds in movable), default=0)) + _pack(movable, fixed, left=_PADDING, top=_HEADER_HEIGHT, right=run['width'] - _PADDING, + gap=_CONTENT_GAP) + content_bottom = max((_positioned(child, bounds).bottom for child, bounds in items), default=0) + run['height'] = max(_HEADER_HEIGHT, content_bottom) + _PADDING + + +def layout_runs(data: dict): + """Reflow visible, unlocked Run groups before calculating object revisions.""" + children = defaultdict(list) + for item in data['canvasItems']: + if item['visible']: + children[item['parentId']].append(item) + + runs, fixed, locked_runs = [], [], [] + for item in children[None]: + if item['kind'] == 'group' and item.get('autoLayout') == 'run' and not item['locked']: + _layout_contents(item, children) + runs.append((item, _footprint(item, children))) + else: + bounds = _positioned(item, _footprint(item, children)) + if item.get('autoLayout') == 'run': + for other, other_bounds in locked_runs: + if bounds.overlaps(other_bounds, 0): + raise ContractError('canvas_run_layout_conflict', '已锁定的 Run 区域重叠,请解锁其中一个后重试。', + UUID(item['id']), related_object_id=UUID(other['id'])) + locked_runs.append((item, bounds)) + fixed.append(bounds) + _pack(runs, fixed, left=0, top=0, right=_RUN_ROW_WIDTH, gap=_RUN_GAP) + + +def _validate_membership(canvas, managed, original): + items = {item['id']: item for item in canvas} + locked = {run_id for run_id in managed if items[run_id]['locked'] and original.get(run_id, {}).get('locked')} + if len(managed) < 2 and not locked: + return + owners = {} + for item in canvas: + root = item + while root['parentId'] is not None: + root = items[root['parentId']] + run_id = root['id'] + if run_id not in managed: + continue + previous = original.get(item['id']) + if run_id in locked and item is not root and (previous is None + or previous['parentId'] != item['parentId'] or (item['visible'] and not previous['visible'])): + raise ContractError('role_restricted', '所属 Run 已锁定,请解锁后再加入或显示节点。', UUID(run_id)) + binding = item['binding'] + references = list(item.get('editors', ())) + if binding['role'] in {'generation', 'editor'}: + references.append(binding['objectRef']) + elif binding['role'] == 'empty' and binding.get('draftSpec'): + references.append(binding['draftSpec']) + for reference in references: + owner = owners.setdefault(reference['id'], run_id) + if owner != run_id: + raise ContractError('canvas_run_layout_shared_object', '两个 Run 使用了同一个可编辑对象。请复制配置或编辑文档后重试。', + UUID(run_id), related_object_id=UUID(owner)) + + +_LAYOUT_FIELDS = ('position', 'width', 'height', 'parentId', 'visible', 'locked', 'autoLayout') + + +def reflow_runs(before: ProjectSnapshot, edited: ProjectSnapshot, *, force=False) -> tuple[ProjectSnapshot, set[UUID]]: + managed = {str(item.id) for item in edited.canvasItems if item.kind == 'group' and item.autoLayout == 'run'} + if not managed: + return edited, set() + canvas = [item.model_dump(mode='json') for item in edited.canvasItems] + original = {str(item.id): item.model_dump(mode='json') for item in before.canvasItems} + _validate_membership(canvas, managed, original) + if (not force and len(canvas) == len(original) + and all(item['id'] in original and all( + item.get(field) == original[item['id']].get(field) for field in _LAYOUT_FIELDS + ) for item in canvas)): + return edited, set() + + geometry = [(item['position'], item['width'], item['height']) for item in canvas] + layout_runs({'canvasItems': canvas}) + derived = set() + for item, prior_geometry in zip(canvas, geometry, strict=True): + if (item['position'], item['width'], item['height']) == prior_geometry: + continue + identity = item['id'] + derived.add(UUID(identity)) + previous = original.get(identity) + if previous is not None: + item['revision'] = previous['revision'] + if item != previous: + item['revision'] += 1 + if not derived: + return edited, derived + return ProjectSnapshot.model_validate({**edited.model_dump(), 'canvasItems': canvas}), derived diff --git a/packages/core/src/opendirector/domain/creation/validation.py b/packages/core/src/opendirector/domain/creation/validation.py index 8a3a7af9f..b8c9893b4 100644 --- a/packages/core/src/opendirector/domain/creation/validation.py +++ b/packages/core/src/opendirector/domain/creation/validation.py @@ -10,9 +10,9 @@ class ContractError(ValueError): - def __init__(self, code, message, object_id=None): + def __init__(self, code, message, object_id=None, *, related_object_id=None): super().__init__(message) - self.issue = ContractIssue(code=code, message=message, objectId=object_id) + self.issue = ContractIssue(code=code, message=message, objectId=object_id, relatedObjectId=related_object_id) @classmethod def from_error(cls, error: ValueError | ProjectError, object_id: UUID | None = None) -> 'ContractError': diff --git a/packages/core/src/opendirector/infrastructure/creation_publication.py b/packages/core/src/opendirector/infrastructure/creation_publication.py index a43ec088a..205276d81 100644 --- a/packages/core/src/opendirector/infrastructure/creation_publication.py +++ b/packages/core/src/opendirector/infrastructure/creation_publication.py @@ -10,6 +10,7 @@ from opendirector.domain.creation.base import digest 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.projects import ProjectError, identifier from opendirector.infrastructure.creation_files import cleanup_staging, delete_files, install_files @@ -73,6 +74,14 @@ def commit(self, command: Command, if snapshot.project.name != before.project.name and command.type != 'project.rename': raise ContractError('invalid_input', 'Only the rename command can rename a project') 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) + if organize_runs or any(item['version'].objectType == 'canvas_item' for item in changed): + # All service writes passed their original CAS above. Only the + # geometry derived from the locked current snapshot is exempt. + snapshot, derived = reflow_runs(before, snapshot, force=organize_runs) + if derived: + changed = object_changes(before, snapshot, command, derived_canvas=derived) if command.type == 'project.rename': self.local._conflict(self.root, snapshot.project.name, path) except ContractError as error: diff --git a/packages/core/src/opendirector/infrastructure/creation_records.py b/packages/core/src/opendirector/infrastructure/creation_records.py index c759fbd8b..58ebf0b87 100644 --- a/packages/core/src/opendirector/infrastructure/creation_records.py +++ b/packages/core/src/opendirector/infrastructure/creation_records.py @@ -96,7 +96,7 @@ def durable_json(path: Path, value): sync_directory(path.parent) -def object_changes(before, after, command): +def object_changes(before, after, command, *, derived_canvas=frozenset()): """The storage boundary also checks revisions on trusted service writes.""" old = object_index(before) if before else {} new = object_index(after) @@ -107,7 +107,8 @@ def object_changes(before, after, command): if previous == current: continue kind, object_id = key - if previous is not None and expected.get(key) != previous.revision: + derived = kind == 'canvas_item' and object_id in derived_canvas + if previous is not None and not derived and expected.get(key) != previous.revision: raise ContractError('revision_conflict', 'Every changed object requires its current version', object_id) if current is not None and current.revision != (previous.revision + 1 if previous else 1): raise ContractError('revision_conflict', 'Object revisions must advance exactly once', object_id) diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index e68ed479c..0c5e5b4c9 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -632,6 +632,7 @@ export class CreationProjection { height: item.height, locked: item.locked, ...(item.color ? { color: item.color } : {}), + ...(item.kind === "group" && item.autoLayout ? { autoLayout: item.autoLayout } : {}), zIndex: item.zIndex, parentId: item.parentId ?? undefined, }; @@ -1654,6 +1655,7 @@ export class CreationProjection { zIndex: node.zIndex ?? 0, locked: node.locked ?? false, ...(node.color ? { color: node.color } : {}), + ...(node.type === "group" && node.autoLayout ? { autoLayout: node.autoLayout } : {}), parentId: node.parentId ?? null, binding, } as CanvasItem, diff --git a/src/canvas/CanvasCreationMenu.tsx b/src/canvas/CanvasCreationMenu.tsx index 39a978eac..cc165d4fc 100644 --- a/src/canvas/CanvasCreationMenu.tsx +++ b/src/canvas/CanvasCreationMenu.tsx @@ -115,6 +115,7 @@ export function CanvasCreationMenu({ onPaste, onUndo, onRedo, + onOrganizeRuns, onClose, ...actions }: CreationActions & { @@ -127,6 +128,7 @@ export function CanvasCreationMenu({ onPaste: () => void; onUndo: () => void; onRedo: () => void; + onOrganizeRuns?: () => void; onClose: () => void; }) { const [expanded, setExpanded] = useState(false); @@ -275,6 +277,15 @@ export function CanvasCreationMenu({
+ {onOrganizeRuns && ( + + )}