diff --git a/docs/development/lessons.md b/docs/development/lessons.md index a49f2f31a..a3d2db4e0 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -54,6 +54,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Assistant completion follow-up:** [PR #465's browser run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45526547494/job/138913562926) read a saved reply while the Agent still held its write lease. The assistant panel test must wait for both the reply's final status and removal of the active turn ID. Delaying lease release reproduced the failure on the upstream baseline. - **Shared model catalog follow-up:** [Nightly run 45309310680](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45309310680/job/138160760923) reached the empty-video-selector test after an earlier script saved a video model. A new page still reads the shared server's catalog. For a UI test of an empty category, scope that catalog response to the test page and verify the flow with a model already present on the shared server. +- **Shared composer follow-up:** [PR #529's voice library check](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/45865822618/job/140084924197) timed out when a save refreshed the audio draft and dropped its image-only preset default. A shared panel was closed by the preset's reset effect. Scope panel resets to the state the panel owns, and exercise a save while the panel is open in another media mode. ## A pending checkpoint can race with accepted cancellation @@ -114,7 +115,11 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Lesson:** A timer may run after the editor's saving flag clears but before React installs the new document. Comparing that old closure against the new baseline can turn a view-only save into a business rollback, invalidating a previously captured publication version. - **Check:** Invalidate scheduled automatic callbacks when the editor transaction starts, drain queued saves and explicitly persist the current draft before the edit. Preserve publication CAS checks. Exercise the real due callback at the acknowledgment boundary; isolate projection-test gates by snapshot identity, assert release/restoration and always clean up. Distinguish a forced reproduction from proof of the exact CI schedule. - **Queued-edit follow-up:** The H3 browser regression in [PR #266](https://github.com/ThinkFlowLab/OpenDirector/pull/266) holds the first import's background hydration until the second import queues an edit. A ref updated during render can still describe the old document; a late refresh then replaces both nodes with one. Track requested and rendered history writes, defer refreshes while they differ, and recheck when hydration finishes. Resume after a no-op write too. Verify both saved nodes, their bytes, and subsequent edits after reopening. / **排队编辑补充:** React 尚未显示的编辑也需要保护;后台刷新必须检查已经请求的修改,并在页面更新后继续。回归检查两张图片的保存内容及重开后的编辑,不能把人工控制的执行顺序当作原 CI 顺序的证明。 - +- **Preset editor follow-up:** Selecting an image preset used to queue a settings edit and a prompt-chip edit that still held the old settings. Render the chip from the saved preset and publish preset changes caused by prompt editing in the same command as the prompt. Check the saved parameters after autosave and reopening. Chrome can move the caret past a wrapped hint through native mouse-down selection. Verify the caret's rendered position after the chip with a visible multiline hint before releasing the button. Check that typing replaces the hint, retains the first character and saves only the user's text. +- **Preset submission follow-up:** Treat the selected preset as a prompt in both the button preflight and the generation service. Freeze its instructions in the accepted job, since updating only the draft's plain prompt can be ignored by structured references and can duplicate instructions on a second run. Check preset-only submission, the structured provider prompt, and adoption without modifying the draft. +- **Image preset prompt variants:** Use the resolved image inputs to choose between image-guided and text-guided instructions. Publish both variants so the preview can make the same choice from usable references. Check that enabling face emphasis and adding or removing the last image change both the preview and the submitted prompt. Keep the ordered steps of multi-shot presets in both variants. +- **Four-view cropping:** A frozen face-emphasis prompt proves the setting reached the provider, while visual compliance still requires reviewing the generated image. Put the crop before appearance guidance and scope it to the first two columns. Specify a separate scale and headroom for the full back view. Check both a text-only subject and a reference with a less obvious neck. +- **Reference medium:** Explicit photography wording corrected a photograph but turned an illustrated reference into a live-action portrait. Treat the layout as composition only and use medium-neutral framing language. Verify style changes against a photo and an illustration. ## An upstream response and a consumer finishing it are separate facts diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index c645007c3..7b45efc73 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -27,6 +27,7 @@ from opendirector.domain.creation.models import ModelConfigPublic, ModelSnapshot from opendirector.domain.creation.project import ProjectSnapshot from opendirector.domain.creation.validation import ContractError +from opendirector.domain.image_presets import preset_prompt from opendirector.domain.input_rules import input_rules from opendirector.domain.minimax_speech import is_minimax_speech from opendirector.domain.projects import ProjectError @@ -93,6 +94,15 @@ def new_seed(): return secrets.randbelow(2**31) +def transmitted_assets(references): + """Keep the first transmitted binding for each asset, in request order.""" + assets = {} + for reference in references: + if reference.transmission != 'context_only': + assets.setdefault(reference.asset.assetId, reference) + return assets + + class CreationGeneration(GenerationRuntime): def __init__(self, projects, configs, provider=None, *, availability=None): super().__init__() @@ -118,7 +128,7 @@ def task(self, job): # Project accepted jobs without revalidating the current speech catalog. profile = 'minimax-speech' if is_minimax_speech(config) else input_rules(config)['profile'] assets = {a.id: a for a in self.projects.snapshot(job.projectId).assets} - reference_ids = list(dict.fromkeys(str(r.asset.assetId) for r in job.inputSnapshot.references if r.transmission != 'context_only')) + reference_ids = [str(asset_id) for asset_id in transmitted_assets(job.inputSnapshot.references)] content = None kling_content = None if spec.promptContent is not None: @@ -138,13 +148,19 @@ def task(self, job): content.append(rendered) if kling_content is not None: kling_content.append({**rendered, 'referenceId': str(ref.referenceId), 'subjectRole': ref.subjectRole}) + prompt = spec.prompt + if job.inputSnapshot.presetPrompt: + prefix = job.inputSnapshot.presetPrompt + prompt = f'{prefix}\n\n{prompt}' if prompt.strip() else prefix + if content is not None: + content.insert(0, dict(type='text', text=prefix + ('\n\n' if content else ''))) adapter_content = {} if model.protocol != 'kling_video' else dict(klingPromptContent=kling_content, klingReferences=[dict(assetId=str(r.asset.assetId), role=r.role, referenceId=str(r.referenceId), subjectRole=r.subjectRole) for r in job.inputSnapshot.references if r.transmission != 'context_only']) return dict(schemaVersion=1, id=str(job.id), projectId=str(job.projectId), nodeId=str(job.originItemId or spec.id), kind=spec.kind, status=job.status, phase=job.phase, recovery=job.recovery, resumeAllowed=job.resumeAllowed, modelConfigId=str(model.modelConfigId), model=model.modelId, baseURL=model.url, protocol=model.protocol, - title=spec.prompt[:80] or spec.kind, prompt=spec.prompt, promptContent=content, referenceIds=reference_ids, + title=spec.prompt[:80] or spec.kind, prompt=prompt, promptContent=content, referenceIds=reference_ids, referenceRoles=[{'assetId': str(r.asset.assetId), 'role': r.role} for r in job.inputSnapshot.references if r.transmission != 'context_only'], referenceInputs={'profile': profile}, videoMode=spec.parameters.videoMode if spec.kind == 'video' else 'first_frame', parameters=job.adapterParameters, @@ -414,9 +430,15 @@ def accept(before): if reference.transmission != 'context_only': self.assets.reference_available(command.projectId, reference.asset.assetId) self.provider.validate(spec.kind, config) + preset = preset_prompt( + spec.parameters.preset, spec.parameters.faceEmphasis, + tuple(reference.sourceTitle or reference.name for reference in transmitted_assets(resolved).values() + if reference.asset.kind == 'image'), + ) if spec.kind == 'image' else None snapshot = InputSnapshot(spec=spec.model_copy(update={'currentResultId': None}), model=ModelSnapshot(modelConfigId=public.id, inputRules=public.inputRules, - **{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), references=resolved) + **{k: getattr(public, k) for k in ('kind', 'modelId', 'url', 'protocol', 'connectionType', 'proxyMode', 'videoAdapter')}), + references=resolved, presetPrompt=preset) # Use the same rendering, protocol validation and parameter resolver # as the established adapters, with immutable media from the facade. stub = Job(id=uuid5(command.commandId, 'job'), projectId=command.projectId, inputSnapshot=snapshot, @@ -553,7 +575,8 @@ def apply(current, asset): projected_spec, references = current_generation_inputs(current, current_spec, current_job.inputSnapshot.model.inputRules) effective = execution_spec(projected_spec, references, current_job.inputSnapshot.model.inputRules) now = InputSnapshot(spec=effective.model_copy(update={'purpose': 'generation', 'currentResultId': None}), - model=current_job.inputSnapshot.model, references=references) + model=current_job.inputSnapshot.model, references=references, + presetPrompt=current_job.inputSnapshot.presetPrompt) eligible = eligible and now.fingerprint() == current_job.inputFingerprint except (ValueError, ContractError): eligible = False diff --git a/packages/core/src/opendirector/application/tool_image_edits.py b/packages/core/src/opendirector/application/tool_image_edits.py index 12cfb4cd5..679906361 100644 --- a/packages/core/src/opendirector/application/tool_image_edits.py +++ b/packages/core/src/opendirector/application/tool_image_edits.py @@ -1,10 +1,10 @@ """Image edit recipes: reframing, cleanup, presets, and poster motion.""" import json -from dataclasses import dataclass from PIL import Image from opendirector.application.tool_context import Output, ToolContext, _source_image, _with, image_output +from opendirector.domain.image_presets import PRESETS, preset_instructions from opendirector.domain.projects import ProjectError from opendirector.media import processing as media @@ -168,71 +168,12 @@ async def panorama(ctx: ToolContext): edge = {'4K': 4096, '2K': 2048}.get(ctx.parameters.get('resolution'), 2048) return [image_output(media.resize(result, edge, edge // 2), '720 全景')] -@dataclass(frozen=True) -class ImagePreset: - title: str - prompts: tuple[str, ...] - size: tuple[int, int] = (2048, 1152) - -PRESETS = { - # Written as edit instructions: editing models follow imperatives, not captions. - 'three-view': ImagePreset('人物三视图', ( - '以参考图中的人物为唯一身份依据,生成同一人物的全身三视图设定板。' - '横版画面分为三个等宽区域,从左至右严格排列:正面全身、右侧90度全身、背面全身。' - '三个视图保持同一身份、年龄、体型、头身比、发型、服装、配色、材质及配饰,衣服结构与细节相互对应。' - '全部自然站立、双臂放松,同一高度与地面基线,完整呈现头顶到鞋底,不裁头、不切脚、不遮挡、不重叠。' - '若原图仅有半身,依据可见服装合理补全下半身,补全部分在三个视角保持一致。' - '保持参考图画风,纯净浅灰背景、均匀柔光、弱透视,无剧情场景、文字、标签、水印、分割线或额外视图。',)), - 'four-view': ImagePreset('人物四视图', ( - '根据参考图生成一张同一人物的横版四视图设定板。' - '从左到右依次为正面全身、右侧90度全身、背面全身、正脸特写,四个视图并排分开。' - '前三格自然站立,头顶到鞋底完整,同一比例与地面基线;最右格只展示正面头肩,清楚呈现正脸。' - '各视图保持同一人物、发型、服装和配饰。若参考图只展示半身,合理补全下半身并保持一致。' - '保持参考图画风、浅灰背景、均匀柔光,无文字、分割线、水印或额外视图。',), (3456, 1152)), - 'face-three-view': ImagePreset('面部三视图', ( - '以参考图人物的面部为唯一身份依据,生成同一人物的面部三视图参考板。' - '3:1超宽横版画面均分为三个等宽区域,从左至右严格排列:正面、左侧90度、右侧90度。' - '第二格(左侧90度)鼻尖朝向画面右方,第三格(右侧90度)鼻尖朝向画面左方;' - '两张侧脸朝向相反、左右镜像对称,不要输出两张朝向相同的侧脸。' - '每个区域只放一个居中的头肩像,三个头像之间留有自然间隔,不接触、不重叠、不粘连。' - '每个视图只呈现完整头部至肩颈,头顶、下巴、耳朵均完整,不出现背面或全身视图。' - '保持同一身份、年龄、脸型、骨相、五官比例、肤色、发际线、发型及识别性细节,左右侧面符合真实结构。' - '三个头部大小一致、眼睛基线对齐、中性表情、视线随朝向自然变化,面部不被头发遮挡。' - '保持参考图画风、纯净浅灰背景、均匀柔光,无美颜改脸、夸张透视、文字、标签、水印或额外人物。',), (3456, 1152)), - 'product-three-view': ImagePreset('产品三视图', ( - '以参考图中的产品为唯一设计依据,生成同一产品的工业设计三视图参考板。' - '横版画面分为三个等宽区域,从左至右严格排列:正视图、右侧90度侧视图、后视图。' - '采用近正交投影、无广角畸变,同一比例尺、同一高度与底部基线,完整展示产品外轮廓,不裁切、不重叠。' - '三个视图保持结构、尺寸关系、材质、颜色、表面纹理、接口、按钮、接缝及标识一致,细节在视角之间符合物理对应关系。' - '不可见部位依据已知结构作合理且一致的补全,不增加功能件或改变产品设计。' - '产品独立展示,纯白背景、均匀棚拍光,无人物、手、包装道具、剧情场景、说明文字、尺寸标注、水印或额外视图;保留原有品牌标识。',)), - 'storyboard': ImagePreset('连续分镜图', ('把镜头拉远成远景建立镜头,完整交代周围环境,主体在画面中较小', - '改为中景镜头,主体占画面一半高度,动作清晰', - '改为近景镜头,镜头推近到主体胸口以上,突出表情', - '改为特写镜头,只拍主体面部或关键细节,背景虚化')), - 'multi-camera': ImagePreset('多机位', ('把机位移到主体正前方,平视拍摄', - '把机位向左绕到主体左前方约45度,从左侧斜角拍摄,透视随之改变', - '把机位向右绕到主体右前方约45度,从右侧斜角拍摄,透视随之改变', - '把机位升高到主体上方,高角度俯拍')), -} - -FOUR_VIEW_FACE_EMPHASIS = ( - '根据参考图生成同一人物的横版四格设定板,四张独立取景的照片从左到右并排。' - '第一格为正面、第二格为右侧90度。两格都降低取景范围,画框上缘正好切在下巴下沿,' - '脖子从顶边进入画面,从颈部一直拍到鞋底;下巴以上完全在画框外。' - '前两格顶边紧贴颈部,不在颈部上方留空;保持平直透视,不仰拍,不用面罩。' - '第三格拍完整的背面全身,从头顶到鞋底。第四格拍清晰的正脸头肩特写,保留参考人物的完整五官。' - '保持同一人物、体型、发型、服装、配饰和参考图画风。若参考图只展示半身,合理补全下半身并保持一致。' - '浅灰背景、均匀柔光,无文字、分割线、水印或额外视图。' -) - async def image_presets(ctx: ToolContext): image = _source_image(ctx) key = ctx.choice('preset', PRESETS) preset = PRESETS[key] - title, prompts = preset.title, preset.prompts - if key == 'four-view' and ctx.parameters.get('faceEmphasis') is True: - prompts = (FOUR_VIEW_FACE_EMPHASIS,) + title = preset.title + prompts = preset_instructions(key, ctx.parameters.get('faceEmphasis') is True) outputs = [] for index, instruction in enumerate(prompts, 1): await ctx.progress(f'正在生成{title}({index}/{len(prompts)})') diff --git a/packages/core/src/opendirector/application/tool_image_inputs.py b/packages/core/src/opendirector/application/tool_image_inputs.py index 4ada84de0..660add0d3 100644 --- a/packages/core/src/opendirector/application/tool_image_inputs.py +++ b/packages/core/src/opendirector/application/tool_image_inputs.py @@ -78,7 +78,7 @@ def image_execution(tool, parameters, source, *, has_mask, has_annotation, polic edge = {'4K': 4096, '2K': 2048}.get(parameters.get('resolution'), 2048) candidate = (width, height) != original and (width, height) == (edge, edge // 2) elif tool == 'image-presets': - from opendirector.application.tool_image_edits import PRESETS + from opendirector.domain.image_presets import PRESETS preset = PRESETS.get(parameters.get('preset')) if preset is not None: width, height = preset.size diff --git a/packages/core/src/opendirector/application/tool_operations.py b/packages/core/src/opendirector/application/tool_operations.py index e48333d5b..96e0d83b6 100644 --- a/packages/core/src/opendirector/application/tool_operations.py +++ b/packages/core/src/opendirector/application/tool_operations.py @@ -9,10 +9,11 @@ from opendirector.application.tool_context import Output, Source, ToolContext from opendirector.application.tool_image_edits import ( - PRESETS, dynamic_poster, image_hd, image_presets, inpainting_remove, lighting, multi_size, + dynamic_poster, image_hd, image_presets, inpainting_remove, lighting, multi_size, outpaint, panorama, product_replacement, smart_edit, view_control, ) from opendirector.application.tool_image_segments import cutout, layer_decompose, select_image_objects +from opendirector.domain.image_presets import PRESETS, preset_instructions from opendirector.application.tool_video_recipes import ( AUDIO_MODES, audio_separation, depth_capture, mask_composite, frame_interpolation, partial_reshoot, subtitle_erasure, video_edit, video_matting, video_upscale, @@ -44,6 +45,22 @@ def _select(key, label, options, default=None, required=True): value['default'] = default return value + +def _preset_select(): + """Preset options plus the instructions, so the composer can apply the same + text as a prompt skill instead of keeping a second copy in the frontend.""" + options = [] + for key, value in PRESETS.items(): + option = {'value': key, 'label': value.title, 'prompts': list(value.prompts), + 'textPrompts': list(value.text_prompts), 'size': list(value.size)} + if key == 'four-view': + option['textPrompt'] = value.text_prompts[0] + option['faceEmphasisPrompt'] = preset_instructions(key, True)[0] + option['faceEmphasisTextPrompt'] = preset_instructions(key, True, has_reference=False)[0] + options.append(option) + return {'key': 'preset', 'label': '预设', 'type': 'select', 'required': True, 'default': 'three-view', + 'options': options} + TOOLS: dict[str, ToolSpec] = {item.id: item for item in [ ToolSpec('smart-edit', ('image',), _needs('image.edit'), smart_edit), ToolSpec('outpaint', ('image',), _needs('image.edit'), outpaint), @@ -59,7 +76,7 @@ def _select(key, label, options, default=None, required=True): ToolSpec('panorama', ('image',), _needs('image.edit'), panorama, (_select('resolution', '清晰度', [('2K', '2K'), ('4K', '4K')], '2K'),)), ToolSpec('image-presets', ('image',), _needs('image.edit'), image_presets, - (_select('preset', '预设', [(key, value.title) for key, value in PRESETS.items()], 'three-view'), + (_preset_select(), {'key': 'faceEmphasis', 'label': '脸部强调', 'type': 'boolean', 'required': False})), ToolSpec('multi-size', ('image',), _needs('image.edit'), multi_size), ToolSpec('product-replacement', ('image',), _needs('image.edit'), product_replacement), diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 74175b7ea..513c705e7 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -8,6 +8,7 @@ from pydantic import Field, JsonValue, model_validator from opendirector.domain.minimax_models import MINIMAX_MODELS +from opendirector.domain.image_presets import PRESETS from opendirector.domain.projects import ProjectError from opendirector.domain.generation import GenerationFailure, ResultCheck from opendirector.domain.projects import ProjectError @@ -32,7 +33,10 @@ class ImageParameters(Contract): description='Image rendering quality; auto leaves the provider request unchanged.') size: str = Field(default='auto', pattern=r'^(?:auto|2K|[1-9]\d{2,3}x[1-9]\d{2,3})$', description='Requested image dimensions or size preset.') aspectRatio: str | None = Field(default=None, pattern=r'^[1-9]\d?:[1-9]\d?$', description='Output width-to-height ratio.') - preset: Literal['none', 'product-views'] = Field(default='none', description='Selected generation or motion preset.') + preset: str = Field(default='none', pattern=r'^(?:none|product-views|[a-z0-9-]{1,40})$', + description='Selected generation or prompt-skill preset.') + faceEmphasis: bool = Field(default=False, exclude_if=lambda value: not value, + description='Preset alternate framing that emphasises the face.') responseFormat: Literal['url'] = Field(default='url', description='Provider response representation.') outputFormat: Literal['png'] = Field(default='png', description='Generated image encoding.') @@ -198,6 +202,8 @@ class InputSnapshot(Contract): spec: GenerationSpec = Field(description='Generation configuration for this operation.') model: ModelSnapshot = Field(description='Fixed model configuration for this execution.') references: tuple[ResolvedReference, ...] = Field(default=(), description='Ordered generation reference bindings.') + presetPrompt: str | None = Field(default=None, exclude_if=lambda value: value is None, + description='Image preset instructions frozen when the job is accepted.') @model_validator(mode='after') def identity(self): @@ -393,7 +399,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc 'profile': model.inputRules.profile, 'hasMedia': any(ref.transmission != 'context_only' and ref.asset.kind in {'image', 'video', 'audio'} for ref in references), }) - if not written and not implicit_text_prompt(spec, references) and not optional_prompt: + has_preset = spec.kind == 'image' and spec.parameters.preset in PRESETS + if not written and not has_preset and not implicit_text_prompt(spec, references) and not optional_prompt: raise ValueError('请填写生成提示词。') rules = model.inputRules if rules.referencesAllowed is False and references: @@ -445,7 +452,8 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc from opendirector.domain.image_output import resolve_image_output if spec.parameters.quality != 'auto' and spec.parameters.quality not in (rules.imageQualities or ()): raise ProjectError('当前模型不支持所选图片质量,请选择自动或切换模型。', 422, code='image_quality_unsupported') - if spec.parameters.preset != 'none': + # Only the legacy service-side preset is unsupported here. + if spec.parameters.preset == 'product-views': raise ValueError('当前服务不支持产品三视图预设,请使用自由创作。') resolve_image_output(model.model_dump(), rules.model_dump(), spec.parameters.model_dump()) if spec.kind == 'audio' and rules.profile == 'vllm-omni-music': diff --git a/packages/core/src/opendirector/domain/image_presets.py b/packages/core/src/opendirector/domain/image_presets.py new file mode 100644 index 000000000..2eadb11b4 --- /dev/null +++ b/packages/core/src/opendirector/domain/image_presets.py @@ -0,0 +1,153 @@ +"""Shared image preset instructions for tools and generation jobs.""" +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ImagePreset: + title: str + prompts: tuple[str, ...] + text_prompts: tuple[str, ...] + size: tuple[int, int] = (2048, 1152) + + +THREE_VIEW_LAYOUT = ( + '横版画面分为三个等宽区域,从左至右严格排列:正面全身、右侧90度全身、背面全身。' + '三个视图保持同一身份、年龄、体型、头身比、发型、服装、配色、材质及配饰,衣服结构与细节相互对应。' + '全部自然站立、双臂放松,同一高度与地面基线,完整呈现头顶到鞋底,不裁头、不切脚、不遮挡、不重叠。' +) +THREE_VIEW_FINISH = ( + '纯净浅灰背景、均匀柔光、弱透视,无剧情场景、文字、标签、水印、分割线或额外视图。' +) +FOUR_VIEW_LAYOUT = ( + '从左到右依次为正面全身、右侧90度全身、背面全身、正脸特写,四个视图并排分开。' + '前三格自然站立,头顶到鞋底完整,同一比例与地面基线;最右格只展示正面头肩,清楚呈现正脸。' + '各视图保持同一人物、发型、服装和配饰。' +) +FOUR_VIEW_FINISH = '浅灰背景、均匀柔光,无文字、分割线、水印或额外视图。' +FOUR_VIEW_TEXT_SUBJECT = ( + '按提供的文字描述确定人物的外貌、服装与画风。未描述的细节自行设计,并在四个视图保持一致。' +) +FOUR_VIEW_TEXT = ( + '生成一张同一人物的横版四视图设定板。' + FOUR_VIEW_TEXT_SUBJECT + + FOUR_VIEW_LAYOUT + FOUR_VIEW_FINISH +) +FACE_THREE_VIEW_LAYOUT = ( + '3:1超宽横版画面均分为三个等宽区域,从左至右严格排列:正面、左侧90度、右侧90度。' + '第二格(左侧90度)鼻尖朝向画面右方,第三格(右侧90度)鼻尖朝向画面左方;' + '两张侧脸朝向相反、左右镜像对称,不要输出两张朝向相同的侧脸。' + '每个区域只放一个居中的头肩像,三个头像之间留有自然间隔,不接触、不重叠、不粘连。' + '每个视图只呈现完整头部至肩颈,头顶、下巴、耳朵均完整,不出现背面或全身视图。' + '保持同一身份、年龄、脸型、骨相、五官比例、肤色、发际线、发型及识别性细节,左右侧面符合真实结构。' + '三个头部大小一致、眼睛基线对齐、中性表情、视线随朝向自然变化,面部不被头发遮挡。' +) +FACE_THREE_VIEW_FINISH = '纯净浅灰背景、均匀柔光,无美颜改脸、夸张透视、文字、标签、水印或额外人物。' +PRODUCT_THREE_VIEW_LAYOUT = ( + '横版画面分为三个等宽区域,从左至右严格排列:正视图、右侧90度侧视图、后视图。' + '采用近正交投影、无广角畸变,同一比例尺、同一高度与底部基线,完整展示产品外轮廓,不裁切、不重叠。' + '三个视图保持结构、尺寸关系、材质、颜色、表面纹理、接口、按钮、接缝及标识一致,细节在视角之间符合物理对应关系。' +) +PRODUCT_THREE_VIEW_FINISH = ( + '产品独立展示,纯白背景、均匀棚拍光,无人物、手、包装道具、剧情场景、说明文字、尺寸标注、水印或额外视图' +) +STORYBOARD_SHOTS = ( + '远景建立镜头,完整交代环境,主体在画面中较小。', + '中景呈现同一主体的动作,主体占画面约一半高度。', + '近景推到主体胸口以上,突出表情或主体的主要特征。', + '特写呈现面部或关键细节,背景虚化。', +) +MULTI_CAMERA_ANGLES = ( + '主体正前方,平视拍摄。', + '主体左前方约45度,从左侧斜角拍摄。', + '主体右前方约45度,从右侧斜角拍摄。', + '主体上方,高角度俯拍。', +) + + +PRESETS = { + 'three-view': ImagePreset('人物三视图', ( + '以参考图中的人物为唯一身份依据,生成同一人物的全身三视图设定板。' + + THREE_VIEW_LAYOUT + + '若原图仅有半身,依据可见服装合理补全下半身,补全部分在三个视角保持一致。保持参考图画风,' + + THREE_VIEW_FINISH, + ), ( + '按文字描述设计同一人物的全身三视图,未描述的外貌、服装或画风自行设计并保持一致。' + + THREE_VIEW_LAYOUT + THREE_VIEW_FINISH, + )), + 'four-view': ImagePreset('人物四视图', ( + '根据参考图生成一张同一人物的横版四视图设定板。' + + FOUR_VIEW_LAYOUT + + '若参考图只展示半身,合理补全下半身并保持一致。保持参考图画风、' + + FOUR_VIEW_FINISH, + ), (FOUR_VIEW_TEXT,), (3456, 1152)), + 'face-three-view': ImagePreset('面部三视图', ( + '以参考图人物的面部为唯一身份依据,生成同一人物的面部三视图参考板。' + + FACE_THREE_VIEW_LAYOUT + '保持参考图画风、' + FACE_THREE_VIEW_FINISH, + ), ( + '按文字描述设计同一个人的面部三视图,未描述的五官、发型与画风自行设计并保持一致。' + + FACE_THREE_VIEW_LAYOUT + FACE_THREE_VIEW_FINISH, + ), (3456, 1152)), + 'product-three-view': ImagePreset('产品三视图', ( + '以参考图中的产品为唯一设计依据,生成同一产品的工业设计三视图参考板。' + + PRODUCT_THREE_VIEW_LAYOUT + + '不可见部位依据已知结构作合理且一致的补全,不增加功能件或改变产品设计。' + + PRODUCT_THREE_VIEW_FINISH + ';保留原有品牌标识。', + ), ( + '按文字描述设计同一产品的工业设计三视图。未描述的结构、配色与材质按用途合理设计,不虚构品牌标识。' + + PRODUCT_THREE_VIEW_LAYOUT + PRODUCT_THREE_VIEW_FINISH + '。', + )), + 'storyboard': ImagePreset('连续分镜图', + tuple('保持参考图的主体、环境和画风。' + shot for shot in STORYBOARD_SHOTS), + tuple('按文字描述建立同一场景与主体,未描述处自行设计,四个镜头保持人物、服装、环境与光线连续。' + shot + for shot in STORYBOARD_SHOTS)), + 'multi-camera': ImagePreset('多机位', + tuple('保持参考图的主体、环境和光线,按指定机位调整透视和遮挡。' + angle for angle in MULTI_CAMERA_ANGLES), + tuple('按文字描述设计主体和场景,未描述处自行补全。各机位保持主体、动作、空间布局和光线一致。' + angle + for angle in MULTI_CAMERA_ANGLES)), +} + +FOUR_VIEW_FACE_LAYOUT = ( + '同一角色的四格横排设定板,每格独立取景。\n' + '第1格:正面身体,肩颈交界至脚底。第2格:右侧90度身体,肩颈交界至脚底。' + '这两格以身体与服装为主,双脚完整。' + '正面和侧面都将眼睛、鼻子和嘴留在画外。\n' + '第3格:从头顶到鞋底的背面全身,人物缩小到完整后脑勺和双脚都在格内,头顶上方留空。\n' + '第4格:唯一可见五官的正脸头肩特写。\n' + '四格保持同一角色的体型、配色和装束。' +) +FOUR_VIEW_FACE_EMPHASIS = ( + '保持上传参考图的原始成像方式与画风。' + '四格认真还原原图的材质纹理、细节密度、轮廓边缘、光影与用色,不作风格转换。\n' + + FOUR_VIEW_FACE_LAYOUT + + '\n设定板只规定排版和取景。改变视角、取景范围与背景,人物始终保持参考图原有的视觉质感。\n' + + '保持参考图原有造型和服装,不添加参考图中没有的衣物、鞋帽和配饰。' + + '若参考图只展示半身,合理补全下半身并保持一致。' + + FOUR_VIEW_FINISH +) +FOUR_VIEW_FACE_TEXT = ( + FOUR_VIEW_FACE_LAYOUT + FOUR_VIEW_TEXT_SUBJECT + FOUR_VIEW_FINISH +) + + +def preset_instructions(key: str, face_emphasis: bool, *, has_reference: bool = True) -> tuple[str, ...]: + if key == 'four-view' and face_emphasis: + return (FOUR_VIEW_FACE_EMPHASIS if has_reference else FOUR_VIEW_FACE_TEXT,) + preset = PRESETS.get(key) + if not preset: + return () + return preset.prompts if has_reference else preset.text_prompts + + +def preset_prompt(key: str, face_emphasis: bool, reference_titles: tuple[str, ...]) -> str | None: + prompts = preset_instructions(key, face_emphasis, has_reference=bool(reference_titles)) + if not prompts: + return None + lines = [] + if len(reference_titles) > 1: + labels = '、'.join(f'参考{index}({title})' for index, title in enumerate(reference_titles, 1)) + lines.append(f'本次共 {len(reference_titles)} 张参考图:{labels}。请按编号区分主体、场景与其他参考,不要把不同参考的角色混用。') + if len(prompts) > 1: + lines.append('按以下顺序逐张生成:') + lines.extend(f'{index}. {prompt}' for index, prompt in enumerate(prompts, 1)) + else: + lines.append(prompts[0]) + return '\n'.join(lines) diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 0c5e5b4c9..b161441c5 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -48,7 +48,10 @@ import { } from "./creationClient.ts"; import { assetSource } from "./assetSource.ts"; import { sameJsonValue } from "./sameJsonValue.ts"; -import { classifyImportFile, readEditorResource } from "../canvas/editorMedia.ts"; +import { + classifyImportFile, + readEditorResource, +} from "../canvas/editorMedia.ts"; /** Every comparison here is over a document that carries its media inline, so * it reads the values instead of serializing both sides to compare strings. */ @@ -801,6 +804,7 @@ export class CreationProjection { ? "auto" : spec.parameters.size, imagePreset: spec.parameters.preset, + faceEmphasis: spec.parameters.faceEmphasis === true, imageQuality: spec.parameters.quality ?? "auto", } : {}), @@ -938,10 +942,20 @@ export class CreationProjection { } for (const item of snapshot.canvasItems) { const asset = currentAsset(snapshot, item); - const timelineSources = asset?.provenance.source === "rendered" && asset.provenance.editorDocumentId - ? snapshot.canvasItems.filter((source) => source.kind === "timeline" && source.binding.role === "editor" && source.binding.objectRef.id === asset.provenance.editorDocumentId) - : []; - const sourceId = asset?.provenance.sourceItemId ?? (timelineSources.length === 1 ? timelineSources[0].id : undefined); + const timelineSources = + asset?.provenance.source === "rendered" && + asset.provenance.editorDocumentId + ? snapshot.canvasItems.filter( + (source) => + source.kind === "timeline" && + source.binding.role === "editor" && + source.binding.objectRef.id === + asset.provenance.editorDocumentId, + ) + : []; + const sourceId = + asset?.provenance.sourceItemId ?? + (timelineSources.length === 1 ? timelineSources[0].id : undefined); if (sourceId && snapshot.canvasItems.some((i) => i.id === sourceId)) document.edges.push({ id: `publication:${item.id}:${asset!.id}`, @@ -1031,6 +1045,9 @@ export class CreationProjection { ? null : node.data.settings.aspectRatio, preset: node.data.settings?.imagePreset ?? "none", + ...(node.data.settings?.faceEmphasis + ? { faceEmphasis: true } + : {}), ...(node.data.settings?.imageQuality && node.data.settings.imageQuality !== "auto" ? { quality: node.data.settings.imageQuality } diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 4410a6a47..5da816653 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -465,7 +465,7 @@ export function serviceGenerationSettings( } next = serviceImageSettings(serviceAudioSettings(next, config), config); if (modelChanged) { - next.imagePreset = "none"; + if (next.imagePreset === "product-views") next.imagePreset = "none"; if (next.voiceSelection) { if (voiceIssue(next.voiceSelection, config.inputRules.voiceLibrary)) { next.voiceName = undefined; @@ -632,7 +632,7 @@ export function backendBlocker( limit: rules.maxPromptCharacters, }); if (settings.mode === "image") { - if (settings.imagePreset && settings.imagePreset !== "none") + if (settings.imagePreset === "product-views") return tNow("errors.rules.productViews"); if ( !backendAspectRatios(settings, config).includes(settings.aspectRatio) || diff --git a/src/canvas/ChatReferenceEditor.tsx b/src/canvas/ChatReferenceEditor.tsx index 77a9a1b82..6f073e9bb 100644 --- a/src/canvas/ChatReferenceEditor.tsx +++ b/src/canvas/ChatReferenceEditor.tsx @@ -33,6 +33,7 @@ import { type Caret, } from "./chatReferenceDOM.ts"; import { referenceInsertion } from "./chatReferenceInsertion.ts"; +import { presetPart, withoutPresetParts, withPresetPart } from "./promptSkill.ts"; import type { ReferenceRules } from "./chatReferenceInsertion.ts"; import { isCaretNavigationKey, @@ -87,6 +88,17 @@ interface Props { onPasteFiles: (files: File[]) => void; onConfirmPending?: (caret: Caret) => void; onSlashChange?: (query: string | null) => void; + /** Summary drawn after a preset chip while the prompt has no words yet. */ + presetNote?: string; + /** Whether the preset offers its alternate framing. */ + presetTunable?: boolean; + presetLabel?: string; + presetTuneOpen?: boolean; + onPresetAction?: ( + action: "prompt" | "tune", + element: HTMLElement, + preset: string, + ) => void; skillsEnabled?: boolean; label?: string; placeholder?: string; @@ -119,6 +131,15 @@ const CATEGORY_LABELS: Record = { subject: "assistant.kind.subject", }; +function presetPlaceholder(text: string) { + const note = document.createElement("span"); + note.className = "cw-chat-preset-note"; + note.dataset.presetNote = text; + // Give the caret a real editable position before the generated hint. + note.textContent = "\u200b"; + return note; +} + /** OpenDirector's atomic content model: one reference is one editing position. */ export function ChatReferenceEditor({ scope, @@ -137,6 +158,11 @@ export function ChatReferenceEditor({ onPasteFiles, onConfirmPending, onSlashChange, + presetNote, + presetTunable, + presetLabel, + presetTuneOpen, + onPresetAction, skillsEnabled = false, label: labelProp, placeholder: placeholderProp, @@ -178,8 +204,8 @@ export function ChatReferenceEditor({ [active, setActive] = useState(0); const [busy, setBusy] = useState(false), [notice, setNotice] = useState(""); - const latest = useRef({onChange, onChoose, onOpen, assets, previews, visibleReferenceNodeIds, onSlashChange}); - latest.current = {onChange, onChoose, onOpen, assets, previews, visibleReferenceNodeIds, onSlashChange}; + const latest = useRef({onChange, onChoose, onOpen, assets, previews, visibleReferenceNodeIds, onSlashChange, presetNote, presetTunable, presetLabel, presetTuneOpen, onPresetAction}); + latest.current = {onChange, onChoose, onOpen, assets, previews, visibleReferenceNodeIds, onSlashChange, presetNote, presetTunable, presetLabel, presetTuneOpen, onPresetAction}; const listId = useId(); const categories = mentionCategories(options); const effectiveCategory = categories.includes(category) ? category : "all"; @@ -284,7 +310,49 @@ export function ChatReferenceEditor({ for (const part of blank ? [] : content) { if (part.type === "text") fragment.append(document.createTextNode(part.text)); - else if (part.type === "skill") { + else if (part.type === "skill" && part.preset) { + const previous = root.current.querySelector("[data-preset]"); + const chip = previous?.dataset.preset === part.preset ? previous : document.createElement("span"); + chip.contentEditable = "false"; + chip.className = "cw-chat-reference cw-chat-preset"; + chip.dataset.preset = part.preset; + chip.dataset.label = part.name; + if (part.faceEmphasis) chip.dataset.faceEmphasis = "1"; + else delete chip.dataset.faceEmphasis; + let label = chip.querySelector(".cw-chat-preset-label"); + if (!label) { + const icon = document.createElement("span"); + icon.dataset.referenceIcon = "1"; + icon.className = "cw-chat-preset-icon"; + icon.setAttribute("aria-hidden", "true"); + const template = iconTemplates.current?.querySelector('[data-kind="image"]'); + if (template) icon.append(template.cloneNode(true)); + label = document.createElement("button"); + label.type = "button"; + label.className = "cw-chat-reference-label cw-chat-preset-label"; + chip.append(icon, label); + } + label.textContent = latest.current.presetLabel ?? part.name; + let tune = chip.querySelector("[data-preset-tune]"); + if (latest.current.presetTunable) { + if (!tune) { + tune = document.createElement("button"); + tune.type = "button"; + tune.className = "cw-chat-preset-tune"; + tune.dataset.presetTune = "1"; + const template = iconTemplates.current?.querySelector('[data-kind="sliders"]'); + if (template) tune.append(template.cloneNode(true)); + chip.append(tune); + } + tune.setAttribute("aria-label", t("generation.preset.tune")); + tune.title = t("generation.preset.tune"); + tune.setAttribute("aria-haspopup", "dialog"); + tune.setAttribute("aria-expanded", String(Boolean(latest.current.presetTuneOpen))); + } else tune?.remove(); + fragment.append(chip); + if (latest.current.presetNote) + fragment.append(presetPlaceholder(latest.current.presetNote)); + } else if (part.type === "skill") { const chip = document.createElement("span"); chip.contentEditable = "false"; chip.dataset.skill = part.name; @@ -322,6 +390,14 @@ export function ChatReferenceEditor({ root.current.focus({ preventScroll: true }); select(root.current, at); } + function placeCaretAfterPreset() { + if (disabled || busy || composing.current || !root.current || + !latest.current.presetNote || !presetPart(current.current)) return false; + const afterChip = { start: 1, end: 1 }; + saved.current = afterChip; + focus(afterChip); + return true; + } function publish( content: ReferenceContent, at: Caret, @@ -574,7 +650,21 @@ export function ChatReferenceEditor({ } function input() { if (!root.current || composing.current || choosing.current) return; - publish(readDOM(root.current), caret(), false, true); + const content = readDOM(root.current); + const at = caret(); + const preset = presetPart(content); + if (preset && content[0] !== preset) { + // Browsers can insert before the leading chip. Move it back to the + // front and preserve the user's editing position in the typed text. + const presetOffset = editingText(content.slice(0, content.indexOf(preset))).length; + const moveCaret = (position: number) => position <= presetOffset ? position + 1 : position; + publish(withPresetPart(content, preset), { + start: moveCaret(at.start), + end: moveCaret(at.end), + }, true, true); + } else { + publish(content, at, false, true); + } updateMention(); } function removeReference(direction: "backward" | "forward") { @@ -712,6 +802,28 @@ export function ChatReferenceEditor({ visibleReferenceNodeIds, t, ]); + useLayoutEffect(() => { + if ( + !root.current || + !current.current.some((part) => part.type === "skill" && part.preset) + ) + return; + paint(current.current, document.activeElement === root.current ? caret() : undefined); + }, [presetLabel, presetTunable, t]); + useLayoutEffect(() => { + const chip = root.current?.querySelector("[data-preset]"); + const note = root.current?.querySelector(".cw-chat-preset-note"); + if (presetNote && chip) { + if (note) note.dataset.presetNote = presetNote; + else chip.after(presetPlaceholder(presetNote)); + } else if (note) { + delete note.dataset.presetNote; + } + }, [presetNote]); + useLayoutEffect(() => { + root.current?.querySelector("[data-preset-tune]") + ?.setAttribute("aria-expanded", String(Boolean(presetTuneOpen))); + }, [presetTuneOpen]); useLayoutEffect(() => { if (!autoGrow || !root.current) return; const element = root.current; @@ -845,10 +957,11 @@ export function ChatReferenceEditor({ [], ); event.preventDefault(); - event.clipboardData.setData("text/plain", contentText(selected, false, t)); + const content = withoutPresetParts(selected); + event.clipboardData.setData("text/plain", contentText(content, false, t)); event.clipboardData.setData( CLIPBOARD, - JSON.stringify({ scope, content: selected }), + JSON.stringify({ scope, content }), ); if (cut) publish(editContent(current.current, at, []), { @@ -862,6 +975,7 @@ export function ChatReferenceEditor({ {["image", "video", "audio", "text", "subject"].map((kind) => ( ))} +
{ composing.current = false; + if (root.current) delete root.current.dataset.composing; input(); }} onInput={input} - onFocus={() => { + onFocus={(event) => { + if (event.target === event.currentTarget) placeCaretAfterPreset(); updateMention(); }} onPointerUp={() => { @@ -904,7 +1023,34 @@ export function ChatReferenceEditor({ onBlur={() => { if (!choosing.current) close(); }} - onClick={() => { + onMouseDown={(event) => { + const target = event.target instanceof Element ? event.target : null; + // Preserve focus when pressing a preset control. + if (target?.closest("[data-preset]")) { + event.preventDefault(); + return; + } + // Cancel native caret placement while the button is held over the hint. + if (event.button === 0 && !event.defaultPrevented && + !target?.closest("[data-reference]") && placeCaretAfterPreset()) { + event.preventDefault(); + } + }} + onClick={(event) => { + const target = event.target as HTMLElement | null; + const chip = target?.closest?.("[data-preset]"); + if (chip && latest.current.onPresetAction) { + event.preventDefault(); + if (disabled || busy) return; + const tune = target?.closest("[data-preset-tune]"); + latest.current.onPresetAction( + tune ? "tune" : "prompt", + tune ?? chip, + chip.dataset.preset ?? "", + ); + return; + } + if (!target?.closest?.("[data-reference]")) placeCaretAfterPreset(); if (onConfirmPending && !disabled && !busy && !composing.current) onConfirmPending(caret()); }} @@ -945,6 +1091,7 @@ export function ChatReferenceEditor({ event.preventDefault(); }} onKeyDown={(event) => { + if (event.target instanceof HTMLElement && event.target.closest(".cw-chat-preset button")) return; if (event.key === "Escape" && busy) { event.preventDefault(); event.stopPropagation(); diff --git a/src/canvas/GenerationReferenceEditor.tsx b/src/canvas/GenerationReferenceEditor.tsx index 126c91fc7..b7b79644f 100644 --- a/src/canvas/GenerationReferenceEditor.tsx +++ b/src/canvas/GenerationReferenceEditor.tsx @@ -15,7 +15,7 @@ import { } from "./ChatReferenceEditor"; import { generationContent, - generationContentPatch, + generationEditorPatch, nodeReferenceAsset, } from "./generationReferenceContent.ts"; import { type MentionOption } from "./referenceMentions.ts"; @@ -27,6 +27,7 @@ import type { } from "./chatReferenceContent.ts"; import { normalizeContent, referencePart } from "./chatReferenceContent.ts"; import { useI18n } from "../i18n/I18nProvider.tsx"; +import { presetPart, withPresetPart, type PresetPart } from "./promptSkill.ts"; export interface GenerationReferenceControls { projectId: string; @@ -36,7 +37,7 @@ export interface GenerationReferenceControls { visibleNodes: CanvasNode[]; assets: ReferenceAsset[]; pinned?: ReferenceAsset[]; - onChange: (content: ReferenceContent, sources: CanvasNode[]) => void; + onChange: (content: ReferenceContent, sources: CanvasNode[], presetEdited?: boolean) => void; /** Removes the connection itself; the strip owns relationships, not the text. */ removeReference?: (source: CanvasNode) => void; prepareAsset: ( @@ -65,6 +66,12 @@ export function GenerationReferenceEditor({ pickerRef, placeholder, label, + presetNote, + preset, + presetTunable, + presetLabel, + presetTuneOpen, + onPresetAction, onRun, validate, }: { @@ -77,6 +84,17 @@ export function GenerationReferenceEditor({ pickerRef: Ref; placeholder: string; label: string; + /** Summary drawn after the preset chip while the prompt has no words yet. */ + presetNote?: string; + preset?: PresetPart; + presetTunable?: boolean; + presetLabel?: string; + presetTuneOpen?: boolean; + onPresetAction?: ( + action: "prompt" | "tune", + element: HTMLElement, + preset: string, + ) => void; onRun: () => void; validate?: (sources: CanvasNode[]) => string | null; }) { @@ -128,6 +146,7 @@ export function GenerationReferenceEditor({ ? [{ type: "text" as const, text: "\n" }, ...value] : []), ]); + if (node.type === "image") value = withPresetPart(value, preset ?? null); latestContent.current = value; const assets: ReferenceAsset[] = nodes .filter(canSourceReference) @@ -557,9 +576,12 @@ export function GenerationReferenceEditor({ const reason = validate?.([...sources, ...pinnedSources(content)]); if (reason) throw new Error(reason); } + const editedPreset = presetPart(content); + const presetEdited = node.type === "image" && + (preset?.preset !== editedPreset?.preset || preset?.faceEmphasis !== editedPreset?.faceEmphasis); if (controls) - controls.onChange(content, [...prepared.current.values()]); - else onUpdate(generationContentPatch(content)); + controls.onChange(content, [...prepared.current.values()], presetEdited); + else onUpdate(generationEditorPatch(node, content, presetEdited)); }} onSubmit={onRun} onPasteFiles={(files) => void uploadFiles(files)} @@ -657,6 +679,11 @@ export function GenerationReferenceEditor({ label={label} placeholder={placeholder} className="cw-prompt-input" + presetNote={presetNote} + presetTunable={presetTunable} + presetLabel={presetLabel} + presetTuneOpen={presetTuneOpen} + onPresetAction={onPresetAction} autoGrow submitOnEnter={false} metadataOnlyKinds={node.type === "text" ? ["video", "audio"] : []} diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index dfabfd77d..260a320e0 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -6,9 +6,21 @@ import { providerLabel } from "./providerPresets"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; import { normalizeContent, + presetOnlyContent, type ReferenceContent, } from "./chatReferenceContent.ts"; import { generationContent } from "./generationReferenceContent.ts"; +import { + presetImageTitles, + presetPart, + presetSkillText, + promptWithPreset, + supportsFaceEmphasis, + withPresetPart, + type PromptSkillPreset, +} from "./promptSkill.ts"; +import { translateToolText } from "./toolText.ts"; +import type { MessageKey } from "../i18n/types.ts"; import type { CanvasNode, CanvasNodeData, GenerationSettings } from "./model"; import { LOCAL_DEMO_MODEL } from "./model"; @@ -70,6 +82,8 @@ export interface NodeComposerProps { incomingNodes: CanvasNode[]; /** Pinned assets included in run-before reference checks, not frame-slot limits. */ pinnedPrecheck?: CanvasNode[]; + /** Images available for the preset preview, including sources hidden on the canvas. */ + presetSources?: readonly CanvasNode[]; onUpdate: (data: Partial) => void; onRun: () => void; lastOptimizedText?: string; @@ -83,6 +97,8 @@ export interface NodeComposerProps { /** Failures and warnings worth a canvas toast instead of an inline note. */ onOptimizationNotice?: (message: string, error: boolean) => void; running?: boolean; + /** Image presets published by the tool catalog; applied as prompt skills. */ + imagePresets?: readonly PromptSkillPreset[]; /** Models configured in the local API, usable alongside the catalog. */ backendModels?: readonly ModelConfig[]; @@ -105,10 +121,21 @@ function clockTime(seconds: number) { /** Built-in demo voice id; the visible label is localized separately. */ const DEMO_VOICE = "动漫海绵"; +/** Help shown beside a preset chip while the prompt is empty. */ +const PRESET_HELP: Record = { + "three-view": { description: "generation.preset.description.three-view", ratios: ["16:9", "3:2"] }, + "four-view": { description: "generation.preset.description.four-view", ratios: ["21:9", "16:9", "3:2"] }, + "face-three-view": { description: "generation.preset.description.face-three-view", ratios: ["21:9", "16:9", "3:2"] }, + "product-three-view": { description: "generation.preset.description.product-three-view", ratios: ["16:9", "3:2"] }, + storyboard: { description: "generation.preset.description.storyboard", ratios: ["16:9", "3:2"] }, + "multi-camera": { description: "generation.preset.description.multi-camera", ratios: ["16:9", "3:2"] }, +}; + export function NodeComposer({ selectedNode, incomingNodes, pinnedPrecheck, + presetSources, onUpdate, onRun, lastOptimizedText, @@ -118,6 +145,7 @@ export function NodeComposer({ onPickReference, onOptimizationNotice, running = false, + imagePresets = [], backendModels = [], onCheckModels, removeWatermark = false, @@ -140,6 +168,16 @@ export function NodeComposer({ const pendingOptimization = useRef(null); const restoreFocus = useRef(false); const [optimizing, setOptimizing] = useState(false); + /** Preset popovers hold their own anchor: they are not composer panels. */ + const [presetPromptAnchor, setPresetPromptAnchor] = + useState(null); + const [presetTuneAnchor, setPresetTuneAnchor] = useState( + null, + ); + const [presetCopied, setPresetCopied] = useState(false); + const presetValue = selectedNode?.type === "image" + ? selectedNode.data.settings?.imagePreset ?? "none" + : "none"; const panel = running || optimizing ? null : openPanel; const [optimizedText, setOptimizedText] = useState(lastOptimizedText); const latestRunning = useRef(running); @@ -160,6 +198,10 @@ export function NodeComposer({ useEffect(() => { setPanel(null); }, [selectedNode?.id, running]); + useEffect(() => { + setPresetPromptAnchor(null); + setPresetTuneAnchor(null); + }, [selectedNode?.id, presetValue, running]); if ( !selectedNode || @@ -247,7 +289,7 @@ export function NodeComposer({ const reference = references[Number(index) - 1]; return reference ? [reference] : []; }); - const rewritten = normalizeContent(output); + const rewritten = normalizeContent(withPresetPart(output, presetPart(before) ?? null)); if (!mentions.current?.replacePrompt(rewritten)) throw new Error(t("generation.optimize.changed")); const text = promptText(rewritten); @@ -290,11 +332,28 @@ export function NodeComposer({ : config ? backendReferenceIssue(node, settings, config) : t("generation.model.unavailable"); + // The chip mirrors the saved preset and supplies its own prompt. + const activePreset = mode === "image" + ? imagePresets.find((item) => item.value === presetValue) + : undefined; + const faceEmphasis = + settings.faceEmphasis === true && supportsFaceEmphasis(activePreset); + const presetPromptText = activePreset + ? presetSkillText( + activePreset, + presetImageTitles(settings, presetSources ?? [...incomingNodes, ...(pinnedPrecheck ?? [])], config), + faceEmphasis, + ) + : ""; + const checkedSettings = { + ...settings, + prompt: promptWithPreset(settings.prompt, presetPromptText), + }; const blocker = unconfigured ? t("generation.model.unconfigured") : backend - ? backendBlocker(settings, incomingNodes, backendModels, pinnedPrecheck) - : generationBlocker(settings, incomingNodes, t); + ? backendBlocker(checkedSettings, incomingNodes, backendModels, pinnedPrecheck) + : generationBlocker(checkedSettings, incomingNodes, t); const canRun = !blocker; // A blank prompt falls back to connected text references. const implicitTextPrompt = Boolean( @@ -354,7 +413,8 @@ export function NodeComposer({ const serviceModes = config?.inputRules.videoModes ?? []; const supportsControl = mode === "video" && serviceModes.includes("control"); // The adapter derives duration from the control clip and aligns to model frames. - const followsControl = backend && mode === "video" && settings.videoMode === "control"; + const followsControl = + backend && mode === "video" && settings.videoMode === "control"; const durationValues = followsControl ? [] : backend && mode === "video" @@ -401,7 +461,8 @@ export function NodeComposer({ updateSettings({ model: value, modelConfigId: undefined, - ...(settings.videoMode === "continuation" || settings.videoMode === "control" + ...(settings.videoMode === "continuation" || + settings.videoMode === "control" ? { videoMode: "reference" as const } : {}), }); @@ -425,6 +486,32 @@ export function NodeComposer({ : next, }); }; + const presetHelp = activePreset ? PRESET_HELP[activePreset.value] : undefined; + const availableRatios = config ? backendAspectRatios(settings, config) : undefined; + const recommendedRatio = availableRatios + ? presetHelp?.ratios.find((ratio) => availableRatios.includes(ratio)) + : presetHelp?.ratios[0]; + const presetDescription = presetHelp + ? [ + t(presetHelp.description), + ...(recommendedRatio + ? [t("generation.preset.description.recommendedRatio", { ratio: recommendedRatio })] + : []), + ...(faceEmphasis + ? [t("generation.preset.description.faceEmphasis")] + : []), + ].join(locale === "zh-CN" ? "" : " ") + : ""; + const applyPreset = (value: string) => { + setPanel(null); + setPresetPromptAnchor(null); + setPresetTuneAnchor(null); + updateSettings({ imagePreset: value, faceEmphasis: false }); + }; + const toggleFaceEmphasis = () => { + if (!activePreset) return; + updateSettings({ faceEmphasis: !faceEmphasis }); + }; const togglePanel = (next: Panel, anchor: HTMLElement) => { panelAnchor.current = anchor; setPanel((current) => (current === next ? null : next)); @@ -597,7 +684,9 @@ export function NodeComposer({ node={node} onInsert={() => insertReference(node)} onRemove={() => mentions.current?.remove(node)} - disabled={running || optimizing || Boolean(referenceIssue(node))} + disabled={ + running || optimizing || Boolean(referenceIssue(node)) + } removalDisabled={running || optimizing} title={`${t("generation.reference.title", { role: generationReferenceRole(node, t), @@ -608,7 +697,10 @@ export function NodeComposer({
)} {referenceVisibility.showReadingContextNote && ( -

+

{t("generation.reference.readingContext")}

)} @@ -627,6 +719,35 @@ export function NodeComposer({ }} onUpdate={onUpdate} running={running || optimizing} + presetNote={ + activePreset && presetOnlyContent(draft) ? presetDescription : undefined + } + preset={activePreset ? { + type: "skill", name: activePreset.label, preset: activePreset.value, + ...(faceEmphasis ? { faceEmphasis: true } : {}), + } : undefined} + presetLabel={ + activePreset + ? faceEmphasis + ? t("generation.preset.labelWithEmphasis", { + preset: translateToolText(locale, activePreset.label), + emphasis: t("generation.preset.faceEmphasis"), + }) + : translateToolText(locale, activePreset.label) + : undefined + } + presetTunable={supportsFaceEmphasis(activePreset)} + presetTuneOpen={Boolean(presetTuneAnchor)} + onPresetAction={(action, element) => { + setPresetCopied(false); + if (action === "tune") { + setPresetPromptAnchor(null); + setPresetTuneAnchor((anchor) => anchor === element ? null : element); + } else { + setPresetTuneAnchor(null); + setPresetPromptAnchor(element); + } + }} onRun={() => { if (canRun && !running && !pendingOptimization.current) onRun(); }} @@ -638,21 +759,99 @@ export function NodeComposer({ : t("generation.prompt.image") } placeholder={ - implicitTextPrompt - ? t("generation.prompt.implicitTextPlaceholder") - : mode === "image" - ? t("generation.prompt.imagePlaceholder") - : mode === "video" - ? firstLast - ? t("generation.prompt.videoPlaceholder") - : t("generation.prompt.videoReferencePlaceholder") - : reading - ? t("generation.prompt.readingPlaceholder") - : music - ? t("generation.prompt.musicPlaceholder") - : t("generation.prompt.audioPlaceholder") + // The preset summary stands in for the hint while the prompt is empty. + activePreset && presetOnlyContent(draft) + ? "" + : implicitTextPrompt + ? t("generation.prompt.implicitTextPlaceholder") + : mode === "image" + ? t("generation.prompt.imagePlaceholder") + : mode === "video" + ? firstLast + ? t("generation.prompt.videoPlaceholder") + : t("generation.prompt.videoReferencePlaceholder") + : reading + ? t("generation.prompt.readingPlaceholder") + : music + ? t("generation.prompt.musicPlaceholder") + : t("generation.prompt.audioPlaceholder") } /> + {presetPromptAnchor && activePreset && ( + setPresetPromptAnchor(null)} + > +
+ + {t("generation.preset.promptTitle", { + preset: translateToolText(locale, activePreset.label), + })} + + { + void navigator.clipboard + ?.writeText(presetPromptText) + .then(() => setPresetCopied(true)) + .catch(() => setPresetCopied(false)); + }} + > + + + setPresetPromptAnchor(null)} + > + + +
+
{presetPromptText}
+
+ )} + {!running && !optimizing && presetTuneAnchor?.isConnected && + activePreset && + supportsFaceEmphasis(activePreset) && ( + setPresetTuneAnchor(null)} + > +
+ {t("generation.preset.faceEmphasis")} + { + event.preventDefault(); + event.stopPropagation(); + }} + onClick={toggleFaceEmphasis} + > + + +
+
+ )} {optimizing && (

@@ -740,7 +939,13 @@ export function NodeComposer({ id: `config:${item.id}`, name: modelLabel(item), modelId: item.modelId, - description: [modelDescription(item), availabilitySummary(item.availability)].filter(Boolean).join(" · ") || undefined, + description: + [ + modelDescription(item), + availabilitySummary(item.availability), + ] + .filter(Boolean) + .join(" · ") || undefined, group: providerLabel(item), })), ]} @@ -779,22 +984,23 @@ export function NodeComposer({ {mode === "image" && ( )} {mode === "video" && ( @@ -942,8 +1148,16 @@ export function NodeComposer({ mentions.current?.openUpload()} > @@ -1078,12 +1292,18 @@ export function NodeComposer({ {durationValues.length > 0 && ( updateSettings({ durationSeconds })} + onChange={(durationSeconds) => + updateSettings({ durationSeconds }) + } /> )} @@ -1280,7 +1500,9 @@ export function NodeComposer({ {mode === "video" && - (!backend || config?.protocol === "volcengine" || config?.protocol === "higgsfield_open") && ( + (!backend || + config?.protocol === "volcengine" || + config?.protocol === "higgsfield_open") && (