diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 52d810fae..8081f3a84 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -291,7 +291,7 @@ def projection(project_id: UUID): return canvas.projection(project_id) @router.post('/projects/{project_id}/queries') - async def query(project_id: UUID, value: CreationQuery): + async def query(project_id: UUID, value: CreationQuery, request: Request): if value.projectId != project_id: raise ProjectError('查询不属于当前工程。') if value.type in {'pipeline.plan', 'pipeline.execution.get', 'pipeline.executions.list'}: @@ -306,6 +306,8 @@ async def query(project_id: UUID, value: CreationQuery): return {'executions': await executor.history(project_id, value.groupId)} return await executor.status(project_id, value.objectId) result = await canvas.query(value) + if value.type == 'receipt.get': + return localized_receipt(request, CommandReceipt.model_validate(result)) if value.type == 'asset.preview' and 'preview' in result: result['preview'].pop('path') result['preview']['url'] = f'/api/creation/projects/{project_id}/assets/{value.objectId}/preview' diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index d826de4e3..1dcc8a12e 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -174,9 +174,10 @@ "chat_incomplete_response": "The model response did not finish normally (it may have hit a length limit or content filter). Any generated content has been preserved.", "invalid_input": "The request is invalid. Check the required fields and their formats.", "invalid_project": "The project or asset identifier is invalid.", + "command_conflict": "This operation ID was already used with different input. Use a new operation ID for changed input, or inspect the original receipt.", + "missing_receipt": "No committed receipt was found for this command or operation ID.", "missing_object": "The requested item no longer exists.", "not_found": "The requested item no longer exists.", - "command_conflict": "This identifier was already used with different input. Use a new identifier.", "revision_conflict": "This item changed since it was loaded. Reload it and try again.", "preview_expired": "The preview expired. Generate it again.", "reference_invalid": "A reference is no longer valid. Select it again and retry.", @@ -250,6 +251,8 @@ def localized_error_for_language( translated = english_capability_message(chinese) if translated: return translated + if code == 'command_conflict' and chinese == '该工程标识已经使用。': + return 'This project ID is already in use.' if code == 'invalid_input' and chinese == '聊天引用超过数量上限,请移除部分引用。': return 'The chat reference limit was exceeded. Remove some references and retry.' if code == 'invalid_input' and chinese == '视频裁切需要视频来源节点。': diff --git a/docs/guides/cli.md b/docs/guides/cli.md index b5c29b91f..5c22d6878 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -63,9 +63,11 @@ opendirector --project PROJECT_UUID job wait --all --timeout 300 CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回一条覆盖本次全部任务的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;等待窗口超时后可以再次执行同一命令。`job wait` 超时结束等待,任务继续由后台执行。 -修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则拒绝。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先查询回执,再决定后续操作。 +修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则以错误码 `command_conflict` 拒绝,并返回省略或更换 `--operation-id` 及查看原回执的指引(Agent 模式下附带 `receiptCommand` 与 `guidance`)。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先用 `opendirector --project PROJECT_UUID receipt show OPERATION_OR_COMMAND_UUID`(或 `query receipt.get --object-id UUID`)查询原操作回执,未找到已提交回执时返回 404 与错误码 `missing_receipt`。 -读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 +Pass `--operation-id UUID` before a write subcommand for idempotent retries. Replaying the same ID with identical input returns the original receipt; changing the input is rejected with `command_conflict` (in Agent mode, with `guidance` and a `receiptCommand` when an operation UUID is present). When an outcome is unknown, run `opendirector --project PROJECT_UUID receipt show OPERATION_OR_COMMAND_UUID` (or `query receipt.get --object-id UUID`) before deciding whether to submit a new operation; missing receipts return 404 with `missing_receipt`. + +读取类查询 `job.get`、`object.get`、`canvas.status`、`job.status` 与 `receipt.get` 不占用本轮执行锁,因此等待任务或查询回执不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样为 60 秒且不自动续期,进程被强行终止也不会长期占用;单条命令(例如上传大文件)超过 60 秒时,写入可能因会话过期被拒,原窗口此时已转为预览,需要重新执行或在窗口中收回。使用 `--session UUID` 时,接管的编辑权留在该会话、命令结束后不释放,仍在 60 秒后过期,除非该会话自行续期。 diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index e919fb221..3cb2fd3f7 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -41,11 +41,41 @@ def event(self, name: str) -> AgentEvent: # Reads are answered from immutable snapshots, so a wait cannot block unrelated # work; writes still hold the turn's single execution slot. -READ_ONLY_QUERIES = frozenset({'job.status', 'job.get', 'object.get', 'canvas.status'}) +READ_ONLY_QUERIES = frozenset({'job.status', 'job.get', 'object.get', 'canvas.status', 'receipt.get'}) # Queries that wait for a business state. Closing a turn cancels them; a read # that has not been answered is worth nothing once the turn is over. WAITING_QUERIES = frozenset({'job.status', 'canvas.status'}) +COMMAND_CONFLICT_ZH = ( + '工具调用标识被用于不同输入。修改输入后请省略 --operation-id 或使用新的操作标识;' + '如需确认原操作是否已提交,请查询原操作回执。' +) + + +def _command_conflict(call_id: str) -> ToolResult: + receipt_command = None + if call_id.startswith('cli:'): + raw = call_id.removeprefix('cli:') + try: + receipt_command = f'opendirector receipt show {UUID(raw)}' + except ValueError: + receipt_command = None + guidance = ( + f'Reuse an operation ID only for identical retries. Omit --operation-id or pass a new UUID for changed input, ' + f'or run `{receipt_command}` to inspect the original operation receipt.' + if receipt_command else + 'Reuse a call ID only for identical retries. Use a new call ID for changed input, ' + 'or query receipt.get with the commandId from the original tool result to inspect its receipt.' + ) + value: dict[str, JsonValue] = { + 'error': COMMAND_CONFLICT_ZH, + 'code': 'command_conflict', + 'callId': call_id, + 'guidance': guidance, + **({'receiptCommand': receipt_command} if receipt_command else {}), + } + return ToolResult(value=value, error=COMMAND_CONFLICT_ZH) + def _read_only(name, arguments) -> bool: """Whether this call may skip the execution lock. @@ -81,7 +111,7 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) - previous = self.calls.get(call_id) if previous is not None: if previous[0] != identity: - return ToolResult(value={'error': '工具调用标识被用于不同输入。'}, error='工具调用标识被用于不同输入。') + return _command_conflict(call_id) task = previous[1] else: task = asyncio.create_task(self.execute(call_id, name, deepcopy(arguments))) diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index a78550032..51dff776b 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -704,6 +704,14 @@ def recording(): # A rejected query must name the accepted types rather than echo a # tag list the model has to reinterpret. raise ProjectError(query_guidance(failure)) from None + if query.type == 'receipt.get': + candidates = ( + query.objectId, + agent_command_id(turn_id, 'cli:' + str(query.objectId)), + agent_command_id(turn_id, str(query.objectId)), + ) + found = await asyncio.to_thread(self.projects.receipt_any, project_id, candidates) + return found.model_dump(mode='json') if query.type in {'pipeline.plan', 'pipeline.execution.get', 'pipeline.executions.list'}: executor = getattr(self.generation, 'pipelines', None) if executor is None: diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 25b4fd196..d8c83cc9d 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -1014,6 +1014,8 @@ async def query(self, query: Query) -> JsonValue: return await self.wait_item_status(query.projectId, query.objectId, query.waitSeconds) if query.type == 'job.status': return await self.wait_jobs(query.projectId, query.objectIds, query.waitSeconds, query.until) + if query.type == 'receipt.get': + return to_jsonable_python(await asyncio.to_thread(self.projects.receipt, query.projectId, query.objectId)) if query.type == 'asset.preview': target = self.projects.local.state_dir / 'previews' / str(query.projectId) return await asyncio.to_thread(CreationAssets(self.projects).preview, query.projectId, query.objectId, target) diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 2982c1daf..6e9abebd6 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -59,6 +59,7 @@ "canvas": "Display, arrange, hide and configure canvas items.", "video": "Create video generation nodes or trim a source video.", "job": "Inspect, wait for, cancel or recover generation jobs.", + "receipt": "Inspect persisted receipts for earlier commands or operation IDs.", "artifact": "Register files from the active agent execution directory.", "generation-spec": "Create, edit and restore generation settings and prompts.", "reference": "Add, update, restore or remove generation input references.", @@ -524,6 +525,14 @@ def compression_task(ctx: typer.Context, task_id: Annotated[UUID, typer.Argument } +class _CliCallError(ProjectError): + def __init__(self, message: str, status: int = 400, *, code: str | None = None, + guidance: str | None = None, receipt_command: str | None = None): + super().__init__(message, status, code=code) + self.guidance = guidance + self.receipt_command = receipt_command + + class Client: def __init__(self, project, url, session, operation_id, take_over=False): self.project = project @@ -585,6 +594,12 @@ def call(self, name, arguments, *, identity=None): with connection.makefile("rb") as reader: response = json.loads(reader.readline(64 * 1024 * 1024)) if response.get("error"): + detail = response.get("value") if isinstance(response.get("value"), dict) else {} + guidance = detail.get("guidance") if isinstance(detail.get("guidance"), str) else None + receipt_command = detail.get("receiptCommand") if isinstance(detail.get("receiptCommand"), str) else None + if guidance or receipt_command: + raise _CliCallError(response["error"], code=response.get('code'), + guidance=guidance, receipt_command=receipt_command) raise ProjectError(response["error"], code=response.get('code')) return response["value"] @@ -1347,6 +1362,15 @@ def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Arg raise typer.Exit(2) +@group("receipt").command("show", help="Read the persisted receipt for a command ID or this turn's --operation-id.") +def receipt_show(ctx: typer.Context, + operation_id: Annotated[UUID, typer.Argument(help="Command ID or operation ID from an earlier attempt.")]): + client = ctx.obj + client.command = ctx.command_path + emit(client.query("receipt.get", objectId=str(operation_id)) if client.live + else client.request("GET", client.path(f"/receipts/{operation_id}"))) + + @app.command("capabilities", help="List every business command with its required fields; one call replaces per-command --help discovery.") def capabilities(compact: Annotated[bool, typer.Option("--compact", help="Only names, summaries and required fields.")] = False): from typing import get_args @@ -1543,12 +1567,28 @@ def main(): value = {"error": str(error)} if isinstance(error, ProjectError): value['code'] = error.code + guidance = error.guidance if isinstance(error, _CliCallError) else None + receipt_command = error.receipt_command if isinstance(error, _CliCallError) else None language = os.environ.get('OPENDIRECTOR_LANGUAGE', 'en-US') translated = timeline_error_message(error.code, language) if not language.lower().startswith('zh'): translated = translated or ASSET_DOWNLOAD_ENGLISH.get(error.code) + if translated is None and error.code == 'missing_receipt': + translated = 'No committed receipt was found for this command or operation ID.' + elif (translated is None and error.code == 'command_conflict' + and (isinstance(error, _CliCallError) or any('\u3400' <= ch <= '\u9fff' for ch in str(error)))): + command_hint = receipt_command or 'opendirector receipt show ' + translated = ( + 'This project ID is already in use.' if str(error) == '该工程标识已经使用。' else + f'This operation ID was already used with different input. Omit --operation-id or pass a new UUID ' + f'for changed input, or run `{command_hint}` to inspect the original receipt.' + ) value['error'] = (translated or url_import_message(error.code, language, str(error)) or contract_message(error.code, language, str(error)) or str(error)) + if guidance: + value['guidance'] = guidance + if receipt_command: + value['receiptCommand'] = receipt_command emit(value) raise SystemExit(1) diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index a01d79662..124476e58 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -712,6 +712,11 @@ class AssetPreviewQuery(QueryBase): objectId: UUID = Field(description='Asset ID.') +class ReceiptQuery(QueryBase): + type: Literal['receipt.get'] = Field(description='Read the persisted receipt for a command ID or current-turn operation ID.') + objectId: UUID = Field(description='Command ID or operation ID to inspect.') + + class PipelinePlanQuery(QueryBase): type: Literal['pipeline.plan'] = Field(description='Compile a Pipeline DAG read-only and preview cache hits, dependencies, and issues.') scope: PipelineScope = Field(description='Target canvas scope to compile.') @@ -732,7 +737,7 @@ class PipelineExecutionsQuery(QueryBase): Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | - CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | PipelinePlanQuery | + CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | ReceiptQuery | PipelinePlanQuery | PipelineExecutionQuery | PipelineExecutionsQuery, Field(discriminator='type')] diff --git a/packages/core/src/opendirector/infrastructure/creation_commit_log.py b/packages/core/src/opendirector/infrastructure/creation_commit_log.py index 3e8458a0d..1ad00d6bb 100644 --- a/packages/core/src/opendirector/infrastructure/creation_commit_log.py +++ b/packages/core/src/opendirector/infrastructure/creation_commit_log.py @@ -519,11 +519,15 @@ def history_index(self, project_id): ) for r in records if r.visible_in_history) def receipt(self, project_id, command_id): - records = self.records(project_id) - found = next((record.receipt for record in records if str(record.command.commandId) == str(command_id)), None) - if found is None: - raise ProjectError('没有该命令的已提交回执。', 404) - return found.model_copy(deep=True) + return self.receipt_any(project_id, (command_id,)) + + def receipt_any(self, project_id, command_ids): + by_id = {str(record.command.commandId): record.receipt for record in self.records(project_id)} + for command_id in command_ids: + found = by_id.get(str(command_id)) + if found is not None: + return found.model_copy(deep=True) + raise ProjectError('没有该命令的已提交回执。', 404, code='missing_receipt') def changes(self, project_id, *, after=0, limit=100): if type(after) is not int or after < 0 or type(limit) is not int or not 1 <= limit <= 200: diff --git a/packages/core/src/opendirector/integrations/minimax_video.py b/packages/core/src/opendirector/integrations/minimax_video.py index d070e039f..2ffbfa133 100644 --- a/packages/core/src/opendirector/integrations/minimax_video.py +++ b/packages/core/src/opendirector/integrations/minimax_video.py @@ -12,12 +12,13 @@ from opendirector.integrations.generation_errors import protocol_failure, provider_failure, transport_failure from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment from opendirector.integrations.reference_inputs import data_uri, image_type, references, request_size, reference_text -from opendirector.integrations.volcengine import bounded +from opendirector.integrations.volcengine import DEFAULT_POLL_RETRY_DELAYS, bounded, retry_poll from opendirector.media.probe import probe, require_ffprobe class MinimaxVideoGeneration: - def __init__(self, store, transport=None, poll_interval=3): + def __init__(self, store, transport=None, poll_interval=3, retry_delays=DEFAULT_POLL_RETRY_DELAYS): self.store, self.transport, self.poll_interval = store, transport, poll_interval + self.retry_delays = retry_delays def validate(self, kind, config): if kind != 'video' or config['modelId'] not in MINIMAX_MODELS: @@ -130,9 +131,12 @@ async def generate(self, config, task, submitted, *, result_ready=None): raise protocol_failure(stage) await submitted(external_id) stage = 'poll' + query_url = base + '/query/video_generation/' + quote(external_id, safe='') + async def read_status(): + async with client.stream('GET', query_url, headers=auth_headers(config)) as response: + return json.loads(await bounded(response, stage=stage, secrets=secrets, limit=1024 * 1024)) while True: - async with client.stream('GET', base + '/query/video_generation/' + quote(external_id, safe=''), headers=auth_headers(config)) as response: - value = json.loads(await bounded(response, stage=stage, secrets=secrets, limit=1024 * 1024)) + value = await retry_poll(read_status, self.retry_delays) remote = value['task'] if remote['id'] != external_id: raise protocol_failure(stage) diff --git a/packages/core/src/opendirector/integrations/model_adapters.py b/packages/core/src/opendirector/integrations/model_adapters.py index e882b0171..f5ef5cd8e 100644 --- a/packages/core/src/opendirector/integrations/model_adapters.py +++ b/packages/core/src/opendirector/integrations/model_adapters.py @@ -37,7 +37,7 @@ from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment from opendirector.integrations.reference_inputs import data_uri, image_type, request_size -from opendirector.integrations.volcengine import VolcengineGeneration, bounded, endpoint +from opendirector.integrations.volcengine import DEFAULT_POLL_RETRY_DELAYS, VolcengineGeneration, bounded, endpoint, retry_poll from opendirector.media import processing as media from opendirector.media.async_work import blocking @@ -113,8 +113,8 @@ class ModelAdapter: capabilities: frozenset[str] = frozenset() supports_native_mask = False - def __init__(self, transport=None, poll_interval=3): - self.transport, self.poll_interval = transport, poll_interval + def __init__(self, transport=None, poll_interval=3, retry_delays=DEFAULT_POLL_RETRY_DELAYS): + self.transport, self.poll_interval, self.retry_delays = transport, poll_interval, retry_delays def image_parameters(self, width, height, **options): """Only adapters with an exact image-route projection supply fields.""" @@ -669,9 +669,11 @@ async def _job(self, config, fields, files, submitted): await submitted(external_id) stage = 'poll' url = base + '/' + quote(external_id, safe='') - while True: + async def read_status(): async with client.stream('GET', url, headers=headers) as response: - value = json.loads(await bounded(response, stage=stage, secrets=secrets)) + return json.loads(await bounded(response, stage=stage, secrets=secrets)) + while True: + value = await retry_poll(read_status, self.retry_delays) status = value.get('status') if status == 'completed': stage = 'download' diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 4c9eacbe4..e6d90cf8b 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -34,11 +34,11 @@ class GenerationProviders(VolcengineGeneration): def __init__(self, store, transport=None, poll_interval=3, retry_delays=(0.5, 1.0)): super().__init__(store, transport, poll_interval, retry_delays) - self.minimax_video = MinimaxVideoGeneration(store, transport, poll_interval) + self.minimax_video = MinimaxVideoGeneration(store, transport, poll_interval, retry_delays) self.bigmodel_video = BigModelVideoGeneration(store, transport, poll_interval, retry_delays) self.kling_video = KlingVideoGeneration(store, transport, poll_interval, retry_delays) self.higgsfield_open = HiggsfieldOpenGeneration(store, transport, poll_interval, retry_delays) - self.vllm_omni = VllmOmniGeneration(store, transport, poll_interval) + self.vllm_omni = VllmOmniGeneration(store, transport, poll_interval, retry_delays) self.vllm_omni_image = VllmOmniImageGeneration(store, transport, poll_interval) self.minimax_image = MinimaxH3Images(transport, poll_interval) self.moss_image = MossImages(transport, poll_interval) diff --git a/packages/core/src/opendirector/integrations/vllm_omni.py b/packages/core/src/opendirector/integrations/vllm_omni.py index cd8ce528c..523a8d1cd 100644 --- a/packages/core/src/opendirector/integrations/vllm_omni.py +++ b/packages/core/src/opendirector/integrations/vllm_omni.py @@ -18,7 +18,7 @@ from opendirector.integrations.http_settings import MODEL_HTTP_HOOKS, auth_headers, trust_environment from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.reference_inputs import generation_references -from opendirector.integrations.volcengine import bounded, endpoint +from opendirector.integrations.volcengine import DEFAULT_POLL_RETRY_DELAYS, bounded, endpoint, retry_poll from opendirector.media.probe import require_ffprobe FPS = 24 @@ -108,8 +108,9 @@ async def continuation_rejection(response, stage, secrets): class VllmOmniGeneration: - def __init__(self, store, transport=None, poll_interval=3): + def __init__(self, store, transport=None, poll_interval=3, retry_delays=DEFAULT_POLL_RETRY_DELAYS): self.store, self.transport, self.poll_interval = store, transport, poll_interval + self.retry_delays = retry_delays def validate(self, kind, config): if kind != 'video': @@ -163,9 +164,11 @@ async def generate(self, config, task, submitted, *, result_ready=None): await submitted(external_id) stage = 'poll' url = base + '/' + quote(external_id, safe='') - while True: + async def read_status(): async with client.stream('GET', url, headers=headers) as response: - value = json.loads(await bounded(response, stage=stage, secrets=secrets)) + return json.loads(await bounded(response, stage=stage, secrets=secrets)), response.status_code + while True: + value, status_code = await retry_poll(read_status, self.retry_delays) status = value.get('status') if status == 'completed': stage = 'download' @@ -175,7 +178,7 @@ async def generate(self, config, task, submitted, *, result_ready=None): if status in {'failed', 'cancelled', 'expired'}: if status == 'failed' and _missing_latents(value): raise _continuation_failure(stage) - raise provider_failure(value, stage=stage, http_status=response.status_code, secrets=secrets) + raise provider_failure(value, stage=stage, http_status=status_code, secrets=secrets) if status not in {'queued', 'in_progress'}: raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index d574b8328..a3ee9c8b0 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -42,24 +42,29 @@ async def _public_result_url(url): unresolved=lambda: transport_failure('download')) +DEFAULT_POLL_RETRY_DELAYS = (0.5, 1.0) + + +async def retry_poll(operation, retry_delays=DEFAULT_POLL_RETRY_DELAYS): + for attempt in range(len(retry_delays) + 1): + try: + return await operation() + except GenerationError as failure: + if failure.details.category not in {'temporary', 'rate_limit'} or attempt == len(retry_delays): + raise + except httpx.HTTPError: + if attempt == len(retry_delays): + raise + await asyncio.sleep(retry_delays[attempt]) + + class VolcengineGeneration: - def __init__(self, store, transport=None, poll_interval=3, retry_delays=(0.5, 1.0)): + def __init__(self, store, transport=None, poll_interval=3, retry_delays=DEFAULT_POLL_RETRY_DELAYS): self.store, self.transport, self.poll_interval = store, transport, poll_interval self.retry_delays = retry_delays async def _retry_read(self, operation): - for attempt in range(len(self.retry_delays) + 1): - try: - return await operation() - except GenerationError as failure: - if failure.details.category not in {'temporary', 'rate_limit'}: - raise - if attempt == len(self.retry_delays): - raise - except httpx.HTTPError: - if attempt == len(self.retry_delays): - raise - await asyncio.sleep(self.retry_delays[attempt]) + return await retry_poll(operation, self.retry_delays) async def resume_result(self, config, suffix, url, *, public_only=False): secrets = (config['apiKey'],) if config else () diff --git a/src/canvas/assistantToolText.ts b/src/canvas/assistantToolText.ts index df273e467..ec2bff5a6 100644 --- a/src/canvas/assistantToolText.ts +++ b/src/canvas/assistantToolText.ts @@ -23,6 +23,12 @@ const BY_MESSAGE: Record = { "批量命令包含未开放的 Agent 操作。": "assistant.reply.toolForbidden", }; +const BY_CODE: Record = { + capability_paused: "errors.capability.paused", + command_conflict: "assistant.reply.toolIdConflict", + missing_receipt: "assistant.reply.missingReceipt", +}; + /** Keep English tool errors and codes; replace Chinese detail in English UI. */ export function assistantToolText( text: string, @@ -33,6 +39,6 @@ export function assistantToolText( const capability = capabilityErrorText(text, t); if (capability) return capability; // Codes describe the category; known detail above always takes priority. - if (code === "capability_paused") return t("errors.capability.paused"); + if (code && BY_CODE[code]) return t(BY_CODE[code]); return t(BY_MESSAGE[text] ?? "assistant.reply.toolError"); } diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 90c059d80..7a167b4bf 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -5030,7 +5030,8 @@ "pipeline.execution.get": "#/$defs/PipelineExecutionQuery", "pipeline.executions.list": "#/$defs/PipelineExecutionsQuery", "pipeline.plan": "#/$defs/PipelinePlanQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "receipt.get": "#/$defs/ReceiptQuery" }, "propertyName": "type" }, @@ -5059,6 +5060,9 @@ { "$ref": "#/$defs/AssetPreviewQuery" }, + { + "$ref": "#/$defs/ReceiptQuery" + }, { "$ref": "#/$defs/PipelinePlanQuery" }, @@ -14026,6 +14030,43 @@ "title": "QueryBase", "type": "object" }, + "ReceiptQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "receipt.get", + "description": "Read the persisted receipt for a command ID or current-turn operation ID.", + "title": "Type", + "type": "string" + }, + "objectId": { + "description": "Command ID or operation ID to inspect.", + "format": "uuid", + "title": "Objectid", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "objectId" + ], + "title": "ReceiptQuery", + "type": "object" + }, "RectangleLayerContent": { "additionalProperties": false, "properties": { @@ -19697,7 +19738,8 @@ "pipeline.execution.get": "#/$defs/PipelineExecutionQuery", "pipeline.executions.list": "#/$defs/PipelineExecutionsQuery", "pipeline.plan": "#/$defs/PipelinePlanQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "receipt.get": "#/$defs/ReceiptQuery" }, "propertyName": "type" }, @@ -19726,6 +19768,9 @@ { "$ref": "#/$defs/AssetPreviewQuery" }, + { + "$ref": "#/$defs/ReceiptQuery" + }, { "$ref": "#/$defs/PipelinePlanQuery" }, @@ -25020,7 +25065,8 @@ "pipeline.execution.get": "#/$defs/PipelineExecutionQuery", "pipeline.executions.list": "#/$defs/PipelineExecutionsQuery", "pipeline.plan": "#/$defs/PipelinePlanQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "receipt.get": "#/$defs/ReceiptQuery" }, "propertyName": "type" }, @@ -25049,6 +25095,9 @@ { "$ref": "#/$defs/AssetPreviewQuery" }, + { + "$ref": "#/$defs/ReceiptQuery" + }, { "$ref": "#/$defs/PipelinePlanQuery" }, @@ -34334,6 +34383,43 @@ "title": "QueryBase", "type": "object" }, + "ReceiptQuery": { + "additionalProperties": false, + "properties": { + "queryId": { + "description": "Caller-supplied query ID.", + "format": "uuid", + "title": "Queryid", + "type": "string" + }, + "projectId": { + "description": "Owning project ID.", + "format": "uuid", + "title": "Projectid", + "type": "string" + }, + "type": { + "const": "receipt.get", + "description": "Read the persisted receipt for a command ID or current-turn operation ID.", + "title": "Type", + "type": "string" + }, + "objectId": { + "description": "Command ID or operation ID to inspect.", + "format": "uuid", + "title": "Objectid", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "objectId" + ], + "title": "ReceiptQuery", + "type": "object" + }, "RectangleLayerContent": { "additionalProperties": false, "properties": { @@ -40217,7 +40303,8 @@ "pipeline.execution.get": "#/$defs/PipelineExecutionQuery", "pipeline.executions.list": "#/$defs/PipelineExecutionsQuery", "pipeline.plan": "#/$defs/PipelinePlanQuery", - "project.get": "#/$defs/ProjectQuery" + "project.get": "#/$defs/ProjectQuery", + "receipt.get": "#/$defs/ReceiptQuery" }, "propertyName": "type" }, @@ -40246,6 +40333,9 @@ { "$ref": "#/$defs/AssetPreviewQuery" }, + { + "$ref": "#/$defs/ReceiptQuery" + }, { "$ref": "#/$defs/PipelinePlanQuery" }, diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 5bc0d437d..161906ee8 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -512,7 +512,7 @@ export interface CreationContractsInput extends ContractInput { readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput | MotionDocumentInput; readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | GroupSavePlanCommandInput | GroupPublishRunCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasLayoutRunsCommandInput | CanvasLayoutPipelinesCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | VideoTrimCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | PipelineStartCommandInput | PipelinePauseCommandInput | PipelineResumeCommandInput | PipelineCancelCommandInput | PipelineRetryCommandInput | PipelineAdoptCommandInput | NodeVersionApplyCommandInput | NodeVersionExportCommandInput | 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 | PipelinePlanQueryInput | PipelineExecutionQueryInput | PipelineExecutionsQueryInput; + readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | JobStatusQueryInput | AssetPreviewQueryInput | ReceiptQueryInput | PipelinePlanQueryInput | PipelineExecutionQueryInput | PipelineExecutionsQueryInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -1407,6 +1407,11 @@ export interface QueryBaseInput extends ContractInput { readonly projectId: string; } +export interface ReceiptQueryInput extends QueryBaseInput { + readonly type: "receipt.get"; + readonly objectId: string; +} + export interface RectangleLayerContentInput extends LayerContentBaseInput { readonly kind: "rectangle"; readonly color: string; @@ -2550,7 +2555,7 @@ export interface CreationContracts extends Contract { readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument | MotionDocument; readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | GroupSavePlanCommand | GroupPublishRunCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasLayoutRunsCommand | CanvasLayoutPipelinesCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | VideoTrimCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | PipelineStartCommand | PipelinePauseCommand | PipelineResumeCommand | PipelineCancelCommand | PipelineRetryCommand | PipelineAdoptCommand | NodeVersionApplyCommand | NodeVersionExportCommand | 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 | PipelinePlanQuery | PipelineExecutionQuery | PipelineExecutionsQuery; + readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery | ReceiptQuery | PipelinePlanQuery | PipelineExecutionQuery | PipelineExecutionsQuery; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -3444,6 +3449,11 @@ export interface QueryBase extends Contract { readonly projectId: string; } +export interface ReceiptQuery extends QueryBase { + readonly type: "receipt.get"; + readonly objectId: string; +} + export interface RectangleLayerContent extends LayerContentBase { readonly kind: "rectangle"; readonly color: string; diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index 92e8248a4..3e7bfc22e 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -145,7 +145,9 @@ export const assistant = { "assistant.reply.toolError": "The tool failed. Expand the details.", "assistant.reply.toolClosed": "The tool entry point is closed for this turn.", "assistant.reply.toolIdConflict": - "The tool call id was reused with different input.", + "The tool call ID was reused with different input. Use a new operation ID for changed input, or inspect the original receipt.", + "assistant.reply.missingReceipt": + "No committed receipt was found for this command or operation ID.", "assistant.reply.toolHostScope": "The host provides the query identity and project scope.", "assistant.reply.toolTextLimit": diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 7813a6711..5363288c0 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -143,7 +143,9 @@ export const assistant = { "assistant.reply.copyFailed": "复制失败,请选择正文复制", "assistant.reply.toolError": "工具执行失败,请展开查看详情。", "assistant.reply.toolClosed": "本轮工具入口已关闭。", - "assistant.reply.toolIdConflict": "工具调用标识被用于不同输入。", + "assistant.reply.toolIdConflict": + "工具调用标识被用于不同输入;请使用新的操作标识,或查询原操作回执。", + "assistant.reply.missingReceipt": "没有该命令或操作标识的已提交回执。", "assistant.reply.toolHostScope": "查询身份与工程范围由宿主提供。", "assistant.reply.toolTextLimit": "只能读取不超过 64 KB 的文本素材。", "assistant.reply.toolSkillOutside": "只能读取已发现技能目录内的文本资源。", diff --git a/tests/assistantToolText.test.ts b/tests/assistantToolText.test.ts index 9a701c6b0..cf6ed951e 100644 --- a/tests/assistantToolText.test.ts +++ b/tests/assistantToolText.test.ts @@ -25,6 +25,31 @@ test("agent tool errors never show Chinese in the English reply card", () => { assert.equal(assistantToolText("本轮工具入口已关闭。"), "本轮工具入口已关闭。"); }); +test("command_conflict and missing_receipt localize by code and keep legacy fallback", () => { + setActiveLocale("en-US"); + assert.equal( + assistantToolText( + "工具调用标识被用于不同输入。修改输入后请省略 --operation-id 或使用新的操作标识;如需确认原操作是否已提交,请查询原操作回执。", + undefined, + "command_conflict", + ), + "The tool call ID was reused with different input. Use a new operation ID for changed input, or inspect the original receipt.", + ); + assert.equal( + assistantToolText("工具调用标识被用于不同输入。"), + "The tool call ID was reused with different input. Use a new operation ID for changed input, or inspect the original receipt.", + ); + assert.equal( + assistantToolText("没有该命令的已提交回执。", undefined, "missing_receipt"), + "No committed receipt was found for this command or operation ID.", + ); + setActiveLocale("zh-CN"); + assert.equal( + assistantToolText("工具调用标识被用于不同输入。", undefined, "command_conflict"), + "工具调用标识被用于不同输入。", + ); +}); + test("image geometry rejections retain their concrete cause in both languages", () => { setActiveLocale("en-US"); assert.equal( diff --git a/tests/test_agent_gateway.py b/tests/test_agent_gateway.py index 6c984357a..875bcaca2 100644 --- a/tests/test_agent_gateway.py +++ b/tests/test_agent_gateway.py @@ -64,7 +64,11 @@ async def execute(*args): await entered.wait() replay = asyncio.create_task(gateway.call('same-id', 'read_project', {})) conflict = await gateway.call('same-id', 'read', {'path': 'different'}) - assert conflict.error == '工具调用标识被用于不同输入。' + assert conflict.error and conflict.error.startswith('工具调用标识被用于不同输入。') + assert conflict.value['code'] == 'command_conflict' + assert conflict.event('read')['code'] == 'command_conflict' + assert 'call ID' in conflict.value['guidance'] + assert 'commandId from the original tool result' in conflict.value['guidance'] release.set() left, right = await asyncio.gather(first, replay) assert left.value == right.value == {'status': 'applied', 'commandId': 'same-id', 'modelSelections': {}} @@ -72,6 +76,76 @@ async def execute(*args): await gateway.close() +@pytest.mark.anyio +async def test_non_uuid_native_write_conflict_guides_receipt_lookup_by_original_command_id(tmp_path): + from opendirector.domain.creation.commands import parse_command + projects = CreationProjects(LocalProjects(tmp_path)) + project_id = uuid4() + session = str(uuid4()) + projects.execute(parse_command(dict(commandId=uuid4(), projectId=project_id, type='project.create', payload={'name': 'Native T2'})), source='ui') + projects.open(project_id, session) + business = AgentTools(projects, None, ModelConfigs(tmp_path)) + run = RunContext(runtime='codex', project_id=project_id, turn_id=uuid4(), session=session, + directory=tmp_path, config=None, messages=[], selected_skills=[]) + gateway = ToolGateway(business, run) + + call_id = 'native-call-write-1' + first_args = {'type': 'asset.writeText', 'payload': {'name': 'draft.md', 'text': 'v1'}} + first = await gateway.call(call_id, 'execute_command', first_args) + assert first.error is None and first.value['status'] == 'applied' + + changed_args = {'type': 'asset.writeText', 'payload': {'name': 'draft.md', 'text': 'v2'}} + conflict = await gateway.call(call_id, 'execute_command', changed_args) + assert conflict.error and conflict.value['code'] == 'command_conflict' + assert 'receiptCommand' not in conflict.value + assert 'commandId from the original tool result' in conflict.value['guidance'] + + looked_up = await gateway.call('native-lookup-1', 'query', {'type': 'receipt.get', 'objectId': first.value['commandId']}) + assert looked_up.error is None and looked_up.value == first.value + assert len(projects.snapshot(project_id).assets) == 1 + await gateway.close() + + +@pytest.mark.anyio +async def test_cli_call_id_conflict_guides_receipt_lookup_without_duplicate_writes(tmp_path): + from opendirector.domain.creation.commands import parse_command + projects = CreationProjects(LocalProjects(tmp_path)) + project_id = uuid4() + session = str(uuid4()) + projects.execute(parse_command(dict(commandId=uuid4(), projectId=project_id, type='project.create', payload={'name': 'T2'})), source='ui') + projects.open(project_id, session) + business = AgentTools(projects, None, ModelConfigs(tmp_path)) + run = RunContext(runtime='codex', project_id=project_id, turn_id=uuid4(), session=session, + directory=tmp_path, config=None, messages=[], selected_skills=[]) + gateway = ToolGateway(business, run) + + operation_id = uuid4() + call_id = f'cli:{operation_id}' + first_args = {'type': 'asset.writeText', 'payload': {'name': 'original.md', 'text': 'hello'}} + first = await gateway.call(call_id, 'execute_command', first_args) + assert first.error is None and first.value['status'] == 'applied' + + replay = await gateway.call(call_id, 'execute_command', first_args) + assert replay.error is None and replay.value == first.value + + changed_args = {'type': 'asset.writeText', 'payload': {'name': 'modified.md', 'text': 'changed'}} + conflict = await gateway.call(call_id, 'execute_command', changed_args) + assert conflict.error and conflict.value['code'] == 'command_conflict' + assert conflict.event('opendirector asset write-text')['code'] == 'command_conflict' + assert conflict.value['receiptCommand'] == f'opendirector receipt show {operation_id}' + assert f'opendirector receipt show {operation_id}' in conflict.value['guidance'] + + by_op = await gateway.call('lookup-op', 'query', {'type': 'receipt.get', 'objectId': str(operation_id)}) + assert by_op.error is None and by_op.value == first.value + by_command = await gateway.call('lookup-cmd', 'query', {'type': 'receipt.get', 'objectId': first.value['commandId']}) + assert by_command.error is None and by_command.value == first.value + + missing = await gateway.call('lookup-missing', 'query', {'type': 'receipt.get', 'objectId': str(uuid4())}) + assert missing.error and missing.value['code'] == 'missing_receipt' + assert len(projects.snapshot(project_id).assets) == 1 + await gateway.close() + + @pytest.mark.anyio async def test_failed_calls_replay_without_limiting_subsequent_calls(gateway, monkeypatch): attempts = [] diff --git a/tests/test_cli.py b/tests/test_cli.py index aba07fb0e..6ba68b51c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -828,3 +828,159 @@ def invoke(args, *, content=None, status=0): canvas.query_snapshot(ObjectQuery( queryId=uuid4(), type="job.get", projectId=project_id, objectId=UUID(first_id), revision=3)) assert not_a_job.value.issue.code == "missing_object" + + +@pytest.mark.parametrize("live", [False, True], ids=["http", "agent"]) +def test_receipt_show_works_in_http_and_agent_modes_and_reports_missing_receipt(tmp_path, monkeypatch, live): + import asyncio + from opendirector.agent.tools import AgentTools + from opendirector.infrastructure.creation_projects import CreationProjects + + local = LocalProjects(tmp_path) + projects = CreationProjects(local) + api = TestClient(create_app(local), headers={"X-OpenDirector-Request": "1"}) + original_client = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + + monkeypatch.setattr(cli.httpx, "Client", lambda **kwargs: + original_client(**kwargs, transport=httpx.MockTransport(forward))) + project_id, turn_id, operation_id = uuid4(), uuid4(), uuid4() + runner = CliRunner() + monkeypatch.delenv("OPENDIRECTOR_AGENT_SOCKET", raising=False) + monkeypatch.delenv("OPENDIRECTOR_AGENT_HOST", raising=False) + created = runner.invoke(cli.app, ["--project", str(project_id), "project", "create", "--name", "Receipts"]) + assert created.exit_code == 0, created.output + + if live: + session = str(uuid4()) + projects.open(project_id, session) + business = AgentTools(projects, None, ModelConfigs(tmp_path)) + monkeypatch.setenv("OPENDIRECTOR_AGENT_SOCKET", "in-process-test") + monkeypatch.setattr(cli.Client, "call", lambda self, name, arguments, *, identity=None: + asyncio.run(business.execute(project_id, turn_id, session, f"cli:{identity or uuid4()}", + name, arguments, roots=[], config=None, native_runtime="codex"))) + + applied = runner.invoke(cli.app, [ + "--project", str(project_id), "--operation-id", str(operation_id), + "asset", "write-text", "--name", "receipt.md", "--text", "hello receipt", + ]) + assert applied.exit_code == 0, applied.output + receipt = json.loads(applied.output) + assert receipt["status"] == "applied" + + looked_up = runner.invoke(cli.app, ["--project", str(project_id), "receipt", "show", str(operation_id)]) + assert looked_up.exit_code == 0, looked_up.output + assert json.loads(looked_up.output) == receipt + + missing = runner.invoke(cli.app, ["--project", str(project_id), "receipt", "show", str(uuid4())]) + assert missing.exit_code == 1 + assert isinstance(missing.exception, ProjectError) and missing.exception.code == "missing_receipt" + + caps = json.loads(runner.invoke(cli.app, ["capabilities", "--compact"]).output) + assert "receipt.get" in caps["queries"] + assert any(entry["command"] == "receipt show" for entry in caps["commands"]) + + +@pytest.mark.parametrize("language", ["en-US", "zh-CN"]) +def test_cli_main_preserves_command_conflict_guidance_and_receipt_command_end_to_end(tmp_path, language): + import asyncio + import os + import tempfile + from opendirector.agent.cli_transport import turn_environment + from opendirector.agent.context import RunContext + from opendirector.agent.gateway import ToolGateway + from opendirector.agent.tools import AgentTools + from opendirector.domain.creation.commands import parse_command + from opendirector.infrastructure.creation_projects import CreationProjects + + projects = CreationProjects(LocalProjects(tmp_path)) + project_id = uuid4() + session = str(uuid4()) + projects.execute(parse_command(dict( + commandId=uuid4(), projectId=project_id, type="project.create", payload={"name": "Conflict E2E"}, + )), source="ui") + projects.open(project_id, session) + business = AgentTools(projects, None, ModelConfigs(tmp_path)) + run = RunContext(runtime="codex", project_id=project_id, turn_id=uuid4(), session=session, + directory=tmp_path, config=None, messages=[], selected_skills=[]) + gateway = ToolGateway(business, run) + queue: asyncio.Queue = asyncio.Queue() + + async def exercise(): + work = tmp_path / "work" + work.mkdir() + with tempfile.TemporaryDirectory(prefix="od-cli-") as sock_dir: + async with turn_environment(work, gateway, queue, Path(sock_dir)) as env: + run_env = {**env, "OPENDIRECTOR_LANGUAGE": language, + "PYTHONPATH": os.environ.get("PYTHONPATH", "")} + op_id = str(uuid4()) + + def run_cli(args): + return subprocess.run( + [sys.executable, "-m", "opendirector.cli", *args], + env=run_env, capture_output=True, text=True, timeout=30, + ) + + first = await asyncio.to_thread(run_cli, [ + "--project", str(project_id), "--operation-id", op_id, + "asset", "write-text", "--name", "one.md", "--text", "first", + ]) + assert first.returncode == 0, first.stdout + first.stderr + first_receipt = json.loads(first.stdout) + assert first_receipt["status"] == "applied" + + conflict = await asyncio.to_thread(run_cli, [ + "--project", str(project_id), "--operation-id", op_id, + "asset", "write-text", "--name", "two.md", "--text", "changed", + ]) + assert conflict.returncode == 1, conflict.stdout + conflict.stderr + body = json.loads(conflict.stdout) + expected_cmd = f"opendirector receipt show {op_id}" + assert body["code"] == "command_conflict" + assert body["receiptCommand"] == expected_cmd + assert expected_cmd in body["guidance"] + if language == "en-US": + assert expected_cmd in body["error"] + assert "工具调用" not in body["error"] + else: + assert body["error"].startswith("工具调用标识被用于不同输入。") + + followup_args = shlex.split(body["receiptCommand"])[1:] + looked_up = await asyncio.to_thread(run_cli, followup_args) + assert looked_up.returncode == 0, looked_up.stdout + looked_up.stderr + assert json.loads(looked_up.stdout) == first_receipt + + asyncio.run(exercise()) + + +def test_cli_main_preserves_http_duplicate_project_id_command_conflict_message(tmp_path, monkeypatch, capsys): + local = LocalProjects(tmp_path) + api = TestClient(create_app(local), headers={"X-OpenDirector-Request": "1"}) + original_client = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + + monkeypatch.setattr(cli.httpx, "Client", lambda **kwargs: + original_client(**kwargs, transport=httpx.MockTransport(forward))) + monkeypatch.delenv("OPENDIRECTOR_AGENT_SOCKET", raising=False) + monkeypatch.delenv("OPENDIRECTOR_AGENT_HOST", raising=False) + monkeypatch.setenv("OPENDIRECTOR_LANGUAGE", "en-US") + + project_id = str(uuid4()) + monkeypatch.setattr(sys, "argv", ["opendirector", "--project", project_id, "project", "create", "--name", "First"]) + with pytest.raises(SystemExit) as created: + cli.main() + assert created.value.code == 0 + capsys.readouterr() + + monkeypatch.setattr(sys, "argv", ["opendirector", "--project", project_id, "project", "create", "--name", "Duplicate"]) + with pytest.raises(SystemExit) as exited: + cli.main() + assert exited.value.code == 1 + payload = json.loads(capsys.readouterr().out) + assert payload == {"error": "This project ID is already in use.", "code": "command_conflict"} diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py index f0833fb01..cd8ba6e19 100644 --- a/tests/test_creation_api.py +++ b/tests/test_creation_api.py @@ -74,6 +74,16 @@ def test_conflicting_command_id_and_stale_version_have_distinct_outcomes(api): receipt = client.post(path + '/commands', json=stale).json() assert receipt['status'] == 'rejected' and receipt['issues'][0]['code'] == 'revision_conflict' assert client.get(path + '/receipts/' + stale['commandId']).json() == receipt + query_applied = client.post(path + '/queries', json=dict( + queryId=str(uuid4()), projectId=command['projectId'], type='receipt.get', objectId=command['commandId'])) + assert query_applied.status_code == 200 and query_applied.json() == created + query_rejected = client.post(path + '/queries', headers={'Accept-Language': 'en-US'}, json=dict( + queryId=str(uuid4()), projectId=command['projectId'], type='receipt.get', objectId=stale['commandId'])) + assert query_rejected.status_code == 200 + assert query_rejected.json() == client.get(path + '/receipts/' + stale['commandId'], headers={'Accept-Language': 'en-US'}).json() + query_missing = client.post(path + '/queries', json=dict( + queryId=str(uuid4()), projectId=command['projectId'], type='receipt.get', objectId=str(uuid4()))) + assert query_missing.status_code == 404 and query_missing.json()['code'] == 'missing_receipt' assert len(client.get(path + '/changes').json()['events']) == 1 assert client.get(path).json()['project']['revision'] == 1 diff --git a/tests/test_fasth3_video_edit.py b/tests/test_fasth3_video_edit.py index 6f0f46562..9cde460ca 100644 --- a/tests/test_fasth3_video_edit.py +++ b/tests/test_fasth3_video_edit.py @@ -1,6 +1,7 @@ import asyncio import json +import httpx import pytest from opendirector.domain.capabilities import EditMask, MediaResult, VideoEditRequest @@ -163,3 +164,44 @@ def test_the_final_picture_is_found_when_the_sound_runs_longer(tmp_path): assert blue > 200 and red < 60 red, green, blue = Image.open(BytesIO(FastH3VideoEdit._last_edited_frame(clip.read_bytes(), 0.5))).convert('RGB').getpixel((32, 24)) assert red > 200 and blue < 60 + + +def test_vllm_omni_video_poll_retries_transient_500_without_resubmitting(): + from opendirector.domain.capabilities import VideoRequest + from opendirector.domain.generation import GenerationError + + calls, accepted = [], [] + def handle(request): + calls.append((request.method, request.url.path)) + if request.method == 'POST': + return httpx.Response(200, json={'id': 'remote-adapter-1', 'status': 'queued'}) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=b'mp4-bytes') + polls = [p for m, p in calls if m == 'GET' and p == '/v1/videos/remote-adapter-1'] + if len(polls) == 1: + return httpx.Response(500, json={'error': {'message': 'temporary outage'}}) + if len(polls) == 2: + raise httpx.ReadTimeout('poll timeout', request=request) + return httpx.Response(200, json={'id': 'remote-adapter-1', 'object': 'video', 'status': 'completed'}) + + adapter = VllmOmniVideo(httpx.MockTransport(handle), poll_interval=0, retry_delays=(0, 0)) + async def on_submitted(external_id): + accepted.append(external_id) + result = asyncio.run(adapter.video(CONFIG, VideoRequest(prompt='test', seconds=5), submitted=on_submitted)) + assert result.data == b'mp4-bytes' and result.suffix == 'mp4' + assert accepted == ['remote-adapter-1'] + assert sum(method == 'POST' for method, _ in calls) == 1 + assert sum(method == 'GET' and path == '/v1/videos/remote-adapter-1' for method, path in calls) == 3 + + terminal_calls = [] + def terminal(request): + terminal_calls.append(request.method) + if request.method == 'POST': + return httpx.Response(200, json={'id': 'remote-adapter-2', 'status': 'queued'}) + return httpx.Response(500, json={'id': 'remote-adapter-2', 'object': 'video', 'status': 'failed', + 'error': {'code': 500, 'message': 'fatal'}}) + terminal_adapter = VllmOmniVideo(httpx.MockTransport(terminal), poll_interval=0, retry_delays=(0, 0)) + with pytest.raises(GenerationError) as caught: + asyncio.run(terminal_adapter.video(CONFIG, VideoRequest(prompt='test', seconds=5))) + assert caught.value.details.providerStatus == 'failed' + assert terminal_calls == ['POST', 'GET'] diff --git a/tests/test_localization.py b/tests/test_localization.py index e96c4c824..6d8e93e4d 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -93,6 +93,18 @@ def test_size_and_timeout_statuses_are_more_specific_than_generic_codes() -> Non ) +def test_command_conflict_and_missing_receipt_localize_in_both_languages() -> None: + en_conflict = localized_error(request("en-US"), chinese="工具调用标识被用于不同输入。", status=409, code="command_conflict") + assert "operation ID" in en_conflict and "original receipt" in en_conflict + assert localized_error(request("zh-CN"), chinese="工具调用标识被用于不同输入。", status=409, code="command_conflict") == "工具调用标识被用于不同输入。" + en_dup_project = localized_error(request("en-US"), chinese="该工程标识已经使用。", status=409, code="command_conflict") + assert en_dup_project == "This project ID is already in use." + assert localized_error(request("zh-CN"), chinese="该工程标识已经使用。", status=409, code="command_conflict") == "该工程标识已经使用。" + en_missing = localized_error(request("en-US"), chinese="没有该命令的已提交回执。", status=404, code="missing_receipt") + assert "No committed receipt" in en_missing + assert localized_error(request("zh-CN"), chinese="没有该命令的已提交回执。", status=404, code="missing_receipt") == "没有该命令的已提交回执。" + + def test_streaming_and_background_jobs_use_the_same_language_rule() -> None: assert ( localized_error_for_language( diff --git a/tests/test_minimax_video.py b/tests/test_minimax_video.py index 94a1d8694..150d241ef 100644 --- a/tests/test_minimax_video.py +++ b/tests/test_minimax_video.py @@ -124,6 +124,31 @@ async def submitted(identity): await adapter.cancel(config(), 'remote-1') +@pytest.mark.anyio +async def test_poll_retries_transient_500_and_429_without_resubmitting(): + requests, accepted = [], [] + async def submitted(identity): + accepted.append(identity) + def handle(request): + requests.append(request) + if request.method == 'POST': + return httpx.Response(200, json={'task_id': 'remote-449'}) + if request.url.host == 'cdn.example.test': + return httpx.Response(200, content=b'video-bytes') + polls = [r for r in requests if r.method == 'GET' and r.url.host == 'api.minimax.cn'] + if len(polls) == 1: + return httpx.Response(500, json={'base_resp': {'status_code': 500, 'status_msg': 'transient'}}) + if len(polls) == 2: + return httpx.Response(429, json={'base_resp': {'status_code': 1002, 'status_msg': 'rate limited'}}) + return httpx.Response(200, json={'task': {'id': 'remote-449', 'status': 'succeeded', + 'content': {'url': 'https://cdn.example.test/output.mp4'}}}) + adapter = MinimaxVideoGeneration(None, httpx.MockTransport(handle), poll_interval=0, retry_delays=(0, 0)) + assert await adapter.generate(config(), task('project', prompt='test'), submitted) == ('mp4', b'video-bytes') + assert accepted == ['remote-449'] + assert sum(r.method == 'POST' for r in requests) == 1 + assert sum(r.method == 'GET' and r.url.host == 'api.minimax.cn' for r in requests) == 3 + + @pytest.mark.anyio @pytest.mark.parametrize('slot', ['first_frame', 'last_frame']) @pytest.mark.parametrize('subject_role', [None, 'main']) diff --git a/tests/test_self_hosted_queue.py b/tests/test_self_hosted_queue.py index 4364b3399..a3e4fbbb2 100644 --- a/tests/test_self_hosted_queue.py +++ b/tests/test_self_hosted_queue.py @@ -391,3 +391,82 @@ async def run(): assert caught.value.details.providerStatus == state asyncio.run(run()) assert calls == ['GET'] + + +@pytest.mark.parametrize('model', ['FastH3-Omni', 'MiniMaxAI/MiniMax-H3']) +def test_vllm_poll_retries_transient_500_without_resubmitting_and_keeps_terminal_500_immediate(model): + calls, submitted = [], [] + def transient_then_done(request): + calls.append((request.method, request.url.path)) + if request.method == 'POST': + return httpx.Response(200, json={'id': 'remote-449', 'status': 'queued'}) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=b'video-bytes') + polls = [p for m, p in calls if m == 'GET' and p == '/v1/videos/remote-449'] + if len(polls) == 1: + return httpx.Response(500, json={'error': {'message': 'temporary gateway hiccup'}}) + if len(polls) == 2: + return httpx.Response(429, json={'error': {'message': 'busy'}}) + return httpx.Response(200, json={'id': 'remote-449', 'object': 'video', 'status': 'completed'}) + + provider = GenerationProviders(None, httpx.MockTransport(transient_then_done), poll_interval=0, retry_delays=(0, 0)) + config = {'kind': 'video', 'protocol': 'vllm_omni', 'connectionType': 'self_hosted', + 'modelId': model, 'url': 'http://model.test/v1', 'authMode': 'none'} + async def on_submitted(external_id): + submitted.append(external_id) + mode = 'reference' if model == 'FastH3-Omni' else 'first_frame' + result = asyncio.run(provider.generate(config, {'projectId': 'p', 'kind': 'video', 'videoMode': mode, 'prompt': 'test', 'referenceIds': [], 'parameters': {}}, on_submitted)) + assert result == ('mp4', b'video-bytes') + assert submitted == ['remote-449'] + assert sum(method == 'POST' for method, _ in calls) == 1 + assert sum(method == 'GET' and path == '/v1/videos/remote-449' for method, path in calls) == 3 + + terminal_calls = [] + def confirmed_terminal(request): + terminal_calls.append(request.method) + return httpx.Response(500, json={'id': 'remote-449', 'object': 'video', 'status': 'failed', + 'error': {'code': 500, 'message': 'model crashed'}}) + terminal_provider = GenerationProviders(None, httpx.MockTransport(confirmed_terminal), poll_interval=0, retry_delays=(0, 0)) + async def run_terminal(): + with pytest.raises(GenerationError) as caught: + await terminal_provider.generate(config, {'kind': 'video', 'externalTaskId': 'remote-449'}, None) + assert caught.value.details.providerStatus == 'failed' + assert caught.value.details.category == 'provider' + asyncio.run(run_terminal()) + assert terminal_calls == ['GET'] + + +def test_exhausted_vllm_poll_500_preserves_remote_id_for_recovery_without_resubmitting(context): + store, session, project, configs, _ = context + calls, healthy = [], False + def handle(request): + calls.append((request.method, request.url.path)) + if request.url.path.endswith('/content'): + return httpx.Response(200, content=mp4()) + if not healthy: + return httpx.Response(500, json={'error': {'message': 'backend restart'}}) + return httpx.Response(200, json={'id': 'original-remote', 'object': 'video', 'status': 'completed'}) + provider = GenerationProviders(store, httpx.MockTransport(handle), poll_interval=0, retry_delays=(0,)) + async def run(): + nonlocal healthy + manager = CreationGeneration(store, configs, provider) + task, pinned, config = prepare(manager, context) + task.update(phase='poll', externalTaskId='original-remote') + manager.checkpoint(project['id'], task, pinned) + try: + manager._launch(task, pinned, config, 'remote') + await asyncio.gather(*(job.future for job in list(manager.jobs.values()))) + failed = tasks(manager, project['id'])[0] + assert failed['status'] == 'failed' and failed['resumeAllowed'] + assert failed['externalTaskId'] == 'original-remote' + assert failed['errorDetails']['category'] == 'temporary' + assert len(calls) == 2 and all(method == 'GET' for method, _ in calls) + healthy = True + await manager.recover(project['id'], task['id']) + await asyncio.gather(*(job.future for job in list(manager.jobs.values()))) + recovered = tasks(manager, project['id'])[0] + assert recovered['status'] == 'succeeded' and recovered['externalTaskId'] == 'original-remote' + assert not any(method == 'POST' for method, _ in calls) + finally: + await manager.close() + asyncio.run(run())