Restructure backend and frontend modules; add story, library, and editor schema migrations. Support editable automatic production, manual confirmation modes, account and user lifecycle management, compact container scrolling, consistent forms, and per-task result previews. Update inference and TTS scheduling, deployment guidance, and regression coverage; remove obsolete standalone pages and temporary acceptance artifacts.
37 KiB
Shared API contract
All endpoints use /api. JSON errors: {detail:{code,message}}; normal FastAPI validation errors may additionally contain field locations. Session cookie cmvr_session is HttpOnly, same-origin. POST/PATCH/DELETE except login need X-CSRF-Token from auth response. Never expose inference keys or absolute server paths.
Private resources are owner-scoped for both regular users and admin: private assets, jobs, workflow drafts/runs and batches never become cross-user readable through the admin role. Explicit /shared-assets reads are authenticated cross-user reads of active publications. User administration does not grant access to another user's private content.
Authentication
- POST
/auth/login{username,password}→{user:{id,username,display_name,role},csrf_token}plus session cookie. - GET
/auth/me→ same shape; 401 when signed out. - POST
/auth/logout→ 204; close SSE on frontend. - Admin POST
/auth/users{username,display_name,password}→ user. Initial passwords allow 6–256 characters, including six digits.
Capabilities and resources
- GET
/capabilities→{items:Capability[],scheduler:Scheduler}. - GET
/system/status→{inference_online:boolean,scheduler:Scheduler,models:Capability[]}. - Capability:
{task_type,label,model,available,input_types:string[],defaults:object,constraints:object,description:string}. - Scheduler:
{available:boolean,state:string,reason:string|null,gpus:[{index,name,busy:boolean,eligible:boolean,free_gib:number|null}],updated_at:string|null}. No PID or user identity. - Types:
image.generate,image.reference.generate,video.generate,video.people.analyze,video.replace,defect.generate,audio.transcribe,math.solve,media.structure,video.compose, optionalaudio.speech(only available when a real provider is configured). Video editing availability requires both business/inference enablement and the pinned operator validation receipt; constraints are the smaller local/remote budgets.
Assets
- POST
/assetsmultipart fieldfile, optionalname→ Asset. - GET
/assets?page=1&page_size=24&kind=&q=&tag=&origin=&favorite=→{items:Asset[],total,page,page_size}. Returns only the caller's active, ready, private assets.originacceptsupload,generated, orshared; omitfavoritefor no favorite filter. - GET
/assets/{id}→ Asset. - PATCH
/assets/{id}{name?,tags?:string[],favorite?:boolean}→ Asset. - DELETE
/assets/{id}→ 204 after soft deletion. Workflow references or active input use reject with409 asset_in_use; resolve references/control the owning record first. Physical files are retained until explicit eligible GC. - GET
/assets/{id}/contentinline, Range supported;?download=1attachment. - GET
/assets/{id}/thumbnailauthenticated image preview (fallback image content when no separate thumbnail). - Asset:
{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,preview_url,thumbnail_url:null|string,download_url,source_job_id:null|string,origin:'upload'|'generated'|'shared',tags:string[],favorite:boolean,created_at:string}. A retained generated asset may keepsource_job_idafter its source job is archived; that identifier does not guarantee an accessible job.
Logical folders (schema 006)
- GET
/folders→{items:Folder[]}. Folder:{id,name,parent_id:null|string,created_at,updated_at}; private to the current owner. - POST
/folders{name,parent_id?}→ 201 Folder. PATCH/folders/{id}{name?,parent_id?}→ Folder. Same-parent duplicate names and parent cycles are rejected. - DELETE
/folders/{id}→ 204. Removes this category and descendants; preserves all assets, jobs, drafts, runs and physical files. Remaining memberships in other folders survive. - POST
/folders/assign{kind:'assets'|'jobs'|'drafts'|'runs',ids:string[],folder_id:null|string,mode?:'move'|'add'}→{updated,kind,folder_id}. At most 200 requested IDs; all owner checks are atomic.addapplies only to assets;movereplaces memberships/classification. Moving a job does not change its frozen output target. - Asset DTO adds
folder_ids:string[]. Asset PATCH acceptsfolder_ids; upload multipart acceptsfolder_id; shared import optionally accepts{folder_id}while no-body calls remain valid. - Jobs add
folder_idandoutput_folder_id; drafts/stories addfolder_id; runs add both. Asset/job/story/workflow/run list endpoints acceptfolder_id: omitted/empty means all,unclassifiedmeans no category, otherwise an owned folder ID. - Submit accepts
folder_idandoutput_folder_id; omitted output inherits classification, explicit null selects unclassified. Candidate/batch-candidate, story render and workflow RunCreate acceptoutput_folder_id, defaulting to the draft's folder when omitted. Batch items carry the corresponding metadata on each item. - StoryCreate optionally accepts
folder_idandcreate_folder(default true). Omitted folder creates a unique same-name folder; explicit null orcreate_folder:falseopts out. Draft/Story PATCH acceptsfolder_id. - Output targets are persisted at submission; later draft moves do not alter queued destinations. Folder deletion falls back to unclassified during collection. Folder metadata never enters upstream model parameters or generation hashes. Legacy requests without the new fields preserve their idempotency fingerprints.
- New directory events are
folder.created,folder.updated,folder.deleted,folder.contents_changed; affected assets/jobs/stories/runs also use their existing update events. Machine directory access usesfolders:read/folders:write, separate from asset reads and task execution privileges. - Bulk publish/delete in the UI uses the existing per-asset endpoints, bounded to three concurrent calls, and reports individual failures. It does not bypass reference protection or change publication-copy behavior.
Shared assets
Shared publications are independent file and metadata snapshots, separate from private Asset DTOs. All logged-in users may read active publications, including their content and thumbnails. Shared content is read-only; import it before using it as a private job/workflow input. Bearer-token reads require assets:read; publish/import/withdraw require assets:write, and ownership still applies.
- POST
/assets/{id}/publish→ 201 SharedAsset, publishing only a caller-owned private asset. Optional body is absent or{}; extra fields are rejected. Repeating publication of a source with an active publication returns that existing snapshot. Editing/deleting the private source does not update/delete its publication. - GET
/shared-assets?page=1&page_size=24&q=&kind=&tag=&mine=false→{items:SharedAsset[],total,page,page_size}.mine=truerestricts to the caller's publications; page starts at1 and page_size is1–100. - GET
/shared-assets/{id}→ SharedAsset. - GET
/shared-assets/{id}/content→ authenticated inline content with Range support;?download=1downloads the snapshot. - GET
/shared-assets/{id}/thumbnail→ authenticated thumbnail, falling back to original content for an image without a separate thumbnail. - POST
/shared-assets/{id}/import→ 201 Asset. Optional body is absent or{}. Copies bytes into a new caller-owned private asset with a new asset ID,origin:'shared',source_job_id:null, andfavorite:false. The publication ID is not a valid private input ID. Each new import without replay creates an independent copy. - DELETE
/shared-assets/{id}→ 204, publisher-only, idempotent withdrawal. A publication not owned by the caller returns404. Withdrawal makes shared metadata/content unavailable to further reads/imports; unavailable publications return404 shared_asset_not_found. Existing private imports survive withdrawal and source deletion. - SharedAsset:
{id,name,kind:'image'|'video'|'audio'|'text'|'json',mime_type,size_bytes,width:null|number,height:null|number,duration_seconds:null|number,tags:string[],created_at:string,publisher_id,publisher_name,is_owner:boolean,version:number,preview_url,thumbnail_url:null|string,download_url}.idis the publication ID; media URLs use/api/shared-assets/{id}/.... This DTO omits private source asset/job IDs, hidden snapshot asset IDs, favorite state and storage paths.
Publish and import accept optional Idempotency-Key headers under operations assets.publish and shared.import. Reuse the same key for the same operation and source ID after a lost response; a changed source ID with that key returns 409 idempotency_conflict. Replaying assets.publish after its publication is withdrawn, or shared.import after its imported private asset is deleted, returns 410 resource_purged. Publication copies charge the publisher's storage budget; private imports charge the importer. Soft-deleted retained files still consume quota until physically collected. Copy operations can fail with 429 quota_exceeded or 503 storage_insufficient.
Record deletion and retention
The following commands are caller-owned soft archival, each returning 200 with {deleted:{job_ids:string[],run_ids:string[],draft_ids:string[],batch_ids:string[]}}; arrays describe the complete archived tree, including empty arrays. They accept optional If-Match: <version>, not a request body. An already archived owned root returns the same tree without a new archival action. Missing/foreign records return404; a non-archived root with a mismatched version returns 409 version_conflict.
| Command | Cascade and retained resources |
|---|---|
DELETE /jobs/{id} |
Archives an independent terminal job; all generated assets remain in its owner's private library |
DELETE /workflows/{id} |
Archives the draft, its runs and their child jobs; generated assets remain |
DELETE /workflow-runs/{id} |
Archives the run and its child jobs; preserves the draft and generated assets, clearing the draft's current-run pointer when applicable |
DELETE /batches/{id} |
Archives the batch, member runs and jobs; preserves workflow drafts and generated assets |
Archival removes resources from ordinary list/detail/control APIs while retaining audit rows. It releases obsolete job/input and snapshot references; it does not delete media or restore a cancelled run. The complete tree is validated before archival, so conflicts do not partially delete it.
409 parent_control_required: a job belongs to a run/batch, a run belongs to a batch, or a draft still has runs belonging to a live batch. Delete through the required parent; delete the related batch before its draft.409 deletion_requires_terminal: a non-archived member is still active. Cancel first, then wait for terminal state. Allowed job terminal states aresucceeded|failed|cancelled|timed_out; run terminal states aresucceeded|failed|cancelled; batch terminal states aresucceeded|cancelled|completed_with_errors.409 cleanup_pending: an execution has not reachedexitedorresults_ready. Wait for confirmed execution exit/cleanup, even if the business record is already terminal.409 resource_in_use: another live run still selects a job in the proposed deletion tree for reuse. Delete the dependent run first. Private asset deletion uses the separateasset_in_useerror above.GET /submissions/{key}?operation=...and replay of an archived record's original command return410 resource_purged. An old idempotency key cannot resurrect deleted records; intentionally creating new work requires a new submission.
Asset DELETE and shared withdrawal now remove the owned original/thumbnail files and hard-delete their Asset rows; withdrawal also removes the publication row. Independent published/imported copies survive. Missing files are accepted for retries, unsafe paths return 409 unsafe_asset_path, and filesystem failures return 503 asset_delete_failed without a false success; remaining DB rows allow retry. Active producers/consumers and unresolved executions return 409 asset_in_use. Legacy soft-deleted files retain the conservative dry-run-first maintenance GC path. Model caches and historical task audit records remain independently managed.
Jobs
MAX_INTERACTIVE_GPU_JOBS defaults to 0, which disables the per-owner unfinished interactive GPU queue cap. Direct submissions, standalone retries, workflow step retries and automatic workflow replenishment use the same rule. Positive values explicitly enable that optional cap; negative values are invalid. Creation-rate, total unfinished-job, storage and execution-resource limits still apply. This is not a lifetime video count or a GPU concurrency setting.
- POST
/jobs, optionalIdempotency-Key, body{task_type,input:{prompt?,negative_prompt?,image_asset_id?,audio_asset_id?,asset_id?,asset_ids?:string[]},parameters:object,count?:1..4,scheduled_at?:ISO8601|null}→{jobs:Job[]}. Batch only for image/defect; each gets its own independent upstream job. Composition clip order and trims live inparameters.clips:[{asset_id,start_seconds?,end_seconds?}], optionalaudio_asset_id,subtitles:[{start,end,text}], width/height/fps. Server resolves owned assets only. - GET
/jobs?page=1&page_size=24&task_type=&state=→{items:Job[],total,page,page_size,cursor:number}. - GET
/jobs/{id}→ Job. - POST
/jobs/{id}/cancel→ Job, cancellation may remain pending. - POST
/jobs/{id}/retry→{jobs:Job[]}(user requested new generation, new business ID). - Job:
{id,task_type,state,phase,version,prompt:string,parameters:object,input_asset_ids:string[],result_assets:Asset[],result:object|null,progress:number|null,queue_position:number|null,upstream_id:string|null,attempt_count:number,preemptions:number,last_preempted_reason:string|null,cancel_requested:boolean,error:null|{code,message,retriable},sync_warning:string|null,created_at:string,scheduled_at:string|null,started_at:string|null,finished_at:string|null}. - States:
scheduled,submitting,queued,running,collecting,cancelling,succeeded,failed,cancelled,timed_out. Remote sync failures do not invent terminal failures; set sync_warning. Requeue is the same job ID and may go running→queued. - Image defaults1024²/50 steps; video defaults1280×704/121frames/24fps/50steps, 1080p enhancement optional. Advanced field is exactly
num_inference_steps. Video accepts5–361 integer frames withnum_frames % 4 == 1, fixed24fps. The web duration input supports1–15 whole seconds and submits24 * seconds + 1frames; default5 seconds remains121 frames. A15-second native source contains361 frames (15.041667 seconds), not interpolated or slowed-down footage. No fake generation percentage. - ASR input accepts audio asset or video asset (CPU extract to owned WAV before upstream dispatch). Structure accepts image/video; result
subjects,scene,ocr,tags,frames?, timestamps reflect actual sampled frames. Math result{text}; ASR result{text,segments}; composition produces video asset.
Creation image and multi-person video editing
These use the existing POST /jobs, owner-scoped assets, idempotency keys and durable SSE events. No new business tables or public media paths. Generated Asset DTOs additionally expose source_output_index:number|null; map analysis previews by this index, never by current array position, since a preview may have been deleted independently.
image.reference.generate: input{prompt,negative_prompt?,reference_asset_ids:string[]}with 1–3 ordered, distinct private images. Parameters useprofile:'qwen-image-edit-2511-v1', sizes1024×1024/1280×704/704×1280, defaultsnum_inference_steps:40,guidance_scale:1,true_cfg_scale:4,max_sequence_length:1024,seed:42.count:1..4creates independent jobs with all reference images preserved. Profile/model mismatch or unavailable capability fails rather than falling back to text-only generation.video.people.analyze: input{video_asset_id}; parameters{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24}.countmust be1. Result{profile,analysis_token,source_sha256,video:{width,height,fps,frames,duration_seconds},poster_output_index,people:[{id,label,thumbnail_output_index,first_frame,last_frame,confidence,samples:[{frame,bbox:[x1,y1,x2,y2]}]}],warnings:[]}. Bbox coordinates are normalized0..1 against the display-oriented, square-pixel output; frame indexes start at0. Detection IDs are per-video tracks, not real identities.video.replace: input{video_asset_id,analysis_job_id,prompt,negative_prompt?,replacements:[{person_id,reference_asset_id,prompt?:string}]}. Globalpromptmust contain non-whitespace text; each selected person must be distinct and belong to that successful analysis. Parameters{profile:'wan-animate-replace-v1',max_pixels:399360,fps:24,num_inference_steps:20,guidance_scale:1,seed:42,preserve_audio:true,mask_expand_pixels:8,mask_feather_pixels:4}; both mask controls are integers0..64.countmust be1. Public Job.result includes{profile,person_ids,source_frames,output_frames,fps,width,height,warnings,final_output_indices}plus the private video asset. The frozen source hash, actor/reference mapping and upstream execution proof remain in internal persistence; the lower-level inference result additionally containsactor_mapping, source SHA and duration/audio parameters.
Analysis must be successful, active and owned by the caller, reference the identical source asset/hash and use matching profile/fps/max_pixels. The server resolves its trusted upstream analysis ID/token; clients cannot supply mask files, arbitrary paths or another owner's analysis. Every selected identity image is held as a job input reference. Video-stream timeline, not a longer container audio tail, determines duration admission and binding. Original audio duration is frozen independently and optionally remuxed; no voice/face identity guarantee or new audio synthesis is implied.
Default configurable video budgets are120seconds/12people/399360pixels;720p budget921600 is accepted only if both sides explicitly support it. Replacing multiple people runs temporal model passes sequentially within one job and combines their visible masks into one output while protecting other actors/background. Ambiguous tracking fails closed. Close/disconnect has no cancellation semantics; use the existing explicit cancel command and wait for process cleanup.
Events
- GET
/events?after=0authenticated EventSource.Last-Event-IDheader overrides query on reconnect. - Durable event:
id: <integer>\nevent: job.updated\ndata: {"job":Job}\n\n. - Other events:
asset.createddata{asset:Asset},asset.updatedsame;asset.deleted{id},resetasks client to refetch snapshots. Heartbeat comments do not change cursor. Stream owner-filtered; logout/expiry ends stream. - Record archival emits
job.deleted,workflow.deleted(a run),draft.deleted, andbatch.deleted, each with{id,version}. Cascades emit an event for each newly archived record. Treat these IDs as tombstones so delayed HTTP responses or older updates cannot reinsert deleted records; clear session state/tombstones on owner change. A surviving draft whose current run is deleted also receivesdraft.updated. - Fetch jobs snapshot and cursor before opening stream; after reconnection refresh HTTP state as well. Ignore Job versions older than or equal to the current version.
Backend provider interface
Implemented in app/providers.py and app/media.py, independent of database models.
Provider(settings) methods (async):
health() -> boolscheduler_status() -> dictsanitized Scheduler above.prepare_gpu_payload(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> dictvalidated original upstream payload{task_type,input,parameters,timeout_seconds}. Input paths must be within shared workspace. Preprocess video ASR as needed.submit(payload:dict,idempotency_key:str) -> dictoriginal upstream job response; retry only same immutable payload/key.query(upstream_id:str) -> dict,cancel(upstream_id:str) -> dict.download(upstream_id:str,index:int,destination:Path) -> Noneatomic streamed output, size bounded.run_cpu(task_type:str, inputs:dict, parameters:dict, assets:dict[str,Path], work_dir:Path) -> CpuResult.aclose() -> None.CpuResultdataclass:outputs:list[Path],result:dict,metadata:dict.ProviderError(code,message,retriable=False)has those attributes; no secret/path leaks in public messages.- Settings attributes consumed:
inference_base_url,inference_api_key,inference_api_key_file,workspace_root,asset_root,job_work_root,gpu_status_path,gpu_scheduler_path,qwen_base_url,qwen_model,qwen_api_key,ffmpeg_bin,ffprobe_bin,tts_base_url,tts_model,tts_api_key,request_timeout_seconds,max_output_bytes. app/media.py:inspect_media(path:Path,settings)->dict(kind,mime_type,width,height,duration_seconds);make_thumbnail(path:Path,destination:Path,settings)->Path|None. These are async, subprocess is fixed argv, bounded time/resources; no shell. Image validation can use Pillow. JSON/text generated outputs supported.capabilities(settings)->list[dict]returns exact DTO above. Optional speech is false unless real service configured; provider speech through OpenAI-compatible/audio/speechif selected later.
Production files live under /workspace/cmvr-visual. The website's business database is MySQL 192.168.28.10:3306/cmvr-visual; media originals/thumbnails live on the host at /data/llmusers/llmuser/workspace/cmvr-visual/assets, mounted as /workspace/cmvr-visual/assets. The inference service's SQLite is an independent GPU scheduling/recovery store, not the website business database. Database and media backups must be coordinated. These are operator deployment locations, not fields exposed in public resource DTOs.
Tests/explicit local preview use isolated configured roots, never implicitly access host files. CPU provider cancellation must kill/wait only its own subprocess. The coordinator supplies one task-private work directory per attempt.
V2 additions
HTTP remains the command/query channel, SSE the owner-scoped notification channel. execution_policy is returned by capabilities/status: {timezone:'Asia/Shanghai',start:'21:00',end:'08:00',batch_open,next_batch_at,close_behavior:'finish_current'}. The server accepts and persists batch commands all day; only new compute phases are gated. Current work is never killed by the clock or a browser disconnect.
- GET
/liveprocess liveness; GET/ready200/503 with database, coordinator, upstream_protocol and accepting checks. GPU capacity does not affect readiness. - User DTO adds
disabled,must_change_password; GET/PATCH/auth/users[/{id}]administer users, POST/auth/password{current_password,new_password}revokes sessions and requires relogin. - Session POST
/auth/username{username,current_password}→ current User DTO. The normalized login username must be unique and match 3–64 lowercase letters/digits/_.-; a correct current password is required. User ID, role, resources and existing sessions remain unchanged. Renaming the bootstrap administrator does not recreate the old administrator on restart. - User management requires a current administrator session and CSRF on writes. Disabling revokes browser sessions and suspends admission without deleting resources; re-enabling clears only
admin_suspendand preserves manual holds. Bearer access is denied while disabled. - Admin DELETE
/auth/users/{id}removes the account and its owned records, assets, thumbnails, publications and local job files, preserving independent copies imported by other users. It returns 204 only after cleanup. Active execution, upload or file writes first cause durable disable/cancel and 409cleanup_pending; retry after confirmed cleanup. Self-deletion is rejected. Unsafe paths return 409unsafe_user_path, foreign resource consumers return 409resource_in_use, and file failures return 503user_delete_failedwhile retaining the disabled account for retry. - GET/POST
/auth/tokens, DELETE/auth/tokens/{id}. POST{name,scopes,expires_at?}returns{token,record}once. UseAuthorization: Bearer ...for machine calls; tokens never grant admin authority. Interactive use additionally requiresinteractive:write. - POST
/jobsaddsexecution_mode:'interactive'|'batch'; new UI always persists and supplies an Idempotency-Key. GET list addsroot_only=trueto exclude workflow children. Job DTO addsrun_id,step_key,batch_id,batch_item_index,execution_mode,explicit_attempt,desired_state,hold_reasons,current_execution_id. States additionally includepaused,pausing,needs_attention. - POST
/jobs/{id}/retryhonors Idempotency-Key; legacy callers omitting it explicitly create a fresh attempt without replay guarantees. Parent-owned children require their parent retry/control APIs. - GET
/submissions/{key}?operation=jobs.create|jobs.retry|workflow.run|workflow.retry|workflow.pause|workflow.resume|workflow.cancel|batch.create|batch.control|assets.publish|shared.importrecovers owned resources. Replaying the original key and immutable JSON is safe after a lost response while its resources remain available; 404 alone does not prove an in-flight command was rejected. Archived resources return410 as specified above. - POST/GET
/workflows; GET/PATCH/workflows/{id}. PATCH requiresIf-Match: <version>. Draft edits increment revision; new Runs freeze a snapshot. - POST
/workflows/{id}/runs{draft_revision,expected_version,execution_mode?,reuse_run_id?}plus Idempotency-Key →{draft,run,steps,jobs,cursor}. GET/workflow-runsis paginated; GET/{id}returns the consistent snapshot. - POST
/workflow-runs/{id}/pause|resume|cancel{expected_version?}plus Idempotency-Key. Pause closes future admission and drains current work. Cancel remains pending until cleanup/completion is known. - POST
/workflow-runs/{id}/steps/{step_key}/retry{expected_run_version,target_job_id}plus Idempotency-Key retries only the selected failed step, preserving other successful shots and inherited mode/holds. - POST
/batches{name?,items:[{kind:'workflow',draft_id,draft_revision,expected_version}|{kind:'job',task_type,input,parameters?,count?}]}plus Idempotency-Key. Maximum100 items, fixedbatchmode, one active member per batch. GET list and/{id}snapshots; POST/{id}/control{desired_state:'run'|'pause'|'cancel',expected_version?}plus Idempotency-Key. - Asset list additionally accepts
favoriteandoriginSQL filters. Workflow references protect frozen inputs/outputs from physical deletion. - SSE adds
draft.updated:{draft},workflow.updated:{run,steps,jobs},batch.updated:{batch,items}with object versions. Ignore older/equal versions; reconnect/reset refreshes HTTP snapshots. Machine SSE requiresevents:readand Authorization, never tokens in URLs.
Legacy workflow spec schema1 remains exactly ordered shot_1,shot_2,shot_3, each {key,prompt,image_asset_id:null|string,parameters:{seed}}, with360 frames at24fps. Its serialization and generation hashes remain compatible.
Story studio v3 additions
Stories use independent /stories endpoints and WorkflowDraft.kind=story_v3; legacy /workflows excludes these records. The full field/endpoint contract is Story studio specification; executable usage is in API examples. MySQL revision005 adds visual_shot_candidates and append-only visual_shot_selections without changing historical001–004.
- The v3 spec contains story context, scenes, entities with forms/appearances, stable shot IDs and cast references, frame/video parameters, per-shot trim, and the existing audio/subtitle render settings. Plain JSON contains intent, never trusted approvals. PATCH uses
If-Match; commands freezeexpected_versionand an Idempotency-Key. - Reference inputs are the first-occurrence ordered unique private asset IDs. The compiled prompt binds Picture numbers and unique subject aliases to the same ordered files; forms/appearances name their owning subject.
image.reference.generaterequires the enabled identical profile at both API and upstream, accepts at most3 pictures by default, and never silently falls back. Explicit text mode removes the attached-picture instructions and actually sends no images. - Candidate DTO
input_summaryexposesreference_mode,actual_reference_asset_ids,model_profile,seed,promptand optionalfirst_frame_asset_id; it does not expose filesystem paths or credentials. Readiness and selection reject stale/missing/deleted/inaccessible results. Completion never selects a candidate automatically. - Generated video requires an approved current first frame; its requested source length is1–15seconds and must cover trim before dispatch. Manual video needs neither a frame nor a generation prompt, and checks its actual source independently of unused generation parameters. Start frame is nonnegative, each selected clip is24–360frames, final source bounds are verified against real decoded media.
- V3 Runs freeze the story and ordered selected asset/SHA/trim/audio/subtitle inputs and contain only a compose step. Historical Runs do not recompile current draft intent. Deleting a shot appends empty current selections while retaining prior approval audit; reintroducing its ID cannot resurrect old approvals.
- New owner events:
story.updated,candidate.updated,selection.updated. Reset/reconnect refetches complete loaded scopes with version/session/tombstone guards; it never resubmits generation. Machine-token scopes map stories andstory.*submission recovery toworkflows. - Pending candidate plans have separate owner/global budgets4000/16000; internal bounded admission uses existing active Job quotas. Creation/retry/render commands share the existing per-minute budget and immutable replay rules. No per-user8-video limit is introduced.
Schema2 accepts1–1000 sequentially ordered shot_N entries with additional duration_frames (strict integer24–360, default120). New submissions are additionally bounded by the operator's configured shot limit. profile=landscape_1080_v1|portrait_1080_v1; render={fps:24,total_frames?:integer,fit:'contain'|'cover',audio:null|{asset_id,source_start_ms,source_end_ms,offset_frame,short_policy:'silence'},subtitles:[{start_frame,end_frame,text}],template_version:'plain-v1'}. Omitted total_frames is derived from shots; a supplied unequal value fails validation. Each shot generates max(121, 4 * ceil(duration_frames / 4) + 1) source frames and composition trims to the requested frame count. A5/10/15-second workflow requests121/241/361-frame sources and produces720 final frames (30 seconds). Schema1 retains its original3×5-second contract. Audio must fit the entire dynamic timeline explicitly and subtitles use whole-film half-open frame intervals. Run total_steps is shot count+1, and steps/compose inputs follow snapshot order, including shot_10. New draft kind is multi_shot; three_shot remains accepted.
Capabilities and system/status include workflow_limits={max_shots,source_frames:121,default_source_frames:121,max_source_frames:361,default_clip_frames:120,max_clip_frames:360,fps:24} and execution_policy.batch_window_enabled, configuration_error, nullable next_batch_at. source_frames remains a legacy default; it is not the maximum. New snapshots freeze compiled.shot_generation_parameters keyed by shot; legacy snapshots without that map use their original frozen shared parameters. Long-source frame counts participate in reuse/retry semantic hashes, so a short source cannot satisfy a longer shot. Both API and GPU worker hot-read the operator-owned RUNTIME_POLICY_FILE (default /workspace/projects/llm-services/config/runtime-policy.json): {schema_version:1,batch_window_enabled:boolean,workflow_max_shots:integer1..1000}. Missing means production defaults; malformed policy blocks new batch compute. False bypasses only the clock/window, preserves durable clock evidence and all manual/maintenance/owner/GPU priority controls. Client payloads cannot override this switch. Already admitted work finishes when the switch is re-enabled.
Manual video.compose no longer has a24-clip or1800-second final-duration cap. New commands respect the same configured clip-count limit; source cuts stay within decoded media and a86400-second source bound. Output/intermediate size, storage, process and overall execution time budgets still apply.
Private inference protocol2 carries server-generated scheduling={execution_mode,principal_id,batch_id?,run_id?,step_key?,policy_version:'night-v1'}. Its /capabilities reports admission_pause/control_versions/final_output_indices. GPU result metadata identifies final enhanced output indices; workflows never choose the native intermediate by list order. Internal phase callbacks acquire separate new_gpu, cpu_media, qwen_http slots. No endpoint accepts arbitrary PIDs, Docker IDs, FFmpeg scripts or server filesystem paths from web users.
Editable production (007)
GET /editors/{draft_id} returns {draft_id,name,version,revision,manifest,issues,assets} for the current owner. A legacy draft is converted without writing. New editor writes require a live session, CSRF, transactional session recheck, and draft version CAS. Existing story spec writes/runs return409 editor_required while automatic mode is active; an explicit switch to manual permits the synchronized manual interfaces.
POST /editors/{id}/save{expected_version,manifest,name?}+ Idempotency-Key; server resolves private asset identities and SHA, reconstructs all draft references, and saves structurally valid authoring conflicts as issues. Optional name is trimmed, nonblank and at most255 characters; omitted/null keeps the existing name. Name and manifest commit atomically with one version increment.capabilities.name_edit=truedeclares support; old clients and old no-name idempotency receipts remain compatible. Historical Run inputs do not change when a draft is renamed.POST /editors/{id}/from-run{expected_version,run_id}+ key restores an owned same-draft frozen configuration and resolved assets; it is an explicit whole-version restore.POST /editors/{id}/plan{expected_version,output_goal:media|film,targets:[],force:[],execution_mode,output_folder_id?}returns{plan_hash,source_version,steps,issues}; no model executes.POST /editors/{id}/runsaddsexpected_plan_hashand an idempotency key;202 returns RunSnapshot. The server recompiles the plan under the acceptance transaction. Binding targets useframe:<stable_id>,video:<stable_id>,audio:<segment_id>, plusscript/captions. Fresh seeds are accepted once; retries preserve frozen inputs.POST /editors/{id}/apply{expected_version,run_id}+ key only accepts a succeeded Run whose source draft version still matches. A stale result is preserved and returns a conflict, rather than replacing later edits.
The independent editor_manifest.schema_version=1 contains source spec, stable shot IDs, private asset bindings, audio mode/segments and caption cues. Old workflow/story schemas remain1/2/3. Incoming manual bindings may omit SHA; persisted bindings always use server facts. Text and timing overrides are independent. Final composition alone projects relative cue anchors to existing24fps absolute subtitles and a single selected audio track.
Auto runs use story_auto/workflow_auto, target-driven typed Steps and direct Jobs; they do not write manual ShotSelection/ShotCandidate. output_goal=media publishes target assets without changing the film pointer. film requires compose success. Source and step-input snapshots remain immutable, result_manifest records resolved editable results, and apply_state=conflict leaves subsequent authoring untouched. Output references belong independently to each draft/run; reuse points to asset+SHA, not an old selected Job.
New CPU tasks: text.script.generate uses the shared Qwen HTTP resource pool and returns per-shot JSON; audio.assemble consumes owned segments at frame offsets, normalizes48kHz and writes an exact-length WAV. audio.speech supports an optional frozen model check and independent timeouts. Speech health only confirms configured/reachable protocol; it does not certify model quality. Unknown execution outcomes remain blocked until reconciled.
Stories support reversible editing modes without a schema migration. EditorManifest.editing_mode is auto|manual (existing manifests default to auto; drafts without a manifest are manual). StoryDTO and EditorDTO expose editing_mode and capabilities.mode_switch. POST /editors/{id}/mode accepts {expected_version,mode} with session/CSRF and Idempotency-Key (editor.mode), and returns EditorDTO plus the complete authoritative story. Only story_v3 is supported. The command checks owner, CAS and unresolved work, advances the draft version, and retains the manifest and run history. Auto bindings become unapproved manual candidates with provenance; no approval is fabricated. Manual PATCH/confirm/clear synchronize the manifest and references. Auto-only writes reject manual mode; callers cannot change modes by posting a manifest field. Legacy first editor.save remains compatible but checks idle work before conversion.
New automatic story composition inputs freeze decoded source width, height, fps and source frame count, plus the selected audio SHA. Historical inputs missing video dimensions are executed by verifying the frozen video SHA before deriving missing dimensions from those exact bytes; stored Job/Step inputs remain unchanged. Existing dimension, fps, duration and SHA conflicts still reject execution.