diff --git a/.github/workflows/dsh-plugin.yml b/.github/workflows/dsh-plugin.yml index 08387570b..0b0723411 100644 --- a/.github/workflows/dsh-plugin.yml +++ b/.github/workflows/dsh-plugin.yml @@ -18,7 +18,12 @@ permissions: jobs: tests: - runs-on: ubuntu-22.04 + name: Plugin checks (${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, windows-latest, macos-latest] timeout-minutes: 15 steps: - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -33,3 +38,77 @@ jobs: - name: DSH plugin tests working-directory: plugins/deepseek-harness run: npm test + - name: Check the installable DSH bundle + shell: bash + working-directory: plugins/deepseek-harness + run: | + npm pack --json > package-check.json + node --input-type=module <<'NODE' + import assert from 'node:assert/strict' + import { execFileSync } from 'node:child_process' + import { readFileSync, writeFileSync, unlinkSync } from 'node:fs' + import { createHash } from 'node:crypto' + + const run = (command, args) => execFileSync(command, args, { encoding: 'utf8' }) + const [{ filename }] = JSON.parse(readFileSync('package-check.json', 'utf8')) + try { + const entries = new Set(run('tar', ['-tzf', filename]).trim().split(/\r?\n/)) + const manifest = JSON.parse(run('tar', ['-xOzf', filename, 'package/package.json'])) + for (const entry of [manifest.dsh?.bundle?.patch, manifest.exports?.['./client'], manifest.icon, + ...['en', 'zh'].map(language => manifest.exports?.['./locale/*.json']?.replace('*', language))]) { + assert.ok(entry?.startsWith('./') && entries.has('package/' + entry.slice(2)), entry) + } + assert.ok(manifest.version && manifest.engines?.dsh) + const sha256 = createHash('sha256').update(readFileSync(filename)).digest('hex') + writeFileSync(filename + '.sha256', sha256 + ' ' + filename + '\n') + if (process.env.RUNNER_OS === 'Linux') { + execFileSync(process.execPath, ['scripts/prepare-release.mjs', '--tarball', filename, + '--output', process.env.RUNNER_TEMP + '/opendirector-dsh-release'], { stdio: 'inherit' }) + } + } finally { + unlinkSync('package-check.json') + } + NODE + - name: Save the installable plugin + if: matrix.os == 'ubuntu-22.04' + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: opendirector-dsh-plugin-${{ github.sha }} + path: ${{ runner.temp }}/opendirector-dsh-release/* + if-no-files-found: error + retention-days: 7 + + latest-tools: + name: Plugin compatibility + runs-on: ubuntu-22.04 + timeout-minutes: 15 + env: + DSH_VERSION: 0.2.2-rc.5 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: .nvmrc + cache: npm + cache-dependency-path: plugins/deepseek-harness/package-lock.json + - name: Install plugin dependencies + working-directory: plugins/deepseek-harness + run: npm ci + - name: Install the DSH compatibility checker and tool runtime + working-directory: plugins/deepseek-harness + run: >- + npm install --ignore-scripts --no-save --package-lock=false + "@deepseek-ai/dsh-app-boot@$DSH_VERSION" + "@deepseek-ai/dsh-tools@$DSH_VERSION" + "@deepseek-ai/dsh-tool-executor-native@$DSH_VERSION" + "@deepseek-ai/dsh-system-prompt@$DSH_VERSION" + - name: Check plugin loading and execution + working-directory: plugins/deepseek-harness + run: | + node --input-type=module <<'JS' + import assert from 'node:assert/strict' + import { evaluatePluginCompatibility } from '@deepseek-ai/dsh-app-boot' + import manifest from './package.json' with { type: 'json' } + assert.equal(evaluatePluginCompatibility(manifest, {}, process.env.DSH_VERSION), undefined) + JS + npm test diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 7672a63ca..afa369c27 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -19,6 +19,12 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **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. - **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. +## Cancellation can race with a worker checkpoint + +- **Trigger:** A worker reads a running job, then cancellation advances its revision before the worker saves the next phase. +- **Lesson:** Commit 3635393 reconciles only the checkpoint on revision conflict. The old path converted this race into a provider failure even though cancellation was saved. A stale checkpoint could also lose a saved remote task identity. +- **Check:** Inject cancellation between the snapshot read and commit. Preserve stop intent, terminal cancellation and the accepted remote identity; do not repeat provider submission. Keep unrelated rejections as errors. The deterministic regressions in [test_creation_generation_service.py](../../tests/test_creation_generation_service.py) cover the interleaving, no provider call, terminal states and remote identity preservation. + ## Baseline failures still need tracking - **Trigger:** A relevant test fails and comparison shows that it also fails on the baseline. diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index c94b6d236..7b97f4cc8 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -38,6 +38,9 @@ _INPUTS = ContextVar('creation_generation_inputs', default=None) # Connection facts a job freezes for a helper model; credentials stay in the model settings. SNAPSHOT_KEYS = ('kind', 'modelId', 'url', 'protocol', 'connectionType') +# A checkpoint can lose a race with cancellation or another state write. Only +# the state checkpoint is repeated, never a provider submission. +CHECKPOINT_ATTEMPTS = 8 def version(kind, obj): @@ -416,28 +419,61 @@ def control(before): return receipt def checkpoint(self, project_id, task, pinned): - before = self.projects.snapshot(project_id) - job = next(j for j in before.jobs if str(j.id) == task['id']) - if job.status == 'succeeded': - return - changes = {key: task[key] for key in ('status', 'phase', 'recovery', 'resumeAllowed', 'externalTaskId', 'errorDetails', 'technicalCheck') if key in task} - changes['adopted'] = task.get('adopted', job.adopted) - if changes['status'] == 'cancelled' and job.cancelRequested: - changes['remoteCancellation'] = ('unknown' if task.get('errorDetails') else 'requested') if task.get('externalTaskId') else 'not_requested' - if changes['recovery'] == 'submit': - changes['resumeAllowed'] = False - if job.cancelRequested and (task.get('errorDetails') or {}).get('providerStatus') == 'cancelled': - changes.update(status='cancelled', remoteCancellation='confirmed', resumeAllowed=False, recovery='retry') - updated = Job.model_validate({**job.model_dump(), **changes, 'revision': job.revision + 1}) - if updated.model_copy(update={'revision': job.revision}) == job: - return - command = parse_command(dict(commandId=uuid4(), projectId=project_id, type='job.checkpoint', - expectedVersions=[version('job', job)], payload=dict(job=updated))) - def apply(current): - return current.model_copy(update={'jobs': tuple(updated if j.id == job.id else j for j in current.jobs)}) - receipt = self.projects.commit(command, apply, source='background') - if receipt.status == 'rejected': - raise ProjectError('任务状态发生并发修改,请重新读取原任务。', 409) + # Cancellation and another worker can commit between the snapshot read + # and this write. A revision conflict is a state race, not an execution + # failure: reread authoritative state and redo only this checkpoint, + # with bounded attempts. Provider calls are never repeated here. + for attempt in range(CHECKPOINT_ATTEMPTS): + before = self.projects.snapshot(project_id) + job = next(j for j in before.jobs if str(j.id) == task['id']) + if job.status == 'succeeded': + return + changes = {key: task[key] for key in ('status', 'phase', 'recovery', 'resumeAllowed', 'externalTaskId', 'errorDetails', 'technicalCheck') if key in task} + changes['adopted'] = task.get('adopted', job.adopted) + # An accepted remote identity belongs to this job even if the + # checkpoint was prepared before it was recorded. + if job.externalTaskId: + changes['externalTaskId'] = job.externalTaskId + if job.cancelRequested: + # The stop intent is part of the authoritative state. Preserve + # it even when this save was planned before the cancellation. + changes['cancelRequested'] = True + if changes['status'] == 'cancelled' and job.cancelRequested: + changes['remoteCancellation'] = ('unknown' if task.get('errorDetails') else 'requested') if task.get('externalTaskId') else 'not_requested' + if changes['recovery'] == 'submit': + changes['resumeAllowed'] = False + if job.cancelRequested and (task.get('errorDetails') or {}).get('providerStatus') == 'cancelled': + changes.update(status='cancelled', remoteCancellation='confirmed', resumeAllowed=False, recovery='retry') + if job.status == 'cancelled': + # Cancellation is terminal. A stale worker may still carry + # running, interrupted or failed facts; keep the committed + # cancellation and only fill in an execution identity that was + # not known when cancellation was recorded. + confirmed = (task.get('errorDetails') or {}).get('providerStatus') == 'cancelled' + changes['status'] = 'cancelled' + if not confirmed: + changes.update(phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed, + remoteCancellation=job.remoteCancellation, errorDetails=job.errorDetails, + technicalCheck=job.technicalCheck, adopted=job.adopted) + if job.cancelRequested and not job.externalTaskId and task.get('externalTaskId'): + changes['externalTaskId'] = task['externalTaskId'] + if changes.get('remoteCancellation', job.remoteCancellation) == 'not_requested': + changes['remoteCancellation'] = 'unknown' + updated = Job.model_validate({**job.model_dump(), **changes, 'revision': job.revision + 1}) + if updated.model_copy(update={'revision': job.revision}) == job: + return + command = parse_command(dict(commandId=uuid4(), projectId=project_id, type='job.checkpoint', + expectedVersions=[version('job', job)], payload=dict(job=updated))) + def apply(current): + return current.model_copy(update={'jobs': tuple(updated if j.id == job.id else j for j in current.jobs)}) + receipt = self.projects.commit(command, apply, source='background') + if receipt.status != 'rejected': + return + # Only a concurrent object-version change can be reconciled by + # rereading state. Validation or storage rejection remains a real + # failure instead of being retried with a stale execution record. + if not receipt.issues or any(issue.code != 'revision_conflict' for issue in receipt.issues) or attempt == CHECKPOINT_ATTEMPTS - 1: + raise ProjectError('任务状态发生并发修改,请重新读取原任务。', 409) def _result_asset(self, task, directory): job = self.get_job(task['projectId'], task['id']) diff --git a/plugins/deepseek-harness/README.md b/plugins/deepseek-harness/README.md index 81476c372..ed28dda39 100644 --- a/plugins/deepseek-harness/README.md +++ b/plugins/deepseek-harness/README.md @@ -6,7 +6,7 @@ Create media from a DSH conversation, follow generation progress, and open the s ## Install and connect -Use DSH **0.2.2-rc.1** with Node.js **24.9.0 or newer** and `pnpm` on `PATH`. Start OpenDirector using the [installation guide](../../docs/guides/installation.md). From this plugin directory, package it and create a Web profile before adding the bundle: +Start OpenDirector using the [installation guide](https://github.com/ThinkFlowLab/OpenDirector/blob/main/docs/guides/installation.md). The plugin supports DSH **0.2.2-rc.1, rc.2, rc.3 and rc.5**. In Desktop, open **Plugins** and add the local `.tgz` file. To build the package and use it in a Web profile, run these commands from the plugin directory with Node.js **24.9.0 or newer** and `pnpm` on your path. ```sh npm pack @@ -17,7 +17,7 @@ dsh --profile studio Open the full DSH Web address printed at startup, then choose a workspace and a configured DSH conversation model. Initializing from `web` supplies the chat interface. For an existing Web profile, just run the `plugin ... add` command with its name. Tarball installation, Web chat, and the canvas handoff were verified with DSH 0.2.2-rc.1. -The default OpenDirector connection is `http://127.0.0.1:8000`, so a normal local installation needs no extra configuration. The plugin row is named `opendirector`. DSH calls its eight native tools as part of its own agent loop. +The default OpenDirector connection is `http://127.0.0.1:8000`, so a normal local installation needs no extra configuration. The plugin row is named `opendirector`. DSH calls its native tools as part of its own agent loop. For development, install this checkout's dependencies before linking it into an existing profile: @@ -28,26 +28,125 @@ dsh plugin --profile studio add /absolute/path/to/OpenDirector/plugins/deepseek- The bundle ships ready-to-run JavaScript and needs no build. Tarball installation installs its dependencies; a linked checkout keeps its own `node_modules`. Neither route requires an npm release or a marketplace listing. +## Find and install the plugin + +The package name is `@opendirector/dsh-plugin`. In DSH’s plugin manager it appears as **OpenDirector**, with a localized description and icon. This checkout provides source and an installable `.tgz`; a registry package or a plugin-index listing is a separate publication step. Until a package is published, install from a local path or a tarball rather than entering the bare package name. Once a PR’s **DSH plugin checks** run succeeds, its Linux job uploads an installable bundle and SHA-256 file under **Artifacts**, retained for seven days. + +In DSH rc.3, **Plugins → Experimental plugins → Custom plugin indexes** adds a **Discover** tab. It lists the index sources the user adds; installing a local plugin does not list it for everyone. An index entry can point to a published npm version or an exact Git commit and package directory. A release tarball remains a direct installation option. [DSH custom plugin indexes](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.2-rc.3/packages/experimental/plugin-market-bundle/README.md) + +Use the same installation source to update a local tarball or linked checkout. Registry-installed bundles can use DSH’s compatible-version update controls after publication; the plugin leaves installation and updates to DSH. + + +### Desktop installation + +For Desktop, open **Plugins → Add plugin**, enter a local tarball such as `file:E:/Downloads/opendirector-dsh-plugin-0.1.0.tgz`, and enable OpenDirector. For the default address, run OpenDirector on the computer running DSH. + +Beyond npm and an index, a versioned GitHub Release can carry the tarball and checksum as a stable download. Workflow artifacts are useful for trying a PR; release assets are better for a documented version. Link the setup guide and a short generation-to-adoption demo from the project README and any community listing. + +### Check the connection + +Open **OpenDirector → Connection check** beside the message box. The dialog shows the configured API and canvas addresses, project count, and model connections for images, references, image-to-video, continuation and voiceover. It checks once when opened; use **Check again** after changing the service. + +An empty model catalog links you to OpenDirector to configure one. Connection errors explain whether to check the address, start the service, or fix access. **Copy diagnostics** copies the plugin version, addresses, status and counts; it omits project names, model credentials and provider responses. Listed models have not been tested by a generation. This check makes no model calls. + +## Platform coverage + +The interactive workflow has been verified in DSH Web with the host running in WSL Ubuntu. Native Windows checks cover plugin loading, tool execution and HTTP routes. The plugin workflow includes Linux, Windows and macOS jobs. DSH Desktop still needs an end-to-end installation and media check. + +## Continue with fewer repeated choices + +Open **Resume project** to see the project you have been using in this chat. You can switch projects in the picker. The plugin remembers the list view and generation settings on this device for each OpenDirector service. New forms reuse models that are still available and keep the last image size or video duration. For continuation, choose the connection that generated the source clip. An unsubmitted draft takes priority. A fresh creation starts with one candidate; a saved draft keeps the count you chose. Clear these preferences under **Connection check → Diagnostic text → Forget recent settings**. + +Image cards keep **Adopt**, **Edit** and **More actions** in view. Open **More actions → Animate** to use the image as a first frame. On a video card, pause on a shot you like and choose **More actions → Save current frame as PNG**. The frame uses the original video dimensions. Clips from models that support continuation also offer **Continue**. + +Click a picture to see its original dimensions. Use the arrow keys to browse the images on the current page and **Adopt this image** to keep the one on screen. You can also edit that image or send its reference to the chat draft. While creating, **Edit**, **Animate** and **Continue** open the next step in the same window. **Back one step** returns to your earlier candidates and draft. + +Each node's results show V1, V2 and so on in registration order, unchanged by search or pagination. Image cards show the saved file size in pixels. When it differs from the requested dimensions, the card shows both. Cards also show the job time and an identified source version when available. An edit creates a separate node, so its numbering starts at V1 and can point back to the source node's version. + +If a project list or model catalog cannot be loaded, reload it in the same dialog. After adding a model in OpenDirector, reload an empty catalog to continue. Your description, action names and chosen reference stay in place; reloading only reads data. + +If a preview fails to load, choose **Reload preview** on the same card. The original-image viewer also offers a reload button. + +## Examples and a short demo + +Pick an example below the description to fill an empty prompt. If you have already written something, you can read the example before choosing **Replace current description**. You can edit the text before generating. + +Action packs offer **Example actions** for a desktop companion or a set of expressions. **Replace action list** fills three editable actions while keeping the reference image, shared description and model. + +See the [workflow demo and example scenarios](https://github.com/ThinkFlowLab/OpenDirector/blob/main/plugins/deepseek-harness/docs/showcase.md). To prepare a versioned tarball, checksum, Release notes and a custom plugin index together, follow the [release guide](https://github.com/ThinkFlowLab/OpenDirector/blob/main/plugins/deepseek-harness/RELEASING.md). + ## Try a complete workflow -In OpenDirector, configure an image model under **Settings → Model connections** first. The [user guide](../../docs/guides/user-guide.md) explains model connections. The example uses that configured service. +In OpenDirector, configure an image model under **Settings → Model connections** first. The [user guide](https://github.com/ThinkFlowLab/OpenDirector/blob/main/docs/guides/user-guide.md) explains model connections. The example uses that configured service. + +In DSH Web, choose **OpenDirector → Create media** next to the composer. Select an existing project or name a new one. Choose **Image**, **Video** or **Voiceover**. For a video, pick **Animate an image** or **Continue a clip**, then select the source from that project. If you already wrote a shot description in the composer, choose **Use chat draft** to copy it into the form. Choose a model, review the description, and click **Generate one candidate**. + +Choose **Number of candidates** (1–4) to create a group in one action. Each candidate is a separate generation task on the same node. The group shows saved progress and completed media together; select two images to compare, then adopt the version you prefer. Groups also work with voiceover and video forms. A failed member keeps its error while successful siblings remain available. + +When a group submission is unconfirmed, check its original receipts. **Continue the original group** explicitly submits any remaining members with their original operation IDs. It keeps accepted jobs and stops if the source node’s settings have changed. Saved task history reopens the whole group after reloading DSH. + +After a submission is accepted, **Generation settings** folds away so the candidates stay in view. Expand it to inspect the submitted settings. The plugin follows DSH’s light and dark themes, with distinct generation, adoption and current-result controls. -In DSH Web, choose **Create media** in the composer and describe what you want: +Unsubmitted input stays in the current browser tab. Close the dialog or reload DSH, then return to the same creation or edit action to continue. This includes the chosen model, image size and ordered references. Use **Clear draft** to start over. After submitting, you can close the form and keep chatting. Click the task status beside **OpenDirector** to reopen your result. If several tasks are running, pick one by its description. Older jobs are under **Resume project → Tasks**. + +If a submission is unconfirmed, reopen the action or choose **Resume project → Submissions to check** after closing or reloading DSH. Checking uses the original submission ID and opens the accepted task without generating again; it does not require the model catalog. **Start a separate creation** opens a new form and keeps the original submission available to check. **Hide reminder** only removes the local reminder. Recovery information stays in the current browser tab. If browser storage is unavailable, keep the page open and check before reloading. + +If you choose an image size and then change models, the form keeps your choice when the new model supports it. If that size is unavailable, choose a different size or model before generating. + +In **Resume project**, search descriptions, canvas node names, models or copied IDs across the whole project. Search checks the full recorded description, including text beyond the card preview. Results, tasks and reference choices show one page at a time; use Previous page and Next page to browse without keeping every card mounted. Selected comparison images and references stay selected when you change pages. Combine it with media and adoption filters, or filter tasks by their current status. **Clear search and filters** returns to the full list. + +Choose **Compare images** in **Resume project**, select two saved images, and open the comparison. Selections can come from different filtered pages of the same project. Original images load only when you open the comparison. You can inspect them at a larger size and adopt either result; each node keeps its own current-result selection. + +Automatic task checks pause while the page is hidden or offline. Returning to the page or reconnecting checks the same task. This does not stop the generation job. Media players show a buffering message while waiting for content. + +To change a saved image or voiceover, choose **Reuse settings** on its result card. The form starts from that version’s recorded prompt and parameters. Images can keep their original size or use another listed size. The model, voice identity and references stay fixed; other saved parameters are retained. Generation creates a new node in the same project, ready to review before adoption. Structured prompt documents and expanded subject references can be adjusted on the canvas. + +Choose **Generate another candidate** to run the same canvas node again with its saved settings. Compare the results in the dialog and choose **Adopt** on the one you want to use. + +Cards show the file's actual dimensions and duration when available. Click an image to view the original in DSH, then switch between **Actual size** and **Fit to window**. + +After a run in the creation form finishes, choose **Adjust settings for another version** to keep its source, prompt and settings. Change the description and submit when ready. The previous results stay in the form. After two single-image runs, **Compare versions** shows them side by side. + +If you lose the connection, use **Check submission** or **Check progress** to look up the same operation. If the provider confirms a quota or rate limit failure, fix the issue and choose **Retry generation** to use the same node. When a canvas holds the project open, save and close it, then try again in the same dialog. + +### Pick up an earlier edit in chat + +Try “Show the two versions of the keeper in Night Watch. Which one was used for the video?” The images appear in the order you asked for. If an image was used as the first frame of a saved video, its card names the clip. Ask to play that clip to get a player in the conversation. + +Choose **Discuss edit** on the original portrait and tell the chat model what you want to keep: “I like this coastline. How would you add the red scarf without changing the framing?” The proposal stays attached to that portrait. Choose **Review edit** to adjust the wording and generation settings. Clicking **Generate one candidate** submits the image request. + +In **Resume project**, choose **Reference in chat** on a result to add that exact version to your message. For an image or clip, **More actions → Plan the next shot** also adds a question about framing and motion. Add your own direction and send when ready. + +To start a new project from chat, try this: > Create a project called “Moonlit studio”. Use one of my configured image models to make a cinematic moonlit room. Show me the candidate before adopting it. 1. DSH uses `opendirector_projects` and `opendirector_project` to create the project and find its image model. It saves a node with `opendirector_create_generation`, submits it with `opendirector_submit`, then checks the job ID with `opendirector_job`. 2. Once the job succeeds, inspect the saved candidate right in DSH Web. You can also open the project link and find the candidate under **Generation history**. Close the canvas tab before asking DSH to write to the project. -3. Choose **Adopt** on the candidate card. The action prepares a draft in the same DSH conversation. Review and send it. DSH reads the current revisions and calls `opendirector_adopt_result`. +3. Choose **Adopt** on the candidate card. The plugin reads the current revisions, selects the result, and shows a link to the canvas. 4. Follow the `/ai-canvas/` link back to the same project. Double-click the image node's title, rename it, and reopen the project to check that the new name and the selected image are still there. -To revise an image, choose **Edit** on its result card. Describe the change on the card and choose **Send request**. Use a model that accepts reference images. DSH uses `sourceResultId` to pin the exact saved image, then creates a separate generation node in the same project. The result card shows the source and candidate together. Both remain available on the canvas. Card actions preserve your current draft and attachments. +To revise an image, choose **Edit** on its result card. Pick a model that accepts reference images, describe the change, and click **Generate one candidate**. The plugin pins the saved image and creates a separate generation node in the same project. You can compare the source and the new result before adopting it. These forms preserve your chat draft and submit directly to OpenDirector. + +If the model accepts multiple references, choose **Add reference images** to pick other saved images from the same project. The source stays first. Use the arrows to change the order of the other references. + +If the submission reply is lost, choose **Check submission** to look up the original operation. For a job that failed after submission, open the canvas to inspect the saved generation settings and the failure details. + +### Pick up an earlier project + +Choose **OpenDirector → Resume project**, then select an OpenDirector project. Filter the saved results by media type or current selection, sort by when they were saved, and choose **Load more** for the next page. If a canvas is open for editing, save and close it before trying to adopt a result. If the connection drops during adoption, choose **Check adoption** to look up the original write. + +Choose **Tasks** to find running, completed, and failed generations, including work submitted before you refreshed DSH. Filter by media type or change the order to find an earlier task. **View progress** opens that saved task. Completed candidates can be previewed and adopted there. A confirmed retryable failure offers **Retry generation** on the existing node. Closing the dialog keeps the task available in this list. + +Right-click a result card or choose **More actions** on it. The menu shows the actions for that media type, including downloading the original file. Use the arrow keys to move between actions, and press Escape to return to the card. -### Continue a video +In task progress, choose **Request stop** to ask OpenDirector to stop the job. Closing the dialog leaves the job running. If the response is lost, **Check stop request** reads the original operation. The dialog distinguishes stopped local processing from confirmed provider cancellation. -With a configured MiniMax-H3 vLLM-Omni connection, choose **Animate** on an image result, describe the shot on the card, and send the request. Once the clip is ready, play it in the result card. Choose **Continue** and describe what should happen next. DSH shows the source clip and the continuation together before you decide whether to adopt the new candidate. +### Animate an image or continue a clip -The first job uses `videoMode: first_frame` with the saved image's `sourceResultId`. The next uses `videoMode: continuation` with the saved clip's result ID. The configured backend must still hold that clip's continuation cache. If the cache has expired, DSH shows the job's recovery guidance. Regenerate the source on that backend or choose first-frame or reference mode. Both the existing clip and the failed attempt's inputs stay in the project. +Choose **Animate** on a saved image. The form shows that image as the first frame and lists the video models that support it. Pick a model, choose a duration from its available options, and describe the motion. Generate one candidate and play it in DSH before adopting it. + +For a clip generated by a compatible MiniMax-H3 vLLM-Omni connection, choose **Continue**. Select the same connection, choose the duration of the next shot, and describe what happens next. Play the source and candidate in the same form. The service uses its cached state for that clip. If the cache has expired, generate the source clip again on that connection. The clip and the continuation settings are saved in the project. ## Configuration @@ -94,6 +193,7 @@ Accepted OpenDirector jobs keep running when the DSH plugin is disabled or an ag | --- | --- | --- | | `opendirector_projects` | “List my projects” or “Create a project called Moonlit studio.” | Project list or create receipt. | | `opendirector_project` | “Show Moonlit studio and its configured image models.” | Project, model catalog, current object revisions, and project link. | +| `opendirector_results` | “Show both versions, then help me draft an edit for the first one.” | Saved result cards, first-frame links, or a prompt for review. | | `opendirector_create_generation` | “Set up an image node for a moonlit room. Wait before generating.” | Editable node and its saved references. | | `opendirector_submit` | “Run that image generation.” | Accepted job ID with `candidate_only` selection policy. | | `opendirector_job` | “Check the job and show me the saved candidates.” | Job state, candidates, and selection state. | @@ -119,7 +219,17 @@ Cancellation is an explicit `opendirector_cancel` action. Aborting a tool reques Tools return canonical JSON for programmatic use. Submission, progress, candidate selection, and cancellation render short localized summaries with the project name, useful IDs, next step, and project link. A full project/model read is available when the agent needs it. -DSH Web shows saved images and videos on result cards in the current interface language. Editing and continuation can be sent from the card. **Adopt** prepares a draft for you to review before sending. Once it succeeds, the receipt has a direct link to the editable canvas. +DSH Web shows saved images, videos, and audio on result cards in the current interface language. Open the creation forms directly from a card. **Adopt** selects the result and links back to the canvas. + +## Character action packs + +From a saved image, open **More actions → Make an action pack**. Name 1–6 actions, add a shared character description, and choose an image model accepting references or a first-frame video model. **Create and generate** sends one task per action. Each action keeps its own candidates and adoption; generating another version leaves the current choice in place. Use **Adjust action** to change one action’s description and generate a new version while keeping other actions and existing choices. + +Choose **OpenDirector → Action packs** to reopen a saved pack. Pick one version for every action, then **Download action pack**. The ZIP contains numbered media files and a manifest with the selected results, descriptions, model IDs and content fingerprints. Downloads stream directly from project assets, up to 128 MB, without making a second local copy. + +The reference image is pinned for every action. Character consistency, motion quality, transparency and loop timing depend on the model and the prompt; inspect the actual output before using it in a desktop pet. The pack exports individual images or clips, rather than an installed pet or a sprite-sheet runtime. + +In conversation, use `opendirector_action_pack` to list, read, prepare, generate or check a pack. Preparing saves its nodes without calling a model. Generating requires explicit action item IDs and keeps the results as candidates. For a lost response, check the original operation ID and continue the same submission. Use `revise` with `itemId`, `prompt` and `expectedSpecRevision` to save one action’s description without generating. Selection uses the existing adoption tool. Closing the dialog leaves accepted jobs running. ## Development checks @@ -145,4 +255,4 @@ node test/creation.integration.mjs This checks project creation, a saved PNG candidate, result selection and replay, edit-session conflicts, and an accepted job completing while the plugin is disabled. It requires the fixture's health marker before writing. `OPENDIRECTOR_FIXTURE_URL` can select another fixture port; the test uses generated fixture images rather than a model service. -The package pins its DSH compatibility to `0.2.2-rc.1`; DSH is in developer preview, so check compatibility before upgrading the host. OpenDirector’s own installation requirements are maintained in its installation guide. +The rc.5 Windows Desktop runtime installed the tarball in a fresh profile. In its Web UI we generated a fixture image, previewed it and adopted it. The Desktop window still needs a hands-on check. Earlier checks covered Web installation on rc.1 and image creation, action revisions, candidate selection, reload recovery, video playback and ZIP export on rc.3. For rc.2 we checked the published tool interfaces. diff --git a/plugins/deepseek-harness/README.zh-CN.md b/plugins/deepseek-harness/README.zh-CN.md index feda27142..6a93691ef 100644 --- a/plugins/deepseek-harness/README.zh-CN.md +++ b/plugins/deepseek-harness/README.zh-CN.md @@ -6,7 +6,7 @@ ## 安装并连接 -使用 **DSH 0.2.2-rc.1**、**Node.js 24.9.0 或更新版本**,并确保 `pnpm` 在 `PATH` 中。先按[安装指南](../../docs/guides/installation.zh-CN.md)启动 OpenDirector,再从本插件目录打包,并先创建带对话界面的 Web profile,再加入插件包: +先按[安装指南](https://github.com/ThinkFlowLab/OpenDirector/blob/main/docs/guides/installation.zh-CN.md)启动 OpenDirector。插件支持 **DSH 0.2.2-rc.1、rc.2、rc.3 和 rc.5**。在桌面客户端打开「插件」,选择本地 `.tgz` 文件安装。要自己打包并在网页版使用,请准备 **Node.js 24.9.0 或更新版本**,确保能运行 `pnpm`,然后在插件目录执行以下命令。 ```sh npm pack @@ -17,7 +17,7 @@ dsh --profile studio 打开启动时打印的完整 DSH Web 地址,选择工作区和已配置的 DSH 对话模型。先从 `web` 初始化才能得到聊天界面;直接向全新 profile 安装插件只会创建基础组合。已有 Web profile 则只需将 `plugin ... add` 命令中的名称换成它。压缩包安装、Web 对话和画布交接已使用 DSH 0.2.2-rc.1 验证。 -默认 OpenDirector 地址为 `http://127.0.0.1:8000`,普通本地安装无需额外配置。插件行名为 `opendirector`,DSH 在自己的对话与规划流程中调用它提供的八个原生工具。 +默认 OpenDirector 地址为 `http://127.0.0.1:8000`,普通本地安装无需额外配置。插件行名为 `opendirector`,DSH 在自己的对话与规划流程中调用它提供的原生工具。 开发时,也可以先安装本检出的依赖,再链接到已有 profile: @@ -28,28 +28,126 @@ dsh plugin --profile studio add /absolute/path/to/OpenDirector/plugins/deepseek- 包内 JavaScript 可直接运行,无需构建。压缩包安装会安装依赖;链接源码目录则使用该目录自己的 `node_modules`。两种方式都不依赖 npm 发布或市场收录。 +## 找到和安装插件 + +包名是 `@opendirector/dsh-plugin`,装好后在 DSH 插件管理器中显示为 **OpenDirector**,带中英文介绍和图标。当前代码提供源码和可安装的 `.tgz`;发布到 npm 或收录到插件索引是另外的步骤。包还未发布时,请用本地目录或安装包,不要直接输入包名安装。PR 的 **DSH plugin checks** 运行成功后,Linux 任务会在 **Artifacts** 中提供安装包和 SHA-256 文件,保留七天。 + +DSH rc.3 可在**插件 → 实验性插件 → 自定义插件索引**中开启**发现**页。它展示用户添加的索引来源;本地装好插件,不会自动进入所有人的发现页。索引条目支持已发布的 npm 版本,或固定的 Git 提交及包目录。Release 安装包可直接安装。[DSH 自定义插件索引说明](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.2-rc.3/packages/experimental/plugin-market-bundle/README.md) + +本地安装包或源码链接沿用同一来源更新。发布到 npm 后,从注册表安装的插件可使用 DSH 提供的兼容版本更新入口;安装、升级和失败回退由 DSH 处理。 + +### 桌面客户端安装 + +在桌面客户端中打开 **插件 → 添加插件**,输入本地安装包路径,例如 `file:E:/Downloads/opendirector-dsh-plugin-0.1.0.tgz`,然后启用 OpenDirector。使用默认地址时,OpenDirector 服务应运行在 DSH 所在的电脑上。 + +除了 npm 和插件索引,GitHub Release 可以提供带版本号的安装包和校验文件,作为稳定下载入口。工作流产物适合试用 PR;正式版本适合放在 Release 中。项目 README 和社区目录可以链接安装说明,以及一段从生成到采用的演示。 + +### 检查连接 + +在聊天框旁打开 **OpenDirector → 连接检查**,可以查看已配置的接口和画布地址、工程数量,以及图片、参考图、图片转视频、视频续写和配音模型数量。每次打开检查一次;修改服务后点击 **重新检查**。 + +没有模型时,可以打开 OpenDirector 配置;连接失败时,界面会说明应检查地址、启动服务还是调整访问设置。**复制诊断信息** 只复制插件版本、地址、状态和数量,省去工程名称、模型密钥和服务商响应。模型列表表示已配置,实际可用性和生成效果需要生成后确认。检查本身不调用模型。 + +## 平台验收范围 + +交互流程已在 WSL Ubuntu 中运行的 DSH Web 验证。Windows 原生检查覆盖插件加载、工具执行和 HTTP 路由。插件检查工作流包含 Linux、Windows 和 macOS 三个系统。DSH 桌面客户端仍待安装及完整素材流程验收。 + +## 少重复选择,接着上次做 + +点**继续工程**可以查看当前对话用过的工程,也可以在列表里切换。插件在这台设备上按 OpenDirector 服务分别记住列表视图和生成设置。新表单沿用仍然可用的模型,以及上次的图片尺寸或视频时长。续写仍需选择生成来源片段的模型连接。未提交草稿优先恢复。新创作默认一个候选,已保存草稿保留你选过的数量。可以在 **连接检查 → 诊断文本 → 清除最近设置** 中重置这些偏好。 + +图片卡片直接显示 **采用、改图、更多操作**。选 **更多操作 → 转成视频**,就能用这张图作首帧。播放视频时,在喜欢的画面暂停,选 **更多操作 → 保存当前帧为 PNG**,即可按视频原始尺寸保存图片。生成模型支持续写时,卡片也会显示 **续写**。 + +点开图片就能看原图尺寸。用左右方向键翻看这一页的图片,满意时点**采用这张图**。也可以直接改眼前这张,或点**引用到对话**,带着它去跟 DeepSeek 讨论。在创作窗口里,可以从候选直接改图、转成视频,再接着续写。点**返回上一步**就能找回刚才的候选和写到一半的描述。 + +同一节点的结果按登记顺序显示 V1、V2 等版本号,搜索和翻页不会重新编号。图片卡片显示文件的实际尺寸。如果和生成时请求的尺寸不同,卡片会同时标出两者。卡片还显示任务时间,以及能够明确识别的来源版本。改图会创建独立节点,新节点从 V1 开始,并可标出来自原节点的哪一版。 + +工程列表或模型目录读取失败时,可以在当前窗口重新读取。在 OpenDirector 配好模型后,也可以刷新空目录继续操作。已填的描述、动作名称和参考素材会保留;重新读取只查询数据。 + +预览加载失败时,可以在原卡片点击 **重新加载预览**。原图窗口也可以重新读取。 + +## 示例和演示 + +点描述框下的示例就能填入文字。如果已经写过描述,先看示例内容,再决定是否替换。文字可以继续改,点生成才会提交。 + +动作包提供桌宠基础动作和表情动作示例。点击 **替换动作列表** 可填入三个可编辑动作,保留参考图、共用描述和模型。 + +[查看操作演示和示例场景](https://github.com/ThinkFlowLab/OpenDirector/blob/main/plugins/deepseek-harness/docs/showcase.md)。维护者可以按[发布说明](https://github.com/ThinkFlowLab/OpenDirector/blob/main/plugins/deepseek-harness/RELEASING.md),将固定版本的安装包、校验文件、Release 文案和插件索引一起准备好。 + ## 试一次完整创作 先在 OpenDirector 的**设置 → 模型连接**中配置一个图片模型。[使用指南](../../docs/guides/user-guide.zh-CN.md)介绍了连接方式,下面的示例会使用该服务。 -在 DSH 网页输入栏点**创作素材**,然后描述你想做什么: +在聊天框旁打开 **OpenDirector → 创作素材**。选择**图片**、**视频**或**配音**。做视频时,可点**让图片动起来**选一张首帧,也可点**续写视频**选一个片段。如果分镜描述已写在聊天框里,点**带入聊天草稿**就能接着改。选好模型、确认描述后,再点**生成一个候选**。 + +在**候选数量**中选择 1~4,可一次创建一组候选。每个候选是同一节点上的独立生成任务,组内集中显示保存的进度和已完成素材。选两张图片可以直接对比,再采用满意的版本。配音和视频表单也支持候选组;某项失败会保留原因,其他已完成结果仍可查看和选用。 + +候选组提交未确认时,先查询原回执。点**继续提交原候选组**,才会用原操作 ID 继续剩余项,已接受的任务会保留;源节点设置变了就停止继续提交。从保存的任务中打开任一组员,刷新后也能找回整组。 + +在创作表单里完成一轮后,点**调整设置,再做一版**,可以接着改原来的描述,所选模型和参考素材都会保留。上一轮的结果可在表单里展开。前后各出一张图时,点**对比前后两版**就能并排看。 + +提交确认后,**生成设置**会收起,把空间留给候选作品;展开即可查看提交时的设置。界面跟随 DSH 的明暗主题,突出生成、采用与当前结果的操作层级。 + +未提交的输入会保留在当前浏览器标签页。关闭弹窗或刷新 DSH 后,回到同一个创作或改图入口即可继续填写,模型、尺寸和参考图顺序也会保留。点**清空草稿**可以重新开始。提交后可以关掉表单继续聊天。点聊天框旁的任务状态就能打开结果。有几项任务时,按描述选回想看的那一项。较早的任务可以从**继续工程 → 任务**找回。 + +提交结果未确认时,关闭弹窗或刷新 DSH 后,可重新打开原操作,或从**继续工程 → 待确认的提交**查询。查询会沿用原提交 ID,找到已接收的任务后直接打开,不会再次生成,也不依赖模型列表。**开始另一项创作**会打开新表单,并保留原提交的查询入口。**隐藏提示**只移除本地提醒。恢复信息保留在当前浏览器标签页;浏览器存储不可用时,请保持页面打开,先查询再刷新。 + +选好图片尺寸后再切换模型,新模型支持该尺寸时会沿用。若当前模型不支持,表单会提示你重新选择尺寸或模型,再继续生成。 + +在**继续工程**中,可按描述、画布节点名称、模型或复制的 ID 搜索整个工程。搜索会查完整的生成记录,不受卡片预览文字长度限制。结果、任务和参考图每次只展示一页,可用上一页、下一页浏览,避免翻页越多、常驻卡片越多。已选的对比图片和参考图会保留。可组合素材类型、采用状态等条件,也可按任务当前状态筛选。点**清除搜索和筛选**即可回到完整列表。 + +在**继续工程**中点**对比图片**,选择两张已保存图片,再打开对比。可以跨筛选结果和分页选择同一工程的图片;打开对比时才加载原图。可以放大查看并采用其中一版,各节点的当前采用结果分别保留。 + +切到后台或离线时,任务自动查询会暂停;回到页面或恢复网络后,继续查询原任务,不会停止生成。音视频等待内容加载时会显示缓冲提示。 + +要调整已保存的图片或配音,点结果卡片的**复用设置**。表单会带入这版实际生成时的描述和参数;图片可沿用原尺寸,也可选择其他可用尺寸。模型、音色身份和参考素材固定沿用,其他已保存参数保留。生成后会在同一工程的新节点中留下候选,审阅后再采用。结构化描述和展开的主体参考可在画布中调整。 + +点**再生成一个候选**,会用当前画布节点上保存的设置再生成一版。可以在弹窗里比较结果,满意后点对应卡片上的**采用**。 + +卡片会显示文件的实际尺寸或时长。点图片即可在 DSH 中查看原图,并在**实际大小**和**适应窗口**之间切换。 + +断开连接后,可以点**查询提交状态**或**查询进度**继续查看原操作。若服务商明确返回额度或限流错误,处理后点**重试生成**,继续用原节点。画布占用工程时,先保存并关闭画布,再回到同一个弹窗重试。 + +### 在聊天里接着改上一版 + +可以说“把 Night Watch 里两版守夜人放一起。上次的视频用了哪张?”两张图会按你指定的顺序出现在对话里。哪张图做过已生成视频的首帧,卡片上就会标出对应片段。接着说“把那段放给我看”,就能在聊天里播放。 + +点初版守夜人下面的**讨论改图**,把想保留的部分告诉对话模型,比如“我喜欢这片海岸。想加上红围巾,又想保留这个景别,你会怎么写?”提案会带着这张参考图。点**检查并改图**可以改措辞、选模型和尺寸,点**生成一个候选**才会提交图片生成请求。 + +在**继续工程**里找到素材后,点**引用到对话**就能把这一版加到正在写的消息后面。想讨论下一镜,可以在图片或视频的**更多操作**里选**规划下一镜**,补一句自己的想法再发送。 + +也可以从聊天开始一个新工程,比如: > 新建一个叫“月光工作室”的工程,用已配置的图片模型生成一个有电影感的月光房间。先给我看候选,再给我画布链接。 1. DSH 使用 `opendirector_projects` 和 `opendirector_project` 创建工程并找到它的图片模型。随后用 `opendirector_create_generation` 保存节点、用 `opendirector_submit` 提交,再用 `opendirector_job` 查询任务 ID。 2. 任务成功后,直接在 DSH 网页对话里预览已保存的候选。也可以打开工程链接,在**生成历史**中查看。让 DSH 写入工程前,请关闭画布标签页。 -3. 点候选卡片上的**采用**,在同一 DSH 对话中检查草稿并发送。DSH 会读取当前版本并调用 `opendirector_adopt_result`。 +3. 点候选卡片上的**采用**。插件会读取当前版本,采用该结果并显示画布链接。 4. 通过 `/ai-canvas/` 链接回到同一工程。双击图像节点标题重命名,然后重新打开该工程,确认新名称和所选图片仍然存在。 工程链接打开后,还可以修改提示词、查看参考、切换候选,并继续编辑同一个工程。 -要修改某张图,点结果卡片上的**改图**,在卡片里描述修改,再点**发送请求**。请选择支持参考图的图片模型。DSH 用 `sourceResultId` 锁定那张已保存的图,再在同一工程内建立独立的生成节点。结果卡片会并排显示原图和修改候选,两张图都可以在画布继续使用。卡片操作会保留已有草稿和附件。 +要修改某张图,点结果卡片上的**改图**,选择支持参考图的模型,描述修改后点**生成一个候选**。插件会固定所选原图,在同一工程里建立独立的生成节点。采用之前可以对照原图和新结果。表单直接向 OpenDirector 提交,聊天草稿和附件可以继续使用。 + +模型支持多张参考图时,可以点**添加参考图**,从同一个工程里选择已保存的图片。原图固定排第一,可以用箭头调整其他参考图的顺序。 + +提交时如果回执没有返回,点**查询提交状态**查看原操作。任务提交后若生成失败,可以打开画布查看保留的配置和失败原因。 + +### 继续以前的工程 + +点 **OpenDirector → 继续工程**,选择一个 OpenDirector 工程。可以按素材类型或当前采用状态筛选,按保存顺序排序,并点**加载更多**继续浏览。如果画布正在编辑,保存并关闭画布后再采用。采用过程中断线时,点**查询采用状态**查看原操作。 + +右键点击结果卡片,或点卡片的**更多操作**,可以查看该素材支持的操作,也可以下载原文件。用方向键移动,按 Escape 返回卡片。 + +在「继续工程」里点**任务**,可以找回正在生成、已完成和失败的任务,刷新 DSH 后也能继续查看。可以按素材类型筛选、调整排序或翻页查找。点**查看进度**打开原任务,完成后可在其中预览和采用候选。任务明确失败且允许重试时,可以在原节点**重试生成**。关闭弹窗后,任务仍可从列表里找回。 -### 续写一段视频 +在任务进度中点**请求停止**,可以请 OpenDirector 停止当前任务。关闭弹窗后任务仍会继续。回执丢失时,点**查询停止请求**查看原操作。界面会区分本地处理已停止与服务商已确认取消。 -在 OpenDirector 配置 MiniMax-H3 的 vLLM-Omni 连接后,点图片结果上的**转成视频**,在卡片里描述镜头并发送请求。生成后可直接在结果卡片播放。点**续写**并补充下一段要发生什么。续写完成后,DSH 并排显示源片段和续写候选,由你决定是否采用。 +### 把图片转成视频或续写片段 -首段使用 `videoMode: first_frame` 和原图的 `sourceResultId`,下一段使用 `videoMode: continuation` 和源片段的结果 ID。后端必须保有该片段的接续缓存。缓存失效时,任务会给出恢复建议,可以在该后端重生成源片段,或改用首帧或素材参考模式。已有片段和失败任务的输入仍保存在工程里。 +在已保存的图片上点**转成视频**。弹窗会显示作为首帧的图片,并列出支持首帧的模型。选好模型和可用时长,描述画面怎么动,点**生成一个候选**。可以先在 DSH 播放,满意后再采用。 + +如果片段由支持续写的 MiniMax-H3 vLLM-Omni 连接生成,点**续写**,选同一个模型连接和下一段的时长,再描述接下来要发生什么。可以在同一个弹窗里播放源片段和续写候选。服务会用源片段的接续缓存。如果缓存过期,可以在同一个连接上重新生成源片段。原片段和续写设置会保存在工程里。 ## 配置 @@ -96,6 +194,7 @@ dsh plugin --profile remove @opendirector/dsh-plugin | --- | --- | --- | | `opendirector_projects` | “列出我的工程”或“新建一个叫月光工作室的工程。” | 工程列表或创建回执。 | | `opendirector_project` | “显示月光工作室和它已配置的图片模型。” | 工程、模型目录、当前对象版本和工程链接。 | +| `opendirector_results` | “把两版找回来,先帮我想想第一张怎么改。” | 原生素材卡、首帧来源或可审阅的改图提示词。 | | `opendirector_create_generation` | “为月光房间建一个图像节点,先不要生成。” | 可编辑节点及其已保存参考。 | | `opendirector_submit` | “运行刚才的图像生成。” | 已接受的 `jobIds`,采用 `candidate_only` 选择策略。 | | `opendirector_job` | “检查任务并显示已保存的候选。” | 任务状态、候选和选择状态。 | @@ -121,7 +220,17 @@ DSH 无法连接 OpenDirector 时,检查 `baseUrl` 以及服务是否在运行 工具返回结构化 JSON,供程序继续操作。提交、进度、候选选择和取消会展示简短中文或英文摘要,说明工程名称、必要身份、下一步和工程链接;需要检查详细工程或模型时再读取完整数据。 -DSH 网页的结果卡片跟随界面语言,展示已保存的图片和视频。改图和续写请求可在卡片里直接发送。点**采用**会填入草稿供你确认,采用成功的回执有直接打开画布的链接。 +DSH 网页的结果卡片跟随界面语言,展示已保存的图片、视频和音频。可以从卡片直接打开创作表单。点**采用**会选中该结果,并提供画布链接。 + +## 角色动作素材包 + +在已保存的图片上选择**更多操作 → 制作动作素材包**,填写 1 至 6 个动作、共用的角色描述,再选择支持参考图的图片模型或首帧视频模型。**创建并生成**会为每个动作提交一个任务。各动作分别保存候选和采用结果,再生成一版也会保留当前选择。用“调整动作”可以只改一个动作的描述并重做,其他动作和已有选择都会保留。 + +从 **OpenDirector → 动作素材包**可以重新打开已保存的素材包。为每个动作选一版,再点击**下载动作素材包**。ZIP 包含按动作编号命名的媒体文件,以及记录所选结果、描述、模型 ID 和内容指纹的 manifest。下载直接读取工程素材流,合计最多 128 MB,不在服务端另存一份媒体。 + +每个动作都固定引用同一张角色图。角色一致性、动作效果、透明背景和循环时长取决于模型和提示词,请检查实际输出后再用于桌宠。导出的是独立图片或视频片段,后续还需按桌宠运行环境的要求组织动画。 + +也可以通过对话调用 `opendirector_action_pack`,列出、读取、准备、生成或查询素材包。准备只保存动作节点;生成时明确指定动作节点 ID,结果先留为候选。提交确认丢失后,以原操作 ID 查询并继续同一次提交,也可用 `revise` 指定 `itemId`、`prompt` 和 `expectedSpecRevision`,只保存描述而不生成。采用仍使用已有采用工具。关闭弹窗不会取消已接受的任务。 ## 开发检查 @@ -147,4 +256,4 @@ node test/creation.integration.mjs 这会检查创建工程、PNG候选落盘、采用与重放、编辑会话冲突,以及停用插件期间已接受任务继续完成。脚本先检查隔离夹具标记再写入;用 `OPENDIRECTOR_FIXTURE_URL` 可选择其他夹具端口。图片来自测试夹具,不调用模型服务。 -本包将 DSH 兼容版本固定为 `0.2.2-rc.1`。DSH 仍在开发预览阶段,升级宿主前应重新确认兼容性。OpenDirector 自身的运行环境要求以安装指南为准。 +在 Windows 桌面版 rc.5 随附的运行环境中,我们已用独立配置安装本地包,并在其网页界面生成、预览和采用了一张测试图片。桌面窗口中的操作还待手测。此前在 rc.1 测过网页安装,在 rc.3 测过图片创作、动作修改、候选选版、刷新找回、视频播放和 ZIP 导出。rc.2 核对过已发布的工具接口。 diff --git a/plugins/deepseek-harness/RELEASING.md b/plugins/deepseek-harness/RELEASING.md new file mode 100644 index 000000000..03b71fd4c --- /dev/null +++ b/plugins/deepseek-harness/RELEASING.md @@ -0,0 +1,48 @@ +# Preparing a plugin release + +The plugin tarball is the release unit. Keep the tested tarball, screenshots and recording together; use the same bytes for npm and the GitHub Release. + +## Prepare the files + +From this package directory: + +~~~sh +npm test +npm pack --pack-destination /absolute/path/to/candidates +npm run release:prepare -- \ + --tarball /absolute/path/to/candidates/opendirector-dsh-plugin-0.1.0.tgz \ + --output /absolute/path/to/release-candidate +~~~ + +Commit package changes locally before preparing the release. The script checks every packaged file against the current commit and creates a new output directory containing: + +- The tested .tgz and its SHA-256 file. +- Bilingual release-notes.md, with versioned installation links. +- plugin-index.json, using DSH's format 1 and the package's exact npm version and DSH requirements. +- release.json, with the source commit, checksum, release tag and proposed publishing commands. + +The script only writes local files. If a candidate already exists, choose another output directory. The Linux plugin check also prepares these files in its downloadable workflow artifact. + +## Review and publish + +Choose the version in package.json and package-lock.json before packaging. Confirm access to the @opendirector npm scope and the target repository. Review the release text, screenshots, host version and hands-on results for this exact tarball. + +Run the command in release.json from the prepared directory to publish the tarball to npm. Create the draft GitHub Release with the same package and checksum, then attach the demo assets and finish the release description. The command pins the release tag to the tested source commit. + +An index can install an exact npm version or a pinned Git commit and package path. Publish the npm version before making the prepared npm entry available. Set publishTimestamp to the actual publication time, or regenerate with --published-at . Add the entry to a community index, or host the generated JSON at a stable URL and add that source in DSH's **Custom plugin indexes**. + +DSH owns installation and compatible-version updates. A tarball remains useful for PR trials; a registry package provides a simpler update path. + +[DSH index format](https://github.com/deepseek-ai/deepseek-harness/blob/dsh-v0.2.2-rc.3/packages/util/plugin-market-index/README.md) · [Plugin guide](README.md) + +--- + +## 中文 + +先固定并验证安装包,再准备发布材料。运行上面的命令,会一起生成安装包、SHA-256、双语 Release 文案、插件索引和发布记录;脚本只在本地生成文件,不执行发布。 + +打包前确定版本,并将包内文件提交到本地。脚本逐个核对安装包与当前提交,避免演示、校验文件和发布代码对不上。已有候选目录会保留,新一轮使用另一个目录。 + +发布前核对 npm 作用域与仓库权限,检查实际宿主版本、媒体来源和手动验收记录。npm 与 GitHub Release 使用同一个安装包;Release 标签固定到相应源码提交。工作流也会提供这些材料,供 PR 试用。 + +插件索引支持明确的 npm 版本或固定 Git 提交及包目录。生成的 npm 条目应在对应版本发布后再提供给用户,并填写实际发布时间。可以提交到社区索引,也可以托管自己的索引,让用户在 DSH 的「自定义插件索引」里添加。后续安装和升级沿用 DSH 的入口。 diff --git a/plugins/deepseek-harness/docs/media/lunar-mail.mp4 b/plugins/deepseek-harness/docs/media/lunar-mail.mp4 new file mode 100644 index 000000000..68d013c60 Binary files /dev/null and b/plugins/deepseek-harness/docs/media/lunar-mail.mp4 differ diff --git a/plugins/deepseek-harness/docs/media/night-watch.mp4 b/plugins/deepseek-harness/docs/media/night-watch.mp4 new file mode 100644 index 000000000..be9e11951 Binary files /dev/null and b/plugins/deepseek-harness/docs/media/night-watch.mp4 differ diff --git a/plugins/deepseek-harness/docs/media/walkthrough.gif b/plugins/deepseek-harness/docs/media/walkthrough.gif new file mode 100644 index 000000000..eb6d13f76 Binary files /dev/null and b/plugins/deepseek-harness/docs/media/walkthrough.gif differ diff --git a/plugins/deepseek-harness/docs/media/walkthrough.mp4 b/plugins/deepseek-harness/docs/media/walkthrough.mp4 new file mode 100644 index 000000000..3e3387754 Binary files /dev/null and b/plugins/deepseek-harness/docs/media/walkthrough.mp4 differ diff --git a/plugins/deepseek-harness/docs/media/workflow.png b/plugins/deepseek-harness/docs/media/workflow.png new file mode 100644 index 000000000..b67a9d009 Binary files /dev/null and b/plugins/deepseek-harness/docs/media/workflow.png differ diff --git a/plugins/deepseek-harness/docs/showcase.html b/plugins/deepseek-harness/docs/showcase.html new file mode 100644 index 000000000..e5e7927bc --- /dev/null +++ b/plugins/deepseek-harness/docs/showcase.html @@ -0,0 +1,58 @@ + + + + + +OpenDirector × DeepSeek Harness + + + +
+
OpenDirector × DeepSeek Harness
Local preview
+
+
A shared project. A continuous workflow.

Make it. Compare it.
Keep your best version.

从一个想法,到一组可用素材。

+

Create images, video and voiceover in DSH. Refine candidates, choose a result and continue in the same OpenDirector project.

+
+
Lunar Post Office · from prompt to saved image
+ +
+
01 / STARTDescribe the idea

Use an example or your own prompt. Choose the model and number of candidates.

+
02 / REFINECompare versions

Keep references in order, edit a saved image or generate another candidate.

+
03 / CHOOSEMake it current

Adopt the result you prefer. Other versions stay available in the project.

+
04 / CONTINUEReturn and export

Reopen saved work or build an action pack and export one chosen version per action.

+
+

Three ways to start

可以把下面的描述填进创作表单,也可以直接在 DSH 对话中说明目标。

+
+
Image / 图片

Studio by the window

Warm sunlight streams through a large studio window onto a wooden desk. A blue ceramic mug sits beside a leafy green plant. Realistic photography, shallow depth of field.

+
Character / 角色

A little companion

A friendly small robot with a rounded cream body, teal eyes and a tiny orange scarf. Full body, front view, centered, plain light background, clean silhouette.

+
Voiceover / 配音

A warm welcome

A quiet corner, a warm cup, and a little room to create. Welcome to our studio.

+
+

Ready to try it?

+

Start with one image or one short voiceover.

+
    +
  1. Start OpenDirector and add a model under Settings → Model connections.
  2. +
  3. In DSH, open Plugins → Add plugin and enter the local .tgz path from your Release or PR artifact. Enable OpenDirector.
  4. +
  5. Choose Create media. Try an example, select your model and generate a candidate.
  6. +

先启动 OpenDirector 并配置模型,再在 DSH 安装插件。从「创作素材 → 试一个例子」开始。

+Full setup guide ↗
+

Keep the whole project.

Generation settings, references, candidate history and selections stay in OpenDirector. DSH provides the conversation and direct creation forms.

描述、参考素材、候选和采用记录保存在工程中,刷新后还能接着做。

Use your configured models.

Start OpenDirector and configure a media model. The plug icon in DSH checks the service address and available capabilities.

先配置模型,再从一张图片或一句配音开始。

+
OpenDirector for DeepSeek Harness · Apache-2.0Local presentation preview · npm and index publication pending
+
+ + + diff --git a/plugins/deepseek-harness/docs/showcase.md b/plugins/deepseek-harness/docs/showcase.md new file mode 100644 index 000000000..609574130 --- /dev/null +++ b/plugins/deepseek-harness/docs/showcase.md @@ -0,0 +1,56 @@ +# From an idea to a saved media project + +[中文](#中文) · [Open the presentation page](showcase.html) · [Install and connect](../README.md) + +## Night Watch + +[Watch the walkthrough (2:26)](media/night-watch.mp4). A lighthouse keeper gets a red scarf, turns toward the sea and speaks a single line. The portrait, edit, moving shot and voiceover came from four live MiniMax requests. The walkthrough also shows a later conversation about the saved project. + +- **0:04** — DeepSeek finds the portrait used as the video's first frame. +- **0:54** — Compare the two portraits and adopt the red-scarf version. +- **2:07** — Open DeepSeek's suggested scarf edit with the wider coastal portrait already selected. +- **2:22** — Watch the exported film with its title and voiceover. + +## Lunar Post Office + +[![A penguin at a lunar mailbox, shown as a candidate in DSH](media/workflow.png)](media/walkthrough.mp4) + +[Watch Lunar Post Office (1 min 16 sec)](media/walkthrough.mp4) · [Compare three saved versions (GIF)](media/walkthrough.gif) + +The video follows one image from prompt to saved project. The plugin sends a single generation through OpenDirector and a local bridge to MiniMax image-01. The candidate appears around 0:50. After adoption, the same image is marked current when the project reopens. This is a continuous, browser-driven recording on the web host bundled with Windows DSH 0.2.2-rc.5. + +The separate GIF shows how to compare V1, V2 and V3. It uses previously generated images replayed in DSH rc.3 Web. + +[Watch the penguin post its letter](media/lunar-mail.mp4). From the saved image card we chose **Animate**, used the image as the first frame, and requested four seconds at 480P from MiniMax-H3-Lite. The downloaded clip plays for 4.46 seconds. Pause it in DSH and choose **Save current frame as PNG** to keep a still. + +## Try an example + +Open **OpenDirector → Create media** and pick an example below the description. The form keeps your model and parameters; choose **Generate** when ready. + +| Start with | Next step | +| --- | --- | +| Studio by the window | Generate two candidates, compare them and adopt one. Reopen the same project. | +| A character for an action pack | From the saved image, choose **Make an action pack**. Start with the desktop companion or expression actions, generate and choose one version per action. | +| A short introduction | Select **Voiceover**, use your configured voice model and voice ID, then generate and listen. | + +Saved-image forms also have examples for a desk-lamp edit, evening lighting and a gentle camera move. Supported continuation forms have a matching example. + +A DSH conversation can start the same workflow: + +> Create a project called “Studio by the window”. Use my configured image model to generate two candidates of a wooden desk, a blue mug and a green plant in natural window light. Show them before adopting either one. + +## 中文 + +[看企鹅把信投进邮筒](media/lunar-mail.mp4)。从已保存的企鹅图片点「转成视频」,用它作首帧,向 MiniMax-H3-Lite 请求 4 秒、480P 的镜头。成片实际长 4.46 秒。在 DSH 中暂停后,可以从视频菜单把当前画面存成 PNG。 + +「月面邮局」的视频在 Windows DSH rc.5 自带的网页宿主中连续录制。浏览器自动操作插件,通过 OpenDirector 和本机转接向 MiniMax image-01 实际生成一张图。约 0:50 可以看到候选,结尾是刷新后重新打开工程的结果。另附的 GIF 用回放图片演示三版候选的比较与采用。 + +打开「OpenDirector → 创作素材」,在描述下选择示例,选择工作室生图、角色参考图或配音。示例先填入描述;检查模型和参数后再生成。已经选好的模型、尺寸、参考图顺序和候选数量会保留。 + +- **工作室图片**:先生成两张候选,对比并采用一张,再从「继续工程」找回。 +- **角色动作素材包**:用一张已保存的角色图创建动作包。选择基础动作或表情示例,逐动作选版,再导出 ZIP。 +- **配音**:选择配音模型和音色,填入开场白示例,生成后试听。 + +也可以在 DSH 中直接说: + +> 新建“窗边工作室”工程,用我已配置的图片模型生成两张候选:木桌、蓝色陶瓷杯、绿植和自然窗光。先给我对比,不要直接采用。 diff --git a/plugins/deepseek-harness/icon.svg b/plugins/deepseek-harness/icon.svg new file mode 100644 index 000000000..0ccef2967 --- /dev/null +++ b/plugins/deepseek-harness/icon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/plugins/deepseek-harness/index.js b/plugins/deepseek-harness/index.js index acb467d66..872e046bc 100644 --- a/plugins/deepseek-harness/index.js +++ b/plugins/deepseek-harness/index.js @@ -1,7 +1,11 @@ import Schema from '@deepseek-ai/schemastery' +import packageInfo from './package.json' with { type: 'json' } +import { connectionStatus } from './src/connection.js' +import { Readable } from 'node:stream' +import { zipEntries } from './src/archive.js' import { OpenDirectorClient } from './src/client.js' -import { resolveConfig } from './src/config.js' -import { ConfigError, HttpError, InputError } from './src/errors.js' +import { DEFAULT_BASE_URL, resolveConfig } from './src/config.js' +import { ConfigError, HttpError, InputError, NetworkError, RequestTimeoutError, UnknownOperationError } from './src/errors.js' import { createMessages } from './src/i18n.js' import { createOpenDirectorTools } from './src/tools.js' @@ -9,12 +13,28 @@ export const name = 'opendirector' export const inject = ['tools'] export const Config = Schema.object({ - baseUrl: Schema.string().default('http://127.0.0.1:8000'), + baseUrl: Schema.string().default(DEFAULT_BASE_URL), canvasBaseUrl: Schema.string().default(''), locale: Schema.union(['en-US', 'zh-CN']).default('en-US'), requestTimeoutMs: Schema.number().default(30000), }) +function isBrowserAction(request) { + const site = request.headers.get('sec-fetch-site') + return request.headers.get('x-opendirector-action') === '1' && (!site || site === 'same-origin') +} + +async function actionInput(request) { + const input = await request.json() + if (!input || typeof input !== 'object' || Array.isArray(input)) throw new TypeError('Invalid action') + return input +} + +function errorCode(error) { + if (error instanceof HttpError) return error.code + return error instanceof InputError ? error.key : 'unavailable' +} + export function apply(ctx, config) { const requestedLocale = config?.locale === 'zh-CN' ? 'zh-CN' : 'en-US' const requestedMessages = createMessages(requestedLocale) @@ -31,6 +51,8 @@ export function apply(ctx, config) { ctx.tools.register(tool) } ctx.inject(['connection'], (scope) => { + const headers = { 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' } + scope.effect(() => scope.connection.fetch.register({ path: '/api/opendirector/media', methods: ['GET'], @@ -40,27 +62,218 @@ export function apply(ctx, config) { try { ({ searchParams } = new URL(request.url, 'http://localhost')) } catch { - return new Response(null, { status: 400 }) + return new Response(null, { status: 400, headers }) } try { const media = await client.media( searchParams.get('project'), searchParams.get('asset'), { - kind: searchParams.get('kind'), range: request.headers.get('range'), signal: request.signal, + kind: searchParams.get('kind'), original: searchParams.get('original') === '1', + range: request.headers.get('range'), signal: request.signal, }, ) - const headers = new Headers({ 'Cache-Control': 'private, no-store', 'X-Content-Type-Options': 'nosniff' }) + const mediaHeaders = new Headers(headers) for (const name of ['Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges']) { const value = media.headers.get(name) - if (value !== null) headers.set(name, value) + if (value !== null) mediaHeaders.set(name, value) } - return new Response(media.body, { status: media.status, headers }) + return new Response(media.body, { status: media.status, headers: mediaHeaders }) } catch (error) { const status = error instanceof InputError ? 400 : error instanceof HttpError && error.status === 404 ? 404 : 502 - return new Response(null, { status }) + return new Response(null, { status, headers }) } }, }), 'OpenDirector media previews') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/connection', + methods: ['GET'], + requestBody: 'buffered', + async fetch(request) { + const diagnosticClient = new OpenDirectorClient({ + ...resolved, requestTimeoutMs: Math.min(resolved.requestTimeoutMs, 5000), + }) + return Response.json(await connectionStatus(diagnosticClient, resolved, packageInfo.version, + { signal: request.signal }), { headers }) + }, + }), 'OpenDirector connection check') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/library', + methods: ['GET'], + requestBody: 'buffered', + async fetch(request) { + try { + const params = new URL(request.url, 'http://localhost').searchParams + const projectId = params.get('project') + if (params.has('show')) { + const value = await client.showResults(projectId, params.get('show').split(','), { signal: request.signal }) + return Response.json(value, { headers }) + } + if (params.has('compare')) { + const value = await client.compareImages(projectId, params.get('compare').split(','), { signal: request.signal }) + return Response.json(value, { headers }) + } + if (projectId !== null) { + const options = { + kind: params.get('kind') ?? undefined, selection: params.get('selection') ?? undefined, + order: params.get('order') ?? undefined, after: params.get('after'), signal: request.signal, + query: params.get('q') ?? '', status: params.get('status') ?? undefined, + } + const library = params.get('view') === 'jobs' + ? await client.libraryJobs(projectId, options) + : await client.libraryResults(projectId, options) + return Response.json(library, { headers }) + } + const value = await client.listProjects({ signal: request.signal }) + const projects = value.projects.map(({ id, name }) => ({ id, name })) + return Response.json({ projects, scope: resolved.baseUrl }, { headers }) + } catch (error) { + const status = error instanceof InputError ? (error.key === 'library.cursor_expired' ? 409 : 400) + : error instanceof HttpError && error.status === 404 ? 404 + : 502 + return new Response(null, { status, headers }) + } + }, + }), 'OpenDirector project library') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/adopt', + methods: ['POST'], + requestBody: 'buffered', + async fetch(request) { + // The DSH connection authenticates the request. Require a same-origin + // browser action as well, so a cross-origin form cannot adopt a result. + if (!isBrowserAction(request)) { + return new Response(null, { status: 403, headers }) + } + let input + try { + input = await actionInput(request) + } catch { + return new Response(null, { status: 400, headers }) + } + const { projectId, resultId, operationId } = input + const check = input.check === true + try { + const receipt = await client.adoptCandidate({ + projectId, resultId, operationId, check, signal: request.signal, + }) + return Response.json({ + status: receipt?.status ?? 'unknown', + code: receipt?.issues?.[0]?.code, + canvasUrl: client.canvasUrl(projectId), + }, { headers }) + } catch (error) { + if (error instanceof UnknownOperationError || (check && !(error instanceof InputError))) { + return Response.json({ status: 'unknown' }, { headers }) + } + return Response.json({ status: 'rejected', code: errorCode(error) }, { headers }) + } + }, + }), 'OpenDirector result adoption') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/cancel', + methods: ['POST'], + requestBody: 'buffered', + async fetch(request) { + if (!isBrowserAction(request)) return new Response(null, { status: 403, headers }) + let input + try { + input = await actionInput(request) + } catch { + return new Response(null, { status: 400, headers }) + } + try { + const receipt = await client.cancelCreation({ ...input, signal: request.signal }) + return Response.json({ status: receipt?.status ?? 'unknown', code: receipt?.issues?.[0]?.code }, { headers }) + } catch (error) { + if (error instanceof UnknownOperationError || (input.check === true && !(error instanceof InputError))) { + return Response.json({ status: 'unknown' }, { headers }) + } + return Response.json({ status: 'rejected', code: errorCode(error) }, { headers }) + } + }, + }), 'OpenDirector job cancellation') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/action-packs', + methods: ['GET', 'POST'], + requestBody: 'buffered', + async fetch(request) { + if (request.method === 'GET') { + try { + const params = new URL(request.url, 'http://localhost').searchParams + const input = { projectId: params.get('project'), packId: params.get('pack'), + action: params.has('pack') ? 'get' : 'list' } + if (params.get('download') === '1') { + const archive = await client.actionPackArchive(input, { signal: request.signal }) + return new Response(Readable.toWeb(Readable.from(zipEntries(archive.entries, + { signal: request.signal, maxBytes: archive.maxBytes }))), { + headers: { ...headers, 'Content-Type': 'application/zip', + 'Content-Disposition': 'attachment; filename="' + archive.filename + '"' }, + }) + } + return Response.json({ ...await client.actionPack(input, { signal: request.signal }), + canvasUrl: client.canvasUrl(input.projectId) }, { headers }) + } catch (error) { + return Response.json({ code: errorCode(error) }, { status: error instanceof InputError ? 400 : 502, headers }) + } + } + if (!isBrowserAction(request)) return new Response(null, { status: 403, headers }) + let input + try { input = await actionInput(request) } catch { return new Response(null, { status: 400, headers }) } + try { + const value = await client.actionPack(input, { signal: request.signal }) + return Response.json({ ...value, projectId: input.projectId, canvasUrl: client.canvasUrl(input.projectId) }, { headers }) + } catch (error) { + return Response.json(error instanceof UnknownOperationError || input.action === 'check' + ? { status: 'unknown' } : { status: 'rejected', code: errorCode(error) }, { headers }) + } + }, + }), 'OpenDirector action packs') + + scope.effect(() => scope.connection.fetch.register({ + path: '/api/opendirector/creation', + methods: ['GET', 'POST'], + requestBody: 'buffered', + async fetch(request) { + if (request.method === 'GET') { + try { + const params = new URL(request.url, 'http://localhost').searchParams + const { signal } = request + const value = params.has('group') + ? await client.creationGroupStatus(params.get('project'), params.get('group'), { signal }) + : params.has('job') + ? await client.creationStatus(params.get('project'), params.get('job'), { signal }) + : params.has('reuse') + ? await client.creationTemplate(params.get('project'), params.get('reuse'), { signal }) + : { models: await client.creationModels({ signal }), scope: resolved.baseUrl } + return Response.json(value, { headers }) + } catch (error) { + return new Response(null, { status: error instanceof InputError ? 400 : 502, headers }) + } + } + if (!isBrowserAction(request)) return new Response(null, { status: 403, headers }) + let input + try { + input = await actionInput(request) + } catch { + return new Response(null, { status: 400, headers }) + } + try { + const value = await client.startCreation(input, { signal: request.signal }) + return Response.json({ ...value, canvasUrl: client.canvasUrl(input.projectId) }, { headers }) + } catch (error) { + const unknown = error instanceof UnknownOperationError || (input.check === true && !(error instanceof InputError)) + const code = error instanceof NetworkError || error instanceof RequestTimeoutError + ? 'creation.unavailable' : errorCode(error) + return Response.json(unknown ? { status: 'unknown' } + : { status: 'rejected', code }, { headers }) + } + }, + }), 'OpenDirector creation controls') }) } diff --git a/plugins/deepseek-harness/locale/en.json b/plugins/deepseek-harness/locale/en.json new file mode 100644 index 000000000..da3781ac8 --- /dev/null +++ b/plugins/deepseek-harness/locale/en.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "OpenDirector", + "description": "Create images, video, and voice in shared projects, compare and select candidates, and resume projects from DeepSeek Harness.", + "detail": "README.md" + } +} diff --git a/plugins/deepseek-harness/locale/zh.json b/plugins/deepseek-harness/locale/zh.json new file mode 100644 index 000000000..33757a47a --- /dev/null +++ b/plugins/deepseek-harness/locale/zh.json @@ -0,0 +1,7 @@ +{ + "meta": { + "title": "OpenDirector", + "description": "在 DeepSeek Harness 中创作图片、视频和语音,对比并选择候选结果,随时继续未完成的工程。", + "detail": "README.zh-CN.md" + } +} diff --git a/plugins/deepseek-harness/package-lock.json b/plugins/deepseek-harness/package-lock.json index 02e1eb8a2..38411b321 100644 --- a/plugins/deepseek-harness/package-lock.json +++ b/plugins/deepseek-harness/package-lock.json @@ -19,12 +19,12 @@ "@deepseek-ai/dsh-tools": "0.2.2-rc.1" }, "engines": { - "dsh": "0.2.2-rc.1", + "dsh": "0.2.2-rc.1 || 0.2.2-rc.2 || 0.2.2-rc.3 || 0.2.2-rc.5", "node": ">=24.9.0" }, "peerDependencies": { "@deepseek-ai/cordis": "~4.1.0", - "@deepseek-ai/dsh-tools": "0.2.2-rc.1" + "@deepseek-ai/dsh-tools": "0.2.2-rc.1 || 0.2.2-rc.2 || 0.2.2-rc.3 || 0.2.2-rc.5" } }, "node_modules/@deepseek-ai/cordis": { diff --git a/plugins/deepseek-harness/package.json b/plugins/deepseek-harness/package.json index c87a02980..b1e154efb 100644 --- a/plugins/deepseek-harness/package.json +++ b/plugins/deepseek-harness/package.json @@ -5,23 +5,47 @@ "license": "Apache-2.0", "type": "module", "main": "index.js", + "icon": "./icon.svg", "exports": { ".": "./index.js", "./client": "./src/web-client.js", + "./locale/*.json": "./locale/*.json", + "./icon": "./icon.svg", "./package.json": "./package.json" }, "files": [ "index.js", "src", + "locale/*.json", + "icon.svg", "cordis.patch.yml", "README.md", "README.zh-CN.md" ], + "homepage": "https://github.com/ThinkFlowLab/OpenDirector/tree/main/plugins/deepseek-harness", + "repository": { + "type": "git", + "url": "git+https://github.com/ThinkFlowLab/OpenDirector.git", + "directory": "plugins/deepseek-harness" + }, + "bugs": { + "url": "https://github.com/ThinkFlowLab/OpenDirector/issues" + }, + "keywords": [ + "deepseek-harness", + "dsh-plugin", + "opendirector", + "image-generation", + "video-generation", + "voice-generation", + "media" + ], "scripts": { - "test": "node --test test/*.test.js" + "test": "node --test test/*.test.js", + "release:prepare": "node scripts/prepare-release.mjs" }, "engines": { - "dsh": "0.2.2-rc.1", + "dsh": "0.2.2-rc.1 || 0.2.2-rc.2 || 0.2.2-rc.3 || 0.2.2-rc.5", "node": ">=24.9.0" }, "dsh": { @@ -38,7 +62,7 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "~4.1.0", - "@deepseek-ai/dsh-tools": "0.2.2-rc.1" + "@deepseek-ai/dsh-tools": "0.2.2-rc.1 || 0.2.2-rc.2 || 0.2.2-rc.3 || 0.2.2-rc.5" }, "devDependencies": { "@deepseek-ai/cordis": "~4.1.0", diff --git a/plugins/deepseek-harness/scripts/prepare-release.mjs b/plugins/deepseek-harness/scripts/prepare-release.mjs new file mode 100644 index 000000000..d23da6665 --- /dev/null +++ b/plugins/deepseek-harness/scripts/prepare-release.mjs @@ -0,0 +1,135 @@ +#!/usr/bin/env node +// Prepare one frozen package locally. npm and GitHub publishing are separate. +import { execFileSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { readFile, writeFile, mkdir, copyFile, stat } from 'node:fs/promises' +import { dirname, resolve, relative, basename, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const options = {} +for (let i = 2; i < process.argv.length; i += 2) { + const key = process.argv[i] + if (!['--tarball', '--output', '--published-at'].includes(key) || !process.argv[i + 1]) { + throw new Error('Usage: npm run release:prepare -- --tarball --output [--published-at ]') + } + options[key.slice(2)] = process.argv[i + 1] +} +if (!options.tarball || !options.output) throw new Error('--tarball and --output are required') +const tarball = resolve(options.tarball) +const output = resolve(options.output) +const run = (command, args, cwd = root) => execFileSync(command, args, { cwd, maxBuffer: 16 * 1024 * 1024 }) +const listing = run('tar', ['-tzf', tarball]).toString().trim().split(/\r?\n/) +if (listing.some(name => !name.startsWith('package/') || name.split('/').includes('..'))) throw new Error('Expected an npm package archive') +const readEntry = name => run('tar', ['-xOzf', tarball, 'package/' + name]) +const manifest = JSON.parse(readEntry('package.json')) +if (manifest.name !== '@opendirector/dsh-plugin' || !/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/.test(manifest.version)) { + throw new Error('Unexpected package name or version') +} +const commit = run('git', ['rev-parse', 'HEAD']).toString().trim() +const repoRoot = run('git', ['rev-parse', '--show-toplevel']).toString().trim() +const packagePath = relative(repoRoot, root).replaceAll('\\', '/') +for (const name of listing.filter(name => !name.endsWith('/'))) { + const path = name.slice('package/'.length) + const committed = run('git', ['show', commit + ':' + packagePath + '/' + path], repoRoot) + if (!readEntry(path).equals(committed)) throw new Error('The tested tarball differs from the committed file: ' + path) +} +try { + await stat(output) + throw new Error('Choose a new output directory to keep an earlier publication candidate intact') +} catch (error) { + if (error.code !== 'ENOENT') throw error +} +const repository = manifest.repository.url.replace(/^git\+/, '').replace(/\.git$/, '') +const tag = 'dsh-plugin-v' + manifest.version +const releaseUrl = repository + '/releases/download/' + tag +const filename = basename(tarball) +if (!/^[a-zA-Z0-9._-]+\.tgz$/.test(filename)) throw new Error('Use an npm tarball filename') +const sha256 = createHash('sha256').update(await readFile(tarball)).digest('hex') +const publishedAt = options['published-at'] ?? new Date().toISOString() +const publishTimestamp = Math.floor(Date.parse(publishedAt) / 1000) +if (!Number.isSafeInteger(publishTimestamp) || publishTimestamp < 0) throw new Error('Invalid publication time') +const locale = language => JSON.parse(readEntry('locale/' + language + '.json')).meta +const index = { + format: 1, + title: { en: 'OpenDirector plugins', zh: 'OpenDirector 插件' }, + description: { en: 'Media creation in shared OpenDirector projects.', zh: '在共享的 OpenDirector 工程中创作素材。' }, + plugins: [{ + name: manifest.name, + title: { en: locale('en').title, zh: locale('zh').title }, + description: { en: locale('en').description, zh: locale('zh').description }, + icon: 'data:image/svg+xml;base64,' + readEntry(manifest.icon.slice(2)).toString('base64'), + homepage: manifest.homepage, + repository: { url: repository, directory: manifest.repository.directory }, + metadata: { keywords: manifest.keywords }, + versions: [{ version: manifest.version, publishTimestamp, source: { type: 'npm' }, engines: { dsh: manifest.engines.dsh } }], + }], +} +const guide = repository + '/tree/' + tag + '/' + packagePath +const notes = `# OpenDirector for DeepSeek Harness ${manifest.version} + +Create images, video and voiceover in DSH. Compare candidates, refine a saved result, choose a version and return to the same OpenDirector project. + +- Generate 1–4 candidates, inspect the output and adopt the version you prefer. +- Edit with ordered image references, animate an image, or continue a supported clip. +- Reopen saved work after a reload and check an unconfirmed submission before retrying. +- Create a character action pack, refine individual actions and export the selected media as a ZIP. +- Start with a ready-made description, and check the service connection from the composer. + +## Install + +Download [${filename}](${releaseUrl}/${filename}) and its [SHA-256 file](${releaseUrl}/${filename}.sha256). +In DSH, choose **Plugins → Add plugin**, enter the local tarball path and enable OpenDirector. +For the CLI, run: + +\`\`\`sh +dsh plugin --profile studio add ./${filename} +\`\`\` + +Start OpenDirector first. See the [setup guide](${guide}) for connection settings. +DSH requirement: \`${manifest.engines.dsh}\`; Node.js: \`${manifest.engines.node}\`. + +## Package + +SHA-256: \`${sha256}\` +Source: [\`${commit.slice(0, 7)}\`](${repository}/commit/${commit}) + +## Validation to complete before publication + +Add the tested host version, media source, checks and hands-on acceptance evidence for this package. +The index file is a publication draft; publish the exact npm version before making that entry available. + +--- + +在 DSH 中生成图片、视频和配音,对比候选,调整已保存的结果,再回到同一个 OpenDirector 工程继续编辑。 + +支持成组候选、参考图改图、图片转视频、工程找回和角色动作素材包导出。创作表单提供可填入的示例,输入框旁可检查服务连接。 + +下载本页安装包后,在 DSH 的「插件 → 添加插件」中输入本地路径并启用 OpenDirector。先启动 OpenDirector;连接配置见上方安装说明。发布前请补齐这个安装包对应的实际验收记录。 +` +const presentationFiles = ['icon.svg', 'README.md', 'README.zh-CN.md', 'docs/showcase.html', 'docs/showcase.md', + 'docs/media/walkthrough.mp4', 'docs/media/walkthrough.gif', 'docs/media/workflow.png'] +const presentation = presentationFiles.map(path => ({ + path, bytes: run('git', ['show', commit + ':' + packagePath + '/' + path], repoRoot), +})) +await mkdir(output) +for (const file of presentation) { + const target = join(output, file.path) + await mkdir(dirname(target), { recursive: true }) + await writeFile(target, file.bytes) +} +await copyFile(tarball, join(output, filename)) +await writeFile(join(output, filename + '.sha256'), sha256 + ' ' + filename + '\n') +await writeFile(join(output, 'plugin-index.json'), JSON.stringify(index, null, 2) + '\n') +await writeFile(join(output, 'release-notes.md'), notes) +await writeFile(join(output, 'release.json'), JSON.stringify({ + status: 'local publication draft', name: manifest.name, version: manifest.version, sourceCommit: commit, + package: filename, sha256, tag, repository, presentation: 'docs/showcase.html', proposedPublishTimestamp: publishTimestamp, + indexSource: 'npm; publish the exact version before distributing the index', + commands: { + npm: 'npm publish ' + filename + ' --access public', + github: 'gh release create ' + tag + ' ' + filename + ' ' + filename + '.sha256 docs/media/walkthrough.mp4 docs/media/walkthrough.gif docs/media/workflow.png --repo ' + + repository.replace('https://github.com/', '') + ' --target ' + commit + ' --title "OpenDirector DSH ' + manifest.version + '" --notes-file release-notes.md --draft', + }, +}, null, 2) + '\n') +console.log(JSON.stringify({ output, version: manifest.version, commit, sha256, status: 'prepared locally; nothing published' })) diff --git a/plugins/deepseek-harness/src/action-packs.js b/plugins/deepseek-harness/src/action-packs.js new file mode 100644 index 000000000..9d4360008 --- /dev/null +++ b/plugins/deepseek-harness/src/action-packs.js @@ -0,0 +1,268 @@ +import { buildCreateGeneration, buildSubmitCommand, imageOutputParameters, requireUuid, requireString, uuid5 } from './operations.js' +import { InputError, UnknownOperationError } from './errors.js' +import { mediaDetails, resultMediaDetails } from './presentation.js' +import { resultVersionInfo } from './versions.js' + +const TAG = 'dsh-action-pack' +const LIMIT = 128 * 1024 * 1024 +const EXTENSIONS = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp', 'image/gif': 'gif', + 'image/avif': 'avif', 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'audio/wav': 'wav', 'audio/mpeg': 'mp3' } + +function packNodes(snapshot, packId) { + const group = snapshot.canvasItems.find(item => item.id === packId && item.kind === 'group' && item.tags?.includes(TAG)) + if (!group) throw new InputError('pack.missing') + const specs = new Map(snapshot.generationSpecs.map(spec => [spec.id, spec])) + const nodes = snapshot.canvasItems.filter(item => item.parentId === packId + && item.binding?.role === 'generation' && ['image', 'video'].includes(item.kind) + && specs.has(item.binding.objectRef?.id)) + .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x || a.id.localeCompare(b.id)) + return { group, nodes, specs } +} + +export function packState(snapshot, packId, canRetry) { + const { group, nodes, specs } = packNodes(snapshot, packId) + const metadata = new Map((snapshot.assets ?? []).map(asset => [asset.id, asset.metadata])) + const versions = resultVersionInfo(snapshot) + const detailsFor = resultMediaDetails(snapshot) + const actions = nodes.map(item => { + const spec = specs.get(item.binding.objectRef.id) + const jobs = snapshot.jobs.filter(job => job.inputSnapshot.spec.id === spec.id) + const active = jobs.find(job => ['queued', 'running'].includes(job.status)) + const latest = jobs.at(-1) + const results = snapshot.results.filter(result => result.specId === spec.id).map(result => ({ + resultId: result.id, assetId: result.asset.assetId, kind: result.asset.kind, + selected: result.id === spec.currentResultId, + ...(versions.get(result.id) ?? {}), + details: detailsFor(result), + })) + const reference = snapshot.references.find(ref => ref.targetSpecId === spec.id && ref.active !== false && ref.source?.assetId) + return { + itemId: item.id, specId: spec.id, name: item.title || spec.kind, prompt: spec.prompt, kind: spec.kind, + revision: spec.revision, selectedResultId: spec.currentResultId, + status: active?.status ?? latest?.status ?? 'not_started', + jobs: jobs.map(job => ({ jobId: job.id, status: job.status, category: job.errorDetails?.category, + cancelRequested: job.cancelRequested, remoteCancellation: job.remoteCancellation })), + canRevise: !active, + canGenerate: !active && (!latest || latest.status === 'succeeded' || canRetry(latest)), + results, + ...(reference && { reference: { assetId: reference.source.assetId, kind: reference.source.kind, + details: mediaDetails(metadata.get(reference.source.assetId)) } }), + } + }) + return { projectId: snapshot.project.id, projectName: snapshot.project.name, packId, title: group.title, + actions, selectedCount: actions.filter(action => action.selectedResultId && action.results.some(r => r.selected)).length, + active: actions.some(action => ['queued', 'running'].includes(action.status)), + missingCount: actions.filter(action => !action.jobs.length).length } +} + +function validatePlan(input) { + const title = requireString(input.title, 'title').trim() + const shared = typeof input.sharedPrompt === 'string' ? input.sharedPrompt.trim() : '' + if (!title || title.length > 100 || shared.length > 4000 || !Array.isArray(input.actions) + || input.actions.length < 1 || input.actions.length > 6) throw new InputError('pack.plan') + const names = new Set() + const actions = input.actions.map(value => { + const name = typeof value?.name === 'string' ? value.name.trim() : '' + const prompt = typeof value?.prompt === 'string' ? value.prompt.trim() : '' + const key = name.normalize('NFKC').toLowerCase() + if (!name || name.length > 80 || !prompt || prompt.length > 4000 || names.has(key)) throw new InputError('pack.plan') + names.add(key) + return { name, prompt: [shared, prompt].filter(Boolean).join('\n\n') } + }) + return { title, actions } +} + +function packItemIds(input) { + if (!Array.isArray(input.itemIds) || !input.itemIds.length || input.itemIds.length > 6) throw new InputError('pack.plan') + const ids = input.itemIds.map(id => requireUuid(id, 'itemIds')) + if (new Set(ids).size !== ids.length) throw new InputError('pack.plan') + return ids +} + +export async function actionPackRequest(input, io) { + const action = input.action ?? 'get' + if (!['list', 'get', 'check', 'prepare', 'generate', 'revise'].includes(action)) throw new InputError('pack.action') + if (input.redo != null && typeof input.redo !== 'boolean') throw new InputError('pack.plan') + if (action === 'list') { + const snapshot = await io.read() + const packs = snapshot.canvasItems.filter(item => item.kind === 'group' && item.tags?.includes(TAG)) + .map(item => ({ packId: item.id, title: item.title, actionCount: 0, selectedCount: 0 })) + const groups = new Map(packs.map(pack => [pack.packId, pack])) + const specs = new Map(snapshot.generationSpecs.map(spec => [spec.id, spec])) + const results = new Map(snapshot.results.map(result => [result.id, result])) + for (const item of snapshot.canvasItems) { + const group = groups.get(item.parentId) + const spec = item.binding?.role === 'generation' && specs.get(item.binding.objectRef?.id) + if (!group || !spec || !['image', 'video'].includes(item.kind)) continue + group.actionCount++ + if (results.get(spec.currentResultId)?.specId === spec.id) group.selectedCount++ + } + return { projectId: input.projectId, packs } + } + const operationId = input.operationId == null ? null : requireUuid(input.operationId, 'operationId') + if (input.packId == null && !operationId) throw new InputError('input.uuid', { field: 'packId' }) + const packId = action === 'prepare' || input.packId == null ? uuid5(operationId, 'action-pack') : requireUuid(input.packId, 'packId') + if (action === 'get' || action === 'check') { + const snapshot = await io.read() + const exists = snapshot.canvasItems.some(item => item.id === packId && item.tags?.includes(TAG)) + if (!exists && action === 'check') return { status: 'unknown', projectId: input.projectId, packId, found: false } + let status = 'applied', code + if (action === 'check' && ['generate', 'revise'].includes(input.packAction)) { + const ids = packItemIds(input) + const receipts = await Promise.all(ids.map(id => io.receipt(uuid5(operationId, (input.packAction === 'revise' ? 'action.revise:' : 'action:') + id)))) + const rejected = receipts.find(receipt => receipt?.status === 'rejected') + status = rejected ? 'rejected' : receipts.every(receipt => ['accepted', 'applied', 'noop'].includes(receipt?.status)) ? 'applied' : 'unknown' + code = rejected?.issues?.[0]?.code + } + return { ...packState(snapshot, packId, io.canRetry), status, found: true, ...(code && { code }) } + } + if (!operationId) throw new InputError('input.uuid', { field: 'operationId' }) + if (action === 'prepare') { + const prior = await io.receipt(uuid5(operationId, 'pack.prepare')) + if (prior) return { status: prior.status, packId, code: prior.issues?.[0]?.code } + const plan = validatePlan(input) + const models = await io.models() + const model = models.find(model => model.id === input.modelConfigId) + if (!model || !['image', 'video'].includes(model.kind) + || (model.kind === 'image' ? !(model.maxImages >= 1) : !model.videoChoices?.first_frame)) throw new InputError('pack.model') + let parameters + if (model.kind === 'image') { + parameters = imageOutputParameters(model.imageOutputs, input.output) + } else { + const video = model.videoChoices.first_frame + const durationSeconds = input.durationSeconds ?? video.defaultDuration + if (durationSeconds != null && !video.durations.includes(durationSeconds)) throw new InputError('creation.video_duration') + parameters = { videoMode: 'first_frame', resolution: video.resolution, + ...(durationSeconds != null && { durationSeconds }) } + } + if (plan.actions.some(action => Array.from(action.prompt).length > Math.min(model.maxPromptCharacters ?? 20000, 20000))) { + throw new InputError('pack.plan') + } + return io.edit(async (snapshot, execute) => { + if (snapshot.canvasItems.some(item => item.id === packId)) return { status: 'noop', packId } + const source = snapshot.results.find(result => result.id === input.sourceResultId)?.asset + if (source?.kind !== 'image') throw new InputError('result.candidate_missing') + const right = snapshot.canvasItems.filter(item => item.parentId == null) + .reduce((x, item) => Math.max(x, item.position.x + item.width + 48), 0) + const operations = [{ type: 'canvas.show', payload: { item: { + id: packId, projectId: input.projectId, kind: 'group', title: plan.title, tags: [TAG], + position: { x: right, y: 0 }, width: 1184, height: Math.ceil(plan.actions.length / 3) * 340 + 64, + binding: { role: 'container' }, + } } }] + plan.actions.forEach((action, index) => { + const { command } = buildCreateGeneration({ + projectId: input.projectId, operationId: uuid5(operationId, 'action.' + index), + kind: model.kind, modelConfigId: model.id, prompt: action.prompt, parameters, + position: { x: 24 + (index % 3) * 384, y: 48 + Math.floor(index / 3) * 340 }, + references: [{ binding: 'pinned', role: model.kind === 'video' ? 'first_frame' : 'reference', order: 0, source }], + }) + const { spec, item, references } = command.payload + item.parentId = packId + item.title = action.name + operations.push({ type: 'generationSpec.create', payload: { spec } }, + { type: 'canvas.show', payload: { item } }, + ...references.map(reference => ({ type: 'reference.add', payload: { reference } }))) + }) + const receipt = await execute({ commandId: uuid5(operationId, 'pack.prepare'), projectId: input.projectId, + type: 'creation.batch', expectedVersions: [], payload: { operations } }) + return { status: receipt.status, packId, code: receipt.issues?.[0]?.code } + }) + } + if (action === 'revise') { + const itemId = requireUuid(input.itemId, 'itemId') + const commandId = uuid5(operationId, 'action.revise:' + itemId) + const prior = await io.receipt(commandId) + if (prior) return { status: prior.status, packId, code: prior.issues?.[0]?.code } + const prompt = requireString(input.prompt, 'prompt').trim() + if (!prompt || Array.from(prompt).length > 20000) throw new InputError('pack.plan') + if (!Number.isInteger(input.expectedSpecRevision) || input.expectedSpecRevision < 1) { + throw new InputError('input.positiveInteger', { field: 'expectedSpecRevision' }) + } + return io.edit(async (snapshot, execute) => { + const { nodes, specs } = packNodes(snapshot, packId) + const item = nodes.find(item => item.id === itemId) + if (!item) throw new InputError('pack.missing') + const spec = specs.get(item.binding.objectRef.id) + if (spec.revision !== input.expectedSpecRevision) throw new InputError('revision_conflict') + if (snapshot.jobs.some(job => job.inputSnapshot.spec.id === spec.id && ['queued', 'running'].includes(job.status))) { + throw new InputError('pack.active') + } + const receipt = await execute({ commandId, projectId: input.projectId, type: 'generationSpec.update', + expectedVersions: [{ objectType: 'generation_spec', id: spec.id, revision: spec.revision }], + payload: { spec: { ...spec, prompt } } }) + return { status: receipt.status, packId, code: receipt.issues?.[0]?.code } + }) + } + if (action !== 'generate') throw new InputError('pack.action') + return io.edit(async (snapshot, execute) => { + const { nodes, specs } = packNodes(snapshot, packId) + const selected = packItemIds(input) + if (selected.some(id => !nodes.some(item => item.id === id))) throw new InputError('pack.missing') + const accepted = [] + let blocked, uncertain = false + for (const item of nodes) { + if (!selected.includes(item.id)) continue + const commandId = uuid5(operationId, 'action:' + item.id) + let prior + try { prior = await io.receipt(commandId) } + catch { uncertain = true; break } + if (prior) { + if (['accepted', 'applied', 'noop'].includes(prior.status)) accepted.push(...(prior.jobIds ?? [])) + else if (prior.status === 'rejected') { blocked = prior.issues?.[0]?.code; break } + continue + } + const spec = specs.get(item.binding.objectRef.id) + const jobs = snapshot.jobs.filter(job => job.inputSnapshot.spec.id === spec.id) + const latest = jobs.at(-1) + if (jobs.some(job => ['queued', 'running'].includes(job.status))) continue + if (latest && (!input.redo || (latest.status !== 'succeeded' && !io.canRetry(latest)))) continue + const command = buildSubmitCommand({ projectId: input.projectId, operationId: commandId, + specId: spec.id, originItemId: item.id, expectedSpecRevision: spec.revision, + expectedItemRevision: item.revision, + ...(latest && io.canRetry(latest) && { previousJobId: latest.id }) }) + try { + const receipt = await execute(command) + if (receipt.status === 'accepted') accepted.push(...receipt.jobIds) + else { blocked = receipt.issues?.[0]?.code ?? 'unavailable'; break } + } catch (error) { + if (!(error instanceof UnknownOperationError)) throw error + uncertain = true + break + } + } + return { status: uncertain ? 'unknown' : blocked ? 'rejected' : 'accepted', + packId, jobIds: accepted, ...(blocked && { code: blocked }) } + }) +} + +export async function actionPackArchive(input, io) { + const snapshot = await io.read() + const pack = packState(snapshot, input.packId, io.canRetry) + if (!pack.actions.length || pack.selectedCount !== pack.actions.length) throw new InputError('pack.incomplete') + const assets = new Map(snapshot.assets.map(asset => [asset.id, asset])) + const files = pack.actions.map((action, index) => { + const result = snapshot.results.find(result => result.id === action.selectedResultId && result.specId === action.specId) + const asset = result && assets.get(result.asset.assetId) + const extension = EXTENSIONS[asset?.metadata?.mimeType] + if (!asset || !extension) throw new InputError('pack.export') + const safeName = action.name.replace(/[<>:"/\\|?*\x00-\x1f]/g, '-').slice(0, 60).replace(/[ .]+$/g, '') || 'action' + const filename = String(index + 1).padStart(2, '0') + '-' + safeName + '.' + extension + const job = snapshot.jobs.find(job => job.id === result.jobId) + return { filename, assetId: asset.id, size: asset.metadata.size, kind: asset.kind, + manifest: { name: action.name, file: filename, resultId: result.id, jobId: result.jobId, + description: job?.inputSnapshot?.spec?.prompt ?? action.prompt, + model: job?.inputSnapshot?.model?.modelId, fingerprint: asset.fingerprint } } + }) + const manifest = { version: 1, project: pack.projectName, pack: pack.title, + actions: files.map(file => file.manifest) } + const description = new TextEncoder().encode(JSON.stringify(manifest, null, 2) + '\n') + if (description.length + files.reduce((sum, file) => sum + (file.size ?? 0), 0) > LIMIT) throw new InputError('pack.too_large') + async function* entries() { + yield { name: 'manifest.json', data: description } + for (const file of files) { + const media = await io.media(file.assetId, file.kind) + yield { name: file.filename, data: media.body } + } + } + return { entries: entries(), filename: 'action-pack-' + input.packId.slice(0, 8) + '.zip', maxBytes: LIMIT } +} diff --git a/plugins/deepseek-harness/src/archive.js b/plugins/deepseek-harness/src/archive.js new file mode 100644 index 000000000..0d0e8ff2b --- /dev/null +++ b/plugins/deepseek-harness/src/archive.js @@ -0,0 +1,175 @@ +import { crc32 } from 'node:zlib' + +const CHUNK_SIZE = 64 * 1024 +const MAX_ENTRIES = 0xffff +const MAX_NAME_BYTES = 255 +const FLAGS = 0x0808 +const DOS_TIME = 0 +const DOS_DATE = 0x0021 +const EMPTY = Buffer.alloc(0) + +function abortReason(signal) { + return signal?.reason instanceof Error + ? signal.reason + : new DOMException('The operation was aborted', 'AbortError') +} + +function throwIfAborted(signal) { + if (signal?.aborted) throw abortReason(signal) +} + +function asChunk(value) { + if (!(value instanceof Uint8Array)) throw new TypeError('entry data chunks must be Uint8Array') + return value +} + +function validateName(name, seen) { + if (typeof name !== 'string' || name === '' || name === '.' || name === '..') { + throw new TypeError('entry name must be a non-empty basename') + } + if (/[\\/]|\p{Cc}/u.test(name)) throw new TypeError('entry name must not contain slashes or control characters') + const bytes = Buffer.from(name, 'utf8') + if (bytes.length > MAX_NAME_BYTES) throw new RangeError('entry name exceeds 255 UTF-8 bytes') + const key = bytes.toString('hex') + if (seen.has(key)) throw new TypeError(`duplicate entry name: ${name}`) + seen.add(key) + return bytes +} + +function build(size, name, fields) { + const buffer = Buffer.alloc(size + name.length) + for (const [offset, value, width] of fields) { + if (width === 4) buffer.writeUInt32LE(value, offset) + else buffer.writeUInt16LE(value, offset) + } + name.copy(buffer, size) + return buffer +} + +function localHeader(name) { + return build(30, name, [ + [0, 0x04034b50, 4], [4, 20, 2], [6, FLAGS, 2], [8, 0, 2], + [10, DOS_TIME, 2], [12, DOS_DATE, 2], [26, name.length, 2], + ]) +} + +function dataDescriptor(crc, size) { + return build(16, EMPTY, [ + [0, 0x08074b50, 4], [4, crc, 4], [8, size, 4], [12, size, 4], + ]) +} + +function centralHeader({ name, crc, size, offset }) { + return build(46, name, [ + [0, 0x02014b50, 4], [4, 20, 2], [6, 20, 2], [8, FLAGS, 2], [10, 0, 2], + [12, DOS_TIME, 2], [14, DOS_DATE, 2], [16, crc, 4], [20, size, 4], + [24, size, 4], [28, name.length, 2], [42, offset, 4], + ]) +} + +function endOfCentralDirectory(count, size, offset) { + return build(22, EMPTY, [ + [0, 0x06054b50, 4], [8, count, 2], [10, count, 2], [12, size, 4], [16, offset, 4], + ]) +} + +function raceAbort(promise, signal) { + if (!signal) return promise + if (signal.aborted) return Promise.reject(abortReason(signal)) + return new Promise((resolve, reject) => { + const onAbort = () => reject(abortReason(signal)) + signal.addEventListener('abort', onAbort, { once: true }) + promise.then( + value => { signal.removeEventListener('abort', onAbort); resolve(value) }, + error => { signal.removeEventListener('abort', onAbort); reject(error) }, + ) + }) +} + +async function* chunksOf(data, signal) { + if (data instanceof Uint8Array) { + if (data.length > 0) yield data + return + } + const reader = data && typeof data.getReader === 'function' ? data.getReader() : null + const iterator = reader || !data || typeof data[Symbol.asyncIterator] !== 'function' + ? null + : data[Symbol.asyncIterator]() + if (!reader && !iterator) { + throw new TypeError('entry.data must be a Uint8Array, ReadableStream, or AsyncIterable') + } + let complete = false + try { + while (true) { + throwIfAborted(signal) + const result = await raceAbort(reader ? reader.read() : iterator.next(), signal) + if (result.done) { complete = true; break } + yield asChunk(result.value) + } + } finally { + if (!complete) { + try { + if (reader) await reader.cancel(signal?.reason) + else if (typeof iterator.return === 'function') await iterator.return() + } catch {} + } + if (reader) try { reader.releaseLock() } catch {} + } +} + +export async function* zipEntries(entries, { signal, maxBytes = 128 * 1024 * 1024 } = {}) { + if (entries == null || (typeof entries[Symbol.iterator] !== 'function' && typeof entries[Symbol.asyncIterator] !== 'function')) { + throw new TypeError('entries must be iterable or async iterable') + } + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) { + throw new TypeError('maxBytes must be a non-negative safe integer') + } + throwIfAborted(signal) + const central = [] + const names = new Set() + let offset = 0 + let total = 0 + for await (const entry of entries) { + throwIfAborted(signal) + if (entry == null || typeof entry !== 'object') throw new TypeError('entry must be an object') + const name = validateName(entry.name, names) + if (central.length === MAX_ENTRIES) throw new RangeError('ZIP32 supports at most 65535 entries') + const localOffset = offset + const header = localHeader(name) + offset += header.length + yield header + let crc = 0 + let size = 0 + for await (const chunk of chunksOf(entry.data, signal)) { + throwIfAborted(signal) + if (size + chunk.length > 0xffffffff) throw new RangeError('entry exceeds ZIP32 size limit') + total += chunk.length + if (total > maxBytes) throw new RangeError(`archive exceeds maxBytes (${maxBytes})`) + size += chunk.length + crc = crc32(chunk, crc) >>> 0 + for (let start = 0; start < chunk.length; start += CHUNK_SIZE) { + throwIfAborted(signal) + const slice = chunk.subarray(start, Math.min(start + CHUNK_SIZE, chunk.length)) + offset += slice.length + yield slice + } + } + throwIfAborted(signal) + const descriptor = dataDescriptor(crc, size) + offset += descriptor.length + yield descriptor + central.push({ name, crc, size, offset: localOffset }) + } + throwIfAborted(signal) + const centralOffset = offset + let centralSize = 0 + for (const entry of central) { + throwIfAborted(signal) + const record = centralHeader(entry) + centralSize += record.length + offset += record.length + yield record + } + throwIfAborted(signal) + yield endOfCentralDirectory(central.length, centralSize, centralOffset) +} diff --git a/plugins/deepseek-harness/src/client.js b/plugins/deepseek-harness/src/client.js index dec780127..0e5b0009f 100644 --- a/plugins/deepseek-harness/src/client.js +++ b/plugins/deepseek-harness/src/client.js @@ -1,11 +1,18 @@ import { randomUUID } from 'node:crypto' +import { mediaDetails, resultMediaDetails } from './presentation.js' +import { resultVersionInfo } from './versions.js' +import { actionPackRequest, actionPackArchive } from './action-packs.js' import { buildCreateGeneration, buildJobCancelCommand, buildProjectCreateCommand, buildResultSelectCommand, buildSubmitCommand, + imageOutputParameters, requireUuid, + requireString, + requireEnum, + uuid5, } from './operations.js' import { HttpError, @@ -17,6 +24,14 @@ import { } from './errors.js' const PROJECTS = '/api/creation/projects' +const PROMPT_LIMIT = 20000 +const LIBRARY_PAGE_SIZE = 12 +const RETRYABLE_FAILURES = new Set(['quota', 'rate_limit', 'authentication', 'permission', 'temporary', 'provider']) +const MEDIA_TYPES = { + image: ['image/webp', 'image/png', 'image/jpeg', 'image/gif', 'image/avif'], + video: ['video/mp4', 'video/webm', 'video/quicktime'], + audio: ['audio/mpeg', 'audio/wav', 'audio/x-wav', 'audio/mp4', 'audio/ogg', 'audio/flac', 'audio/aac', 'audio/webm'], +} export function joinUrl(baseUrl, path) { return `${baseUrl.replace(/\/+$/, '')}/${String(path).replace(/^\/+/, '')}` @@ -26,6 +41,70 @@ function creationPath(projectId) { return `${PROJECTS}/${projectId}` } +function canRetryFailedJob(job) { + return job?.status === 'failed' && job.recovery === 'retry' && !job.cancelRequested + && RETRYABLE_FAILURES.has(job.errorDetails?.category) +} + +function librarySearch(snapshot, query) { + if (typeof query !== 'string' || query.length > 200) throw new InputError('library.search') + const normalize = value => value.normalize('NFKC').toLowerCase() + const terms = normalize(query).trim().split(/\s+/).filter(Boolean) + const titles = new Map() + for (const item of snapshot.canvasItems ?? []) { + if (item.binding?.role !== 'generation' || !item.title) continue + const specId = item.binding.objectRef.id + titles.set(specId, [titles.get(specId), item.title].filter(Boolean).join(' · ')) + } + return { + title: specId => titles.get(specId), + matches: (prompt, title, modelId, ...ids) => { + if (!terms.length) return true + const text = normalize([prompt, title, modelId].filter(value => typeof value === 'string').join('\n')) + return terms.every(term => text.includes(term)) + || (terms.length === 1 && terms[0].length >= 8 && ids.some(id => id?.startsWith(terms[0]))) + }, + } +} + +function savedResultCards(snapshot, search, jobs, versionOptions) { + const specs = new Map(snapshot.generationSpecs.map(spec => [spec.id, spec])) + const selected = result => specs.get(result.specId)?.currentResultId === result.id + const detailsFor = resultMediaDetails(snapshot, jobs) + const versions = resultVersionInfo(snapshot, versionOptions) + function card(result, promptLimit) { + const { id, specId, jobId, asset } = result + const prompt = jobs.get(jobId)?.inputSnapshot?.spec?.prompt ?? '' + const title = search.title(specId) + const details = detailsFor(result) + return { + resultId: id, specId, assetId: asset.assetId, kind: asset.kind, selected: selected(result), + ...(versions.get(id) ?? {}), ...(details && { details }), ...(title && { title }), + prompt: prompt.slice(0, promptLimit), + } + } + return { selected, card } +} + +function creationSeed(snapshot, resultId, model) { + const result = snapshot.results.find(item => item.id === resultId) + const job = snapshot.jobs.find(item => item.id === result?.jobId) + const spec = job?.inputSnapshot?.spec + if (!spec || job.status !== 'succeeded' || !['image', 'audio'].includes(spec.kind) + || spec.kind !== model?.kind || spec.modelConfigId !== model.id + || job.inputSnapshot.model.modelId !== model.modelId + || job.inputSnapshot.model.protocol !== model.protocol) throw new InputError('creation.template_unavailable') + const references = job.inputSnapshot.references ?? [] + if (spec.promptContent != null || references.some(ref => ref.role !== 'reference' + || ref.documentVersion || ref.subjectRole || (ref.transmission && ref.transmission !== 'content'))) { + throw new InputError('creation.template_complex') + } + if (spec.kind === 'image' && references.filter(ref => ref.asset.kind === 'image').length > model.maxImages) { + throw new InputError('creation.reference_limit') + } + return { spec, references } +} + function resultReference(input) { if (input.sourceResultId === undefined) return undefined const resultId = requireUuid(input.sourceResultId, 'sourceResultId') @@ -38,6 +117,21 @@ function resultReference(input) { throw new InputError('result.source_mode') } +function videoChoices(inputRules) { + const modes = inputRules?.videoModes ?? [] + const caps = inputRules?.videoCapabilities + const choices = {} + for (const mode of ['first_frame', 'continuation']) { + if (!modes.includes(mode)) continue + if (mode === 'first_frame' && (!inputRules.allowedKinds?.includes('image') || !inputRules.maxImages)) continue + const resolution = mode === 'first_frame' ? caps?.defaultResolution ?? 'auto' : 'auto' + const outputs = caps?.outputs.filter(output => resolution === 'auto' || output.resolution === resolution) ?? [] + const durations = [...new Set(outputs.flatMap(output => output.durations))].sort((a, b) => a - b) + choices[mode] = { durations, resolution, defaultDuration: caps?.defaultDuration ?? null } + } + return choices +} + function responseError(response, payload, text) { const detail = typeof payload?.detail === 'string' ? payload.detail @@ -93,7 +187,7 @@ export class OpenDirectorClient { } async #request(method, path, { - body, session = randomUUID(), signal, timeoutMs = this.requestTimeoutMs, mediaType, range, + body, session = randomUUID(), signal, timeoutMs = this.requestTimeoutMs, mediaType, allowedMediaTypes = [mediaType], range, } = {}) { const url = joinUrl(this.baseUrl, path) const headers = { @@ -132,9 +226,7 @@ export class OpenDirectorClient { } if (mediaType && (response.ok || response.status === 416)) { const type = response.headers.get('content-type')?.split(';', 1)[0] - if (response.ok && (mediaType === 'video/*' - ? !['video/mp4', 'video/webm', 'video/quicktime'].includes(type) - : type !== mediaType)) { + if (response.ok && !allowedMediaTypes.includes(type)) { await response.body?.cancel() throw new HttpError({ status: 502, code: 'invalid_media', detail: 'Unexpected OpenDirector media type.' }) } @@ -222,6 +314,27 @@ export class OpenDirectorClient { } } + actionPack(input, { signal } = {}) { + return this.#actionPackIO(input, signal, actionPackRequest) + } + + actionPackArchive(input, { signal } = {}) { + return this.#actionPackIO(input, signal, actionPackArchive) + } + + #actionPackIO(input, signal, run) { + const projectId = requireUuid(input.projectId, 'projectId') + return run({ ...input, projectId }, { + read: () => this.project(projectId, { signal }), + models: () => this.creationModels({ signal }), + receipt: id => this.receipt(projectId, id, { signal }), + canRetry: canRetryFailedJob, + media: (assetId, kind) => this.media(projectId, assetId, { kind, original: true, signal }), + edit: action => this.#withLease(projectId, signal, (session, snapshot) => action(snapshot, + command => this.#command({ projectId, operationId: command.commandId, command, session, signal }))), + }) + } + async listProjects({ signal } = {}) { return this.#request('GET', PROJECTS, { signal }) } @@ -231,17 +344,145 @@ export class OpenDirectorClient { return this.#request('GET', creationPath(id), { signal }) } + async libraryResults(projectId, { kind = 'all', selection = 'all', order = 'newest', query = '', after, signal } = {}) { + requireEnum(kind, 'kind', ['all', ...Object.keys(MEDIA_TYPES)]) + requireEnum(selection, 'selection', ['all', 'current', 'other']) + requireEnum(order, 'order', ['newest', 'oldest']) + const cursor = after == null ? null : requireUuid(after, 'after') + const snapshot = await this.project(projectId, { signal }) + const search = librarySearch(snapshot, query) + const jobs = new Map(snapshot.jobs.map(job => [job.id, job])) + const cards = savedResultCards(snapshot, search, jobs) + const results = [] + const step = order === 'oldest' ? 1 : -1 + const cursorIndex = cursor === null ? null : snapshot.results.findIndex(result => result.id === cursor) + if (cursorIndex === -1) throw new InputError('library.cursor_expired') + const start = cursorIndex === null ? (step === 1 ? 0 : snapshot.results.length - 1) : cursorIndex + step + // Registration order is stable even when jobs finish out of order. + for (let index = start; index >= 0 && index < snapshot.results.length && results.length <= LIBRARY_PAGE_SIZE; index += step) { + const result = snapshot.results[index] + const { id, specId, jobId, asset } = result + if (!Object.hasOwn(MEDIA_TYPES, asset.kind) || (kind !== 'all' && asset.kind !== kind)) continue + const selected = cards.selected(result) + if ((selection === 'current' && !selected) || (selection === 'other' && selected)) continue + const job = jobs.get(jobId) + const prompt = job?.inputSnapshot?.spec?.prompt ?? '' + const title = search.title(specId) + if (!search.matches(prompt, title, job?.inputSnapshot?.model?.modelId, id, jobId, specId)) continue + results.push(cards.card(result, 160)) + } + const hasMore = results.length > LIBRARY_PAGE_SIZE + if (hasMore) results.pop() + return { projectId, projectName: snapshot.project.name, canvasUrl: this.canvasUrl(projectId), results, + nextCursor: hasMore ? results.at(-1).resultId : null } + } + async models({ signal } = {}) { return this.#request('GET', '/api/model-configs', { signal }) } - async media(projectId, assetId, { kind, range, signal } = {}) { + async libraryJobs(projectId, { kind = 'all', order = 'newest', status = 'all', query = '', after, signal } = {}) { + requireEnum(kind, 'kind', ['all', ...Object.keys(MEDIA_TYPES)]) + requireEnum(order, 'order', ['newest', 'oldest']) + const cursor = after == null ? null : requireUuid(after, 'after') + const snapshot = await this.project(projectId, { signal }) + requireEnum(status, 'status', ['all', 'active', 'succeeded', 'failed', 'cancelled', 'interrupted']) + const search = librarySearch(snapshot, query) + const cursorIndex = cursor === null ? null : snapshot.jobs.findIndex(job => job.id === cursor) + if (cursorIndex === -1) throw new InputError('library.cursor_expired') + const step = order === 'oldest' ? 1 : -1 + const start = cursorIndex === null ? (step === 1 ? 0 : snapshot.jobs.length - 1) : cursorIndex + step + const jobs = [] + for (let index = start; index >= 0 && index < snapshot.jobs.length && jobs.length <= LIBRARY_PAGE_SIZE; index += step) { + const job = snapshot.jobs[index] + const spec = job.inputSnapshot.spec + if (!Object.hasOwn(MEDIA_TYPES, spec.kind) || (kind !== 'all' && spec.kind !== kind)) continue + if (status === 'active' ? !['queued', 'running'].includes(job.status) + : status !== 'all' && job.status !== status) continue + const title = search.title(spec.id) + if (!search.matches(spec.prompt, title, job.inputSnapshot.model.modelId, job.id, spec.id)) continue + jobs.push({ + jobId: job.id, kind: spec.kind, status: job.status, prompt: spec.prompt.slice(0, 160), + ...(job.batchId && { groupId: job.batchId }), + ...(title && { title }), + modelId: job.inputSnapshot.model.modelId, + }) + } + const hasMore = jobs.length > LIBRARY_PAGE_SIZE + if (hasMore) jobs.pop() + return { projectId, projectName: snapshot.project.name, canvasUrl: this.canvasUrl(projectId), jobs, + nextCursor: hasMore ? jobs.at(-1).jobId : null } + } + + async creationModels({ signal } = {}) { + const models = await this.models({ signal }) + return models.filter(model => (model.kind === 'image' && model.protocol !== 'vllm_omni_segmentation') + || (model.kind === 'audio' && !['vllm_omni_music', 'vllm_omni_score'].includes(model.protocol)) + || (model.kind === 'video' && Object.keys(videoChoices(model.inputRules)).length > 0)) + .map(({ id, kind, modelId, protocol, connectionType, inputRules }) => ({ + id, kind, modelId, protocol, connectionType, + imageOutputs: inputRules?.imageOutputs ?? [], + maxImages: inputRules?.allowedKinds?.includes('image') ? (inputRules.maxImages ?? 0) : 0, + voiceRequired: inputRules?.voiceRequired === true, + maxPromptCharacters: inputRules?.maxPromptCharacters, + ...(kind === 'video' && { videoChoices: videoChoices(inputRules) }), + })) + } + + async #readResultCards(projectId, resultIds, signal, imagesOnly) { + const project = requireUuid(projectId, 'projectId') + const errorKey = imagesOnly ? 'library.compare' : 'library.results' + if (!Array.isArray(resultIds) || resultIds.length < 1 || resultIds.length > 4 + || (imagesOnly && resultIds.length !== 2)) throw new InputError(errorKey) + const ids = resultIds.map(id => requireUuid(id, 'resultId')) + if (new Set(ids).size !== ids.length) throw new InputError(errorKey) + const snapshot = await this.project(project, { signal }) + const jobs = new Map(snapshot.jobs.map(job => [job.id, job])) + const byId = new Map(snapshot.results.map(result => [result.id, result])) + const cards = savedResultCards(snapshot, librarySearch(snapshot, ''), jobs, { includeFirstFrameUsage: !imagesOnly }) + const results = ids.map(id => { + const result = byId.get(id) + const kind = result?.asset?.kind + if (imagesOnly ? kind !== 'image' : !Object.hasOwn(MEDIA_TYPES, kind)) throw new InputError(errorKey) + return cards.card(result, imagesOnly ? 500 : undefined) + }) + return { projectId: project, projectName: snapshot.project.name, canvasUrl: this.canvasUrl(project), results } + } + + showResults(projectId, resultIds, { signal } = {}) { + return this.#readResultCards(projectId, resultIds, signal, false) + } + + async compareImages(projectId, resultIds, { signal } = {}) { + const saved = await this.#readResultCards(projectId, resultIds, signal, true) + return { projectId: saved.projectId, canvasUrl: saved.canvasUrl, + images: saved.results.map(image => ({ title: '', ...image })) } + } + + async creationTemplate(projectId, resultId, { signal } = {}) { + const project = requireUuid(projectId, 'projectId') + const id = requireUuid(resultId, 'resultId') + const [snapshot, models] = await Promise.all([this.project(project, { signal }), this.creationModels({ signal })]) + const jobId = snapshot.results.find(item => item.id === id)?.jobId + const spec = snapshot.jobs.find(job => job.id === jobId)?.inputSnapshot?.spec + const model = models.find(item => item.id === spec?.modelConfigId) + const seed = creationSeed(snapshot, id, model) + return { + kind: seed.spec.kind, modelConfigId: seed.spec.modelConfigId, prompt: seed.spec.prompt, + voice: seed.spec.parameters.voice ?? '', + originalOutput: [seed.spec.parameters.size, seed.spec.parameters.aspectRatio].filter(Boolean).join(' · '), + references: seed.references.map(({ asset, metadata }) => ({ assetId: asset.assetId, kind: asset.kind, details: mediaDetails(metadata) })), + } + } + + async media(projectId, assetId, { kind, original, range, signal } = {}) { const project = requireUuid(projectId, 'projectId') const asset = requireUuid(assetId, 'assetId') - if (kind !== 'image' && kind !== 'video') throw new InputError('input.enum', { field: 'kind', values: 'image|video' }) - const video = kind === 'video' - return this.#request('GET', `${creationPath(project)}/assets/${asset}/${video ? 'content' : 'thumbnail'}`, { - signal, mediaType: video ? 'video/*' : 'image/webp', range: video ? range : undefined, + if (!Object.hasOwn(MEDIA_TYPES, kind)) throw new InputError('input.enum', { field: 'kind', values: 'image|video|audio' }) + const thumbnail = kind === 'image' && !original + return this.#request('GET', `${creationPath(project)}/assets/${asset}/${thumbnail ? 'thumbnail' : 'content'}`, { + signal, mediaType: thumbnail ? 'image/webp' : `${kind}/*`, + allowedMediaTypes: thumbnail ? ['image/webp'] : MEDIA_TYPES[kind], range: thumbnail ? undefined : range, timeoutMs: Math.min(this.requestTimeoutMs, 5000), }) } @@ -254,16 +495,127 @@ export class OpenDirectorClient { ? snapshot.jobs.find((item) => item.id === job) : undefined if (!value) throw new InputError('job.missing', { jobId: job, projectId: id }) + const versions = resultVersionInfo(snapshot) const results = Array.isArray(snapshot?.results) - ? snapshot.results.filter((item) => item.jobId === job) + ? snapshot.results.filter((item) => item.jobId === job).map(item => ({ ...item, ...versions.get(item.id) })) : [] + const detailsFor = resultMediaDetails(snapshot) + const resultDetails = Object.fromEntries(results.flatMap(result => { + const details = detailsFor(result) + return details ? [[result.asset.assetId, details]] : [] + })) return { job: value, results, projectName: snapshot.project.name, + ...(Object.keys(resultDetails).length && { resultDetails }), registered: results.length > 0, adopted: snapshot.generationSpecs.some(spec => results.some(result => result.id === spec.currentResultId)), } } + async creationStatus(projectId, jobId, { signal } = {}) { + const project = requireUuid(projectId, 'projectId') + const id = requireUuid(jobId, 'jobId') + const job = await this.#request('POST', `${creationPath(project)}/queries`, { + body: { type: 'job.get', projectId: project, queryId: randomUUID(), objectId: id }, signal, + }) + const cancellation = job.cancelRequested + ? { cancelRequested: true, remoteCancellation: job.remoteCancellation } : {} + if (job.status !== 'succeeded') { + return { + status: job.status, ...cancellation, + category: job.errorDetails?.category, + ...(canRetryFailedJob(job) && { canRetry: true }), + ...(job.resumeAllowed && ['failed', 'interrupted'].includes(job.status) && { canResume: true }), + } + } + const snapshot = await this.project(project, { signal }) + const specId = job.inputSnapshot.spec.id + const selected = snapshot.generationSpecs.find(spec => spec.id === specId)?.currentResultId + const detailsFor = resultMediaDetails(snapshot) + const versions = resultVersionInfo(snapshot) + return { + status: job.status, ...cancellation, + results: snapshot.results.filter(result => result.specId === specId).map(result => { + const { id, asset } = result + const details = detailsFor(result) + return { resultId: id, assetId: asset.assetId, kind: asset.kind, selected: id === selected, + ...(versions.get(id) ?? {}), + ...(details && { details }) } + }), + } + } + + async creationGroupStatus(projectId, groupId, { signal } = {}) { + const project = requireUuid(projectId, 'projectId') + const group = requireUuid(groupId, 'groupId') + const snapshot = await this.project(project, { signal }) + const jobs = snapshot.jobs.filter(job => job.batchId === group) + if (!jobs.length) throw new InputError('job.missing', { projectId: project, jobId: group }) + const active = jobs.some(job => ['queued', 'running'].includes(job.status)) + const done = jobs.filter(job => job.status === 'succeeded').length + const failed = jobs.filter(job => ['failed', 'interrupted'].includes(job.status)).length + const status = active ? 'running' : done ? 'succeeded' + : jobs.every(job => job.status === 'cancelled') ? 'cancelled' : 'failed' + const ids = new Set(jobs.map(job => job.id)) + const selected = new Set(snapshot.generationSpecs.map(spec => spec.currentResultId)) + const detailsFor = resultMediaDetails(snapshot) + const versions = resultVersionInfo(snapshot) + return { + groupId: group, status, completedCount: done, failedCount: failed, totalCount: jobs.length, + jobs: jobs.map(job => ({ jobId: job.id, status: job.status, cancelRequested: job.cancelRequested, + remoteCancellation: job.remoteCancellation, category: job.errorDetails?.category })), + results: snapshot.results.filter(result => ids.has(result.jobId)).map(result => ({ + resultId: result.id, assetId: result.asset.assetId, kind: result.asset.kind, selected: selected.has(result.id), + ...(versions.get(result.id) ?? {}), details: detailsFor(result), + })), + } + } + + async #startCandidateGroup(input, signal) { + const projectId = requireUuid(input.projectId, 'projectId') + const groupId = requireUuid(input.operationId, 'operationId') + const count = input.candidateCount + const accepted = [] + let blocked + for (let index = 0; index < count; index++) { + const child = uuid5(groupId, 'candidate.' + index) + let reply = await this.receipt(projectId, uuid5(child, 'creation.submit'), { signal }) + if (!reply && !input.check) { + try { + if (index === 0 && input.continueGroup) break + const { candidateCount, continueGroup, check, ...base } = input + reply = await this.startCreation(index === 0 + ? { ...base, operationId: child, batchId: groupId } + : { projectId, operationId: child, repeatJobId: accepted[0], batchId: groupId }, { signal }) + } catch (error) { + if (error instanceof UnknownOperationError || error instanceof NetworkError || error instanceof RequestTimeoutError + || error instanceof RequestAbortedError) break + blocked = error instanceof InputError ? error.key : error instanceof HttpError ? error.code : 'unavailable' + break + } + } + const jobId = reply?.jobId ?? reply?.jobIds?.[0] + if (jobId && ['accepted', 'applied', 'noop'].includes(reply.status)) { + accepted.push(jobId) + } else if (reply?.status === 'rejected') { + blocked = reply.code ?? reply.issues?.[0]?.code ?? 'unavailable' + break + } else break + } + const complete = accepted.length === count || blocked != null + const firstDraft = input.check && !accepted.length + ? await this.receipt(projectId, uuid5(uuid5(groupId, 'candidate.0'), 'creation.draft'), { signal }) : null + return { + status: blocked ? 'rejected' : complete ? 'accepted' : 'unknown', + groupId, requestedCount: count, acceptedCount: accepted.length, + jobId: accepted[0], jobIds: accepted, groupComplete: complete, + ...(firstDraft?.status === 'applied' && { draftSaved: true }), + ...(input.projectName != null && { projectCreated: true }), + ...(blocked && { code: blocked }), + ...(!complete && accepted.length > 0 && { canContinueGroup: true }), + } + } + async receipt(projectId, operationId, { signal } = {}) { const id = requireUuid(projectId, 'projectId') const command = requireUuid(operationId, 'operationId') @@ -275,6 +627,14 @@ export class OpenDirectorClient { } } + async #submissionReceipt(projectId, operationId, signal) { + try { + return await this.receipt(projectId, operationId, { signal }) + } catch (cause) { + throw new UnknownOperationError({ projectId, operationId, cause }) + } + } + async createProject({ name, projectId, operationId, signal } = {}) { const command = buildProjectCreateCommand({ name, projectId, operationId }) return this.#command({ @@ -314,10 +674,213 @@ export class OpenDirectorClient { return this.#write(buildSubmitCommand(input), input.signal) } + async startCreation(input, { signal } = {}) { + const count = input.candidateCount ?? 1 + if (!Number.isInteger(count) || count < 1 || count > 4) throw new InputError('creation.candidate_count') + if (count > 1) return this.#startCandidateGroup(input, signal) + if (input.batchId != null) requireUuid(input.batchId, 'batchId') + const projectId = requireUuid(input.projectId, 'projectId') + const intent = requireUuid(input.operationId, 'operationId') + const createId = uuid5(intent, 'creation.draft') + const submitId = uuid5(intent, 'creation.submit') + if (input.check === true) { + const submitted = await this.receipt(projectId, submitId, { signal }) + if (submitted) return { status: submitted.status, jobId: submitted.jobIds?.[0], code: submitted.issues?.[0]?.code, + ...(input.repeatJobId == null && submitted.status === 'rejected' && { draftSaved: true }), + ...(input.projectName != null && { projectCreated: true }) } + if (input.repeatJobId != null) return { status: 'unknown' } + const draft = await this.receipt(projectId, createId, { signal }) + return draft?.status === 'rejected' + ? { status: 'rejected', code: draft.issues?.[0]?.code, ...(input.projectName != null && { projectCreated: true }) } + : { status: 'unknown', draftSaved: draft?.status === 'applied' } + } + if (input.repeatJobId != null) { + return this.#repeatCreation(projectId, submitId, requireUuid(input.repeatJobId, 'repeatJobId'), signal, input.batchId) + } + const prompt = requireString(input.prompt, 'prompt').trim() + const modelConfigId = requireUuid(input.modelConfigId, 'modelConfigId') + const model = (await this.creationModels({ signal })).find(item => item.id === modelConfigId) + if (!model || model.kind !== input.kind) throw new InputError('creation.model') + if (!prompt || Array.from(prompt).length > Math.min(model.maxPromptCharacters ?? PROMPT_LIMIT, PROMPT_LIMIT)) { + throw new InputError('creation.prompt') + } + const values = input.sourceResultIds ?? (input.sourceResultId == null ? [] : [input.sourceResultId]) + if (!Array.isArray(values) || (input.sourceResultIds != null && input.sourceResultId != null)) { + throw new InputError('creation.references') + } + const reuseResultId = input.reuseResultId == null ? null : requireUuid(input.reuseResultId, 'reuseResultId') + if (reuseResultId && (values.length || input.projectName != null || model.kind === 'video')) { + throw new InputError('creation.template_unavailable') + } + const isVideo = model.kind === 'video' + const video = isVideo && Object.hasOwn(model.videoChoices, input.videoMode) && model.videoChoices[input.videoMode] + if (isVideo && !video) throw new InputError('creation.video_mode') + if (isVideo && values.length !== 1) throw new InputError('creation.video_source') + if (!isVideo && values.length && (model.kind !== 'image' || values.length > model.maxImages)) { + throw new InputError('creation.reference_limit') + } + const sourceIds = values.map(id => requireUuid(id, 'sourceResultIds')) + if (new Set(sourceIds).size !== sourceIds.length) throw new InputError('creation.references') + let parameters + const videoSource = isVideo && resultReference({ + kind: 'video', sourceResultId: sourceIds[0], parameters: { videoMode: input.videoMode }, + }) + if (reuseResultId && (model.kind === 'audio' || input.output == null)) parameters = {} + else if (model.kind === 'image') { + parameters = imageOutputParameters(model.imageOutputs, input.output) + } else if (video) { + const durationSeconds = input.durationSeconds ?? video.defaultDuration + if (durationSeconds !== null && !video.durations.includes(durationSeconds)) throw new InputError('creation.video_duration') + parameters = { videoMode: input.videoMode, resolution: video.resolution, ...(durationSeconds !== null && { durationSeconds }) } + } else { + const voice = typeof input.voice === 'string' ? input.voice.trim() : '' + if ((model.voiceRequired && !voice) || voice.length > 200) throw new InputError('creation.voice') + parameters = { creationType: 'audio', ...(voice && { voice }) } + } + if (input.projectName != null) { + if (sourceIds.length) throw new InputError('creation.references') + const project = await this.createProject({ + projectId, name: input.projectName, operationId: uuid5(intent, 'creation.project'), signal, + }) + if (project.status !== 'applied' && project.status !== 'noop') { + return { status: 'rejected', code: project.issues?.[0]?.code } + } + } + const started = await this.#withLease(projectId, signal, async (session, snapshot) => { + const existing = snapshot.generationSpecs.some(spec => spec.id === uuid5(createId, 'spec')) + if (existing) { + const receipt = await this.#submissionReceipt(projectId, submitId, signal) + return receipt ? { status: receipt.status, jobId: receipt.jobIds?.[0], code: receipt.issues?.[0]?.code, + ...(receipt.status === 'rejected' && { draftSaved: true }) } + : { status: 'unknown', draftSaved: true } + } + const seed = reuseResultId ? creationSeed(snapshot, reuseResultId, model) : null + let references = sourceIds.map((id, order) => { + const source = snapshot.results.find(result => result.id === id)?.asset + if (source?.kind !== (videoSource?.kind ?? 'image')) { + throw new InputError(isVideo ? 'creation.video_source' : 'result.candidate_missing') + } + return { binding: 'pinned', role: videoSource?.role ?? 'reference', order, source } + }) + if (seed) { + if (model.kind === 'audio' && input.voice != null && input.voice !== (seed.spec.parameters.voice ?? '')) { + throw new InputError('creation.template_unavailable') + } + const inherited = { ...seed.spec.parameters } + if (model.kind === 'image' && input.output != null) { + delete inherited.size + delete inherited.aspectRatio + } + parameters = { ...inherited, ...parameters } + references = seed.references.map((ref, order) => ({ + binding: 'pinned', role: ref.role, order, source: ref.asset, + ...(ref.sourceVersion && { sourceVersion: ref.sourceVersion }), + })) + } + if (new Set(references.map(reference => reference.source.assetId)).size !== references.length) { + throw new InputError('creation.references') + } + const right = snapshot.canvasItems.filter(item => item.parentId == null) + .reduce((x, item) => Math.max(x, item.position.x + item.width + 48), 0) + const { command, specId, itemId } = buildCreateGeneration({ + projectId, operationId: createId, kind: model.kind, modelConfigId, prompt, parameters, + position: { x: right, y: 0 }, + references, + }) + const draft = await this.#command({ projectId, operationId: createId, command, session, signal }) + if (draft.status !== 'applied') return { status: 'rejected', code: draft.issues?.[0]?.code } + const submit = buildSubmitCommand({ + projectId, operationId: submitId, specId, originItemId: itemId, + expectedSpecRevision: draft.changed.find(item => item.id === specId)?.revision, + expectedItemRevision: draft.changed.find(item => item.id === itemId)?.revision, + batchId: input.batchId, + }) + try { + const accepted = await this.#command({ projectId, operationId: submitId, command: submit, session, signal }) + return { status: accepted.status, jobId: accepted.jobIds?.[0], code: accepted.issues?.[0]?.code, draftSaved: true } + } catch (error) { + if (error instanceof HttpError) return { status: 'rejected', code: error.code, draftSaved: true } + throw error + } + }).catch(error => { + if (input.projectName != null && error instanceof HttpError) return { status: 'rejected', code: error.code } + if (input.projectName != null && (error instanceof NetworkError || error instanceof RequestTimeoutError)) { + return { status: 'rejected', code: 'creation.unavailable' } + } + throw error + }) + return input.projectName == null ? started : { ...started, projectCreated: true } + } + + async #repeatCreation(projectId, submitId, jobId, signal, batchId) { + return this.#withLease(projectId, signal, async (session, snapshot) => { + const existing = await this.#submissionReceipt(projectId, submitId, signal) + if (existing) return { status: existing.status, jobId: existing.jobIds?.[0], code: existing.issues?.[0]?.code } + const job = snapshot.jobs.find(item => item.id === jobId) + const spec = snapshot.generationSpecs.find(item => item.id === job?.inputSnapshot?.spec?.id) + const item = snapshot.canvasItems.find(item => item.id === job?.originItemId) + const ownGroup = batchId != null && job?.batchId === batchId + if ((job?.status !== 'succeeded' && !canRetryFailedJob(job) && !(ownGroup && ['queued', 'running'].includes(job?.status))) + || !spec || !Object.hasOwn(MEDIA_TYPES, spec.kind) + || item?.binding?.objectRef?.id !== spec.id) { + throw new InputError('creation.repeat_unavailable') + } + if (ownGroup && spec.revision !== job.inputSnapshot.spec.revision) throw new InputError('revision_conflict') + const command = buildSubmitCommand({ + projectId, operationId: submitId, specId: spec.id, originItemId: item.id, batchId, + expectedSpecRevision: spec.revision, expectedItemRevision: item.revision, + ...(job.status === 'failed' && { previousJobId: job.id }), + }) + const receipt = await this.#command({ projectId, operationId: submitId, command, session, signal }) + return { status: receipt.status, jobId: receipt.jobIds?.[0], code: receipt.issues?.[0]?.code } + }) + } + async adoptResult(input) { return this.#write(buildResultSelectCommand(input), input.signal) } + async adoptCandidate({ projectId, resultId, operationId, check, signal }) { + const project = requireUuid(projectId, 'projectId') + const result = requireUuid(resultId, 'resultId') + const commandId = uuid5(requireUuid(operationId, 'operationId'), `result.select:${project}:${result}`) + if (check) { + return this.receipt(project, commandId, { signal }) + } + return this.#withLease(project, signal, async (session, snapshot) => { + const candidate = snapshot.results.find(item => item.id === result) + const spec = snapshot.generationSpecs.find(item => item.id === candidate?.specId) + if (!spec) throw new InputError('result.candidate_missing') + if (spec.currentResultId === result) return { status: 'noop' } + const expectedCanvasVersions = snapshot.canvasItems + .filter(item => item.binding?.objectRef?.id === spec.id || item.binding?.draftSpec?.id === spec.id) + .map(({ id, revision }) => ({ id, revision })) + const command = buildResultSelectCommand({ + projectId: project, operationId: commandId, specId: spec.id, resultId: result, + expectedSpecRevision: spec.revision, expectedCanvasVersions, + }) + return this.#command({ projectId: project, operationId: commandId, command, session, signal }) + }) + } + + async cancelCreation({ projectId, jobId, operationId, check, signal }) { + const project = requireUuid(projectId, 'projectId') + const job = requireUuid(jobId, 'jobId') + const commandId = uuid5(requireUuid(operationId, 'operationId'), 'job.cancel:' + project + ':' + job) + if (check) return this.receipt(project, commandId, { signal }) + return this.#withLease(project, signal, async (session, snapshot) => { + const existing = await this.#submissionReceipt(project, commandId, signal) + if (existing) return existing + const current = snapshot.jobs.find(item => item.id === job) + if (!current) throw new InputError('job.missing', { projectId: project, jobId: job }) + if (current.cancelRequested || !['accepted', 'queued', 'running'].includes(current.status)) return { status: 'noop' } + const command = buildJobCancelCommand({ + projectId: project, jobId: job, operationId: commandId, expectedJobRevision: current.revision, + }) + return this.#command({ projectId: project, operationId: commandId, command, session, signal }) + }) + } + async cancelJob(input) { return this.#write(buildJobCancelCommand(input), input.signal) } diff --git a/plugins/deepseek-harness/src/connection.js b/plugins/deepseek-harness/src/connection.js new file mode 100644 index 000000000..c16b7692b --- /dev/null +++ b/plugins/deepseek-harness/src/connection.js @@ -0,0 +1,47 @@ +import { HttpError, NetworkError, RequestTimeoutError } from './errors.js' + +function issue(error) { + if (error instanceof RequestTimeoutError) return 'timeout' + if (error instanceof NetworkError) return 'network' + if (error instanceof HttpError) { + if ([401, 403].includes(error.status)) return 'access' + if (error.status === 404) return 'address' + return 'service' + } + return 'response' +} + +// Read the configured service only. Return counts, never model credentials, +// project names, provider replies or local file paths. +export async function connectionStatus(client, config, version, { signal } = {}) { + const results = await Promise.allSettled([ + client.listProjects({ signal }).then(value => { + if (!Array.isArray(value?.projects)) throw new TypeError('Invalid project catalog') + return { status: 'ok', count: value.projects.length } + }), + client.creationModels({ signal }).then(models => { + if (!Array.isArray(models)) throw new TypeError('Invalid model catalog') + return { + status: 'ok', + count: models.length, + capabilities: { + image: models.filter(model => model.kind === 'image').length, + imageEdit: models.filter(model => model.kind === 'image' && model.maxImages > 0).length, + imageToVideo: models.filter(model => model.kind === 'video' && model.videoChoices?.first_frame).length, + videoContinuation: models.filter(model => model.kind === 'video' && model.videoChoices?.continuation).length, + voiceover: models.filter(model => model.kind === 'audio').length, + }, + } + }), + ]) + if (signal?.aborted) throw signal.reason + const [projects, models] = results.map(result => result.status === 'fulfilled' + ? result.value : { status: issue(result.reason) }) + return { + version, + apiUrl: config.baseUrl, + canvasUrl: config.canvasBaseUrl, + projects, + models, + } +} diff --git a/plugins/deepseek-harness/src/i18n.js b/plugins/deepseek-harness/src/i18n.js index 3537ee7a7..e238f0f5a 100644 --- a/plugins/deepseek-harness/src/i18n.js +++ b/plugins/deepseek-harness/src/i18n.js @@ -1,6 +1,43 @@ const enUS = { + "tool.results.description": "Find and show saved OpenDirector images, videos and audio in chat. Use find to look up result IDs, show to compare versions or play a clip, and draft to give the user an editable image prompt tied to one result. These actions only read the project. For a prompt request, suggest a concrete edit using the saved prompt and the user’s preferences. The prompt records intent; only describe visible details you have inspected. Generate when the user requests it.", + "param.resultKind": "Media type to find. Omit for all saved results.", + "param.resultQuery": "Optional terms from the saved title, prompt or model. Omit to browse.", + "param.resultCursor": "Continue from the nextCursor returned by find.", + "param.savedResultIds": "For show, one to four saved result IDs in display order. For draft, one image result ID.", + "param.editPrompt": "The proposed image edit prompt for the user to review.", + "library.results": "Choose one to four distinct, available media results from this project.", + "library.edit_draft": "Choose one saved image and include the proposed edit prompt.", + "summary.foundResults": "Use show with the chosen result IDs to display them. For a specific edit proposal, use draft with one image and the proposed prompt.", + "summary.noResults": "No matches. Try a shorter search or browse by media type.", + "summary.savedCards": "The selected results appear in chat in the order listed. The cards provide comparison, playback and editing. Answer the user’s question using the recorded relationships.", + "summary.editDraftWeb": "The draft appears in chat with a button to review the edit settings. An image request starts when the user chooses Generate.", + "summary.editDraft": "The proposed prompt is ready for review. No generation was submitted.", + "render.results": "Saved OpenDirector results", + "present.call.results": "Look up saved media", + "present.result.results": "OpenDirector media", + "pack.active": "Wait for this action’s running task to finish before changing its description.", + "tool.actionPack.description": "Create and resume an action pack from one saved character image. list/get/check only read. revise saves one action’s new prompt using itemId and expectedSpecRevision, retaining candidates and current adoption; generate explicitly starts a new candidate. prepare atomically saves 1–6 named action nodes with a pinned image, using a compatible image or first-frame video model; it does not generate. generate submits the explicit itemIds as candidate-only jobs. Count each action as a separate model request. For an unknown outcome check with the same operationId, packAction and itemIds; continue with the original generate input. Never automatically adopt; use opendirector_adopt_result for each chosen action result.", + "param.packId": "Action pack group UUID returned by prepare or list.", + "param.packCheck": "Original action being checked. For generate preserve the original itemIds and operationId.", + "param.packTitle": "Action pack title (1–100 characters).", + "param.packShared": "Optional description shared by all actions.", + "param.packName": "Unique action name (1–80 characters).", + "param.packSize": "Published model output size, for example 1024x1024.", + "param.packRatio": "Published aspect ratio, for example 1:1.", + "param.packDuration": "Supported first-frame video duration in seconds.", + "param.packRedo": "Explicitly generate another candidate for selected actions, or retry an eligible failed task.", + "render.actionPack": "OpenDirector action pack:", + "present.call.actionPack": "OpenDirector action pack", + "present.result.actionPack": "OpenDirector action pack ready", + "pack.missing": "This action pack or one of its action nodes is unavailable. Refresh the project.", + "pack.plan": "Use 1–6 actions with unique names and descriptions, and a pack title.", + "pack.model": "Choose an image model accepting references or a first-frame video model.", + "pack.action": "Unknown action pack operation.", + "pack.incomplete": "Choose one result for each action before downloading the pack.", + "pack.export": "One of the selected media files is unavailable for export.", + "pack.too_large": "The selected pack exceeds the 128 MB download limit.", 'tool.projects.description': 'List OpenDirector projects or create one with an explicit projectId and operationId.', - 'tool.project.description': 'Read the authoritative OpenDirector project snapshot, model catalog, and canvas URL without opening an edit session.', + 'tool.project.description': 'Read the OpenDirector project snapshot, model catalog and current revisions. For saved media and prompt proposals in chat, use opendirector_results.', 'tool.createGeneration.description': 'Create an OpenDirector generation node and its generation spec. This does not submit a job.', 'tool.submit.description': 'Submit an OpenDirector generation job with candidate-only adoption. It never adopts the result automatically.', 'tool.job.description': 'Read one OpenDirector generation job and its candidate results without modifying the project.', @@ -38,6 +75,7 @@ const enUS = { 'param.specId': 'Generation spec UUID.', 'param.expectedSpecRevision': 'Current generation spec revision used for optimistic concurrency.', 'param.originItemId': 'Optional originating canvas item UUID.', + 'param.batchId': 'Optional candidate group UUID. Use the same ID to group related jobs.', 'param.expectedItemRevision': 'Current origin canvas item revision. Required with originItemId.', 'param.jobId': 'Generation job UUID.', 'param.resultId': 'Generation result UUID.', @@ -123,8 +161,45 @@ const enUS = { } const zhCN = { + "tool.results.description": "在对话中查找和展示 OpenDirector 已有的图片、视频和音频。find 查结果 ID,show 并排看版本或播放片段,draft 针对一张已有图片给出可编辑的提示词草案。这三个动作只读工程。讨论改法时,结合原提示词和用户偏好给出具体建议;原提示词记录的是创作意图,画面细节以实际看过的素材为准。用户要求生成时再提交。", + "param.resultKind": "要查找的素材类型,留空可查看全部。", + "param.resultQuery": "可选,使用标题、原提示词或模型中的关键词,留空即可浏览。", + "param.resultCursor": "接着上一页 find 返回的 nextCursor 查找。", + "param.savedResultIds": "show 按填写顺序展示一至四个结果 ID;draft 填一个图片结果 ID。", + "param.editPrompt": "供用户审阅的改图提示词。", + "library.results": "请从这个工程选择一至四个可用的素材结果,每个结果只选一次。", + "library.edit_draft": "请选择一张已有图片并填写改图提示词。", + "summary.foundResults": "确定素材后,用 show 展示所选结果。要提出具体改图方案,用 draft 带上一张图片和建议的提示词。", + "summary.noResults": "没有找到匹配的素材。可以缩短搜索词,或按素材类型浏览。", + "summary.savedCards": "素材将按上述顺序显示在聊天中,用户可直接对比、播放或继续修改。请根据工程记录回答素材关系。", + "summary.editDraftWeb": "聊天中会显示提示词草案,用户可以打开改图设置。点击生成才会向图片模型提交请求。", + "summary.editDraft": "提示词草案已备好,等待用户审阅。没有提交生成任务。", + "render.results": "已存的 OpenDirector 素材", + "present.call.results": "查找已存素材", + "present.result.results": "OpenDirector 素材", + "pack.active": "请等待这个动作的任务结束,再修改描述。", + "tool.actionPack.description": "从已保存的角色图片创建并继续动作素材包。list/get/check 只读。revise 用 itemId、prompt 与 expectedSpecRevision 保存一个动作的新描述,保留历史候选和采用结果,随后由 generate 明确生成新候选。prepare 原子保存 1 至 6 个命名动作节点和固定图片引用,使用支持参考图的图片模型或首帧视频模型,不会生成。generate 为明确指定的 itemIds 分别提交仅候选任务,每个动作消耗一次模型请求。结果未知时,以原 operationId、packAction 和 itemIds 查询;继续提交沿用原 generate 输入。不会自动采用,请用 opendirector_adopt_result 逐项采用用户选择的结果。", + "param.packId": "prepare 或 list 返回的动作素材包分组 UUID。", + "param.packCheck": "要查询的原操作。generate 保留原 itemIds 和 operationId。", + "param.packTitle": "素材包名称,1 至 100 字符。", + "param.packShared": "所有动作共用的描述,可省略。", + "param.packName": "不重复的动作名称,1 至 80 字符。", + "param.packSize": "模型支持的输出尺寸,例如 1024x1024。", + "param.packRatio": "模型支持的比例,例如 1:1。", + "param.packDuration": "模型支持的首帧视频时长,单位为秒。", + "param.packRedo": "明确为所选动作再生成候选,或重试符合条件的失败任务。", + "render.actionPack": "OpenDirector 动作素材包:", + "present.call.actionPack": "OpenDirector 动作素材包", + "present.result.actionPack": "OpenDirector 动作素材包已就绪", + "pack.missing": "暂时无法读取这个素材包或其中的动作节点,请刷新工程。", + "pack.plan": "请填写素材包名称和 1 至 6 个名称不重复、描述完整的动作。", + "pack.model": "请选择支持参考图的图片模型或首帧视频模型。", + "pack.action": "未知的素材包操作。", + "pack.incomplete": "请为每个动作选一版结果,再下载素材包。", + "pack.export": "所选素材中有文件暂时无法导出。", + "pack.too_large": "所选素材包超过 128 MB 的下载上限。", 'tool.projects.description': '列出 OpenDirector 工程,或用显式 projectId 与 operationId 创建工程。', - 'tool.project.description': '读取权威 OpenDirector 工程快照、模型目录和画布地址,不申请编辑会话。', + 'tool.project.description': '读取 OpenDirector 工程快照、模型目录和当前版本。在聊天里找素材、看版本或起草改图提示词,请用 opendirector_results。', 'tool.createGeneration.description': '创建 OpenDirector 生成节点及其生成配置,不提交任务。', 'tool.submit.description': '以 candidate_only 策略提交 OpenDirector 生成任务,绝不自动采用结果。', 'tool.job.description': '只读查看一个 OpenDirector 生成任务及其候选结果。', @@ -162,6 +237,7 @@ const zhCN = { 'param.specId': '生成配置 UUID。', 'param.expectedSpecRevision': '用于乐观并发的当前生成配置版本。', 'param.originItemId': '可选的来源画布节点 UUID。', + 'param.batchId': '可选候选组 UUID;相关任务使用同一个 ID。', 'param.expectedItemRevision': '来源画布节点的当前版本;提供 originItemId 时必填。', 'param.jobId': '生成任务 UUID。', 'param.resultId': '生成结果 UUID。', diff --git a/plugins/deepseek-harness/src/operations.js b/plugins/deepseek-harness/src/operations.js index 2250c1cce..4352fa7ac 100644 --- a/plugins/deepseek-harness/src/operations.js +++ b/plugins/deepseek-harness/src/operations.js @@ -7,6 +7,13 @@ export const MEDIA_KINDS = ['text', 'image', 'video', 'audio', 'file'] export const SUBJECT_ROLES = ['main', 'auxiliary', 'voice'] export const REFERENCE_BINDINGS = ['follow_current', 'pinned'] +export function imageOutputParameters(outputs, requested) { + const output = requested == null ? outputs[0] : outputs.find(item => + item.size === requested.size && item.aspectRatio === requested.aspectRatio) + if (requested != null && !output) throw new InputError('creation.output') + return output ? { size: output.size, aspectRatio: output.aspectRatio } : { size: 'auto' } +} + const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i function fail(key, params) { @@ -42,7 +49,7 @@ function requireArray(value, field) { return value } -function requireEnum(value, field, values) { +export function requireEnum(value, field, values) { if (value == null) fail('input.required', { field }) if (!values.includes(value)) fail('input.enum', { field, values: values.join('|') }) return value @@ -228,6 +235,8 @@ export function buildSubmitCommand({ expectedSpecRevision, originItemId, expectedItemRevision, + previousJobId, + batchId, } = {}) { const id = requireUuid(projectId, 'projectId') const commandId = requireUuid(operationId, 'operationId') @@ -252,6 +261,8 @@ export function buildSubmitCommand({ specId: spec, expectedSpecRevision: revision, ...(origin == null ? {} : { originItemId: origin }), + ...(previousJobId == null ? {} : { previousJobId: requireUuid(previousJobId, 'previousJobId') }), + ...(batchId == null ? {} : { batchId: requireUuid(batchId, 'batchId') }), adoptionPolicy: 'candidate_only', showAdditionalResult: false, }, diff --git a/plugins/deepseek-harness/src/presentation.js b/plugins/deepseek-harness/src/presentation.js index ef0542a0b..e94ad838a 100644 --- a/plugins/deepseek-harness/src/presentation.js +++ b/plugins/deepseek-harness/src/presentation.js @@ -1,3 +1,27 @@ +export function mediaDetails(metadata) { + const { width, height, durationSeconds } = metadata ?? {} + const hasDimensions = Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0 + const hasDuration = Number.isFinite(durationSeconds) && durationSeconds > 0 + if (!hasDimensions && !hasDuration) return undefined + return { + ...(hasDimensions && { width, height }), + ...(hasDuration && { durationSeconds }), + } +} + +// A repeat can share a spec with earlier jobs. Read the size each job actually submitted. +export function resultMediaDetails(snapshot, jobs = new Map(snapshot.jobs.map(job => [job.id, job]))) { + const assets = new Map((snapshot.assets ?? []).map(asset => [asset.id, asset.metadata])) + return ({ asset, jobId }) => { + const details = mediaDetails(assets.get(asset.assetId)) + const size = jobs.get(jobId)?.inputSnapshot?.spec?.parameters?.size + if (asset.kind === 'image' && details?.width && /^\d+x\d+$/.test(size) && size !== `${details.width}x${details.height}`) { + return { ...details, requestedSize: size } + } + return details + } +} + /** Model-facing summaries. The canonical value remains available to programs. */ export function renderToolResult(key, value, t, { webPreview = false } = {}) { const lines = [t(`render.${key}`)] @@ -6,6 +30,20 @@ export function renderToolResult(key, value, t, { webPreview = false } = {}) { if (status) lines.push(`${t('summary.status')}: ${t(`status.${status}`)}`) if (value.receipt?.status === 'rejected') { lines.push(...value.receipt.issues.map(issue => `${issue.code}: ${issue.message}`)) + } else if (key === 'results') { + // The user sees media cards. The chat model needs identities, the saved prompt and exact source links. + for (const [index, result] of value.results.entries()) { + const { resultId, kind, title, prompt, selected, sourceResultId, firstFrameFor } = result + lines.push(JSON.stringify({ position: index + 1, resultId, kind, title, prompt, selected, sourceResultId, firstFrameFor })) + } + if (value.action === 'find') { + lines.push(value.results.length ? t('summary.foundResults') : t('summary.noResults')) + if (value.nextCursor) lines.push(`after: ${value.nextCursor}`) + } else if (value.action === 'draft') { + lines.push(value.editPrompt, t(webPreview ? 'summary.editDraftWeb' : 'summary.editDraft')) + } else { + lines.push(t(webPreview ? 'summary.savedCards' : 'summary.canvasPreview')) + } } else if (key === 'submit') { lines.push(t('summary.submitted'), ...value.jobIds.map(id => `jobId: ${id}`)) } else if (key === 'job') { @@ -20,7 +58,7 @@ export function renderToolResult(key, value, t, { webPreview = false } = {}) { if (result.asset) lines.push(`${t('summary.referenceAsset')}: ${JSON.stringify(result.asset)}`) } const hasPreview = webPreview && value.results.some(({ asset }) => - asset?.kind === 'image' || asset?.kind === 'video') + asset?.kind === 'image' || asset?.kind === 'video' || asset?.kind === 'audio') lines.push(t(hasPreview ? 'summary.webPreview' : 'summary.canvasPreview')) } if (value.job.errorDetails?.message) lines.push(value.job.errorDetails.message) diff --git a/plugins/deepseek-harness/src/tools.js b/plugins/deepseek-harness/src/tools.js index 874c01a8a..61d62e0f2 100644 --- a/plugins/deepseek-harness/src/tools.js +++ b/plugins/deepseek-harness/src/tools.js @@ -1,5 +1,5 @@ import { defineTool } from '@deepseek-ai/dsh-tools' -import { renderToolResult } from './presentation.js' +import { mediaDetails, renderToolResult } from './presentation.js' import { GENERATION_KINDS, MEDIA_KINDS, @@ -54,6 +54,7 @@ function rawInput(args) { 'specId', 'resultId', 'sourceResultId', + 'resultIds', 'jobId', 'expectedSpecRevision', 'expectedItemRevision', @@ -64,6 +65,14 @@ function rawInput(args) { return output } +function resultVersionFields(result) { + const fields = {} + for (const key of ['version', 'createdAt', 'sourceResultId', 'sourceVersion', 'sourceTitle', 'supportsContinuation']) { + if (result?.[key] !== undefined) fields[key] = result[key] + } + return fields +} + function presentationMeta(_args, value) { const meta = {} for (const key of ['projectId', 'operationId', 'specId', 'itemId', 'resultId', 'jobId', 'canvasUrl']) { @@ -73,19 +82,30 @@ function presentationMeta(_args, value) { if (typeof status === 'string') meta.status = status if (Array.isArray(value?.jobIds)) meta.jobIds = value.jobIds.slice(0, 8) if (Array.isArray(value?.projects)) meta.projectCount = value.projects.length + if (value.action === 'show' && value.results) { + meta.savedResults = { projectName: value.projectName, results: value.results } + } else if (value.action === 'draft' && value.editPrompt) { + meta.editDraft = { projectName: value.projectName, source: value.results[0], prompt: value.editPrompt } + } const kind = value?.job?.execution?.kind - if (kind === 'image' || kind === 'video') { + if (kind === 'image' || kind === 'video' || kind === 'audio') { const candidates = value.results.filter(result => result.asset?.kind === kind) if (!candidates.length) return meta const references = value.job.inputSnapshot?.references ?? [] const source = kind === 'video' ? references.find(ref => ref.role === 'continuation' || ref.role === 'first_frame') - : references.find(ref => ref.asset?.kind === 'image') + : kind === 'image' ? references.find(ref => ref.asset?.kind === 'image') : undefined + const sourceDetails = mediaDetails(source?.metadata) meta.mediaPreview = { kind, projectName: value.projectName, ...(source && { sourceAssetId: source.asset.assetId, sourceKind: source.asset.kind }), - candidates: candidates.map(result => ({ resultId: result.id, assetId: result.asset.assetId })), + ...(sourceDetails && { sourceDetails }), + candidates: candidates.map((result) => { + const details = value.resultDetails?.[result.asset.assetId] + return { resultId: result.id, assetId: result.asset.assetId, + ...(details && { details }), ...resultVersionFields(result) } + }), } } return meta @@ -227,7 +247,7 @@ export function createOpenDirectorTools({ client, t, hasWebPreview = () => false schema, render: (_args, value) => [{ type: 'text', - text: renderToolResult(key, value, t, { webPreview: key === 'job' && hasWebPreview() }), + text: renderToolResult(key, value, t, { webPreview: (key === 'job' || key === 'results') && hasWebPreview() }), }], presentationMeta, }, @@ -420,6 +440,7 @@ export function createOpenDirectorTools({ client, t, hasWebPreview = () => false expectedSpecRevision: required(integer(t('param.expectedSpecRevision'))), originItemId: string(t('param.originItemId')), expectedItemRevision: integer(t('param.expectedItemRevision')), + batchId: string(t('param.batchId')), }, schema: outputSchema({ projectId: string('Project ID.'), @@ -436,6 +457,7 @@ export function createOpenDirectorTools({ client, t, hasWebPreview = () => false expectedSpecRevision: args.expectedSpecRevision, originItemId: args.originItemId, expectedItemRevision: args.expectedItemRevision, + batchId: args.batchId, signal: exec.signal, }) return { @@ -475,6 +497,7 @@ export function createOpenDirectorTools({ client, t, hasWebPreview = () => false registered: value.registered, adopted: value.adopted, results: value.results, + ...(value.resultDetails && { resultDetails: value.resultDetails }), } }, }) @@ -594,5 +617,74 @@ export function createOpenDirectorTools({ client, t, hasWebPreview = () => false }, }) - return [projects, project, createGeneration, submit, job, adoptResult, cancel, operation] + + const results = makeTool({ + key: 'results', + name: 'opendirector_results', + description: t('tool.results.description'), + parameters: { + projectId: projectIdParam, + action: required({ type: 'string', enum: ['find', 'show', 'draft'] }), + kind: { type: 'string', enum: ['image', 'video', 'audio'], description: t('param.resultKind') }, + query: string(t('param.resultQuery')), + after: string(t('param.resultCursor')), + resultIds: arrayOf(string(t('param.resultId')), t('param.savedResultIds')), + editPrompt: string(t('param.editPrompt')), + }, + schema: outputSchema({ + action: string(), projectId: string(), projectName: string(), canvasUrl: string(), + results: arrayOf(objectOf()), editPrompt: string(), + }, ['action', 'projectId', 'projectName', 'canvasUrl', 'results']), + async execute(args, { signal }) { + if (args.action === 'find') { + const matches = await client.libraryResults(args.projectId, { + kind: args.kind, query: args.query, after: args.after, signal, + }) + return { ...matches, action: args.action } + } + if (args.action === 'draft' && (args.resultIds?.length !== 1 + || typeof args.editPrompt !== 'string' || !args.editPrompt.trim())) throw new InputError('library.edit_draft') + const saved = await client.showResults(args.projectId, args.resultIds, { signal }) + if (args.action === 'draft') { + if (saved.results[0].kind !== 'image') throw new InputError('library.edit_draft') + return { ...saved, action: args.action, editPrompt: args.editPrompt.trim() } + } + return { ...saved, action: args.action } + }, + }) + + const actionPack = makeTool({ + key: 'actionPack', + name: 'opendirector_action_pack', + description: t('tool.actionPack.description'), + parameters: { + projectId: projectIdParam, + action: required({ type: 'string', enum: ['list', 'get', 'prepare', 'generate', 'check', 'revise'] }), + operationId: string(t('param.operationId')), + packId: string(t('param.packId')), + packAction: { type: 'string', enum: ['prepare', 'generate', 'revise'], description: t('param.packCheck') }, + sourceResultId: string(t('param.sourceResultId')), + title: string(t('param.packTitle')), + itemId: string(t('param.originItemId')), + prompt: string(t('param.prompt')), + expectedSpecRevision: integer(t('param.expectedSpecRevision')), + sharedPrompt: string(t('param.packShared')), + actions: { ...arrayOf(objectOf({ name: required(string(t('param.packName'))), + prompt: required(string(t('param.prompt'))) }, { additionalProperties: false })) }, + modelConfigId: string(t('param.modelConfigId')), + output: objectOf({ size: required(string(t('param.packSize'))), + aspectRatio: required(string(t('param.packRatio'))) }, { additionalProperties: false }), + durationSeconds: number(t('param.packDuration')), + itemIds: arrayOf(string(t('param.originItemId'))), + redo: boolean(t('param.packRedo')), + }, + schema: outputSchema({ projectId: string(), packId: string(), status: string(), + canvasUrl: string(), actions: arrayOf(objectOf()), packs: arrayOf(objectOf()) }, ['projectId', 'canvasUrl']), + async execute(args, exec) { + const value = await client.actionPack(args, { signal: exec.signal }) + return { ...value, projectId: args.projectId, canvasUrl: client.canvasUrl(args.projectId) } + }, + }) + + return [projects, project, results, createGeneration, submit, job, adoptResult, cancel, operation, actionPack] } diff --git a/plugins/deepseek-harness/src/versions.js b/plugins/deepseek-harness/src/versions.js new file mode 100644 index 000000000..536a28dff --- /dev/null +++ b/plugins/deepseek-harness/src/versions.js @@ -0,0 +1,89 @@ +const TITLE_LIMIT = 160 + +function validTime(value) { + return typeof value === 'string' && value.trim() !== '' && Number.isFinite(Date.parse(value)) + ? value + : undefined +} + +function identityKey(asset) { + if (!asset || typeof asset.assetId !== 'string' || !Number.isInteger(asset.revision) + || typeof asset.fingerprint !== 'string') return undefined + return JSON.stringify([asset.assetId, asset.revision, asset.fingerprint]) +} + +function referenceSourceAsset(job) { + const references = job?.inputSnapshot?.references + if (!Array.isArray(references)) return undefined + const continuation = references.find(reference => reference?.role === 'continuation') + const firstFrame = references.find(reference => reference?.role === 'first_frame') + const image = references.find(reference => reference?.asset?.kind === 'image') + return (continuation ?? firstFrame ?? image)?.asset +} + +function titlesBySpec(snapshot) { + const titles = new Map() + for (const item of snapshot?.canvasItems ?? []) { + if (item?.binding?.role !== 'generation') continue + const specId = item.binding.objectRef?.id + if (typeof specId !== 'string' || titles.has(specId)) continue + const title = typeof item.title === 'string' ? item.title.trim() : '' + if (title) titles.set(specId, title.slice(0, TITLE_LIMIT)) + } + return titles +} + +/** + * Build the read-only version metadata for registered results. + * + * Versions come from each spec's results in snapshot registration order, so + * paging and filtering never renumber them. A source is reported only when a + * frozen reference asset identity matches exactly one result registered before + * the current one; a shared fingerprint alone is not evidence of provenance. + */ +export function resultVersionInfo(snapshot, { includeFirstFrameUsage = false } = {}) { + const results = Array.isArray(snapshot?.results) ? snapshot.results : [] + const jobs = new Map((snapshot?.jobs ?? []).map(job => [job.id, job])) + const titles = titlesBySpec(snapshot) + const counts = new Map() + const seenIdentities = new Map() + const info = new Map() + + for (const result of results) { + const version = (counts.get(result.specId) ?? 0) + 1 + counts.set(result.specId, version) + const job = jobs.get(result.jobId) + const videoModes = result.asset?.kind === 'video' ? job?.inputSnapshot?.model?.inputRules?.videoModes : undefined + const createdAt = validTime(job?.createdAt) + const key = identityKey(referenceSourceAsset(job)) + let source + if (key !== undefined) { + const prior = seenIdentities.get(key) + if (prior?.length === 1) source = prior[0] + } + info.set(result.id, { + version, + ...(includeFirstFrameUsage && result.asset?.kind === 'image' && { firstFrameFor: [] }), + ...(Array.isArray(videoModes) && { supportsContinuation: videoModes.includes('continuation') }), + ...(createdAt !== undefined && { createdAt }), + ...(source && { sourceResultId: source.result.id, sourceVersion: source.version }), + ...(source && titles.has(source.result.specId) && { sourceTitle: titles.get(source.result.specId) }), + }) + if (includeFirstFrameUsage && result.asset?.kind === 'video' && job?.status === 'succeeded') { + const firstFrame = job.inputSnapshot?.references?.find(ref => ref.role === 'first_frame') + const matches = seenIdentities.get(identityKey(firstFrame?.asset)) + if (matches?.length === 1 && matches[0].result.asset.kind === 'image') { + const title = titles.get(result.specId) + info.get(matches[0].result.id).firstFrameFor.push({ resultId: result.id, ...(title && { title }) }) + } + } + const own = identityKey(result.asset) + if (own !== undefined) { + const registered = seenIdentities.get(own) + if (registered) registered.push({ result, version }) + else seenIdentities.set(own, [{ result, version }]) + } + } + + return info +} diff --git a/plugins/deepseek-harness/src/web-client.js b/plugins/deepseek-harness/src/web-client.js index e2f4f4a61..abb97ad01 100644 --- a/plugins/deepseek-harness/src/web-client.js +++ b/plugins/deepseek-harness/src/web-client.js @@ -2,35 +2,402 @@ window.__ModuleLoader__.load({ id: '@opendirector/dsh-plugin', factory(require) { - const { createElement: h, useState, useSyncExternalStore } = require('react') + const { Children, cloneElement, createContext, createElement: h, useContext, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } = require('react') const namespace = 'opendirector' + const ChatContext = createContext(null) const en = { + reloadData: 'Reload', + chooseModel: 'Choose a model', needsModel: 'Select a model to continue', promptPlaceholder: 'Describe the subject, setting and light.', + needsProject: 'Choose a project or create one.', needsName: 'Enter a project name.', + needsPrompt: 'Write a description or pick an example.', needsVoice: 'Enter a voice ID.', + fileSize: 'File {size}', requestedSize: 'Requested {size}', + recentRestored: 'Using your recent settings.', forgetRecent: 'Forget recent settings', recentForgotten: 'Recent settings cleared.', + versionLabel: 'V{number}', sourceVersionLabel: 'From {title} · V{number}', + examples: 'Try an example', exampleChoose: 'Example', exampleApply: 'Use this description', + exampleReplace: 'Replace current description', exampleHint: 'Fills the description only. Review your model and settings, then generate when ready.', + exampleStudio: 'Studio by the window', + exampleStudioPrompt: 'Warm sunlight streams through a large studio window onto a wooden desk. A blue ceramic mug sits beside a leafy green plant. Natural light, realistic photography, shallow depth of field.', + exampleCharacter: 'A character for an action pack', + exampleCharacterPrompt: 'A small friendly robot with a rounded cream body, teal eyes and a tiny orange scarf. Full body, front view, centered, plain light background, clean silhouette, soft 3D illustration.', + exampleCover: 'Product cover', + exampleCoverPrompt: 'A single handmade ceramic mug on a pale wooden surface, soft side lighting, uncluttered warm background, realistic product photography. Leave space above for a title; no text in the image.', + exampleLamp: 'Add a desk lamp', + exampleLampPrompt: 'Keep the original composition and objects. Add a brass desk lamp on the left side of the wooden desk. Match the existing perspective, light and shadows.', + exampleEvening: 'Change the lighting', + exampleEveningPrompt: 'Keep the same subject, layout and camera position. Change the light to a calm blue evening with a warm lamp nearby. Preserve the identity and details of the original subject.', + exampleWave: 'A gentle greeting', + exampleWavePrompt: 'The character gently waves one hand in greeting, then returns to the starting pose. Keep the same character, framing and background. Fixed camera, smooth restrained movement.', + examplePush: 'Slow camera move', + examplePushPrompt: 'The camera moves slowly toward the main subject. Soft natural light and a gentle background breeze. Keep the original layout, objects and visual style.', + exampleContinue: 'Continue the moment', + exampleContinuePrompt: 'Continue smoothly from the end of the previous shot. Keep the same subject, setting, camera direction and lighting. Let the action settle naturally.', + exampleSpeech: 'A short introduction', + exampleSpeechPrompt: 'A quiet corner, a warm cup, and a little room to create. Welcome to our studio.', + exampleNarration: 'A character introduction', + exampleNarrationPrompt: 'Meet our little robot. It likes to wave hello, think through new ideas, and take a well-earned rest.', + actionExamples: 'Example actions', actionExamplesHint: 'Replaces the action list. Keeps the shared description, reference image and model.', + actionExampleApply: 'Replace action list', actionExampleStarter: 'Desktop companion', + actionExampleMood: 'Expressions', packHappy: 'Happy', packHappyPrompt: 'Show a happy expression with a small cheerful bounce, keep the same character and camera framing.', + packSleep: 'Rest', packSleepPrompt: 'Close the eyes and rest calmly, keep the same character, pose scale and camera framing.', + connection: 'Connection check', connectionHint: 'Check your OpenDirector service and available model connections.', + connectionChecking: 'Checking connection…', connectionReady: 'Connected', + connectionPartial: 'Some checks need attention', connectionFailed: 'Could not reach OpenDirector', + connectionApi: 'OpenDirector API', connectionCanvas: 'OpenDirector canvas', connectionProjects: 'Saved projects', + connectionModels: 'Model connections', connectionCount: '{count} available', + connectionNoModels: 'Add a model in OpenDirector → Settings → Model connections, then check again.', + connectionConfigured: 'Listed models are configured in OpenDirector. A generation is needed to test provider access and output.', + connectionNetwork: 'Start OpenDirector and check the API address. localhost refers to the computer running DSH.', + connectionTimeout: 'OpenDirector did not respond in time. Check that the service has finished starting.', + connectionAccess: 'The service refused access. Check the OpenDirector address and its local access settings.', + connectionAddress: 'The API was not found at this address. Check baseUrl in the plugin configuration.', + connectionService: 'OpenDirector returned an error. Check the service, then try again.', + connectionResponse: 'The service returned an unexpected response. Check the API address and OpenDirector version.', + connectionHost: 'The DSH connection is unavailable. Reconnect DSH, then try again.', + connectionSetup: 'Set baseUrl and canvasBaseUrl in this profile’s opendirector row. The README shows the configuration.', + connectionImage: 'Image generation', connectionEdit: 'Image references', connectionVideo: 'Image to video', + connectionContinue: 'Video continuation', connectionVoice: 'Voiceover', connectionCheck: 'Check again', + connectionCopy: 'Copy diagnostics', connectionCopied: 'Diagnostics copied.', connectionCopyFailed: 'Copy failed. Select and copy the diagnostic text below.', + connectionGuide: 'Setup guide', connectionOpen: 'Open OpenDirector', connectionPlugin: 'Manage plugin', + connectionDiagnostic: 'Diagnostic text', connectionReadOnly: 'This check reads project and model counts. It does not generate media.', + packRevise: 'Adjust action', packEditPrompt: 'Action description', packSaveGenerate: 'Generate with this description', + packCancelEdit: 'Cancel changes', packRevised: 'Description saved. Review it, then generate a candidate when ready.', + packActive: 'Wait for this action’s task to finish before changing its description.', + + actionPacks: 'Action packs', newActionPack: 'Make an action pack', packTitle: 'Pack name', + packHint: 'Keep one reference image, make each action separately, then choose one version per action.', + packEmpty: 'No action packs in this project yet. Start from a saved image.', + packSource: 'Use as character reference', packShared: 'Shared description', packActionName: 'Action name', + packDescription: 'Describe this action', packAdd: 'Add an action', packRemove: 'Remove action', + packCreate: 'Create and generate {count} actions', packMissing: 'Generate {count} unstarted actions', + packCount: '{selected}/{total} actions selected', packExport: 'Download action pack', + packExportHint: 'Choose one result for every action to export named media files and manifest.json (up to 128 MB).', + packInvalid: 'Give the pack a name and add 1–6 actions with unique names and descriptions.', + packNotStarted: 'Not started', packContinue: 'Continue original submission', + packReference: 'Character reference', packSelectSource: 'Choose a saved reference image', + packIdle: 'Idle', packIdlePrompt: 'Stand naturally, relaxed posture, keep the same character and appearance.', + packWave: 'Wave', packWavePrompt: 'Wave one hand in greeting, keep the same character and appearance.', + packThink: 'Think', packThinkPrompt: 'Tilt the head thoughtfully, keep the same character and appearance.', + packDefaultTitle: 'Character actions', images: 'Image results', videos: 'Video results', original: 'Original', sourceClip: 'Source clip', - candidate: 'Candidate', unavailable: 'Preview unavailable. Open the canvas to view this result.', + previousImage: 'Previous image', nextImage: 'Next image', adoptImage: 'Adopt this image', + viewOriginal: 'View original image', fitImage: 'Fit to window', actualImageSize: 'Actual size', + originalUnavailable: 'Could not load the original image.', duration: '{seconds} s', + candidate: 'Candidate', unavailable: 'Could not load the preview.', retryMedia: 'Reload preview', canvas: 'Open canvas', edit: 'Edit', firstFrame: 'Animate', continue: 'Continue', adopt: 'Adopt', adopted: 'Result adopted', - create: 'Create media', send: 'Send request', cancel: 'Cancel', draftReady: 'Draft ready to send.', - draftBusy: 'Finish or clear your current draft first.', brief: 'Describe what to change', - shot: 'Describe the next shot', ready: 'Request sent.', copyId: 'Copy result ID', copied: 'Result ID copied.', - createPrompt: 'Create in OpenDirector: ', - editPrompt: 'Edit the image. Show the new candidate before adopting it.', - firstFramePrompt: 'Use the image as the first frame of a video. Show the candidate before adopting it.', - continuePrompt: 'Continue the clip with a compatible video model. Show the candidate before adopting it.', - adoptPrompt: 'Adopt this result. Read the current revisions first, then share the canvas link.', - reference: 'OpenDirector project and result', + createHint: 'Choose what to make and where to save it.', backStep: 'Back one step', + animateStill: 'Animate an image', extendClip: 'Continue a clip', videoStart: 'Start from', + pickStill: 'Choose a saved image for the first frame.', pickClip: 'Choose the clip to continue.', + noStills: 'This project has no saved image to animate.', noClips: 'This project has no saved video yet.', + clipsUnsupported: 'The clips on this page were made with models that cannot continue a video.', + makeStill: 'Create a first frame', videoProject: 'Choose a project to browse its images and clips.', + noVideoMode: 'No configured video model supports this mode.', + libraryHint: 'Pick a project, or ask in chat: “Show my last two versions and help me plan an edit.”', + discussEdit: 'Discuss edit', discussPrompt: 'Help me plan an edit for “{image}” in “{project}” (result {id}). Draft a prompt for me to review before generating. What I want to change: ', + discussReady: 'Add your change in the chat box, then send.', discussBusy: 'The chat box is busy. Try again in a moment.', + referenceInChat: 'Reference in chat', planNextShot: 'Plan the next shot', chatRefAdded: 'Reference added to the chat box.', + assetReference: 'OpenDirector · {title} · {kind} (project {projectId}, result {resultId})', + nextShotPrompt: 'Help me plan the next shot using this version. Suggest the framing and movement before generating.', + useChatDraft: 'Use chat draft', appendChatDraft: 'Append chat draft', draftTooLong: 'The combined description exceeds the model’s limit.', + savedOnly: 'Saved results', wasFirstFrame: 'First frame for {videos}', savedPrompt: 'Original prompt', + savedRefreshFailed: 'Could not refresh these versions. Try again.', + editProposal: 'Suggested edit', reviewEdit: 'Review edit', editProposalHint: 'Review the prompt and settings before generating.', + generationSettings: 'Generation settings', + moreCandidateCount: 'Additional candidates', groupStopped: 'The remaining planned candidates were not submitted.', + candidateCount: 'Number of candidates', generateGroup: 'Generate {count} candidates', + groupHint: 'Sends {count} separate generation tasks. Results stay as candidates.', + groupSummary: '{done}/{total} ready · {failed} failed', groupTask: 'Candidate {number}', + groupUnsubmitted: '{count} planned candidates have not been confirmed.', + continueGroup: 'Continue the original group', groupCompare: 'Compare selected images', + candidateCountInvalid: 'Choose between 1 and 4 candidates.', + create: 'Create media', brief: 'Describe what to change', copyId: 'Copy result ID', copied: 'Result ID copied.', + firstFrameSource: 'First frame', motion: 'Describe the motion', shot: 'Describe the next shot', + videoDuration: 'Video duration', chooseDuration: 'Choose a duration', modelDuration: 'This model uses its default duration.', + useDefaultDuration: 'Use model default', + durationUnavailable: 'This model does not support the selected duration.', + videoModeUnavailable: 'Choose a model that supports this video action.', + videoSourceUnavailable: 'The source result is unavailable. Refresh the project and try again.', + continuationHint: 'Use the same model connection that generated this clip. The new clip keeps its dimensions.', + noClipContinuation: 'The model that made this clip doesn’t support continuation.', + saveFrame: 'Save current frame as PNG', playForFrame: 'Play the video, then pause on the frame you want to save.', + frameFailed: 'Couldn’t save this frame. Wait for the picture to load and try again.', + continuationUnavailable: 'Open the canvas for details. If the source cache has expired, generate the source clip again.', + resume: 'Resume project', close: 'Close', chooseProject: 'Choose a project', + projectsEmpty: 'No OpenDirector projects yet.', resultsEmpty: 'This project has no saved media results.', + loading: 'Loading…', refresh: 'Refresh results', libraryError: 'Could not load OpenDirector. Try refreshing.', + recent: 'Saved results', selected: 'Current result', adopting: 'Adopting…', checkAdoption: 'Check adoption', + tasks: 'Tasks', tasksEmpty: 'No generation tasks match these filters.', viewTask: 'View progress', + taskProgress: 'Task progress', backgroundHint: 'Closing this dialog does not cancel the job. Find it under Resume project → Tasks.', + chatTasks: 'Tasks in this chat', taskCount: '{count} tasks', taskNeedsCheck: 'Needs checking', partlyReady: 'Partly ready', partialGroup: 'Some candidates are unconfirmed', + taskStatusUnavailable: 'Status unavailable', closeTaskHint: 'You can close this window and follow the task beside the OpenDirector button.', + cancelled: 'Cancelled', interrupted: 'Interrupted', + pendingSubmissions: 'Submissions to check', pendingHint: 'Check the original submission without generating again.', + startSeparateCreation: 'Start a separate creation', + hidePending: 'Hide reminder', hidePendingHint: 'Hiding a reminder does not cancel a submitted job.', + pendingStorageUnavailable: 'Recovery is available on this page, but cannot be saved. Check before reloading.', + pendingCheckFailed: 'Could not check this submission. Try again when OpenDirector is available.', + pendingNotAccepted: 'The original submission was not accepted.', pendingConfirmed: 'The original operation was confirmed. Open the canvas to continue.', + reuseSettings: 'Reuse settings', resetTemplate: 'Reset to this version', keepOriginalOutput: 'Keep original size', + reuseHint: 'Uses this version’s saved settings in a new node. Review the candidate before adopting.', + reuseReferences: 'References kept from this version', referenceMedia: 'Reference media', + reuseUnavailable: 'Could not load the saved settings. Reload them, or check the model and references in OpenDirector.', + draftRestored: 'Unsubmitted draft restored.', clearDraft: 'Clear draft', resumeEarlierDraft: 'Resume earlier draft', + modelUnavailable: 'The saved model is unavailable. Choose another model.', + projectUnavailable: 'The saved project is unavailable. Choose another project.', + stopGeneration: 'Request stop', stoppingGeneration: 'Requesting stop…', checkStop: 'Check stop request', + stopRequested: 'Stop requested.', stopUnknown: 'The stop request has not been confirmed. Check the same request.', + stopFinished: 'The task has already finished.', stopFailed: 'Could not request a stop. Check progress before trying again.', + stopChanged: 'The task changed. Check progress and try again.', localStopped: 'Local processing has stopped.', + remoteStopUnconfirmed: 'Provider cancellation has not been confirmed. Check the original task with the provider.', + remoteStopped: 'The provider confirmed cancellation.', + + adoptUnknown: 'Adoption has not been confirmed yet. Check its status.', + adoptBusy: 'Save and close the open OpenDirector canvas, then try again.', + adoptConflict: 'This result or canvas has changed. Refresh the project before trying again.', + adoptFailed: 'Could not adopt this result. Check the project and try again.', + audios: 'Audio results', speech: 'Voiceover', picture: 'Image', mediaType: 'Media type', + newProject: 'New project', projectName: 'Project name', model: 'Model', local: 'Self-hosted', hosted: 'Hosted', + output: 'Image size', voice: 'Voice ID', prompt: 'Describe the image', speechText: 'Text to read aloud', + chooseOutput: 'Choose an image size', useModelDefault: 'Use model default', + outputUnavailable: '{size} is unavailable on this model. Choose a different size or model.', + generate: 'Generate one candidate', submitting: 'Submitting…', checkGeneration: 'Check submission', + repeatGeneration: 'Generate another candidate', + adjustGeneration: 'Adjust settings for another version', previousRound: 'Previous results', compareRevisions: 'Compare versions', + repeatHint: 'Uses the settings saved on this canvas node. Existing candidates stay available.', + repeatUnavailable: 'The generation node is unavailable. Open the canvas to check it.', + noModels: 'Configure a compatible model in OpenDirector first.', + failedToSubmit: 'Could not submit generation. Check your project and model settings.', + generationUnknown: 'Submission has not been confirmed. Check it here or under Resume project → Submissions to check.', + retrySubmission: 'Try submitting again', retryGeneration: 'Retry generation', + connectionUnavailable: 'Could not reach OpenDirector. Reconnect, then try submitting again.', + progressUnavailable: 'Could not check progress. Once connected, check the same job again.', + providerUnknown: 'The model service may have received the request. Check the original job with the provider first.', + rateLimited: 'The model service is rate limiting requests. Wait a moment before trying again.', + credentialsRejected: 'The model service rejected the credentials. Check the API key in Model connections.', + permissionDenied: 'The model service denied access. Check that the account can use this model.', + inputRejected: 'The model service rejected the inputs. Open the canvas to review the settings or reference media.', + recoverOnCanvas: 'Open the canvas to recover the existing job.', + draftSaved: 'The generation settings are saved on the canvas.', + waiting: 'Waiting for OpenDirector…', queued: 'Queued', running: 'Generating…', + succeeded: 'Candidate ready', stopped: 'Generation stopped', failed: 'Generation failed', + quota: 'Check the model account’s balance or quota before trying again.', + checkProgress: 'Check progress', download: 'Download original', + compareImages: 'Compare images', compareHint: 'Choose two images, then open the comparison.', + openComparison: 'Open comparison', clearComparison: 'Clear comparison', + chooseComparison: 'Compare this image', removeComparison: 'Remove from comparison', + comparisonUnavailable: 'Could not load this comparison. Refresh the results and select two saved images.', + buffering: 'Buffering…', updatesPaused: 'Automatic status checks are paused while offline or in the background.', + searchLibrary: 'Search saved work', searchHint: 'Description, node name, model or ID', + clearFilters: 'Clear search and filters', taskStatus: 'Filter tasks by status', allTasks: 'All tasks', + activeTasks: 'Queued or running', + libraryType: 'Filter by media', librarySelection: 'Filter by selection', libraryOrder: 'Sort results', + allMedia: 'All media', video: 'Video', audio: 'Audio', allSelections: 'All results', other: 'Other results', + previousPage: 'Previous page', nextPage: 'Next page', pageNumber: 'Page {number}', + newest: 'Newest first', oldest: 'Oldest first', noMatches: 'No results match these filters.', + actions: 'More actions', play: 'Play', pause: 'Pause', playbackFailed: 'Could not start playback.', + references: 'Reference images', chooseReferences: 'Add reference images', hideReferences: 'Hide image picker', + addReference: 'Add reference', removeReference: 'Remove reference', referenceImage: 'Reference image', + moveReferenceEarlier: 'Move reference {number} earlier', moveReferenceLater: 'Move reference {number} later', + noMoreImages: 'No other saved images on this page.', + referenceOrder: 'The source stays first. Other images are sent in the order shown.', + referenceLimit: 'This model accepts up to {count} reference images.', + referencesChanged: 'Check the selected images and the model’s reference limit, then try again.', } const zh = { + chooseModel: '请选择模型', needsModel: '先选择模型', promptPlaceholder: '想画什么?试着描述主体、场景和光线。', + needsProject: '选择一个工程,或新建工程。', needsName: '请填写工程名称。', + needsPrompt: '写一句描述,或选择一个示例。', needsVoice: '请填写音色 ID。', + fileSize: '文件 {size}', requestedSize: '请求 {size}', + reloadData: '重新读取', + recentRestored: '已沿用上次设置。', forgetRecent: '清除最近设置', recentForgotten: '最近设置已清除。', + versionLabel: 'V{number}', sourceVersionLabel: '来源:{title} · V{number}', + examples: '试一个例子', exampleChoose: '创作示例', exampleApply: '填入这份描述', + exampleReplace: '替换当前描述', exampleHint: '只填入描述。确认模型和参数后,再点击生成。', + exampleStudio: '窗边工作室', + exampleStudioPrompt: '阳光透过工作室的大窗洒在木桌上,桌上有一只蓝色陶瓷杯,旁边是一盆绿植。暖色自然光,真实摄影质感,浅景深。', + exampleCharacter: '动作包的角色原图', + exampleCharacterPrompt: '一个友好的小机器人,圆润的奶油色身体,青绿色眼睛,系着一条小橙色围巾。全身正面,居中,浅色纯背景,轮廓清晰,柔和的三维插画风格。', + exampleCover: '产品封面', + exampleCoverPrompt: '一只手工陶瓷杯放在浅色木桌上,柔和的侧光,温暖简洁的背景,真实产品摄影。画面上方留出标题空间,图片中不要出现文字。', + exampleLamp: '加一盏台灯', + exampleLampPrompt: '保留原来的构图和物体,在木桌左侧加一盏黄铜台灯。让透视、光线和阴影与原图一致。', + exampleEvening: '换成傍晚光线', + exampleEveningPrompt: '保留原图的主体、布局和机位,改为安静的蓝调傍晚光线,旁边有一盏暖色灯。保持主体身份和细节。', + exampleWave: '角色挥手', + exampleWavePrompt: '角色轻轻挥手打招呼,然后回到起始姿势。保持同一个角色、构图和背景,固定镜头,动作平滑自然。', + examplePush: '缓慢推进', + examplePushPrompt: '镜头缓缓向主体推进,自然光柔和,背景有轻微的风。保留原有布局、物体和视觉风格。', + exampleContinue: '延续这个瞬间', + exampleContinuePrompt: '从上一段结尾平滑接续,保持同一个主体、场景、镜头方向和光线,让动作自然收束。', + exampleSpeech: '工作室开场白', + exampleSpeechPrompt: '一处安静的角落,一杯热饮,一点创作的空间。欢迎来到我们的工作室。', + exampleNarration: '角色介绍', + exampleNarrationPrompt: '这是我们的小机器人。它喜欢挥手打招呼,认真思考新点子,也会在忙完以后好好休息。', + actionExamples: '试用示例动作', actionExamplesHint: '替换动作列表,保留共用描述、参考图和模型。', + actionExampleApply: '替换动作列表', actionExampleStarter: '桌宠基础动作', + actionExampleMood: '表情动作', packHappy: '开心', packHappyPrompt: '露出开心的表情,轻轻跳一下,保持同一个角色和镜头构图。', + packSleep: '休息', packSleepPrompt: '闭眼安静休息,保持同一个角色、身体比例和镜头构图。', + connection: '连接检查', connectionHint: '查看 OpenDirector 服务和可用的模型连接。', + connectionChecking: '正在检查连接…', connectionReady: '连接正常', + connectionPartial: '部分检查需要处理', connectionFailed: '未能连接 OpenDirector', + connectionApi: 'OpenDirector 接口', connectionCanvas: 'OpenDirector 画布', connectionProjects: '已保存工程', + connectionModels: '模型连接', connectionCount: '{count} 个可用', + connectionNoModels: '请在 OpenDirector → 设置 → 模型连接中添加模型,再检查一次。', + connectionConfigured: '这里列出 OpenDirector 已配置的模型。服务商权限和生成效果需要实际生成后确认。', + connectionNetwork: '请启动 OpenDirector,并检查接口地址。localhost 指的是运行 DSH 的那台电脑。', + connectionTimeout: 'OpenDirector 未及时响应,请确认服务已经启动完成。', + connectionAccess: '服务拒绝了访问,请检查 OpenDirector 地址和本地访问设置。', + connectionAddress: '这个地址没有找到接口,请检查插件配置中的 baseUrl。', + connectionService: 'OpenDirector 返回了错误,请检查服务后重试。', + connectionResponse: '服务返回的内容不符合预期,请检查接口地址和 OpenDirector 版本。', + connectionHost: 'DSH 连接暂时不可用,请重新连接 DSH 后重试。', + connectionSetup: '在当前配置的 opendirector 行中设置 baseUrl 和 canvasBaseUrl,README 中有配置示例。', + connectionImage: '生成图片', connectionEdit: '图片参考', connectionVideo: '图片转视频', + connectionContinue: '视频续写', connectionVoice: '配音', connectionCheck: '重新检查', + connectionCopy: '复制诊断信息', connectionCopied: '诊断信息已复制。', connectionCopyFailed: '复制失败,请选中下方诊断文本手动复制。', + connectionGuide: '安装配置说明', connectionOpen: '打开 OpenDirector', connectionPlugin: '管理插件', + connectionDiagnostic: '诊断文本', connectionReadOnly: '检查只读取工程和模型数量,不生成素材。', + packRevise: '调整动作', packEditPrompt: '动作描述', packSaveGenerate: '按这份描述生成', + packCancelEdit: '取消修改', packRevised: '描述已保存。确认后可以再生成一版候选。', + packActive: '请等待这个动作的任务结束,再修改描述。', + + actionPacks: '动作素材包', newActionPack: '制作动作素材包', packTitle: '素材包名称', + packHint: '固定一张角色参考图,分别生成各个动作,再为每个动作选一版。', + packEmpty: '这个工程还没有动作素材包,可以从已保存的图片开始。', + packSource: '用作角色参考', packShared: '共用描述', packActionName: '动作名称', + packDescription: '描述这个动作', packAdd: '添加动作', packRemove: '移除动作', + packCreate: '创建并生成 {count} 个动作', packMissing: '生成 {count} 个未开始的动作', + packCount: '已选择 {selected}/{total} 个动作', packExport: '下载动作素材包', + packExportHint: '每个动作选一版后,可导出按动作命名的媒体文件和 manifest.json,合计最多 128 MB。', + packInvalid: '请填写素材包名称,添加 1 至 6 个名称不重复、描述完整的动作。', + packNotStarted: '未开始', packContinue: '继续原提交', + packReference: '角色参考图', packSelectSource: '选择已保存的参考图', + packIdle: '待机', packIdlePrompt: '自然站立,姿态放松,保持同一个角色和外观。', + packWave: '挥手', packWavePrompt: '抬起一只手打招呼,保持同一个角色和外观。', + packThink: '思考', packThinkPrompt: '歪头思考,保持同一个角色和外观。', + packDefaultTitle: '角色动作', images: '图片结果', videos: '视频结果', original: '原图', sourceClip: '源片段', - candidate: '候选', unavailable: '暂时无法预览。可在画布查看。', + previousImage: '上一张', nextImage: '下一张', adoptImage: '采用这张图', + viewOriginal: '查看原图', fitImage: '适应窗口', actualImageSize: '实际大小', + originalUnavailable: '暂时无法加载原图。', duration: '{seconds} 秒', + candidate: '候选', unavailable: '暂时无法加载预览。', retryMedia: '重新加载预览', canvas: '打开画布', edit: '改图', firstFrame: '转成视频', continue: '续写', adopt: '采用', adopted: '已采用结果', - create: '创作素材', send: '发送请求', cancel: '取消', draftReady: '草稿已填入,检查后发送。', - draftBusy: '请先发送或清空当前草稿。', brief: '描述你想改什么', - shot: '描述接下来的镜头', ready: '请求已发送。', copyId: '复制结果 ID', copied: '已复制结果 ID。', - createPrompt: '用 OpenDirector 创作:', - editPrompt: '修改这张图片,先展示修改候选,再由我决定是否采用。', - firstFramePrompt: '用这张图片作为视频首帧,先展示候选,再由我决定是否采用。', - continuePrompt: '用支持续写的模型接着生成这段视频,先展示候选,再由我决定是否采用。', - adoptPrompt: '采用此结果,先读取工程当前版本,采用后给我画布链接。', - reference: 'OpenDirector 工程与结果', + createHint: '选好要制作的素材和保存工程,就可以开始。', backStep: '返回上一步', + animateStill: '让图片动起来', extendClip: '续写视频', videoStart: '从哪里开始', + pickStill: '选一张已保存的图片作为首帧。', pickClip: '选一个要续写的视频片段。', + noStills: '这个工程还没有可作首帧的图片。', noClips: '这个工程还没有已保存的视频。', + clipsUnsupported: '这一页的片段使用的模型不支持视频续写。', + makeStill: '先生成一张首帧图', videoProject: '选择工程即可浏览其中的图片和视频。', + noVideoMode: '已配置的视频模型暂不支持这种生成方式。', + libraryHint: '选择工程,也可以在聊天里说:“把上次的两版放一起,先帮我想想怎么改。”', + discussEdit: '讨论改图', discussPrompt: '我想修改「{project}」里的「{image}」(结果 {id})。先帮我拟一段改图提示词,等我确认后再生成。我想改的是:', + discussReady: '在聊天框补上想改的地方,再发送。', discussBusy: '聊天框正忙,稍后再试。', + referenceInChat: '引用到对话', planNextShot: '规划下一镜', chatRefAdded: '已把这版素材加到聊天输入框。', + assetReference: 'OpenDirector · {title} · {kind}(工程 {projectId},结果 {resultId})', + nextShotPrompt: '我想用这一版接下一镜。先帮我想想景别和镜头运动,等我确认再生成。', + useChatDraft: '带入聊天草稿', appendChatDraft: '追加聊天草稿', draftTooLong: '合并后的描述超过了模型的字数上限。', + savedOnly: '已保存的结果', wasFirstFrame: '用作「{videos}」的首帧', savedPrompt: '原提示词', + savedRefreshFailed: '暂时无法刷新这些版本,可以再试一次。', + editProposal: '改图提案', reviewEdit: '检查并改图', editProposalHint: '检查提示词和生成设置后,再决定是否生成。', + generationSettings: '生成设置', + moreCandidateCount: '新增候选数量', groupStopped: '其余计划候选未提交。', + candidateCount: '候选数量', generateGroup: '生成 {count} 个候选', + groupHint: '会提交 {count} 个独立生成任务,结果先保留为候选。', + groupSummary: '已完成 {done}/{total} · 失败 {failed}', groupTask: '候选 {number}', + groupUnsubmitted: '还有 {count} 个计划候选尚未确认提交。', + continueGroup: '继续提交原候选组', groupCompare: '对比所选图片', + candidateCountInvalid: '请选择 1 至 4 个候选。', + create: '创作素材', brief: '描述你想改什么', copyId: '复制结果 ID', copied: '已复制结果 ID。', + firstFrameSource: '首帧', motion: '描述画面怎么动', shot: '描述接下来的镜头', + videoDuration: '视频时长', chooseDuration: '选择时长', modelDuration: '此模型使用默认时长。', + useDefaultDuration: '使用模型默认时长', + durationUnavailable: '当前模型不支持所选时长。', + videoModeUnavailable: '请选择支持此视频操作的模型。', + videoSourceUnavailable: '暂时无法使用源素材,请刷新工程后重试。', + continuationHint: '请选择生成原片段时用的模型连接。续写沿用原片段的尺寸。', + noClipContinuation: '生成这段视频的模型不支持续写。', + saveFrame: '保存当前帧为 PNG', playForFrame: '先播放视频,在想保存的画面暂停。', + frameFailed: '这帧还没保存。等画面加载后再试一次。', + continuationUnavailable: '可在画布查看详情。如果源片段的接续缓存已过期,请重新生成源片段。', + resume: '继续工程', close: '关闭', chooseProject: '选择工程', + projectsEmpty: '还没有 OpenDirector 工程。', resultsEmpty: '这个工程还没有保存素材结果。', + loading: '加载中…', refresh: '刷新结果', libraryError: '暂时无法读取 OpenDirector,请刷新重试。', + recent: '已保存的结果', selected: '当前结果', adopting: '正在采用…', checkAdoption: '查询采用状态', + tasks: '任务', tasksEmpty: '没有符合筛选条件的生成任务。', viewTask: '查看进度', + taskProgress: '任务进度', backgroundHint: '关闭弹窗不会取消任务,可从「继续工程 → 任务」找回。', + chatTasks: '这次对话的任务', taskCount: '{count} 个任务', taskNeedsCheck: '待确认', partlyReady: '部分成功', partialGroup: '部分候选待确认', + taskStatusUnavailable: '暂时查不到进度', closeTaskHint: '可以关掉窗口继续聊天,在 OpenDirector 按钮旁查看进度和结果。', + cancelled: '已取消', interrupted: '已中断', + pendingSubmissions: '待确认的提交', pendingHint: '查询原来的提交,不会重新生成。', + startSeparateCreation: '开始另一项创作', + hidePending: '隐藏提示', hidePendingHint: '隐藏提示不会取消已提交的任务。', + pendingStorageUnavailable: '本页仍可恢复,但无法保存恢复入口。请先查询再刷新。', + pendingCheckFailed: '暂时无法查询这次提交,请在 OpenDirector 恢复连接后重试。', + pendingNotAccepted: '原提交未被接受。', pendingConfirmed: '原操作已确认,可打开画布继续。', + reuseSettings: '复用设置', resetTemplate: '恢复这版设置', keepOriginalOutput: '沿用原尺寸', + reuseHint: '沿用所选版本的设置,在同一工程的新节点中生成候选,审阅后再采用。', + reuseReferences: '沿用这版的参考素材', referenceMedia: '参考素材', + reuseUnavailable: '暂时无法读取已保存的设置。可以重新读取,或在 OpenDirector 中检查模型与参考素材。', + draftRestored: '已恢复未提交的草稿。', clearDraft: '清空草稿', resumeEarlierDraft: '继续之前的创作草稿', + modelUnavailable: '草稿中的模型暂不可用,请重新选择。', + projectUnavailable: '草稿中的工程暂不可用,请重新选择。', + stopGeneration: '请求停止', stoppingGeneration: '正在请求停止…', checkStop: '查询停止请求', + stopRequested: '已请求停止。', stopUnknown: '尚未确认停止请求,请查询原操作。', + stopFinished: '任务已结束。', stopFailed: '暂时无法请求停止,请先查询任务进度。', + stopChanged: '任务状态已变化,请查询进度后重试。', localStopped: '本地处理已停止。', + remoteStopUnconfirmed: '服务商取消尚未确认,请到服务商核对原任务。', + remoteStopped: '服务商已确认取消。', + + adoptUnknown: '尚未确认是否采用,请查询状态。', + adoptBusy: '请保存并关闭已打开的 OpenDirector 画布,然后重试。', + adoptConflict: '结果或画布状态已变,请刷新工程后再试。', + adoptFailed: '暂时无法采用此结果,请检查工程后重试。', + audios: '音频结果', speech: '配音', picture: '图片', mediaType: '素材类型', + newProject: '新建工程', projectName: '工程名称', model: '模型', local: '自部署', hosted: '在线服务', + output: '图片尺寸', voice: '音色 ID', prompt: '描述要生成的图片', speechText: '要朗读的文字', + chooseOutput: '选择图片尺寸', useModelDefault: '使用模型默认尺寸', + outputUnavailable: '当前模型不支持 {size}。请选择其他尺寸或切换模型。', + generate: '生成一个候选', submitting: '正在提交…', checkGeneration: '查询提交状态', + repeatGeneration: '再生成一个候选', + adjustGeneration: '调整设置,再做一版', previousRound: '上一轮结果', compareRevisions: '对比前后两版', + repeatHint: '使用此画布节点上保存的设置,已有候选仍可选择。', + repeatUnavailable: '暂时无法使用该生成节点,请打开画布查看。', + noModels: '请先在 OpenDirector 配置支持此操作的模型。', + failedToSubmit: '暂时无法提交生成,请检查工程和模型设置。', + generationUnknown: '尚未确认提交结果,可在这里或「继续工程 → 待确认的提交」查询。', + retrySubmission: '重新提交', retryGeneration: '重试生成', + connectionUnavailable: '暂时连不上 OpenDirector。恢复连接后可以重新提交。', + progressUnavailable: '暂时查不到进度。恢复连接后,可以继续查询原任务。', + providerUnknown: '模型服务可能已经收到请求。请先到服务商处核对原任务。', + rateLimited: '模型服务限制了请求频率,请稍等再试。', + credentialsRejected: '模型服务拒绝了当前凭证。请在「模型接入」中检查密钥。', + permissionDenied: '模型服务拒绝了访问。请检查当前账号是否有权使用此模型。', + inputRejected: '模型服务拒绝了输入。请到画布检查生成设置或参考素材。', + recoverOnCanvas: '可打开画布恢复原任务。', + draftSaved: '本次生成配置已保存到画布。', + waiting: '等待 OpenDirector…', queued: '排队中', running: '生成中…', + succeeded: '候选已生成', stopped: '生成已停止', failed: '生成失败', + quota: '请检查模型账号的余额或套餐额度,再重试生成。', + checkProgress: '查询进度', download: '下载原文件', + compareImages: '对比图片', compareHint: '选择两张图片,再打开对比。', + openComparison: '打开对比', clearComparison: '清空对比选择', + chooseComparison: '加入图片对比', removeComparison: '移出图片对比', + comparisonUnavailable: '暂时无法加载对比,请刷新结果并重新选择两张已保存图片。', + buffering: '缓冲中…', updatesPaused: '离线或切到后台时,自动状态查询已暂停。', + searchLibrary: '搜索已有作品', searchHint: '描述、节点名称、模型或 ID', + clearFilters: '清除搜索和筛选', taskStatus: '按任务状态筛选', allTasks: '全部任务', + activeTasks: '排队或生成中', + libraryType: '按素材类型筛选', librarySelection: '按采用状态筛选', libraryOrder: '排序', + allMedia: '全部素材', video: '视频', audio: '音频', allSelections: '全部结果', other: '其他结果', + previousPage: '上一页', nextPage: '下一页', pageNumber: '第 {number} 页', + newest: '最新优先', oldest: '最早优先', noMatches: '没有符合筛选条件的结果。', + actions: '更多操作', play: '播放', pause: '暂停', playbackFailed: '暂时无法播放。', + references: '参考图', chooseReferences: '添加参考图', hideReferences: '收起选图', + addReference: '加入参考图', removeReference: '移除参考图', referenceImage: '参考图', + moveReferenceEarlier: '将参考图 {number} 前移', moveReferenceLater: '将参考图 {number} 后移', + noMoreImages: '这一页没有其他已保存的图片。', + referenceOrder: '原图固定在第一张,其他图片按显示顺序发送。', + referenceLimit: '当前模型最多支持 {count} 张参考图。', + referencesChanged: '请核对所选图片和模型的参考图上限,再试一次。', } const border = '1px solid var(--dsw-alias-border-l1)' @@ -39,70 +406,2325 @@ window.__ModuleLoader__.load({ const row = { display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '.4rem' } const buttonStyle = { font: 'inherit', fontSize: '.82em', padding: '.3rem .65rem', borderRadius: '.45rem', - border, background: 'transparent', color: 'inherit', cursor: 'pointer', + border, cursor: 'pointer', + } + const dialogStyle = { width: 'min(52rem, calc(100vw - 2rem))', maxHeight: '86vh', boxSizing: 'border-box', + color: 'var(--dsw-alias-label-primary)', background: 'var(--dsw-alias-bg-layer-1)', border, + borderRadius: '1rem', padding: '1.25rem', boxShadow: '0 18px 60px #0003' } + const clientStyles = ` + .od-media-ui { color: var(--dsw-alias-label-primary); line-height: 1.5; } + .od-media-ui::backdrop { background: rgb(0 0 0 / .42); } + .od-media-ui .od-button { display: inline-flex; align-items: center; justify-content: center; gap: .35rem; + min-height: 2.15rem; background: transparent; color: inherit; text-decoration: none; transition: background 120ms, border-color 120ms; } + .od-media-ui .od-button:not(:disabled):hover { background: var(--dsw-alias-interactive-bg-hover); } + .od-media-ui .od-button.od-primary { background: var(--dsw-alias-button-primary-fill); + color: var(--dsw-alias-label-primary-foreground); border-color: transparent; } + .od-media-ui .od-button.od-primary:not(:disabled):hover { background: var(--dsw-alias-button-primary-hover); } + .od-media-ui .od-button:disabled { opacity: .5; cursor: default; } + .od-media-ui .od-button[data-current] { opacity: 1; color: var(--dsw-alias-brand-text); + background: var(--dsw-alias-interactive-bg-active); border-color: transparent; } + .od-media-ui :is(button, a, input, select, textarea, summary):focus-visible { + outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 3px; } + .od-media-ui :is(select, textarea, input:not([type=checkbox])) { box-sizing: border-box; max-width: 100%; + padding: .5rem .65rem; border: 1px solid var(--dsw-alias-border-l1); border-radius: .55rem; + background: var(--dsw-alias-bg-layer-2); color: var(--dsw-alias-label-primary); font: inherit; } + .od-media-ui form :is(input:not([type=checkbox]), select, textarea) { width: 100%; } + .od-media-ui form :is(input, select, textarea):disabled { opacity: .7; } + .od-media-ui form label { font-size: .85em; } + .od-media-ui .od-launcher { width: 2rem; min-height: 2rem; padding: 0 !important; border-color: transparent; } + .od-create-form { display: grid; gap: .85rem; } + .od-create-form > label:has(textarea) { font-weight: 600; } + .od-create-form textarea { resize: vertical; min-height: 5.75rem; font-weight: normal; } + .od-source-name { max-width: 14rem; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + .od-create-options { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(19rem,100%),1fr)); gap: .8rem 1.2rem; + border-top: 1px solid var(--dsw-alias-border-l1); padding-block: 1rem .5rem; align-items: start; } + .od-submit-row { display: flex; flex-wrap: wrap; gap: .45rem .8rem; align-items: center; + border-top: 1px solid var(--dsw-alias-border-l1); padding-top: .75rem; } + .od-submit-row small { color: var(--dsw-alias-label-secondary); flex: 1; } + .od-field-link { font: inherit; color: var(--dsw-alias-brand-text); cursor: pointer; + background: transparent; border: 0; padding: .25rem 0; text-decoration: underline; text-underline-offset: .2em; } + .od-media-ui [role=menuitem]:is(:hover,:focus-visible) { background: var(--dsw-alias-interactive-bg-hover); } + .od-dialog-header { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; + margin-bottom: 1rem; padding-bottom: .9rem; border-bottom: 1px solid var(--dsw-alias-border-l1); } + .od-dialog-header h2 { margin: .15rem 0; font-size: 1.15em; font-weight: 650; letter-spacing: -.02em; } + .od-eyebrow { color: var(--dsw-alias-label-secondary); font-size: .72em; letter-spacing: .04em; } + .od-hint { display: block; margin-top: .25rem; color: var(--dsw-alias-label-secondary); font-size: .8em; } + .od-media-ui .od-preview { --od-preview-height: clamp(8rem, 23vw, 15rem); padding: .7rem; border: 1px solid var(--dsw-alias-border-l1); border-radius: .85rem; + background: var(--dsw-alias-bg-layer-1); overflow: hidden; } + .od-media-ui .od-preview:only-child { --od-preview-height: clamp(14rem, 36vh, 23rem); } + .od-media-ui .od-preview[data-selected] { border-color: var(--dsw-alias-brand-primary); } + .od-version { font-size: .75em; padding: .05rem .45rem; border: 1px solid var(--dsw-alias-border-l1); border-radius: 1rem; } + .od-version[data-current] { color: var(--dsw-alias-brand-text); border-color: var(--dsw-alias-brand-primary); } + .od-preview figcaption { justify-content: space-between; padding: .1rem 0 .35rem; } + .od-media-ui .od-settings { padding: .6rem .75rem; margin-block: .7rem; + border: 1px solid var(--dsw-alias-border-l1); border-radius: .65rem; } + .od-settings > summary { color: var(--dsw-alias-label-secondary); font-size: .8em; cursor: pointer; } + .od-media-ui [role=status] { font-size: .88em; } + .od-media-ui [role=alert] { padding: .65rem .75rem; border: 1px solid var(--dsw-alias-border-l2); + border-radius: .6rem; font-size: .85em; } + @media (prefers-reduced-motion: reduce) { .od-media-ui .od-button { transition: none; } } + @media (max-width: 480px) { + dialog.od-media-ui { padding: .85rem !important; } + .od-media-ui .od-preview { padding: .55rem; } + } + ` + const libraryDefaults = { kind: 'all', selection: 'all', order: 'newest', status: 'all' } + const submissionMessages = new Map([ + ['creation.candidate_count', 'candidateCountInvalid'], + ['storage_busy', 'adoptBusy'], ['creation.unavailable', 'connectionUnavailable'], + ['creation.repeat_unavailable', 'repeatUnavailable'], ['revision_conflict', 'adoptConflict'], + ['creation.references', 'referencesChanged'], ['creation.reference_limit', 'referencesChanged'], + ['result.candidate_missing', 'referencesChanged'], + ['creation.video_mode', 'videoModeUnavailable'], ['creation.video_duration', 'durationUnavailable'], + ['creation.video_source', 'videoSourceUnavailable'], + ['creation.template_unavailable', 'reuseUnavailable'], ['creation.template_complex', 'reuseUnavailable'], + ]) + const generationMessages = new Map([ + ['quota', 'quota'], ['rate_limit', 'rateLimited'], ['authentication', 'credentialsRejected'], + ['permission', 'permissionDenied'], ['input', 'inputRejected'], ['reference', 'inputRejected'], + ['submission_unknown', 'providerUnknown'], + ]) + + function icon(name) { + const paths = { + create: 'm12 3 2.4 6.6L21 12l-6.6 2.4L12 21l-2.4-6.6L3 12l6.6-2.4Z', + library: 'M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z', + check: 'm5 12 4 4L19 6', + connection: 'M8 3v4M16 3v4M6 7h12v3a6 6 0 0 1-12 0ZM12 16v5', + } + return h('svg', { width: 15, height: 15, viewBox: '0 0 24 24', fill: 'none', + stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round', + 'aria-hidden': true, focusable: false, style: { flexShrink: 0 } }, h('path', { d: paths[name] })) } function button(label, onClick, options = {}) { - const { primary, ...attrs } = options + const { primary, current, symbol, className, ...attrs } = options return h('button', { type: 'button', onClick, ...attrs, - style: { ...buttonStyle, ...(primary && { background: surface, fontWeight: 600 }) }, - }, label) + className: ['od-button', primary && 'od-primary', className].filter(Boolean).join(' '), + 'data-current': current || undefined, + style: { ...buttonStyle, ...((primary || current) && { fontWeight: 600 }) }, + }, symbol && icon(symbol), label) + } + + function dialogHeader(title, close, t, hint) { + return h('header', { className: 'od-dialog-header' }, + h('div', null, h('span', { className: 'od-eyebrow' }, 'OpenDirector'), + h('h2', null, title), hint && h('small', { className: 'od-hint' }, hint)), + button(t('close'), close)) + } + + function SubmitRow({ reason, busy, label, focusModel }) { + const hint = useId() + return h('div', { className: 'od-submit-row' }, + h('small', { id: hint, role: 'status' }, focusModel + ? h('button', { type: 'button', className: 'od-field-link', onClick: e => e.currentTarget.form.elements.namedItem('model').focus() }, reason) + : reason), + button(label, undefined, { type: 'submit', primary: true, disabled: busy || Boolean(reason), + 'aria-describedby': reason ? hint : undefined })) + } + + function mediaHref(project, asset, kind) { + return '/api/opendirector/media?' + new URLSearchParams({ project, asset, kind }) + } + + const recentKey = '@opendirector/dsh-plugin:recent:v1:' + const recentCache = new Map() + function readRecent(scope) { + if (!scope) return {} + if (!recentCache.has(scope)) { + let value + try { value = JSON.parse(window.localStorage.getItem(recentKey + scope) ?? '{}') } catch {} + recentCache.set(scope, value && typeof value === 'object' && !Array.isArray(value) ? value : {}) + } + return recentCache.get(scope) + } + function rememberRecent(scope, changes) { + if (!scope) return + const previous = readRecent(scope) + const value = { ...previous, ...changes, + ...(changes.setups && { setups: { ...previous.setups, ...changes.setups } }) } + recentCache.set(scope, value) + try { window.localStorage.setItem(recentKey + scope, JSON.stringify(value)) } catch {} + } + function forgetRecent(scope) { + recentCache.set(scope, {}) + try { window.localStorage.removeItem(recentKey + scope) } catch {} + } + function lastChatProject(chat) { + const turns = chat?.timeline?.turnOrder ?? [] + for (let i = turns.length - 1; i >= 0; i--) { + const calls = chat.nodes.turnDataSource(turns[i], 'tool-call').getSnapshot() + const call = calls.findLast(({ root }) => root.name?.startsWith('opendirector_') && root.meta?.projectId) + if (call) return { id: call.root.meta.projectId, callId: call.root.callId } + } + return null + } + function initialProject(projects, scope, sessionId, chatProject) { + const recent = readRecent(scope) + const choice = sessionId ? recent.projectChoices?.[sessionId] : { id: recent.projectId } + const has = id => projects.some(project => project.id === id) + if (choice && choice.after === chatProject?.callId && (choice.id === '' || has(choice.id))) return choice.id + if (has(chatProject?.id)) return chatProject.id + return projects.length === 1 ? projects[0].id : '' + } + function chooseProject(scope, sessionId, chatProject, id) { + const changes = { projectId: id } + if (sessionId) changes.projectChoices = { ...readRecent(scope).projectChoices, + [sessionId]: { id, after: chatProject?.callId } } + rememberRecent(scope, changes) + } + function recentSetup(catalog, context, kind, videoMode) { + const saved = readRecent(catalog?.scope).setups?.[context] + const model = catalog?.models?.find(item => item.id === saved?.modelId && item.kind === kind + && (videoMode ? item.videoChoices?.[videoMode] : context === 'edit' || context.startsWith('pack:') ? item.maxImages > 0 : true)) + if (!model) return {} + const output = saved.output && typeof saved.output.size === 'string' && typeof saved.output.aspectRatio === 'string' + ? { size: saved.output.size, aspectRatio: saved.output.aspectRatio } : null + const durationSeconds = Number.isFinite(saved.durationSeconds) ? saved.durationSeconds : null + return { modelId: model.id, output, durationSeconds } + } + function creationModels(catalog, kind, videoMode, edit) { + return catalog?.models.filter(model => model.kind === kind + && (videoMode ? model.videoChoices?.[videoMode] : !edit || model.maxImages > 0)) + } + function creationSetup(catalog, context, kind, videoMode) { + const saved = context === 'continuation' ? {} : recentSetup(catalog, context, kind, videoMode) + if (saved.modelId) return saved + const models = creationModels(catalog, kind, videoMode, context === 'edit') + return models?.length === 1 ? { modelId: models[0].id } : {} + } + + const mediaDraftKey = '@opendirector/dsh-plugin:media-drafts:v1' + let mediaDrafts = new Map() + let draftsLoaded = false + let draftTimer + function readMediaDraft(key) { + if (!draftsLoaded) { + draftsLoaded = true + try { + const entries = JSON.parse(window.sessionStorage.getItem(mediaDraftKey) ?? '[]') + if (Array.isArray(entries)) { + mediaDrafts = new Map(entries.filter(entry => Array.isArray(entry) && entry.length === 2 + && typeof entry[0] === 'string' && entry[1]?.form && typeof entry[1].form.prompt === 'string')) + } + } catch {} + } + return mediaDrafts.get(key) + } + function flushMediaDrafts() { + if (!draftsLoaded) return + clearTimeout(draftTimer) + try { + if (mediaDrafts.size) window.sessionStorage.setItem(mediaDraftKey, JSON.stringify([...mediaDrafts])) + else window.sessionStorage.removeItem(mediaDraftKey) + } catch {} + } + function saveMediaDraft(key, value) { + readMediaDraft(key) + mediaDrafts.delete(key) + if (value) mediaDrafts.set(key, value) + clearTimeout(draftTimer) + draftTimer = setTimeout(flushMediaDrafts, 250) + } + + const pendingSubmissionsKey = '@opendirector/dsh-plugin:pending-submissions:v1' + const pendingListeners = new Set() + let pendingSubmissions + let pendingDurable = true + const pendingIdentity = item => item.projectId + ':' + item.operationId + function readPendingSubmissions() { + if (pendingSubmissions) return pendingSubmissions + try { + const values = JSON.parse(window.sessionStorage.getItem(pendingSubmissionsKey) ?? '[]') + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + const entries = Array.isArray(values) ? values.filter(item => item && uuid.test(item.projectId) + && uuid.test(item.operationId) && typeof item.context === 'string' && item.context.length <= 160 + && (item.repeatJobId == null || uuid.test(item.repeatJobId))).map(item => ({ + projectId: item.projectId, operationId: item.operationId, context: item.context, + label: typeof item.label === 'string' ? item.label.slice(0, 160) : '', + ...(typeof item.projectName === 'string' && { projectName: item.projectName.slice(0, 255) }), + ...(item.repeatJobId && { repeatJobId: item.repeatJobId }), + ...(['prepare', 'generate', 'revise'].includes(item.packAction) && { + packAction: item.packAction, packRedo: item.packRedo === true, + ...(uuid.test(item.packId) && { packId: item.packId }), + ...(Array.isArray(item.packItemIds) && item.packItemIds.length <= 6 + && item.packItemIds.every(id => uuid.test(id)) && { packItemIds: item.packItemIds }), + }), + ...(Number.isInteger(item.candidateCount) && item.candidateCount >= 2 && item.candidateCount <= 4 + && { candidateCount: item.candidateCount }), + })) : [] + pendingSubmissions = [...new Map(entries.map(item => [pendingIdentity(item), item])).values()] + } catch { + pendingSubmissions = [] + pendingDurable = false + } + return pendingSubmissions + } + function subscribePending(listener) { + pendingListeners.add(listener) + return () => pendingListeners.delete(listener) + } + function writePendingSubmissions(items) { + pendingSubmissions = items + try { + if (items.length) window.sessionStorage.setItem(pendingSubmissionsKey, JSON.stringify(items)) + else window.sessionStorage.removeItem(pendingSubmissionsKey) + pendingDurable = true + } catch { pendingDurable = false } + for (const listener of pendingListeners) listener() + } + function rememberSubmission(input, context, label) { + const item = { + projectId: input.projectId, operationId: input.operationId, context, label: label.slice(0, 160), + ...(input.projectName != null && { projectName: input.projectName.slice(0, 255) }), + ...(input.repeatJobId && { repeatJobId: input.repeatJobId }), + ...(input.packAction && { packAction: input.packAction, packId: input.packId, + packItemIds: input.packItemIds, packRedo: input.packRedo === true }), + ...(input.candidateCount > 1 && { candidateCount: input.candidateCount }), + } + writePendingSubmissions([...readPendingSubmissions().filter(value => pendingIdentity(value) !== pendingIdentity(item)), item]) + } + function forgetSubmission(item) { + if (!item) return + const previous = readPendingSubmissions() + const next = previous.filter(value => pendingIdentity(value) !== pendingIdentity(item)) + if (next.length !== previous.length) writePendingSubmissions(next) } - function useComposerRequest(useInput, inputActions) { - const emptyRevision = useInput(state => state.phase === 'plain' && !state.draft.trim() - && !state.attachmentIds.length && !state.occurrences.length ? state.draftRev : null) - return (text, send = false) => { - if (emptyRevision === null) return false - const span = inputActions.captureInsertion() - if (span.draftRev !== emptyRevision || !inputActions.insertText(text, span)) return false - if (send) inputActions.submit() - return true + function PendingSubmissions({ context, onRecovered, disabled = false, t }) { + const saved = useSyncExternalStore(subscribePending, readPendingSubmissions) + const items = context === 'packs' ? saved.filter(item => item.packAction) : context ? saved.filter(item => item.context === context) : saved + const [page, setPage] = useState({}) + const [feedback, setFeedback] = useState({}) + const busy = useRef(new Set()) + const start = page.after ? items.findIndex(item => pendingIdentity(item) === page.after) + 1 : 0 + const visible = items.slice(start, start + 12) + useEffect(() => { + if (page.after && !items.some(item => pendingIdentity(item) === page.after)) setPage({}) + }, [saved, page, context]) + async function check(item) { + const key = pendingIdentity(item) + if (busy.current.has(key)) return + busy.current.add(key) + setFeedback(previous => ({ ...previous, [key]: { message: 'submitting' } })) + try { + const { projectId, operationId, repeatJobId, projectName, candidateCount } = item + const response = await fetch(item.packAction ? '/api/opendirector/action-packs' : '/api/opendirector/creation', { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-OpenDirector-Action': '1' }, + body: JSON.stringify(item.packAction ? { action: 'check', projectId, operationId, + packId: item.packId, packAction: item.packAction, itemIds: item.packItemIds } : { projectId, operationId, ...(repeatJobId && { repeatJobId }), + ...(projectName != null && { projectName }), ...(candidateCount && { candidateCount }), check: true }), + }) + if (!response.ok) throw new Error('Receipt unavailable') + const value = await response.json() + if (item.packAction && value.found) { + setFeedback(previous => ({ ...previous, [key]: { message: value.status === 'unknown' ? 'generationUnknown' : 'pendingConfirmed' } })) + onRecovered({ ...value, projectId, recovery: item }) + } else if (value.jobId && (value.groupId || ['accepted', 'applied', 'noop'].includes(value.status))) { + onRecovered({ ...value, projectId, prompt: item.label, recovery: item, + ...(value.groupId && { requestedCount: candidateCount }) }) + } else { + setFeedback(previous => ({ ...previous, [key]: { + message: value.status === 'unknown' ? 'generationUnknown' + : value.status === 'rejected' ? 'pendingNotAccepted' : 'pendingConfirmed', + canvasUrl: value.draftSaved || value.projectCreated ? value.canvasUrl : undefined, + } })) + } + } catch { + setFeedback(previous => ({ ...previous, [key]: { message: 'pendingCheckFailed' } })) + } finally { + busy.current.delete(key) + setFeedback(previous => ({ ...previous, [key]: { ...previous[key] } })) + } } + if (!items.length) return null + return h('section', { 'aria-label': t('pendingSubmissions'), style: { display: 'grid', gap: '.5rem', marginBlock: '.7rem' } }, + h('strong', null, t('pendingSubmissions')), h('small', null, t('pendingHint')), + !pendingDurable && h('p', { role: 'alert' }, t('pendingStorageUnavailable')), + ...visible.map(item => { + const key = pendingIdentity(item) + const value = feedback[key] + return h('article', { key, style: { display: 'grid', gap: '.4rem', border, padding: '.6rem', borderRadius: '.55rem' } }, + h('span', { style: { overflowWrap: 'anywhere' } }, item.projectName || item.label || item.projectId), + item.projectName && item.label && h('small', null, item.label), + h('div', { style: row }, + button(t('checkGeneration'), () => check(item), { disabled: disabled || busy.current.has(key) }), + button(t('hidePending'), () => forgetSubmission(item), { title: t('hidePendingHint'), disabled: disabled || busy.current.has(key) }), + value?.canvasUrl && canvasLink(value.canvasUrl, t)), + value?.message && h('small', { role: 'status' }, t(value.message))) + }), + h('small', null, t('hidePendingHint')), + h(PageControls, { cursor: page, + nextCursor: items.length > start + 12 ? pendingIdentity(visible.at(-1)) : null, onPage: setPage, t })) + } + + const taskStorage = '@opendirector/dsh-plugin:chat-tasks:v1' + const taskListeners = new Set() + const taskDialogs = new Map() + const backgroundReads = new Map() + let chatTasks + function getChatTasks() { + if (chatTasks) return chatTasks + try { chatTasks = JSON.parse(window.sessionStorage.getItem(taskStorage) ?? '[]') } catch {} + if (!Array.isArray(chatTasks)) chatTasks = [] + return chatTasks + } + function subscribeTasks(listener) { taskListeners.add(listener); return () => taskListeners.delete(listener) } + const taskKey = task => task.projectId + ':' + (task.groupId || task.jobId) + const activeTask = phase => ['accepted', 'queued', 'running'].includes(phase) + function changeTask(sessionId, task, changes) { + if (!sessionId || !task?.jobId) return + const tasks = getChatTasks() + const previous = tasks.find(item => item.sessionId === sessionId && taskKey(item) === taskKey(task)) + if (changes && previous && Object.keys(changes).every(key => changes[key] === previous[key])) return + if (previous) chatTasks = changes ? tasks.map(item => item === previous ? { ...item, ...changes } : item) + : tasks.filter(item => item !== previous) + else if (changes?.jobId) chatTasks = [{ ...changes, sessionId }, ...tasks] + else return + try { + if (chatTasks.length) window.sessionStorage.setItem(taskStorage, JSON.stringify(chatTasks)) + else window.sessionStorage.removeItem(taskStorage) + } catch {} + for (const listener of taskListeners) listener() + } + async function readTask(task, signal) { + const params = new URLSearchParams({ project: task.projectId, ...(task.groupId ? { group: task.groupId } : { job: task.jobId }) }) + const response = await fetch('/api/opendirector/creation?' + params, { signal }) + if (!response.ok) throw new Error('Job status unavailable') + return response.json() + } + function recordProgress(sessionId, task, value) { + const complete = task.groupId && task.requestedCount && value.totalCount >= task.requestedCount + const partial = task.groupId && task.groupComplete === false && !complete + const uncertain = value.category === 'submission_unknown' || value.jobs?.some(item => item.category === 'submission_unknown') + const mixed = value.completedCount > 0 && value.failedCount > 0 + const phase = activeTask(value.status) ? value.status : uncertain ? 'providerUnknown' + : partial ? 'partialGroup' : mixed ? 'partlyReady' : value.status + changeTask(sessionId, task, { phase, + unavailable: false, ...(complete && { groupComplete: true, canContinueGroup: false, acceptedCount: value.totalCount }) }) + } + function rememberTask(sessionId, projectId, receipt, kind, prompt) { + if (!projectId || !receipt.jobId) return + const task = { projectId, jobId: receipt.jobId, ...(receipt.groupId && { groupId: receipt.groupId }) } + changeTask(sessionId, task, { ...task, status: receipt.status, phase: 'accepted', kind, prompt: prompt?.slice(0, 160), + canvasUrl: receipt.canvasUrl, ...(receipt.groupId && { groupComplete: receipt.groupComplete, + requestedCount: receipt.requestedCount, acceptedCount: receipt.acceptedCount, canContinueGroup: receipt.canContinueGroup }) }) + } + function ChatOverlay({ onReturn, children }) { + const chat = useContext(ChatContext) + return h(ChatContext.Provider, { value: { ...chat, returnToChat() { + onReturn() + chat?.returnToChat?.() + } } }, children) } - function CreateMedia({ t, useInput, inputActions }) { - const request = useComposerRequest(useInput, inputActions) - const [busy, setBusy] = useState(false) + function SessionTasks({ sessionId, t }) { + const tasks = useSyncExternalStore(subscribeTasks, getChatTasks).filter(task => task.sessionId === sessionId) + const [panel, setPanel] = useState(null) + const list = useRef(null) + const viewed = useRef(null) + const active = tasks.some(task => activeTask(task.phase)) + useEffect(() => { + if (!active) return + let timer, current, disposed = false + const visible = () => !document.hidden && navigator.onLine !== false + async function check() { + if (disposed || current || !visible()) return + for (const task of getChatTasks()) { + if (disposed || !visible()) break + const key = taskKey(task) + if (task.sessionId !== sessionId || !activeTask(task.phase) || taskDialogs.has(key) || backgroundReads.has(key)) continue + const controller = new AbortController() + current = controller + backgroundReads.set(key, controller) + try { + const value = await readTask(task, controller.signal) + if (!controller.signal.aborted) recordProgress(sessionId, task, value) + } catch { + if (!controller.signal.aborted) changeTask(sessionId, task, { unavailable: true }) + } finally { + backgroundReads.delete(key) + current = null + } + } + if (!disposed && visible()) timer = setTimeout(check, 15000) + } + function wake() { + clearTimeout(timer) + if (visible()) timer = setTimeout(check, 0) + else current?.abort() + } + if (visible()) timer = setTimeout(check, 15000) + document.addEventListener('visibilitychange', wake) + window.addEventListener('online', wake) + window.addEventListener('offline', wake) + return () => { + disposed = true + clearTimeout(timer) + current?.abort() + document.removeEventListener('visibilitychange', wake) + window.removeEventListener('online', wake) + window.removeEventListener('offline', wake) + } + }, [sessionId, active]) + useEffect(() => { if (panel === 'list') list.current?.showModal() }, [panel]) + if (!tasks.length) return null + const selected = tasks.find(item => taskKey(item) === panel) + const phase = task => t(task.unavailable ? 'taskStatusUnavailable' : task.phase === 'accepted' ? 'queued' + : task.phase === 'providerUnknown' ? 'taskNeedsCheck' : task.phase) + const summary = tasks.length === 1 ? phase(tasks[0]) : t('taskCount').replace('{count}', tasks.length) + function openPanel(key) { viewed.current = null; setPanel(key) } + function closeTask(toChat = false) { + setPanel(!toChat && tasks.length > 1 ? 'list' : null) + if (selected && viewed.current === taskKey(selected) && !activeTask(selected.phase) && !['partialGroup', 'providerUnknown'].includes(selected.phase)) + changeTask(sessionId, selected, null) + } return h('div', { style: row }, - button(t('create'), () => setBusy(!request(t('createPrompt'))), { title: 'OpenDirector' }), - busy && h('span', { role: 'status', style: { color: muted, fontSize: '.78em' } }, t('draftBusy'))) + button(summary, () => openPanel(tasks.length === 1 ? taskKey(tasks[0]) : 'list'), { + 'aria-label': t('chatTasks') + ' · ' + summary, 'aria-haspopup': 'dialog', title: t('chatTasks'), + }), + panel === 'list' && h('dialog', { ref: list, className: 'od-media-ui', style: dialogStyle, 'aria-label': t('chatTasks'), + onClose: e => { if (e.target === e.currentTarget) setPanel(null) } }, + dialogHeader(t('chatTasks'), () => list.current.close(), t), + ...tasks.map(task => button((task.prompt || t(task.kind === 'image' ? 'picture' : task.kind || 'taskProgress')) + ' · ' + phase(task), + () => openPanel(taskKey(task)), { key: taskKey(task) }))), + selected && h(ChatOverlay, { onReturn: () => closeTask(true) }, + h(GenerationDialog, { key: taskKey(selected), sessionId, existingJob: selected, t, onClose: closeTask, + onSettledRead: () => { viewed.current = taskKey(selected) } }))) } - function Preview({ projectId, assetId, resultId, kind, title, t, request }) { + function CreateMedia({ t, openPlugin, appendChatDraft, useInput, focusChat, sessionId, readChatProject }) { + const [open, setOpen] = useState(null) + const [chatProject, setChatProject] = useState(null) + const [menu, setMenu] = useState(null) + const trigger = useRef(null) + const actions = [['create', 'creation'], ['resume', 'library'], ['actionPacks', 'packs'], ['connection', 'connection']] + .map(([label, page]) => ({ label, run: () => { + if (page === 'library' || page === 'creation') setChatProject(readChatProject?.()) + setOpen(page) + } })) + const chat = { sessionId, appendChatDraft, useInput, returnToChat() { + setOpen(null) + focusChat?.() + } } + return h(ChatContext.Provider, { value: chat }, h('div', { className: 'od-media-ui', style: row }, + button(icon('create'), event => { + const rect = event.currentTarget.getBoundingClientRect() + setMenu(menu ? null : { x: rect.left, y: rect.top, above: true }) + }, { ref: trigger, className: 'od-launcher', title: 'OpenDirector', 'aria-label': 'OpenDirector', + 'aria-haspopup': 'menu', 'aria-expanded': Boolean(menu) }), + sessionId && h(SessionTasks, { sessionId, t }), + menu && h(ActionMenu, { actions, position: menu, trigger, t, label: 'OpenDirector', + close: (restore = true) => { setMenu(null); if (restore) trigger.current?.focus() } }), + open === 'connection' && h(ConnectionDialog, { t, openPlugin, onClose: () => setOpen(null) }), + open === 'packs' && h(ActionPackLibrary, { t, onClose: () => setOpen(null) }), + open === 'library' && h(ProjectLibrary, { t, sessionId, chatProject, onClose: () => setOpen(null) }), + open === 'creation' && h(GenerationDialog, { t, sessionId, chatProject, onClose: () => setOpen(null) }))) + } + + function ConnectionDialog({ t, openPlugin, onClose }) { + const dialog = useRef(null) + const [value, setValue] = useState(null) const [failed, setFailed] = useState(false) - const [action, setAction] = useState(null) - const [brief, setBrief] = useState('') - const [status, setStatus] = useState('') - const url = '/api/opendirector/media?' + new URLSearchParams({ project: projectId, asset: assetId, kind }) - const video = kind === 'video' - const mediaStyle = { width: '100%', height: 'clamp(8rem, 23vw, 15rem)', display: 'block', objectFit: 'contain', - borderRadius: '.55rem', background: surface } - const onError = () => setFailed(true) - const media = video - ? h('video', { src: url, controls: true, playsInline: true, preload: 'none', 'aria-label': title, onError, style: mediaStyle }) - : h('a', { href: url, target: '_blank', rel: 'noopener noreferrer' }, - h('img', { src: url, alt: title, loading: 'lazy', onError, style: mediaStyle })) - function message(key, detail = '') { - return [t(key), t('reference') + ' ' + projectId + ' / ' + resultId, detail].filter(Boolean).join('\n') + const [checking, setChecking] = useState(true) + const [revision, setRevision] = useState(0) + const [copyState, setCopyState] = useState('') + const [forgotten, setForgotten] = useState(false) + useEffect(() => { dialog.current.showModal() }, []) + useEffect(() => { + const controller = new AbortController() + setChecking(true) + setValue(null) + setFailed(false) + setCopyState('') + fetch('/api/opendirector/connection', { signal: controller.signal }).then(async response => { + if (!response.ok) throw new Error('Connection check unavailable') + const report = await response.json() + if (!controller.signal.aborted) setValue(report) + }).catch(() => { if (!controller.signal.aborted) setFailed(true) }) + .finally(() => { if (!controller.signal.aborted) setChecking(false) }) + return () => controller.abort() + }, [revision]) + const statuses = value ? [value.projects.status, value.models.status] : [] + const problem = statuses.find(status => status !== 'ok') + const heading = checking ? 'connectionChecking' : failed ? 'connectionFailed' + : !problem ? 'connectionReady' : statuses.includes('ok') ? 'connectionPartial' : 'connectionFailed' + const errors = { + network: 'connectionNetwork', timeout: 'connectionTimeout', access: 'connectionAccess', + address: 'connectionAddress', service: 'connectionService', response: 'connectionResponse', + } + const diagnostic = value ? [ + 'OpenDirector DSH plugin ' + value.version, + 'API: ' + value.apiUrl, 'Canvas: ' + value.canvasUrl, + 'Projects: ' + value.projects.status + (value.projects.status === 'ok' ? ' (' + value.projects.count + ')' : ''), + 'Models: ' + value.models.status + (value.models.status === 'ok' ? ' (' + value.models.count + ')' : ''), + ...(value.models.status === 'ok' ? Object.entries(value.models.capabilities).map(([kind, count]) => kind + ': ' + count) : []), + ].join('\n') : '' + async function copy() { + try { await navigator.clipboard.writeText(diagnostic); setCopyState('connectionCopied') } + catch { setCopyState('connectionCopyFailed') } + } + const capabilityNames = { image: 'connectionImage', imageEdit: 'connectionEdit', + imageToVideo: 'connectionVideo', videoContinuation: 'connectionContinue', voiceover: 'connectionVoice' } + return h('dialog', { ref: dialog, className: 'od-media-ui', 'aria-label': t('connection'), style: dialogStyle, + onCancel: onClose }, + dialogHeader(t('connection'), onClose, t, t('connectionHint')), + h('p', { role: 'status', style: { fontWeight: 600 } }, t(heading)), + failed && h('p', { role: 'alert' }, t('connectionHost')), + value && h('div', { style: { display: 'grid', gap: '.8rem' } }, + h('dl', { style: { margin: 0, display: 'grid', gap: '.35rem', overflowWrap: 'anywhere' } }, + h('dt', null, t('connectionApi')), h('dd', { style: { margin: 0 } }, h('code', null, value.apiUrl)), + h('dt', null, t('connectionCanvas')), h('dd', { style: { margin: 0 } }, h('code', null, value.canvasUrl)), + h('dt', null, t('connectionProjects')), h('dd', { style: { margin: 0 } }, + value.projects.status === 'ok' ? String(value.projects.count) : t(errors[value.projects.status])), + h('dt', null, t('connectionModels')), h('dd', { style: { margin: 0 } }, + value.models.status === 'ok' ? t('connectionCount').replace('{count}', value.models.count) : t(errors[value.models.status]))), + problem && h('p', { role: 'alert' }, t(errors[problem])), + value.models.status === 'ok' && (value.models.count === 0 + ? h('p', null, t('connectionNoModels')) + : h('div', null, + h('div', { style: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(9rem, 1fr))', gap: '.5rem' } }, + ...Object.entries(value.models.capabilities).map(([kind, count]) => h('div', { + key: kind, style: { border, borderRadius: '.65rem', padding: '.7rem' }, + }, h('small', { style: { color: muted } }, t(capabilityNames[kind])), h('div', { style: { fontSize: '1.3em' } }, count)))), + h('small', { className: 'od-hint' }, t('connectionConfigured')))), + h('div', { style: row }, h('a', { href: value.canvasUrl, className: 'od-button', style: buttonStyle, + target: '_blank', rel: 'noopener noreferrer' }, t('connectionOpen'))), + h('details', null, h('summary', null, t('connectionDiagnostic')), + h('pre', { style: { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere', fontSize: '.8em' } }, diagnostic), + button(t('forgetRecent'), () => { forgetRecent(value.apiUrl); setForgotten(true) }), + forgotten && h('p', { role: 'status' }, t('recentForgotten')))), + h('p', { className: 'od-hint' }, t('connectionSetup')), + h('div', { style: row }, + button(t('connectionCheck'), () => setRevision(v => v + 1), { disabled: checking }), + value && button(t('connectionCopy'), copy, { disabled: checking }), + openPlugin && button(t('connectionPlugin'), () => { onClose(); openPlugin() }), + h('a', { href: 'https://github.com/ThinkFlowLab/OpenDirector/tree/main/plugins/deepseek-harness#configuration', + target: '_blank', rel: 'noopener noreferrer', className: 'od-button', style: buttonStyle }, t('connectionGuide'))), + copyState && h('p', { role: 'status' }, t(copyState)), + h('small', { className: 'od-hint' }, t('connectionReadOnly'))) + } + + function PageControls({ cursor, nextCursor, disabled, onPage, t }) { + const before = cursor.before ?? [] + if (!before.length && !nextCursor) return null + return h('div', { style: { ...row, marginTop: '.7rem' } }, + button(t('previousPage'), () => onPage({ after: before.at(-1), before: before.slice(0, -1) }), + { disabled: disabled || !before.length }), + h('span', null, t('pageNumber').replace('{number}', before.length + 1)), + button(t('nextPage'), () => onPage({ after: nextCursor, before: [...before, cursor.after ?? null] }), + { disabled: disabled || !nextCursor })) + } + + async function readLibrary(projectId, signal, filters = {}, after = null) { + const query = projectId ? '?' + new URLSearchParams({ + project: projectId, ...filters, ...(after && { after }), + }) : '' + const response = await fetch('/api/opendirector/library' + query, { signal }) + if (!response.ok) throw new Error('Project read failed') + return response.json() + } + + function ProjectLibrary({ t, onClose, sessionId, chatProject }) { + const dialog = useRef(null) + const initialized = useRef(false) + const [projects, setProjects] = useState(null) + const [scope, setScope] = useState('') + const [projectId, setProjectId] = useState('') + const [library, setLibrary] = useState(null) + const [error, setError] = useState(false) + const [pending, setPending] = useState(true) + const [filters, setFilters] = useState(libraryDefaults) + const [search, setSearch] = useState('') + const [query, setQuery] = useState('') + const [composing, setComposing] = useState(false) + const [page, setPage] = useState({}) + const [view, setView] = useState('results') + const [task, setTask] = useState(null) + const [compareMode, setCompareMode] = useState(false) + const [comparison, setComparison] = useState([]) + const [comparing, setComparing] = useState(false) + const taskView = view === 'jobs' + const searching = search.trim() !== query + useEffect(() => { + dialog.current.showModal() + }, []) + useEffect(() => { + const controller = new AbortController() + setPending(true) + setError(false) + readLibrary(projectId, controller.signal, { ...filters, view, q: query }, page.after).then(value => { + if (controller.signal.aborted) return + if (projectId) setLibrary(value) + else { + setProjects(value.projects) + setScope(value.scope) + if (!initialized.current) { + initialized.current = true + setProjectId(initialProject(value.projects, value.scope, sessionId, chatProject)) + if (!chatProject && readRecent(value.scope).view === 'jobs') setView('jobs') + } + } + setPending(false) + }).catch(() => { + if (controller.signal.aborted) return + setError(true) + setPending(false) + }) + return () => controller.abort() + }, [projectId, filters, page, view, query]) + useEffect(() => { + if (composing) return + const timeout = setTimeout(() => { + if (search.trim() === query) return + setQuery(search.trim()) + setLibrary(null) + setPage({}) + }, 250) + return () => clearTimeout(timeout) + }, [search, query, composing]) + const current = !searching && library?.projectId === projectId ? library : null + const refresh = () => setPage({}) + const filtered = search.trim() || Object.keys(libraryDefaults).some(key => filters[key] !== libraryDefaults[key]) + function clearFilters() { + setSearch('') + setQuery('') + setFilters(libraryDefaults) + setLibrary(null) + refresh() } - function open(key) { - setAction(key) - setStatus('') + function changeProject(id) { + chooseProject(scope, sessionId, chatProject, id) + setProjectId(id) + setComparison([]) + setComparing(false) + setLibrary(null) + refresh() + } + function changeView(value) { + rememberRecent(scope, { view: value }) + setView(value) + setLibrary(null) + refresh() + } + function toggleComparison(image) { + setComparison(previous => previous.some(item => item.resultId === image.resultId) + ? previous.filter(item => item.resultId !== image.resultId) + : previous.length < 2 ? [...previous, image] : previous) + } + function filterControl(key, label, options) { + return h('select', { + value: filters[key], 'aria-label': t(label), title: t(label), + onChange: event => { + const value = event.target.value + setFilters(previous => ({ ...previous, [key]: value })) + setLibrary(null) + refresh() + }, + }, ...options.map(([value, text]) => h('option', { key: value, value }, t(text)))) + } + return h('dialog', { + className: 'od-media-ui', + ref: dialog, onClose: event => { if (event.target === event.currentTarget) onClose() }, + 'aria-label': t('resume'), + style: dialogStyle, + }, + dialogHeader(t('resume'), () => dialog.current.close(), t, t('libraryHint')), + h(PendingSubmissions, { t, onRecovered: setTask }), + h('div', { style: { ...row, marginBlock: '.7rem' } }, + projects?.length > 0 && h('select', { + value: projectId, onChange: event => changeProject(event.target.value), 'aria-label': t('chooseProject'), + }, + h('option', { value: '' }, t('chooseProject')), + ...projects.map(({ id, name }) => h('option', { key: id, value: id }, name))), + button(t('refresh'), refresh, { disabled: pending }), + current && canvasLink(current.canvasUrl, t)), + projectId && h('div', { style: { ...row, marginBlock: '.7rem' } }, + button(t('recent'), () => changeView('results'), { 'aria-pressed': !taskView }), + button(t('tasks'), () => changeView('jobs'), { 'aria-pressed': taskView }), + button(t('compareImages'), () => setCompareMode(value => !value), { 'aria-pressed': compareMode })), + projectId && compareMode && h('section', { 'aria-label': t('compareImages'), style: { display: 'grid', gap: '.4rem', marginBlock: '.7rem' } }, + h('small', null, t('compareHint')), + h('div', { style: row }, + ...comparison.map((image, index) => button((index + 1) + ' · ' + image.title + ' ×', () => toggleComparison(image), { + key: image.resultId, 'aria-label': t('removeComparison') + ' ' + (index + 1), + })), + button(t('openComparison') + ' (' + comparison.length + '/2)', () => setComparing(true), { disabled: comparison.length !== 2 }), + comparison.length > 0 && button(t('clearComparison'), () => setComparison([])))), + projectId && h('div', { style: { ...row, marginBlock: '.7rem' } }, + h('input', { type: 'search', 'aria-label': t('searchLibrary'), placeholder: t('searchHint'), + maxLength: 200, value: search, style: { flex: '1 1 18rem', minWidth: 0 }, + onChange: event => setSearch(event.target.value), + onCompositionStart: () => setComposing(true), + onCompositionEnd: event => { setComposing(false); setSearch(event.currentTarget.value) }, + }), + filtered && button(t('clearFilters'), clearFilters)), + projectId && h('div', { style: { ...row, marginBlock: '.7rem' } }, + filterControl('kind', 'libraryType', [['all', 'allMedia'], ['image', 'picture'], ['video', 'video'], ['audio', 'audio']]), + taskView && filterControl('status', 'taskStatus', [['all', 'allTasks'], ['active', 'activeTasks'], + ['succeeded', 'succeeded'], ['failed', 'failed'], ['cancelled', 'cancelled'], ['interrupted', 'interrupted']]), + !taskView && filterControl('selection', 'librarySelection', [['all', 'allSelections'], ['current', 'selected'], ['other', 'other']]), + filterControl('order', 'libraryOrder', [['newest', 'newest'], ['oldest', 'oldest']])), + (pending || searching) && h('p', { role: 'status' }, t('loading')), + error && h('p', { role: 'alert' }, t('libraryError')), + projects?.length === 0 && h('p', null, t('projectsEmpty')), + current && h('section', { 'aria-label': t(taskView ? 'tasks' : 'recent') }, + h('h3', null, t(taskView ? 'tasks' : 'recent')), + taskView ? (current.jobs.length === 0 ? h('p', null, t('tasksEmpty')) + : h('div', { style: { display: 'grid', gap: '.65rem' } }, + ...current.jobs.map(job => h('article', { + key: job.jobId, 'data-opendirector-job': job.jobId, style: { display: 'grid', gap: '.4rem', padding: '.65rem', border, borderRadius: '.55rem' }, + }, + h('strong', null, t(['queued', 'running', 'succeeded', 'failed', 'cancelled', 'interrupted'].includes(job.status) + ? job.status : 'waiting')), + job.title && h('span', null, job.title), + h('small', { style: { color: muted } }, job.modelId), + h('p', { style: { margin: 0, overflowWrap: 'anywhere' } }, job.prompt), + button(t('viewTask'), () => setTask({ ...job, projectId, canvasUrl: current.canvasUrl }), { 'aria-haspopup': 'dialog' }))))) + : current.results.length === 0 ? h('p', null, t(!query && filters.kind === 'all' && filters.selection === 'all' ? 'resultsEmpty' : 'noMatches')) + : h(ImageReviewGrid, { style: { display: 'grid', gap: '.75rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(15rem, 100%), 1fr))' } }, + ...current.results.map((candidate, index) => h(Preview, { + ...candidate, key: candidate.resultId, projectId, projectName: current.projectName, t, canvasUrl: current.canvasUrl, + title: candidate.title || (candidate.version ? t('candidate') : `${t('candidate')} ${index + 1}`), + onAdopted: refresh, + compareSelected: comparison.some(item => item.resultId === candidate.resultId), + compareDisabled: comparison.length === 2 && !comparison.some(item => item.resultId === candidate.resultId), + onCompare: compareMode && candidate.kind === 'image' + ? () => toggleComparison({ resultId: candidate.resultId, title: candidate.title || candidate.resultId.slice(0, 8) }) : undefined, + }))), + h(PageControls, { cursor: page, nextCursor: current.nextCursor, disabled: pending, onPage: setPage, t })), + comparing && h(ImageComparisonDialog, { + projectId, resultIds: comparison.map(item => item.resultId), t, onAdopted: refresh, + onClose: () => setComparing(false), + }), + task && (task.packId ? h(ActionPackDialog, { projectId: task.projectId, packId: task.packId, + recovery: task.recovery, status: task.status, t, onClose: () => { setTask(null); refresh() } }) : h(GenerationDialog, { + existingJob: task, t, onClose: () => { setTask(null); refresh() }, + }))) + } + + function ImageComparisonDialog({ projectId, resultIds, t, onClose, onAdopted }) { + const dialog = useRef(null) + const [value, setValue] = useState(null) + const [failed, setFailed] = useState(false) + const [revision, setRevision] = useState(0) + const pair = resultIds.join(',') + useEffect(() => { dialog.current.showModal() }, []) + useEffect(() => { + const controller = new AbortController() + setFailed(false) + fetch('/api/opendirector/library?' + new URLSearchParams({ project: projectId, compare: pair }), + { signal: controller.signal }).then(async response => { + if (!response.ok) throw new Error('Comparison unavailable') + const result = await response.json() + if (!controller.signal.aborted) setValue(result) + }).catch(() => { if (!controller.signal.aborted) setFailed(true) }) + return () => controller.abort() + }, [projectId, pair, revision]) + return h('dialog', { + className: 'od-media-ui', + ref: dialog, 'aria-label': t('compareImages'), + onClose: event => { if (event.target === event.currentTarget) onClose() }, + style: { ...dialogStyle, width: 'min(80rem, calc(100vw - 2rem))' }, + }, + dialogHeader(t('compareImages'), () => dialog.current.close(), t), + !value && !failed && h('p', { role: 'status' }, t('loading')), + failed && h('div', null, h('p', { role: 'alert' }, t('comparisonUnavailable')), + button(t('refresh'), () => setRevision(previous => previous + 1))), + value && !failed && h(ImageReviewGrid, { style: { display: 'grid', gap: '1rem', + gridTemplateColumns: 'repeat(auto-fit, minmax(min(24rem, 100%), 1fr))' } }, + ...value.images.map((image, index) => h(Preview, { + ...image, key: image.resultId, projectId, t, expanded: true, canvasUrl: value.canvasUrl, + title: (index + 1) + ' · ' + (image.title || t('candidate')), + onAdopted: () => { setRevision(previous => previous + 1); onAdopted?.() }, + })))) + } + + function useSourcePage(projectId, kind, enabled) { + const [cursor, setCursor] = useState({}) + const [page, setPage] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(false) + useEffect(() => { + if (!enabled) return + const controller = new AbortController() + setPage(null) + setLoading(true) + setError(false) + readLibrary(projectId, controller.signal, { kind }, cursor.after).then(value => { + if (controller.signal.aborted) return + setPage(value) + setLoading(false) + }).catch(() => { + if (controller.signal.aborted) return + setError(true) + setLoading(false) + }) + return () => controller.abort() + }, [enabled, cursor, projectId, kind]) + return { page, loading, error, cursor, setCursor } + } + + function VideoSourcePicker({ projectId, mode, selected, onSelect, emptyAction, t }) { + const kind = mode === 'continuation' ? 'video' : 'image' + const { page, loading, error, cursor, setCursor } = useSourcePage(projectId, kind, true) + const items = page?.results.filter(item => kind === 'image' || item.supportsContinuation !== false) ?? [] + return h('section', { 'aria-label': t(kind === 'image' ? 'firstFrameSource' : 'sourceClip') }, + h('p', null, t(kind === 'image' ? 'pickStill' : 'pickClip')), + !page && !error && h('small', { role: 'status' }, t('loading')), + error && h('div', { style: row }, h('small', { role: 'alert' }, t('libraryError')), + button(t('reloadData'), () => setCursor({ ...cursor }))), + page && !items.length && h('div', { style: row }, + h('small', null, t(kind === 'image' ? 'noStills' : page.results.length ? 'clipsUnsupported' : 'noClips')), emptyAction), + h('div', { style: row }, ...items.map(item => { + const label = [item.title || item.prompt || t('candidate'), item.version && 'v' + item.version].filter(Boolean).join(' · ') + return button(h('span', { style: row }, + kind === 'image' && h('img', { src: mediaHref(projectId, item.assetId, kind), alt: '', loading: 'lazy', + style: { width: '3.2rem', height: '3.2rem', objectFit: 'contain' } }), + h('span', { className: 'od-source-name' }, label)), () => onSelect({ ...item, projectId }), + { key: item.resultId, title: label, current: item.resultId === selected?.resultId, + 'aria-pressed': item.resultId === selected?.resultId }) + })), + page && h(PageControls, { cursor, nextCursor: page.nextCursor, onPage: setCursor, disabled: loading, t })) + } + + function ReferencePicker({ projectId, references, setReferences, limit, locked, t }) { + const [open, setOpen] = useState(false) + const full = references.length >= limit + const pickerOpen = open && !locked && limit > 1 + const { page, loading, error, cursor, setCursor } = useSourcePage(projectId, 'image', pickerOpen) + function toggle() { + if (!open) setCursor({}) + setOpen(value => !value) + } + function add(image) { + setReferences(previous => previous.length >= limit || previous.some(item => item.assetId === image.assetId) + ? previous : [...previous, image]) + } + function move(resultId, direction) { + setReferences(previous => { + const index = previous.findIndex(item => item.resultId === resultId) + const destination = index + direction + if (index < 1 || destination < 1 || destination >= previous.length) return previous + const reordered = [...previous] + reordered[index] = previous[destination] + reordered[destination] = previous[index] + return reordered + }) + } + const available = page?.results.filter(item => !references.some(reference => reference.assetId === item.assetId)) + const thumb = { width: '4rem', height: '4rem', objectFit: 'contain', display: 'block', borderRadius: '.3rem' } + return h('section', { 'aria-label': t('references'), style: { display: 'grid', gap: '.4rem' } }, + limit > 1 && h('small', null, t('referenceOrder')), + (limit > 1 || references.length > 1) && h('small', null, t('referenceLimit').replace('{count}', limit)), + references.length > 1 && h('div', { style: row }, + ...references.slice(1).map(({ assetId, resultId }, index) => h('figure', { key: resultId, style: { margin: 0 } }, + h('img', { src: mediaHref(projectId, assetId, 'image'), alt: '', loading: 'lazy', style: thumb }), + h('figcaption', null, `${t('referenceImage')} ${index + 2}`), + h('div', { style: row }, + references.length > 2 && button('↑', () => move(resultId, -1), { + disabled: locked || index === 0, 'aria-label': t('moveReferenceEarlier').replace('{number}', index + 2), + }), + references.length > 2 && button('↓', () => move(resultId, 1), { + disabled: locked || index === references.length - 2, 'aria-label': t('moveReferenceLater').replace('{number}', index + 2), + }), + button('×', () => setReferences(previous => previous.filter(item => item.resultId !== resultId)), { + disabled: locked, 'aria-label': `${t('removeReference')} ${index + 2}`, + }))))), + !locked && limit > 1 && h('div', null, + button(t(open ? 'hideReferences' : 'chooseReferences'), toggle, { 'aria-expanded': open, disabled: full && !open })), + pickerOpen && h('div', null, + loading && h('p', { role: 'status' }, t('loading')), + error && h('p', { role: 'alert' }, t('libraryError')), + available?.length === 0 && !loading && h('p', null, t('noMoreImages')), + h('div', { style: row }, ...(available ?? []).map((item, index) => + button(h('img', { src: mediaHref(projectId, item.assetId, 'image'), alt: '', loading: 'lazy', style: thumb }), + () => add(item), { key: item.resultId, disabled: full, title: item.prompt || t('addReference'), + 'aria-label': `${t('addReference')} ${index + 1}` }))), + page && h(PageControls, { cursor, nextCursor: page.nextCursor, disabled: loading || full, onPage: setCursor, t }))) + } + + + async function readPack(projectId, packId, signal) { + const response = await fetch('/api/opendirector/action-packs?' + new URLSearchParams({ + project: projectId, ...(packId && { pack: packId }), + }), { signal }) + if (!response.ok) throw new Error('Pack unavailable') + return response.json() + } + async function writePack(input) { + const response = await fetch('/api/opendirector/action-packs', { + method: 'POST', headers: { 'Content-Type': 'application/json', 'X-OpenDirector-Action': '1' }, + body: JSON.stringify(input), + }) + if (!response.ok) throw new Error('Pack request unavailable') + return response.json() + } + + + const packStyles = ` + .od-pack-reference{display:flex;gap:1rem;align-items:center;margin:1rem 0;color:var(--dsw-alias-label-secondary)} + .od-pack-reference img{width:5rem;height:5rem;object-fit:contain;border-radius:.7rem} + .od-pack-form fieldset{display:grid;gap:.8rem;border:0;padding:0;min-width:0} + .od-pack-form fieldset > .od-button{justify-self:start} + .od-pack-form label{display:grid;gap:.35rem;min-width:0} + .od-pack-action-input{display:grid;grid-template-columns:minmax(7rem,1fr) minmax(12rem,3fr) auto;gap:.6rem;padding:.8rem;border:1px solid #8884;border-radius:.7rem;align-items:center} + .od-pack-form textarea{min-height:4rem;width:100%;box-sizing:border-box} + .od-pack-form input,.od-pack-form select{max-width:100%;box-sizing:border-box} + .od-pack-form button[type=submit]{justify-self:start} + .od-pack-toolbar,.od-pack-summary{display:flex;flex-wrap:wrap;gap:.6rem;align-items:center} + .od-pack-summary{padding:.8rem;border-bottom:1px solid #8884} + .od-pack-summary strong{flex:1} + .od-pack-action{min-width:0;margin:.2rem 0;padding:1rem;border:1px solid #8884;border-radius:1rem} + .od-pack-candidates,.od-pack-source-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(16rem,100%),1fr));gap:1rem} + .od-pack-actions-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(22rem,100%),1fr));gap:1rem} + .od-action-pack .od-pack-candidates .od-preview:only-child{--od-preview-height:14rem} + .od-pack-source{display:grid;background:transparent;color:inherit;border:1px solid #8884;border-radius:.8rem;cursor:pointer;padding:.7rem} + .od-pack-source img{width:100%;height:9rem;object-fit:contain} + .od-action-pack h3{margin:.3rem 0;flex:1} + .od-action-pack .od-hint{overflow-wrap:anywhere} + @media(max-width:600px){.od-pack-action-input{grid-template-columns:1fr} + .od-pack-action{padding:.6rem}} + ` + + function ActionPackLibrary({ t, onClose }) { + const dialog = useRef(null) + const [projects, setProjects] = useState([]) + const [scope, setScope] = useState('') + const [projectsRun, setProjectsRun] = useState(0) + const [projectsLoading, setProjectsLoading] = useState(true) + const [projectId, setProjectId] = useState('') + const [packs, setPacks] = useState(null) + const [sourcePicker, setSourcePicker] = useState(false) + const [images, setImages] = useState(null) + const [cursor, setCursor] = useState({}) + const [task, setTask] = useState(null) + const [version, setVersion] = useState(0) + const [error, setError] = useState(false) + const [imageError, setImageError] = useState(false) + useEffect(() => { if (!task) dialog.current.showModal() }, [task]) + useEffect(() => { + const controller = new AbortController() + setProjectsLoading(true); setError(false) + readLibrary(null, controller.signal).then(value => { + if (controller.signal.aborted) return + setProjects(value.projects); setScope(value.scope) + const recent = readRecent(value.scope) + if (value.projects.some(project => project.id === recent.projectId)) setProjectId(recent.projectId) + }) + .catch(() => { if (!controller.signal.aborted) setError(true) }) + .finally(() => { if (!controller.signal.aborted) setProjectsLoading(false) }) + return () => controller.abort() + }, [projectsRun]) + useEffect(() => { + if (!projectId) return + const controller = new AbortController() + setPacks(null); setError(false) + readPack(projectId, null, controller.signal) + .then(value => { if (!controller.signal.aborted) setPacks(value.packs) }) + .catch(() => { if (!controller.signal.aborted) setError(true) }) + return () => controller.abort() + }, [projectId, version]) + useEffect(() => { + setImages(null); setImageError(false) + if (!projectId || !sourcePicker) return + const controller = new AbortController() + readLibrary(projectId, controller.signal, { kind: 'image' }, cursor.after) + .then(value => { if (!controller.signal.aborted) setImages(value) }) + .catch(() => { if (!controller.signal.aborted) setImageError(true) }) + return () => controller.abort() + }, [projectId, sourcePicker, cursor, version]) + if (task) return h(ActionPackDialog, { ...task, t, onClose: () => { setTask(null); setVersion(value => value + 1) } }) + return h('dialog', { ref: dialog, className: 'od-media-ui', style: dialogStyle, onCancel: onClose }, + dialogHeader(t('actionPacks'), onClose, t, t('packHint')), + h(PendingSubmissions, { context: 'packs', t, onRecovered: value => setTask(value) }), + h('label', null, t('chooseProject'), h('select', { 'aria-label': t('chooseProject'), + value: projectId, onChange: event => { if (event.target.value) rememberRecent(scope, { projectId: event.target.value }); setProjectId(event.target.value); setCursor({}); setSourcePicker(false) }, + }, h('option', { value: '' }, t('chooseProject')), ...projects.map(project => + h('option', { key: project.id, value: project.id }, project.name)))), + (error || imageError) && h('p', { role: 'alert' }, t('libraryError')), + !projectId && projectsLoading && h('p', { role: 'status' }, t('loading')), + !projectsLoading && !error && !projects.length && h('p', null, t('projectsEmpty')), + h('div', { style: row }, + projectId && button(t('newActionPack'), () => setSourcePicker(value => !value), { primary: true }), + button(t(projectId ? 'refresh' : 'reloadData'), () => projectId ? setVersion(value => value + 1) : setProjectsRun(value => value + 1), { disabled: projectsLoading })), + projectId && !packs && !error && h('p', null, t('loading')), + packs && !packs.length && h('p', null, t('packEmpty')), + ...(packs ?? []).map(pack => h('article', { key: pack.packId, className: 'od-pack-summary' }, + h('strong', null, pack.title), + h('span', null, t('packCount').replace('{selected}', pack.selectedCount).replace('{total}', pack.actionCount)), + button(t('viewTask'), () => setTask({ projectId, packId: pack.packId })))), + sourcePicker && h('section', { 'aria-label': t('packSelectSource') }, + h('h3', null, t('packSelectSource')), + !images && !imageError && h('p', { role: 'status' }, t('loading')), + images && !images.results.length && h('p', null, t('resultsEmpty')), + h('div', { className: 'od-pack-source-grid' }, ...(images?.results ?? []).map(image => + h('button', { type: 'button', key: image.resultId, className: 'od-pack-source', + 'aria-label': t('packSource'), onClick: () => setTask({ source: { ...image, projectId } }) }, + h('img', { src: mediaHref(projectId, image.assetId, 'image'), alt: image.title || t('candidate'), loading: 'lazy' }), + h('span', null, image.title || t('packSource'))))), + h(PageControls, { cursor, nextCursor: images?.nextCursor, onPage: setCursor, t }))) + } + + function imageOutputSelection(model, requested) { + const options = model?.imageOutputs ?? [] + const output = requested == null ? options[0] : options.find(item => + item.size === requested.size && item.aspectRatio === requested.aspectRatio) + return { options, requested, output, unavailable: Boolean(model && requested && !output) } + } + + function ImageOutputField({ selection, original, onChange, disabled, t }) { + const { options, requested, output, unavailable } = selection + const keepOriginal = original !== undefined + if (!options.length && !unavailable && !keepOriginal) return null + const value = keepOriginal && requested == null ? 'original' : unavailable ? '' : options.indexOf(output) + return h('div', { style: { display: 'grid', gap: '.3rem' } }, + (options.length > 0 || keepOriginal) && h('label', { style: { display: 'grid', gap: '.3rem' } }, t('output'), + h('select', { 'aria-label': t('output'), value, disabled, + onChange: e => onChange(e.target.value === 'original' ? null : options[Number(e.target.value)]), + }, keepOriginal && h('option', { value: 'original' }, [t('keepOriginalOutput'), original].filter(Boolean).join(' · ')), + unavailable && h('option', { value: '', disabled: true }, t('chooseOutput')), + ...options.map(({ size, aspectRatio }, i) => h('option', { key: i, value: i }, [size, aspectRatio].filter(Boolean).join(' · '))))), + unavailable && h('p', { role: 'alert' }, t('outputUnavailable').replace('{size}', requested.size)), + unavailable && !options.length && button(t(keepOriginal ? 'keepOriginalOutput' : 'useModelDefault'), () => onChange(null), { disabled })) + } + + function ActionPackDialog({ source, projectId: suppliedProject, packId: suppliedPack, recovery, status: recoveredStatus, t, onClose }) { + const dialog = useRef(null) + const busy = useRef(false) + const projectId = source?.projectId ?? suppliedProject + const draftKey = 'pack-create:' + projectId + ':' + source?.resultId + const [packId, setPackId] = useState(suppliedPack ?? null) + const [pack, setPack] = useState(null) + const [catalog, setCatalog] = useState(null) + const [initialDraft] = useState(() => readMediaDraft(draftKey)) + const catalogInitialized = useRef(Boolean(initialDraft)) + const [dirty, setDirty] = useState(Boolean(initialDraft)) + const [form, setForm] = useState(() => initialDraft?.form ?? { + title: t('packDefaultTitle'), prompt: '', kind: 'image', modelId: '', output: null, + durationSeconds: null, actions: [ + { name: t('packIdle'), prompt: t('packIdlePrompt') }, + { name: t('packWave'), prompt: t('packWavePrompt') }, + { name: t('packThink'), prompt: t('packThinkPrompt') }, + ], + }) + const [submitting, setSubmitting] = useState(false) + const [feedback, setFeedback] = useState('') + const [version, setVersion] = useState(0) + const [pages, setPages] = useState({}) + const [comparison, setComparison] = useState([]) + const [comparing, setComparing] = useState(false) + const [editing, setEditing] = useState(null) + const editDraftKey = itemId => 'pack-revise:' + projectId + ':' + packId + ':' + itemId + const pending = useSyncExternalStore(subscribePending, readPendingSubmissions) + const pendingItems = pending.filter(item => item.context === (packId ? 'pack:' + packId : draftKey)) + const pendingItem = pendingItems[0] + const locked = submitting || Boolean(pendingItem) + const refresh = () => setVersion(value => value + 1) + useEffect(() => { dialog.current.showModal() }, []) + useEffect(() => { + if (recovery && packId) { + if (recovery.packAction === 'prepare' || ['applied', 'accepted', 'noop', 'rejected'].includes(recoveredStatus)) forgetSubmission(recovery) + } + }, [recovery, packId, recoveredStatus]) + useEffect(() => { + if (packId || !source || pendingItem) return + const controller = new AbortController() + setCatalog(null) + fetch('/api/opendirector/creation', { signal: controller.signal }).then(response => { + if (!response.ok) throw new Error('Catalog unavailable') + return response.json() + }).then(value => { + if (controller.signal.aborted) return + setCatalog(value) + if (!catalogInitialized.current) { + const kind = ['image', 'video'].includes(readRecent(value.scope).packKind) ? readRecent(value.scope).packKind : 'image' + setForm(previous => ({ ...previous, kind, + ...recentSetup(value, 'pack:' + kind, kind, kind === 'video' ? 'first_frame' : undefined), + })) + } + catalogInitialized.current = true + }).catch(() => { if (!controller.signal.aborted) setCatalog({ error: true, models: [] }) }) + return () => controller.abort() + }, [packId, Boolean(pendingItem), version]) + useEffect(() => { + if (!packId && !locked) saveMediaDraft(draftKey, dirty ? { form } : null) + }, [packId, locked, form, draftKey, dirty]) + useEffect(() => { + if (!packId) return + const controller = new AbortController() + let timer, inFlight = false + async function update() { + if (inFlight || document.visibilityState === 'hidden' || !navigator.onLine) return + inFlight = true + try { + const value = await readPack(projectId, packId, controller.signal) + if (controller.signal.aborted) return + setPack(value) + if (value.active) timer = setTimeout(update, 2500) + } catch { if (!controller.signal.aborted) setFeedback('progressUnavailable') } + finally { inFlight = false } + } + update() + const visible = () => { clearTimeout(timer); update() } + document.addEventListener('visibilitychange', visible) + window.addEventListener('online', visible) + return () => { + clearTimeout(timer); controller.abort() + document.removeEventListener('visibilitychange', visible) + window.removeEventListener('online', visible) + } + }, [packId, projectId, version]) + const choices = catalog?.models.filter(model => model.kind === form.kind + && (form.kind === 'image' ? model.maxImages > 0 : model.videoChoices?.first_frame)) ?? [] + const model = choices.find(model => model.id === form.modelId) + const imageSize = imageOutputSelection(model, form.output) + const video = model?.videoChoices?.first_frame + const names = form.actions.map(action => action.name.trim().normalize('NFKC').toLowerCase()) + const missing = !catalog ? 'loading' : catalog.error ? 'libraryError' : !choices.length ? 'noModels' + : !model ? 'needsModel' : imageSize.unavailable ? 'chooseOutput' + : !form.title.trim() || names.some(name => !name) || new Set(names).size !== names.length + || form.actions.some(action => !action.prompt.trim()) ? 'packInvalid' : null + function change(key, value) { + setDirty(true) + if (['kind', 'modelId', 'output', 'durationSeconds'].includes(key)) catalogInitialized.current = true + setForm(previous => ({ ...previous, [key]: value, + ...(key === 'modelId' && { durationSeconds: null }), + ...(key === 'kind' && { modelId: '', output: null, durationSeconds: null, + ...recentSetup(catalog, 'pack:' + value, value, value === 'video' ? 'first_frame' : undefined) }), + })) + } + useEffect(() => { + if (packId || locked || !model || imageSize.unavailable) return + rememberRecent(catalog.scope, { projectId, packKind: form.kind, setups: { ['pack:' + form.kind]: { + modelId: model.id, output: form.kind === 'image' ? imageSize.output ?? null : null, + durationSeconds: form.durationSeconds ?? video?.defaultDuration ?? null, + } } }) + }, [packId, locked, model?.id, form.kind, form.output, form.durationSeconds, catalog?.scope, projectId]) + async function submitActions(id, itemIds, redo = false, original) { + const input = { action: 'generate', projectId, packId: id, + operationId: original?.operationId ?? crypto.randomUUID(), itemIds, redo } + const saved = { ...input, packAction: 'generate', packItemIds: itemIds, packRedo: redo } + rememberSubmission(saved, 'pack:' + id, pack?.title ?? form.title) + let value + try { value = await writePack(input) } catch { value = { status: 'unknown' } } + if (value.status !== 'unknown') forgetSubmission(saved) + setFeedback(value.status === 'unknown' ? 'generationUnknown' : value.status === 'rejected' + ? packError(value.code) : '') + refresh() + } + async function generate(itemIds, redo, original) { + if (busy.current) return + busy.current = true; setSubmitting(true) + try { await submitActions(packId, itemIds, redo, original) } + finally { busy.current = false; setSubmitting(false) } + } + async function prepare(event) { + event.preventDefault() + if (busy.current || pendingItem || missing) return + busy.current = true; setSubmitting(true); setFeedback('') + const input = { action: 'prepare', projectId, operationId: crypto.randomUUID(), + sourceResultId: source.resultId, title: form.title, sharedPrompt: form.prompt, + actions: form.actions, modelConfigId: form.modelId, + ...(imageSize.output && { output: imageSize.output }), + ...(video && { durationSeconds: form.durationSeconds ?? video.defaultDuration }), + } + const saved = { ...input, packAction: 'prepare' } + rememberSubmission(saved, draftKey, form.title) + try { + let value + try { value = await writePack(input) } catch { value = { status: 'unknown' } } + if (value.status === 'unknown') { setFeedback('generationUnknown'); return } + forgetSubmission(saved) + if (value.status === 'rejected') { setFeedback(packError(value.code)); return } + setPackId(value.packId) + saveMediaDraft(draftKey, null); flushMediaDrafts() + const current = await readPack(projectId, value.packId) + setPack(current) + await submitActions(value.packId, current.actions.map(action => action.itemId)) + } catch { setFeedback('progressUnavailable') } + finally { busy.current = false; setSubmitting(false) } + } + function recovered(value) { + setPackId(value.packId); setPack(value) + setFeedback(value.status === 'unknown' ? 'generationUnknown' : '') + if (value.status !== 'unknown') forgetSubmission(value.recovery) + if (value.recovery.packAction === 'revise' && value.status !== 'unknown') { + if (['applied', 'accepted', 'noop'].includes(value.status)) { + saveMediaDraft(editDraftKey(value.recovery.packItemIds[0]), null) + setEditing(null); setFeedback('packRevised') + } else setFeedback(packError(value.code)) + } + if (value.recovery.packAction === 'prepare') { + saveMediaDraft(draftKey, null); flushMediaDrafts() + } + refresh() + } + function changeAction(action) { + const draft = readMediaDraft(editDraftKey(action.itemId))?.form + setEditing(draft?.itemId === action.itemId ? draft + : { itemId: action.itemId, prompt: action.prompt, revision: action.revision }) + } + function cancelEdit() { + if (editing) saveMediaDraft(editDraftKey(editing.itemId), null) + setEditing(null) + } + useEffect(() => { + if (editing) saveMediaDraft(editDraftKey(editing.itemId), { form: editing }) + }, [editing, packId]) + async function revise(event) { + event.preventDefault() + if (busy.current || !editing || pendingItem) return + busy.current = true; setSubmitting(true); setFeedback('') + const input = { action: 'revise', projectId, packId, operationId: crypto.randomUUID(), + itemId: editing.itemId, prompt: editing.prompt, expectedSpecRevision: editing.revision } + const saved = { ...input, packAction: 'revise', packItemIds: [editing.itemId] } + rememberSubmission(saved, 'pack:' + packId, pack.title) + try { + let value + try { value = await writePack(input) } catch { value = { status: 'unknown' } } + if (value.status === 'unknown') { setFeedback('generationUnknown'); return } + forgetSubmission(saved) + if (value.status === 'rejected') { setFeedback(packError(value.code)); return } + const itemId = editing.itemId + cancelEdit() + await submitActions(packId, [itemId], true) + } finally { busy.current = false; setSubmitting(false); refresh() } + } + const remaining = pack?.actions.filter(action => !action.jobs.length) ?? [] + const sourceImage = source ?? pack?.actions[0]?.reference + return h('dialog', { ref: dialog, className: 'od-media-ui od-action-pack', 'aria-label': t('newActionPack'), + style: packId ? { ...dialogStyle, width: 'min(80rem, calc(100vw - 2rem))' } : dialogStyle, + onCancel: e => { if (e.target === e.currentTarget) onClose() } }, + dialogHeader(pack?.title ?? t('newActionPack'), onClose, t, t('packHint')), + sourceImage && h('div', { className: 'od-pack-reference' }, + h('img', { src: mediaHref(projectId, sourceImage.assetId, 'image'), alt: t('packReference') }), + h('span', null, t('packReference'))), + h(PendingSubmissions, { context: packId ? 'pack:' + packId : draftKey, onRecovered: recovered, disabled: submitting, t }), + feedback && h('p', { role: 'status' }, t(feedback)), + pendingItem?.packAction === 'generate' && button(t('packContinue'), + () => generate(pendingItem.packItemIds, pendingItem.packRedo, pendingItem), { disabled: submitting }), + !packId && !pendingItem && !catalog && h('p', { role: 'status' }, t('loading')), + !packId && !pendingItem && catalog?.error && h('p', { role: 'alert' }, t('libraryError')), + !packId && !pendingItem && h('form', { onSubmit: prepare, className: 'od-pack-form' }, + h('fieldset', { disabled: locked }, + h('label', null, t('packTitle'), h('input', { required: true, maxLength: 100, value: form.title, onChange: e => change('title', e.target.value) })), + h('label', null, t('packShared'), h('textarea', { maxLength: 4000, value: form.prompt, onChange: e => change('prompt', e.target.value) })), + h('div', { style: row }, + h('label', null, t('mediaType'), h('select', { 'aria-label': t('mediaType'), value: form.kind, onChange: e => change('kind', e.target.value) }, + h('option', { value: 'image' }, t('picture')), h('option', { value: 'video' }, t('video')))), + h('label', null, t('model'), h('select', { name: 'model', 'aria-label': t('model'), required: true, value: form.modelId, onChange: e => change('modelId', e.target.value) }, + h('option', { value: '' }, t('chooseModel')), ...choices.map(model => + h('option', { key: model.id, value: model.id }, model.modelId)))), + form.kind === 'image' && h(ImageOutputField, { selection: imageSize, + onChange: value => change('output', value), disabled: locked, t }), + video?.durations.length > 0 && h('label', null, t('videoDuration'), h('select', { + 'aria-label': t('videoDuration'), value: form.durationSeconds ?? video.defaultDuration ?? video.durations[0], + onChange: e => change('durationSeconds', Number(e.target.value)), + }, ...video.durations.map(seconds => h('option', { key: seconds, value: seconds }, t('duration').replace('{seconds}', seconds)))))), + catalog && !choices.length && h('div', { style: row }, + !catalog.error && h('p', null, t('noModels')), + button(t('reloadData'), refresh, { disabled: locked })), + !locked && h(ActionExamples, { t, onApply: actions => change('actions', actions) }), + ...form.actions.map((action, index) => h('div', { key: index, className: 'od-pack-action-input' }, + h('label', null, t('packActionName'), h('input', { required: true, maxLength: 80, value: action.name, + onChange: e => change('actions', form.actions.map((value, i) => i === index ? { ...value, name: e.target.value } : value)) })), + h('label', null, t('packDescription'), h('textarea', { required: true, maxLength: 4000, value: action.prompt, + onChange: e => change('actions', form.actions.map((value, i) => i === index ? { ...value, prompt: e.target.value } : value)) })), + button(t('packRemove'), () => change('actions', form.actions.filter((_, i) => i !== index)), { disabled: form.actions.length === 1 }))), + button(t('packAdd'), () => change('actions', [...form.actions, { name: '', prompt: '' }]), { disabled: form.actions.length >= 6 }), + h(SubmitRow, { label: t(submitting ? 'submitting' : 'packCreate').replace('{count}', form.actions.length), + reason: missing && t(missing), focusModel: missing === 'needsModel', busy: locked }))), + packId && !pack && h('p', null, t('loading')), + pack && h('section', null, + h('div', { className: 'od-pack-toolbar' }, + h('strong', null, t('packCount').replace('{selected}', pack.selectedCount).replace('{total}', pack.actions.length)), + button(t('refresh'), refresh, { disabled: submitting }), + remaining.length > 0 && button(t('packMissing').replace('{count}', remaining.length), + () => generate(remaining.map(action => action.itemId), false), { primary: true, disabled: locked }), + pack.actions.length > 0 && pack.selectedCount === pack.actions.length + && h('a', { href: '/api/opendirector/action-packs?' + new URLSearchParams({ project: projectId, pack: packId, download: '1' }), + className: 'od-button od-primary', download: '', style: { ...buttonStyle, textDecoration: 'none' } }, t('packExport'))), + h('p', { className: 'od-hint' }, t('packExportHint')), + h('div', { className: 'od-pack-actions-grid' }, ...pack.actions.map(action => { + const page = pages[action.itemId] ?? 0 + const results = [...action.results].reverse().slice(page * 4, page * 4 + 4) + const active = action.jobs.filter(job => ['queued', 'running'].includes(job.status)) + return h('article', { key: action.itemId, className: 'od-pack-action', 'data-pack-action': action.itemId }, + h('div', { className: 'od-pack-toolbar' }, h('h3', null, action.name), + h('span', { role: 'status' }, t(action.status === 'not_started' ? 'packNotStarted' : action.status)), + button(t(action.jobs.length ? 'repeatGeneration' : 'generate'), + () => generate([action.itemId], Boolean(action.jobs.length)), { disabled: locked || !action.canGenerate }), + button(t('packRevise'), () => changeAction(action), { disabled: locked || !action.canRevise })), + h('details', { className: 'od-hint' }, h('summary', null, t('generationSettings')), h('p', null, action.prompt)), + editing?.itemId === action.itemId && h('form', { onSubmit: revise }, + h('label', { style: { display: 'grid', gap: '.4rem' } }, t('packEditPrompt'), + h('textarea', { required: true, maxLength: 20000, 'aria-label': t('packEditPrompt'), + style: { width: '100%', minHeight: '8rem', boxSizing: 'border-box' }, disabled: locked, + value: editing.prompt, onChange: event => setEditing(previous => ({ ...previous, prompt: event.target.value })) })), + h('div', { style: row }, + h('button', { type: 'submit', className: 'od-button od-primary', style: buttonStyle, + disabled: locked || !editing.prompt.trim() }, t('packSaveGenerate')), + button(t('packCancelEdit'), cancelEdit, { disabled: locked }))), + ...active.map(job => h(JobCancellation, { key: job.jobId, projectId, jobId: job.jobId, progress: job, t, onChange: refresh })), + ['failed', 'interrupted'].includes(action.status) && h('p', null, t(generationMessages.get(action.jobs.at(-1)?.category) ?? 'recoverOnCanvas')), + h(ImageReviewGrid, { className: 'od-pack-candidates' }, ...results.map((result, index) => h(Preview, { + ...result, key: result.resultId, projectId, title: t(result.selected ? 'selected' : 'candidate') + ' ' + (action.results.length - page * 4 - index), + t, onAdopted: refresh, canvasUrl: pack.canvasUrl, compactActions: true, + onCompare: action.kind === 'image' ? () => setComparison(previous => + previous.some(item => item.resultId === result.resultId) ? previous.filter(item => item.resultId !== result.resultId) + : previous[0]?.itemId !== action.itemId ? [{ itemId: action.itemId, resultId: result.resultId }] + : [...previous, { itemId: action.itemId, resultId: result.resultId }].slice(0, 2)) : undefined, + compareSelected: comparison.some(item => item.resultId === result.resultId), + compareDisabled: comparison.length === 2 && comparison[0]?.itemId === action.itemId && !comparison.some(item => item.resultId === result.resultId), + }))), + action.results.length > 4 && h('div', { style: row }, + button(t('previousPage'), () => setPages(previous => ({ ...previous, [action.itemId]: page - 1 })), { disabled: page === 0 }), + button(t('nextPage'), () => setPages(previous => ({ ...previous, [action.itemId]: page + 1 })), { disabled: (page + 1) * 4 >= action.results.length }))) + })), + comparison.length === 2 && button(t('openComparison'), () => setComparing(true)), + pack.canvasUrl && canvasLink(pack.canvasUrl, t)), + comparing && h(ImageComparisonDialog, { projectId, resultIds: comparison.map(item => item.resultId), + onAdopted: refresh, t, onClose: () => setComparing(false) })) + } + function packError(code) { + if (code === 'storage_busy') return 'adoptBusy' + if (['pack.plan', 'input.string', 'input.required'].includes(code)) return 'packInvalid' + if (code === 'pack.model') return 'noModels' + if (code === 'pack.active') return 'packActive' + if (submissionMessages.has(code)) return submissionMessages.get(code) + if (code === 'creation.output') return 'chooseOutput' + return 'failedToSubmit' + } + + function ExamplePicker({ mode, t, prompt, onApply }) { + const [replacement, setReplacement] = useState(null) + const ids = mode === 'audio' ? ['Speech', 'Narration'] : mode === 'edit' ? ['Lamp', 'Evening'] + : mode === 'first_frame' ? ['Wave', 'Push'] : mode === 'continuation' ? ['Continue'] : ['Studio', 'Character', 'Cover'] + return h('div', { 'data-opendirector-examples': mode }, + h('div', { style: row }, h('small', null, t('examples')), + ...ids.map(id => button(t('example' + id), () => { + if (prompt.trim()) setReplacement(id) + else { setReplacement(null); onApply(t('example' + id + 'Prompt')) } + }, { key: id }))), + replacement && h('div', { className: 'od-settings' }, + h('p', null, t('example' + replacement + 'Prompt')), + button(t('exampleReplace'), () => { onApply(t('example' + replacement + 'Prompt')); setReplacement(null) }), + button(t('packCancelEdit'), () => setReplacement(null)))) + } + + function ActionExamples({ t, onApply }) { + const [choice, setChoice] = useState('starter') + const keys = choice === 'starter' ? ['Idle', 'Wave', 'Think'] : ['Happy', 'Think', 'Sleep'] + return h('details', { className: 'od-settings', 'data-opendirector-action-examples': '' }, + h('summary', null, t('actionExamples')), + h('div', { style: { display: 'grid', gap: '.5rem', marginTop: '.6rem' } }, + h('select', { 'aria-label': t('actionExamples'), value: choice, onChange: e => setChoice(e.target.value) }, + h('option', { value: 'starter' }, t('actionExampleStarter')), h('option', { value: 'mood' }, t('actionExampleMood'))), + h('span', null, keys.map(key => t('pack' + key)).join(' · ')), + h('small', { className: 'od-hint' }, t('actionExamplesHint')), + h('div', { style: row }, button(t('actionExampleApply'), + () => onApply(keys.map(key => ({ name: t('pack' + key), prompt: t('pack' + key + 'Prompt') }))))))) + } + + function ImportChatDraft({ useInput, prompt, limit, onApply, t }) { + const draft = useInput(state => state.phase === 'plain' ? state.draft.trim() : '') + if (!draft || prompt.trim() === draft || prompt.trimEnd().endsWith('\n' + draft)) return null + const next = prompt ? prompt + (prompt.endsWith('\n') ? '' : '\n') + draft : draft + const tooLong = next.length > limit + return h('div', { style: row }, button(t(prompt.trim() ? 'appendChatDraft' : 'useChatDraft'), + () => onApply(next), { disabled: tooLong }), tooLong && h('small', null, t('draftTooLong'))) + } + + function generationTitle({ existingJob, templateOf, videoMode, source }) { + return existingJob ? 'taskProgress' : templateOf ? 'reuseSettings' : videoMode === 'continuation' ? 'continue' + : videoMode ? 'firstFrame' : source ? 'edit' : 'create' + } + + function GenerationDialog(props) { + const dialog = useRef(null) + const [steps, setSteps] = useState([]) + const [pack, setPack] = useState(null) + const returning = useRef(null) + const pages = [props, ...steps.map(step => step.page)] + function leavePage() { + const element = dialog.current + element.querySelectorAll('video, audio').forEach(player => player.pause()) + return { focus: document.activeElement, scroll: element.scrollTop } + } + function openStep(page) { + const from = leavePage() + setSteps(previous => [...previous, { page, from }]) + } + function back() { + returning.current = steps.at(-1).from + setSteps(previous => previous.slice(0, -1)) + } + function openPack(source) { + const from = leavePage() + dialog.current.close() + setPack({ source, from }) + } + function close() { + flushMediaDrafts() + props.onClose() + } + useLayoutEffect(() => { + const element = dialog.current + if (pack) return + if (!element.open) element.showModal() + if (returning.current) { + const { focus, scroll } = returning.current + returning.current = null + focus?.focus({ preventScroll: true }) + element.scrollTop = scroll + } else if (steps.length) { + element.querySelector('[data-generation-page]:not([hidden]) [data-step-back]')?.focus() + element.scrollTop = 0 + } + }, [steps.length, pack]) + const { t } = props + return h('div', null, h('dialog', { className: 'od-media-ui', ref: dialog, style: dialogStyle, + onClose: event => { if (event.target === dialog.current && !pack && !dialog.current.open) close() }, + 'aria-label': t(generationTitle(pages.at(-1))), onCancel: event => { + if (event.target !== dialog.current) return + event.preventDefault() + if (steps.length) back() + else close() + } }, ...pages.map((page, index) => h('div', { key: index, hidden: index !== steps.length, 'data-generation-page': '' }, + h(GenerationStep, { ...page, t, visible: index === steps.length && !pack, openStep, openPack, + back: index > 0 ? back : null, onClose: close })))), + pack && h(ActionPackDialog, { source: pack.source, t, onClose: () => { + returning.current = pack.from + setPack(null) + } })) + } + + function GenerationStep({ source, videoMode: fixedVideoMode, existingJob, templateOf, proposal, sessionId, chatProject, t, visible, openStep, openPack, back, onClose, onSettledRead }) { + const page = useRef(null) + const busy = useRef(false) + const attempt = useRef(null) + const [catalog, setCatalog] = useState(null) + const chat = useContext(ChatContext) + const taskSession = sessionId ?? chat?.sessionId + const createKey = sessionId ? 'create:' + sessionId : 'create' + const draftKey = proposal ? ['proposal', source.projectId, source.resultId, proposal.callId].join(':') : existingJob ? ['repeat', existingJob.projectId, existingJob.jobId].join(':') : templateOf ? ['reuse', templateOf.projectId, templateOf.resultId].join(':') : source ? [fixedVideoMode ?? 'edit', source.projectId, source.resultId].join(':') : createKey + const pending = useSyncExternalStore(subscribePending, readPendingSubmissions) + const [startFresh, setStartFresh] = useState(false) + const [result, setResult] = useState(existingJob ?? null) + const restoringPending = !result && !startFresh && !attempt.current && pending.some(item => item.context === draftKey) + const defaults = { + kind: templateOf?.kind ?? (fixedVideoMode ? 'video' : 'image'), projectId: '', projectName: '', modelId: '', + videoSource: null, videoMode: 'first_frame', + prompt: proposal?.prompt ?? '', output: null, voice: '', durationSeconds: null, candidateCount: 1, + } + const [saved] = useState(() => existingJob ? null : readMediaDraft(draftKey)) + const [earlierDraft, setEarlierDraft] = useState(() => !saved && sessionId && draftKey === createKey ? readMediaDraft('create') : null) + const catalogInitialized = useRef(Boolean(saved)) + const [catalogRun, setCatalogRun] = useState(0) + const [restored, setRestored] = useState(Boolean(saved)) + const [recentRestored, setRecentRestored] = useState(false) + const [recentBase, setRecentBase] = useState(null) + const [form, setForm] = useState(() => ({ ...defaults, ...saved?.form })) + const videoMode = fixedVideoMode ?? (form.kind === 'video' ? form.videoMode : undefined) + const videoSource = source ?? (form.videoSource?.projectId === form.projectId ? form.videoSource : null) + const [progress, setProgress] = useState(null) + const [previousRound, setPreviousRound] = useState(null) + const [repeatStatus, setRepeatStatus] = useState(null) + const [repeatCount, setRepeatCount] = useState(1) + const [comparison, setComparison] = useState([]) + const [comparing, setComparing] = useState(false) + const [submitting, setSubmitting] = useState(false) + const [pollError, setPollError] = useState(false) + const [updatesPaused, setUpdatesPaused] = useState(false) + const [pollRun, setPollRun] = useState(0) + const [references, setReferences] = useState(() => source && !videoMode + ? [source, ...(Array.isArray(saved?.references) ? saved.references.filter(item => item?.kind === 'image' + && typeof item.resultId === 'string' && typeof item.assetId === 'string' && item.resultId !== source.resultId) : [])] : []) + const fromResult = Boolean(source) + const continuation = videoMode === 'continuation' + const title = t(generationTitle({ existingJob, templateOf, videoMode: fixedVideoMode, source })) + const choices = creationModels(catalog, form.kind, videoMode, Boolean(source)) + const model = choices?.find(item => item.id === form.modelId) + const video = model?.videoChoices?.[videoMode] + const durationSeconds = form.durationSeconds ?? video?.defaultDuration + const durationUnavailable = Boolean(video && form.durationSeconds !== null && !video.durations.includes(durationSeconds)) + const imageSize = imageOutputSelection(model, form.output) + const { output, unavailable: outputUnavailable } = imageSize + const referenceLimit = model?.maxImages ?? 1 + const tooManyReferences = Boolean(model) && references.length > referenceLimit + const jobId = result?.jobId + const projectId = result?.projectId + const groupId = result?.groupId + const unknown = result?.status === 'unknown' + const locked = submitting || unknown || Boolean(jobId) || result?.draftSaved === true + const draftBase = catalog?.template ? { ...defaults, projectId: templateOf.projectId, + kind: catalog.template.kind, modelId: catalog.template.modelConfigId, + prompt: catalog.template.prompt, voice: catalog.template.voice } : recentBase ?? defaults + const dirty = Object.keys(defaults).some(key => form[key] !== draftBase[key]) + || references.length > (source && !videoMode ? 1 : 0) + const projectUnavailable = !source && !templateOf && catalog && !catalog.error && form.projectId && form.projectId !== 'new' + && !catalog.projects.some(project => project.id === form.projectId) + const modelUnavailable = catalog && !catalog.error && form.modelId && !model + const missing = projectUnavailable ? 'projectUnavailable' : !source && !templateOf && !form.projectId ? 'needsProject' + : videoMode && !videoSource ? (continuation ? 'pickClip' : 'pickStill') + : form.projectId === 'new' && !form.projectName.trim() ? 'needsName' + : !choices?.length ? (videoMode ? 'noVideoMode' : 'noModels') : modelUnavailable ? 'modelUnavailable' : !model ? 'needsModel' + : tooManyReferences ? 'referencesChanged' : outputUnavailable ? 'chooseOutput' + : durationUnavailable ? 'chooseDuration' : model.voiceRequired && !form.voice.trim() ? 'needsVoice' + : !form.prompt.trim() ? 'needsPrompt' : null + useEffect(() => { + if (!visible || existingJob || restoringPending) return + saveMediaDraft(draftKey, !locked && (dirty || restored) ? { form, references } : null) + }, [draftKey, form, references, locked, existingJob, dirty, restored, restoringPending, visible]) + function clearDraft() { + setForm(draftBase) + setReferences(source && !videoMode ? [source] : []) + setRestored(false) + saveMediaDraft(draftKey, null) + flushMediaDrafts() + } + const update = (key, value) => setForm(previous => ({ ...previous, [key]: value, + ...(['kind', 'videoMode', 'projectId'].includes(key) && { videoSource: null }), + ...(key === 'kind' && { modelId: '', output: null, durationSeconds: null, videoMode: 'first_frame', + ...(value === 'video' ? creationSetup(catalog, 'first_frame', 'video', 'first_frame') : creationSetup(catalog, value, value)) }), + ...(key === 'videoMode' && { modelId: '', durationSeconds: null, + ...creationSetup(catalog, value, 'video', value) }), + ...((key === 'kind' || key === 'modelId') && { voice: '' }), + })) + useEffect(() => { + if (existingJob || templateOf || videoMode === 'continuation' || locked || !model || outputUnavailable || !catalog?.scope) return + const context = videoMode ?? (source ? 'edit' : form.kind) + const chosenProject = source?.projectId + ?? (catalog.projects?.some(project => project.id === form.projectId) ? form.projectId : undefined) + rememberRecent(catalog.scope, { + ...(!source && { kind: form.kind }), ...(chosenProject && { projectId: chosenProject }), + setups: { [context]: { modelId: model.id, output: form.kind === 'image' ? output ?? null : null, + durationSeconds: Number.isFinite(durationSeconds) ? durationSeconds : null } }, + }) + }, [existingJob, templateOf, locked, model?.id, form.kind, form.projectId, form.output, form.durationSeconds, catalog?.scope]) + + useEffect(() => { + if (existingJob || restoringPending) return + const controller = new AbortController() + setCatalog(null) + Promise.all([ + (fromResult || templateOf) ? Promise.resolve({ projects: [] }) : readLibrary(null, controller.signal), + fetch('/api/opendirector/creation', { signal: controller.signal }).then(response => { + if (!response.ok) throw new Error('Model catalog unavailable') + return response.json() + }), + templateOf ? fetch('/api/opendirector/creation?' + new URLSearchParams({ + project: templateOf.projectId, reuse: templateOf.resultId, + }), { signal: controller.signal }).then(response => { + if (!response.ok) throw new Error('Saved settings unavailable') + return response.json() + }) : Promise.resolve(null), + ]).then(([projects, models, template]) => { + if (controller.signal.aborted) return + setCatalog({ ...projects, ...models, ...(template && { template }) }) + const initialize = !catalogInitialized.current + if (template) setForm(previous => ({ ...previous, + kind: template.kind, projectId: templateOf.projectId, modelId: template.modelConfigId, + ...(initialize && { prompt: template.prompt, voice: template.voice }), + })) + else if (initialize || saved) { + const recent = readRecent(models.scope) + const kind = !source && ['image', 'video', 'audio'].includes(recent.kind) ? recent.kind : defaults.kind + const initialMode = fixedVideoMode ?? (kind === 'video' ? defaults.videoMode : undefined) + const context = initialMode ?? (source ? 'edit' : kind) + const preferred = creationSetup(models, context, kind, initialMode) + const preferredProject = !source && initialProject(projects.projects, models.scope, sessionId, chatProject) + const restoredForm = { ...defaults, kind, ...preferred, ...(preferredProject && { projectId: preferredProject }) } + setRecentBase(restoredForm) + if (initialize) { + setForm(previous => ({ ...restoredForm, ...(previous.prompt && { prompt: previous.prompt }) })) + setRecentRestored(Boolean(preferred.modelId && preferred.modelId === recent.setups?.[context]?.modelId)) + } + } + catalogInitialized.current = true + }).catch(() => { + if (!controller.signal.aborted) setCatalog({ error: true, projects: [], models: [] }) + }) + return () => controller.abort() + }, [fromResult, existingJob, templateOf?.projectId, templateOf?.resultId, restoringPending, catalogRun]) + useEffect(() => { + if (existingJob?.recovery) rememberTask(taskSession, existingJob.projectId, existingJob, existingJob.kind, existingJob.prompt) + if (existingJob?.recovery && (!existingJob.groupId || existingJob.groupComplete)) forgetSubmission(existingJob.recovery) + }, [existingJob?.recovery]) + useEffect(() => { + if (!jobId || !visible) return + const controller = new AbortController() + let timer + let inFlight = false + let active = true + const key = taskKey({ projectId, jobId, groupId }) + taskDialogs.set(key, (taskDialogs.get(key) ?? 0) + 1) + backgroundReads.get(key)?.abort() + const available = () => !document.hidden && navigator.onLine !== false + async function poll() { + if (controller.signal.aborted || inFlight || !available()) return + inFlight = true + try { + const value = await readTask({ projectId, jobId, groupId }, controller.signal) + if (controller.signal.aborted) return + active = activeTask(value.status) + recordProgress(taskSession, result, value) + if (!active) onSettledRead?.() + setPollError(false) + setProgress(previous => ({ ...value, jobId, results: value.results ?? previous?.results ?? [] })) + if (active && available()) timer = setTimeout(poll, 2500) + } catch { + if (!controller.signal.aborted) setPollError(true) + } finally { + inFlight = false + } + } + function wake() { + clearTimeout(timer) + setUpdatesPaused(!available()) + if (active) poll() + } + document.addEventListener('visibilitychange', wake) + window.addEventListener('online', wake) + window.addEventListener('offline', wake) + wake() + return () => { + controller.abort() + clearTimeout(timer) + const count = taskDialogs.get(key) - 1 + if (count) taskDialogs.set(key, count) + else taskDialogs.delete(key) + document.removeEventListener('visibilitychange', wake) + window.removeEventListener('online', wake) + window.removeEventListener('offline', wake) + } + }, [jobId, projectId, groupId, pollRun, visible]) + useEffect(() => { + // Saved group members also prove acceptance when a reply was lost. + // This only reconciles the display; it never submits remaining work. + if (!groupId || !result.requestedCount || !progress?.totalCount + || progress.totalCount <= (result.acceptedCount ?? 0)) return + const complete = progress.totalCount >= result.requestedCount + setResult(previous => ({ ...previous, acceptedCount: progress.totalCount, + ...(complete && { status: 'accepted', groupComplete: true, canContinueGroup: false }) })) + if (complete) { + forgetSubmission({ projectId, operationId: groupId }) + if (!busy.current) attempt.current = null + } + }, [groupId, projectId, result?.requestedCount, result?.acceptedCount, progress?.totalCount]) + async function send(makeAttempt) { + if (busy.current) return + // Accepted and uncertain submissions belong in task recovery, never in a new-input draft. + if (!existingJob) { + saveMediaDraft(draftKey, null) + flushMediaDrafts() + } + busy.current = true + setSubmitting(true) + let current + function receive(value) { + rememberTask(taskSession, current?.projectId, value, current?.kind || existingJob?.kind || form.kind, + current?.prompt || form.prompt || existingJob?.prompt) + if (value.groupId && value.jobId) setPollRun(value => value + 1) + if (value.projectCreated && current?.projectName) { + const project = { id: current.projectId, name: current.projectName } + setCatalog(previous => previous.projects.some(item => item.id === project.id) ? previous + : { ...previous, projects: [...previous.projects, project] }) + setForm(previous => ({ ...previous, projectId: project.id })) + rememberRecent(catalog?.scope, { projectId: project.id }) + } + if (attempt.current?.repeatJobId && !value.jobId) { + setRepeatStatus(value.status === 'unknown' ? 'generationUnknown' + : submissionMessages.get(value.code) ?? 'failedToSubmit') + } else { + setResult(previous => { + if (current?.candidateCount > 1 && previous?.groupId === current.operationId) { + const acceptedCount = Math.max(previous.acceptedCount ?? 0, value.acceptedCount ?? 0) + const complete = acceptedCount >= (value.requestedCount ?? previous.requestedCount) + return { ...previous, ...value, projectId: current.projectId, acceptedCount, + ...(complete && { status: 'accepted', groupComplete: true, canContinueGroup: false }) } + } + return { ...value, projectId: current?.projectId, + ...(value.status === 'unknown' && previous?.draftSaved + && { draftSaved: true, canvasUrl: value.canvasUrl ?? previous.canvasUrl }) } + }) + setRepeatStatus(null) + } + if (value.status !== 'unknown' || value.groupComplete) { + if (!value.groupId || value.groupComplete) forgetSubmission(current) + attempt.current = null + } + } + try { + const check = attempt.current !== null + attempt.current ??= makeAttempt() + current = attempt.current + if (!check) rememberSubmission(attempt.current, attempt.current.repeatJobId + ? ['repeat', attempt.current.projectId, attempt.current.repeatJobId].join(':') : draftKey, + form.prompt || existingJob?.prompt || '') + const response = await fetch('/api/opendirector/creation', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-OpenDirector-Action': '1' }, + body: JSON.stringify({ ...attempt.current, check }), + }) + if (response.status === 400 || response.status === 403) { + receive({ status: check ? 'unknown' : 'rejected' }) + return + } + if (!response.ok) throw new Error('Submission unavailable') + receive(await response.json()) + } catch { + receive({ status: attempt.current ? 'unknown' : 'rejected' }) + } finally { + busy.current = false + setSubmitting(false) + } } function submit(event) { event.preventDefault() - const detail = brief.trim() - if (!detail) return - if (request(message(action, detail), true)) { - setStatus(t('ready')) - setAction(null) - setBrief('') - } else { - setStatus(t('draftBusy')) + if (!unknown && (locked || missing)) return + send(() => { + const newProject = !source && !templateOf && form.projectId === 'new' + return { + projectId: templateOf?.projectId ?? source?.projectId ?? (newProject ? crypto.randomUUID() : form.projectId), + operationId: crypto.randomUUID(), + ...(templateOf && { reuseResultId: templateOf.resultId }), + ...(videoMode ? { videoMode, sourceResultId: videoSource.resultId, durationSeconds } + : source && { sourceResultIds: references.map(item => item.resultId) }), + ...(newProject && { projectName: form.projectName.trim() }), + kind: form.kind, modelConfigId: form.modelId, prompt: form.prompt.trim(), + output: templateOf ? form.output : output, voice: form.voice, candidateCount: form.candidateCount, + } + }) + } + function field(label, control) { + return h('label', { style: { display: 'grid', gap: '.3rem' } }, t(label), cloneElement(control, { 'aria-label': t(label) })) + } + const status = progress?.jobId === jobId ? progress?.status : null + const candidates = progress?.results ?? [] + const providerUnknown = Boolean(status) && progress.category === 'submission_unknown' + const canRetry = status === 'failed' && progress.canRetry + const settled = ['succeeded', 'failed', 'interrupted', 'cancelled'].includes(status) + || (!jobId && result?.status === 'rejected' && result.draftSaved) + const canAdjust = !existingJob && settled && !unknown && !providerUnknown && !attempt.current + && (!groupId || result.groupComplete && !progress?.jobs?.some(job => job.category === 'submission_unknown')) + const previousImages = previousRound && previousRound.projectId === projectId + ? previousRound.results.filter(item => item.kind === 'image') : [] + const currentImages = candidates.filter(item => item.kind === 'image') + const comparePair = previousImages.length === 1 && currentImages.length === 1 + && previousImages[0].resultId !== currentImages[0].resultId + ? [previousImages[0].resultId, currentImages[0].resultId] : null + const outcome = providerUnknown ? 'providerUnknown' + : status === 'failed' ? generationMessages.get(progress.category) ?? 'failed' + : ['cancelled', 'interrupted'].includes(status) ? 'stopped' : status === 'accepted' ? 'queued' : status + const submitLabel = submitting ? 'submitting' : unknown ? 'checkGeneration' + : result?.status === 'rejected' ? 'retrySubmission' : 'generate' + const generateLabel = submitLabel === 'generate' && form.candidateCount > 1 + ? t('generateGroup').replace('{count}', form.candidateCount) : t(submitLabel) + function toggleComparison(candidate) { + setComparison(previous => previous.includes(candidate.resultId) ? previous.filter(id => id !== candidate.resultId) + : previous.length < 2 ? [...previous, candidate.resultId] : previous) + } + function adjustGeneration() { + if (!canAdjust || busy.current) return + if (candidates.length) setPreviousRound({ projectId, canvasUrl: result.canvasUrl, results: candidates }) + setResult(null) + setProgress(null) + setPollError(false) + setRepeatStatus(null) + setComparison([]) + setComparing(false) + requestAnimationFrame(() => page.current?.querySelector('form textarea')?.focus()) + } + function checkGroup() { + attempt.current ??= { projectId, operationId: groupId, candidateCount: result.requestedCount } + return send(() => ({})) + } + async function continueGroup() { + const identity = { projectId, operationId: groupId, candidateCount: result.requestedCount } + attempt.current = null + await send(() => ({ ...identity, continueGroup: true })) + } + const previewSource = videoMode ? videoSource : source + const sourcePreview = previewSource && h(Preview, { + version: previewSource.version, projectId: previewSource.projectId, assetId: previewSource.assetId, kind: previewSource.kind, details: previewSource.details, t, + title: t(continuation ? 'sourceClip' : videoMode ? 'firstFrameSource' : 'original'), + }) + return h('div', { ref: page }, + back && button(t('backStep'), back, { 'data-step-back': '' }), + dialogHeader(title, onClose, t, + !existingJob && !source && !templateOf && !jobId ? t('createHint') : undefined), + !existingJob && !restoringPending && !catalog && h('p', { role: 'status' }, t('loading')), + !existingJob && !restoringPending && !locked && h('div', { style: row }, + restored && h('small', { role: 'status' }, t('draftRestored')), + earlierDraft && catalog && !catalog.error && !dirty && !locked && button(t('resumeEarlierDraft'), () => { + setForm({ ...defaults, ...earlierDraft.form }) + setRestored(true) + setEarlierDraft(null) + saveMediaDraft(draftKey, earlierDraft) + saveMediaDraft('create', null) + flushMediaDrafts() + }), + !restored && recentRestored && h('small', { role: 'status' }, t('recentRestored')), + (dirty || restored) && catalog && !catalog.error && button(t(templateOf ? 'resetTemplate' : 'clearDraft'), clearDraft)), + projectUnavailable && h('p', { role: 'alert' }, t('projectUnavailable')), + modelUnavailable && h('p', { role: 'alert' }, t('modelUnavailable')), + existingJob && h('p', { style: { overflowWrap: 'anywhere' } }, existingJob.prompt), + catalog?.error && h('div', { style: row }, + h('p', { role: 'alert' }, t(templateOf ? 'reuseUnavailable' : 'libraryError')), + button(t('reloadData'), () => setCatalogRun(value => value + 1))), + restoringPending && h(PendingSubmissions, { context: draftKey, t, onRecovered: job => openStep({ existingJob: job }) }), + restoringPending && !existingJob && button(t('startSeparateCreation'), () => setStartFresh(true)), + !restoringPending && pending.length > 0 && !pendingDurable && h('p', { role: 'alert' }, t('pendingStorageUnavailable')), + !restoringPending && catalog && !catalog.error && h(jobId ? 'details' : 'div', + { className: jobId ? 'od-settings' : undefined }, + jobId && h('summary', null, t('generationSettings')), + h('form', { onSubmit: submit, className: 'od-create-form' }, + !source && !templateOf && h('div', { role: 'group', 'aria-label': t('mediaType'), style: row }, + ...[['image', 'picture'], ['video', 'video'], ['audio', 'speech']].map(([kind, label]) => + button(t(label), () => { if (form.kind !== kind) update('kind', kind) }, + { key: kind, disabled: locked, current: form.kind === kind, 'aria-pressed': form.kind === kind }))), + !source && !templateOf && field('chooseProject', h('select', { + required: true, disabled: locked, value: form.projectId, onChange: event => { + const id = event.target.value + if (id !== 'new') chooseProject(catalog?.scope, sessionId, chatProject, id) + update('projectId', id) + }, + }, h('option', { value: '' }, t('chooseProject')), + ...catalog.projects.map(({ id, name }) => h('option', { key: id, value: id }, name)), + h('option', { value: 'new' }, t('newProject')))), + !source && !templateOf && form.projectId === 'new' && field('projectName', h('input', { + required: true, disabled: locked, value: form.projectName, onChange: event => update('projectName', event.target.value), + })), + !source && videoMode && !locked && h('div', null, + h('div', { role: 'group', 'aria-label': t('videoStart'), style: row }, + ...[['first_frame', 'animateStill'], ['continuation', 'extendClip']].map(([mode, label]) => + button(t(label), () => { if (mode !== videoMode) update('videoMode', mode) }, + { key: mode, current: videoMode === mode, 'aria-pressed': videoMode === mode }))), + !form.projectId ? h('p', null, t('videoProject')) + : form.projectId === 'new' ? h('div', { style: row }, h('p', null, t(continuation ? 'noClips' : 'noStills')), + button(t('makeStill'), () => update('kind', 'image'))) + : !projectUnavailable && h(VideoSourcePicker, { key: form.projectId + ':' + videoMode, + projectId: form.projectId, mode: videoMode, selected: videoSource, + onSelect: value => update('videoSource', value), t, + emptyAction: continuation ? button(t('animateStill'), () => update('videoMode', 'first_frame')) + : button(t('makeStill'), () => update('kind', 'image')) })), + field(form.kind === 'audio' ? 'speechText' : continuation ? 'shot' : videoMode ? 'motion' : source ? 'brief' : 'prompt', h('textarea', { + required: true, disabled: locked, rows: 3, maxLength: Math.min(model?.maxPromptCharacters ?? 20000, 20000), + placeholder: !source && form.kind === 'image' ? t('promptPlaceholder') : undefined, + value: form.prompt, onChange: event => update('prompt', event.target.value), + })), + !locked && chat?.useInput && h(ImportChatDraft, { useInput: chat.useInput, prompt: form.prompt, + limit: Math.min(model?.maxPromptCharacters ?? 20000, 20000), onApply: value => update('prompt', value), t }), + !locked && h(ExamplePicker, { + key: form.kind + (videoMode ?? ''), mode: form.kind === 'audio' ? 'audio' : continuation ? 'continuation' : videoMode ? 'first_frame' : source ? 'edit' : 'image', + prompt: form.prompt, t, onApply: value => update('prompt', value), + }), + h('div', { className: 'od-create-options' }, + field('model', h('select', { + name: 'model', required: true, disabled: locked || Boolean(templateOf), value: form.modelId, onChange: event => update('modelId', event.target.value), + }, h('option', { value: '' }, t('chooseModel')), + ...choices.map(item => h('option', { key: item.id, value: item.id }, + `${item.modelId} · ${t(item.connectionType === 'self_hosted' ? 'local' : 'hosted')}`)))), + choices.length === 0 && h('div', { style: row }, h('p', null, t(videoMode ? 'noVideoMode' : 'noModels')), + !locked && button(t('reloadData'), () => setCatalogRun(value => value + 1))), + video?.durations.length > 0 && field('videoDuration', h('select', { + disabled: locked, value: durationUnavailable ? '' : durationSeconds, + onChange: event => update('durationSeconds', Number(event.target.value)), + }, durationUnavailable && h('option', { value: '', disabled: true }, t('chooseDuration')), + ...video.durations.map(seconds => h('option', { key: seconds, value: seconds }, + t('duration').replace('{seconds}', seconds))))), + video?.durations.length === 0 && h('small', null, t('modelDuration')), + durationUnavailable && h('p', { role: 'alert' }, t('durationUnavailable')), + durationUnavailable && video.durations.length === 0 + && button(t('useDefaultDuration'), () => update('durationSeconds', null), { disabled: locked }), + form.kind === 'image' && h(ImageOutputField, { selection: imageSize, + original: templateOf ? catalog.template.originalOutput ?? '' : undefined, + onChange: value => update('output', value), disabled: locked, t }), + form.kind === 'audio' && field('voice', h('input', { + required: model?.voiceRequired, disabled: locked || Boolean(templateOf), maxLength: 200, value: form.voice, + onChange: event => update('voice', event.target.value), + })), + field('candidateCount', h('select', { value: form.candidateCount, disabled: locked, + onChange: event => update('candidateCount', Number(event.target.value)) }, + ...[1, 2, 3, 4].map(count => h('option', { key: count, value: count }, count)))), + form.candidateCount > 1 && h('small', null, t('groupHint').replace('{count}', form.candidateCount))), + catalog.template && h('small', null, t('reuseHint')), + catalog.template?.references.length > 0 && h('section', { 'aria-label': t('reuseReferences') }, + h('small', null, t('reuseReferences')), + h('div', { style: { display: 'grid', gap: '.5rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(10rem, 100%), 1fr))' } }, + ...catalog.template.references.map((reference, index) => h(Preview, { ...reference, + key: index, projectId: templateOf.projectId, t, title: t('referenceMedia') + ' ' + (index + 1), + })))), + candidates.length === 0 && sourcePreview, + continuation && h('small', null, t('continuationHint')), + source && !videoMode && h(ReferencePicker, { projectId: source.projectId, references, setReferences, limit: referenceLimit, locked, t }), + tooManyReferences && h('p', { role: 'alert' }, t('referencesChanged')), + (!locked || submitting || unknown) && h(SubmitRow, { label: generateLabel, busy: submitting, + reason: !unknown && missing ? t(missing) : null, focusModel: !unknown && missing === 'needsModel' }))), + templateOf?.canvasUrl && catalog?.error && canvasLink(templateOf.canvasUrl, t), + result?.status === 'rejected' && h('p', { role: 'alert' }, t(submissionMessages.get(result.code) ?? 'failedToSubmit')), + unknown && h('p', { role: 'status' }, t('generationUnknown')), + result?.draftSaved && !jobId && h('p', null, t('draftSaved')), + jobId && h('p', { role: status === 'failed' || providerUnknown ? 'alert' : 'status' }, t(outcome ?? 'waiting')), + jobId && h('small', null, t(taskSession && getChatTasks().some(item => item.sessionId === taskSession && taskKey(item) === taskKey(result)) + ? 'closeTaskHint' : 'backgroundHint')), + groupId && progress?.jobs && h('section', { 'aria-label': t('candidateCount'), style: { display: 'grid', gap: '.4rem' } }, + h('strong', null, t('groupSummary').replace('{done}', progress.completedCount) + .replace('{total}', progress.totalCount).replace('{failed}', progress.failedCount)), + ...progress.jobs.map((job, index) => h('div', { key: job.jobId, style: row }, + h('span', null, t('groupTask').replace('{number}', index + 1) + ' · ' + t( + ['queued', 'running', 'succeeded', 'failed', 'cancelled', 'interrupted'].includes(job.status) ? job.status : 'waiting')), + job.category && h('small', null, t(generationMessages.get(job.category) ?? 'failed')), + h(JobCancellation, { projectId, jobId: job.jobId, progress: job, t, + onChange: () => setPollRun(value => value + 1) })))), + groupId && result.requestedCount > result.acceptedCount && h('div', null, + h('p', { role: 'status' }, result.groupComplete ? t('groupStopped') + : t('groupUnsubmitted').replace('{count}', result.requestedCount - result.acceptedCount)), + !result.groupComplete && button(t('checkGeneration'), checkGroup, { disabled: submitting }), + result.canContinueGroup && button(t('continueGroup'), continueGroup, { disabled: submitting })), + jobId && !groupId && h(JobCancellation, { key: jobId, projectId, jobId, progress: progress?.jobId === jobId ? progress : null, t, + onChange: () => setPollRun(value => value + 1) }), + continuation && status === 'failed' && progress.category === 'reference' && h('p', null, t('continuationUnavailable')), + status && progress.canResume && h('p', null, t('recoverOnCanvas')), + updatesPaused && ['accepted', 'queued', 'running'].includes(progress?.status ?? result?.status ?? existingJob?.status) + && h('small', { role: 'status' }, t('updatesPaused')), + pollError && h('p', { role: 'alert' }, t('progressUnavailable')), + (pollError || providerUnknown) && button(t('checkProgress'), () => { setPollError(false); setPollRun(value => value + 1) }), + result?.canvasUrl && (jobId || result.draftSaved) && canvasLink(result.canvasUrl, t), + canAdjust && button(t('adjustGeneration'), adjustGeneration, { disabled: submitting }), + previousRound && h('details', { open: true, className: 'od-settings' }, + h('summary', null, t('previousRound')), + h(ImageReviewGrid, { style: { display: 'grid', gap: '.7rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(12rem, 100%), 1fr))' } }, + ...previousRound.results.map((item, index) => h(Preview, { + ...item, key: item.resultId, projectId: previousRound.projectId, canvasUrl: previousRound.canvasUrl, t, + onOpenGeneration: openStep, onMakePack: () => openPack({ ...item, projectId: previousRound.projectId }), + title: previousRound.results.length === 1 ? t('previousRound') : t('previousRound') + ' ' + (index + 1), + onCompare: !comparePair && previousImages.length && currentImages.length && item.kind === 'image' ? () => toggleComparison(item) : undefined, + compareSelected: comparison.includes(item.resultId), compareDisabled: comparison.length === 2 && !comparison.includes(item.resultId), + })))), + candidates.length > 0 && h(ImageReviewGrid, { + style: { display: 'grid', gap: '.7rem', marginBlock: '.7rem', + gridTemplateColumns: 'repeat(auto-fit, minmax(min(12rem, 100%), 1fr))' }, + }, sourcePreview, ...candidates.map((candidate, index) => h(Preview, { + ...candidate, projectId, key: candidate.resultId, t, canvasUrl: result.canvasUrl, + onOpenGeneration: openStep, onMakePack: () => openPack({ ...candidate, projectId }), + title: candidate.version || candidates.length === 1 ? t('candidate') : `${t('candidate')} ${index + 1}`, + onCompare: !comparePair && (groupId || previousImages.length) && candidate.kind === 'image' ? () => toggleComparison(candidate) : undefined, + compareSelected: comparison.includes(candidate.resultId), + compareDisabled: comparison.length === 2 && !comparison.includes(candidate.resultId), + onAdopted: () => setPollRun(value => value + 1), + }))), + comparePair ? button(t('compareRevisions'), () => { setComparison(comparePair); setComparing(true) }) + : (groupId || previousImages.length > 0) && currentImages.length > 0 && button(t('groupCompare') + ' (' + comparison.length + '/2)', + () => setComparing(true), { disabled: comparison.length !== 2 }), + comparing && h(ImageComparisonDialog, { projectId, resultIds: comparison, t, + onAdopted: () => setPollRun(value => value + 1), onClose: () => setComparing(false) }), + !restoringPending && !groupId && ((status === 'succeeded' && candidates.length > 0) || canRetry) && h('div', { style: row }, + h('label', { style: row }, t('moreCandidateCount'), h('select', { value: repeatCount, + 'aria-label': t('moreCandidateCount'), disabled: submitting, + onChange: event => setRepeatCount(Number(event.target.value)) }, + ...[1, 2, 3, 4].map(count => h('option', { key: count, value: count }, count)))), + button(repeatCount > 1 && !submitting && repeatStatus !== 'generationUnknown' + ? t('generateGroup').replace('{count}', repeatCount) + : t(submitting ? 'submitting' : repeatStatus === 'generationUnknown' ? 'checkGeneration' + : canRetry ? 'retryGeneration' : 'repeatGeneration'), + () => send(() => ({ projectId, operationId: crypto.randomUUID(), repeatJobId: jobId, candidateCount: repeatCount })), { disabled: submitting }), + h('small', { style: { color: muted } }, t('repeatHint'))), + repeatStatus && h('p', { role: repeatStatus === 'generationUnknown' ? 'status' : 'alert' }, t(repeatStatus))) + } + + function JobCancellation({ projectId, jobId, progress, t, onChange }) { + const operation = useRef(null) + const busy = useRef(false) + const [state, setState] = useState(null) + const requested = progress?.cancelRequested || state === 'stopRequested' + const active = ['accepted', 'queued', 'running'].includes(progress?.status) + const unknown = state === 'stopUnknown' + async function stop() { + if (busy.current) return + busy.current = true + const check = operation.current !== null + operation.current ??= crypto.randomUUID() + setState('stoppingGeneration') + try { + const response = await fetch('/api/opendirector/cancel', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-OpenDirector-Action': '1' }, + body: JSON.stringify({ projectId, jobId, operationId: operation.current, check }), + }) + if (response.status === 400 || response.status === 403) { + operation.current = null + setState('stopFailed') + return + } + if (!response.ok) throw new Error('Stop response unavailable') + const receipt = await response.json() + if (receipt.status === 'unknown') { + setState('stopUnknown') + return + } + operation.current = null + setState(receipt.status === 'applied' ? 'stopRequested' : receipt.status === 'noop' ? 'stopFinished' + : receipt.code === 'storage_busy' ? 'adoptBusy' + : receipt.code === 'revision_conflict' ? 'stopChanged' : 'stopFailed') + onChange() + } catch { + setState('stopUnknown') + } finally { + busy.current = false + } + } + let message = state + if (progress?.cancelRequested) { + message = progress.status === 'succeeded' ? 'stopFinished' + : progress.status === 'cancelled' + ? progress.remoteCancellation === 'confirmed' ? 'remoteStopped' + : ['requested', 'unknown'].includes(progress.remoteCancellation) ? 'remoteStopUnconfirmed' : 'localStopped' + : 'stopRequested' + } + if (!active && !message) return null + return h('div', { style: { display: 'grid', gap: '.4rem' } }, + ((active && !requested) || unknown) && button(t(state === 'stoppingGeneration' ? state : unknown ? 'checkStop' : 'stopGeneration'), + stop, { disabled: state === 'stoppingGeneration' }), + message === 'remoteStopUnconfirmed' && button(t('checkProgress'), onChange), + message && h('p', { role: ['stopFailed', 'stopUnknown', 'stopChanged', 'adoptBusy', 'remoteStopUnconfirmed'].includes(message) ? 'alert' : 'status' }, t(message))) + } + + function useAdoption({ projectId, resultId, onAdopted }) { + const operation = useRef(null) + const running = useRef(false) + const [status, setStatus] = useState(null) + const [canvasUrl, setCanvasUrl] = useState(null) + async function adopt() { + if (running.current) return + running.current = true + const check = operation.current !== null + setStatus('adopting') + try { + operation.current ??= crypto.randomUUID() + const response = await fetch('/api/opendirector/adopt', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-OpenDirector-Action': '1' }, + body: JSON.stringify({ projectId, resultId, operationId: operation.current, check }), + }) + if (response.status === 400 || response.status === 403) { + operation.current = null + setStatus('adoptFailed') + return + } + if (!response.ok) throw new Error('Adoption response unavailable') + const { status: outcome, code, canvasUrl: url } = await response.json() + if (outcome === 'unknown') { + setStatus('adoptUnknown') + return + } + operation.current = null + if (outcome === 'applied' || outcome === 'noop') { + setStatus('adopted') + setCanvasUrl(url) + onAdopted?.() + } else { + setStatus(code === 'storage_busy' ? 'adoptBusy' + : ['revision_conflict', 'missing_object', 'result.candidate_missing'].includes(code) ? 'adoptConflict' + : 'adoptFailed') + } + } catch { + setStatus(operation.current ? 'adoptUnknown' : 'adoptFailed') + } finally { + running.current = false + } + } + return { adopt, status, canvasUrl } + } + + function ActionMenu({ actions, position, trigger, close, label, t }) { + const menu = useRef(null) + useLayoutEffect(() => { + const element = menu.current + element.style.left = '0px' + element.style.top = '0px' + const origin = element.getBoundingClientRect() + element.style.left = '100px' + element.style.top = '100px' + const shifted = element.getBoundingClientRect() + const scaleX = (shifted.left - origin.left) / 100 || 1 + const scaleY = (shifted.top - origin.top) / 100 || 1 + const left = Math.max(8, Math.min(position.x, window.innerWidth - origin.width - 8)) + const anchorY = position.above ? position.y - origin.height - 4 : position.y + const top = Math.max(8, Math.min(anchorY, window.innerHeight - origin.height - 8)) + // Measure CSS offsets in viewport coordinates to include host zoom without integer-size rounding. + element.style.left = `${(left - origin.left) / scaleX}px` + element.style.top = `${(top - origin.top) / scaleY}px` + element.querySelector('[role="menuitem"]')?.focus() + }, [position]) + useEffect(() => { + function outside(event) { + if (!menu.current?.contains(event.target) && !trigger.current?.contains(event.target)) close(false) + } + document.addEventListener('pointerdown', outside) + return () => document.removeEventListener('pointerdown', outside) + }, [close, trigger]) + function keyboard(event) { + if (event.key === 'Escape' || event.key === 'Tab') { + event.stopPropagation() + if (event.key === 'Escape') event.preventDefault() + close() + return } + if (!['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) return + event.preventDefault() + const items = [...menu.current.querySelectorAll('[role="menuitem"]')] + const current = items.indexOf(document.activeElement) + const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 + : (current + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length + items[next]?.focus() + } + const style = { ...buttonStyle, display: 'block', width: '100%', textAlign: 'start', whiteSpace: 'nowrap', + border: 0, textDecoration: 'none', boxSizing: 'border-box' } + return h('div', { + ref: menu, role: 'menu', 'aria-label': label, onKeyDown: keyboard, + style: { position: 'fixed', zIndex: 100, padding: '.25rem', border, borderRadius: '.45rem', + background: surface, boxShadow: '0 4px 16px #0004', maxHeight: 'calc(100vh - 16px)', overflow: 'auto' }, + }, ...actions.map(({ label, run, href, quick, ...attributes }) => h(href ? 'a' : 'button', { + key: label, role: 'menuitem', tabIndex: -1, style, + ...(href ? { href } : { type: 'button' }), ...attributes, + onClick: () => { close(); run?.() }, + }, t(label)))) + } + + // Keep review order identical to the visible cards, including the source in an edit. + function ImageReviewGrid({ children, ...layout }) { + const cards = Children.toArray(children) + const images = cards.filter(card => card.type === Preview && card.props.kind === 'image') + const [active, setActive] = useState(null) + return h('div', layout, cards.map(card => { + const index = images.indexOf(card) + if (index < 0) return card + return cloneElement(card, { review: { + active: active === card.key, index, count: images.length, + close: () => setActive(null), open: () => setActive(card.key), + step: delta => { const next = images[index + delta]; if (next) setActive(next.key) }, + } }) + })) + } + + function OriginalImageDialog({ url, title, t, onClose, review, decision }) { + const dialog = useRef(null) + const [actualSize, setActualSize] = useState(false) + const [size, setSize] = useState(null) + const [status, setStatus] = useState('loading') + useEffect(() => { dialog.current.showModal() }, []) + return h('dialog', { + className: 'od-media-ui', + ref: dialog, 'aria-label': t('viewOriginal'), + onKeyDown: event => { + if (!review || event.altKey || event.ctrlKey || event.metaKey) return + if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') { + event.preventDefault() + review.step(event.key === 'ArrowLeft' ? -1 : 1) + } + }, + onClose: event => { if (event.target === event.currentTarget) onClose() }, + onContextMenu: event => event.stopPropagation(), + style: { ...dialogStyle, width: 'min(72rem, calc(100vw - 2rem))' }, + }, + h('header', { style: { ...row, justifyContent: 'space-between', marginBottom: '.65rem' } }, + h('div', { style: row }, h('strong', null, title), + size && h('small', { className: 'od-hint' }, size)), + h('div', { style: row }, + review?.count > 1 && h('nav', { 'aria-label': t('viewOriginal'), style: row }, + button(t('previousImage'), () => review.step(-1), { disabled: review.index === 0 }), + h('span', { role: 'status' }, (review.index + 1) + ' / ' + review.count), + button(t('nextImage'), () => review.step(1), { disabled: review.index + 1 === review.count })), + button(t(actualSize ? 'fitImage' : 'actualImageSize'), () => setActualSize(value => !value), + { disabled: status !== 'ready' }), + button(t('close'), () => dialog.current.close(), { autoFocus: true }))), + status === 'loading' && h('p', { role: 'status' }, t('loading')), + status === 'failed' ? h('div', { style: row }, + h('span', { role: 'alert' }, t('originalUnavailable')), + button(t('reloadData'), () => setStatus('loading'))) + : h('div', { style: { maxHeight: '62vh', overflow: 'auto', background: surface, borderRadius: '.55rem' } }, + h('img', { + src: url, alt: title, onLoad: event => { + const img = event.currentTarget + setSize(img.naturalWidth + ' × ' + img.naturalHeight) + setStatus('ready') + }, onError: () => setStatus('failed'), + style: { display: 'block', margin: 'auto', maxWidth: actualSize ? 'none' : '100%', + maxHeight: actualSize ? 'none' : '62vh', width: 'auto', height: 'auto' }, + })), + decision) + } + + function Preview({ projectId, projectName, assetId, resultId, kind, title, selected, prompt, details, t, onAdopted, onMakePack, onOpenGeneration, canvasUrl, expanded, review, onCompare, compareSelected, compareDisabled, compactActions, onDiscuss, saved, firstFrameFor, version, createdAt, sourceResultId, sourceVersion, sourceTitle, supportsContinuation }) { + const [failed, setFailed] = useState(false) + const [action, setAction] = useState(null) + const [status, setStatus] = useState('') + const [standaloneOriginal, setStandaloneOriginal] = useState(false) + const viewingOriginal = review ? review.active : standaloneOriginal + const openOriginal = review?.open ?? (() => setStandaloneOriginal(true)) + const thumbnail = useRef(null) + function closeOriginal() { + if (review) review.close() + else setStandaloneOriginal(false) + thumbnail.current?.focus({ preventScroll: true }) + } + function leaveOriginal(event) { + event.currentTarget.closest('dialog')?.close() + closeOriginal() + } + const [menu, setMenu] = useState(null) + const [buffering, setBuffering] = useState(false) + const trigger = useRef(null) + const player = useRef(null) + const adoption = useAdoption({ projectId, resultId, onAdopted }) + const chat = useContext(ChatContext) + const thumbnailUrl = mediaHref(projectId, assetId, kind) + const downloadUrl = thumbnailUrl + '&original=1' + const url = expanded && kind === 'image' ? downloadUrl : thumbnailUrl + const video = kind === 'video' + const audio = kind === 'audio' + const image = kind === 'image' + useEffect(() => { + const element = player.current + if (!video || !element || failed) return + const visible = new IntersectionObserver(entries => { + if (entries.some(entry => entry.isIntersecting)) { + element.preload = 'metadata' + visible.disconnect() + } + }) + visible.observe(element) + return () => visible.disconnect() + }, [video, url, failed]) + const facts = [ + (image || video) && details?.width && details?.height && t('fileSize').replace('{size}', `${details.width} × ${details.height}`), + image && details?.requestedSize && t('requestedSize').replace('{size}', details.requestedSize.replace('x', ' × ')), + (video || audio) && details?.durationSeconds + && t('duration').replace('{seconds}', Number(details.durationSeconds.toFixed(2))), + ].filter(Boolean) + const versionText = Number.isInteger(version) && version > 0 ? t('versionLabel').replace('{number}', version) : '' + const created = typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt)) ? new Date(createdAt) : null + const sourceText = sourceResultId && Number.isInteger(sourceVersion) && sourceVersion > 0 + ? t('sourceVersionLabel').replace('{title}', sourceTitle || t('candidate')).replace('{number}', sourceVersion) : '' + const mediaStyle = { width: '100%', height: expanded ? 'clamp(14rem, 50vh, 36rem)' : 'var(--od-preview-height)', display: 'block', objectFit: 'contain', + borderRadius: '.55rem', background: surface } + const onError = () => { setBuffering(false); setFailed(true) } + const playbackEvents = { + onWaiting: () => setBuffering(true), onStalled: () => setBuffering(true), + onPlaying: () => setBuffering(false), onCanPlay: () => setBuffering(false), + onPause: () => setBuffering(false), onEnded: () => setBuffering(false), } + const media = video + ? h('video', { ...playbackEvents, ref: player, src: url, controls: true, playsInline: true, preload: 'none', 'aria-label': title, onError, style: mediaStyle }) + : audio ? h('audio', { ...playbackEvents, ref: player, src: url, controls: true, preload: 'none', 'aria-label': title, onError, style: { width: '100%' } }) + : h('button', { type: 'button', ref: thumbnail, onClick: openOriginal, + 'aria-label': t('viewOriginal'), 'aria-haspopup': 'dialog', title: t('viewOriginal'), + style: { padding: 0, border: 0, background: 'transparent', cursor: 'zoom-in' }, + }, h('img', { src: url, alt: title, loading: 'lazy', onError, style: mediaStyle })) async function copyResult() { try { await navigator.clipboard.writeText(resultId) @@ -111,72 +2733,268 @@ window.__ModuleLoader__.load({ setStatus(resultId) } } - return h('figure', { style: { margin: 0, minWidth: 0, display: 'grid', gap: '.45rem', alignContent: 'start' } }, - h('figcaption', { style: { color: muted, fontSize: '.8em', fontWeight: 600 } }, title), - failed ? h('p', null, t('unavailable')) : media, + function referenceInChat(nextShot = false) { + const kindLabel = t(image ? 'picture' : kind) + const values = { title: [projectName, title].filter(Boolean).join(' · '), kind: kindLabel, projectId, resultId } + let text = t('assetReference').replace(/\{(\w+)\}/g, (_, key) => values[key]) + if (nextShot) text += '\n' + t('nextShotPrompt') + if (chat.appendChatDraft(text)) { + setStatus(t('chatRefAdded')) + chat.returnToChat?.() + return true + } + setStatus(t('discussBusy')) + return false + } + function closeMenu(restore = true) { + setMenu(null) + if (restore) trigger.current?.focus() + } + function contextMenu(event) { + if (event.target.closest('audio, video, form, [role="menu"]')) return + event.preventDefault() + setMenu({ x: event.clientX, y: event.clientY }) + } + function togglePlayback() { + const element = player.current + if (!element) return + if (element.paused) element.play().catch(() => setStatus(t('playbackFailed'))) + else element.pause() + } + function saveFrame() { + const element = player.current + if (!element || element.readyState < HTMLMediaElement.HAVE_CURRENT_DATA || element.seeking) { + setStatus(t('playForFrame')) + return + } + const frame = document.createElement('canvas') + frame.width = element.videoWidth + frame.height = element.videoHeight + const timestamp = element.currentTime.toFixed(3) + try { + frame.getContext('2d').drawImage(element, 0, 0) + frame.toBlob(blob => { + if (!blob) { setStatus(t('frameFailed')); return } + const link = document.createElement('a') + const url = URL.createObjectURL(blob) + link.href = url + link.download = `frame-${resultId}-${timestamp}s.png` + link.click() + setTimeout(() => URL.revokeObjectURL(url), 1000) + setStatus('') + }, 'image/png') + } catch { + setStatus(t('frameFailed')) + } + } + const pending = adoption.status === 'adopting' + const adoptLabel = pending ? 'adopting' : selected ? 'selected' + : adoption.status === 'adoptUnknown' ? 'checkAdoption' : 'adopt' + const canReference = Boolean(resultId && chat?.appendChatDraft) + function derive(mode) { + const step = mode === 'reuse' ? { templateOf: { projectId, resultId, kind, canvasUrl } } + : { source: { projectId, assetId, resultId, kind, details, version }, + ...(mode !== 'edit' && { videoMode: mode }) } + if (onOpenGeneration) onOpenGeneration(step) + else setAction(step) + } + const actions = [ + canReference && { label: 'referenceInChat', run: () => referenceInChat() }, + canReference && (image || video) && { label: 'planNextShot', run: () => referenceInChat(true) }, + image && onDiscuss && { label: 'discussEdit', quick: true, run: () => setStatus(onDiscuss() ? t('discussReady') : t('discussBusy')) }, + !expanded && (image || audio) && { label: 'reuseSettings', quick: audio && !compactActions, run: () => derive('reuse') }, + !expanded && image && { label: 'edit', quick: !compactActions, run: () => derive('edit') }, + image && { label: 'newActionPack', run: onMakePack ?? (() => setAction('pack')) }, + image && { label: 'viewOriginal', run: openOriginal }, + !expanded && image && { label: 'firstFrame', run: () => derive('first_frame') }, + video && supportsContinuation !== false && { label: 'continue', quick: !compactActions, run: () => derive('continuation') }, + (video || audio) && !failed && { label: player.current?.paused === false ? 'pause' : 'play', run: togglePlayback }, + video && !failed && { label: 'saveFrame', run: saveFrame }, + !selected && !pending && { label: adoptLabel, run: adoption.adopt }, + { label: 'download', href: downloadUrl, download: '' }, + canvasUrl && { label: 'canvas', href: canvasUrl, target: '_blank', rel: 'noopener noreferrer' }, + { label: 'copyId', run: copyResult }, + ].filter(Boolean) + const quickAction = actions.find(action => action.quick) + return h('figure', { + className: 'od-media-ui od-preview', 'data-selected': selected || undefined, + 'data-opendirector-result': resultId, + onContextMenu: resultId ? contextMenu : undefined, + style: { margin: 0, minWidth: 0, display: 'grid', gap: '.45rem', alignContent: 'start' }, + }, + h('figcaption', { style: { ...row, color: muted, fontSize: '.8em' } }, + h('strong', null, selected && title === t('candidate') ? t('selected') : title), + versionText && h('span', { className: 'od-version', 'data-opendirector-version': version, 'data-current': selected || undefined }, versionText), + facts.length > 0 && h('span', null, facts.join(' · '))), + (created || sourceText) && h('div', { style: { ...row, color: muted, fontSize: '.73em' } }, + created && h('time', { dateTime: createdAt, title: created.toLocaleString() }, + created.toLocaleString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })), + sourceText && h('span', { 'data-opendirector-source-version': sourceVersion }, sourceText)), + failed ? h('div', { style: row }, h('span', { role: 'alert' }, t('unavailable')), + button(t('retryMedia'), () => { + setFailed(false) + setStatus(previous => previous === t('playbackFailed') ? '' : previous) + }), + image && button(t('viewOriginal'), openOriginal, { ref: thumbnail, 'aria-haspopup': 'dialog' })) : media, + firstFrameFor?.length > 0 && h('small', { className: 'od-hint' }, t('wasFirstFrame').replace('{videos}', + () => firstFrameFor.map(video => video.title || video.resultId.slice(0, 8)).join(', '))), + buffering && h('small', { role: 'status' }, t('buffering')), + video && resultId && supportsContinuation === false && h('small', { style: { color: muted } }, t('noClipContinuation')), + onCompare && h('label', { style: row }, + h('input', { type: 'checkbox', checked: compareSelected, disabled: compareDisabled, + onChange: onCompare }), t('chooseComparison')), + prompt && (saved ? h('details', { style: { fontSize: '.82em', overflowWrap: 'anywhere' } }, + h('summary', null, t('savedPrompt')), h('p', null, prompt)) + : h('p', { style: { margin: 0, color: muted, fontSize: '.82em', overflowWrap: 'anywhere' } }, prompt)), resultId && h('div', { style: { display: 'grid', gap: '.45rem' } }, h('div', { style: row }, - video ? button(t('continue'), () => open('continuePrompt')) : button(t('edit'), () => open('editPrompt')), - !video && button(t('firstFrame'), () => open('firstFramePrompt')), - button(t('adopt'), () => setStatus(t(request(message('adoptPrompt')) ? 'draftReady' : 'draftBusy')), { primary: true }), - button('···', copyResult, { title: t('copyId'), 'aria-label': t('copyId') })), - action && h('form', { onSubmit: submit, style: row }, - h('input', { - autoFocus: true, type: 'text', value: brief, onChange: event => setBrief(event.target.value), - 'aria-label': t(action === 'editPrompt' ? 'brief' : 'shot'), - placeholder: t(action === 'editPrompt' ? 'brief' : 'shot'), - style: { ...buttonStyle, flex: '1 1 10rem', minWidth: 0, cursor: 'text' }, - }), - button(t('send'), undefined, { type: 'submit', primary: true, disabled: !brief.trim() }), - button(t('cancel'), () => { setAction(null); setBrief(''); setStatus('') })), - status && h('span', { role: 'status', style: { color: muted, fontSize: '.78em' } }, status))) + button(t(adoptLabel), adoption.adopt, { primary: !selected, current: selected, symbol: selected ? 'check' : undefined, disabled: pending || selected }), + quickAction && button(t(quickAction.label), quickAction.run, { 'aria-haspopup': onOpenGeneration || quickAction.label === 'discussEdit' ? undefined : 'dialog' }), + canReference && chat.returnToChat && button(t('referenceInChat'), () => referenceInChat()), + button('···', event => { + if (menu) closeMenu() + else { + const { left, bottom } = event.currentTarget.getBoundingClientRect() + setMenu({ x: left, y: bottom }) + } + }, { ref: trigger, 'aria-haspopup': 'menu', 'aria-expanded': Boolean(menu), title: t('actions'), 'aria-label': t('actions') })), + menu && h(ActionMenu, { actions, position: menu, trigger, close: closeMenu, label: t('actions'), t }), + adoption.status && !pending && !selected && !(adoption.status === 'adopted' && onAdopted) + && h('span', { role: 'status', style: { color: muted, fontSize: '.78em' } }, t(adoption.status)), + adoption.canvasUrl && !onAdopted && canvasLink(adoption.canvasUrl, t), + status && h('span', { role: 'status', style: { color: muted, fontSize: '.78em' } }, status)), + action && h(ChatOverlay, { onReturn: () => setAction(null) }, action === 'pack' + ? h(ActionPackDialog, { source: { projectId, resultId, assetId, kind, details, version }, t, onClose: () => setAction(null) }) + : h(GenerationDialog, { ...action, t, onClose: () => setAction(null) })), + viewingOriginal && h(OriginalImageDialog, { + url: downloadUrl, title: [title, versionText].filter(Boolean).join(' · '), t, review, onClose: closeOriginal, + decision: resultId && h('footer', { style: { ...row, marginTop: '.55rem' } }, + button(t(adoptLabel === 'adopt' ? 'adoptImage' : adoptLabel), adoption.adopt, + { primary: !selected, current: selected, disabled: pending || selected }), + !expanded && button(t('edit'), event => { leaveOriginal(event); derive('edit') }), + canReference && button(t('referenceInChat'), event => { if (referenceInChat()) leaveOriginal(event) }), + status === t('discussBusy') && h('span', { role: 'status' }, status), + adoption.status && !pending && !selected && h('span', { role: 'status' }, t(adoption.status))), + })) } function canvasLink(url, t) { return h('a', { href: url, target: '_blank', rel: 'noopener noreferrer', - style: { ...buttonStyle, textDecoration: 'none', whiteSpace: 'nowrap' } }, `${t('canvas')} ↗`) + className: 'od-button', style: { ...buttonStyle, textDecoration: 'none', whiteSpace: 'nowrap' } }, `${t('canvas')} ↗`) + } + + function discussImage(appendChatDraft, projectName, imageTitle, resultId, t) { + if (!appendChatDraft || !resultId) return undefined + return () => appendChatDraft(t('discussPrompt') + .replace('{image}', () => imageTitle).replace('{project}', () => projectName) + .replace('{id}', () => resultId.slice(0, 8))) } - function MediaResults({ meta, t, request }) { + function MediaResults({ meta, appendChatDraft, t }) { + const [adopted, setAdopted] = useState(null) const preview = meta.mediaPreview ?? meta.imagePreview const kind = preview.kind ?? 'image' - const heading = t(kind === 'video' ? 'videos' : 'images') + const heading = t(kind === 'video' ? 'videos' : kind === 'audio' ? 'audios' : 'images') const sourceKind = preview.sourceKind ?? kind - return h('section', { 'aria-label': heading, [`data-opendirector-${kind}-results`]: '', + return h('section', { className: 'od-media-ui', 'aria-label': heading, [`data-opendirector-${kind}-results`]: '', style: { display: 'grid', gap: '.75rem', padding: '.85rem 1rem', border, borderRadius: '.9rem' } }, h('header', { style: { ...row, justifyContent: 'space-between' } }, h('div', { style: { display: 'grid', gap: '.1rem' } }, h('span', { style: { color: muted, fontSize: '.73em' } }, `OpenDirector · ${heading}`), h('strong', { style: { fontSize: '1em', overflowWrap: 'anywhere' } }, preview.projectName)), canvasLink(meta.canvasUrl, t)), - h('div', { style: { display: 'grid', gap: '.7rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(12rem, 100%), 1fr))' } }, + h(ImageReviewGrid, { style: { display: 'grid', gap: '.7rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(12rem, 100%), 1fr))' } }, preview.sourceAssetId && h(Preview, { key: preview.sourceAssetId, projectId: meta.projectId, assetId: preview.sourceAssetId, - kind: sourceKind, title: t(sourceKind === 'video' ? 'sourceClip' : 'original'), t, + version: preview.candidates[0]?.sourceVersion, kind: sourceKind, details: preview.sourceDetails, title: t(sourceKind === 'video' ? 'sourceClip' : 'original'), t, }), - ...preview.candidates.map(({ resultId, assetId }, index) => h(Preview, { - key: resultId, projectId: meta.projectId, assetId, resultId, kind, t, request, - title: preview.candidates.length > 1 ? `${t('candidate')} ${index + 1}` : t('candidate'), - })))) + ...preview.candidates.map((candidate, index) => { + const title = candidate.version ? t('candidate') : preview.candidates.length > 1 ? `${t('candidate')} ${index + 1}` : t('candidate') + return h(Preview, { + ...candidate, key: candidate.resultId, projectId: meta.projectId, projectName: preview.projectName, kind, title, t, canvasUrl: meta.canvasUrl, + selected: adopted ? adopted === candidate.resultId : candidate.selected, onAdopted: () => setAdopted(candidate.resultId), + onDiscuss: kind === 'image' ? discussImage(appendChatDraft, preview.projectName, title, candidate.resultId, t) : undefined, + }) + }))) } - function MediaResultsTail({ turn, useChat, useInput, inputActions, t }) { + function SavedResults({ meta, results, appendChatDraft, t }) { + const [updated, setUpdated] = useState(null) + const [revision, setRevision] = useState(0) + const [status, setStatus] = useState('') + const projectId = meta.projectId + const ids = results.map(result => result.resultId).join(',') + useEffect(() => { + if (!revision) return + const controller = new AbortController() + fetch('/api/opendirector/library?' + new URLSearchParams({ project: projectId, show: ids }), + { signal: controller.signal }).then(async response => { + if (!response.ok) throw new Error('Saved results unavailable') + const value = await response.json() + if (!controller.signal.aborted) { setUpdated(value.results); setStatus('') } + }).catch(() => { if (!controller.signal.aborted) setStatus('savedRefreshFailed') }) + return () => controller.abort() + }, [revision, projectId, ids]) + function refresh() { setStatus('loading'); setRevision(value => value + 1) } + return h('section', { 'data-opendirector-saved-results': '', 'aria-label': t('savedOnly'), + style: { display: 'grid', gap: '.65rem' } }, + h('header', { style: { ...row, justifyContent: 'space-between' } }, + h('strong', null, meta.savedResults.projectName), + h('div', { style: row }, button(t('refresh'), refresh, { disabled: status === 'loading' }), + canvasLink(meta.canvasUrl, t))), + h(ImageReviewGrid, { style: { display: 'grid', gap: '.7rem', gridTemplateColumns: 'repeat(auto-fit, minmax(min(15rem, 100%), 1fr))' } }, + ...(updated ?? results).map((item, index) => { + const name = item.title || t(item.kind === 'image' ? 'picture' : item.kind) + const title = results.length > 1 ? (index + 1) + ' · ' + name : name + return h(Preview, { ...item, key: item.resultId, saved: true, projectId, projectName: meta.savedResults.projectName, title, t, canvasUrl: meta.canvasUrl, onAdopted: refresh, + onDiscuss: item.kind === 'image' ? discussImage(appendChatDraft, meta.savedResults.projectName, title, item.resultId, t) : undefined }) + })), + status && h('small', { role: status === 'loading' ? 'status' : 'alert' }, t(status))) + } + + function EditProposal({ meta, callId, t }) { + const [open, setOpen] = useState(false) + const { projectName, source, prompt } = meta.editDraft + return h('section', { className: 'od-settings', 'data-opendirector-edit-draft': '', 'aria-label': t('editProposal') }, + h('strong', null, t('editProposal')), + h('small', { className: 'od-hint' }, projectName + ' · ' + (source.title || t('picture'))), + h('p', { style: { whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' } }, prompt), + h('div', { style: row }, button(t('reviewEdit'), () => setOpen(true), { primary: true, 'aria-haspopup': 'dialog' }), + h('small', { className: 'od-hint' }, t('editProposalHint'))), + open && h(ChatOverlay, { onReturn: () => setOpen(false) }, h(GenerationDialog, { + source: { ...source, projectId: meta.projectId }, proposal: { prompt, callId }, t, onClose: () => setOpen(false) }))) + } + + function MediaResultsTail({ turn, useChat, appendChatDraft, t }) { const source = useChat(snapshot => snapshot.nodes.turnDataSource(turn.turn, 'tool-call')) const calls = useSyncExternalStore(source.subscribe, source.getSnapshot) - const request = useComposerRequest(useInput, inputActions) const previews = new Map() const adoptions = new Map() + const shows = [] + const latestShow = new Map() + const proposals = new Map() for (const { root } of calls) { const meta = root.meta if (root.name === 'opendirector_job' && (meta?.mediaPreview || meta?.imagePreview)) { previews.set(meta.jobId, meta) + } else if (root.name === 'opendirector_results' && meta?.savedResults) { + shows.push({ callId: root.callId, meta }) + for (const item of meta.savedResults.results) latestShow.set(meta.projectId + ':' + item.resultId, root.callId) + } else if (root.name === 'opendirector_results' && meta?.editDraft) { + proposals.set(meta.projectId + ':' + meta.editDraft.source.resultId, { callId: root.callId, meta }) } else if (root.name === 'opendirector_adopt_result' && meta?.status === 'applied' && meta.canvasUrl) { adoptions.set(meta.resultId, meta.canvasUrl) } } - if (!previews.size && !adoptions.size) return null - return h('div', { style: { display: 'grid', gap: '.65rem' } }, - ...Array.from(previews, ([key, meta]) => h(MediaResults, { key, meta, t, request })), + if (!previews.size && !adoptions.size && !shows.length && !proposals.size) return null + return h('div', { className: 'od-media-ui', style: { display: 'grid', gap: '.65rem' } }, + ...Array.from(previews, ([key, meta]) => h(MediaResults, { key, meta, appendChatDraft, t })), + ...shows.map(({ callId, meta }) => { + const results = meta.savedResults.results.filter(item => latestShow.get(meta.projectId + ':' + item.resultId) === callId) + return results.length > 0 && h(SavedResults, { key: callId + ':' + results.map(item => item.resultId).join(','), + meta, results, appendChatDraft, t }) + }), + ...Array.from(proposals.values(), ({ callId, meta }) => h(EditProposal, { key: callId, callId, meta, t })), ...Array.from(adoptions, ([key, url]) => h('div', { key, 'data-opendirector-adoption': '', style: { ...row, justifyContent: 'space-between', padding: '.5rem .7rem', border, borderRadius: '.55rem', fontSize: '.9em' }, @@ -186,13 +3004,52 @@ window.__ModuleLoader__.load({ return { inject: ['slots', 'locale'], apply(ctx) { + ctx.effect(() => { + const style = document.createElement('style') + style.textContent = clientStyles + packStyles + document.head.append(style) + return () => style.remove() + }) + ctx.effect(() => { + window.addEventListener('pagehide', flushMediaDrafts) + return () => { flushMediaDrafts(); window.removeEventListener('pagehide', flushMediaDrafts) } + }) ctx.effect(() => ctx.locale.register(namespace, { en, zh })) + const chatFor = sessionId => { + const input = ctx.get('conversation')?.input + const binding = ctx.get('sessions')?.binding?.(sessionId) + if (!binding || !input?.requestDraftInitialization) return { sessionId } + return { sessionId, + focusChat: () => requestAnimationFrame(() => { + const composer = input.for?.(binding.ctx) + if (!composer?.focus) return + composer.focus() + const editor = document.activeElement + if (editor?.isContentEditable) { + const placeCaret = () => window.getSelection()?.collapse(editor, editor.childNodes.length) + placeCaret() + // rc.5 restores a previous selection after focus. Allow that update to settle. + requestAnimationFrame(() => { if (document.activeElement === editor) placeCaret() }) + } + }), + appendChatDraft: prompt => input.requestDraftInitialization(binding, + { prompt, whenDraftExists: 'append' }) === 'applied' } + } ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({ name: 'conversation.chat.turnTail', id: '@opendirector/dsh-plugin', locale: namespace, - }, MediaResultsTail)) + inject: chatFor, + }, props => h(ChatContext.Provider, { value: { sessionId: props.sessionId, useInput: props.useInput, + appendChatDraft: props.appendChatDraft, returnToChat: props.focusChat } }, h(MediaResultsTail, props)))) ctx.slots.inject('conversation.input.left', () => ctx.slots.register({ name: 'conversation.input.left', id: '@opendirector/dsh-plugin:create', locale: namespace, - }, CreateMedia)) + inject: sessionId => ({ ...chatFor(sessionId), sessionId, readChatProject() { + const binding = ctx.get('sessions')?.binding?.(sessionId) + return binding ? lastChatProject(ctx.get('uiConversation')?.binding(binding).target('chat').getSnapshot()) : null + } }), + }, props => h(CreateMedia, { ...props, key: props.sessionId, + openPlugin: typeof ctx.get('pluginNavigation')?.openBundle === 'function' + ? () => ctx.get('pluginNavigation')?.openBundle('@opendirector/dsh-plugin') : undefined, + }))) }, } }, diff --git a/plugins/deepseek-harness/test/action-packs.test.js b/plugins/deepseek-harness/test/action-packs.test.js new file mode 100644 index 000000000..09dd0537d --- /dev/null +++ b/plugins/deepseek-harness/test/action-packs.test.js @@ -0,0 +1,302 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import test from 'node:test' +import { actionPackRequest, actionPackArchive, packState } from '../src/action-packs.js' +import { UnknownOperationError } from '../src/errors.js' +import { uuid5 } from '../src/operations.js' + +function fixture() { + const projectId = randomUUID(), sourceId = randomUUID(), modelId = randomUUID() + const asset = { assetId: randomUUID(), revision: 1, fingerprint: 'a'.repeat(64), kind: 'image' } + const snapshot = { project: { id: projectId, name: '角色' }, canvasItems: [], generationSpecs: [], + references: [], jobs: [], results: [{ id: sourceId, asset }], assets: [] } + const commands = [], receipts = new Map() + let loseNext = false, catalogs = 0 + const io = { + async read() { return structuredClone(snapshot) }, + async models() { catalogs++; return [{ id: modelId, modelId: 'test', kind: 'image', maxImages: 1, + imageOutputs: [{ size: '1024x1024', aspectRatio: '1:1' }] }] }, + async receipt(id) { return receipts.get(id) }, + canRetry: job => job.status === 'failed' && job.errorDetails?.category === 'quota', + async media(id) { return { body: new ReadableStream({ start(controller) { + controller.enqueue(new TextEncoder().encode(id)); controller.close() + } }) } }, + async edit(fn) { return fn(structuredClone(snapshot), async command => { + commands.push(command) + let receipt + if (command.type === 'creation.batch') { + for (const { type, payload } of command.payload.operations) { + if (type === 'canvas.show') snapshot.canvasItems.push({ revision: 1, ...payload.item }) + if (type === 'generationSpec.create') snapshot.generationSpecs.push({ revision: 1, ...payload.spec }) + if (type === 'reference.add') snapshot.references.push(payload.reference) + } + receipt = { status: 'applied' } + } else if (command.type === 'generationSpec.update') { + const index = snapshot.generationSpecs.findIndex(spec => spec.id === command.payload.spec.id) + snapshot.generationSpecs[index] = { ...command.payload.spec, revision: command.payload.spec.revision + 1 } + receipt = { status: 'applied' } + } else { + const spec = snapshot.generationSpecs.find(spec => spec.id === command.payload.specId) + const job = { id: randomUUID(), status: 'succeeded', inputSnapshot: { + spec: structuredClone(spec), model: { modelId: 'frozen-model', apiKey: 'PRIVATE' }, + } } + snapshot.jobs.push(job) + receipt = { status: 'accepted', jobIds: [job.id] } + } + receipts.set(command.commandId, receipt) + if (loseNext) { loseNext = false; throw new UnknownOperationError({ projectId, operationId: command.commandId }) } + return receipt + }) }, + } + const input = { action: 'prepare', projectId, operationId: randomUUID(), modelConfigId: modelId, + sourceResultId: sourceId, title: '角色动作', sharedPrompt: 'same character', + actions: [{ name: '待机', prompt: 'standing' }, { name: '挥手', prompt: 'waving' }] } + return { io, input, snapshot, commands, receipts, lose: () => { loseNext = true }, catalogs: () => catalogs } +} + +test('action plan is one atomic project batch with separate specs and one pinned reference per action', async () => { + const f = fixture() + const result = await actionPackRequest(f.input, f.io) + assert.equal(result.status, 'applied') + assert.equal(f.commands.length, 1) + assert.equal(f.commands[0].type, 'creation.batch') + const { group, children } = { group: f.snapshot.canvasItems[0], children: f.snapshot.canvasItems.slice(1) } + assert.deepEqual(group.tags, ['dsh-action-pack']) + assert.deepEqual(children.map(item => item.title), ['待机', '挥手']) + assert.ok(children.every(item => item.parentId === group.id)) + assert.notEqual(children[0].binding.objectRef.id, children[1].binding.objectRef.id) + assert.deepEqual(f.snapshot.generationSpecs.map(spec => spec.prompt), ['same character\n\nstanding', 'same character\n\nwaving']) + assert.ok(f.snapshot.references.every(ref => ref.binding === 'pinned' && ref.role === 'reference' + && ref.source.assetId === f.snapshot.results[0].asset.assetId)) + assert.equal(packState(f.snapshot, group.id, f.io.canRetry).actions[0].reference.assetId, f.snapshot.results[0].asset.assetId) + const before = f.catalogs() + await actionPackRequest(f.input, f.io) + assert.equal(f.catalogs(), before) + assert.equal(f.commands.length, 1) + const query = await actionPackRequest({ action: 'check', projectId: f.input.projectId, operationId: f.input.operationId }, f.io) + assert.equal(query.status, 'applied') + assert.equal(query.actions.length, 2) + assert.equal(f.commands.length, 1) + f.snapshot.canvasItems[1].visible = false + assert.equal(packState(f.snapshot, group.id, f.io.canRetry).actions.length, 2) +}) + +test('an action pack keeps the chosen image size and only uses automatic sizing when none was requested', async () => { + const f = fixture() + const output = { size: '2048x2048', aspectRatio: '1:1' } + const model = (await f.io.models())[0] + f.io.models = async () => [model] + model.imageOutputs = [] + await assert.rejects(actionPackRequest({ ...f.input, output }, f.io), { key: 'creation.output' }) + assert.equal(f.commands.length, 0) + await actionPackRequest(f.input, f.io) + assert.deepEqual(f.snapshot.generationSpecs[0].parameters, { size: 'auto' }) + model.imageOutputs = [{ size: '1024x1024', aspectRatio: '1:1' }, output] + await actionPackRequest({ ...f.input, operationId: randomUUID(), output }, f.io) + assert.deepEqual(f.snapshot.generationSpecs.at(-1).parameters, output) +}) + +test('invalid plans and unsupported references never write; video actions pin the first frame', async () => { + const f = fixture() + for (const actions of [[], Array(7).fill({ name: 'x', prompt: 'p' }), + [{ name: 'Idle', prompt: 'x' }, { name: 'IDLE', prompt: 'y' }]]) { + await assert.rejects(actionPackRequest({ ...f.input, actions }, f.io), { key: 'pack.plan' }) + } + await assert.rejects(actionPackRequest({ ...f.input, sourceResultId: randomUUID() }, f.io), + { key: 'result.candidate_missing' }) + assert.equal(f.commands.length, 0) + f.io.models = async () => [{ id: f.input.modelConfigId, kind: 'video', videoChoices: { + first_frame: { resolution: '480P', durations: [5], defaultDuration: 5 }, + } }] + await actionPackRequest(f.input, f.io) + assert.ok(f.snapshot.references.every(ref => ref.role === 'first_frame')) + assert.ok(f.snapshot.generationSpecs.every(spec => spec.parameters.videoMode === 'first_frame' + && spec.parameters.durationSeconds === 5)) +}) + +test('lost generation response resumes exact child operations without duplicate jobs or automatic adoption', async () => { + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + const plan = packState(f.snapshot, packId, f.io.canRetry) + const input = { action: 'generate', projectId: f.input.projectId, packId, operationId: randomUUID(), + itemIds: plan.actions.map(action => action.itemId) } + f.lose() + assert.equal((await actionPackRequest(input, f.io)).status, 'unknown') + assert.equal(f.snapshot.jobs.length, 1) + const check = await actionPackRequest({ ...input, action: 'check', packAction: 'generate' }, f.io) + assert.equal(check.status, 'unknown') + assert.equal(f.snapshot.jobs.length, 1) + await actionPackRequest(input, f.io) + assert.equal(f.snapshot.jobs.length, 2) + await actionPackRequest(input, f.io) + assert.equal(f.snapshot.jobs.length, 2) + assert.equal((await actionPackRequest({ ...input, action: 'check', packAction: 'generate' }, f.io)).status, 'applied') + const submits = f.commands.filter(command => command.type === 'generation.submit') + assert.deepEqual(submits.map(command => command.commandId), input.itemIds.map(id => uuid5(input.operationId, 'action:' + id))) + assert.ok(submits.every(command => command.payload.adoptionPolicy === 'candidate_only' && !command.payload.batchId)) + assert.ok(f.snapshot.generationSpecs.every(spec => !spec.currentResultId)) + await actionPackRequest({ ...input, operationId: randomUUID() }, f.io) + assert.equal(f.snapshot.jobs.length, 2) + const retry = { ...input, itemIds: [input.itemIds[0]], operationId: randomUUID(), redo: true } + f.snapshot.jobs[0].status = 'running' + await actionPackRequest(retry, f.io) + assert.equal(f.snapshot.jobs.length, 2) + f.snapshot.jobs[0].status = 'failed'; f.snapshot.jobs[0].errorDetails = { category: 'submission_unknown' } + await actionPackRequest(retry, f.io) + assert.equal(f.snapshot.jobs.length, 2) + f.snapshot.jobs[0].errorDetails = { category: 'quota' } + await actionPackRequest(retry, f.io) + assert.equal(f.snapshot.jobs.length, 3) + assert.equal(f.commands.at(-1).payload.previousJobId, f.snapshot.jobs[0].id) +}) + +test('pack export captures each action’s selected version and actual generation settings', async () => { + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + await assert.rejects(actionPackArchive({ packId }, f.io), { key: 'pack.incomplete' }) + const plan = packState(f.snapshot, packId, f.io.canRetry) + await actionPackRequest({ action: 'generate', projectId: f.input.projectId, packId, + operationId: randomUUID(), itemIds: plan.actions.map(action => action.itemId) }, f.io) + for (const [i, spec] of f.snapshot.generationSpecs.entries()) { + const asset = { id: randomUUID(), kind: 'image', fingerprint: String(i).repeat(64), + metadata: { mimeType: 'image/png', size: 36 } } + const result = { id: randomUUID(), specId: spec.id, jobId: f.snapshot.jobs[i].id, + asset: { assetId: asset.id, kind: 'image' } } + f.snapshot.assets.push(asset); f.snapshot.results.push(result) + spec.currentResultId = result.id; spec.prompt = 'edited later' + } + f.snapshot.canvasItems[1].title = '../待机' + const archive = await actionPackArchive({ packId }, f.io) + // Changing selection after starting an export does not mix versions into its manifest. + f.snapshot.generationSpecs[0].currentResultId = 'different' + const files = [] + for await (const entry of archive.entries) files.push({ name: entry.name, + body: await new Response(entry.data).text() }) + const manifest = JSON.parse(files[0].body) + assert.deepEqual(files.map(file => file.name), ['manifest.json', '01-..-待机.png', '02-挥手.png']) + assert.equal(manifest.actions[0].description, 'same character\n\nstanding') + assert.equal(manifest.actions[1].model, 'frozen-model') + assert.equal(files[1].body, f.snapshot.assets[0].id) + assert.doesNotMatch(files[0].body, /PRIVATE|apiKey|edited later/) +}) + +test('action-pack HTTP route keeps reads lease-free, guards writes and streams selected original assets', async t => { + const { apply } = await import('../index.js') + const { createServer } = await import('node:http') + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + const actions = packState(f.snapshot, packId, f.io.canRetry).actions + for (const action of actions) { + const assetId = randomUUID(), resultId = randomUUID() + f.snapshot.assets.push({ id: assetId, kind: 'image', fingerprint: 'b'.repeat(64), metadata: { mimeType: 'image/png', size: 3 } }) + f.snapshot.results.push({ id: resultId, specId: action.specId, asset: { assetId, kind: 'image' } }) + f.snapshot.generationSpecs.find(spec => spec.id === action.specId).currentResultId = resultId + } + const requests = [] + const server = createServer((request, response) => { + requests.push(request.method + ' ' + request.url) + assert.equal(request.headers['x-opendirector-request'], '1') + if (request.url === '/api/creation/projects/' + f.input.projectId) { + response.setHeader('Content-Type', 'application/json'); response.end(JSON.stringify(f.snapshot)); return + } + if (request.url.endsWith('/content')) { + response.setHeader('Content-Type', 'image/png'); response.end(Buffer.from([1, 2, 3])); return + } + response.statusCode = 404; response.end('{}') + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => new Promise(resolve => server.close(resolve))) + const routes = new Map() + apply({ tools: { register() {} }, get() {}, inject(_services, callback) { + callback({ effect(fn) { fn() }, connection: { fetch: { register(route) { routes.set(route.path, route.fetch) } } } }) + } }, { baseUrl: 'http://127.0.0.1:' + server.address().port }) + const route = routes.get('/api/opendirector/action-packs') + const base = 'http://localhost/api/opendirector/action-packs' + assert.equal((await route(new Request(base, { method: 'POST', body: '{}' }))).status, 403) + assert.equal((await route(new Request(base, { method: 'POST', headers: { + 'X-OpenDirector-Action': '1', 'Sec-Fetch-Site': 'cross-site', + }, body: '{}' }))).status, 403) + assert.equal(requests.length, 0) + const view = await route(new Request(base + '?project=' + f.input.projectId + '&pack=' + packId)) + assert.equal((await view.json()).selectedCount, 2) + assert.ok(requests.every(request => request.startsWith('GET '))) + const archive = await route(new Request(base + '?project=' + f.input.projectId + '&pack=' + packId + '&download=1')) + assert.equal(archive.headers.get('Content-Type'), 'application/zip') + assert.match(archive.headers.get('Content-Disposition'), /attachment; filename="action-pack-/) + assert.equal(archive.headers.get('Cache-Control'), 'private, no-store') + const body = Buffer.from(await archive.arrayBuffer()) + assert.equal(body.readUInt32LE(0), 0x04034b50) + assert.ok(requests.some(request => request.endsWith('/content'))) + assert.ok(!requests.some(request => request.includes('/thumbnail') || request.includes('/open'))) +}) + +test('a receipt read outage after a partial group keeps the original operation recoverable', async () => { + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + const plan = packState(f.snapshot, packId, f.io.canRetry) + const input = { action: 'generate', projectId: f.input.projectId, packId, + operationId: randomUUID(), itemIds: plan.actions.map(action => action.itemId) } + const read = f.io.receipt + f.io.receipt = async id => { + if (f.snapshot.jobs.length === 1) throw new Error('offline') + return read(id) + } + assert.equal((await actionPackRequest(input, f.io)).status, 'unknown') + assert.equal(f.snapshot.jobs.length, 1) + f.io.receipt = read + await actionPackRequest(input, f.io) + assert.equal(f.snapshot.jobs.length, 2) + assert.equal(f.commands.filter(command => command.type === 'generation.submit').length, 2) +}) + +test('revising one action preserves pinned references, sibling prompts, selected results and frozen jobs', async () => { + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + const plan = packState(f.snapshot, packId, f.io.canRetry) + await actionPackRequest({ action: 'generate', projectId: f.input.projectId, packId, + operationId: randomUUID(), itemIds: plan.actions.map(action => action.itemId) }, f.io) + const first = f.snapshot.generationSpecs[0] + const selected = first.currentResultId = randomUUID() + const oldInputs = structuredClone(f.snapshot.jobs.map(job => job.inputSnapshot)) + const oldRefs = structuredClone(f.snapshot.references) + const input = { action: 'revise', projectId: f.input.projectId, packId, operationId: randomUUID(), + itemId: plan.actions[0].itemId, expectedSpecRevision: first.revision, prompt: 'A slower wave' } + const result = await actionPackRequest(input, f.io) + assert.equal(result.status, 'applied') + assert.equal(f.snapshot.generationSpecs[0].prompt, input.prompt) + assert.equal(f.snapshot.generationSpecs[0].revision, 2) + assert.equal(f.snapshot.generationSpecs[0].currentResultId, selected) + assert.equal(f.snapshot.generationSpecs[1].prompt, 'same character\n\nwaving') + assert.deepEqual(f.snapshot.references, oldRefs) + assert.deepEqual(f.snapshot.jobs.map(job => job.inputSnapshot), oldInputs) + assert.equal(f.snapshot.jobs.length, 2) + const writes = f.commands.length + await actionPackRequest(input, f.io) + assert.equal(f.commands.length, writes) + const checked = await actionPackRequest({ action: 'check', projectId: f.input.projectId, packId, + operationId: input.operationId, packAction: 'revise', itemIds: [input.itemId] }, f.io) + assert.equal(checked.status, 'applied') + await assert.rejects(actionPackRequest({ ...input, operationId: randomUUID() }, f.io), { key: 'revision_conflict' }) + assert.equal(f.commands.length, writes) + f.snapshot.jobs[0].status = 'running' + await assert.rejects(actionPackRequest({ ...input, operationId: randomUUID(), expectedSpecRevision: 2 }, f.io), { key: 'pack.active' }) + assert.equal(f.commands.length, writes) +}) + +test('lost action-edit response can be confirmed without generating or rewriting the revision', async () => { + const f = fixture() + const { packId } = await actionPackRequest(f.input, f.io) + const action = packState(f.snapshot, packId, f.io.canRetry).actions[0] + const input = { action: 'revise', projectId: f.input.projectId, packId, operationId: randomUUID(), + itemId: action.itemId, expectedSpecRevision: 1, prompt: 'Wave with the other hand' } + f.lose() + await assert.rejects(actionPackRequest(input, f.io), { name: 'UnknownOperationError' }) + const recovered = await actionPackRequest({ action: 'check', projectId: f.input.projectId, packId, + operationId: input.operationId, packAction: 'revise', itemIds: [input.itemId] }, f.io) + assert.equal(recovered.status, 'applied') + assert.equal(recovered.actions[0].prompt, input.prompt) + assert.equal(recovered.actions[0].revision, 2) + assert.equal(f.snapshot.jobs.length, 0) + await actionPackRequest(input, f.io) + assert.equal(f.snapshot.generationSpecs[0].revision, 2) +}) diff --git a/plugins/deepseek-harness/test/archive.test.js b/plugins/deepseek-harness/test/archive.test.js new file mode 100644 index 000000000..c14319d90 --- /dev/null +++ b/plugins/deepseek-harness/test/archive.test.js @@ -0,0 +1,202 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { zipEntries } from '../src/archive.js' + +const encoder = new TextEncoder() + +async function collect(entries, options) { + const chunks = [] + for await (const chunk of zipEntries(entries, options)) chunks.push(Buffer.from(chunk)) + return Buffer.concat(chunks) +} + +function findPython() { + const candidates = [process.env.PYTHON, process.env.PYTHON3, 'python3', 'python'] + for (const command of candidates) { + if (!command) continue + const result = spawnSync(command, ['-c', 'import sys; print(sys.version_info[0])'], { + encoding: 'utf8', + windowsHide: true, + }) + if (result.status === 0 && result.stdout.trim() === '3') return command + } + return null +} + +const PYTHON_SCRIPT = ` +import base64, binascii, json, sys, zipfile +path = sys.argv[1] +with zipfile.ZipFile(path) as archive: + bad = archive.testzip() + entries = [] + for info in archive.infolist(): + data = archive.read(info.filename) + entries.append({ + 'name': info.filename, + 'size': info.file_size, + 'compress_size': info.compress_size, + 'crc': info.CRC, + 'expected_crc': binascii.crc32(data) & 0xffffffff, + 'method': info.compress_type, + 'utf8': bool(info.flag_bits & 0x800), + 'descriptor': bool(info.flag_bits & 0x8), + 'data': base64.b64encode(data).decode('ascii'), + }) +print(json.dumps({'bad': bad, 'entries': entries})) +` + +async function inspectWithPython(t, archive) { + const python = findPython() + if (!python) { + t.diagnostic('independent Python zipfile validation skipped: Python 3 not found') + return null + } + const directory = await mkdtemp(join(tmpdir(), 'dsh-archive-')) + t.after(() => rm(directory, { recursive: true, force: true })) + const path = join(directory, 'archive.zip') + await writeFile(path, archive) + const result = spawnSync(python, ['-c', PYTHON_SCRIPT, path], { + encoding: 'utf8', + windowsHide: true, + maxBuffer: 16 * 1024 * 1024, + }) + assert.equal(result.status, 0, result.stderr) + const parsed = JSON.parse(result.stdout) + assert.equal(parsed.bad, null) + return parsed.entries +} + +test('creates a ZIP32 stored archive that Python reads with UTF-8 names and real CRCs', async t => { + const streamedParts = [ + encoder.encode('streamed '), + encoder.encode('chunks '), + new Uint8Array([0, 1, 2, 255]), + ] + const expected = new Map([ + ['中文 名字.txt', Buffer.from(encoder.encode('你好,ZIP!'))], + ['empty.txt', Buffer.alloc(0)], + ['streamed.bin', Buffer.concat(streamedParts.map(part => Buffer.from(part)))], + ['web.bin', Buffer.from(encoder.encode('web stream'))], + ]) + const entries = [ + { name: '中文 名字.txt', data: new Uint8Array(expected.get('中文 名字.txt')) }, + { name: 'empty.txt', data: new Uint8Array(0) }, + { name: 'streamed.bin', data: (async function* () { yield* streamedParts })() }, + { + name: 'web.bin', + data: new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('web ')) + controller.enqueue(encoder.encode('stream')) + controller.close() + }, + }), + }, + ] + const archive = await collect(entries) + assert.equal(archive.subarray(0, 4).toString('hex'), '504b0304') + + const actual = await inspectWithPython(t, archive) + if (!actual) return + assert.equal(actual.length, 4) + for (const info of actual) { + const bytes = expected.get(info.name) + assert.ok(bytes, `unexpected entry ${info.name}`) + assert.equal(info.size, bytes.length) + assert.equal(info.compress_size, bytes.length) + assert.equal(info.method, 0) + assert.equal(info.utf8, true) + assert.equal(info.descriptor, true) + assert.equal(info.crc, info.expected_crc) + assert.deepEqual(Buffer.from(info.data, 'base64'), bytes) + } +}) + +test('rejects unsafe, duplicate and oversized entry names', async () => { + const rejected = [ + ['../escape.txt', /slashes/], + ['dir/file.txt', /slashes/], + ['dir\\file.txt', /slashes/], + ['.', /basename/], + ['..', /basename/], + ['', /basename/], + [null, /basename/], + ['bad\nname.txt', /control/], + ['bad\u0000name.txt', /control/], + ['bad\u007f.txt', /control/], + ['bad\u0085.txt', /control/], + ['a'.repeat(256), /255/], + ['中'.repeat(86), /255/], + ] + for (const [name, pattern] of rejected) { + await assert.rejects(collect([{ name, data: new Uint8Array(0) }]), pattern) + } + await assert.rejects(collect([ + { name: 'same.txt', data: new Uint8Array(0) }, + { name: 'same.txt', data: new Uint8Array(0) }, + ]), /duplicate/) +}) + +test('enforces the cumulative uncompressed size cap', async () => { + const archive = await collect([ + { name: 'a.bin', data: new Uint8Array(6) }, + { name: 'b.bin', data: new Uint8Array(4) }, + ], { maxBytes: 10 }) + assert.ok(archive.length > 0) + await assert.rejects(collect([ + { name: 'a.bin', data: new Uint8Array(6) }, + { name: 'b.bin', data: new Uint8Array(5) }, + ], { maxBytes: 10 }), /maxBytes/) +}) + +test('aborting cancels the active ReadableStream reader', async () => { + let cancelled = false + const stream = new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array(64 * 1024).fill(7)) + }, + cancel() { + cancelled = true + }, + }) + const controller = new AbortController() + let seen = 0 + await assert.rejects(async () => { + for await (const chunk of zipEntries([{ name: 'large.bin', data: stream }], { signal: controller.signal })) { + seen += 1 + if (seen === 2) controller.abort() + } + }, error => error.name === 'AbortError') + assert.ok(seen >= 2) + assert.equal(cancelled, true) +}) + +test('aborting closes the active async iterator', async () => { + let closed = false + const data = { + [Symbol.asyncIterator]() { + return { + async next() { + return { value: new Uint8Array(1024), done: false } + }, + async return() { + closed = true + return { done: true } + }, + } + }, + } + const controller = new AbortController() + let seen = 0 + await assert.rejects(async () => { + for await (const chunk of zipEntries([{ name: 'iter.bin', data }], { signal: controller.signal })) { + seen += 1 + if (seen === 2) controller.abort() + } + }, error => error.name === 'AbortError') + assert.equal(closed, true) +}) diff --git a/plugins/deepseek-harness/test/cancellation.test.js b/plugins/deepseek-harness/test/cancellation.test.js new file mode 100644 index 000000000..765c65303 --- /dev/null +++ b/plugins/deepseek-harness/test/cancellation.test.js @@ -0,0 +1,91 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { randomUUID } from 'node:crypto' +import { apply } from '../index.js' +import { OpenDirectorClient } from '../src/client.js' +import { uuid5 } from '../src/operations.js' + +test('explicit stop reads the current revision, recovers a lost receipt and preserves provider confirmation', async t => { + const [projectId, jobId, operationId] = Array.from({ length: 3 }, randomUUID) + const job = { id: jobId, revision: 7, status: 'running', cancelRequested: false, remoteCancellation: 'not_requested' } + const snapshot = { project: { id: projectId, name: 'Studio' }, jobs: [job] } + const root = '/api/creation/projects/' + projectId + const receipts = new Map() + const commands = [] + let blocked = false + let receiptUnavailable = false + const server = createServer(async (request, response) => { + assert.equal(request.headers['x-opendirector-request'], '1') + const reply = (status, value) => response.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify(value)) + if (request.url === root + '/open') return blocked ? reply(409, { code: 'storage_busy' }) : reply(200, snapshot) + if (request.method === 'DELETE') return reply(200, {}) + if (request.url.startsWith(root + '/receipts/')) { + if (receiptUnavailable) return reply(503, {}) + const receipt = receipts.get(request.url.split('/').at(-1)) + return reply(receipt ? 200 : 404, receipt ?? {}) + } + if (request.url === root + '/queries') return reply(200, job) + if (request.url === root + '/commands') { + let body = '' + for await (const chunk of request) body += chunk + const command = JSON.parse(body) + commands.push(command) + job.cancelRequested = true + job.remoteCancellation = 'unknown' + job.status = 'cancelled' + job.revision += 1 + receipts.set(command.commandId, { status: 'applied' }) + request.socket.destroy() + return + } + reply(404, {}) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => { server.closeAllConnections(); server.close() }) + const baseUrl = 'http://127.0.0.1:' + server.address().port + const routes = new Map() + apply({ + tools: { register() {} }, get() { return undefined }, + inject(_services, configure) { + configure({ + effect(register) { register() }, + connection: { fetch: { register(route) { routes.set(route.path, route) } } }, + }) + }, + }, { baseUrl }) + const route = routes.get('/api/opendirector/cancel') + const input = { projectId, jobId, operationId } + const request = (body, headers = { 'X-OpenDirector-Action': '1' }) => new Request('http://dsh.local/api/opendirector/cancel', { + method: 'POST', headers, body: typeof body === 'string' ? body : JSON.stringify(body), + }) + assert.equal((await route.fetch(request(input, {}))).status, 403) + assert.equal((await route.fetch(request(input, { 'X-OpenDirector-Action': '1', 'Sec-Fetch-Site': 'cross-site' }))).status, 403) + assert.equal((await route.fetch(request('{'))).status, 400) + assert.deepEqual(await (await route.fetch(request(input))).json(), { status: 'unknown' }) + assert.equal(commands.length, 1) + assert.equal(commands[0].type, 'job.cancel') + assert.equal(commands[0].commandId, uuid5(operationId, 'job.cancel:' + projectId + ':' + jobId)) + assert.deepEqual(commands[0].expectedVersions, [{ objectType: 'job', id: jobId, revision: 7 }]) + receiptUnavailable = true + assert.deepEqual(await (await route.fetch(request({ ...input, check: true }))).json(), { status: 'unknown' }) + receiptUnavailable = false + assert.deepEqual(await (await route.fetch(request({ ...input, check: true }))).json(), { status: 'applied' }) + const client = new OpenDirectorClient({ baseUrl, requestTimeoutMs: 1000 }) + assert.deepEqual(await client.cancelCreation(input), { status: 'applied' }) + assert.equal(commands.length, 1) + for (const remoteCancellation of ['requested', 'unknown', 'confirmed']) { + job.remoteCancellation = remoteCancellation + assert.deepEqual(await client.creationStatus(projectId, jobId), { + status: 'cancelled', cancelRequested: true, remoteCancellation, category: undefined, + }) + } + job.cancelRequested = false + job.status = 'succeeded' + assert.deepEqual(await client.cancelCreation({ ...input, operationId: randomUUID() }), { status: 'noop' }) + assert.equal(commands.length, 1) + blocked = true + assert.deepEqual(await (await route.fetch(request({ ...input, operationId: randomUUID() }))).json(), + { status: 'rejected', code: 'storage_busy' }) + assert.equal(commands.length, 1) +}) diff --git a/plugins/deepseek-harness/test/candidate-groups.test.js b/plugins/deepseek-harness/test/candidate-groups.test.js new file mode 100644 index 000000000..d8fde28b4 --- /dev/null +++ b/plugins/deepseek-harness/test/candidate-groups.test.js @@ -0,0 +1,124 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import test from 'node:test' +import { OpenDirectorClient } from '../src/client.js' +import { uuid5 } from '../src/operations.js' + +function fixture(loss) { + const projectId = randomUUID(), modelConfigId = randomUUID() + const snapshot = { project: { id: projectId }, generationSpecs: [], canvasItems: [], jobs: [], results: [], assets: [] } + const receipts = new Map(), commands = [], reads = [] + let submits = 0 + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + reads.push(path) + if (path === '/api/model-configs') return Response.json([{ + id: modelConfigId, kind: 'image', modelId: 'fixture', protocol: 'openai', + inputRules: { allowedKinds: ['image'], maxImages: 2, imageOutputs: [{ size: '1024x1024', aspectRatio: '1:1' }] }, + }]) + if (path.endsWith('/open') || (request.method === 'GET' && path.endsWith('/' + projectId))) return Response.json(snapshot) + if (request.method === 'DELETE') return Response.json({}) + if (path.includes('/receipts/')) { + const receipt = receipts.get(path.split('/').at(-1)) + return Response.json(receipt ?? {}, { status: receipt ? 200 : 404 }) + } + assert.ok(path.endsWith('/commands'), path) + const command = JSON.parse(request.body) + commands.push(command) + if (command.type === 'canvas.createGeneration') { + const { spec, item } = command.payload + snapshot.generationSpecs.push({ ...spec, revision: 1, currentResultId: null }) + snapshot.canvasItems.push({ ...item, revision: 1 }) + const receipt = { status: 'applied', changed: [{ id: spec.id, revision: 1 }, { id: item.id, revision: 1 }] } + receipts.set(command.commandId, receipt) + return Response.json(receipt) + } + submits++ + if (submits === 2 && loss === 'before') throw new Error('Connection lost before acceptance') + const spec = snapshot.generationSpecs.find(spec => spec.id === command.payload.specId) + const id = uuid5(command.commandId, 'job') + snapshot.jobs.push({ id, revision: 1, status: 'queued', batchId: command.payload.batchId, + originItemId: command.payload.originItemId, inputSnapshot: { spec: structuredClone(spec) } }) + const receipt = { status: 'accepted', jobIds: [id] } + receipts.set(command.commandId, receipt) + if (submits === 2 && loss === 'after') throw new Error('Acceptance reply lost') + return Response.json(receipt) + }, + }) + const input = { projectId, operationId: randomUUID(), kind: 'image', modelConfigId, prompt: 'A quiet studio', candidateCount: 3 } + return { client, input, snapshot, commands, reads } +} + +for (const loss of ['before', 'after']) { + test('a candidate group reconciles a lost ' + loss + '-acceptance reply and explicitly continues original operations', async () => { + const { client, input, snapshot, commands, reads } = fixture(loss) + const first = await client.startCreation(input) + assert.equal(first.status, 'unknown') + assert.equal(snapshot.jobs.length, loss === 'before' ? 1 : 2) + const writes = commands.length + const beforeRead = reads.length + const checked = await client.startCreation({ + projectId: input.projectId, operationId: input.operationId, candidateCount: 3, check: true, + }) + assert.equal(checked.status, 'unknown') + assert.equal(checked.canContinueGroup, true) + assert.equal(commands.length, writes) + assert.ok(reads.slice(beforeRead).every(path => path.includes('/receipts/'))) + const complete = await client.startCreation({ + projectId: input.projectId, operationId: input.operationId, candidateCount: 3, continueGroup: true, + }) + assert.equal(complete.status, 'accepted') + assert.equal(complete.groupComplete, true) + assert.equal(complete.acceptedCount, 3) + assert.equal(new Set(snapshot.jobs.map(job => job.id)).size, 3) + assert.equal(snapshot.canvasItems.length, 1) + assert.equal(snapshot.generationSpecs.length, 1) + assert.equal(snapshot.generationSpecs[0].currentResultId, null) + const submits = commands.filter(command => command.type === 'generation.submit') + assert.equal(new Set(submits.map(command => command.commandId)).size, 3) + for (const command of submits) { + assert.equal(command.payload.batchId, input.operationId) + assert.equal(command.payload.adoptionPolicy, 'candidate_only') + assert.equal(command.payload.expectedSpecRevision, 1) + } + const beforeReplay = commands.length + const replay = await client.startCreation(input) + assert.equal(replay.acceptedCount, 3) + assert.equal(commands.length, beforeReplay) + // Progress comes from current saved jobs; a failed member does not conceal successful siblings. + snapshot.jobs.forEach((job, index) => { + job.status = index === 1 ? 'failed' : 'succeeded' + job.errorDetails = index === 1 ? { category: 'quota' } : undefined + if (job.status === 'succeeded') snapshot.results.push({ + id: randomUUID(), jobId: job.id, specId: snapshot.generationSpecs[0].id, + asset: { assetId: randomUUID(), kind: 'image' }, + }) + }) + const status = await client.creationGroupStatus(input.projectId, input.operationId) + assert.equal(status.completedCount, 2) + assert.equal(status.failedCount, 1) + assert.equal(status.totalCount, 3) + assert.equal(status.jobs[1].category, 'quota') + assert.equal(status.results.length, 2) + assert.equal(status.results.every(result => !result.selected), true) + assert.equal(commands.length, beforeReplay) + }) +} + +test('candidate groups bound task count and stop when the source settings change before continuation', async () => { + const { client, input, snapshot, commands } = fixture('before') + for (const candidateCount of [0, 5, 2.5, '3']) { + await assert.rejects(client.startCreation({ ...input, candidateCount }), { key: 'creation.candidate_count' }) + } + assert.equal(commands.length, 0) + await client.startCreation(input) + snapshot.generationSpecs[0].revision++ + snapshot.generationSpecs[0].prompt = 'Changed in the canvas' + const reply = await client.startCreation({ + projectId: input.projectId, operationId: input.operationId, candidateCount: 3, continueGroup: true, + }) + assert.equal(reply.status, 'rejected') + assert.equal(reply.code, 'revision_conflict') + assert.equal(snapshot.jobs.length, 1) +}) diff --git a/plugins/deepseek-harness/test/connection.test.js b/plugins/deepseek-harness/test/connection.test.js new file mode 100644 index 000000000..bb7e67c42 --- /dev/null +++ b/plugins/deepseek-harness/test/connection.test.js @@ -0,0 +1,97 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { apply } from '../index.js' +import manifest from '../package.json' with { type: 'json' } +import { connectionStatus } from '../src/connection.js' +import { NetworkError, RequestTimeoutError } from '../src/errors.js' + +test('connection route reads counts and capabilities without exposing model or project data', async () => { + let mode = 'ready' + const calls = [] + const secret = 'private-provider-key-and-project-name' + const server = createServer((request, response) => { + calls.push([request.method, request.url]) + response.setHeader('Content-Type', 'application/json') + if (request.url === '/api/creation/projects') { + response.end(JSON.stringify({ projects: [{ id: 'private-id', name: secret }] })) + } else if (request.url === '/api/model-configs') { + if (mode === 'denied') { + response.writeHead(403).end(JSON.stringify({ detail: secret })) + } else if (mode === 'malformed') { + response.end(JSON.stringify({ detail: secret })) + } else { + response.end(JSON.stringify(mode === 'empty' ? [] : [ + { id: secret, kind: 'image', modelId: secret, apiKey: secret, inputRules: { allowedKinds: ['image'], maxImages: 2 } }, + { kind: 'video', apiKey: secret, inputRules: { allowedKinds: ['image'], maxImages: 1, + videoModes: ['first_frame', 'continuation'], videoCapabilities: { outputs: [] } } }, + { kind: 'audio', apiKey: secret, protocol: 'minimax_speech' }, + { kind: 'audio', apiKey: secret, protocol: 'vllm_omni_music' }, + ])) + } + } else response.writeHead(404).end() + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + try { + let route + const baseUrl = 'http://127.0.0.1:' + server.address().port + apply({ + tools: { register() {} }, get() {}, + inject(_services, configure) { + configure({ effect(register) { register() }, connection: { fetch: { register(value) { + if (value.path === '/api/opendirector/connection') route = value + } } } }) + }, + }, { baseUrl, canvasBaseUrl: 'http://localhost:5173', requestTimeoutMs: 700 }) + assert.deepEqual(route.methods, ['GET']) + const check = () => route.fetch(new Request('http://localhost/api/opendirector/connection')) + let response = await check() + assert.equal(response.headers.get('cache-control'), 'private, no-store') + let value = await response.json() + assert.equal(value.apiUrl, baseUrl) + assert.equal(value.canvasUrl, 'http://localhost:5173') + assert.equal(value.version, manifest.version) + assert.deepEqual(value.projects, { status: 'ok', count: 1 }) + assert.deepEqual(value.models, { status: 'ok', count: 3, capabilities: { + image: 1, imageEdit: 1, imageToVideo: 1, videoContinuation: 1, voiceover: 1, + } }) + assert.ok(!JSON.stringify(value).includes(secret)) + + mode = 'empty' + value = await (await check()).json() + assert.equal(value.models.status, 'ok') + assert.equal(value.models.count, 0) + assert.ok(Object.values(value.models.capabilities).every(count => count === 0)) + + mode = 'denied' + value = await (await check()).json() + assert.deepEqual(value.projects, { status: 'ok', count: 1 }) + assert.deepEqual(value.models, { status: 'access' }) + assert.ok(!JSON.stringify(value).includes(secret)) + + mode = 'malformed' + value = await (await check()).json() + assert.deepEqual(value.models, { status: 'response' }) + assert.ok(calls.every(([method, path]) => method === 'GET' + && ['/api/creation/projects', '/api/model-configs'].includes(path))) + assert.equal(calls.length, 8) + } finally { + server.closeAllConnections() + await new Promise(resolve => server.close(resolve)) + } +}) + +test('connection check distinguishes service timeout, network failure and caller cancellation', async () => { + const controller = new AbortController() + const client = { + async listProjects({ signal }) { assert.equal(signal, controller.signal); throw new RequestTimeoutError(5000) }, + async creationModels({ signal }) { assert.equal(signal, controller.signal); throw new NetworkError('private-url', new Error('private-details')) }, + } + const config = { baseUrl: 'http://localhost:8000', canvasBaseUrl: 'http://localhost:5173' } + const report = await connectionStatus(client, config, '0.1.0', { signal: controller.signal }) + assert.deepEqual(report.projects, { status: 'timeout' }) + assert.deepEqual(report.models, { status: 'network' }) + assert.ok(!JSON.stringify(report).includes('private-')) + controller.abort(new Error('closed')) + await assert.rejects(connectionStatus(client, config, '0.1.0', { signal: controller.signal }), /closed/) +}) diff --git a/plugins/deepseek-harness/test/creation-controls.test.js b/plugins/deepseek-harness/test/creation-controls.test.js new file mode 100644 index 000000000..68aad45e1 --- /dev/null +++ b/plugins/deepseek-harness/test/creation-controls.test.js @@ -0,0 +1,264 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import test from 'node:test' +import { OpenDirectorClient } from '../src/client.js' +import { uuid5 } from '../src/operations.js' + +test('a direct edit pins saved assets in order and recovers the original submission', async () => { + const [projectId, operationId, sourceResultId, assetId, modelConfigId, jobId, priorItemId, extraResult, extraAsset] = + Array.from({ length: 9 }, () => randomUUID()) + const commands = [] + const requests = [] + const receipts = new Map() + const snapshot = { + project: { id: projectId }, + generationSpecs: [], + canvasItems: [{ id: priorItemId, parentId: null, position: { x: 40, y: 0 }, width: 352 }], + results: [ + { id: extraResult, asset: { assetId: extraAsset, kind: 'image', revision: 1, fingerprint: 'b'.repeat(64) } }, + { id: sourceResultId, asset: { assetId, kind: 'image', revision: 1, fingerprint: 'a'.repeat(64) } }, + ], + } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + requests.push(path) + if (path === '/api/model-configs') { + return Response.json([{ + id: modelConfigId, kind: 'image', protocol: 'openai', modelId: 'fixture', + inputRules: { allowedKinds: ['image'], maxImages: 2, imageOutputs: [{ size: '1024x1024', aspectRatio: '1:1' }] }, + }]) + } + if (path.endsWith('/open')) return Response.json(snapshot) + if (request.method === 'DELETE') return Response.json({}) + if (path.includes('/receipts/')) { + const value = receipts.get(path.split('/').at(-1)) + return Response.json(value ?? {}, { status: value ? 200 : 404 }) + } + assert.ok(path.endsWith('/commands')) + const command = JSON.parse(request.body) + commands.push(command) + if (command.type === 'canvas.createGeneration') { + const { spec, item } = command.payload + snapshot.generationSpecs.push({ ...spec, revision: 1 }) + const receipt = { status: 'applied', changed: [{ id: spec.id, revision: 1 }, { id: item.id, revision: 1 }] } + receipts.set(command.commandId, receipt) + return Response.json(receipt) + } + receipts.set(command.commandId, { status: 'accepted', jobIds: [jobId] }) + throw new Error('submission response lost') + }, + }) + const input = { + projectId, operationId, sourceResultIds: [sourceResultId, extraResult], kind: 'image', modelConfigId, prompt: 'Add a lamp', + output: { size: '1024x1024', aspectRatio: '1:1' }, + } + await assert.rejects(client.startCreation({ ...input, output: { size: '2048x2048', aspectRatio: '1:1' } }), + { name: 'InputError', key: 'creation.output' }) + await assert.rejects(client.startCreation({ ...input, sourceResultIds: [sourceResultId, extraResult, randomUUID()] }), + { name: 'InputError', key: 'creation.reference_limit' }) + await assert.rejects(client.startCreation({ ...input, sourceResultIds: [sourceResultId, sourceResultId] }), + { name: 'InputError', key: 'creation.references' }) + await assert.rejects(client.startCreation({ ...input, sourceResultIds: [sourceResultId, randomUUID()] }), + { name: 'InputError', key: 'result.candidate_missing' }) + assert.equal(commands.length, 0) + await assert.rejects(client.startCreation(input), { name: 'UnknownOperationError' }) + const [draft, submit] = commands + assert.deepEqual(draft.payload.references.map(reference => [reference.order, reference.binding, reference.source.assetId]), + [[0, 'pinned', assetId], [1, 'pinned', extraAsset]]) + assert.equal(draft.payload.item.position.x, 440) + assert.equal(submit.payload.adoptionPolicy, 'candidate_only') + assert.equal(submit.commandId, uuid5(operationId, 'creation.submit')) + const beforeCheck = requests.length + assert.deepEqual(await client.startCreation({ projectId, operationId, check: true }), + { status: 'accepted', jobId, code: undefined }) + assert.deepEqual(requests.slice(beforeCheck), + ['/api/creation/projects/' + projectId + '/receipts/' + submit.commandId]) + assert.deepEqual(await client.startCreation(input), { status: 'accepted', jobId, code: undefined }) + assert.equal(commands.length, 2) +}) + +test('direct video uses published durations and pins the exact source for each mode', async () => { + const [projectId, modelConfigId, imageId, videoId, imageAssetId, videoAssetId] = + Array.from({ length: 6 }, () => randomUUID()) + const commands = [] + const snapshot = { + generationSpecs: [], canvasItems: [], + results: [ + { id: imageId, asset: { assetId: imageAssetId, kind: 'image', revision: 1, fingerprint: 'a'.repeat(64) } }, + { id: videoId, asset: { assetId: videoAssetId, kind: 'video', revision: 1, fingerprint: 'b'.repeat(64) } }, + ], + } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + if (path === '/api/model-configs') return Response.json([{ + id: modelConfigId, kind: 'video', + inputRules: { allowedKinds: ['image', 'video'], maxImages: 1, videoModes: ['first_frame', 'continuation'], + videoCapabilities: { + defaultDuration: 5, defaultResolution: '768P', + outputs: [{ resolution: '480P', durations: [5, 6] }, { resolution: '768P', durations: [5, 7] }], + } }, + }]) + if (path.endsWith('/open')) return Response.json(snapshot) + if (request.method === 'DELETE') return Response.json({}) + assert.ok(path.endsWith('/commands')) + const command = JSON.parse(request.body) + commands.push(command) + if (command.type === 'generation.submit') return Response.json({ status: 'accepted', jobIds: [randomUUID()] }) + const { spec, item } = command.payload + return Response.json({ status: 'applied', changed: [{ id: spec.id, revision: 1 }, { id: item.id, revision: 1 }] }) + }, + }) + const first = { projectId, operationId: randomUUID(), kind: 'video', modelConfigId, prompt: 'Pan left', + sourceResultId: imageId, videoMode: 'first_frame', durationSeconds: 7 } + await assert.rejects(client.startCreation({ ...first, videoMode: 'reference' }), { key: 'creation.video_mode' }) + await assert.rejects(client.startCreation({ ...first, durationSeconds: 6 }), { key: 'creation.video_duration' }) + await assert.rejects(client.startCreation({ ...first, sourceResultId: videoId }), { key: 'creation.video_source' }) + assert.equal(commands.length, 0) + await client.startCreation(first) + await client.startCreation({ + ...first, operationId: randomUUID(), sourceResultId: videoId, videoMode: 'continuation', durationSeconds: 6, + }) + assert.deepEqual(commands.filter(command => command.type === 'canvas.createGeneration').map(({ payload }) => [ + payload.spec.parameters, payload.references.map(({ source, binding, role }) => [source.assetId, binding, role]), + ]), [ + [{ videoMode: 'first_frame', resolution: '768P', durationSeconds: 7 }, [[imageAssetId, 'pinned', 'first_frame']]], + [{ videoMode: 'continuation', resolution: 'auto', durationSeconds: 6 }, [[videoAssetId, 'pinned', 'continuation']]], + ]) + assert.deepEqual(commands.filter(command => command.type === 'generation.submit').map(({ payload }) => payload.adoptionPolicy), + ['candidate_only', 'candidate_only']) +}) + +test('another video candidate reuses the node and reconciles a lost response without another submit', async () => { + const [projectId, operationId, jobId, repeatId, specId, itemId, firstId, secondId, firstAsset, secondAsset] = + Array.from({ length: 10 }, () => randomUUID()) + const commands = [] + const prior = { id: jobId, inputSnapshot: { spec: { id: specId } }, originItemId: itemId, status: 'succeeded' } + const jobs = [prior] + const snapshot = { + jobs, + assets: [{ id: firstAsset, metadata: { width: 512, height: 512 } }], + generationSpecs: [{ id: specId, revision: 3, kind: 'video', currentResultId: firstId }], + canvasItems: [{ id: itemId, revision: 2, binding: { objectRef: { id: specId } } }], + results: [{ id: firstId, specId, jobId, asset: { assetId: firstAsset, kind: 'video' } }], + } + let receipt + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + if (path.endsWith('/open')) return Response.json(snapshot) + if (path.endsWith('/queries')) return Response.json(jobs.at(-1)) + if (request.method === 'DELETE') return Response.json({}) + if (path.endsWith('/receipts/' + uuid5(operationId, 'creation.submit'))) { + return Response.json(receipt ?? {}, { status: receipt ? 200 : 404 }) + } + if (request.method === 'GET' && path.endsWith('/' + projectId)) return Response.json(snapshot) + assert.ok(path.endsWith('/commands')) + commands.push(JSON.parse(request.body)) + jobs.push({ ...prior, id: repeatId }) + snapshot.results.push({ id: secondId, specId, jobId: repeatId, asset: { assetId: secondAsset, kind: 'video' } }) + receipt = { status: 'accepted', jobIds: [repeatId] } + throw new Error('submission response lost') + }, + }) + const input = { projectId, operationId, repeatJobId: jobId } + assert.deepEqual(await client.startCreation({ ...input, check: true }), { status: 'unknown' }) + await assert.rejects(client.startCreation(input), { name: 'UnknownOperationError' }) + assert.deepEqual(await client.startCreation({ ...input, check: true }), { status: 'accepted', jobId: repeatId, code: undefined }) + assert.deepEqual(await client.startCreation(input), { status: 'accepted', jobId: repeatId, code: undefined }) + const [submit] = commands + assert.equal(commands.length, 1) + assert.equal(submit.type, 'generation.submit') + assert.equal(submit.payload.adoptionPolicy, 'candidate_only') + assert.equal(submit.payload.specId, specId) + assert.deepEqual(submit.expectedVersions.map(item => [item.id, item.revision]), [[specId, 3], [itemId, 2]]) + assert.deepEqual(await client.creationStatus(projectId, repeatId), { + status: 'succeeded', + results: [ + { resultId: firstId, assetId: firstAsset, kind: 'video', selected: true, version: 1, details: { width: 512, height: 512 } }, + { resultId: secondId, assetId: secondAsset, kind: 'video', selected: false, version: 2 }, + ], + }) +}) + +test('only a confirmed failed job can start a linked retry on the same node', async () => { + const [projectId, specId, itemId, jobId, uncertainId, reviewId, nextId] = Array.from({ length: 7 }, randomUUID) + const quota = { + id: jobId, inputSnapshot: { spec: { id: specId } }, originItemId: itemId, status: 'failed', + errorDetails: { category: 'quota' }, recovery: 'retry', + } + const jobs = [ + quota, + { ...quota, id: uncertainId, errorDetails: { category: 'submission_unknown' } }, + { ...quota, id: reviewId, recovery: 'review' }, + ] + const snapshot = { + jobs, + generationSpecs: [{ id: specId, revision: 3, kind: 'image' }], + canvasItems: [{ id: itemId, revision: 2, binding: { objectRef: { id: specId } } }], + } + const commands = [] + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + if (path.endsWith('/queries')) { + return Response.json(jobs.find(job => job.id === JSON.parse(request.body).objectId)) + } + if (path.endsWith('/open')) return Response.json(snapshot) + if (request.method === 'DELETE') return Response.json({}) + if (path.includes('/receipts/')) return Response.json({}, { status: 404 }) + assert.ok(path.endsWith('/commands')) + commands.push(JSON.parse(request.body)) + return Response.json({ status: 'accepted', jobIds: [nextId] }) + }, + }) + assert.deepEqual(await client.creationStatus(projectId, jobId), { status: 'failed', category: 'quota', canRetry: true }) + assert.deepEqual(await client.creationStatus(projectId, uncertainId), { status: 'failed', category: 'submission_unknown' }) + assert.deepEqual(await client.creationStatus(projectId, reviewId), { status: 'failed', category: 'quota' }) + const repeat = repeatJobId => client.startCreation({ projectId, operationId: randomUUID(), repeatJobId }) + await assert.rejects(repeat(uncertainId), { name: 'InputError', key: 'creation.repeat_unavailable' }) + await assert.rejects(repeat(reviewId), { name: 'InputError', key: 'creation.repeat_unavailable' }) + assert.equal(commands.length, 0) + assert.equal((await repeat(jobId)).jobId, nextId) + const [command] = commands + assert.equal(commands.length, 1) + assert.equal(command.type, 'generation.submit') + assert.equal(command.payload.specId, specId) + assert.equal(command.payload.originItemId, itemId) + assert.equal(command.payload.previousJobId, jobId) + assert.equal(command.payload.adoptionPolicy, 'candidate_only') +}) + +test('known rejections keep a newly created project and any saved draft identifiable', async () => { + const [projectId, modelConfigId, operationId] = Array.from({ length: 3 }, () => randomUUID()) + let busy = true + const commands = [] + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + if (path === '/api/model-configs') return Response.json([{ id: modelConfigId, kind: 'image', protocol: 'openai' }]) + if (path.endsWith('/open')) return busy + ? Response.json({ code: 'storage_busy' }, { status: 409 }) + : Response.json({ generationSpecs: [], canvasItems: [], results: [] }) + if (request.method === 'DELETE') return Response.json({}) + assert.ok(path.endsWith('/commands')) + const command = JSON.parse(request.body) + commands.push(command.type) + if (command.type === 'project.create') return Response.json({ status: 'applied' }) + if (command.type === 'canvas.createGeneration') return Response.json({ + status: 'applied', changed: [command.payload.spec.id, command.payload.item.id].map(id => ({ id, revision: 1 })), + }) + return Response.json({ code: 'revision_conflict' }, { status: 409 }) + }, + }) + const input = { projectId, modelConfigId, operationId, kind: 'image', prompt: 'Studio' } + assert.deepEqual(await client.startCreation({ ...input, projectName: 'Studio' }), { + status: 'rejected', code: 'storage_busy', projectCreated: true, + }) + busy = false + assert.deepEqual(await client.startCreation({ ...input, operationId: randomUUID() }), { + status: 'rejected', code: 'revision_conflict', draftSaved: true, + }) + assert.deepEqual(commands, ['project.create', 'canvas.createGeneration', 'generation.submit']) +}) diff --git a/plugins/deepseek-harness/test/creation.integration.mjs b/plugins/deepseek-harness/test/creation.integration.mjs index f5341e92b..8fbf5c712 100644 --- a/plugins/deepseek-harness/test/creation.integration.mjs +++ b/plugins/deepseek-harness/test/creation.integration.mjs @@ -9,7 +9,7 @@ import ToolRuntime from '@deepseek-ai/dsh-tools'; import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native'; const base = (process.env.OPENDIRECTOR_FIXTURE_URL ?? 'http://127.0.0.1:8019').replace(/\/+$/, ''); -const evidence = { backend: 'real OpenDirector application + isolated image provider fixture', host: 'published DSH 0.2.2-rc.1 Cordis Loader + Tools + Native executor', model: 'fixture only; no real model service', checks: [] }; +const evidence = { backend: 'real OpenDirector application + isolated image provider fixture', host: 'DSH Cordis Loader + Tools + Native executor', model: 'fixture only; no real model service', checks: [] }; const ctx = new Context(); ctx.baseUrl = pathToFileURL(process.cwd() + '/').href; const headers = { 'X-OpenDirector-Request': '1', 'Content-Type': 'application/json' }; @@ -64,8 +64,10 @@ try { await ctx.loader.await(); const entry = [...ctx.loader.entries()].find(value => value.options.id === 'opendirector'); assert.ok(entry); - assert.equal(ctx.tools.schemas().filter(tool => tool.name.startsWith('opendirector_')).length, 8); - evidence.checks.push('real Cordis Loader registered 8 native tools'); + const toolNames = () => ctx.tools.schemas().map(tool => tool.name).filter(name => name.startsWith('opendirector_')).sort(); + const registeredTools = toolNames(); + assert.ok(registeredTools.includes('opendirector_results')); + evidence.checks.push(`real Cordis Loader registered ${registeredTools.length} native tools`); const projectId = randomUUID(); const name = `DSH 148 isolated project ${projectId.slice(0, 8)}`; const created = await call('opendirector_projects', { action: 'create', name, projectId, operationId: randomUUID() }); @@ -96,6 +98,9 @@ try { assert.equal(adopted.receipt.status, 'applied'); const afterAdopt = await call('opendirector_project', { projectId }); assert.equal(afterAdopt.snapshot.generationSpecs.find(value => value.id === node.specId).currentResultId, result.id); + const shown = await call('opendirector_results', { action: 'show', projectId, resultIds: [result.id] }); + assert.equal(shown.results[0].assetId, result.asset.assetId); + assert.equal(shown.results[0].selected, true); const adoptReplay = await call('opendirector_adopt_result', adoptArgs); assert.equal(adoptReplay.receipt.inputFingerprint, adopted.receipt.inputFingerprint); evidence.checks.push('project -> editable generation -> accepted job -> registered real PNG candidate -> explicit adoption -> replay'); @@ -112,7 +117,7 @@ try { await entry.update({ disabled: true }); await ctx.loader.await(); assert.ok(entry); - assert.equal(ctx.tools.schemas().filter(tool => tool.name.startsWith('opendirector_')).length, 0); + assert.deepEqual(toolNames(), []); await api('POST', '/api/creation-test-gate', { open: true }); const whileDisabled = await waitForJob(projectId, pending.jobIds[0], false); assert.equal(whileDisabled.job.status, 'succeeded'); @@ -120,7 +125,7 @@ try { await entry.update({ disabled: false }); await ctx.loader.await(); assert.ok(entry); - assert.equal(ctx.tools.schemas().filter(tool => tool.name.startsWith('opendirector_')).length, 8); + assert.deepEqual(toolNames(), registeredTools); const resumed = await call('opendirector_job', { projectId, jobId: pending.jobIds[0] }); assert.equal(resumed.job.status, 'succeeded'); evidence.checks.push('real loader disable unregisters tools; accepted OD job completes; enable restores persisted result query'); diff --git a/plugins/deepseek-harness/test/host.test.js b/plugins/deepseek-harness/test/host.test.js index 264062546..ad1fdddbe 100644 --- a/plugins/deepseek-harness/test/host.test.js +++ b/plugins/deepseek-harness/test/host.test.js @@ -17,10 +17,11 @@ test('real DSH Loader and Native executor preserve nullable backend facts, local const specId = randomUUID() const asset = { assetId: randomUUID(), revision: 1, fingerprint: `sha256:${'a'.repeat(64)}`, kind: 'image' } const snapshot = { - project: { id: projectId, revision: 1, name: 'Studio' }, + project: { id: projectId, revision: 1, name: 'Studio' }, canvasItems: [], references: [], generationSpecs: [{ id: specId, currentResultId: null }], + assets: [{ id: asset.assetId, metadata: { width: 512, height: 512 } }], jobs: [{ id: jobId, revision: 3, status: 'succeeded', originItemId: null, errorDetails: null, - cancelRequested: false, remoteCancellation: 'not_requested' }], + cancelRequested: false, remoteCancellation: 'not_requested', execution: { kind: 'image' } }], results: [{ id: resultId, specId, jobId, asset }], } const server = createServer((request, response) => { @@ -45,7 +46,10 @@ test('real DSH Loader and Native executor preserve nullable backend facts, local const entry = [...ctx.loader.entries()].find(value => value.options.id === 'opendirector') assert.ok(entry) const names = () => ctx.tools.schemas().filter(tool => tool.name.startsWith('opendirector_')) - assert.equal(names().length, 8) + assert.equal(names().length, 10) + const actionPack = names().find(tool => tool.name === 'opendirector_action_pack').parameters + assert.deepEqual(actionPack.required, ['projectId', 'action']) + assert.deepEqual(actionPack.properties.actions.items.required, ['name', 'prompt']) const generation = names().find(tool => tool.name === 'opendirector_create_generation').parameters assert.deepEqual(generation.required, ['projectId', 'operationId', 'kind', 'modelConfigId', 'prompt', 'parameters', 'position']) assert.deepEqual(generation.properties.position.required, ['x', 'y']) @@ -55,18 +59,40 @@ test('real DSH Loader and Native executor preserve nullable backend facts, local const definition = ctx.tools.definitions().find(tool => tool.name === 'opendirector_create_generation') assert.deepEqual(definition.output.schema.required, ['projectId', 'canvasUrl', 'operationId', 'receipt', 'specId', 'itemId', 'referenceIds']) - async function readJob() { + async function runTool(name, args) { const batch = await ctx.tools.execute({ - calls: [{ type: 'tool-call', id: randomUUID(), name: 'opendirector_job', arguments: JSON.stringify({ projectId, jobId }) }], + calls: [{ type: 'tool-call', id: randomUUID(), name, arguments: JSON.stringify(args) }], signal: new AbortController().signal, }) const result = batch.results[0].result assert.equal(result.isError, false, JSON.stringify(result)) return result } + const readJob = () => runTool('opendirector_job', { projectId, jobId }) + const packRead = await ctx.tools.execute({ + calls: [{ type: 'tool-call', id: randomUUID(), name: 'opendirector_action_pack', + arguments: JSON.stringify({ projectId, action: 'list' }) }], signal: new AbortController().signal, + }) + assert.equal(packRead.results[0].result.isError, false) + assert.deepEqual(packRead.results[0].result.value.packs, []) + const savedSchema = names().find(tool => tool.name === 'opendirector_results').parameters + assert.deepEqual(savedSchema.required, ['projectId', 'action']) + const lookup = (action, fields = {}) => runTool('opendirector_results', { projectId, action, ...fields }) + const found = await lookup('find', { kind: 'image' }) + assert.equal(found.value.results[0].resultId, resultId) + assert.equal(found.meta.savedResults, undefined) + assert.doesNotMatch(found.content[0].text, /"generationSpecs"|"jobs"/) + const shown = await lookup('show', { resultIds: [resultId] }) + assert.equal(shown.meta.savedResults.results[0].assetId, asset.assetId) + assert.equal(shown.meta.savedResults.results[0].selected, false) + const draft = await lookup('draft', { resultIds: [resultId], editPrompt: 'Keep the coast. Add a red scarf.' }) + assert.equal(draft.meta.editDraft.source.resultId, resultId) + assert.equal(draft.meta.editDraft.prompt, 'Keep the coast. Add a red scarf.') + assert.equal(draft.meta.savedResults, undefined) const english = await readJob() assert.equal(english.value.job.originItemId, null) assert.equal(english.value.job.errorDetails, null) + assert.deepEqual(english.meta.mediaPreview.candidates[0].details, { width: 512, height: 512 }) assert.match(english.content[0].text, /Candidate saved in this project/) assert.match(english.content[0].text, /^revision: 3$/m) assert.match(english.content[0].text, /cancelRequested: false/) @@ -79,7 +105,7 @@ test('real DSH Loader and Native executor preserve nullable backend facts, local assert.equal(names().length, 0) await entry.update({ config: { baseUrl, locale: 'zh-CN' }, disabled: false }) await ctx.loader.await() - assert.equal(names().length, 8) + assert.equal(names().length, 10) const chinese = await readJob() assert.match(chinese.content[0].text, /候选已保存到此工程/) assert.doesNotMatch(chinese.content[0].text, /Candidate saved|Status:|Project:/) diff --git a/plugins/deepseek-harness/test/library-route.test.js b/plugins/deepseek-harness/test/library-route.test.js new file mode 100644 index 000000000..86158c48c --- /dev/null +++ b/plugins/deepseek-harness/test/library-route.test.js @@ -0,0 +1,283 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { randomUUID } from 'node:crypto' +import { apply } from '../index.js' +import { OpenDirectorClient } from '../src/client.js' + +test('browse saved results without a lease and adopt with a recoverable receipt', async t => { + const [project, spec, item, original, candidate, audio, originalAsset, candidateAsset, job, operationId] = + Array.from({ length: 10 }, randomUUID) + const snapshot = { + project: { id: project, name: 'Studio' }, + generationSpecs: [{ id: spec, revision: 4, currentResultId: original }], + canvasItems: [{ id: item, revision: 7, binding: { role: 'generation', objectRef: { id: spec } } }], + jobs: [{ id: job, status: 'running', inputSnapshot: { + spec: { kind: 'image', prompt: 'Add a lamp' }, model: { modelId: 'image-01', url: 'http://private-model' }, + } }], + assets: [{ id: audio, metadata: { durationSeconds: 4.92 } }, { id: candidateAsset, metadata: { width: 512, height: 512 } }], + results: [ + { id: original, specId: spec, asset: { kind: 'image', assetId: originalAsset } }, + { id: candidate, specId: spec, jobId: job, asset: { kind: 'image', assetId: candidateAsset } }, + { id: audio, asset: { kind: 'audio', assetId: audio } }, + ], + } + const calls = [] + const path = '/api/creation/projects/' + project + let blocked = true + let receiptUnavailable = true + let command + const server = createServer(async (request, response) => { + calls.push([request.method, request.url]) + function reply(status, value) { + response.writeHead(status, { 'Content-Type': 'application/json' }).end(JSON.stringify(value)) + } + if (request.url === path) return reply(200, snapshot) + if (request.url === '/api/creation/projects') return reply(200, { projects: [snapshot.project] }) + if (request.url === path + '/open') { + return blocked ? reply(409, { code: 'storage_busy' }) : reply(200, snapshot) + } + if (request.url === path + '/commands') { + let body = '' + for await (const chunk of request) body += chunk + command = JSON.parse(body) + snapshot.generationSpecs[0].currentResultId = candidate + // The command commits, but the response is lost. + request.socket.destroy() + return + } + if (command && request.url === path + '/receipts/' + command.commandId) { + return receiptUnavailable ? reply(503, {}) : reply(200, { status: 'applied' }) + } + if (request.method === 'DELETE') return reply(200, {}) + reply(404, {}) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => { + server.closeAllConnections() + return new Promise(resolve => server.close(resolve)) + }) + + const routes = new Map() + apply({ + tools: { register() {} }, + get() {}, + inject(_services, configure) { + configure({ + effect(register) { register() }, + connection: { fetch: { register(value) { routes.set(value.path, value.fetch) } } }, + }) + }, + }, { baseUrl: 'http://127.0.0.1:' + server.address().port }) + const library = routes.get('/api/opendirector/library') + const projects = await library({ url: '/api/opendirector/library' }) + assert.deepEqual(await projects.json(), { projects: [snapshot.project], scope: 'http://127.0.0.1:' + server.address().port }) + const recent = await library({ url: '/api/opendirector/library?project=' + project }) + const { results } = await recent.json() + assert.deepEqual(results.map(result => [result.resultId, result.selected, result.prompt]), [ + [audio, false, ''], + [candidate, false, 'Add a lamp'], + [original, true, ''], + ]) + assert.deepEqual(results.map(result => result.details), [{ durationSeconds: 4.92 }, { width: 512, height: 512 }, undefined]) + assert.deepEqual(calls, [['GET', '/api/creation/projects'], ['GET', path]]) + const current = await library({ url: '/api/opendirector/library?' + new URLSearchParams({ + project, kind: 'image', selection: 'current', order: 'oldest', + }) }) + assert.deepEqual((await current.json()).results.map(item => item.resultId), [original]) + assert.equal((await library({ url: '/api/opendirector/library?' + new URLSearchParams({ + project, after: randomUUID(), + }) })).status, 409) + const tasks = await library({ url: '/api/opendirector/library?' + new URLSearchParams({ project, view: 'jobs' }) }) + assert.deepEqual((await tasks.json()).jobs, [{ + jobId: job, kind: 'image', status: 'running', prompt: 'Add a lamp', modelId: 'image-01', + }]) + + const adopt = routes.get('/api/opendirector/adopt') + const request = (input, headers = { 'X-OpenDirector-Action': '1', 'Sec-Fetch-Site': 'same-origin' }) => new Request( + 'http://localhost/api/opendirector/adopt', + { method: 'POST', headers, body: JSON.stringify({ projectId: project, resultId: candidate, operationId, ...input }) }, + ) + assert.equal((await adopt(request({}, {}))).status, 403) + assert.equal((await adopt(request({}, { 'X-OpenDirector-Action': '1', 'Sec-Fetch-Site': 'cross-site' }))).status, 403) + assert.equal(calls.length, 5) + const refreshed = await library({ url: '/api/opendirector/library?' + new URLSearchParams({ + project, show: [candidate, original].join(','), + }) }) + assert.deepEqual((await refreshed.json()).results.map(item => [item.resultId, item.selected]), + [[candidate, false], [original, true]]) + assert.deepEqual(calls.at(-1), ['GET', path]) + const busy = await adopt(request({})) + assert.equal((await busy.json()).code, 'storage_busy') + assert.equal(command, undefined) + blocked = false + const unknown = await adopt(request({})) + assert.equal((await unknown.json()).status, 'unknown') + assert.deepEqual(command.payload, { specId: spec, resultId: candidate }) + assert.deepEqual(command.expectedVersions, [ + { objectType: 'generation_spec', id: spec, revision: 4 }, + { objectType: 'canvas_item', id: item, revision: 7 }, + ]) + const unavailable = await adopt(request({ check: true })) + assert.equal((await unavailable.json()).status, 'unknown') + receiptUnavailable = false + const checked = await adopt(request({ check: true })) + assert.equal((await checked.json()).status, 'applied') + assert.deepEqual(calls.at(-1), ['GET', path + '/receipts/' + command.commandId]) + assert.equal(calls.filter(([, url]) => url === path + '/commands').length, 1) +}) + +test('library filters the full history before pagination and keeps a stable page boundary', async () => { + const project = randomUUID() + const spec = randomUUID() + const makeResult = kind => ({ id: randomUUID(), specId: spec, asset: { kind, assetId: randomUUID() } }) + const images = Array.from({ length: 15 }, () => makeResult('image')) + const videos = Array.from({ length: 15 }, () => makeResult('video')) + const snapshot = { + project: { id: project, name: 'Studio' }, jobs: [], + generationSpecs: [{ id: spec, currentResultId: images[0].id }], + assets: [{ id: videos.at(-1).asset.assetId, metadata: { width: 832, height: 480, durationSeconds: 5.0625 } }], + results: [...images, ...videos], + } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', canvasBaseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + fetchImpl: async (_url, request) => { + assert.equal(request.method, 'GET') + return Response.json(snapshot) + }, + }) + const first = await client.libraryResults(project, { kind: 'image' }) + const video = await client.libraryResults(project, { kind: 'video' }) + assert.deepEqual(video.results[0].details, { width: 832, height: 480, durationSeconds: 5.0625 }) + const order = [...images].reverse().map(item => item.id) + assert.deepEqual(first.results.map(item => item.resultId), order.slice(0, 12)) + assert.equal(first.nextCursor, order[11]) + snapshot.results.push(makeResult('image')) + const second = await client.libraryResults(project, { kind: 'image', after: first.nextCursor }) + assert.deepEqual(second.results.map(item => item.resultId), order.slice(12)) + assert.equal(second.nextCursor, null) + const oldest = await client.libraryResults(project, { kind: 'image', selection: 'other', order: 'oldest' }) + assert.deepEqual(oldest.results.map(item => item.resultId), images.slice(1, 13).map(item => item.id)) +}) + +test('task history filters and pages saved jobs without creating an editing session', async () => { + const projectId = randomUUID() + const makeJob = (kind, status) => ({ + id: randomUUID(), status, + inputSnapshot: { spec: { kind, prompt: 'Studio' }, model: { modelId: 'fixture' } }, + }) + const images = Array.from({ length: 15 }, () => makeJob('image', 'running')) + const snapshot = { project: { name: 'Studio' }, jobs: [...images, makeJob('video', 'failed')] } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + fetchImpl: async (url, request) => { + assert.equal(new URL(url).pathname, '/api/creation/projects/' + projectId) + assert.equal(request.method, 'GET') + return Response.json(snapshot) + }, + }) + const first = await client.libraryJobs(projectId, { kind: 'image' }) + const order = [...images].reverse().map(job => job.id) + assert.deepEqual(first.jobs.map(job => job.jobId), order.slice(0, 12)) + snapshot.jobs.push(makeJob('image', 'succeeded')) + const next = await client.libraryJobs(projectId, { kind: 'image', after: first.nextCursor }) + assert.deepEqual(next.jobs.map(job => job.jobId), order.slice(12)) + assert.equal(next.nextCursor, null) + const video = await client.libraryJobs(projectId, { kind: 'video', order: 'oldest' }) + assert.equal(video.jobs[0].status, 'failed') + await assert.rejects(client.libraryJobs(projectId, { after: randomUUID() }), { key: 'library.cursor_expired' }) +}) + +test('saved-work search covers the full project and combines with paging, adoption and task status', async t => { + const projectId = randomUUID() + const statuses = ['queued', 'running', 'succeeded', 'failed', 'cancelled', 'interrupted'] + const records = Array.from({ length: 60 }, (_, index) => ({ + specId: randomUUID(), jobId: randomUUID(), resultId: randomUUID(), assetId: randomUUID(), + prompt: 'x'.repeat(180) + (index % 2 ? ' afternoon' : ' DeepFocus 青瓷'), + status: statuses[index % statuses.length], title: 'Reviewed studio ' + index, + })) + const snapshot = { + project: { id: projectId, name: 'Saved work' }, assets: [], + generationSpecs: records.map((row, index) => ({ id: row.specId, prompt: 'Changed current description', currentResultId: index === 28 ? row.resultId : null })), + canvasItems: records.map(row => ({ title: row.title, binding: { role: 'generation', objectRef: { id: row.specId } } })), + jobs: records.map(row => ({ id: row.jobId, status: row.status, inputSnapshot: { + spec: { id: row.specId, kind: 'image', prompt: row.prompt }, + model: { modelId: 'studio-image-01', url: 'http://private-model', apiKey: 'private-key' }, + } })), + results: records.map(row => ({ id: row.resultId, specId: row.specId, jobId: row.jobId, asset: { kind: 'image', assetId: row.assetId } })), + } + const calls = [] + const server = createServer((request, response) => { + calls.push([request.method, request.url]) + assert.equal(request.method, 'GET') + assert.equal(request.url, '/api/creation/projects/' + projectId) + response.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(snapshot)) + }) + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)) + t.after(() => { + server.closeAllConnections() + return new Promise(resolve => server.close(resolve)) + }) + const routes = new Map() + apply({ + tools: { register() {} }, get() {}, + inject(_services, configure) { + configure({ effect(register) { register() }, connection: { fetch: { register(value) { routes.set(value.path, value.fetch) } } } }) + }, + }, { baseUrl: 'http://127.0.0.1:' + server.address().port }) + const read = async (filters = {}) => { + const response = await routes.get('/api/opendirector/library')({ + url: '/api/opendirector/library?' + new URLSearchParams({ project: projectId, ...filters }), + }) + assert.equal(response.status, 200) + return response.json() + } + const query = { q: 'DEEPFOCUS 青瓷', kind: 'image' } + const first = await read(query) + const expected = records.filter((_, index) => index % 2 === 0).reverse().map(row => row.resultId) + assert.deepEqual(first.results.map(row => row.resultId), expected.slice(0, 12)) + assert.equal(first.results[0].prompt, 'x'.repeat(160)) + assert.doesNotMatch(JSON.stringify(first), /private-model|private-key/) + const second = await read({ ...query, after: first.nextCursor }) + const third = await read({ ...query, after: second.nextCursor }) + assert.deepEqual([...first.results, ...second.results, ...third.results].map(row => row.resultId), expected) + assert.equal(third.nextCursor, null) + const selected = await read({ ...query, selection: 'current' }) + assert.deepEqual(selected.results.map(row => row.resultId), [records[28].resultId]) + assert.equal(selected.results[0].title, 'Reviewed studio 28') + assert.deepEqual((await read({ q: 'reviewed studio 28' })).results.map(row => row.resultId), [records[28].resultId]) + assert.deepEqual((await read({ q: records[3].resultId })).results.map(row => row.resultId), [records[3].resultId]) + assert.deepEqual((await read({ q: 'Changed current description' })).results, []) + assert.deepEqual((await read({ q: 'not in this project' })).results, []) + const active = await read({ view: 'jobs', q: 'STUDIO-IMAGE-01 青瓷', status: 'active', order: 'oldest' }) + assert.deepEqual(active.jobs.map(row => row.jobId), records.filter((row, index) => index % 2 === 0 && row.status === 'queued').map(row => row.jobId)) + const failed = await read({ view: 'jobs', status: 'failed', q: 'afternoon' }) + assert.deepEqual(failed.jobs.map(row => row.jobId), records.filter(row => row.status === 'failed').reverse().map(row => row.jobId)) + const invalid = await routes.get('/api/opendirector/library')({ + url: '/api/opendirector/library?' + new URLSearchParams({ project: projectId, view: 'jobs', status: 'imaginary' }), + }) + assert.equal(invalid.status, 400) + const tooLong = await routes.get('/api/opendirector/library')({ + url: '/api/opendirector/library?' + new URLSearchParams({ project: projectId, q: 'x'.repeat(201) }), + }) + assert.equal(tooLong.status, 400) + const beforeCompare = calls.length + const compareRequest = ids => routes.get('/api/opendirector/library')({ + url: '/api/opendirector/library?' + new URLSearchParams({ project: projectId, compare: ids.join(',') }), + }) + const pair = [records[28].resultId, records[0].resultId] + const compared = await compareRequest(pair) + assert.equal(compared.status, 200) + const comparison = await compared.json() + assert.deepEqual(comparison.images.map(image => [image.resultId, image.selected]), [[pair[0], true], [pair[1], false]]) + assert.equal(comparison.images[0].title, records[28].title) + assert.equal(calls.length, beforeCompare + 1) + assert.doesNotMatch(JSON.stringify(comparison), /private-model|private-key/) + assert.equal((await compareRequest([pair[0], pair[0]])).status, 400) + assert.equal((await compareRequest([pair[0]])).status, 400) + assert.equal(calls.length, beforeCompare + 1) + snapshot.results[0].asset.kind = 'audio' + assert.equal((await compareRequest(pair)).status, 400) + snapshot.results[0].asset.kind = 'image' + assert.equal((await compareRequest([pair[0], randomUUID()])).status, 400) + assert.ok(calls.length > 10) + assert.equal(snapshot.generationSpecs[28].currentResultId, records[28].resultId) +}) diff --git a/plugins/deepseek-harness/test/media-route.test.js b/plugins/deepseek-harness/test/media-route.test.js index 36776b557..332ee6ce3 100644 --- a/plugins/deepseek-harness/test/media-route.test.js +++ b/plugins/deepseek-harness/test/media-route.test.js @@ -10,7 +10,7 @@ test('media route accepts relative URLs, forwards ranges, and ends a stalled bod const stalled = randomUUID() const server = createServer((request, response) => { const root = '/api/creation/projects/' + project + '/assets/' - if (request.url === root + asset + '/content') { + if (request.url === root + asset + '/content' && request.headers.accept === 'video/*') { assert.equal(request.headers.range, 'bytes=0-2') response.writeHead(206, { 'Content-Type': 'video/mp4', 'Content-Range': 'bytes 0-2/9', 'Content-Length': '3', 'Accept-Ranges': 'bytes' }) @@ -18,6 +18,9 @@ test('media route accepts relative URLs, forwards ranges, and ends a stalled bod } else if (request.url === root + asset + '/thumbnail') { response.writeHead(200, { 'Content-Type': 'image/webp' }) response.end('thumbnail') + } else if (request.url === root + asset + '/content' && request.headers.accept === 'image/*') { + response.writeHead(200, { 'Content-Type': 'image/png' }) + response.end('original') } else if (request.url === root + stalled + '/content') { response.writeHead(200, { 'Content-Type': 'video/mp4' }) response.write('a') @@ -34,12 +37,14 @@ test('media route accepts relative URLs, forwards ranges, and ends a stalled bod inject(_services, configure) { configure({ effect(register) { register() }, - connection: { fetch: { register(value) { route = value } } }, + connection: { fetch: { register(value) { + if (value.path === '/api/opendirector/media') route = value + } } }, }) }, }, { baseUrl: 'http://127.0.0.1:' + server.address().port, requestTimeoutMs: 750 }) - const request = (id, kind, range) => route.fetch({ - url: '/api/opendirector/media?' + new URLSearchParams({ project, asset: id, kind }), + const request = (id, kind, range, original = false) => route.fetch({ + url: '/api/opendirector/media?' + new URLSearchParams({ project, asset: id, kind, ...(original && { original: '1' }) }), headers: new Headers(range ? { Range: range } : {}), }) const video = await request(asset, 'video', 'bytes=0-2') @@ -51,8 +56,15 @@ test('media route accepts relative URLs, forwards ranges, and ends a stalled bod const thumbnail = await request(asset, 'image') assert.equal(thumbnail.headers.get('content-type'), 'image/webp') assert.equal(await thumbnail.text(), 'thumbnail') + const original = await request(asset, 'image', undefined, true) + assert.equal(original.headers.get('content-type'), 'image/png') + assert.equal(await original.text(), 'original') assert.equal((await request('invalid-id', 'video')).status, 400) + const missing = await request(randomUUID(), 'image', undefined, true) + assert.equal(missing.status, 404) + assert.equal(missing.headers.get('cache-control'), 'private, no-store') + const waiting = await request(stalled, 'video') assert.equal(waiting.status, 200) const reader = waiting.body.getReader() diff --git a/plugins/deepseek-harness/test/metadata.test.js b/plugins/deepseek-harness/test/metadata.test.js new file mode 100644 index 000000000..960c5899c --- /dev/null +++ b/plugins/deepseek-harness/test/metadata.test.js @@ -0,0 +1,76 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { createRequire } from 'node:module' +import { readdir, readFile, stat } from 'node:fs/promises' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const require = createRequire(import.meta.url) +const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..') +const manifest = JSON.parse(await readFile(resolve(packageRoot, 'package.json'), 'utf8')) +const packageSpecifier = name => `${manifest.name}/${name}` + +async function readExportedFile(specifier) { + const path = require.resolve(packageSpecifier(specifier)) + return { path, contents: await readFile(path, 'utf8') } +} + +async function assertFile(path, label) { + const info = await stat(path) + assert.ok(info.isFile(), `${label} must resolve to a file: ${path}`) +} + +test('package exports expose locale entries and a local icon', async () => { + assert.equal(manifest.exports['./locale/*.json'], './locale/*.json') + assert.equal(manifest.exports['./icon'], './icon.svg') + assert.equal(manifest.icon, './icon.svg') + assert.ok(manifest.files.includes('locale/*.json')) + assert.ok(manifest.files.includes('icon.svg')) + + for (const [name, target] of Object.entries(manifest.exports)) { + if (!target.includes('*')) await assertFile(resolve(packageRoot, target), `exports[${name}]`) + } + await assertFile(resolve(packageRoot, manifest.main), 'main') + await assertFile(resolve(packageRoot, manifest.icon), 'icon') + + const localeFiles = await readdir(resolve(packageRoot, 'locale')) + for (const name of ['en.json', 'zh.json']) assert.ok(localeFiles.includes(name), `locale/${name} must ship`) +}) + +test('locale metadata identifies OpenDirector with matching user-facing descriptions', async () => { + const en = JSON.parse((await readExportedFile('locale/en.json')).contents) + const zh = JSON.parse((await readExportedFile('locale/zh.json')).contents) + + assert.deepEqual(Object.keys(en), Object.keys(zh)) + assert.deepEqual(Object.keys(en.meta).sort(), Object.keys(zh.meta).sort()) + + for (const locale of [en, zh]) { + assert.equal(locale.meta.title, 'OpenDirector') + await assertFile(resolve(packageRoot, locale.meta.detail), 'localized detail document') + assert.equal(typeof locale.meta.description, 'string') + assert.ok(locale.meta.description.trim().length > 0) + } + + assert.notEqual(zh.meta.description, en.meta.description) +}) + +test('icon is small, self-contained, and the package points at real project resources', async () => { + const { path, contents } = await readExportedFile('icon') + const bytes = Buffer.byteLength(contents) + assert.ok(bytes < 3 * 1024, `icon must stay under 3KB, got ${bytes} bytes`) + assert.match(contents, /^ React).apply({ + effect: run => run(), get: name => ({sessions: {binding: () => binding}, conversation: {input}})[name], + locale: {register: (_, locales) => { window.reviewLabels = strings = locales[window.reviewLocale]; }}, + slots: {inject: (_, register) => register(), register(slot, render) { + if (slot.name === "conversation.chat.turnTail") { tail = render; inject = slot.inject; } + }} + }); + }}; + window.showSaved = results => { + const calls = [{root: {callId: "show", name: "opendirector_results", meta: { + projectId: "coast", canvasUrl: "/canvas", savedResults: {projectName: "Coast", results} + }}}]; + const source = {subscribe: () => () => {}, getSnapshot: () => calls}; + createRoot(document.querySelector("main")).render(tail({ + turn: {turn: 1}, t: key => strings[key], + useChat: select => select({nodes: {turnDataSource: () => source}}), + ...inject("session") + })); + };` }, + bundle: true, write: false, define: { "process.env.NODE_ENV": '"production"' }, +}); + +const images = ["first-take", "second-take"].map((resultId, i) => ({ + resultId, assetId: "asset-" + resultId, kind: "image", title: "Coast", version: i + 1, +})); +const writes = []; +const browser = await launchBrowser(); +try { + const page = await browser.newPage(); + await page.addInitScript(lang => { window.reviewLocale = lang; }, locale); + await page.route("**/*", route => { + const url = new URL(route.request().url()); + const json = value => route.fulfill({ json: value }); + if (route.request().method() === "POST") { + writes.push({ path: url.pathname, body: route.request().postDataJSON() }); + return json(url.pathname.endsWith("/adopt") ? { status: "applied" } : { status: "accepted", jobId: "edit" }); + } + switch (url.pathname) { + case "/": return route.fulfill({ contentType: "text/html", body: '
Keep the coast.
' }); + case "/api/opendirector/media": return route.fulfill({ contentType: "image/svg+xml", body: '' }); + case "/api/opendirector/library": return json({ results: [{ ...images[1], selected: true }, images[0]] }); + case "/api/opendirector/creation": return json(url.searchParams.has("job") ? { status: "succeeded", results: [] } + : { models: [{ id: "image", modelId: "image", kind: "image", maxImages: 1, imageOutputs: [] }] }); + default: return route.abort(); + } + }); + await page.goto("http://127.0.0.1/"); + await page.addScriptTag({ content: host.outputFiles[0].text }); + await page.addScriptTag({ path: plugin }); + await page.evaluate(results => window.showSaved(results), images); + const labels = await page.evaluate(() => window.reviewLabels); + assert.equal(labels.adoptImage, locale === "en" ? "Adopt this image" : "采用这张图"); + const button = (parent, name) => parent.getByRole("button", { name, exact: true }); + const card = id => page.locator(`figure[data-opendirector-result="${id}"]`); + const viewer = page.getByRole("dialog", { name: labels.viewOriginal }); + await button(card("first-take"), labels.viewOriginal).click(); + await button(viewer, labels.nextImage).click(); + await button(viewer, labels.adoptImage).click(); + await button(viewer, labels.selected).waitFor(); + assert.ok(await button(viewer, labels.previousImage).isDisabled(), "adopted image moved to the first position"); + assert.equal(new URL(await viewer.locator("img").evaluate(img => img.src)).searchParams.get("asset"), images[1].assetId); + await button(viewer, labels.edit).click(); + const edit = page.getByRole("dialog", { name: labels.edit, exact: true }); + await edit.getByLabel(labels.brief).fill("Keep the scarf."); + await Promise.all([page.waitForResponse(res => res.request().method() === "POST"), button(edit, labels.generate).click()]); + await button(edit, labels.close).click(); + await button(card("first-take"), labels.viewOriginal).click(); + await button(viewer, labels.previousImage).click(); + await button(viewer, labels.referenceInChat).click(); + await page.waitForFunction(() => document.activeElement === document.querySelector("#draft")); + const before = await page.locator("#draft").textContent(); + await page.keyboard.type(" Continue."); + const draft = await page.locator("#draft").textContent(); + assert.equal(draft.replaceAll("\u00a0", " "), before.replaceAll("\u00a0", " ") + " Continue."); + assert.ok(draft.startsWith("Keep the coast.\n")); + assert.equal(draft.match(/second-take/g)?.length, 1); + assert.doesNotMatch(draft, /first-take/); + assert.deepEqual(writes.map(({ path, body }) => [path, body.projectId, body.resultId ?? body.sourceResultIds]), [ + ["/api/opendirector/adopt", "coast", "second-take"], + ["/api/opendirector/creation", "coast", ["second-take"]], + ]); + console.log("Reviewed, adopted, edited, and referenced the same result after reordering."); +} finally { + await browser.close(); +} diff --git a/plugins/deepseek-harness/test/template.test.js b/plugins/deepseek-harness/test/template.test.js new file mode 100644 index 000000000..63f4fd806 --- /dev/null +++ b/plugins/deepseek-harness/test/template.test.js @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import test from 'node:test' +import { OpenDirectorClient } from '../src/client.js' + +function fixture(kind = 'image') { + const [projectId, modelId, specId, resultId, jobId, assetId, itemId, referenceId] = + Array.from({ length: 8 }, randomUUID) + const protocol = kind === 'image' ? 'openai_compatible_images' : 'vllm_omni_tts' + const parameters = kind === 'image' + ? { size: '2K', aspectRatio: '3:2', preset: 'product-views', responseFormat: 'url', outputFormat: 'png' } + : { creationType: 'audio', mode: 'unified', voice: 'character-a', voiceSelection: { + protocol, modelId: 'fixture', connectionId: 'test', voiceId: 'character-a', name: 'Character', + source: 'uploaded', hasReferenceAudio: true, refText: 'Original transcript', + } } + const reference = { referenceId: randomUUID(), role: 'reference', asset: { + assetId: referenceId, revision: 2, fingerprint: 'a'.repeat(64), kind, + }, sourceVersion: { objectType: 'canvas_item', id: randomUUID(), revision: 4 }, + metadata: kind === 'image' ? { width: 512, height: 512 } : { durationSeconds: 2 }, + transmission: 'content' } + const frozen = { + spec: { id: specId, projectId, modelConfigId: modelId, kind, prompt: 'Original description', + promptContent: null, parameters }, model: { modelId: 'fixture', protocol }, references: [reference], + } + const snapshot = { + project: { id: projectId }, assets: [], references: [], + generationSpecs: [{ id: specId, revision: 9, currentResultId: resultId, parameters: { size: '1024x1024' } }], + canvasItems: [{ id: itemId, position: { x: 0, y: 0 }, width: 352, parentId: null }], + jobs: [{ id: jobId, status: 'succeeded', inputSnapshot: frozen }], + results: [{ id: resultId, jobId, specId, asset: { assetId, kind, revision: 1, fingerprint: 'b'.repeat(64) } }], + } + const model = { id: modelId, kind, modelId: 'fixture', protocol, + inputRules: { allowedKinds: [kind], maxImages: 3, voiceRequired: kind === 'audio', + imageOutputs: [{ size: '1536x1024', aspectRatio: '3:2' }] } } + const commands = [] + const calls = [] + const receipts = new Map() + let loseSubmission = true + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + async fetchImpl(url, request) { + const path = new URL(url).pathname + calls.push(path) + if (path === '/api/model-configs') return Response.json([model]) + if (request.method === 'DELETE') return Response.json({}) + if (path.endsWith('/open') || path.endsWith('/' + projectId)) return Response.json(snapshot) + if (path.includes('/receipts/')) { + const value = receipts.get(path.split('/').at(-1)) + return Response.json(value ?? {}, { status: value ? 200 : 404 }) + } + assert.ok(path.endsWith('/commands')) + const command = JSON.parse(request.body) + commands.push(command) + if (command.type === 'canvas.createGeneration') { + snapshot.generationSpecs.push(command.payload.spec) + const receipt = { status: 'applied', changed: [ + { id: command.payload.spec.id, revision: 1 }, { id: command.payload.item.id, revision: 1 }, + ] } + receipts.set(command.commandId, receipt) + return Response.json(receipt) + } + assert.equal(command.type, 'generation.submit') + const receipt = { status: 'accepted', jobIds: [randomUUID()] } + receipts.set(command.commandId, receipt) + if (loseSubmission) { loseSubmission = false; throw new TypeError('Lost response') } + return Response.json(receipt) + }, + }) + return { client, commands, calls, frozen, snapshot, model, reference, projectId, resultId, modelId } +} + +test('reuse reads frozen settings, pins ordered assets and changes only an explicit image size', async () => { + const f = fixture() + const template = await f.client.creationTemplate(f.projectId, f.resultId) + assert.equal(template.prompt, f.frozen.spec.prompt) + assert.equal(template.originalOutput, '2K · 3:2') + assert.equal(template.references[0].assetId, f.reference.asset.assetId) + assert.equal(f.calls.some(path => path.endsWith('/open')), false) + assert.equal(Object.hasOwn(template, 'model'), false) + const input = { projectId: f.projectId, operationId: randomUUID(), modelConfigId: f.modelId, kind: 'image', + prompt: 'A new description', reuseResultId: f.resultId, output: null } + await assert.rejects(f.client.startCreation(input), { name: 'UnknownOperationError' }) + const receipt = await f.client.startCreation({ ...input, check: true }) + assert.equal(receipt.status, 'accepted') + assert.deepEqual(await f.client.startCreation(input), receipt) + assert.equal(f.commands.length, 2) + assert.deepEqual(f.commands[0].payload.spec.parameters, f.frozen.spec.parameters) + assert.equal(f.commands[0].payload.spec.prompt, input.prompt) + assert.deepEqual(f.commands[0].payload.references[0].source, f.reference.asset) + assert.deepEqual(f.commands[0].payload.references[0].sourceVersion, f.reference.sourceVersion) + assert.equal(f.commands[1].payload.adoptionPolicy, 'candidate_only') + assert.equal(f.snapshot.generationSpecs[0].currentResultId, f.resultId) + assert.equal(f.frozen.spec.prompt, 'Original description') + await f.client.startCreation({ ...input, operationId: randomUUID(), output: f.model.inputRules.imageOutputs[0] }) + assert.deepEqual(f.commands[2].payload.spec.parameters, + { ...f.frozen.spec.parameters, ...f.model.inputRules.imageOutputs[0] }) + f.frozen.spec.promptContent = [{ type: 'text', text: 'Structured input' }] + await assert.rejects(f.client.creationTemplate(f.projectId, f.resultId), { key: 'creation.template_complex' }) + await assert.rejects(f.client.startCreation({ ...input, operationId: randomUUID() }), { key: 'creation.template_complex' }) + assert.equal(f.commands.length, 4) +}) + +test('voiceover reuse keeps the registered voice identity and rejects an implicit voice or model change', async () => { + const f = fixture('audio') + const input = { projectId: f.projectId, operationId: randomUUID(), modelConfigId: f.modelId, kind: 'audio', + prompt: 'Another line to read', reuseResultId: f.resultId, voice: 'character-a' } + const template = await f.client.creationTemplate(f.projectId, f.resultId) + assert.equal(template.voice, 'character-a') + await assert.rejects(f.client.startCreation({ ...input, voice: 'another-voice' }), { key: 'creation.template_unavailable' }) + assert.equal(f.commands.length, 0) + await assert.rejects(f.client.startCreation(input), { name: 'UnknownOperationError' }) + assert.deepEqual(f.commands[0].payload.spec.parameters, f.frozen.spec.parameters) + assert.equal(f.commands[0].payload.references[0].source.kind, 'audio') + f.model.protocol = 'different-protocol' + await assert.rejects(f.client.creationTemplate(f.projectId, f.resultId), { key: 'creation.template_unavailable' }) + assert.equal(f.commands.length, 2) +}) diff --git a/plugins/deepseek-harness/test/versions.test.js b/plugins/deepseek-harness/test/versions.test.js new file mode 100644 index 000000000..3865338b9 --- /dev/null +++ b/plugins/deepseek-harness/test/versions.test.js @@ -0,0 +1,241 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { randomUUID } from 'node:crypto' +import { OpenDirectorClient } from '../src/client.js' +import { resultVersionInfo } from '../src/versions.js' + +function asset(assetId, revision, fingerprint, kind = 'image') { + return { assetId, revision, fingerprint, kind } +} + +function result(specId, jobId, value) { + return { id: randomUUID(), specId, jobId, asset: value } +} + +test('video cards use the source job’s continuation modes and keep older results actionable', () => { + const modes = [['first_frame', 'reference'], ['first_frame', 'continuation'], undefined] + const jobs = modes.map(videoModes => ({ id: randomUUID(), inputSnapshot: { model: { inputRules: { videoModes } } } })) + const results = jobs.map(job => result(randomUUID(), job.id, asset(randomUUID(), 1, 'a'.repeat(64), 'video'))) + const info = resultVersionInfo({ results, jobs }) + assert.deepEqual(results.map(row => info.get(row.id).supportsContinuation), [false, true, undefined]) +}) + +test('versions follow each spec registration order and accept only valid createdAt strings', () => { + const specA = randomUUID(), specB = randomUUID() + const jobA1 = randomUUID(), jobA2 = randomUUID(), jobB = randomUUID(), jobC = randomUUID() + const a1 = result(specA, jobA1, asset(randomUUID(), 1, 'a'.repeat(64))) + const b1 = result(specB, jobB, asset(randomUUID(), 1, 'b'.repeat(64))) + const a2 = result(specA, jobA2, asset(randomUUID(), 1, 'c'.repeat(64))) + const snapshot = { + results: [a1, b1, a2], + jobs: [ + { id: jobA1, createdAt: '2025-01-02T03:04:05.000Z' }, + { id: jobB, createdAt: 'not a date' }, + { id: jobA2, createdAt: 42 }, + { id: jobC, createdAt: '' }, + ], + canvasItems: [], + } + const info = resultVersionInfo(snapshot) + assert.deepEqual(info.get(a1.id), { version: 1, createdAt: '2025-01-02T03:04:05.000Z' }) + assert.deepEqual(info.get(b1.id), { version: 1 }) + assert.deepEqual(info.get(a2.id), { version: 2 }) +}) + +test('a source is reported only for one exact frozen reference match, preferring continuation then first_frame', () => { + const sourceA = randomUUID(), sourceB = randomUUID(), target = randomUUID() + const assetA = asset(randomUUID(), 3, 'a'.repeat(64)) + const assetB = asset(randomUUID(), 1, 'b'.repeat(64)) + const oldA = result(sourceA, randomUUID(), assetA) + const oldB = result(sourceB, randomUUID(), assetB) + const titleA = 'A'.repeat(200) + const job = references => ({ id: randomUUID(), inputSnapshot: { references } }) + const continuation = result(target, randomUUID(), asset(randomUUID(), 1, 'c'.repeat(64))) + continuation.jobId = job([{ role: 'reference', asset: assetB }, { role: 'continuation', asset: assetA }]).id + const firstFrame = result(target, randomUUID(), asset(randomUUID(), 1, 'd'.repeat(64))) + firstFrame.jobId = job([{ role: 'first_frame', asset: assetB }, { role: 'reference', asset: assetA }]).id + const imageFallback = result(target, randomUUID(), asset(randomUUID(), 1, 'e'.repeat(64))) + imageFallback.jobId = job([{ role: 'reference', asset: assetB }]).id + const both = result(target, randomUUID(), asset(randomUUID(), 1, 'f'.repeat(64))) + both.jobId = job([{ role: 'first_frame', asset: assetB }, { role: 'continuation', asset: assetA }]).id + const snapshot = { + results: [oldA, oldB, continuation, firstFrame, imageFallback, both], + jobs: [ + { id: oldA.jobId }, { id: oldB.jobId }, + { id: continuation.jobId, inputSnapshot: { references: [{ role: 'reference', asset: assetB }, { role: 'continuation', asset: assetA }] } }, + { id: firstFrame.jobId, inputSnapshot: { references: [{ role: 'first_frame', asset: assetB }, { role: 'reference', asset: assetA }] } }, + { id: imageFallback.jobId, inputSnapshot: { references: [{ role: 'reference', asset: assetB }] } }, + { id: both.jobId, inputSnapshot: { references: [{ role: 'first_frame', asset: assetB }, { role: 'continuation', asset: assetA }] } }, + ], + canvasItems: [ + { title: titleA, binding: { role: 'generation', objectRef: { id: sourceA } } }, + { title: 'Source B', binding: { role: 'generation', objectRef: { id: sourceB } } }, + ], + } + const info = resultVersionInfo(snapshot) + assert.deepEqual(info.get(oldA.id), { version: 1 }) + assert.deepEqual(info.get(oldB.id), { version: 1 }) + assert.deepEqual(info.get(continuation.id), { + version: 1, sourceResultId: oldA.id, sourceVersion: 1, sourceTitle: titleA.slice(0, 160), + }) + assert.deepEqual(info.get(firstFrame.id), { + version: 2, sourceResultId: oldB.id, sourceVersion: 1, sourceTitle: 'Source B', + }) + assert.deepEqual(info.get(imageFallback.id), { + version: 3, sourceResultId: oldB.id, sourceVersion: 1, sourceTitle: 'Source B', + }) + assert.deepEqual(info.get(both.id), { + version: 4, sourceResultId: oldA.id, sourceVersion: 1, sourceTitle: titleA.slice(0, 160), + }) +}) + +test('ambiguous, incomplete, fingerprint-only and later matches never claim a source', () => { + const sourceA = randomUUID(), sourceB = randomUUID(), target = randomUUID() + const shared = asset(randomUUID(), 1, 'a'.repeat(64)) + const first = result(sourceA, randomUUID(), { ...shared }) + const duplicate = result(sourceB, randomUUID(), { ...shared }) + const fingerprintOnly = result(sourceA, randomUUID(), asset(randomUUID(), 1, 'b'.repeat(64))) + const newDuplicate = result(target, randomUUID(), asset(randomUUID(), 1, 'c'.repeat(64))) + const newFingerprint = result(target, randomUUID(), asset(randomUUID(), 1, 'd'.repeat(64))) + const newMissing = result(target, randomUUID(), asset(randomUUID(), 1, 'e'.repeat(64))) + const laterAsset = asset(randomUUID(), 1, 'f'.repeat(64)) + const newLater = result(target, randomUUID(), asset(randomUUID(), 1, '0'.repeat(64))) + const later = result(sourceB, randomUUID(), laterAsset) + const snapshot = { + results: [first, duplicate, fingerprintOnly, newDuplicate, newFingerprint, newMissing, newLater, later], + jobs: [ + { id: first.jobId }, { id: duplicate.jobId }, { id: fingerprintOnly.jobId }, + { id: newDuplicate.jobId, inputSnapshot: { references: [{ role: 'continuation', asset: shared }] } }, + { id: newFingerprint.jobId, inputSnapshot: { references: [{ role: 'first_frame', + asset: { assetId: randomUUID(), revision: 1, fingerprint: fingerprintOnly.asset.fingerprint, kind: 'image' } }] } }, + { id: newMissing.jobId, inputSnapshot: { references: [{ role: 'reference', + asset: { assetId: fingerprintOnly.asset.assetId, fingerprint: fingerprintOnly.asset.fingerprint, kind: 'image' } }] } }, + { id: newLater.jobId, inputSnapshot: { references: [{ role: 'first_frame', asset: laterAsset }] } }, + { id: later.jobId }, + ], + canvasItems: [], + } + const info = resultVersionInfo(snapshot) + for (const entry of [newDuplicate, newFingerprint, newMissing, newLater]) { + assert.equal(info.get(entry.id).sourceResultId, undefined) + assert.equal(info.get(entry.id).sourceVersion, undefined) + assert.equal(info.get(entry.id).sourceTitle, undefined) + } + const before = structuredClone(snapshot) + assert.deepEqual(info, resultVersionInfo(snapshot)) + assert.deepEqual(snapshot, before) +}) + +test('library paging, filtering and comparison keep registration versions stable', async () => { + const projectId = randomUUID(), specId = randomUUID() + const results = Array.from({ length: 14 }, (_, index) => result(specId, randomUUID(), + asset(randomUUID(), 1, String(index).repeat(64)))) + const video = result(specId, randomUUID(), asset(randomUUID(), 1, 'v'.repeat(64), 'video')) + const snapshot = { + project: { id: projectId, name: 'Studio' }, + generationSpecs: [{ id: specId, currentResultId: results[5].id }], + canvasItems: [], jobs: [], assets: [], results: [...results, video], + } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', canvasBaseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + fetchImpl: async () => Response.json(snapshot), + }) + const version = value => results.indexOf(value) + 1 + const first = await client.libraryResults(projectId, { kind: 'image' }) + assert.deepEqual(first.results.map(item => [item.resultId, item.version]), + results.slice().reverse().slice(0, 12).map(item => [item.id, version(item)])) + const second = await client.libraryResults(projectId, { kind: 'image', after: first.nextCursor }) + assert.deepEqual(second.results.map(item => [item.resultId, item.version]), + results.slice(0, 2).reverse().map(item => [item.id, version(item)])) + const all = await client.libraryResults(projectId) + assert.equal(all.results.find(item => item.resultId === video.id).version, 15) + assert.equal(all.results.find(item => item.resultId === results[13].id).version, 14) + const other = await client.libraryResults(projectId, { kind: 'image', selection: 'other' }) + assert.deepEqual(other.results.map(item => [item.resultId, item.version]), + results.slice().reverse().filter(item => item.id !== results[5].id).slice(0, 12) + .map(item => [item.id, version(item)])) + const compared = await client.compareImages(projectId, [results[13].id, results[0].id]) + assert.deepEqual(compared.images.map(image => [image.resultId, image.version]), + [[results[13].id, 14], [results[0].id, 1]]) +}) + +test('show saved media in the requested order using the frozen prompt and the actual video first frame', async () => { + const projectId = randomUUID() + const image = result(randomUUID(), randomUUID(), asset(randomUUID(), 1, 'original')) + const edited = result(randomUUID(), randomUUID(), asset(image.asset.assetId, 2, 'edited')) + const voice = result(randomUUID(), randomUUID(), asset(randomUUID(), 1, 'voice', 'audio')) + const makeClip = () => result(randomUUID(), randomUUID(), asset(randomUUID(), 1, 'clip', 'video')) + const video = makeClip(), failed = makeClip(), referenceOnly = makeClip(), changed = makeClip() + const prompt = 'Keep the coast. '.repeat(45) + 'Add a scarf.' + const clipJob = (clip, role, input, status = 'succeeded') => ({ + id: clip.jobId, status, inputSnapshot: { references: [{ role, asset: input }] }, + }) + const snapshot = { + project: { id: projectId, name: 'Night Watch' }, + generationSpecs: [{ id: edited.specId, currentResultId: edited.id, prompt: 'New draft' }], + canvasItems: [{ title: 'Keeper by the sea', binding: { role: 'generation', objectRef: { id: video.specId } } }], + assets: [{ id: voice.asset.assetId, metadata: { durationSeconds: 2 } }], + jobs: [ + { id: edited.jobId, inputSnapshot: { spec: { prompt }, references: [{ role: 'reference', asset: image.asset }] } }, + clipJob(video, 'first_frame', edited.asset), clipJob(failed, 'first_frame', edited.asset, 'failed'), + clipJob(referenceOnly, 'reference', image.asset), clipJob(changed, 'first_frame', { ...edited.asset, fingerprint: 'different' }), + ], + results: [image, edited, voice, video, failed, referenceOnly, changed], + } + const calls = [] + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + fetchImpl: async (url, init) => { calls.push([init.method, new URL(url).pathname]); return Response.json(snapshot) }, + }) + const order = [edited.id, image.id, video.id, voice.id] + const saved = await client.showResults(projectId, order) + assert.equal(saved.projectName, 'Night Watch') + assert.deepEqual(saved.results.map(row => row.resultId), order) + const [scarf, original, shot, audio] = saved.results + assert.deepEqual(scarf.firstFrameFor, [{ resultId: video.id, title: 'Keeper by the sea' }]) + assert.deepEqual(original.firstFrameFor, []) + assert.equal(scarf.prompt, prompt) + assert.equal(scarf.selected, true) + assert.equal(scarf.sourceResultId, image.id) + assert.equal(shot.sourceResultId, edited.id) + assert.equal(audio.details.durationSeconds, 2) + assert.deepEqual(calls, [['GET', '/api/creation/projects/' + projectId]]) + await assert.rejects(client.showResults(projectId, [edited.id, randomUUID()]), { key: 'library.results' }) +}) + +test('creation and group status projections reuse the same versions and createdAt', async () => { + const projectId = randomUUID(), specId = randomUUID(), groupId = randomUUID() + const job1 = randomUUID(), job2 = randomUUID() + const first = result(specId, job1, asset(randomUUID(), 1, 'a'.repeat(64))) + const second = result(specId, job2, asset(randomUUID(), 1, 'b'.repeat(64))) + const snapshot = { + project: { id: projectId, name: 'Studio' }, + generationSpecs: [{ id: specId, currentResultId: second.id }], + canvasItems: [], assets: [first, second].map(item => ({ + id: item.asset.assetId, metadata: { width: 512, height: 512 }, + })), + jobs: [ + { id: job1, batchId: groupId, status: 'succeeded', createdAt: '2025-02-03T04:05:06.000Z', + inputSnapshot: { spec: { id: specId, parameters: { size: '512x512' } } } }, + { id: job2, batchId: groupId, status: 'succeeded', inputSnapshot: { spec: { id: specId, parameters: { size: '1536x1024' } } } }, + ], + results: [first, second], + } + const client = new OpenDirectorClient({ baseUrl: 'http://localhost', requestTimeoutMs: 1000 }, { + fetchImpl: async url => new URL(url).pathname.endsWith('/queries') + ? Response.json(snapshot.jobs[0]) + : Response.json(snapshot), + }) + const status = await client.creationStatus(projectId, job1) + assert.deepEqual(status.results.map(item => [item.resultId, item.version, item.createdAt]), [ + [first.id, 1, '2025-02-03T04:05:06.000Z'], + [second.id, 2, undefined], + ]) + const group = await client.creationGroupStatus(projectId, groupId) + for (const view of [status, group]) { + assert.deepEqual(view.results.map(item => item.details), [ + { width: 512, height: 512 }, { width: 512, height: 512, requestedSize: '1536x1024' }, + ]) + } + assert.deepEqual(group.results.map(item => [item.resultId, item.version, item.selected]), [ + [first.id, 1, false], [second.id, 2, true], + ]) +}) diff --git a/tests/test_creation_generation_service.py b/tests/test_creation_generation_service.py index cbad1e4ae..f16fc2a34 100644 --- a/tests/test_creation_generation_service.py +++ b/tests/test_creation_generation_service.py @@ -1,5 +1,6 @@ """Provider doubles exercise the real durable runtime, files and restart path.""" import asyncio +from types import SimpleNamespace from uuid import UUID, uuid4 import pytest @@ -7,6 +8,7 @@ from opendirector.application.creation_canvas import resolved_inputs from opendirector.application.creation_generation import CreationGeneration from opendirector.domain.creation.commands import parse_command +from opendirector.domain.projects import ProjectError from opendirector.infrastructure.model_configs import ModelConfigs from test_creation_canvas_service import project, media, send, text_material, ver @@ -48,6 +50,26 @@ def configure(project, config): return target, store.snapshot(pid).generationSpecs[-1] +def submit(project, target, spec): + _, pid, _ = project + return parse_command(dict(commandId=uuid4(), projectId=pid, type='generation.submit', + expectedVersions=[ver('canvas_item', target), ver('generation_spec', spec)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=target.id))) + + +def request_cancel(store, pid, job): + """Commit the durable stop intent directly, as job.cancel does before stopping.""" + command = parse_command(dict(commandId=uuid4(), projectId=pid, type='job.cancel', + expectedVersions=[ver('job', job)], payload=dict(jobId=job.id))) + def mark(before): + current = next(j for j in before.jobs if j.id == job.id) + if current.status in {'succeeded', 'cancelled'}: + return before + changed = current.model_copy(update={'cancelRequested': True, 'revision': current.revision + 1}) + return before.model_copy(update={'jobs': tuple(changed if j.id == changed.id else j for j in before.jobs)}) + return store.commit(command, mark, source='background') + + @pytest.mark.anyio @pytest.mark.parametrize('title', ['Output.md', 'Output.md.md']) async def test_result_registration_uses_one_extension_when_the_node_title_has_one(project, title): @@ -285,3 +307,163 @@ async def test_hiding_mentioned_source_during_generation_preserves_spec_and_adop finally: provider.finish.set() await runner.close() + + +@pytest.mark.anyio +async def test_checkpoint_reconciles_cancellation_committed_between_read_and_write(project, monkeypatch): + store, pid, session = project + provider = Provider() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + receipt = runner.prepare(submit(project, target, spec), session=session) + assert receipt.status == 'accepted', receipt + running = runner.task(store.snapshot(pid).jobs[0]) + running.update(status='running', phase='queued') + runner.checkpoint(pid, running, runner.directory(pid)) + stale = runner.task(store.snapshot(pid).jobs[0]) + stale.update(status='running', phase='submit') + original = runner.projects.commit + commits = [] + def injecting(work, apply, **kwargs): + if work.type == 'job.checkpoint': + commits.append(work) + if len(commits) == 1: + current = store.snapshot(pid).jobs[0] + request_cancel(store, pid, current) + return original(work, apply, **kwargs) + monkeypatch.setattr(runner.projects, 'commit', injecting) + runner.checkpoint(pid, stale, runner.directory(pid)) + final = store.snapshot(pid).jobs[0] + assert final.status == 'running' and final.cancelRequested + assert final.errorDetails is None + assert len(commits) == 2, 'the stale save was rejected once and then retried' + assert provider.calls == [] + await runner.close() + + +@pytest.mark.anyio +async def test_checkpoint_keeps_terminal_cancellation_against_a_stale_worker(project): + store, pid, session = project + provider = Provider() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + receipt = runner.prepare(submit(project, target, spec), session=session) + assert receipt.status == 'accepted', receipt + request_cancel(store, pid, store.snapshot(pid).jobs[0]) + cancelled = runner.task(store.snapshot(pid).jobs[0]) + cancelled.update(status='cancelled', recovery='review', resumeAllowed=False) + runner.checkpoint(pid, cancelled, runner.directory(pid)) + before = store.snapshot(pid).jobs[0] + assert before.status == 'cancelled' and before.cancelRequested + stale = runner.task(before) + stale.update(status='running', phase='submit', recovery='submit', resumeAllowed=True) + runner.checkpoint(pid, stale, runner.directory(pid)) + after = store.snapshot(pid).jobs[0] + assert after.status == 'cancelled' + assert after == before + assert provider.calls == [] + await runner.close() + + +@pytest.mark.anyio +async def test_checkpoint_leaves_a_succeeded_job_unchanged(project): + store, pid, session = project + provider = Provider() + provider.finish.set() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + receipt = await runner.execute(submit(project, target, spec), session=session) + assert receipt.status == 'accepted', receipt + await asyncio.gather(runner.jobs[str(receipt.jobIds[0])].future, return_exceptions=True) + succeeded = store.snapshot(pid).jobs[0] + assert succeeded.status == 'succeeded' + stale = runner.task(succeeded) + stale.update(status='running', phase='submit', recovery='submit', resumeAllowed=True) + runner.checkpoint(pid, stale, runner.directory(pid)) + assert store.snapshot(pid).jobs[0] == succeeded + await runner.close() + + +@pytest.mark.anyio +async def test_checkpoint_does_not_retry_an_unrelated_rejection(project, monkeypatch): + store, pid, session = project + provider = Provider() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + receipt = runner.prepare(submit(project, target, spec), session=session) + assert receipt.status == 'accepted', receipt + calls = [] + def rejecting(work, apply, **kwargs): + calls.append(work) + return SimpleNamespace(status='rejected', issues=(SimpleNamespace(code='invalid_input'),)) + monkeypatch.setattr(runner.projects, 'commit', rejecting) + task = runner.task(store.snapshot(pid).jobs[0]) + task.update(status='running', phase='submit') + with pytest.raises(ProjectError) as failure: + runner.checkpoint(pid, task, runner.directory(pid)) + assert failure.value.status == 409 + assert len(calls) == 1 + assert store.snapshot(pid).jobs[0].status == 'queued' + await runner.close() + + +@pytest.mark.anyio +async def test_cancel_committed_during_submit_checkpoint_does_not_fail_or_call_provider(project, monkeypatch): + store, pid, session = project + provider = Provider() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + original = runner.projects.commit + loop = asyncio.get_running_loop() + ready = asyncio.Event() + injected, cancels, worker = {'done': False, 'conflicts': 0}, [], {} + def injecting(work, apply, **kwargs): + if work.type == 'job.checkpoint' and work.payload.job.phase == 'submit' and not injected['done']: + injected['done'] = True + current = store.snapshot(pid).jobs[0] + request_cancel(store, pid, current) + worker['future'] = runner.jobs[str(current.id)].future + loop.call_soon_threadsafe(lambda: cancels.append(asyncio.ensure_future( + runner.cancel(str(pid), str(current.id), session)))) + loop.call_soon_threadsafe(ready.set) + receipt = original(work, apply, **kwargs) + if work.type == 'job.checkpoint' and receipt.status == 'rejected': + injected['conflicts'] += 1 + return receipt + monkeypatch.setattr(runner.projects, 'commit', injecting) + receipt = await runner.execute(submit(project, target, spec), session=session) + assert receipt.status == 'accepted', receipt + await asyncio.wait_for(ready.wait(), 5) + await asyncio.gather(worker['future'], return_exceptions=True) + await asyncio.gather(*cancels, return_exceptions=True) + final = store.snapshot(pid).jobs[0] + assert final.status == 'cancelled', final + assert final.cancelRequested and final.errorDetails is None + assert injected['done'] and injected['conflicts'] >= 1 + assert provider.calls == [] + assert not store.snapshot(pid).results + await runner.close() + + +@pytest.mark.anyio +async def test_stale_checkpoint_preserves_the_saved_remote_identity_after_cancellation(project): + store, pid, session = project + provider = Provider() + runner, config = runtime(project, provider) + target, spec = configure(project, config) + assert runner.prepare(submit(project, target, spec), session=session).status == 'accepted' + stale = runner.task(store.snapshot(pid).jobs[0]) + remote = dict(stale, status='running', phase='poll', externalTaskId='remote-accepted-1') + runner.checkpoint(pid, remote, runner.directory(pid)) + request_cancel(store, pid, store.snapshot(pid).jobs[0]) + stopped = runner.task(store.snapshot(pid).jobs[0]) + stopped.update(status='cancelled', recovery='remote', resumeAllowed=False) + runner.checkpoint(pid, stopped, runner.directory(pid)) + before = store.snapshot(pid).jobs[0] + stale.update(status='running', phase='submit', externalTaskId=None) + runner.checkpoint(pid, stale, runner.directory(pid)) + after = store.snapshot(pid).jobs[0] + assert after == before + assert after.externalTaskId == 'remote-accepted-1' + assert provider.calls == [] + await runner.close()