Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/api/src/opendirector_api/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from opendirector.domain.timeline_errors import timeline_error_message
from opendirector.domain.url_import import url_import_message
from opendirector.domain.creation.contract_messages import contract_message

from opendirector.domain.creation.commands import CommandReceipt
from opendirector.domain.creation.contract_messages import contract_message
Expand All @@ -19,6 +20,11 @@

from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH

_DRAFT_DISCARD_MESSAGES = (
'Replacing a configured draft requires explicit discard (discardGenerationDraft).',
'替换已配置的草稿需要明确丢弃(discardGenerationDraft)。',
)

ENGLISH_BY_CODE = {
'video_compression_preset': 'Choose a valid compression preset.',
'video_compression_source': 'Select one video to compress.',
Expand Down Expand Up @@ -246,6 +252,8 @@ def localized_error_for_language(
or contract_message(code, language, chinese))
if specific is not None:
return specific
if chinese in _DRAFT_DISCARD_MESSAGES:
return _DRAFT_DISCARD_MESSAGES[0 if wants_english_language(language) else 1]
if not wants_english_language(language):
return chinese
if code == 'tool_model_missing':
Expand Down
15 changes: 12 additions & 3 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from opendirector.domain.creation.models import ModelConfigPublic
from opendirector.domain.creation.project import ProjectSnapshot, asset_references
from opendirector.domain.creation.index import object_index
from opendirector.domain.creation.contract_messages import version_required_message, version_required_output_revision_message
from opendirector.domain.creation.validation import ContractError
from opendirector.domain.input_rules import input_rules
from opendirector.domain.rule_facts import FRAME_IMAGE_LIMIT
Expand Down Expand Up @@ -399,8 +400,12 @@ def _apply_edit(self, data, payload, before, command):
raise ContractError('invalid_input', '裁剪参数与输出尺寸不一致。', doc.id)

expected = {(v.objectType, v.id): v.revision for v in command.expectedVersions}
if old_doc and expected.get(('editor_document', doc.id)) != old_doc.revision:
raise ContractError('revision_conflict', '应用编辑需要编辑文档版本。', doc.id)
if old_doc:
key = ('editor_document', doc.id)
if key not in expected:
raise ContractError('version_required', version_required_message([key]), doc.id)
if expected[key] != old_doc.revision:
raise ContractError('revision_conflict', 'Object changed; reread before modifying', doc.id)
output = self.assets._reference(snapshot, payload.asset)
if output.kind != 'image' or output.id == current.id:
raise ContractError('invalid_input', '编辑输出必须是独立图片素材。', output.id)
Expand Down Expand Up @@ -496,7 +501,11 @@ def _publish_render(self, data, payload):
existing = next((i for i in snapshot.canvasItems if i.id == payload.outputId), None)
if existing is not None:
if payload.expectedOutputRevision is None:
raise ContractError('revision_conflict', '输出节点已存在,请提供其当前版本。', payload.outputId)
raise ContractError(
'version_required',
version_required_output_revision_message(payload.outputId, existing.revision),
payload.outputId,
)
target = self._editable(data, payload.outputId)
previous = current_asset(snapshot, existing)
if (existing.kind != 'video' or existing.binding.role != 'material' or previous is None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ def command_fingerprint(command: Command) -> str:

class ContractIssue(Contract):
code: IssueCode = Field(description='Stable error or issue code.')
message: str = Field(min_length=1, max_length=500, description='Human-readable issue description.')
message: str = Field(min_length=1, max_length=2000, 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,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import re
from uuid import UUID

from pydantic_core import PydanticCustomError

Expand All @@ -10,6 +11,14 @@
'Read each current revision (query object.get --object-id ID) and send all of them: '
'expectedVersions += [{entries}]; CLI: {options}',
),
'version_required_output_revision': (
'发布到已有输出节点需要 payload.expectedOutputRevision(当前节点版本 {revision})。'
'请提供:expectedOutputRevision={revision},并在 expectedVersions 中带上 {entry};'
'CLI:--expected-output-revision {revision} {option}',
'Publishing to an existing output node requires payload.expectedOutputRevision '
'(current node revision {revision}). Send expectedOutputRevision={revision} and '
'expectedVersions += [{entry}]; CLI: --expected-output-revision {revision} {option}',
),
'use_canvas_move': (
'canvas.update 只带 position、不带 parentId 时是移动节点,请改用 canvas.move(如需换分组,再加 parentId):'
'{command};CLI:{cli}',
Expand All @@ -36,8 +45,16 @@

def _pattern(template: str) -> re.Pattern:
parts = re.split(r'\{(\w+)\}', template)
return re.compile(''.join(re.escape(part) if index % 2 == 0 else f'(?P<{part}>.*?)'
for index, part in enumerate(parts)), re.DOTALL)
seen, pieces = set(), []
for index, part in enumerate(parts):
if index % 2 == 0:
pieces.append(re.escape(part))
elif part in seen:
pieces.append(f'(?P={part})')
else:
seen.add(part)
pieces.append(f'(?P<{part}>.*?)')
return re.compile(''.join(pieces), re.DOTALL)


_PATTERNS = {code: _pattern(texts[1]) for code, texts in CONTRACT_MESSAGES.items()}
Expand All @@ -55,16 +72,51 @@ def contract_error(code: str, **fields: str) -> PydanticCustomError:
return PydanticCustomError(code, '{message}', {'message': contract_text(code, **fields), 'fields': fields})


def _message_codes(code: str | None) -> tuple[str, ...]:
if not code or code not in CONTRACT_MESSAGES:
return ()
return (code, *(other for other in CONTRACT_MESSAGES if other != code and other.startswith(f'{code}_')))


def contract_message(code: str | None, language: str | None, message: str,
fields: dict[str, str] | None = None) -> str | None:
if code not in CONTRACT_MESSAGES:
codes = _message_codes(code)
if not codes:
return None
if fields is None:
match = _PATTERNS[code].fullmatch(message)
if match is None:
if fields is not None:
resolved_code = code
else:
resolved_code = None
for candidate in codes:
match = _PATTERNS[candidate].fullmatch(message)
if match is not None:
resolved_code, fields = candidate, match.groupdict()
break
if resolved_code is None:
return None
fields = match.groupdict()
primary = (language or '').strip().split(',', 1)[0].split(';', 1)[0].strip().lower()
if primary and not primary.startswith('zh'):
return message
return CONTRACT_MESSAGES[code][0].format(**fields)
return CONTRACT_MESSAGES[resolved_code][0].format(**fields)


def version_required_message(
missing: list[tuple[str, UUID]],
known: dict[tuple[str, UUID], int] | None = None,
) -> str:
entries, options = [], []
for kind, identity in dict.fromkeys(missing):
revision = (known or {}).get((kind, identity))
entries.append(f'{{"objectType":"{kind}","id":"{identity}","revision":{revision or "REVISION"}}}')
options.append(f'--expected-version {kind}:{identity}:{revision or "REVISION"}')
return contract_text('version_required', entries=', '.join(entries), options=' '.join(options))


def version_required_output_revision_message(output_id: UUID, revision: int) -> str:
identity = str(output_id)
entry = f'{{"objectType":"canvas_item","id":"{identity}","revision":{revision}}}'
option = f'--expected-version canvas_item:{identity}:{revision}'
return contract_text(
'version_required_output_revision',
id=identity, revision=revision, entry=entry, option=option,
)
23 changes: 17 additions & 6 deletions packages/core/src/opendirector/domain/creation/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .canvas import GroupCanvasItem, MediaCanvasItem, role_after
from .commands import Command, ContractIssue, IssueCode
from .contract_messages import contract_text
from .contract_messages import contract_text, version_required_message
from .project import ProjectSnapshot


Expand Down Expand Up @@ -75,8 +75,17 @@ def get(kind, object_id):
if item.binding.role == 'empty' and item.binding.draftSpec:
spec = get('generation_spec', item.binding.draftSpec.id)
if spec.prompt or spec.modelConfigId or spec.promptContent:
if not payload.discardGenerationDraft or expected.get(('generation_spec', spec.id)) != spec.revision:
raise ContractError('revision_conflict', 'Replacing configured draft requires explicit discard and its version', spec.id)
key = ('generation_spec', spec.id)
if key not in expected:
raise ContractError('version_required', version_required_message([key]), spec.id)
if expected[key] != spec.revision:
raise ContractError('revision_conflict', 'Object changed; reread before modifying', spec.id)
if not payload.discardGenerationDraft:
raise ContractError(
'invalid_input',
'Replacing a configured draft requires explicit discard (discardGenerationDraft).',
spec.id,
)
else:
if item.kind == 'file':
raise ContractError('role_restricted', 'File nodes cannot generate', item_id)
Expand All @@ -91,9 +100,11 @@ def get(kind, object_id):
raise ContractError('role_restricted', 'Configuration edits cannot change purpose, kind or result selection', current.id)
if command.type == 'reference.add':
spec = get('generation_spec', payload.reference.targetSpecId)
if any(isinstance(item, MediaCanvasItem) and item.binding.role == 'empty' and item.binding.draftSpec
and item.binding.draftSpec.id == spec.id and ('canvas_item', item.id) not in expected for item in project.canvasItems):
raise ContractError('revision_conflict', 'Locking an empty node requires its current version', spec.id)
missing = [('canvas_item', item.id) for item in project.canvasItems
if isinstance(item, MediaCanvasItem) and item.binding.role == 'empty' and item.binding.draftSpec
and item.binding.draftSpec.id == spec.id and ('canvas_item', item.id) not in expected]
if missing:
raise ContractError('version_required', version_required_message(missing), missing[0][1])
if command.type in {'job.cancel', 'job.recover'}:
get('job', payload.jobId)
if command.type == 'result.select':
Expand Down
4 changes: 2 additions & 2 deletions src/contracts/creation.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -4577,7 +4577,7 @@
},
"message": {
"description": "Human-readable issue description.",
"maxLength": 500,
"maxLength": 2000,
"minLength": 1,
"title": "Message",
"type": "string"
Expand Down Expand Up @@ -24616,7 +24616,7 @@
},
"message": {
"description": "Human-readable issue description.",
"maxLength": 500,
"maxLength": 2000,
"minLength": 1,
"title": "Message",
"type": "string"
Expand Down
73 changes: 73 additions & 0 deletions tests/creationClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,43 @@ test("a rejected move rebases over generated dimensions and preserves the genera
assert.equal(client.snapshot.canvasItems[0]!.binding.role, "material");
});

test("a version_required rejection does not rebase or retry a batch save", async () => {
const { client, projection, document, node } = presentationFixture();
const missing = new CreationCommandError({
commandId: crypto.randomUUID(),
projectId: client.id,
inputFingerprint: "a".repeat(64),
status: "rejected",
changed: [],
jobIds: [],
eventCursor: 1,
issues: [
{
code: "version_required",
message: "expectedVersions missing current versions",
objectId: node.id,
field: null,
},
],
});
let calls = 0;
client.batch = async (operations, versions) => {
calls++;
client.batches.push({ operations, versions });
throw missing;
};
await assert.rejects(
projection.save(
{
...document,
nodes: [{ ...node, position: { x: 100, y: 25 } }],
},
{ saveView: false },
),
);
assert.equal(calls, 1);
});

test("renaming sends only the edited field and rebases over a generated size", async () => {
const { client, projection, document, basis, item, node, conflict } =
presentationFixture();
Expand Down Expand Up @@ -1372,6 +1409,42 @@ test("cancel compares the same execution after confirmed progress conflicts, nev
}
});

test("cancel does not retry a missing-version version_required rejection", async () => {
const snapshot = JSON.parse(
readFileSync(
new URL("./fixtures/creation-project.json", import.meta.url),
"utf8",
),
) as ProjectSnapshot;
const client = new CreationClient(snapshot.project.id);
const job = { ...snapshot.jobs[0]!, status: "running" as const };
client.install({ ...snapshot, jobs: [job] });
client.refresh = async () => client.snapshot;
let calls = 0;
client.command = async () => {
calls++;
throw new CreationCommandError({
commandId: crypto.randomUUID(),
projectId: client.id,
inputFingerprint: "a".repeat(64),
status: "rejected",
changed: [],
jobIds: [],
issues: [
{
code: "version_required",
message: "expectedVersions missing current versions",
objectId: job.id,
field: null,
},
],
eventCursor: 1,
});
};
await assert.rejects(client.control(job.id, "cancel"));
assert.equal(calls, 1);
});

test("an older square audio card projects as the compact control strip", async () => {
const snapshot = empty();
const audio = createNode("audio", { x: 10, y: 20 }, { title: "Voice" });
Expand Down
3 changes: 2 additions & 1 deletion tests/test_command_version_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ def test_chinese_templates_contain_no_english_prose(code):
import re
words = set(re.findall(r'[A-Za-z][\w.-]*', re.sub(r'\{\w+\}', '', CONTRACT_MESSAGES[code][0])))
assert words <= {'expectedVersions', 'query', 'object.get', 'object-id', 'ID', 'CLI', 'canvas.update', 'position',
'parentId', 'canvas.move', 'NEXT_REVISION'}
'parentId', 'canvas.move', 'NEXT_REVISION', 'payload.expectedOutputRevision',
'expectedOutputRevision', 'expected-output-revision'}


def _update_error(item_id, **payload):
Expand Down
5 changes: 4 additions & 1 deletion tests/test_creation_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -489,8 +489,11 @@ def test_commands_prevent_role_bypass_and_require_explicit_draft_discard():
validate_command(overwrite, p)
assert error.value.issue.code == 'role_restricted'
payload = dict(itemId=uid(52), asset=asset_ref(p.assets[0]))
with pytest.raises(ContractError, match='discard'):
with pytest.raises(ContractError) as missing:
validate_command(command('canvas.materialize', payload, [('canvas_item', 52, 1)]), p)
assert missing.value.issue.code == 'version_required'
with pytest.raises(ContractError, match='discard'):
validate_command(command('canvas.materialize', payload, [('canvas_item', 52, 1), ('generation_spec', 61, 1)]), p)
validate_command(command('canvas.materialize', {**payload, 'discardGenerationDraft': True},
[('canvas_item', 52, 1), ('generation_spec', 61, 1)]), p)
flipped = {**p.generationSpecs[1].model_dump(), 'purpose': 'generation'}
Expand Down
Loading
Loading