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/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..a93ed0c98 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 @@ -762,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. @@ -844,6 +926,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/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/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/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({ >