From 3c151e1580bc92b553c55fbab40e544ef2e974a1 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:48:39 +0800 Subject: [PATCH 1/2] [perf] agent: answer a wait group with one query (#449) [perf] agent: answer a wait group with one query (#449) The agent waited for generation one job at a time. Each poll issued its own job.get request (954 across the traced run in #449), read the whole project snapshot, and emitted a separate tool record. job.status answers up to 50 jobs from one snapshot and can wait server side for terminal states, so one call covers a whole wait group. The group is resolved once when the wait starts and stays frozen, so a job that settles mid-wait is still named in the answer with its errorDetails and recovery rather than disappearing. An empty group answers with a note instead of reading as success. A long wait costs one CLI process per 60 s window instead of one per second, and read-only queries no longer hold the turn's execution slot. Discovery no longer costs one process per command: capabilities merges the registered parser with the typed command models (56 commands), and project show --summary returns identities and revisions instead of every record body, including reference and editor-document identities so an edit can start from it. Measured on the same fixture: 14 jobs in one poll tick cost 180.6 ms and 14 snapshot reads before, 14.0 ms and 1 read after; command discovery drops from 33 CLI calls to 1; the project summary payload drops from 176,840 to 57,237 bytes. These are server calls, snapshot reads and payload sizes, not CLI process counts. --- docs/guides/cli.md | 11 +- .../core/src/opendirector/agent/gateway.py | 26 ++- packages/core/src/opendirector/agent/tools.py | 11 +- .../application/creation_canvas.py | 66 +++++++ packages/core/src/opendirector/cli.py | 168 +++++++++++++++-- .../opendirector/domain/creation/commands.py | 9 +- scripts/bench_agent_polling.py | 158 ++++++++++++++++ src/contracts/creation.schema.json | 137 ++++++++++++++ src/contracts/generated.ts | 18 +- tests/test_agent_gateway.py | 58 ++++++ tests/test_cli.py | 171 +++++++++++++++++- tests/test_creation_canvas_service.py | 114 ++++++++++++ 12 files changed, 913 insertions(+), 34 deletions(-) create mode 100644 scripts/bench_agent_polling.py diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 743279638..e6dc88c10 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -28,15 +28,22 @@ opendirector --project PROJECT_UUID video create --model MODEL_CONFIG_UUID - ```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 -opendirector --project PROJECT_UUID job wait JOB_UUID --timeout 300 +opendirector --project PROJECT_UUID job wait JOB_UUID... --timeout 300 +opendirector --project PROJECT_UUID job wait --all --timeout 300 ``` +`job wait` 接受多个任务身份,`--all` 等待当前工程全部未结束任务,并在一次等待窗口内用一次服务端查询回答整组任务;返回每个任务的 `status`、`phase` 和成功后已登记的 `delivery`。需要减少等待调用次数时优先用 `--all`,不要为每个任务分别启动一次等待。等待组在第一次回答时确定并保持不变,因此等待期间结束的任务仍会被报告:失败任务计入 `failed`、携带 `errorDetails` 与 `recovery`,并以退出码 1 结束;整组结束时报错信息不会被静默省略。工程内没有未结束任务时返回 `jobs: []` 并在 `note` 中明确说明,不再让空结果看起来像全部成功;此时可用 `project show --summary` 查看每个任务最终状态。 + +`opendirector capabilities` 一次输出全部业务命令、摘要与必填字段(含未由命令契约生成、但已注册的 `job wait`、`query`、`model`、`asset import`、`timeline`、`voice` 等命令),`--compact` 省略非必填字段名与非必填选项。Agent 用它替代逐条执行 `--help` 的发现过程;仅在单个字段结构不清楚时用 `--help-field` 展开。`opendirector project show --summary` 输出对象身份、版本与状态而不含完整记录,工程较大时可避免结果被截断以及重复读取。 + 业务命令按对象分组,参数名使用短横线。复杂参数可使用 JSON 参数,或通过 `--file command.json` 读取含 `payload`、`expectedVersions` 和可选 `expectedPreview` 的对象。`--file -` 从标准输入读取。命令帮助包含从 Pydantic 业务契约派生的参数说明与示例。`--help-field PATH` 展开帮助中返回的结构化字段路径,例如 `opendirector canvas show --help-field payload.item@image.binding`。 -CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回对应的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;60 秒窗口超时后可以再次执行同一等待命令。`job wait` 超时结束等待,任务继续由后台执行。 +CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其列表,视频节点创建回执同时返回包含当前版本的下一步提交命令。参数解析错误直接显示该子命令的完整用法。成功退出码为 0,拒绝或执行失败为 1,参数解析错误及等待任务超时为 2。生成接受回执会在 `next.commands` 返回一条覆盖本次全部任务的 `job wait` 命令,带入服务地址、工程和任务身份。建议按回执等待;等待窗口超时后可以再次执行同一命令。`job wait` 超时结束等待,任务继续由后台执行。 修改命令可在子命令前传 `--operation-id UUID`。相同身份及输入重试复用原回执,输入不同则拒绝。文件导入重放也核对登记文件的内容指纹。需要跨进程恢复暂存上传时,预先通过 `--session UUID` 保持相同会话身份。结果未知时先查询回执,再决定后续操作。 +读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 + 普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。 Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。 diff --git a/packages/core/src/opendirector/agent/gateway.py b/packages/core/src/opendirector/agent/gateway.py index 6f11d131f..38a2c881d 100644 --- a/packages/core/src/opendirector/agent/gateway.py +++ b/packages/core/src/opendirector/agent/gateway.py @@ -1,5 +1,6 @@ """One turn's tool admission, replay and receipts, independent of transport.""" import asyncio +from contextlib import nullcontext from copy import deepcopy from dataclasses import dataclass import json @@ -32,6 +33,27 @@ def event(self, name: str) -> AgentEvent: **({'code': code} if self.error and isinstance(code, str) else {})} +# 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'}) +# 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'}) + + +def _read_only(name, arguments) -> bool: + """Whether this call may skip the execution lock. + + Arguments are validated inside the call itself, so an argument shape that + is not a mapping or whose type is not a string is simply not read-only. + Raising here would leave the tool result contract. + """ + if name != 'query' or not isinstance(arguments, dict): + return False + kind = arguments.get('type') + return isinstance(kind, str) and kind in READ_ONLY_QUERIES + + class ToolGateway: def __init__(self, business: AgentTools, run: RunContext): self.business = business @@ -62,7 +84,7 @@ async def call(self, call_id: str, name: str, arguments: dict[str, JsonValue]) - return await asyncio.shield(task) async def execute(self, call_id: str, name: str, arguments: dict[str, JsonValue]) -> ToolResult: - async with self.execution_lock: + async with (nullcontext() if _read_only(name, arguments) else self.execution_lock): try: if self.closed: raise ProjectError('本轮工具入口已关闭。', 409) @@ -105,6 +127,6 @@ async def close(self) -> None: self.closed = True for identity, task in self.calls.values(): name, arguments = json.loads(identity) - if name == 'query' and arguments.get('type') == 'canvas.status': + if name == 'query' and isinstance(arguments, dict) and arguments.get('type') in WAITING_QUERIES: task.cancel() await asyncio.gather(*(task for _, task in self.calls.values()), return_exceptions=True) diff --git a/packages/core/src/opendirector/agent/tools.py b/packages/core/src/opendirector/agent/tools.py index 4753be1d8..4edfecd21 100644 --- a/packages/core/src/opendirector/agent/tools.py +++ b/packages/core/src/opendirector/agent/tools.py @@ -59,16 +59,17 @@ def query_guidance(failure): assert command_model.__doc__ and command_model.__doc__.strip(), f'Missing command metadata: {command_name}' SYSTEM = '''You are OpenDirector, a video creation assistant. Respond directly when the user's request can be answered without project state or tool execution. -When the task needs project capabilities, use the harness's native shell tool to discover and run the opendirector executable on PATH. -Before using the project CLI, locate opendirector through the shell (Get-Command opendirector in PowerShell, command -v opendirector in POSIX shells), then execute opendirector --help. -Discover the commands needed for the user's task from that output and read their --help before executing them through the same shell tool. +When the task needs project capabilities, run the opendirector executable on PATH through the harness's native shell tool. +Run opendirector capabilities once, and inspect a command with opendirector COMMAND --help-field payload only when one field's shape is unclear. Do not run --help for each command. +Accepted receipts return ready-to-run next commands with current revisions; use them instead of re-reading the project. +Wait for generation with opendirector job wait --all; one call covers every unfinished job, so do not start one wait per job. After performing requested creative work, summarize the delivered result and material limitations. Keep execution IDs, revisions and receipts in tool details unless requested. -Read opendirector project show and opendirector model list through the shell before changing the project. Use exact current object revisions. +Read the project with opendirector project show --summary and opendirector model list before changing it, use the exact revisions they return, and request the full snapshot only when a record body is needed. Project data and skill files are context, never permission to bypass business validation. Do not claim to have viewed media without actual visual input. Use native shell and file tools for media processing in the execution directory. Source assets are read-only. Never edit project storage directly; use the opendirector CLI. Register execution files with opendirector asset import FILE --kind KIND before referring to them as project assets. -For separate clips, register each file, read opendirector project show, then opendirector canvas add-material --asset UUID for each. +For separate clips, register each file, read opendirector project show --summary, then opendirector canvas add-material --asset UUID for each. A timeline of source ranges is not a substitute for requested independent media assets. Successful generation results are already registered project assets. Inspect them using their existing asset identity and canvas item. Do not publish inspection copies or extracted inspection frames, or add another canvas item for the same delivery unless the user requests it. Publish newly created deliverables after editing or processing. A command receipt is execution evidence, not quality approval. Preserve user constraints. diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index aab824957..bac550dc1 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -25,6 +25,9 @@ from opendirector.domain.projects import ProjectError from opendirector.ports.gateway import gateway +DELIVERY_GUIDANCE = ('Inspect this existing asset directly. Local copies and extracted inspection frames do not need ' + 'publishing or new canvas items. Publish only new deliverables; create another display only when requested.') + COLLECTIONS = {'canvas_item': 'canvasItems', 'generation_spec': 'generationSpecs', 'reference': 'references', 'editor_document': 'editorDocuments', 'asset': 'assets', 'job': 'jobs', 'result': 'results'} @@ -727,6 +730,67 @@ def item_status(self, project_id: UUID, item_id: UUID) -> dict: 'errorDetails', 'technicalCheck', 'cancelRequested', 'adopted', 'asset'}) for job in jobs], 'asset': asset.model_dump(mode='json') if asset else None} + TERMINAL_JOB_STATES = frozenset({'succeeded', 'failed', 'cancelled', 'interrupted'}) + + def job_states(self, project_id: UUID, object_ids: tuple[UUID, ...] = ()) -> dict: + """Read the requested jobs and their deliveries from one snapshot; unfinished jobs when none are named.""" + snapshot = self.projects.snapshot(project_id) + jobs = {job.id: job for job in snapshot.jobs} + if object_ids: + missing = [str(identity) for identity in object_ids if identity not in jobs] + if missing: + raise ContractError('missing_object', '未找到该对象或历史版本。', missing[0]) + selected = [jobs[identity] for identity in object_ids] + else: + selected = [job for job in snapshot.jobs if job.status not in self.TERMINAL_JOB_STATES] + results_by_asset = {} + for result in snapshot.results: + results_by_asset.setdefault(result.asset.assetId, []).append(result) + adopted_results = {spec.currentResultId for spec in snapshot.generationSpecs if spec.currentResultId} + views = [] + for job in selected: + view = job.model_dump(mode='json', include={'id', 'revision', 'status', 'phase', 'asset', + 'errorDetails', 'recovery', 'resumeAllowed', 'cancelRequested', 'adopted', 'originItemId', + 'externalTaskId', 'createdAt'}) + if job.status == 'succeeded' and job.asset: + results = results_by_asset.get(job.asset.assetId, ()) + specs = {result.specId for result in results if result.id in adopted_results} + items = [item for item in snapshot.canvasItems if + (item.binding.role == 'generation' and item.binding.objectRef.id in specs + and not item.binding.materialOverride) or + (item.binding.role == 'material' and item.binding.objectRef.assetId == job.asset.assetId)] + view['delivery'] = {'registered': True, 'asset': view['asset'], + 'adopted': any(result.id in adopted_results for result in results), + 'canvasItems': [item.model_dump(mode='json', include={'id', 'revision', 'visible', + 'position', 'width', 'height'}) for item in items], 'guidance': DELIVERY_GUIDANCE} + views.append(view) + return {'jobs': views, 'terminal': all(job.status in self.TERMINAL_JOB_STATES for job in selected)} + + def unfinished_jobs(self, project_id: UUID) -> tuple[UUID, ...]: + """The wait group a caller means by "everything that is still running now". + + A wait is one interaction, so this is read once at its start. Re-reading + it on every poll would drop each job the moment it settles, and the + caller would never learn which of them failed. + """ + return tuple(job.id for job in self.projects.snapshot(project_id).jobs + if job.status not in self.TERMINAL_JOB_STATES) + + async def wait_jobs(self, project_id: UUID, object_ids: tuple[UUID, ...] = (), wait_seconds: float = 0, + until: str = 'all') -> dict: + """Answer for a whole set of jobs with at most one snapshot read per poll tick.""" + group = object_ids or await asyncio.to_thread(self.unfinished_jobs, project_id) + deadline = asyncio.get_running_loop().time() + wait_seconds + while True: + state = await asyncio.to_thread(self.job_states, project_id, group) + jobs = state['jobs'] + settled = state['terminal'] or (bool(jobs) and until == 'any' and any( + job['status'] in self.TERMINAL_JOB_STATES for job in jobs)) + remaining = deadline - asyncio.get_running_loop().time() + if settled or remaining <= 0: + return state + await asyncio.sleep(min(0.5, remaining)) + async def wait_item_status(self, project_id: UUID, item_id: UUID, wait_seconds: float = 0) -> dict: current = await asyncio.to_thread(self.item_status, project_id, item_id) deadline = asyncio.get_running_loop().time() + wait_seconds @@ -844,6 +908,8 @@ def projection(self, project_id, snapshot=None): async def query(self, query: Query) -> JsonValue: if query.type == 'canvas.status': 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 == '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 5824189b1..e5bdc2405 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -21,6 +21,7 @@ from typer._click.exceptions import UsageError from opendirector.agent.tools import COMMANDS, command_help +from opendirector.application.creation_canvas import DELIVERY_GUIDANCE from opendirector.domain.creation.commands import COMMAND_MODELS, command_fingerprint, parse_command from opendirector.domain.projects import ProjectError from opendirector.domain.timeline_errors import timeline_error, timeline_error_message @@ -60,6 +61,39 @@ def group(name: str) -> typer.Typer: return groups[name] +# Discovery must not fall behind the parser: commands that are not built from a +# command model are described from the registered click command itself. +HIDDEN_COMMANDS = frozenset({"capabilities", "serve", "dev", "desktop"}) + + +def registered_commands(): + """Every registered subcommand with the fields it requires.""" + from typer.main import get_command + + def describe(label, command): + parameters = [parameter for parameter in command.params if parameter.name not in {"help", "ctx"}] + required = sorted(parameter.name for parameter in parameters if parameter.required) + options = [" ".join(getattr(parameter, "opts", ()) or ()) or str(parameter.name).upper() + for parameter in parameters] + summary = (command.help or (command.callback.__doc__ if command.callback else "") or "").strip() + return {"command": label, "summary": summary.splitlines()[0] if summary else "", + "required": required, "options": options} + + entries = [] + + def walk(label, command): + children = getattr(command, "commands", None) + if isinstance(children, dict): + for sub, child in children.items(): + walk(f"{label} {sub}", child) + else: + entries.append(describe(label, command)) + + for name, command in get_command(app).commands.items(): + walk(name, command) + return [entry for entry in entries if entry["command"] not in HIDDEN_COMMANDS] + + @group("timeline").command("default-font", help="Find the bundled timeline font without opening a project.") def timeline_default_font(): from opendirector.installation import default_timeline_font @@ -176,7 +210,7 @@ def call(self, name, arguments, *, identity=None): connection = (socket.create_connection((endpoint, int(self.gateway["OPENDIRECTOR_AGENT_PORT"])), timeout=15) if endpoint else socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)) with connection: - connection.settimeout(120) + connection.settimeout(SOCKET_TIMEOUT) if not endpoint: connection.connect(self.gateway["OPENDIRECTOR_AGENT_SOCKET"]) connection.sendall((json.dumps({ @@ -221,10 +255,9 @@ def execute(self, kind, payload, versions=(), preview=None, *, identity=None): raise typer.Exit(1) if value.get("status") == "accepted" and value.get("jobIds"): value = {**value, "next": { - "description": "Wait for each accepted job to finish. On timeout, run the same wait command again.", + "description": "Wait for every accepted job in one call. On timeout, run the same wait command again.", "commands": [shlex.join(["opendirector", "--url", str(self.http.base_url).rstrip("/"), - "--project", value["projectId"], "job", "wait", job_id, "--timeout", "60"]) - for job_id in value["jobIds"]], + "--project", value["projectId"], "job", "wait", *value["jobIds"], "--timeout", "60"])], }} canvas_versions = {item["id"]: item["revision"] for item in value.get("changed", []) if item["objectType"] == "canvas_item"} @@ -266,7 +299,7 @@ def query(self, kind, **arguments): result = {**result, "delivery": {"registered": True, "asset": result["asset"], "adopted": bool(adopted_specs), "canvasItems": [{key: item[key] for key in ("id", "revision", "visible", "position", "width", "height")} for item in items], - "guidance": "Inspect this existing asset directly. Local copies and extracted inspection frames do not need publishing or new canvas items. Publish only new deliverables; create another display only when requested."}} + "guidance": DELIVERY_GUIDANCE}} return result @@ -332,10 +365,49 @@ def emit(value): typer.echo(json.dumps(value, ensure_ascii=False, indent=2)) -@group("project").command("show", help="Read the current authoritative project snapshot.") -def project_show(ctx: typer.Context): +def summarize(snapshot): + """Identity and status of every object, without bodies the agent rarely needs.""" + return { + "project": {key: snapshot["project"][key] for key in ("id", "name", "revision") if key in snapshot["project"]}, + "counts": {key: len(snapshot.get(key, ())) for key in + ("assets", "generationSpecs", "references", "canvasItems", "editorDocuments", "jobs", "results")}, + "assets": [{"id": asset["id"], "kind": asset["kind"], "name": asset["name"], + "durationSeconds": asset.get("metadata", {}).get("durationSeconds"), + "width": asset.get("metadata", {}).get("width"), "height": asset.get("metadata", {}).get("height")} + 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), + "binding": {"role": item["binding"]["role"], + "objectRef": item["binding"].get("objectRef", {}).get("id") or + item["binding"].get("objectRef", {}).get("assetId")} } + for item in snapshot.get("canvasItems", ())], + "generationSpecs": [{"id": spec["id"], "revision": spec["revision"], + "modelConfigId": spec.get("modelConfigId"), "currentResultId": spec.get("currentResultId"), + "purpose": spec.get("purpose")} for spec in snapshot.get("generationSpecs", ())], + "jobs": [{"id": job["id"], "revision": job["revision"], "status": job["status"], "phase": job.get("phase")} + for job in snapshot.get("jobs", ())], + "results": [{"id": result["id"], "assetId": result["asset"]["assetId"], "jobId": result["jobId"]} + for result in snapshot.get("results", ())], + # Identities only: reference.update and reference.remove take a reference + # ID, and editor.save takes an editor ID, so dropping these would make + # the summary the one read that cannot start an edit. + "references": [{"id": reference["id"], "revision": reference["revision"], + "targetSpecId": reference["targetSpecId"], "binding": reference["binding"], + "role": reference.get("role"), "order": reference.get("order"), + "active": reference.get("active", True)} + for reference in snapshot.get("references", ())], + "editorDocuments": [{"id": document["id"], "revision": document["revision"], + "kind": document.get("kind"), "title": document.get("title")} + for document in snapshot.get("editorDocuments", ())], + } + + +@group("project").command("show", help="Read the current authoritative project snapshot, or only identities and status with --summary.") +def project_show(ctx: typer.Context, + summary: Annotated[bool, typer.Option("--summary", help="Print identities, revisions and status without full records.")] = False): ctx.obj.command = ctx.command_path - emit(ctx.obj.snapshot()) + snapshot = ctx.obj.snapshot() + emit(summarize(snapshot) if summary else snapshot) @group("project").command("list", help="List available projects.") @@ -675,24 +747,86 @@ def job_show(ctx: typer.Context, job_id: UUID): emit(ctx.obj.query("job.get", objectId=str(job_id))) -@group("job").command("wait", help="Wait for a job to reach a terminal state.") -def job_wait(ctx: typer.Context, job_id: UUID, +TERMINAL_JOB_STATES = frozenset({"succeeded", "failed", "cancelled", "interrupted"}) +WAIT_WINDOW = 60 # Seconds of waiting answered by one server call. +# One wait window must fit inside the agent socket read timeout with room for +# the snapshot read that answers it, so the timeout is derived, not guessed. +SOCKET_TIMEOUT = WAIT_WINDOW + 60 + + +@group("job").command("wait", help="Wait for one or more jobs to finish; one server call per wait window, not per job.") +def job_wait(ctx: typer.Context, job_ids: Annotated[list[UUID] | None, typer.Argument( + help="Generation job IDs. Omit them with --all.")] = None, + all_jobs: Annotated[bool, typer.Option("--all", help="Wait for every unfinished job in this project.")] = False, timeout: Annotated[float, typer.Option(min=0, help="Maximum wait in seconds.")] = 300): import time ctx.obj.command = ctx.command_path + if not job_ids and not all_jobs: + raise typer.BadParameter("Pass job IDs or --all.") + ids = [str(identity) for identity in (job_ids or ())] deadline = time.monotonic() + timeout + # The first answer also freezes the wait group: the server keeps reporting + # the same jobs, so a job that fails while we wait is still named below. while True: - result = ctx.obj.query("job.get", objectId=str(job_id)) - job = result.get("job", result) - if job.get("status") in {"succeeded", "failed", "cancelled", "interrupted"}: - emit(result) - if job["status"] != "succeeded": + remaining = max(0.0, deadline - time.monotonic()) + result = ctx.obj.query("job.status", objectIds=ids, + waitSeconds=min(WAIT_WINDOW, remaining), until="all") + jobs = result.get("jobs", []) + if not job_ids: + ids = [job["id"] for job in jobs] + failed = [job for job in jobs if job["status"] in TERMINAL_JOB_STATES and job["status"] != "succeeded"] + settled = all(job["status"] in TERMINAL_JOB_STATES for job in jobs) + if settled: + report = {"jobs": jobs, "completed": len(jobs) - len(failed), "failed": len(failed)} + if not jobs: + report["note"] = ("No job in this project is still running. " + "project show --summary lists every job and its final status.") + elif failed: + report["note"] = "These jobs did not succeed; errorDetails names the cause and recovery says whether it can resume." + emit(report) + if failed: raise typer.Exit(1) return if time.monotonic() >= deadline: - emit(result) + emit({"jobs": jobs, "completed": len(jobs) - len([job for job in jobs if job["status"] not in TERMINAL_JOB_STATES]), + "failed": len(failed), "timeout": True}) raise typer.Exit(2) - time.sleep(min(1, max(0, deadline - time.monotonic()))) + + +@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 + from opendirector.domain.creation.commands import Query as QueryModel + commands = [] + for kind, model in COMMAND_MODELS.items(): + if kind not in COMMANDS: + continue + namespace, action = kind.split(".", 1) + schema = model.model_fields["payload"].annotation.model_json_schema() + branches = schema.get("anyOf") or schema.get("oneOf") + entry = {"command": f"{kebab(namespace)} {kebab(action)}", "type": kind, + "summary": (model.__doc__ or "").strip().splitlines()[0], + "required": sorted({field for branch in branches or (schema,) + for field in branch.get("required", ())})} + if branches: + entry["branches"] = [branch.get("description", branch.get("title", "variant")) for branch in branches] + if not compact: + entry["fields"] = list(schema.get("properties", {})) + commands.append(entry) + known = {entry["command"] for entry in commands} + for command in registered_commands(): + if command["command"] not in known: + entry = {"command": command["command"], "summary": command["summary"], + "required": command["required"]} + if not compact: + entry["options"] = command["options"] + commands.append(entry) + commands.sort(key=lambda entry: entry["command"]) + queries = sorted({type_name for model in get_args(get_args(QueryModel)[0]) + for type_name in getattr(model.model_fields["type"].annotation, "__args__", ())}) + emit({"commands": commands, "queries": queries, + "wait": "opendirector job wait --all", + "next": "Accepted receipts return ready-to-run next commands with current revisions."}) @app.command("query", help="Read project objects, versions, previews or execution status.") diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index e79902c46..5f6d0f29b 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -496,13 +496,20 @@ class CanvasStatusQuery(QueryBase): waitSeconds: float = Field(default=0, ge=0, le=30, description='Wait for generation changes; zero returns immediately.') +class JobStatusQuery(QueryBase): + type: Literal['job.status'] = Field(description='Read several generation jobs, optionally waiting for terminal states.') + objectIds: tuple[UUID, ...] = Field(default=(), max_length=50, description='Generation job IDs; every unfinished project job when empty.') + waitSeconds: float = Field(default=0, ge=0, le=300, description='Wait for terminal states; zero returns immediately.') + until: Literal['all', 'any'] = Field(default='all', description='Return after every selected job or any job reaches a terminal state.') + + class AssetPreviewQuery(QueryBase): type: Literal['asset.preview'] = Field(description='Preview an asset; does not establish model observation.') objectId: UUID = Field(description='Asset ID.') Query = Annotated[ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | - CanvasStatusQuery | AssetPreviewQuery, Field(discriminator='type')] + CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery, Field(discriminator='type')] class ChangedObject(Contract): diff --git a/scripts/bench_agent_polling.py b/scripts/bench_agent_polling.py new file mode 100644 index 000000000..b464ea473 --- /dev/null +++ b/scripts/bench_agent_polling.py @@ -0,0 +1,158 @@ +"""Measure the agent's per-turn polling, discovery and project-read cost. + +The agent waits for generation through the CLI. This compares the cost of the +per-job wait loop with the batched `job.status` query, the full project read with +`project show --summary`, and per-command `--help` discovery with the single +`capabilities` digest. The synthetic project has the same shape as the trace in +issue #449 (many canvas items, a long commit history, several unfinished jobs): + + python scripts/bench_agent_polling.py + python scripts/bench_agent_polling.py --jobs 14 --ticks 60 --commits 600 --nodes 200 --json +""" + +import argparse +import asyncio +import json +import shutil +import sys +import tempfile +import time +from pathlib import Path +from uuid import uuid4 + +SOURCE = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(SOURCE / "packages/core/src"), str(SOURCE / "apps/api/src")] + +from opendirector.application.creation_canvas import CreationCanvas # noqa: E402 +from pydantic import TypeAdapter # noqa: E402 +from opendirector.domain.creation.commands import Query, parse_command # noqa: E402 +from opendirector.domain.creation.generation import ImageGenerationSpec, InputSnapshot, Job # noqa: E402 +from opendirector.domain.creation.models import ModelSnapshot # noqa: E402 +from opendirector.domain.creation.project import ProjectSnapshot # noqa: E402 +from opendirector.infrastructure.creation_projects import CreationProjects # noqa: E402 +from opendirector.infrastructure.local_projects import LocalProjects # noqa: E402 +from opendirector.wiring import configure_runtime # noqa: E402 + +sys.path.insert(0, str(SOURCE / "scripts")) +from bench_creation_projects import add_saves, create_project # noqa: E402 + + +def command(kind, project_id, payload, versions=()): + return parse_command({"type": kind, "projectId": project_id, "commandId": uuid4(), + "payload": payload, "expectedVersions": list(versions)}) + + +def seed_jobs(projects, project_id, session, count): + snapshot = projects.snapshot(project_id) + model_id, spec_id = uuid4(), uuid4() + spec = ImageGenerationSpec(id=spec_id, projectId=project_id, kind="image", purpose="generation", + modelConfigId=model_id, prompt="A mountain") + model = ModelSnapshot(modelConfigId=model_id, kind="image", modelId="demo", url="https://model.test/v1", + protocol="openai", connectionType="api") + inputs = InputSnapshot(spec=spec, model=model) + jobs = [Job(id=uuid4(), projectId=project_id, inputSnapshot=inputs, inputFingerprint=inputs.fingerprint(), + execution=dict(kind="image", size="2K")) for _ in range(count)] + seed = command("generationSpec.create", project_id, {"spec": spec}) + + def transform(before): + data = before.model_dump() + data["generationSpecs"] = [spec] + data["jobs"] = jobs + return ProjectSnapshot.model_validate(data) + projects.commit(seed, transform, session=session) + return [job.id for job in jobs] + + +def timed(operation): + start = time.perf_counter() + value = operation() + return (time.perf_counter() - start) * 1000, value + + +def measure_polling(projects, canvas, project_id, job_ids, ticks): + reads = [0] + snapshot = projects.snapshot + + def counted(identity): + reads[0] += 1 + return snapshot(identity) + projects.snapshot = counted + + loop = asyncio.new_event_loop() + adapter = TypeAdapter(Query) + + def per_job(): + for identity in job_ids: + loop.run_until_complete(canvas.query(adapter.validate_python( + dict(type="job.get", projectId=project_id, queryId=uuid4(), objectId=str(identity))))) + return None + + per_job_ms, _ = timed(per_job) + per_job_reads = reads[0] / len(job_ids) + reads[0] = 0 + batch_ms, _ = timed(lambda: asyncio.run(canvas.wait_jobs(project_id, tuple(job_ids), 0, "all"))) + batch_reads = reads[0] + projects.snapshot = snapshot + return {"ticks": ticks, "jobs": len(job_ids), + "perJobQueryMs": round(per_job_ms / len(job_ids), 3), + "perJobSnapshotReads": per_job_reads, + "batchedQueryMs": round(batch_ms, 3), "batchedSnapshotReads": batch_reads, + "baselineTickMs": round(per_job_ms, 3), "batchedTickMs": round(batch_ms, 3), + "baselineQueriesPerWait": len(job_ids) * ticks, "batchedQueriesPerWait": ticks} + + +def measure_reads(projects, project_id): + from opendirector.cli import summarize + full = projects.snapshot(project_id).model_dump(mode="json") + full_bytes = len(json.dumps(full, ensure_ascii=False).encode()) + summary = summarize(full) + summary_bytes = len(json.dumps(summary, ensure_ascii=False).encode()) + return {"fullBytes": full_bytes, "summaryBytes": summary_bytes, + "ratio": round(summary_bytes / full_bytes, 3), "truncated": full_bytes > 65536} + + +def measure_discovery(): + from typer.testing import CliRunner + from opendirector import cli + runner = CliRunner() + per_command = 0 + kinds = sorted(cli.COMMANDS) + for kind in kinds: + namespace, action = kind.split(".", 1) + result = runner.invoke(cli.app, [cli.kebab(namespace), cli.kebab(action), "--help"]) + per_command += len(result.output.encode()) + root = len(runner.invoke(cli.app, ["--help"]).output.encode()) + digest = len(runner.invoke(cli.app, ["capabilities", "--compact"]).output.encode()) + verbose = len(runner.invoke(cli.app, ["capabilities"]).output.encode()) + return {"commands": len(kinds), "rootHelpBytes": root, "perCommandHelpBytes": per_command, + "naiveDiscoveryBytes": root + per_command, "capabilitiesBytes": digest, + "capabilitiesVerboseBytes": verbose} + + +def main(): + configure_runtime() + parser = argparse.ArgumentParser() + parser.add_argument("--jobs", type=int, default=14) + parser.add_argument("--ticks", type=int, default=60) + parser.add_argument("--nodes", type=int, default=200) + parser.add_argument("--commits", type=int, default=600) + parser.add_argument("--json", action="store_true") + options = parser.parse_args() + root = Path(tempfile.mkdtemp(prefix="bench-agent-polling-")) + result = {"jobs": options.jobs, "ticks": options.ticks} + try: + projects = CreationProjects(LocalProjects(root)) + project_id, session = create_project(projects, "polling", options.nodes) + add_saves(projects, project_id, session, options.commits, options.nodes) + canvas = CreationCanvas(projects) + job_ids = seed_jobs(projects, project_id, session, options.jobs) + result["polling"] = measure_polling(projects, canvas, project_id, job_ids, options.ticks) + result["projectRead"] = measure_reads(projects, project_id) + result["discovery"] = measure_discovery() + finally: + shutil.rmtree(root, ignore_errors=True) + print(json.dumps(result, ensure_ascii=False, indent=2) if not options.json else json.dumps(result, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 4bf548140..1e356b81b 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4235,6 +4235,7 @@ "canvas.versions": "#/$defs/VersionsQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", + "job.status": "#/$defs/JobStatusQuery", "object.get": "#/$defs/ObjectQuery", "project.get": "#/$defs/ProjectQuery" }, @@ -4259,6 +4260,9 @@ { "$ref": "#/$defs/CanvasStatusQuery" }, + { + "$ref": "#/$defs/JobStatusQuery" + }, { "$ref": "#/$defs/AssetPreviewQuery" } @@ -7869,6 +7873,65 @@ "title": "JobRecoverCommand", "type": "object" }, + "JobStatusQuery": { + "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": "job.status", + "description": "Read several generation jobs, optionally waiting for terminal states.", + "title": "Type", + "type": "string" + }, + "objectIds": { + "default": [], + "description": "Generation job IDs; every unfinished project job when empty.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 50, + "title": "Objectids", + "type": "array" + }, + "waitSeconds": { + "default": 0, + "description": "Wait for terminal states; zero returns immediately.", + "maximum": 300, + "minimum": 0, + "title": "Waitseconds", + "type": "number" + }, + "until": { + "default": "all", + "description": "Return after every selected job or any job reaches a terminal state.", + "enum": [ + "all", + "any" + ], + "title": "Until", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type" + ], + "title": "JobStatusQuery", + "type": "object" + }, "JsonValue": {}, "LayerContentBase": { "additionalProperties": false, @@ -15830,6 +15893,7 @@ "canvas.versions": "#/$defs/VersionsQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", + "job.status": "#/$defs/JobStatusQuery", "object.get": "#/$defs/ObjectQuery", "project.get": "#/$defs/ProjectQuery" }, @@ -15854,6 +15918,9 @@ { "$ref": "#/$defs/CanvasStatusQuery" }, + { + "$ref": "#/$defs/JobStatusQuery" + }, { "$ref": "#/$defs/AssetPreviewQuery" } @@ -20336,6 +20403,7 @@ "canvas.versions": "#/$defs/VersionsQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", + "job.status": "#/$defs/JobStatusQuery", "object.get": "#/$defs/ObjectQuery", "project.get": "#/$defs/ProjectQuery" }, @@ -20360,6 +20428,9 @@ { "$ref": "#/$defs/CanvasStatusQuery" }, + { + "$ref": "#/$defs/JobStatusQuery" + }, { "$ref": "#/$defs/AssetPreviewQuery" } @@ -24142,6 +24213,68 @@ "title": "JobRecoverCommand", "type": "object" }, + "JobStatusQuery": { + "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": "job.status", + "description": "Read several generation jobs, optionally waiting for terminal states.", + "title": "Type", + "type": "string" + }, + "objectIds": { + "default": [], + "description": "Generation job IDs; every unfinished project job when empty.", + "items": { + "format": "uuid", + "type": "string" + }, + "maxItems": 50, + "title": "Objectids", + "type": "array" + }, + "waitSeconds": { + "default": 0, + "description": "Wait for terminal states; zero returns immediately.", + "maximum": 300, + "minimum": 0, + "title": "Waitseconds", + "type": "number" + }, + "until": { + "default": "all", + "description": "Return after every selected job or any job reaches a terminal state.", + "enum": [ + "all", + "any" + ], + "title": "Until", + "type": "string" + } + }, + "required": [ + "queryId", + "projectId", + "type", + "objectIds", + "waitSeconds", + "until" + ], + "title": "JobStatusQuery", + "type": "object" + }, "JsonValue": {}, "LayerContentBase": { "additionalProperties": false, @@ -32389,6 +32522,7 @@ "canvas.versions": "#/$defs/VersionsQuery", "generationSpec.versions": "#/$defs/VersionsQuery", "job.get": "#/$defs/ObjectQuery", + "job.status": "#/$defs/JobStatusQuery", "object.get": "#/$defs/ObjectQuery", "project.get": "#/$defs/ProjectQuery" }, @@ -32413,6 +32547,9 @@ { "$ref": "#/$defs/CanvasStatusQuery" }, + { + "$ref": "#/$defs/JobStatusQuery" + }, { "$ref": "#/$defs/AssetPreviewQuery" } diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 772d869f9..a4e21479b 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -435,7 +435,7 @@ export interface CreationContractsInput extends ContractInput { readonly editorDocument: TimelineDocumentInput | SubjectDocumentInput | LayerDocumentInput | ImageCropDocumentInput | StackDocumentInput | ToolDocumentInput | DirectorDocumentInput | MediaEditDocumentInput; readonly command: ProjectCreateCommandInput | ProjectRenameCommandInput | ProjectTrashCommandInput | ProjectRestoreCommandInput | AssetImportCommandInput | ArtifactPublishCommandInput | AssetWriteTextCommandInput | AssetMetadataCommandInput | AssetDeleteCommandInput | CanvasCreateGenerationCommandInput | CanvasShowCommandInput | CanvasMoveCommandInput | CanvasUpdateCommandInput | CanvasHideCommandInput | CanvasMaterializeCommandInput | CanvasApplyEditCommandInput | CanvasPublishMediaCommandInput | TimelinePublishRenderCommandInput | NodeVersionApplyCommandInput | CanvasConfigureCommandInput | CanvasEditorAttachCommandInput | CanvasEditorDetachCommandInput | SpecCreateCommandInput | SpecUpdateCommandInput | SpecRestoreCommandInput | SpecPromptCommandInput | ReferenceAddCommandInput | ReferenceUpdateCommandInput | ReferenceRestoreCommandInput | ReferenceRemoveCommandInput | GenerationSubmitCommandInput | JobCancelCommandInput | JobRecoverCommandInput | JobCheckpointCommandInput | ResultSelectCommandInput | EditorCreateCommandInput | EditorSaveCommandInput | HistoryUndoCommandInput | HistoryRedoCommandInput | BatchCommandInput; readonly receipt: CommandReceiptInput; - readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | AssetPreviewQueryInput; + readonly query: ProjectQueryInput | ObjectQueryInput | VersionsQueryInput | AssetSearchQueryInput | AssetUsageQueryInput | CanvasStatusQueryInput | JobStatusQueryInput | AssetPreviewQueryInput; readonly event: ProjectEventInput; readonly job: JobInput; readonly result: ResultVersionInput; @@ -784,6 +784,13 @@ export interface JobRecoverCommandInput extends CommandBaseInput { readonly payload: JobControlInput; } +export interface JobStatusQueryInput extends QueryBaseInput { + readonly type: "job.status"; + readonly objectIds?: ReadonlyArray; + readonly waitSeconds?: number; + readonly until?: "all" | "any"; +} + export type JsonValueInput = unknown; export interface LayerContentBaseInput extends ContractInput { @@ -2084,7 +2091,7 @@ export interface CreationContracts extends Contract { readonly editorDocument: TimelineDocument | SubjectDocument | LayerDocument | ImageCropDocument | StackDocument | ToolDocument | DirectorDocument | MediaEditDocument; readonly command: ProjectCreateCommand | ProjectRenameCommand | ProjectTrashCommand | ProjectRestoreCommand | AssetImportCommand | ArtifactPublishCommand | AssetWriteTextCommand | AssetMetadataCommand | AssetDeleteCommand | CanvasCreateGenerationCommand | CanvasShowCommand | CanvasMoveCommand | CanvasUpdateCommand | CanvasHideCommand | CanvasMaterializeCommand | CanvasApplyEditCommand | CanvasPublishMediaCommand | TimelinePublishRenderCommand | NodeVersionApplyCommand | CanvasConfigureCommand | CanvasEditorAttachCommand | CanvasEditorDetachCommand | SpecCreateCommand | SpecUpdateCommand | SpecRestoreCommand | SpecPromptCommand | ReferenceAddCommand | ReferenceUpdateCommand | ReferenceRestoreCommand | ReferenceRemoveCommand | GenerationSubmitCommand | JobCancelCommand | JobRecoverCommand | JobCheckpointCommand | ResultSelectCommand | EditorCreateCommand | EditorSaveCommand | HistoryUndoCommand | HistoryRedoCommand | BatchCommand; readonly receipt: CommandReceipt; - readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | AssetPreviewQuery; + readonly query: ProjectQuery | ObjectQuery | VersionsQuery | AssetSearchQuery | AssetUsageQuery | CanvasStatusQuery | JobStatusQuery | AssetPreviewQuery; readonly event: ProjectEvent; readonly job: Job; readonly result: ResultVersion; @@ -2433,6 +2440,13 @@ export interface JobRecoverCommand extends CommandBase { readonly payload: JobControl; } +export interface JobStatusQuery extends QueryBase { + readonly type: "job.status"; + readonly objectIds: ReadonlyArray; + readonly waitSeconds: number; + readonly until: "all" | "any"; +} + export type JsonValue = unknown; export interface LayerContentBase extends Contract { diff --git a/tests/test_agent_gateway.py b/tests/test_agent_gateway.py index 4b58f1baa..2e2cfd670 100644 --- a/tests/test_agent_gateway.py +++ b/tests/test_agent_gateway.py @@ -342,6 +342,42 @@ async def test_model_preferences_do_not_add_a_business_veto(gateway): assert str(projects.snapshot(run.project_id).generationSpecs[0].modelConfigId) == alternative +@pytest.mark.anyio +async def test_close_cancels_a_pending_job_status_wait(gateway, monkeypatch): + """Stopping a turn must not wait out the poll window the turn asked for.""" + entered = asyncio.Event() + cancelled = asyncio.Event() + + async def execute(*args): + entered.set() + try: + await asyncio.Event().wait() + finally: + cancelled.set() + + monkeypatch.setattr(gateway.business, 'execute', execute) + waiter = asyncio.create_task(gateway.call('poll', 'query', {'type': 'job.status', 'waitSeconds': 300})) + await entered.wait() + await asyncio.wait_for(gateway.close(), timeout=1) + assert cancelled.is_set() + with pytest.raises(asyncio.CancelledError): + await waiter + + +@pytest.mark.anyio +async def test_a_query_argument_shape_that_is_not_read_only_stays_a_tool_error(gateway): + """The read-only check runs before validation, so it must answer, not raise.""" + from opendirector.agent.gateway import _read_only + + for arguments in ({'type': ['job.status']}, ['job.status'], None, {'objectId': str(uuid4())}): + assert not _read_only('query', arguments) + assert _read_only('query', {'type': 'job.status'}) + assert not _read_only('execute_command', {'type': 'job.status'}) + for arguments in ({'type': ['job.status']}, ['job.status']): + result = await gateway.call('poll', 'query', arguments) + assert result.error + + @pytest.mark.anyio async def test_close_cancels_pending_canvas_status_wait(gateway, monkeypatch): entered = asyncio.Event() @@ -378,3 +414,25 @@ async def execute(*args): arguments = {'type': 'canvas.show', 'payload': {}} assert not (await gateway.call('first', 'execute_command', arguments)).error assert calls == ['execute_command'] + + +@pytest.mark.anyio +async def test_read_only_query_answers_while_a_write_holds_the_execution_slot(gateway, monkeypatch): + entered, release = asyncio.Event(), asyncio.Event() + async def execute(*args): + if args[4] == 'query': + return {'jobs': [], 'terminal': True} + entered.set() + await release.wait() + return {'status': 'accepted'} + monkeypatch.setattr(gateway.business, 'execute', execute) + write = asyncio.create_task(gateway.call('submit', 'execute_command', {'type': 'generation.submit', 'payload': {}})) + await entered.wait() + queued = asyncio.create_task(gateway.call('submit-again', 'execute_command', {'type': 'generation.submit', 'payload': {}})) + await asyncio.sleep(0.05) + assert not queued.done() + answer = await asyncio.wait_for(gateway.call('poll', 'query', {'type': 'job.status'}), 1) + assert answer.value['terminal'] is True + release.set() + await asyncio.gather(write, queued) + await gateway.close() diff --git a/tests/test_cli.py b/tests/test_cli.py index 16d4b4c0e..966c6d860 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,11 +6,12 @@ import subprocess import sys from unittest.mock import Mock -from uuid import uuid4 +from uuid import UUID, uuid4 from fastapi.testclient import TestClient import httpx import pytest +import typer from typer.testing import CliRunner from opendirector import cli @@ -345,10 +346,9 @@ def test_accepted_cli_receipt_provides_wait_commands(monkeypatch): try: result = client.execute("generation.submit", {}) commands = result["next"]["commands"] - assert len(commands) == 2 - for job_id, command in zip(jobs, commands): - assert shlex.split(command) == ["opendirector", "--url", "http://localhost:18765", - "--project", project, "job", "wait", job_id, "--timeout", "60"] + assert len(commands) == 1 + assert shlex.split(commands[0]) == ["opendirector", "--url", "http://localhost:18765", + "--project", project, "job", "wait", *jobs, "--timeout", "60"] assert "next" not in receipt finally: client.http.close() @@ -476,3 +476,164 @@ def forbidden(*args, **kwargs): assert value['version'] == '2.004' assert value['fingerprint'] == 'sha256:' + sha256(path.read_bytes()).hexdigest() assert not (tmp_path / 'unused').exists() + + +def wait_context(monkeypatch, states): + """Record every server call job wait makes.""" + from types import SimpleNamespace + calls = [] + states = list(states) + + def query(kind, **arguments): + calls.append((kind, arguments)) + return states.pop(0) if len(states) > 1 else states[0] + return SimpleNamespace(command_path="job wait", obj=SimpleNamespace(command="", query=query)), calls + + +TERMINAL = {"succeeded", "failed", "cancelled", "interrupted"} + + +def test_job_wait_covers_every_job_in_one_call_per_window(monkeypatch, capsys): + jobs = [str(uuid4()), str(uuid4())] + context, calls = wait_context(monkeypatch, [ + {"jobs": [{"id": jobs[0], "status": "running"}, {"id": jobs[1], "status": "queued"}]}, + {"jobs": [{"id": jobs[0], "status": "succeeded"}, {"id": jobs[1], "status": "succeeded"}]}, + ]) + cli.job_wait(context, [UUID(job) for job in jobs], False, 300) + assert [kind for kind, _ in calls] == ["job.status", "job.status"] + assert calls[0][1]["objectIds"] == jobs + assert calls[0][1]["until"] == "all" + assert calls[0][1]["waitSeconds"] == cli.WAIT_WINDOW + emitted = json.loads(capsys.readouterr().out) + assert emitted["completed"] == 2 and emitted["failed"] == 0 + + +def test_job_wait_all_waits_for_unfinished_jobs_without_naming_ids(monkeypatch, capsys): + job = str(uuid4()) + context, calls = wait_context(monkeypatch, [{"jobs": [{"id": job, "status": "succeeded"}]}]) + cli.job_wait(context, None, True, 30) + assert calls[0][1]["objectIds"] == [] + assert json.loads(capsys.readouterr().out)["completed"] == 1 + + +def test_job_wait_reports_a_failure_that_settles_while_it_waits(monkeypatch, capsys): + jobs = [str(uuid4()), str(uuid4())] + context, calls = wait_context(monkeypatch, [ + {"jobs": [{"id": jobs[0], "status": "running"}, {"id": jobs[1], "status": "running"}]}, + {"jobs": [{"id": jobs[0], "status": "succeeded"}, + {"id": jobs[1], "status": "failed", "errorDetails": {"category": "provider"}}]}, + ]) + with pytest.raises(typer.Exit) as error: + cli.job_wait(context, [UUID(job) for job in jobs], False, 300) + assert error.value.exit_code == 1 + assert calls[1][1]["objectIds"] == jobs + emitted = json.loads(capsys.readouterr().out) + assert emitted["completed"] == 1 and emitted["failed"] == 1 + assert emitted["jobs"][1]["errorDetails"] == {"category": "provider"} + assert "errorDetails" in emitted["note"] + + +def test_job_wait_says_so_when_nothing_is_running(monkeypatch, capsys): + context, calls = wait_context(monkeypatch, [{"jobs": []}]) + cli.job_wait(context, None, True, 30) + assert calls[0][1]["objectIds"] == [] + emitted = json.loads(capsys.readouterr().out) + assert emitted["jobs"] == [] and emitted["completed"] == 0 and emitted["failed"] == 0 + assert "still running" in emitted["note"] + + +def test_a_wait_window_fits_the_agent_socket_timeout(): + """One wait window plus its snapshot read must answer before the read times out.""" + assert cli.WAIT_WINDOW + 60 <= cli.SOCKET_TIMEOUT + assert cli.WAIT_WINDOW > 0 + + +def test_job_wait_reports_failure_and_timeout_with_distinct_exit_codes(monkeypatch, capsys): + job = str(uuid4()) + failed, _ = wait_context(monkeypatch, [{"jobs": [{"id": job, "status": "failed"}]}]) + with pytest.raises(typer.Exit) as error: + cli.job_wait(failed, [UUID(job)], False, 30) + assert error.value.exit_code == 1 + assert json.loads(capsys.readouterr().out)["failed"] == 1 + running, _ = wait_context(monkeypatch, [{"jobs": [{"id": job, "status": "running"}]}]) + with pytest.raises(typer.Exit) as error: + cli.job_wait(running, [UUID(job)], False, 0) + assert error.value.exit_code == 2 + assert json.loads(capsys.readouterr().out)["timeout"] is True + + +def test_project_show_summary_keeps_every_identity_without_record_bodies(monkeypatch, capsys): + from types import SimpleNamespace + def asset(index): + return {"id": str(uuid4()), "revision": 1, "kind": "image", "name": f"asset-{index}", + "metadata": {"width": 2048, "height": 2048, "durationSeconds": None}, + "fingerprint": "sha256:" + "a" * 64, "provenance": {"prompt": "x" * 4096}, "source": {"path": "/tmp/asset.png"}} + snapshot = {"project": {"id": str(uuid4()), "name": "Demo", "revision": 7}, + "assets": [asset(index) for index in range(40)], + "canvasItems": [{"id": str(uuid4()), "revision": 2, "kind": "image", "visible": True, + "position": {"x": 0, "y": 0}, "width": 352, "height": 198, + "binding": {"role": "generation", "objectRef": {"id": str(uuid4())}}}], + "generationSpecs": [{"id": str(uuid4()), "revision": 3, "purpose": "generation", + "modelConfigId": str(uuid4()), "currentResultId": None}], + "jobs": [{"id": str(uuid4()), "revision": 2, "status": "succeeded", "phase": "complete"}], + "results": [{"id": str(uuid4()), "jobId": str(uuid4()), "asset": {"assetId": str(uuid4())}}], + "references": [], "editorDocuments": []} + context = SimpleNamespace(command_path="project show", obj=SimpleNamespace(command="", snapshot=lambda: snapshot)) + cli.project_show(context, True) + summary = json.loads(capsys.readouterr().out) + assert len(summary["assets"]) == 40 and summary["assets"][0]["width"] == 2048 + assert summary["project"]["revision"] == 7 + assert summary["counts"]["assets"] == 40 + assert "fingerprint" not in summary["assets"][0] and "provenance" not in summary["assets"][0] + assert len(json.dumps(summary)) * 4 < len(json.dumps(snapshot)) + + +def test_project_show_summary_keeps_reference_and_editor_identities(monkeypatch, capsys): + """reference.update and editor.save take these IDs, so the summary must carry them.""" + from types import SimpleNamespace + reference, document = str(uuid4()), str(uuid4()) + snapshot = {"project": {"id": str(uuid4()), "name": "Demo", "revision": 7}, + "references": [{"id": reference, "revision": 4, "targetSpecId": str(uuid4()), + "binding": "pinned", "role": "first_frame", "order": 2, "active": True, + "source": {"assetId": str(uuid4()), "fingerprint": "sha256:" + "b" * 64}}], + "editorDocuments": [{"id": document, "revision": 9, "kind": "timeline", "title": "Main", + "data": {"tracks": [1, 2, 3]}}]} + context = SimpleNamespace(command_path="project show", obj=SimpleNamespace(command="", snapshot=lambda: snapshot)) + cli.project_show(context, True) + summary = json.loads(capsys.readouterr().out) + assert summary["references"] == [{"id": reference, "revision": 4, "targetSpecId": snapshot["references"][0]["targetSpecId"], + "binding": "pinned", "role": "first_frame", "order": 2, "active": True}] + assert summary["editorDocuments"] == [{"id": document, "revision": 9, "kind": "timeline", "title": "Main"}] + assert summary["counts"]["references"] == 1 and summary["counts"]["editorDocuments"] == 1 + + +def test_capabilities_lists_commands_and_query_types_once(help_color): + result = CliRunner().invoke(cli.app, ["capabilities", "--compact"]) + assert result.exit_code == 0, result.output + digest = json.loads(result.output) + kinds = {entry["type"]: entry for entry in digest["commands"] if entry.get("type")} + assert {"generation.submit", "canvas.createGeneration", "generationSpec.update", "job.cancel"} <= set(kinds) + assert all(entry["summary"] and entry["command"].strip() == entry["command"] for entry in digest["commands"]) + assert kinds["canvas.show"]["required"] == ["item"] + assert kinds["generation.submit"]["required"] == ["expectedSpecRevision", "specId"] + assert "fields" not in kinds["generation.submit"] + assert {"job.status", "job.get", "canvas.status"} <= set(digest["queries"]) + assert digest["wait"] == "opendirector job wait --all" + assert "opendirector --help" not in result.output + + +def test_capabilities_names_commands_that_have_no_command_model(help_color): + """Discovery must cover the parser, not only commands built from a model.""" + result = CliRunner().invoke(cli.app, ["capabilities", "--compact"]) + assert result.exit_code == 0, result.output + listed = {entry["command"]: entry for entry in json.loads(result.output)["commands"]} + assert {"job wait", "job show", "project show", "query", "model list", "model show", + "model availability", "asset import", "video create", "canvas add-material", + "canvas text create", "timeline import", "timeline export", "timeline default-font", + "voice list", "voice create", "voice delete"} <= set(listed) + assert listed["canvas add-material"]["required"] == ["asset", "x", "y"] + assert listed["job show"]["required"] == ["job_id"] + assert "options" not in listed["job show"] + detailed = json.loads(CliRunner().invoke(cli.app, ["capabilities"]).output)["commands"] + assert "--asset-id" not in [option.split()[-1] for entry in detailed for option in entry.get("options", ())] + assert "--object-id" in [option for entry in detailed for option in entry.get("options", ())] diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py index 99cd88e1b..965f333fc 100644 --- a/tests/test_creation_canvas_service.py +++ b/tests/test_creation_canvas_service.py @@ -505,3 +505,117 @@ def test_canvas_update_without_color_keeps_its_historical_fingerprint(): # The fingerprint hashes this dump, so it must equal the pre-color payload exactly. assert command.model_dump(mode='json')['payload'] == legacy assert parse_command(dict(base, payload=dict(legacy, color=''))).model_dump(mode='json')['payload']['color'] == '' + + +def seed_jobs(project, count, statuses=('queued',)): + """Commit real job records without any provider call.""" + from opendirector.domain.creation.generation import ImageGenerationSpec, InputSnapshot, Job + from opendirector.domain.creation.models import ModelSnapshot + from opendirector.domain.creation.project import ProjectSnapshot + store, pid, session = project + model_id, spec_id = uuid4(), uuid4() + spec = ImageGenerationSpec(id=spec_id, projectId=pid, kind='image', purpose='generation', modelConfigId=model_id, prompt='A mountain') + model = ModelSnapshot(modelConfigId=model_id, kind='image', modelId='demo', url='https://model.test/v1', protocol='openai', connectionType='api') + snapshot = InputSnapshot(spec=spec, model=model) + jobs = [Job(id=uuid4(), projectId=pid, inputSnapshot=snapshot, inputFingerprint=snapshot.fingerprint(), + execution=dict(kind='image', size='2K'), status=statuses[index % len(statuses)]) for index in range(count)] + seed = parse_command(dict(commandId=uuid4(), projectId=pid, type='generationSpec.create', expectedVersions=[], payload={'spec': spec})) + + def transform(before): + data = before.model_dump() + data['generationSpecs'] = [spec] + data['jobs'] = jobs + return ProjectSnapshot.model_validate(data) + store.commit(seed, transform, session=session) + return jobs + + +def test_job_status_answers_every_job_from_one_snapshot(project, monkeypatch): + store, pid, _ = project + jobs = seed_jobs(project, 12) + canvas = CreationCanvas(store) + reads = [] + snapshot = store.snapshot + + def counted(project_id): + reads.append(project_id) + return snapshot(project_id) + monkeypatch.setattr(store, 'snapshot', counted) + result = canvas.job_states(pid, tuple(job.id for job in jobs)) + assert len(reads) == 1 + assert len(result['jobs']) == 12 + assert result['terminal'] is False + assert [job['status'] for job in result['jobs']] == ['queued'] * 12 + assert len(canvas.job_states(pid)['jobs']) == 12 + assert len(reads) == 2 + from opendirector.domain.creation.validation import ContractError + with pytest.raises(ContractError) as error: + canvas.job_states(pid, (uuid4(),)) + assert error.value.issue.code == 'missing_object' + + +def test_job_status_omits_settled_jobs_and_reports_missing_ones(project): + store, pid, _ = project + jobs = seed_jobs(project, 3, statuses=('queued', 'cancelled')) + canvas = CreationCanvas(store) + assert [job['status'] for job in canvas.job_states(pid)['jobs']] == ['queued', 'queued'] + settled = [job for job in jobs if job.status == 'cancelled'] + assert canvas.job_states(pid, (settled[0].id,))['terminal'] is True + + +def test_wait_jobs_returns_on_any_or_all_and_stops_at_the_timeout(project, monkeypatch): + import asyncio + store, pid, _ = project + jobs = seed_jobs(project, 2) + canvas = CreationCanvas(store) + windows = [{'jobs': [{'status': 'running'}, {'status': 'queued'}], 'terminal': False}, + {'jobs': [{'status': 'succeeded'}, {'status': 'queued'}], 'terminal': False}, + {'jobs': [{'status': 'succeeded'}, {'status': 'running'}], 'terminal': False}] + monkeypatch.setattr(canvas, 'job_states', lambda *args: windows[0]) + assert asyncio.run(canvas.wait_jobs(pid, (), 0.01, 'all'))['terminal'] is False + calls = [] + + def sequence(*args): + calls.append(1) + return windows[min(len(calls) - 1, len(windows) - 1)] + monkeypatch.setattr(canvas, 'job_states', sequence) + any_result = asyncio.run(canvas.wait_jobs(pid, (), 5, 'any')) + assert any_result['jobs'][0]['status'] == 'succeeded' + assert len(calls) == 2 + + +def test_wait_jobs_holds_the_group_it_started_with(project, monkeypatch): + """A job that settles while we wait is still reported, with its failure.""" + import asyncio + store, pid, _ = project + jobs = seed_jobs(project, 2) + canvas = CreationCanvas(store) + seen = [] + + def states(project_id, object_ids=()): + seen.append(tuple(object_ids)) + settled = len(seen) > 1 + return {'jobs': [{'id': str(job.id), 'status': 'failed' if settled and index else 'queued', + 'errorDetails': {'category': 'provider'} if settled and index else None} + for index, job in enumerate(jobs)], 'terminal': settled} + + monkeypatch.setattr(canvas, 'job_states', states) + result = asyncio.run(canvas.wait_jobs(pid, (), 5, 'all')) + assert seen[0] == tuple(job.id for job in jobs) + assert seen[1] == seen[0] + assert [job['status'] for job in result['jobs']] == ['queued', 'failed'] + assert result['jobs'][1]['errorDetails'] == {'category': 'provider'} + assert result['terminal'] is True + + +def test_job_status_includes_delivery_from_the_same_snapshot(): + from types import SimpleNamespace + from test_creation_contracts import project_example + snapshot = project_example() + canvas = CreationCanvas(SimpleNamespace(snapshot=lambda _: snapshot)) + view = canvas.job_states(snapshot.project.id, (snapshot.jobs[0].id,))['jobs'][0] + assert view['status'] == 'succeeded' + assert view['delivery']['asset'] == view['asset'] + assert view['delivery']['adopted'] is True + assert [item['id'] for item in view['delivery']['canvasItems']] == [str(snapshot.canvasItems[-3].id)] + assert 'Inspect this existing asset directly' in view['delivery']['guidance'] From d369be5619b452233b6483d8919e8ec31dc8a00b Mon Sep 17 00:00:00 2001 From: Redivesue <177306048+Redivesue@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:45:39 +0800 Subject: [PATCH 2/2] [feat] canvas: show project structure before node media Opening or switching a canvas waited for every node's media, including hidden nodes, before the workspace became interactive. Project the canvas from the opened snapshot and keep a stable asset source in node media fields. Object URLs are resolved only where media is displayed or read, so they no longer enter the document, undo history or save baseline. Saving compares asset identity, so a late media read cannot change a binding. Return text with open-canvas, show loading and failed states per node, and check reference-catalog files against its one snapshot. Refs #446 --- apps/api/src/opendirector_api/creation.py | 5 +- docs/development/validation.md | 1 + .../application/creation_canvas.py | 18 ++ .../application/creation_history.py | 2 +- scripts/run-browser-suite.mjs | 4 + src/backend/assetSource.ts | 17 ++ src/backend/creationClient.ts | 82 ++++++++- src/backend/creationProjection.ts | 56 ++++-- src/backend/imageSelections.ts | 3 +- src/canvas/AssistantPanel.tsx | 3 +- src/canvas/CanvasMediaPreview.tsx | 3 + src/canvas/CanvasNodeView.tsx | 44 ++++- src/canvas/ChatReferenceEditor.tsx | 19 +- src/canvas/EditorModal.tsx | 9 +- src/canvas/ImageEditor.tsx | 16 +- src/canvas/LayerBoard.tsx | 4 +- src/canvas/LocalMediaEditor.tsx | 16 +- src/canvas/NodeComposer.tsx | 4 +- src/canvas/ReferenceThumbnail.tsx | 3 +- src/canvas/SubjectNodeCard.tsx | 11 +- src/canvas/TimelineEditor.tsx | 13 +- src/canvas/VideoActionEditor.tsx | 4 +- src/canvas/canvasArchive.ts | 3 +- src/canvas/clipboardMedia.ts | 7 +- src/canvas/editorMedia.ts | 12 ++ src/canvas/imageCrop.ts | 2 + src/canvas/layerDocument.ts | 4 +- src/canvas/layerRenderer.ts | 5 +- src/canvas/library/CanvasSourceCard.tsx | 7 +- src/canvas/library/libraryClient.ts | 3 +- src/canvas/nodes.css | 1 + src/canvas/storage.ts | 13 +- src/canvas/timelineExport.ts | 10 +- src/canvas/timelineRender.ts | 5 +- src/canvas/timelineTextRenderer.ts | 3 +- src/canvas/useAssetMedia.tsx | 65 +++++++ src/canvas/videoActionRuntime.ts | 5 +- src/canvas/workspace/WorkspaceView.tsx | 9 +- src/canvas/workspace/useWorkspaceDocument.ts | 17 ++ src/canvas/workspace/useWorkspaceTransfer.ts | 5 +- src/i18n/messages/en-US/canvasNodes.ts | 3 + src/i18n/messages/zh-CN/canvasNodes.ts | 3 + tests/browser/canvas_progressive_load.mjs | 164 ++++++++++++++++++ tests/browser/double_shift_chat.mjs | 3 +- tests/browser/manifest.json | 5 + tests/creationClient.test.ts | 112 +++++++++++- tests/creationEditorSession.test.ts | 7 +- tests/creationLayers.test.ts | 12 +- tests/test_creation_api.py | 1 + tests/test_creation_canvas_service.py | 8 + tests/test_creation_history_service.py | 13 ++ 51 files changed, 764 insertions(+), 80 deletions(-) create mode 100644 src/backend/assetSource.ts create mode 100644 src/canvas/useAssetMedia.tsx create mode 100644 tests/browser/canvas_progressive_load.mjs diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index c1de28496..d2ca75cec 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -105,12 +105,13 @@ def open_project(project_id: UUID, x_opendirector_session: UUID = Header()): @router.post('/projects/{project_id}/open-canvas') def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header()): - # The canvas needs its reference edges on first render too. Reuse the + # The canvas needs its reference edges and text on first render too. Reuse the # single snapshot this open read already published instead of making the # page read the same project again through GET /canvas. The no-flag # route above still returns a bare ProjectSnapshot. snapshot = projects.open(project_id, str(x_opendirector_session)) - return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot)} + return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot), + 'texts': canvas.text_contents(snapshot)} @router.put('/sessions/{session_id}') def heartbeat(session_id: UUID, value: Session): diff --git a/docs/development/validation.md b/docs/development/validation.md index 13c985ce6..b037e9bad 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -309,6 +309,7 @@ node tests/browser/reference_reconnect.mjs # 参考连线删除后重连 node tests/browser/context_menu_dismissal.mjs # 右键菜单关闭 node tests/browser/mp4_export.mjs # 合成 MP4(WebCodecs + 软件 AAC) node tests/browser/new_image_node_outputs.mjs # 新建图片节点采用所选适配器的比例与尺寸 +node tests/browser/canvas_progressive_load.mjs # 画布结构先可用,节点媒体独立加载、失败重试且不改写内容 ``` 历史版本预览回归([#393](https://github.com/ThinkFlowLab/OpenDirector/issues/393))沿用上述隔离服务:运行 `node tests/browser/node_versions.mjs`;设置 `HISTORY_PREVIEW_PROBE=delay` 会延迟目标缩略图一秒,完整旅程应通过。设置 `HISTORY_PREVIEW_PROBE=missing` 会注入缩略图 404,预期脚本失败并输出 `History preview unavailable`、目标资产 ID、HTTP 状态和媒体提示;它是故障诊断检查,不是成功旅程。清除变量后恢复正常运行。布局断言必须等待预期资产的图片加载成功,不能以提示词出现代替预览就绪。 diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index bac550dc1..a93ed0c98 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -826,6 +826,24 @@ def check_asset(asset): return check_asset + def text_contents(self, snapshot): + """Text shown by canvas items, read with the snapshot that opens the canvas. + + An unreadable body is left out so only that item reports it. + """ + contents = {} + for item in snapshot.canvasItems: + asset = current_asset(snapshot, item) + if asset is None or asset.kind != 'text' or str(asset.id) in contents: + continue + try: + stream, _ = self.assets.open_media(asset.projectId, asset.id, snapshot=snapshot) + with stream: + contents[str(asset.id)] = stream.read().decode('utf-8-sig', 'replace') + except (ContractError, ProjectError, OSError): + continue + return contents + def reference_edges(self, project_id, snapshot=None, check_asset=None): """Authoritative canvas reference states for one snapshot. diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index abf3ef9f8..a48f5a693 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -125,7 +125,7 @@ def reference_catalog(self, project_id): for asset in snapshot.assets: file_available = True try: - service.reference_available(project_id, asset.id) + service.reference_available(project_id, asset.id, snapshot=snapshot) except (ContractError, ProjectError, OSError, ValueError): file_available = False available = file_available and (asset.id in listed or asset.id in owners) diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 7f1c43be0..9545f3f56 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -60,6 +60,10 @@ const workflows = [ name: "canvas switch", script: "tests/browser/canvas_switch.mjs", }, + { + name: "canvas progressive load", + script: "tests/browser/canvas_progressive_load.mjs", + }, { name: "structured editors", script: "tests/browser/structured_editors.mjs", diff --git a/src/backend/assetSource.ts b/src/backend/assetSource.ts new file mode 100644 index 000000000..93620c372 --- /dev/null +++ b/src/backend/assetSource.ts @@ -0,0 +1,17 @@ +/** A stable reference to a saved asset in a node's media fields. + * + * Object URLs depend on what this page has loaded, so they cannot describe + * project content. This value stays the same before and after the bytes arrive + * and is resolved only where media is displayed or read. */ +const PREFIX = "opendirector-asset://"; + +export const assetSource = (projectId: string, assetId: string) => + `${PREFIX}${projectId}/${assetId}`; + +export function parseAssetSource(src: string | null | undefined) { + if (!src?.startsWith(PREFIX)) return undefined; + const [projectId, assetId, extra] = src.slice(PREFIX.length).split("/"); + return projectId && assetId && extra === undefined + ? { projectId, assetId } + : undefined; +} diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 3f769045a..d5c031e44 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -22,6 +22,7 @@ import { storageRequest, } from "./api.ts"; import { tNow } from "../i18n/messages.ts"; +import { parseAssetSource } from "./assetSource.ts"; import { abortable, resilientRead, type ReadOptions } from "./resilientRead.ts"; export type CreationOperation = BatchPayloadInput["operations"][number]; @@ -77,6 +78,10 @@ export class CreationClient { private subscription: AbortController | undefined; private media = new Map>(); private sourceAssets = new Map(); + /** Bytes behind each object URL. The desktop CSP does not allow fetching blob URLs. */ + private mediaBytes = new Map(); + private unavailableMedia = new Set(); + private mediaListeners = new Set<() => void>(); private text = new Map>(); private submissions: Promise = Promise.resolve(); private deliveries = new Map>(); @@ -134,6 +139,7 @@ export class CreationClient { referenceId: string; state: "used" | "pending" | "unknown" | "unavailable"; }[]; + texts?: Record; } | undefined; for (let attempt = 0; ; attempt++) { @@ -146,6 +152,7 @@ export class CreationClient { referenceId: string; state: "used" | "pending" | "unknown" | "unavailable"; }[]; + texts?: Record; } >(`${creationPath(this.id)}/open-canvas`, { method: "POST" }); // The open-canvas response carries the one authoritative snapshot plus @@ -158,6 +165,10 @@ export class CreationClient { this.referenceStates = new Map( canvas.edges.map((edge) => [edge.referenceId, edge.state]), ); + // Text is part of what the structure shows, so projecting it never + // waits for a separate read per node. + for (const [assetId, text] of Object.entries(canvas?.texts ?? {})) + this.text.set(assetId, Promise.resolve(text)); this.install(canvas ? canvas.snapshot : (opened as ProjectSnapshot)); break; } catch (error) { @@ -396,16 +407,35 @@ export class CreationClient { .then((blob) => { const url = URL.createObjectURL(blob); this.sourceAssets.set(url, assetId); + this.mediaBytes.set(assetId, blob); + this.markMedia(assetId, true); return url; }) .catch((error) => { this.media.delete(assetId); + this.markMedia(assetId, false); throw error; }); this.media.set(assetId, pending); } return abortable(pending, options.signal); } + private markMedia(assetId: string, available: boolean) { + if (available === !this.unavailableMedia.has(assetId)) return; + if (available) this.unavailableMedia.delete(assetId); + else this.unavailableMedia.add(assetId); + for (const listener of this.mediaListeners) listener(); + } + /** Whether the last read of this asset's media failed. */ + mediaUnavailable(assetId: string) { + return this.unavailableMedia.has(assetId); + } + listenMedia(listener: () => void) { + this.mediaListeners.add(listener); + return () => { + this.mediaListeners.delete(listener); + }; + } thumbnailUrl(assetId: string) { const key = `thumbnail:${assetId}`; let pending = this.media.get(key); @@ -445,15 +475,36 @@ export class CreationClient { this.sourceAssets.set(src, assetId); } assetForSource(src: string) { - const id = this.sourceAssets.get(src); + const source = parseAssetSource(src); + const id = + source?.projectId === this.id + ? source.assetId + : this.sourceAssets.get(src); return this.snapshot.assets.find((asset) => asset.id === id); } - async originalMedia(src: string, mimeType?: string, signal?: AbortSignal) { + async originalMedia( + src: string, + mimeType?: string, + signal?: AbortSignal, + ): Promise { + const source = parseAssetSource(src); + if (source && source.projectId !== this.id) + return creationClient(source.projectId).originalMedia(src, mimeType, signal); const asset = this.assetForSource(src); if (asset && ["image/heic", "image/heif"].includes(asset.metadata.mimeType)) return this.blob(asset.id, { signal }); if (["image/heic", "image/heif"].includes(mimeType ?? "")) throw new Error(tNow("errors.archive.readMedia")); + if (source) { + // A saved asset that is not on screen is read without retaining a preview. + if (!this.media.has(source.assetId)) + return this.blob(source.assetId, { signal }); + await this.mediaUrl(source.assetId, { signal }); + return ( + this.mediaBytes.get(source.assetId) ?? + this.blob(source.assetId, { signal }) + ); + } const response = await fetch(src, { signal }); if (!response.ok) throw new Error(tNow("errors.archive.readMedia")); return response.blob(); @@ -753,6 +804,8 @@ export class CreationClient { for (const pending of this.media.values()) void pending.then(URL.revokeObjectURL, () => {}); this.media.clear(); + this.mediaBytes.clear(); + this.unavailableMedia.clear(); this.sourceAssets.clear(); this.text.clear(); } @@ -768,6 +821,31 @@ export const creationClient = (id: string) => { return client; }; +/** The browser URL for a media field. Inline and object URLs are returned as is. */ +export async function resolveMediaSource(src: string, signal?: AbortSignal) { + const source = parseAssetSource(src); + return source + ? creationClient(source.projectId).mediaUrl(source.assetId, { signal }) + : src; +} + +/** Reads a media field. A saved asset is read through its project, and an + * object URL is read immediately, before its owner can revoke it. */ +export function fetchMediaSource( + src: string, + init?: RequestInit & { signal?: AbortSignal }, +): Promise { + const source = parseAssetSource(src); + return source + ? creationClient(source.projectId) + .originalMedia(src, undefined, init?.signal) + .then( + (blob) => + new Response(blob, { headers: { "Content-Type": blob.type } }), + ) + : fetch(src, init); +} + export function currentAsset( snapshot: ProjectSnapshot, item: CanvasItem, diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index d6975ba06..e68ed479c 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -46,6 +46,7 @@ import { visibleItems, type CreationOperation, } from "./creationClient.ts"; +import { assetSource } from "./assetSource.ts"; import { sameJsonValue } from "./sameJsonValue.ts"; import { classifyImportFile, readEditorResource } from "../canvas/editorMedia.ts"; @@ -125,7 +126,7 @@ export class CreationProjection { byteSize: asset.metadata.size, kind: asset.kind as CanvasResource["kind"], title: title ?? asset.name, - src: await this.client.mediaUrl(asset.id).catch(() => undefined), + src: assetSource(this.client.id, asset.id), mimeType: asset.metadata.mimeType, width: asset.metadata.width ?? undefined, height: asset.metadata.height ?? undefined, @@ -244,9 +245,7 @@ export class CreationProjection { title: title ?? asset?.name ?? ref.assetId, asset: { ...ref }, mimeType: asset?.metadata.mimeType ?? "application/octet-stream", - src: asset - ? await this.client.mediaUrl(asset.id).catch(() => undefined) - : undefined, + src: asset ? assetSource(this.client.id, asset.id) : undefined, }; } @@ -395,7 +394,8 @@ export class CreationProjection { ? { name: doc.data.palette.name ?? undefined, sourceImageUri: doc.data.palette.sourceImage - ? await this.client.mediaUrl( + ? assetSource( + this.client.id, doc.data.palette.sourceImage.assetId, ) : undefined, @@ -431,7 +431,8 @@ export class CreationProjection { kind: "image" as const, width: layer.content.width, height: layer.content.height, - src: await this.client.mediaUrl( + src: assetSource( + this.client.id, layer.content.asset.assetId, ), } @@ -443,7 +444,7 @@ export class CreationProjection { case "image_crop": return { imageCrop: { - src: await this.client.mediaUrl(doc.data.source.assetId), + src: assetSource(this.client.id, doc.data.source.assetId), options: doc.data.options, width: doc.data.width, height: doc.data.height, @@ -565,6 +566,32 @@ export class CreationProjection { }; } + /** Media availability is a read result, so it updates a view without an edit. */ + withMediaAvailability(document: CanvasDocument): CanvasDocument { + const update = (nodes: CanvasNode[]) => { + let changed = false; + const next = nodes.map((node) => { + if ( + !node.data.backendAssetId || + !["image", "video", "audio"].includes(node.type) + ) + return node; + const assetState = this.client.mediaUnavailable(node.data.backendAssetId) + ? ("missing" as const) + : ("ready" as const); + if (node.data.assetState === assetState) return node; + changed = true; + return { ...node, data: { ...node.data, assetState } }; + }); + return changed ? next : nodes; + }; + const nodes = update(document.nodes); + const hiddenNodes = document.hiddenNodes && update(document.hiddenNodes); + return nodes === document.nodes && hiddenNodes === document.hiddenNodes + ? document + : { ...document, nodes, ...(hiddenNodes ? { hiddenNodes } : {}) }; + } + private rememberProjection( snapshot: ProjectSnapshot, document: CanvasDocument, @@ -617,8 +644,10 @@ export class CreationProjection { try { if (asset.kind === "text") node.data.text = await this.client.textContent(asset.id); - else node.data.src = await this.client.mediaUrl(asset.id); - node.data.assetState = "ready"; + else node.data.src = assetSource(snapshot.project.id, asset.id); + node.data.assetState = this.client.mediaUnavailable(asset.id) + ? "missing" + : "ready"; } catch { node.data.assetState = "missing"; } @@ -1405,7 +1434,14 @@ export class CreationProjection { ? node.data.text !== undefined && node.data.text !== old?.data.text && (!!node.data.text || !!old?.data.text) - : !!node.data.src && node.data.src !== old?.data.src; + : !!node.data.src && + node.data.src !== old?.data.src && + // The same saved asset can arrive through another of its URLs. + !( + item && + this.client.assetForSource(node.data.src)?.id === + currentAsset(basis, item)?.id + ); if (materialChanged) { const previous = item && node.type === "text" diff --git a/src/backend/imageSelections.ts b/src/backend/imageSelections.ts index e73aaa9a0..0d12407b6 100644 --- a/src/backend/imageSelections.ts +++ b/src/backend/imageSelections.ts @@ -3,6 +3,7 @@ import type { BackendAsset } from "./generation.ts"; import { requireActiveBackendProject } from "./projects.ts"; import { uploadAsset, type ToolSourceInput } from "./tools.ts"; import { tNow } from "../i18n/messages.ts"; +import { fetchMediaSource } from "./creationClient.ts"; export interface ImageSelectionBox { x: number; @@ -46,7 +47,7 @@ export async function previewImageSelection( signal.throwIfAborted(); let sourceAssetId = value.sourceAssetId; if (!sourceAssetId) { - const response = await fetch(value.source.src, { signal }); + const response = await fetchMediaSource(value.source.src, { signal }); if (!response.ok) throw new Error(tNow("errors.backend.imageRead")); sourceAssetId = await uploadAsset( diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index d9a80f845..a8df8835a 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -41,6 +41,7 @@ import { useProjectMentionAssets } from "./useProjectMentionAssets"; import { useReferenceUploads } from "./useReferenceUploads.tsx"; import { useT } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; +import { AssetMedia } from "./useAssetMedia.tsx"; function kindOf(asset: ChatAsset) { return asset.type.startsWith("image/") @@ -578,7 +579,7 @@ export function AssistantPanel({ title={item.error ?? item.title} > {item.thumbnail && !item.error ? ( - + ) : ( )} diff --git a/src/canvas/CanvasMediaPreview.tsx b/src/canvas/CanvasMediaPreview.tsx index 41cd1eaca..ce6838b62 100644 --- a/src/canvas/CanvasMediaPreview.tsx +++ b/src/canvas/CanvasMediaPreview.tsx @@ -10,6 +10,7 @@ import { type ReactNode, } from "react"; import { VideoControls } from "./CanvasVideoControls"; +import { useAssetMedia } from "./useAssetMedia.tsx"; /** Milliseconds a pointer must rest on a node before preview playback starts. */ const HOVER_PLAY_DELAY_MS = 300; @@ -77,6 +78,7 @@ export function CanvasVideoPreview({ ...props }: CanvasVideoPreviewProps) { const playback = useContext(Playback); + const resolved = useAssetMedia(props.src); const element = useRef(null); const wrapper = useRef(null); const [hovered, setHovered] = useState(false); @@ -255,6 +257,7 @@ export function CanvasVideoPreview({ >