diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index d2ca75cec..4f0fa0cab 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -26,6 +26,7 @@ from opendirector.domain.creation.commands import Command, CommandReceipt, Query as CreationQuery from opendirector.domain.creation.project import ProjectSnapshot, ViewState from opendirector.domain.projects import ProjectError +from opendirector.application.prompt_optimization import PromptOptimizationInput from opendirector.domain.timeline_errors import timeline_error, timeline_error_message from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.media.fonts import MAX_FONT_BYTES, inspect_font @@ -59,7 +60,26 @@ async def __call__(self, scope, receive, send): Path(self.path).unlink(missing_ok=True) -def creation_routes(projects: CreationProjects, generation=None): +async def preview_until_disconnect(request: Request, operation): + async def disconnected(): + # FastAPI has consumed the body. Read ASGI events directly so this + # also works through BaseHTTPMiddleware's receive stream. + while (await request.receive())['type'] != 'http.disconnect': + pass + + work = asyncio.create_task(operation) + disconnect = asyncio.create_task(disconnected()) + try: + done, _ = await asyncio.wait((work, disconnect), return_when=asyncio.FIRST_COMPLETED) + return await work if work in done else Response(status_code=499) + finally: + for task in (work, disconnect): + if not task.done(): + task.cancel() + await asyncio.gather(work, disconnect, return_exceptions=True) + + +def creation_routes(projects: CreationProjects, generation=None, prompt_optimization=None): router = APIRouter(prefix='/api/creation', tags=['Unified creation projects']) assets = CreationAssets(projects) canvas = CreationCanvas(projects) @@ -81,6 +101,13 @@ async def inspect_preview_font(request: Request, response: Response, response.headers['Cache-Control'] = 'no-store' return await run_in_threadpool(preview_font_coverage, bytes(value)) + if prompt_optimization is not None: + @router.post('/projects/{project_id}/items/{item_id}/optimize-prompt') + async def optimize_prompt(project_id: UUID, item_id: UUID, value: PromptOptimizationInput, request: Request): + return await preview_until_disconnect(request, prompt_optimization.rewrite( + project_id, item_id, value.prompt, value.inlineReferences, + value.preferredModelId, value.assistantModel)) + @router.get('/projects') def list_projects(): return projects.list_projects() diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 02dd82004..d0d786766 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -17,6 +17,17 @@ ENGLISH_BY_CODE = { "desktop_auth_required": "The desktop connection has expired. Reopen the application.", + 'prompt_optimization_empty': 'Enter a prompt to optimize.', + 'prompt_optimization_refs': 'Prompt references changed. Try again.', + 'prompt_optimization_node': 'Select an image or video node.', + 'prompt_optimization_model': 'Choose an available chat model in the Agent panel.', + 'prompt_optimization_vision': 'The selected chat model cannot use these visual references. Choose an Agent model with image or video input.', + 'prompt_optimization_cli': 'The selected Agent CLI could not optimize the prompt. Check its installation, login, and model.', + 'prompt_optimization_cli_unsupported': 'The selected Agent CLI does not support standalone prompt optimization. Switch the Agent or model in the Agent panel.', + 'prompt_optimization_media': 'The video reference duration is invalid.', + 'prompt_optimization_too_large': 'The references are too large for prompt optimization. Reduce their size or number and try again.', + 'prompt_optimization_result': 'The model did not return a usable prompt. Your original text was kept.', + 'prompt_optimization_provider': 'The text model could not optimize the prompt. Check its settings and try again. Your original text was kept.', 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 724b1806a..5434ca032 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -19,13 +19,14 @@ from opendirector.application.model_catalog import ModelCatalog from opendirector.application.model_availability import ModelAvailability from opendirector.application.preferences import Preferences +from opendirector.application.prompt_optimization import PromptOptimization from opendirector.application.tool_tasks import ToolTasks from opendirector.application.creation_tool_assets import CreationToolAssets from opendirector.infrastructure.local_projects import LocalProjects from opendirector.infrastructure.creation_projects import CreationProjects from opendirector.infrastructure.model_configs import ModelConfigs from opendirector.integrations.chat_completions import ChatCompletions -from opendirector_api.creation import creation_routes +from opendirector_api.creation import creation_routes, preview_until_disconnect from opendirector_api.agent import agent_routes from opendirector_api.library import library_routes from opendirector_api.voices import voice_routes @@ -37,6 +38,11 @@ ModelAvailability as ModelAvailabilityResponse) +async def _cli_prompt_rewrite(runtime, model, thinking, messages): + from opendirector.agent import prompt_rewrite + return await prompt_rewrite.rewrite(runtime, model, thinking, messages) + + def video_capabilities(value): return value.videoCapabilities.model_dump(exclude_none=True) if value.videoCapabilities else None @@ -78,7 +84,9 @@ async def lifespan(app): availability.probe.close() app = FastAPI(title="OpenDirector Local API", version="0.1.5", lifespan=lifespan) - app.include_router(creation_routes(creation_projects, creation_generation)) + app.include_router(creation_routes(creation_projects, creation_generation, + PromptOptimization(creation_projects, model_configs, chat_provider or ChatCompletions(), + cli_rewrite=_cli_prompt_rewrite))) app.include_router(agent_routes(creation_projects, creation_generation, model_configs, chat_provider, active=active_agents)) app.include_router(library_routes(creation_projects)) app.include_router(voice_routes(creation_generation.voices)) @@ -299,25 +307,8 @@ async def image_selection(project_id: UUID, value: ImageSelectionCreate, request x_opendirector_session: str = Header()): # Preview work has no durable task; disconnecting cancels the local # upstream request without disturbing accepted tool executions. - work = asyncio.create_task(service.selection_preview(str(project_id), value.model_dump(mode='json'), - identifier(x_opendirector_session))) - - async def disconnected(): - # The body has been decoded by FastAPI. Wait on the remaining - # ASGI events: is_disconnected() uses a cancelled scope that can - # miss disconnects through BaseHTTPMiddleware's receive stream. - while (await request.receive())['type'] != 'http.disconnect': - pass - - disconnect = asyncio.create_task(disconnected()) - try: - done, _ = await asyncio.wait((work, disconnect), return_when=asyncio.FIRST_COMPLETED) - return await work if work in done else Response(status_code=499) - finally: - for task in (work, disconnect): - if not task.done(): - task.cancel() - await asyncio.gather(work, disconnect, return_exceptions=True) + return await preview_until_disconnect(request, service.selection_preview( + str(project_id), value.model_dump(mode='json'), identifier(x_opendirector_session))) register_selection_route(creation_tools, '/api/creation/projects/{project_id}/image-selections') diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index e74d6338e..36fd15239 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -41,13 +41,13 @@ class ModelConfigInput(ModelConnection): url: str = Field(max_length=2048) modelId: str = Field(max_length=200) apiKey: SecretStr = SecretStr("") - inputModalities: list[AgentInputModality] | None = Field(default=None, min_length=1, max_length=2) + inputModalities: list[AgentInputModality] | None = Field(default=None, min_length=1, max_length=4) videoAdapter: VideoAdapter | None = None videoCapabilities: VideoCapabilities | None = None class ModelOptions(Model): - inputModalities: list[AgentInputModality] | None = Field(default=None, min_length=1, max_length=2) + inputModalities: list[AgentInputModality] | None = Field(default=None, min_length=1, max_length=4) videoAdapter: VideoAdapter | None = None videoCapabilities: VideoCapabilities | None = None diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 02d65b52f..2d9ba1933 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -26,6 +26,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Trigger:** Importing a project, referencing assets across conversation turns, or switching projects during a run. - **Lesson:** Commit `e8c29c9b` fixed provenance and creation-order problems in a canvas archive round trip; `44857448` fixed asset context across turns; `00d8899c` fixed Agent runs stopping when switching projects. These are different defects, but each shows that the current display alone cannot establish state and context. - **Check:** As relevant to the change, inspect persisted object identities, references, and execution inputs after conversion or recovery. Reopen the project or reconnect to the run when needed, and verify the actual result. +- **Preview follow-up:** [PR #465](https://github.com/ThinkFlowLab/OpenDirector/pull/465) initially opened the project for a prompt rewrite, which could contend with the browser's edit lease. A rewrite reads the saved snapshot and has no durable job to recover. Verify it can finish under a separate session and that a browser disconnect closes the server-side request. - **Async projection follow-up:** PR #193's structured-editor CI failure prompted a real-browser delayed-read regression. An older background projection could finish after an acknowledged editor save and restore an obsolete CAS basis, making the next save/publication fail. Recheck the editor transaction and captured snapshot at completion before installing either changed or apparently identical content. Keep publication versions fixed, test the actual save/retry/provenance path with a deterministic interleaving, and retain the original CI failure rather than treating a longer timeout or a rerun as its explanation. - **Media representation follow-up:** [Issue #282](https://github.com/ThinkFlowLab/OpenDirector/issues/282) exposed copy/export paths that read displayed pixels and archive imports that displayed unsupported original bytes. A browser preview and an original asset need distinct read paths while retaining the same asset identity. Verify original bytes through download, fresh publication, cross-project paste fallback and archive round trips, including the first display after import. [PR #287 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5857373679) also exposed missing MIME-extension mappings and a fallback that could name preview PNG bytes as HEIC. Carry the expected original type into readers, reject a missing original, and check timeline/FCPXML packages as well as canvas archives. @@ -50,6 +51,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Check:** Dismiss `opendirector.modelSetup.v1` before the first navigation, and open a project the script itself created when the server is already populated. Point assistant-fixture scripts at their own web URL, and keep `/src` or `/tests` imports out of the production lane. `npm run check:browser-manifest` checks the dismissal, the fixture URL, and those imports. - **Fixture-mode follow-up:** [PR #266 review](https://github.com/ThinkFlowLab/OpenDirector/pull/266#issuecomment-6906025718) found browser workflows passing with local HTTP-generation fixtures but failing before business assertions under nightly's generic provider. Declare the required fixture modes in the manifest and check the running API and web proxy before executing each fixture lane. Reproduce the workflow's service commands and script grouping; separately correct local startup commands do not validate CI wiring. - **Save-observation follow-up:** [Issue #300](https://github.com/ThinkFlowLab/OpenDirector/issues/300) reproduced a stale saved label satisfying a browser wait before the edited text binding was committed. `asset.writeText` had succeeded, but the `creation.batch` containing `canvas.materialize` was still in flight; its later applied receipt installed the binding and the content was `AB`. Wait for the specific persisted binding, settings or position before asserting a save, retain the content check, and bound and release test gates even on failure. A visible saved label alone does not identify which edit was acknowledged. +- **Assistant completion follow-up:** [PR #465's browser run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45526547494/job/138913562926) read a saved reply while the Agent still held its write lease. The assistant panel test must wait for both the reply's final status and removal of the active turn ID. Delaying lease release reproduced the failure on the upstream baseline. ## Browser clock pauses must precede short-lived observations diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 2dcd68807..0e9cc762e 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -89,6 +89,8 @@ The canvas saves automatically. Before closing it or switching projects, check t 3. Connect a source node that has content to the target node, or type `@` in the input field to select reference assets. 4. Check the references and parameters, then generate. When the task finishes, view its result in the node or **Generation history**. +In an image or video node, enter a draft and click the **Optimize prompt** wand below the editor. Optimization follows the model selected in the Agent panel, including the CLI default for Codex and Claude Code. The built-in skill applies to H3 and Seedance 2.0 video models. In model settings, enable the input types supported by the model's API. OpenDirector sends full-length videos to models with video input and samples frames for models with image input only. Audio files and video soundtracks are sent only when the model accepts audio. Press Ctrl+Z (Command+Z on Mac) to undo the replacement. Edit the text to optimize it again. Optimizing a prompt does not submit a generation job. + For GPT Image models, open **Generation settings** and choose **Quality** from **Auto**, **Low**, **Medium**, or **High**. **Auto** keeps the service default. The choice is saved with the project and frozen when a task is submitted. Changing it later affects subsequent tasks. Other image services do not show this option. Standalone image tools retain their service default. The Agent can set the same value through `parameters.quality` in the image generation spec. After typing `@`, use the up and down arrow keys to select an asset, the left and right arrow keys to switch categories, `Enter` to insert, and `Esc` to close the picker. References are inserted into the text as single units. Removing the last reference to a source also removes its corresponding reference connection. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 7d32c5a06..fcb1992a8 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -89,6 +89,8 @@ vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可 3. 将有内容的来源节点连接到目标节点,或在输入框中输入 `@` 选择参考素材。 4. 检查参考和参数,点击生成。完成后在节点或“生成历史”中查看结果。 +在图片或视频节点中输入草稿,点输入框下方的「提示词优化」魔法棒。优化沿用右侧 Agent 当前选择的模型,Codex 和 Claude Code 也可使用 CLI 默认模型。H3 和 Seedance 2.0 视频会使用内置技能。在模型设置的「输入能力」里按接口实际支持的类型勾选。支持视频输入时发送全长视频,只支持图片输入时才从视频抽帧。只有支持音频输入的模型才会收到音频素材,全长视频也只在这种情况下保留音轨。结果替换草稿后可按 Ctrl+Z(Mac 上按 ⌘Z)撤销。修改文字后可再次优化。优化只修改提示词,不提交生成任务。 + GPT Image 模型可在“生成参数”中选择“质量”,取值为“自动、低、中、高”。“自动”沿用服务默认行为。选择会保存在项目中,并在任务提交时固定;之后修改只影响后续任务。其他图片服务不显示此选项,独立图片工具仍使用服务默认值。Agent 可通过图片生成规格中的 `parameters.quality` 设置同一参数。 输入 `@` 后可用上下方向键选择素材、左右方向键切换分类,按 `Enter` 插入,按 `Esc` 关闭选择。引用以整体形式插入正文;删除同一来源的最后一次引用会移除相应参考连线。 diff --git a/packages/agent/skills/h3-official-prompt-optimization/SKILL.md b/packages/agent/skills/h3-official-prompt-optimization/SKILL.md new file mode 100644 index 000000000..2dbbecb39 --- /dev/null +++ b/packages/agent/skills/h3-official-prompt-optimization/SKILL.md @@ -0,0 +1,152 @@ +--- +name: h3-official-prompt-optimization +description: Rewrite a MiniMax H3 video draft into the model's official prompt structure (instruction line plus integrated_multimodal_description, overall_soundscape and non_diegetic_music) while preserving OpenDirector's inline reference markers. Use to compare output against h3-prompt-optimization. +--- + +# H3 official-structure prompt optimization + +Rewrite the draft into the structure MiniMax documents for H3 generation modes +(T2VA, I2VA, FL2VA, L2VA, Ref2VA). Keep the draft's own language for everything +descriptive; the structure and its tokens are English. Return only the rewritten +prompt. + +## Hard invariants + +- Keep every `[[OD_REF_n]]` marker exactly once and in its existing order. These + markers are the editor's inline references; never delete them, renumber them, + or move them into a different shot. +- Write the description text in the draft's language. A Chinese draft stays + Chinese; do not translate it into English. +- Never translate the structural tokens. Field names, `[Shot N]`, the cue tags + ``, ``, ``, ``, `