diff --git a/calliope-backend/scripts/build_widget_orders.py b/calliope-backend/scripts/build_widget_orders.py new file mode 100644 index 00000000..90350c88 --- /dev/null +++ b/calliope-backend/scripts/build_widget_orders.py @@ -0,0 +1,128 @@ +"""Regenerate ``src/calliope/comfyui/ui_widget_orders.py`` (HEL-681). + +Offline widget-order registry for the UI→API converter. Sources, in priority: + +1. ``widgets_values_named`` instances across ``example_ComfyUI_workflows`` + (including subgraph inner nodes) — the frontend serializes named widgets + in widget order, so the key order IS the serialization order; +2. the repo's 10 ground-truth API exports (root ``*_API.json``) — scalar + input names in export order (control_after_generate entries are absent + there; the converter's walk skips them positionally). + +Run from anywhere inside the repo: + python scripts/build_widget_orders.py +""" + +from __future__ import annotations + +import collections +import json +from pathlib import Path + +BACKEND = Path(__file__).resolve().parents[1] +REPO = BACKEND.parent +EXAMPLES = REPO / "example_ComfyUI_workflows" +OUT = BACKEND / "src" / "calliope" / "comfyui" / "ui_widget_orders.py" + +BUTTONS = {"preview", "audioUI", "compare_view", "ToggleableColorPicker", "imagebrowser"} +MAX_SIGNATURES = 3 +MAX_ORDER_LEN = 48 + +# Hand-curated fallbacks for node classes the corpus never serializes with +# names (classic core/custom widgets whose order is stable and public). +CURATED: dict[str, list[list[str]]] = { + "PrimitiveNode": [["value"]], + "Seed (rgthree)": [["seed"]], +} + + +def _iter_ui_nodes() -> list[dict]: + nodes: list[dict] = [] + for path in sorted(EXAMPLES.rglob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + continue + if not (isinstance(data, dict) and isinstance(data.get("nodes"), list)): + continue + nodes.extend(n for n in data["nodes"] if isinstance(n, dict)) + for sub in data.get("definitions", {}).get("subgraphs", []) or []: + if isinstance(sub, dict): + nodes.extend(n for n in sub.get("nodes", []) or [] if isinstance(n, dict)) + return nodes + + +def _iter_api_workflows() -> list[dict]: + out: list[dict] = [] + for path in sorted(EXAMPLES.glob("*_API.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + continue + if isinstance(data, dict) and "nodes" not in data: + out.append(data) + return out + + +def main() -> None: + learned: dict[str, collections.Counter[tuple[str, ...]]] = collections.defaultdict( + collections.Counter + ) + for node in _iter_ui_nodes(): + named = node.get("widgets_values_named") + if not isinstance(named, dict) or not named: + continue + keys = tuple( + str(k) for k in named.keys() if k and k not in BUTTONS + ) + if keys and len(keys) <= MAX_ORDER_LEN: + learned[str(node.get("type") or "")][keys] += 1 + + for workflow in _iter_api_workflows(): + for node in workflow.values(): + if not isinstance(node, dict): + continue + names = [ + str(k) + for k, v in (node.get("inputs") or {}).items() + if not isinstance(v, list) and k and k not in BUTTONS + ] + if len(names) > MAX_ORDER_LEN: + continue + # Display nodes (PreviewAny…) carry zero scalar inputs — that + # empty order is real signal: their positional arrays are pure + # button leftovers and map to {}. + learned[str(node.get("class_type") or "")][tuple(names)] += 1 + + registry: dict[str, list[list[str]]] = {} + for node_type, counter in sorted(learned.items()): + if not node_type: + continue + orders: list[list[str]] = [] + for signature, _count in counter.most_common(MAX_SIGNATURES): + orders.append(list(signature)) + if orders: + registry[node_type] = orders + for node_type, orders in CURATED.items(): + registry.setdefault(node_type, orders) + + body = json.dumps(registry, ensure_ascii=False, indent=1, sort_keys=True) + OUT.write_text( + '"""GENERATED by scripts/build_widget_orders.py — do not edit by hand.\n' + "\n" + "Widget-order registry for the UI→API converter: class_type → candidate\n" + "widget name orders, learned from the repo's named-widget UI files and\n" + "ground-truth API exports (HEL-681).\n" + '"""\n' + "\n" + "from __future__ import annotations\n" + "\n" + f"WIDGET_ORDERS: dict[str, list[list[str]]] = {body}\n", + encoding="utf-8", + ) + total = sum(len(o) for orders in registry.values() for o in orders) + print(f"wrote {OUT.name}: {len(registry)} node types, {total} orders total") + + +if __name__ == "__main__": + main() diff --git a/calliope-backend/scripts/ui_import_dryrun.py b/calliope-backend/scripts/ui_import_dryrun.py new file mode 100644 index 00000000..36b9c208 --- /dev/null +++ b/calliope-backend/scripts/ui_import_dryrun.py @@ -0,0 +1,170 @@ +"""Generate the HEL-681 dry-run report over the repo's UI workflow library. + +Walks ``example_ComfyUI_workflows`` (or ``--root``), runs every file through +the production converter + lint + parser pipeline (exactly what +``POST /api/workflows/convert`` does, minus HTTP), and writes a JSON detail +file plus a human-readable Markdown summary. Read-only: nothing is imported, +no DB is touched. + +Usage: + python scripts/ui_import_dryrun.py [--root DIR] [--out PREFIX] +""" + +from __future__ import annotations + +import argparse +import collections +import json +import sys +from pathlib import Path + +BACKEND = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(BACKEND / "src")) + +from calliope.comfyui.lint import workflow_warnings # noqa: E402 +from calliope.comfyui.metadata import suggested_metadata # noqa: E402 +from calliope.comfyui.parser import classify_usage # noqa: E402 +from calliope.comfyui.ui_convert import convert_ui_workflow # noqa: E402 + +REPO = BACKEND.parent + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--root", default=str(REPO / "example_ComfyUI_workflows")) + parser.add_argument("--out", default=str(REPO / "dryrun_report")) + args = parser.parse_args() + root = Path(args.root) + out_prefix = Path(args.out) + + entries = [] + for path in sorted(root.rglob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError) as exc: + entries.append( + { + "source_path": str(path.relative_to(root)), + "status": "fail", + "issues": [{"code": "unreadable", "message": str(exc)}], + } + ) + continue + if not (isinstance(data, dict) and isinstance(data.get("nodes"), list)): + continue # API-format / non-workflow files are out of scope + rel = str(path.relative_to(root)) + result = convert_ui_workflow(data) + entry: dict = { + "source_path": rel, + "status": result.status, + "needs_confirmation": result.needs_confirmation, + "issues": [ + {"node_id": i.node_id, "code": i.code, "level": i.level, "message": i.message} + for i in result.issues + ], + } + if result.workflow is not None: + entry["node_count"] = len(result.workflow) + entry["suggested"] = suggested_metadata(result.workflow, rel, data) + errors = [w for w in workflow_warnings(result.workflow) if w["level"] == "error"] + entry["lint_errors"] = [e["code"] for e in errors] + entry["importable"] = not result.needs_confirmation and not errors + else: + entry["importable"] = False + entries.append(entry) + + counts = collections.Counter(e["status"] for e in entries) + code_counts = collections.Counter( + i["code"] for e in entries for i in e["issues"] + ) + category_counts = collections.Counter( + (e.get("suggested") or {}).get("category") or "?" for e in entries + ) + family_counts = collections.Counter( + (e.get("suggested") or {}).get("model_family") or "?" for e in entries + ) + importable = sum(1 for e in entries if e.get("importable")) + needs_confirmation = sum(1 for e in entries if e["needs_confirmation"]) + lint_blocked = [e for e in entries if e.get("lint_errors")] + + detail = { + "root": str(root), + "total": len(entries), + "status_counts": dict(counts), + "issue_code_counts": dict(code_counts), + "importable": importable, + "needs_confirmation": needs_confirmation, + "lint_blocked": [e["source_path"] for e in lint_blocked], + "files": entries, + } + out_prefix.parent.mkdir(parents=True, exist_ok=True) + (out_prefix.with_suffix(".json")).write_text( + json.dumps(detail, ensure_ascii=False, indent=1), encoding="utf-8" + ) + + lines = [ + "# HEL-681 工作流 UI→API 转换 dry-run 报告", + "", + f"- 扫描目录:`{root}`(根目录 10 个 API 格式旧文件不在本管线范围)", + f"- UI 格式文件总数:**{len(entries)}**", + f"- 转换结果:ok **{counts.get('ok', 0)}** / warn **{counts.get('warn', 0)}** / fail **{counts.get('fail', 0)}**", + f"- 其中「需人工确认」(控件无法可靠映射,禁止直接导入):**{needs_confirmation}**", + f"- 通过转换+lint 后可直接导入:**{importable}**", + f"- 转换成功但被现有 lint 拦截(导入时按阻止处理):**{len(lint_blocked)}**", + "", + "## 分类分布(自动提取)", + "", + "| 分类 | 数量 |", + "|---|---|", + ] + for cat, n in sorted(category_counts.items()): + lines.append(f"| {cat} | {n} |") + lines += ["", "## 模型家族分布(自动提取)", "", "| 家族 | 数量 |", "|---|---|"] + for fam, n in sorted(family_counts.items(), key=lambda kv: -kv[1]): + lines.append(f"| {fam} | {n} |") + lines += ["", "## 问题代码统计", "", "| 代码 | 次数 | 含义 |", "|---|---|---|"] + meaning = { + "muted_input_dropped": "上游节点被静音,输入按未连接处理", + "variable_upstream_dropped": "Set/Get 变量上游被旁路,取值按未连接处理", + "get_without_set": "GetNode 没有同名 SetNode", + "widget_unmapped": "控件值无法可靠映射到输入名(需人工确认)", + "widget_order_mismatch": "控件数量与已知顺序不符(需人工确认)", + "no_output_node": "图中无已知输出节点,全部活跃节点保留待确认", + "cyclic_variable": "Set/Get 循环(FOR 循环流),该连线按未连接处理", + "dangling_link": "连线指向不存在的节点", + } + for code, n in code_counts.most_common(): + lines.append(f"| `{code}` | {n} | {meaning.get(code, '')} |") + lines += ["", "## 需人工确认文件清单", ""] + for e in entries: + if e["needs_confirmation"]: + reasons = sorted({i["code"] for i in e["issues"]})[:3] + lines.append(f"- `{e['source_path']}`({', '.join(reasons)})") + lines += ["", "## lint 拦截文件清单", ""] + for e in lint_blocked: + lines.append(f"- `{e['source_path']}`({', '.join(e['lint_errors'])})") + lines += [ + "", + "## 逐文件结果", + "", + "| 文件 | 状态 | 节点数 | 分类 | 模型家族 | 用途 | 问题 |", + "|---|---|---|---|---|---|---|", + ] + for e in entries: + sug = e.get("suggested") or {} + issues = collections.Counter(i["code"] for i in e["issues"]) + issue_text = ", ".join(f"{c}×{n}" for c, n in issues.most_common(2)) or "-" + usage = sug.get("usage") or ("待定" if sug.get("usage_ambiguous") else "-") + lines.append( + f"| `{e['source_path']}` | {e['status']} | {e.get('node_count', '-')} " + f"| {sug.get('category') or '-'} | {sug.get('model_family') or '-'} " + f"| {usage} | {issue_text} |" + ) + (out_prefix.with_suffix(".md")).write_text("\n".join(lines) + "\n", encoding="utf-8") + print(f"{len(entries)} files: {dict(counts)}, importable={importable}, nc={needs_confirmation}") + print(f"report → {out_prefix}.md / {out_prefix}.json") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/calliope-backend/src/calliope/comfyui/metadata.py b/calliope-backend/src/calliope/comfyui/metadata.py new file mode 100644 index 00000000..9c170ec9 --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/metadata.py @@ -0,0 +1,160 @@ +"""Suggested workflow metadata for imports (HEL-681 / S2 data layer). + +Everything here derives from two honest sources: the repo directory the file +came from (category) and the converted API graph itself (usage, media in/out, +model family, note text). Per HEL-675's inventory, clean display names and +tags stay human work — the suggestion is a starting point, never a guess that +hides uncertainty. +""" + +from __future__ import annotations + +import re +from typing import Any + +from calliope.comfyui.parser import ( + classify_usage, + parse_dynamic_inputs, + parse_dynamic_outputs, +) + +# Repo top-level directory → (category key, display label). Directory names +# are mapping sources only — they never surface to users verbatim. +CATEGORY_DIRS: dict[str, tuple[str, str]] = { + "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大": ("basic", "基础处理"), + "1-语音生成": ("audio_tts", "语音生成"), + "2-音乐生成": ("music", "音乐生成"), + "3-图像生成": ("image", "图像生成"), + "4-视频生成": ("video", "视频生成"), + "5-数字人": ("digital_human", "数字人"), + "6-动作迁移": ("motion_transfer", "动作迁移"), +} + +# Evidence patterns → model family. Shared VAE/text-encoder files must NOT +# count (HEL-675: Anima/Z-Image graphs reference qwen_image_vae and get +# mislabeled Qwen — `qwen.?image(?!_vae)` is deliberate). +_FAMILY_PATTERNS: tuple[tuple[str, str], ...] = ( + (r"minimax[_\-]?(music|_audio)|MiniMaxMusic", "MiniMax-Music"), + (r"minimax.?h3|minimax_h3|h3[-_]realism|fl2v[aa]?", "MiniMax-H3"), + (r"ltx[-_.]?2", "LTX-2.5"), + (r"ltx", "LTX"), + (r"krea", "Krea2"), + (r"qwen.?image(?!_vae)|qwen_image_2|qwen2vl|qwen3vl|Qwen3?[-.]?ASR|qwen3?[-_.]?tts", "Qwen"), + (r"z[._-]?image", "Z-Image"), + (r"flux", "Flux"), + (r"\bwan", "Wan"), + (r"ace[_-]?step", "ACE-Step"), + (r"index[_-]?tts", "IndexTTS2"), + (r"anima[-_.]?(turbo|klein)", "Anima"), + (r"sdpose", "SDPose"), + (r"gemma", "Gemma"), + (r"instantmesh|instant_mesh", "InstantMesh"), + (r"hidream", "HiDream"), +) +_FAMILY_RE = [(re.compile(pat, re.IGNORECASE), fam) for pat, fam in _FAMILY_PATTERNS] + +# Main-model loaders dominate the vote: a UNET/checkpoint reference says far +# more about the workflow's family than a shared VAE or text encoder does. +_PRIMARY_LOADER_RE = re.compile(r"UNETLoader|CheckpointLoader|unet|diffusion_model", re.IGNORECASE) + +# Directory names that carry family evidence the files' own widget values +# lack (HEL-675: 14 krea2 files reference no "krea" string at all). +_FAMILY_DIRS = ( + (re.compile(r"krea2", re.IGNORECASE), "Krea2"), + (re.compile(r"Minimax-h3|uncensored", re.IGNORECASE), "MiniMax-H3"), + (re.compile(r"Z-Image", re.IGNORECASE), "Z-Image"), + (re.compile(r"Qwen-Image", re.IGNORECASE), "Qwen"), + (re.compile(r"^Anima$", re.IGNORECASE), "Anima"), + (re.compile(r"Flux", re.IGNORECASE), "Flux"), +) + +_NOTE_TYPES = frozenset({"Note", "MarkdownNote"}) + + +def category_from_source_path(source_path: str | None) -> tuple[str | None, str | None]: + """(category key, label) derived from the file's repo-relative path.""" + if not source_path: + return None, None + head = source_path.replace("\\", "/").split("/", 1)[0] + return CATEGORY_DIRS.get(head, (None, None)) + + +def model_family_from(workflow: dict[str, Any], source_path: str | None = None) -> str | None: + """The graph's dominant model family: main-model loader references weigh + triple, other node evidence single, and the repo sub-directory adds a + strong vote for families the widget values don't spell out.""" + votes: dict[str, int] = {} + for node in workflow.values(): + if not isinstance(node, dict): + continue + class_type = str(node.get("class_type") or "") + blob = " ".join( + [class_type] + + [str(v) for v in (node.get("inputs") or {}).values() if isinstance(v, str)] + ) + weight = 3 if _PRIMARY_LOADER_RE.search(blob) else 1 + for pattern, family in _FAMILY_RE: + if pattern.search(blob): + votes[family] = votes.get(family, 0) + weight + break # one vote per node: strongest family that node shows + if source_path: + parts = source_path.replace("\\", "/").split("/") + for part in parts[1:2]: + for pattern, family in _FAMILY_DIRS: + if pattern.search(part): + votes[family] = votes.get(family, 0) + 2 + if not votes: + return None + return max(votes.items(), key=lambda kv: kv[1])[0] + + +def note_description(ui_workflow: dict[str, Any], limit: int = 160) -> str | None: + """First non-trivial author note as description material (never final copy).""" + for node in ui_workflow.get("nodes") or []: + if not isinstance(node, dict) or str(node.get("type")) not in _NOTE_TYPES: + continue + values = node.get("widgets_values") + text = values[0] if isinstance(values, list) and values else None + if isinstance(values, dict): + text = values.get("text") or next(iter(values.values()), None) + if isinstance(text, str): + text = text.strip() + if len(text) >= 8: + return text[:limit].strip() + return None + + +def suggested_metadata( + converted: dict[str, Any], + source_path: str | None = None, + ui_workflow: dict[str, Any] | None = None, +) -> dict[str, Any]: + """The import suggestion bundle for one converted workflow.""" + judgment = classify_usage(converted) + media_kinds = ("image", "image_list", "video", "video_list", "audio", "audio_list") + media_in = sorted( + { + entry["kind"].replace("_list", "") + for entry in parse_dynamic_inputs(converted) + if entry.get("kind") in media_kinds + } + ) + media_out = sorted( + { + str(entry.get("kind")) + for entry in parse_dynamic_outputs(converted) + if entry.get("kind") in ("image", "video", "audio") + } + ) + category, category_label = category_from_source_path(source_path) + return { + "kind": "video" if "video" in media_out and "image" not in media_out else "image", + "usage": judgment["usage"], + "usage_ambiguous": judgment["ambiguous"], + "category": category, + "category_label": category_label, + "model_family": model_family_from(converted, source_path), + "media_in": media_in, + "media_out": media_out, + "description": note_description(ui_workflow or {}), + } diff --git a/calliope-backend/src/calliope/comfyui/ui_convert.py b/calliope-backend/src/calliope/comfyui/ui_convert.py new file mode 100644 index 00000000..799e4f6f --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/ui_convert.py @@ -0,0 +1,801 @@ +"""UI→API converter for ComfyUI workflow JSON (HEL-681 / S2 data layer). + +ComfyUI saves two formats: the editor ("UI") format with ``nodes``/``links`` +arrays, and the API ("prompt") format ``{node_id: {class_type, inputs}}`` the +product executes. This module converts UI→API offline and deterministically: + +* links are rewritten through ``Reroute`` chains and bypassed (mode 4) nodes; +* packed subgraph instances (frontend ≥1.x ``definitions.subgraphs``) expand + into their inner nodes under qualified ids ``:`` — the same + scheme ComfyUI itself exports; +* widget values map through, in priority order: the node's serialized input + list (entries carrying a ``widget`` marker — authoritative, this corpus's + frontend version always writes them), the ``widgets_values_named`` dict, + then a generated registry of widget orders learned from the corpus and the + repo's ground-truth API exports (``ui_widget_orders``). + +Anything that cannot be mapped with certainty is reported as an issue and the +file is flagged ``needs_confirmation`` — never silently guessed: a wrong +widget order produces a runnable-looking workflow with swapped seed/steps, +which is worse than an honest「需人工确认」. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +from calliope.comfyui.ui_widget_orders import WIDGET_ORDERS + +# Values of the frontend-only "control_after_generate" control that serializes +# right after every seed-like INT widget (and is not a real server input). +_CONTROL_MODES = frozenset({"fixed", "increment", "decrement", "randomize"}) + +# Widget names that are pure UI buttons/previews — never serialized in +# widgets_values (named dicts skip them too) and never API inputs. +_BUTTON_WIDGETS = frozenset( + {"preview", "audioUI", "compare_view", "ToggleableColorPicker", "imagebrowser"} +) + +# Leftover positional values that are provably action buttons, not data: +# known labels, self-describing ids, or emoji-prefixed actions. Anything +# else left over keeps the file in the needs-confirmation queue. +_BUTTON_LEFTOVER_LABELS = frozenset({"Edit", "lanpaint_star_button"}) +_BUTTON_LEFTOVER_EMOJI = ("🖼", "🎬", "🎵", "➕", "🔁", "🗑", "📂", "🔎", "✨") + + +def _is_button_leftover(value: Any) -> bool: + if value is None or value == "": + return True + if isinstance(value, str): + return ( + value in _BUTTON_LEFTOVER_LABELS + or "button" in value.lower() + or value.startswith(_BUTTON_LEFTOVER_EMOJI) + ) + return False + +# Virtual editor-only nodes. Links pass *through* reroute-style ones (see +# _resolve_source); the rest are dropped from the graph entirely. +_REROUTE_TYPES = frozenset({"Reroute", "Reroute (rgthree)"}) +# Frontend-virtual variable nodes: SetNode captures a value under a name, +# GetNode reads it. Neither reaches the server — links through a Get resolve +# to whatever its same-named Set captured (scope-local). +_SET_TYPES = frozenset({"SetNode"}) +_GET_TYPES = frozenset({"GetNode"}) +_UI_ONLY_TYPES = frozenset( + { + "Note", + "MarkdownNote", + "Image Comparer (rgthree)", + "GH_ImageVideoComparer", + "Label (rgthree)", + "Fast Groups Bypasser (rgthree)", + "Fast Groups Muter (rgthree)", + "Fast Muter (rgthree)", + "FastGroupsBypassSwitch", + "Mute / Bypass Repeater (rgthree)", + } +) + +# Server-side OUTPUT nodes: the closure roots. Learned from the repo's +# ground-truth API exports (their unreferenced classes) + the corpus's +# real save/preview sinks (SaveVideo/SaveImageAdvanced/… custom nodes). +_OUTPUT_CLASSES = frozenset( + { + "SaveImage", + "PreviewImage", + "SaveImageAdvanced", + "SaveImageKJ", + "SaveAnimatedWEBP", + "SaveAnimatedPNG", + "SaveAnimatedGIF", + "SaveVideo", + "SaveAudio", + "SaveAudioMP3", + "SaveAudioAdvanced", + "PreviewAudio", + "MaskPreview", + "MaskPreview+", + "ImageAndMaskPreview", + "VHS_VideoCombine", + "easy saveVideo", + "easy multitrackProjectVideoCombine", + "easy multiTrackInfoOutput", + "easy multiTrackTaskOutput", + "easy compareVideos", + "easy compareImages", + "easy showText", + "easy imageWall", + "CR Prompt Text", + "PreviewAny", + "easy clearGpuUsed", + "easy clearCacheAll", + "easy showSpentTime", + } +) + +MODE_ACTIVE = 0 +MODE_MUTED = 2 +MODE_BYPASSED = 4 + +_SUBGRAPH_IN = -10 # pseudo-node id of a subgraph's boundary input +_SUBGRAPH_OUT = -20 # pseudo-node id of a subgraph's boundary output + + +@dataclass +class ConvertIssue: + node_id: str + code: str + message: str + level: str = "warning" # 'error' | 'warning' + + +@dataclass +class ConvertResult: + workflow: dict[str, Any] | None + status: str # 'ok' | 'warn' | 'fail' + issues: list[ConvertIssue] = field(default_factory=list) + + @property + def needs_confirmation(self) -> bool: + """Widget mapping uncertain — must not be imported as runnable.""" + return any( + i.code in ("widget_unmapped", "widget_order_mismatch") for i in self.issues + ) + + +def _norm_link(link: Any) -> tuple[int, int, int, int, int, str] | None: + """(id, origin_id, origin_slot, target_id, target_slot, type) from either form.""" + if isinstance(link, dict): + try: + return ( + int(link["id"]), + int(link["origin_id"]), + int(link["origin_slot"]), + int(link["target_id"]), + int(link["target_slot"]), + str(link.get("type") or "*"), + ) + except (KeyError, TypeError, ValueError): + return None + if isinstance(link, (list, tuple)) and len(link) >= 5: + try: + return ( + int(link[0]), + int(link[1]), + int(link[2]), + int(link[3]), + int(link[4]), + str(link[5]) if len(link) > 5 and link[5] else "*", + ) + except (TypeError, ValueError): + return None + return None + + +def _is_seed_like(name: str) -> bool: + lowered = name.lower() + return lowered in ("seed", "noise_seed", "value", "rand_seed", "random_seed") or ( + lowered.endswith("seed") + ) + + +def _is_upload_entry(name: str, type_: str) -> bool: + return type_.upper().endswith("UPLOAD") or name == "upload" or "UPLOAD" in type_.upper() + + +class _Converter: + """One conversion run over a single UI-format document.""" + + def __init__(self, ui: dict[str, Any]) -> None: + self.ui = ui + self.issues: list[ConvertIssue] = [] + self.subgraphs: dict[str, dict[str, Any]] = { + str(s.get("id")): s + for s in self.ui.get("definitions", {}).get("subgraphs", []) or [] + if isinstance(s, dict) + } + # qualified id → UI node + owning scope + self.nodes: dict[str, dict[str, Any]] = {} + # scope key ('' for top level) → link table / node-id index / owner + self.scope_links: dict[str, dict[int, tuple[int, int, int, int, str]]] = {} + self.scope_ids: dict[str, dict[str, str]] = {} + self.scope_owner: dict[str, str] = {} + self._set_capture_cache: dict[str, dict[str, tuple[str, int]]] = {} + self._set_names: dict[str, set[str]] = {} + self._depth = 0 + self._cycle_warned = False + self._set_building: set[str] = set() + + # -------------------------------------------------------------- indexing + def _index_scope(self, scope: str, links: list[Any], owner: str | None) -> None: + table = self.scope_links.setdefault(scope, {}) + for link in links or []: + norm = _norm_link(link) + if norm is not None: + table[norm[0]] = norm[1:] + self.scope_ids.setdefault(scope, {}) + if owner is not None: + self.scope_owner[scope] = owner + + def _flatten( + self, node: dict[str, Any], scope: str, prefix: str + ) -> None: + qualified = f"{prefix}{node.get('id')}" + self.nodes[qualified] = {"node": node, "scope": scope} + self.scope_ids.setdefault(scope, {})[str(node.get("id"))] = qualified + sub = self.subgraphs.get(str(node.get("type") or "")) + if sub is None: + return + if not isinstance(sub.get("nodes"), list): + self.issues.append( + ConvertIssue(qualified, "subgraph_bad_definition", "子图缺少内部节点定义") + ) + return + sub_scope = f"{scope}|{node.get('type')}" if scope else f"{node.get('type')}" + if sub_scope not in self.scope_links: + self._index_scope(sub_scope, sub.get("links") or [], qualified) + for inner in sub["nodes"]: + if isinstance(inner, dict): + self._flatten(inner, sub_scope, f"{qualified}:") + + # --------------------------------------------------------------- lookups + def _node(self, qualified: str) -> dict[str, Any] | None: + entry = self.nodes.get(qualified) + return entry["node"] if entry else None + + def _scope(self, qualified: str) -> str: + entry = self.nodes.get(qualified) + return entry["scope"] if entry else "" + + def _link(self, scope: str, link_id: Any) -> tuple[int, int, int, int, str] | None: + if link_id is None: + return None + try: + key = int(link_id) + except (TypeError, ValueError): + return None + return self.scope_links.get(scope, {}).get(key) + + def _boundary_source(self, scope: str, link_id: Any) -> tuple[str, int] | None: + """(packed qualified id, boundary slot) when this link leaves a + subgraph through its -10 input boundary.""" + link = self._link(scope, link_id) + if link is None or link[0] != _SUBGRAPH_IN: + return None + packed_q = self.scope_owner.get(scope) + if packed_q is None: + return None + return packed_q, link[1] + + def _subgraph_of(self, qualified: str) -> dict[str, Any] | None: + node = self._node(qualified) + if node is None: + return None + return self.subgraphs.get(str(node.get("type") or "")) + + @staticmethod + def _virtual_name(node: dict[str, Any]) -> str: + """A Set/Get node's captured variable name (its first widget value).""" + named = node.get("widgets_values_named") + if isinstance(named, dict): + for key in ("const_name", "name", "value"): + if key in named: + return str(named[key]) + values = node.get("widgets_values") + if isinstance(values, list) and values and isinstance(values[0], str): + return values[0] + return "" + + def _set_captures(self, scope: str) -> dict[str, tuple[str, int]]: + """{variable name → resolved source} for the Set nodes in one scope.""" + table = self._set_capture_cache.get(scope) + if table is not None: + return table + table = {} + # Seed before resolving: a Set feeding a same-named Get (FOR-loop + # graphs) would otherwise recurse into this builder forever. A miss + # while building is not a missing Set — never warn mid-construction. + self._set_capture_cache[scope] = table + self._set_building.add(scope) + try: + return self._build_set_captures(scope, table) + finally: + self._set_building.discard(scope) + + def _build_set_captures( + self, scope: str, table: dict[str, tuple[str, int]] + ) -> dict[str, tuple[str, int]]: + names: set[str] = set() + for qualified, entry in self.nodes.items(): + if entry["scope"] != scope: + continue + node = entry["node"] + if str(node.get("type") or "") not in _SET_TYPES: + continue + name = self._virtual_name(node) + if not name: + continue + names.add(name) + ins = self._inputs_of(node) + link = self._link(scope, ins[0].get("link")) if ins else None + resolved = self._resolve_link(scope, link) + if resolved is not None: + table.setdefault(name, resolved) + self._set_names[scope] = names + self._set_capture_cache[scope] = table + return table + + @staticmethod + def _inputs_of(node: dict[str, Any]) -> list[dict[str, Any]]: + return [i for i in node.get("inputs") or [] if isinstance(i, dict)] + + @staticmethod + def _outputs_of(node: dict[str, Any]) -> list[dict[str, Any]]: + return [o for o in node.get("outputs") or [] if isinstance(o, dict)] + + # ------------------------------------------------------------- resolution + def _resolve_link( + self, scope: str, link: tuple[int, int, int, int, str] | None + ) -> tuple[str, int] | None: + """Resolve one link (in scope) to an API source (qualified id, slot).""" + if link is None: + return None + if self._depth > 200: # Set/Get cycles (FOR-loop graphs) never unwind + if not self._cycle_warned: + self._cycle_warned = True + self.issues.append( + ConvertIssue( + "", + "cyclic_variable", + "变量/Set-Get 连线存在循环(常见于 FOR 循环流),该连线按未连接处理", + ) + ) + return None + self._depth += 1 + try: + return self._resolve_link_inner(scope, link) + finally: + self._depth -= 1 + + def _resolve_link_inner( + self, scope: str, link: tuple[int, int, int, int, str] + ) -> tuple[str, int] | None: + origin_id, origin_slot = link[0], link[1] + if origin_id == _SUBGRAPH_IN: + # Boundary: hand off to the packed instance's own input slot. + packed_q = self.scope_owner.get(scope) + if packed_q is None: + return None + node = self._node(packed_q) + if node is None: + return None + entries = self._inputs_of(node) + if origin_slot >= len(entries): + return None + entry = entries[origin_slot] + if entry.get("link") is None: + return None # unlinked boundary → inner widget value applies + outer = self._scope(packed_q) + return self._resolve_link(outer, self._link(outer, entry.get("link"))) + qualified = self.scope_ids.get(scope, {}).get(str(origin_id)) + if qualified is None: + return None + return self._resolve_source(qualified, origin_slot) + + def _resolve_source(self, qualified: str, slot: int) -> tuple[str, int] | None: + """What an outgoing edge from (node, output slot) really connects to.""" + node = self._node(qualified) + if node is None: + return None + node_type = str(node.get("type") or "") + mode = node.get("mode") or 0 + scope = self._scope(qualified) + + if node_type in _UI_ONLY_TYPES: + return None + + if node_type in _REROUTE_TYPES: + ins = self._inputs_of(node) + if not ins: + return None + return self._resolve_link(scope, self._link(scope, ins[0].get("link"))) + + if node_type in _SET_TYPES: + ins = self._inputs_of(node) + if not ins: + return None + return self._resolve_link(scope, self._link(scope, ins[0].get("link"))) + + if node_type in _GET_TYPES: + name = self._virtual_name(node) + captured = self._set_captures(scope).get(name) + if captured is None and scope not in self._set_building: + if name in self._set_names.get(scope, set()): + self.issues.append( + ConvertIssue( + qualified, + "variable_upstream_dropped", + f"变量「{name}」的上游被旁路或未连接,取值按未连接处理", + ) + ) + else: + self.issues.append( + ConvertIssue( + qualified, + "get_without_set", + f"变量节点「{name}」没有对应的 Set 节点", + ) + ) + return captured + + sub = self._subgraph_of(qualified) + if sub is not None: + outputs = [o for o in sub.get("outputs") or [] if isinstance(o, dict)] + if slot >= len(outputs): + return None + sub_scope = f"{scope}|{node_type}" if scope else node_type + for link in self.scope_links.get(sub_scope, {}).values(): + if link[2] == _SUBGRAPH_OUT and link[3] == slot: + inner_q = self.scope_ids.get(sub_scope, {}).get(str(link[0])) + return self._resolve_source(inner_q, link[1]) if inner_q else None + return None # boundary output with no inner source + + if mode == MODE_MUTED: + return None + if mode == MODE_BYPASSED: + return self._bypass_through(qualified, slot) + return (qualified, slot) + + def _bypass_through(self, qualified: str, slot: int) -> tuple[str, int] | None: + """Pass-through of a bypassed node: same-name input first, then same-type.""" + node = self._node(qualified) + if node is None: + return None + outputs = self._outputs_of(node) + out = outputs[slot] if slot < len(outputs) else {} + out_name = str(out.get("name") or "") + out_type = str(out.get("type") or "*") + linkable = [ + e for e in self._inputs_of(node) if not e.get("widget") and e.get("link") is not None + ] + pick = None + if out_name: + pick = next((e for e in linkable if str(e.get("name") or "") == out_name), None) + if pick is None: + pick = next( + ( + e + for e in linkable + if out_type == "*" or str(e.get("type") or "*") in (out_type, "*") + ), + None, + ) + if pick is None: + return None + scope = self._scope(qualified) + return self._resolve_link(scope, self._link(scope, pick.get("link"))) + + # --------------------------------------------------------- widget mapping + def _widget_entries(self, node: dict[str, Any]) -> list[tuple[str, str]]: + """[(name, type)] of entries carrying the ``widget`` marker, in order.""" + out: list[tuple[str, str]] = [] + for entry in self._inputs_of(node): + marker = entry.get("widget") + if isinstance(marker, dict): + name = str(marker.get("name") or entry.get("name") or "") + if name: + out.append((name, str(entry.get("type") or ""))) + return out + + def _widgets_from_entries( + self, + node_id: str, + entries: list[tuple[str, str]], + values: Any, + ) -> tuple[dict[str, Any], list[ConvertIssue]]: + """Map widget values using the node's serialized input list.""" + inputs: dict[str, Any] = {} + issues: list[ConvertIssue] = [] + if isinstance(values, dict): + for name, type_ in entries: + if name in _BUTTON_WIDGETS or self._is_upload(name, type_): + continue + if name in values: + inputs[name] = values[name] + else: + issues.append( + ConvertIssue(node_id, "widget_unmapped", f"控件「{name}」没有序列化值") + ) + return inputs, issues + if not isinstance(values, list): + return inputs, issues + if not values: + return inputs, issues # nothing serialized — server defaults apply + i = 0 + for name, type_ in entries: + if name in _BUTTON_WIDGETS: + continue # button widgets never serialize + if i >= len(values): + issues.append( + ConvertIssue(node_id, "widget_order_mismatch", f"控件值数量不足({name})") + ) + break + value = values[i] + i += 1 + if self._is_upload(name, type_): + continue # consumes a slot, never an API input + inputs[name] = value + if ( + type_.upper() == "INT" + and _is_seed_like(name) + and i < len(values) + and values[i] in _CONTROL_MODES + ): + i += 1 # control_after_generate rides right after its seed + leftover_ok = all(_is_button_leftover(v) for v in values[i:]) + if not issues and i != len(values) and not leftover_ok: + issues.append( + ConvertIssue( + node_id, + "widget_order_mismatch", + f"有 {len(values)} 个控件值,输入清单只覆盖 {i} 个", + ) + ) + return inputs, issues + + @staticmethod + def _is_upload(name: str, type_: str) -> bool: + return _is_upload_entry(name, type_) + + def _widgets_from_registry( + self, node: dict[str, Any], values: list[Any] + ) -> tuple[dict[str, Any], list[ConvertIssue]]: + node_type = str(node.get("type") or "") + if not values: + return {}, [] # nothing serialized — server defaults apply + for order in WIDGET_ORDERS.get(node_type) or []: + inputs: dict[str, Any] = {} + i = 0 + for name in order: + if name in _BUTTON_WIDGETS: + continue + if i >= len(values): + break + value = values[i] + i += 1 + if _is_upload_entry(name, ""): + continue + inputs[name] = value + if _is_seed_like(name) and i < len(values) and values[i] in _CONTROL_MODES: + i += 1 + if i == len(values) or all(_is_button_leftover(v) for v in values[i:]): + return inputs, [] # exact fit, or trailing button leftovers + return {}, [ + ConvertIssue( + node.get("id", ""), + "widget_unmapped" if not WIDGET_ORDERS.get(node_type) else "widget_order_mismatch", + f"「{node_type}」的 {len(values)} 个控件值无法可靠对应到输入名", + ) + ] + + def _packed_widget_values(self, qualified: str) -> Any: + """Exposed widget values of a packed instance as {boundary name: value}.""" + node = self._node(qualified) + sub = self._subgraph_of(qualified) + if node is None or sub is None: + return None + boundary = [i for i in sub.get("inputs") or [] if isinstance(i, dict)] + named = node.get("widgets_values_named") + if isinstance(named, dict): + return named + values = node.get("widgets_values") + if not isinstance(values, list): + return None + out: dict[str, Any] = {} + i = 0 + for entry in boundary: + name = str(entry.get("name") or "") + type_ = str(entry.get("type") or "") + if name and i < len(values): + out[name] = values[i] + i += 1 + if ( + type_.upper() == "INT" + and _is_seed_like(name) + and i < len(values) + and values[i] in _CONTROL_MODES + ): + i += 1 + return out + + # -------------------------------------------------------------- serialize + def _serialize_node(self, qualified: str) -> dict[str, Any] | None: + node = self._node(qualified) + if node is None: + return None + node_type = str(node.get("type") or "") + if ( + not node_type + or node_type in _UI_ONLY_TYPES + or node_type in _REROUTE_TYPES + or node_type in _SET_TYPES + or node_type in _GET_TYPES + ): + return None + scope = self._scope(qualified) + inputs: dict[str, Any] = {} + + widget_values = node.get("widgets_values_named") + if not isinstance(widget_values, dict): + widget_values = node.get("widgets_values") + if self._subgraph_of(qualified) is not None: + widget_values = self._packed_widget_values(qualified) + + widget_inputs: dict[str, Any] = {} + entries = self._widget_entries(node) + if widget_values is not None: + if entries: + widget_inputs, w_issues = self._widgets_from_entries( + qualified, entries, widget_values + ) + self.issues.extend(w_issues) + elif isinstance(widget_values, dict): + widget_inputs = { + k: v for k, v in widget_values.items() if k not in _BUTTON_WIDGETS + } + elif isinstance(widget_values, list): + widget_inputs, w_issues = self._widgets_from_registry(node, widget_values) + self.issues.extend(w_issues) + + for entry in self._inputs_of(node): + name = str(entry.get("name") or "") + if not name or name in inputs: + continue + if entry.get("link") is None: + continue # unconnected optional input; widget values applied below + # Widget entries fed from the subgraph boundary (-10): when the + # packed instance left that boundary slot unlinked, the value is + # the packed node's own exposed widget value, not the inner one. + boundary = self._boundary_source(scope, entry.get("link")) + if boundary is not None: + packed_q, boundary_slot = boundary + packed_node = self._node(packed_q) + packed_entries = self._inputs_of(packed_node) if packed_node else [] + if boundary_slot < len(packed_entries) and packed_entries[ + boundary_slot + ].get("link") is None: + values = self._packed_widget_values(packed_q) + boundary_name = str(packed_entries[boundary_slot].get("name") or "") + if isinstance(values, dict) and boundary_name in values: + inputs[name] = values[boundary_name] + continue + # linked boundary falls through to normal resolution + link = self._link(scope, entry.get("link")) + if link is None: + self.issues.append( + ConvertIssue(qualified, "dangling_link", f"输入「{name}」的连线不存在") + ) + continue + resolved = self._resolve_link(scope, link) + if resolved is not None: + inputs[name] = [resolved[0], resolved[1]] + elif entry.get("widget"): + pass # muted upstream: the widget value below takes over + else: + self.issues.append( + ConvertIssue( + qualified, + "muted_input_dropped", + f"输入「{name}」上游被静音,已按未连接处理", + ) + ) + + for name, value in widget_inputs.items(): + inputs.setdefault(name, value) + + api_node: dict[str, Any] = {"class_type": node_type, "inputs": inputs} + title = str(node.get("title") or "").strip() + if title: + api_node["_meta"] = {"title": title} + return api_node + + # ------------------------------------------------------------------- main + def run(self) -> ConvertResult: + nodes = self.ui.get("nodes") + if not isinstance(nodes, list) or not nodes: + return ConvertResult( + None, + "fail", + [ConvertIssue("", "no_nodes", "文件不含 nodes 数组,不是 UI 格式工作流", "error")], + ) + try: + self._index_scope("", self.ui.get("links") or [], None) + for node in nodes: + if isinstance(node, dict): + self._flatten(node, "", "") + except RecursionError: + return ConvertResult( + None, "fail", [ConvertIssue("", "subgraph_recursion", "子图嵌套过深", "error")] + ) + + # Closure from known output nodes (ComfyUI's own graphToPrompt roots). + roots = [ + q + for q, entry in self.nodes.items() + if str(entry["node"].get("type") or "") in _OUTPUT_CLASSES + and (entry["node"].get("mode") or 0) == MODE_ACTIVE + ] + keep: dict[str, None] = {} + stack = list(roots) + while stack: + qualified = stack.pop() + if qualified in keep: + continue + entry = self.nodes.get(qualified) + if entry is None: + continue + keep[qualified] = None + node = entry["node"] + scope = entry["scope"] + for e in self._inputs_of(node): + if e.get("link") is None: + continue + link = self._link(scope, e.get("link")) + resolved = self._resolve_link(scope, link) + if resolved is not None: + stack.append(resolved[0]) + + if not keep: + # No known output node: keep every active computed node and warn — + # the import lint will report the missing output separately. + for qualified, entry in self.nodes.items(): + node = entry["node"] + node_type = str(node.get("type") or "") + if ( + node_type in _UI_ONLY_TYPES + or node_type in _REROUTE_TYPES + or (node.get("mode") or 0) != MODE_ACTIVE + or self._subgraph_of(qualified) is not None + ): + continue + keep[qualified] = None + self.issues.append( + ConvertIssue( + "", + "no_output_node", + "图中没有已知输出节点(SaveImage / 视频合成等)," + "全部活跃节点已保留,需人工确认", + ) + ) + + workflow: dict[str, Any] = {} + for qualified in keep: + api_node = self._serialize_node(qualified) + if api_node is not None and api_node["class_type"]: + workflow[qualified] = api_node + + if not workflow: + return ConvertResult( + None, + "fail", + self.issues or [ConvertIssue("", "empty", "转换后没有任何节点", "error")], + ) + status = ( + "fail" + if any(i.level == "error" for i in self.issues) + else ("ok" if not self.issues else "warn") + ) + return ConvertResult(workflow, status, self.issues) + + +def convert_ui_workflow(ui: dict[str, Any]) -> ConvertResult: + """Convert one ComfyUI UI-format workflow dict into API format.""" + if not isinstance(ui, dict) or not isinstance(ui.get("nodes"), list): + return ConvertResult( + None, + "fail", + [ConvertIssue("", "not_ui_format", "不是 UI 格式(缺少 nodes 数组)", "error")], + ) + return _Converter(ui).run() diff --git a/calliope-backend/src/calliope/comfyui/ui_widget_orders.py b/calliope-backend/src/calliope/comfyui/ui_widget_orders.py new file mode 100644 index 00000000..63b7c098 --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/ui_widget_orders.py @@ -0,0 +1,2085 @@ +"""GENERATED by scripts/build_widget_orders.py — do not edit by hand. + +Widget-order registry for the UI→API converter: class_type → candidate +widget name orders, learned from the repo's named-widget UI files and +ground-truth API exports (HEL-681). +""" + +from __future__ import annotations + +WIDGET_ORDERS: dict[str, list[list[str]]] = { + "1970dcb4-982a-4c01-a373-4d239a3041e4": [ + [ + "resize_type.multiplier", + "seed", + "steps", + "cfg", + "sampler_name", + "scheduler", + "denoise", + "unet_name", + "vae_name", + "color_correction_method", + "temporal_size" + ], + [ + "switch", + "start_time", + "duration", + "resize_type.multiplier_1", + "seed_1", + "sampler_name", + "scheduler", + "denoise", + "color_correction_method", + "unet_name", + "vae_name" + ] + ], + "1d5d08b2-2321-43b2-8d8c-0964dc6c6e86": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "23694d89-9fa2-4beb-a712-55beda8c219b": [ + [ + "resolution", + "prompt", + "switch_1", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "device", + "dtype", + "clip_name_1" + ] + ], + "245fac4e-786b-4738-ae3a-982feb33a47d": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "316e9ff3-946b-4908-8b75-b7764b83e62d": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "3aeaa78c-6341-4b9f-aded-e3be0df01b1e": [ + [ + "draw_body", + "draw_hands", + "draw_face", + "draw_feet", + "stick_width", + "face_point_size", + "score_threshold", + "ckpt_name" + ] + ], + "4652eac2-3224-403e-868d-4781efcf3323": [ + [ + "model", + "mmproj", + "chat_handler", + "max_tokens", + "preset_prompt", + "custom_prompt", + "system_prompt", + "inference_mode", + "seed" + ] + ], + "4c314f31-ecda-4b08-ae98-faaba1bf613f": [ + [ + "prompt", + "width", + "height", + "value_1", + "noise_seed", + "unet_name", + "clip_name", + "vae_name", + "vae_name_1", + "attention" + ], + [ + "prompt", + "width", + "height", + "value_1", + "noise_seed", + "unet_name", + "clip_name", + "vae_name", + "vae_name_1", + "value", + "lora_name", + "strength_model_1", + "value_2" + ] + ], + "5b702329-a5ec-4a7d-b000-213d0c04bbbd": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "60854551-a681-4795-8914-96489c548bc0": [ + [ + "prompt", + "switch", + "thinking", + "negative_prompt", + "cfg", + "steps", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "clip_name_1", + "device", + "dtype_1" + ] + ], + "67c5ffbb-368e-43ce-802a-208b96182548": [ + [ + "resolution", + "prompt", + "switch_1", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "device", + "dtype", + "clip_name_1" + ] + ], + "79dd8a95-ce9d-4c14-b264-2162e8bec5ce": [ + [ + "prompt", + "width", + "height", + "value_1", + "noise_seed", + "unet_name", + "clip_name", + "vae_name", + "vae_name_1", + "value", + "lora_name", + "strength_model_1", + "value_2" + ] + ], + "79e9ee75-e8e2-472d-894d-cbe8148acbba": [ + [ + "total", + "b", + "upscale", + "video", + "force_rate", + "seed" + ] + ], + "82296023-8cad-4454-9020-339570cedc2c": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "AIO_Preprocessor": [ + [ + "preprocessor", + "resolution" + ] + ], + "AddLabel": [ + [ + "text_x", + "text_y", + "height", + "font_size", + "font_color", + "label_color", + "font", + "text", + "direction" + ] + ], + "AnyLineArtPreprocessor_aux": [ + [ + "merge_with_lineart", + "resolution", + "lineart_lower_bound", + "lineart_upper_bound", + "object_min_size", + "object_connectivity" + ] + ], + "AudioCrop": [ + [ + "start_time", + "end_time" + ] + ], + "BasicGuider": [ + [] + ], + "BasicScheduler": [ + [ + "scheduler", + "steps", + "denoise" + ] + ], + "BlockSparseAttention": [ + [ + "selection", + "selection.keep_percent", + "start_percent", + "end_percent", + "dense_blocks", + "min_tokens", + "extra_tokens", + "sink_conditioning", + "verbose" + ], + [ + "selection", + "selection.tau", + "start_percent", + "end_percent", + "dense_blocks", + "min_tokens", + "extra_tokens", + "sink_conditioning", + "verbose" + ] + ], + "CFGGuider": [ + [ + "cfg" + ] + ], + "CLIPLoader": [ + [ + "clip_name", + "type", + "device" + ] + ], + "CLIPTextEncode": [ + [ + "text" + ], + [] + ], + "CR Prompt Text": [ + [ + "prompt" + ] + ], + "CheckpointLoaderSimple": [ + [ + "ckpt_name" + ] + ], + "ColorCorrect": [ + [ + "temperature", + "hue", + "brightness", + "contrast", + "saturation", + "gamma" + ] + ], + "ComfyMathExpression": [ + [ + "expression" + ] + ], + "ComfySwitchNode": [ + [ + "switch" + ], + [] + ], + "ConditioningZeroOut": [ + [] + ], + "CreateVideo": [ + [ + "fps", + "bit_depth", + "color_space", + "codec" + ], + [ + "fps", + "bit_depth" + ] + ], + "DA3Inference": [ + [ + "resolution", + "resize_method", + "mode" + ] + ], + "DA3Render": [ + [ + "output", + "output.normalization", + "output.apply_sky_clip" + ] + ], + "Display Any (rgthree)": [ + [ + "output" + ] + ], + "EmptyLatentImage": [ + [ + "width", + "height", + "batch_size" + ] + ], + "EmptyMiniMaxMusic3LatentAudio": [ + [ + "seconds", + "batch_size" + ] + ], + "EmptySD3LatentImage": [ + [ + "width", + "height", + "batch_size" + ] + ], + "FisherQwenFreePose": [ + [ + "width", + "height", + "reference_resolution", + "extra_prompt", + "pose_json", + "打开自由姿势编辑器" + ] + ], + "FluxKontextMultiReferenceLatentMethod": [ + [ + "reference_latents_method" + ] + ], + "FrameInterpolate": [ + [ + "multiplier" + ] + ], + "FrameInterpolationModelLoader": [ + [ + "model_name" + ] + ], + "GH_ImageVideoComparer": [ + [ + "gh_image_video_comparer" + ] + ], + "GetImageSize": [ + [] + ], + "GetNode": [ + [ + "Constant" + ] + ], + "GoohaiAnyExists": [ + [ + "gh_input_type" + ] + ], + "GoohaiMinimaxH3LatentUpscalerGH": [ + [ + "model_name", + "mode", + "mode.scale", + "align", + "force_unload", + "device", + "precision" + ] + ], + "GoohaiMinimaxH3TiledSampler": [ + [ + "enable_tiling", + "n_tiles", + "tile_overlap", + "refine_seams", + "refine_steps" + ] + ], + "GoohaiRatioAndResolution": [ + [ + "比例", + "模式", + "固定边像素", + "百万像素", + "长边最小", + "长边最大", + "自定宽度", + "自定高度", + "倍数取整" + ] + ], + "GoohaiRouteBlocker": [ + [ + "是否阻断", + "阻断模式" + ] + ], + "GoohaiUniversalSlider": [ + [ + "值", + "output_type", + "ghs_ui" + ] + ], + "H3LVUnified": [ + [ + "mode", + "max_seconds", + "target_seconds", + "asr_python", + "asr_model", + "asr_device", + "director_mode", + "project_id", + "segment_index" + ] + ], + "H3SigmaRefiner": [ + [ + "extra_steps", + "start_at_sigma", + "end_at_sigma", + "spacing" + ] + ], + "INTConstant": [ + [ + "value" + ] + ], + "Image Comparer (rgthree)": [ + [ + "rgthree_comparer" + ] + ], + "ImageBatchMulti": [ + [ + "inputcount", + "Update inputs" + ] + ], + "ImageConcatFromBatch": [ + [ + "num_columns", + "match_image_size", + "max_resolution" + ] + ], + "ImageConcatMulti": [ + [ + "inputcount", + "direction", + "match_image_size", + "Update inputs" + ] + ], + "ImageFromBatch": [ + [ + "batch_index", + "length" + ] + ], + "ImageResizeKJv2": [ + [ + "width", + "height", + "upscale_method", + "keep_proportion", + "pad_color", + "crop_position", + "divisible_by", + "device" + ], + [ + "upscale_method", + "keep_proportion", + "pad_color", + "crop_position", + "divisible_by", + "device" + ] + ], + "ImageScaleToTotalPixels": [ + [ + "upscale_method", + "megapixels", + "resolution_steps" + ] + ], + "ImageStitch": [ + [ + "direction", + "match_image_size", + "spacing_width", + "spacing_color" + ] + ], + "Int": [ + [ + "Number" + ] + ], + "JsonExtractString": [ + [ + "json_string", + "key" + ] + ], + "KSampler": [ + [ + "seed", + "control_after_generate", + "steps", + "cfg", + "sampler_name", + "scheduler", + "denoise" + ], + [ + "seed", + "steps", + "cfg", + "sampler_name", + "scheduler", + "denoise" + ] + ], + "KSamplerSelect": [ + [ + "sampler_name" + ] + ], + "Krea2EditGroundedEncode": [ + [ + "prompt", + "grounding_px", + "system_prompt" + ] + ], + "Krea2EditModelPatch": [ + [ + "ref_boost", + "ref_boost_a", + "fit_mode" + ] + ], + "Krea2OstrisEditModelPatch": [ + [ + "kv_cache" + ] + ], + "LTXVAudioVAEDecode": [ + [] + ], + "LTXVAudioVAEEncode": [ + [] + ], + "LTXVConcatAVLatent": [ + [] + ], + "LTXVConditioning": [ + [] + ], + "LTXVImgToVideoInplace": [ + [ + "strength", + "bypass" + ] + ], + "LTXVLatentUpsampler": [ + [] + ], + "LTXVSeparateAVLatent": [ + [] + ], + "LatentUpscaleModelLoader": [ + [ + "model_name" + ] + ], + "LayerUtility: ImageScaleByAspectRatio V2": [ + [ + "aspect_ratio", + "proportional_width", + "proportional_height", + "fit", + "method", + "round_to_multiple", + "scale_to_side", + "scale_to_length", + "background_color" + ] + ], + "LayerUtility: PurgeVRAM": [ + [ + "purge_cache", + "purge_models" + ] + ], + "LayerUtility: PurgeVRAM V2": [ + [ + "purge_cache", + "purge_models" + ] + ], + "LoadAudio": [ + [ + "audio", + "upload" + ] + ], + "LoadDA3Model": [ + [ + "model_name", + "weight_dtype" + ] + ], + "LoadImage": [ + [ + "image", + "upload" + ], + [ + "image" + ] + ], + "LoadMoGeModel": [ + [ + "model_name" + ] + ], + "LoadVideo": [ + [ + "file", + "upload" + ] + ], + "LoraLoaderBypassModelOnly": [ + [ + "lora_name", + "strength_model" + ] + ], + "LoraLoaderModelOnly": [ + [ + "lora_name", + "strength_model" + ] + ], + "ManualSigmas": [ + [ + "sigmas" + ] + ], + "MarkdownNote": [ + [ + "text" + ] + ], + "MathExpression|pysssss": [ + [ + "expression" + ] + ], + "MiniMaxChunkFeedForward": [ + [ + "chunks", + "seq_threshold" + ] + ], + "MiniMaxH3AudioConditioningT8": [ + [ + "prompt", + "width", + "height", + "length", + "task_type", + "audio_mode", + "audio_denoise_strength", + "add_source_as_reference", + "prompt_primary_audio_ordinal", + "strict_prompt_tags", + "ref_image_size", + "reference_video_policy", + "allow_above_reference_area" + ], + [ + "prompt", + "width", + "height", + "length", + "task_type", + "audio_mode", + "audio_denoise_strength", + "add_source_as_reference", + "prompt_primary_audio_ordinal", + "strict_prompt_tags", + "ref_image_size", + "reference_video_policy" + ] + ], + "MiniMaxH3Director": [ + [ + "task_type", + "global_prompt", + "bd_grp_sample", + "cfg", + "seed", + "control_after_generate", + "frame_rate", + "width", + "height", + "ref_max_size", + "total_frames", + "timeline_data", + "bd_grp_advanced", + "steps", + "sampler", + "scheduler", + "shift_video", + "shift_audio", + "export_source_images", + "export_pre_face_refine", + "bd_grp_perf", + "clear_vram_between_segments", + "clear_vram_before_refine", + "clear_vram_before_face_refine", + "cache_frames_codec", + "minimax_director_ui" + ] + ], + "MiniMaxH3DirectorRefine": [ + [ + "mode", + "upscale_method", + "latent_upscale_model", + "sampler", + "passes", + "seed_mode", + "seed", + "control_after_generate", + "aspect_ratio", + "megapixels", + "width", + "height", + "skip_fl2v", + "confirm_first_pass", + "enable_latent_chunking", + "enable_tiling", + "tile_count", + "tile_overlap" + ] + ], + "MiniMaxH3DualClockSamplerT8": [ + [ + "steps", + "shift_video", + "shift_audio", + "sampler_name", + "scheduler" + ] + ], + "MiniMaxH3DualClockT8GH": [ + [ + "steps", + "shift_video", + "shift_audio", + "sampler_name", + "scheduler" + ] + ], + "MiniMaxH3EncodeAVPatched": [ + [] + ], + "MiniMaxH3FiniteSegmentSampler": [ + [ + "seed", + "control_after_generate", + "continue_audio_latent", + "ref_image_size" + ] + ], + "MiniMaxH3GuidedWriter": [ + [ + "prompt", + "model", + "task", + "resolution", + "duration", + "greedy", + "seed", + "control_after_generate", + "keep_model_loaded", + "aspect_ratio", + "reference_material", + "bypass", + "system_prompt", + "repeat_last", + "library_pick" + ] + ], + "MiniMaxH3HybridLoader": [ + [ + "base_model", + "overlay_model", + "overlay_preset", + "block_range_start", + "block_range_end", + "final_adaln_from_overlay", + "custom_overlays", + "custom_base", + "weight_dtype" + ] + ], + "MiniMaxH3ImageToVideo": [ + [ + "prompt", + "width", + "height", + "length" + ], + [] + ], + "MiniMaxH3IntegrationGH": [ + [ + "main_mode", + "clip_name", + "video_vae_name", + "audio_vae_name", + "aspect", + "megapixels", + "duration_seconds", + "prompt", + "task_type", + "audio_mode", + "audio_denoise_strength", + "drive_audio_ordinal", + "strict_prompt_tags", + "ref_image_size", + "first_frame", + "last_frame", + "hybrid_audio", + "ref_image_1", + "ref_image_2", + "ref_image_3", + "ref_image_4", + "ref_image_5", + "ref_image_6", + "ref_image_7", + "ref_image_8", + "ref_image_9", + "ref_video_1", + "ref_video_2", + "ref_video_3", + "ref_audio_1", + "ref_audio_2", + "ref_audio_3", + "gh_state_json", + "gh_h3_panel" + ] + ], + "MiniMaxH3LearnedLatentUpscaleT8Advanced": [ + [ + "model_name", + "size_mode", + "scale_by", + "target_megapixels", + "target_width", + "target_height", + "aspect_policy", + "max_anisotropy", + "precision", + "release_policy" + ] + ], + "MiniMaxH3LearnedTwoPassParityPlanT8Advanced": [ + [ + "base_steps", + "coarse_steps", + "refine_steps" + ] + ], + "MiniMaxH3PromptCheck": [ + [ + "prompt", + "task", + "duration" + ] + ], + "MiniMaxH3ReferenceToVideo": [ + [ + "prompt", + "width", + "height", + "length", + "ref_image_size" + ], + [ + "ref_image_size" + ] + ], + "MiniMaxH3SigmaShift": [ + [ + "shift_video", + "shift_audio" + ] + ], + "MiniMaxH3TimelinePlanner": [ + [ + "width", + "height", + "generation_seconds", + "timeline_data", + "minimax_h3_timeline" + ] + ], + "MiniMaxH3TwoPassDetailMixerT8Advanced": [ + [ + "shift_video", + "shift_audio", + "enable_tail", + "extra_tail_steps", + "tail_spacing", + "enable_model_time_bias", + "bias", + "bias_start_progress", + "bias_end_progress", + "bias_domain", + "enable_stg", + "stg_scale", + "stg_double_blocks", + "stg_start_progress", + "stg_end_progress", + "enable_restart", + "restart_video_sigma", + "restart_steps", + "restart_seed", + "control_after_generate" + ] + ], + "MiniMaxH3TwoPassLatentReconcileT8Advanced": [ + [ + "audio_policy", + "second_pass_audio_source", + "second_pass_audio_strength" + ] + ], + "MiniMaxH3VideoExtendPatched": [ + [ + "context_frames", + "pin_last_frame", + "ref_image_size" + ] + ], + "MiniMaxLowVRAMAttention": [ + [ + "head_chunks" + ] + ], + "MiniMaxMusic3TextEncode": [ + [ + "caption", + "lyrics", + "seed", + "control_after_generate", + "max_duration", + "cfg_scale", + "top_k" + ] + ], + "MinimaxH3LatentUpscaler3D": [ + [ + "model_name", + "mode", + "mode.scale", + "align", + "enable_temporal_chunking", + "force_unload", + "device", + "precision" + ], + [ + "model_name", + "mode", + "mode.width", + "mode.height", + "align", + "enable_temporal_chunking", + "force_unload", + "device", + "precision" + ] + ], + "MoGeInference": [ + [ + "resolution_level", + "fov_x_degrees", + "batch_size", + "force_projection", + "apply_mask", + "refine_steps" + ] + ], + "MoGeRender": [ + [ + "output" + ] + ], + "ModelAttentionBackend": [ + [ + "attention" + ] + ], + "ModelPreviewOverrideKJ": [ + [ + "max_resolution", + "jpeg_quality", + "suppress_default_preview", + "preview_frames", + "preview_fps", + "tiny_vae" + ] + ], + "Note": [ + [ + "text" + ] + ], + "PainterVRAM": [ + [ + "reserved", + "mode", + "clean_gpu_before" + ] + ], + "PathchSageAttentionKJ": [ + [ + "sage_attention", + "allow_compile" + ] + ], + "Power Lora Loader (rgthree)": [ + [ + "PowerLoraLoaderHeaderWidget", + "lora_1", + "➕ Add Lora" + ] + ], + "PreviewAny": [ + [] + ], + "PrimitiveBoolean": [ + [ + "value" + ] + ], + "PrimitiveFloat": [ + [ + "value" + ] + ], + "PrimitiveInt": [ + [ + "value", + "fixed" + ] + ], + "PrimitiveNode": [ + [ + "value" + ] + ], + "PrimitiveStringMultiline": [ + [ + "value" + ] + ], + "QwenH3PromptLocal": [ + [ + "prompt", + "skill", + "duration", + "llm_model", + "vision_model", + "think_mode", + "reasoning_effort", + "seed", + "control_after_generate", + "max_tokens", + "video_sample_frames_per_sec", + "force_unload_model" + ] + ], + "QwenImage21Cache": [ + [ + "device", + "dtype" + ] + ], + "QwenImagePromptOptimizer": [ + [ + "用户提示词", + "文生图模型", + "图生图模型", + "视觉模型", + "输出语言", + "透明背景", + "种子值", + "种子模式", + "卸载模型" + ] + ], + "RTXVideoSuperResolution": [ + [ + "resize_type", + "resize_type.scale", + "quality" + ] + ], + "RandomNoise": [ + [ + "noise_seed", + "control_after_generate" + ], + [ + "noise_seed" + ] + ], + "RegexExtract": [ + [ + "string", + "regex_pattern", + "mode", + "case_insensitive", + "multiline", + "dotall", + "group_index" + ] + ], + "ResizeImageMaskNode": [ + [ + "resize_type", + "resize_type.multiplier", + "scale_method" + ], + [ + "resize_type", + "resize_type.width", + "resize_type.height", + "resize_type.crop", + "scale_method" + ], + [ + "resize_type", + "resize_type.longer_size", + "scale_method" + ] + ], + "ResolutionSelector": [ + [ + "aspect_ratio", + "megapixels", + "multiple" + ], + [ + "aspect_ratio", + "multiple" + ] + ], + "SDPoseDrawKeypoints": [ + [ + "draw_body", + "draw_hands", + "draw_face", + "draw_feet", + "stick_width", + "face_point_size", + "score_threshold", + "draw_head" + ] + ], + "SDPoseKeypointExtractor": [ + [ + "batch_size" + ] + ], + "SamplerCustomAdvanced": [ + [] + ], + "SaveAudioAdvanced": [ + [ + "filename_prefix", + "format", + "format.quality" + ] + ], + "SaveImage": [ + [ + "filename_prefix" + ] + ], + "SaveImageAdvanced": [ + [ + "filename_prefix", + "format", + "format.bit_depth", + "format.input_color_space" + ] + ], + "SaveVideo": [ + [ + "filename_prefix", + "format", + "format.codec", + "codec" + ], + [ + "filename_prefix", + "format", + "codec" + ], + [ + "filename_prefix", + "format", + "format.codec", + "codec", + "codec.encoding" + ] + ], + "Seed (rgthree)": [ + [ + "seed" + ] + ], + "SeedNode": [ + [ + "seed", + "fixed" + ] + ], + "SeedVR2PostProcessing": [ + [ + "color_correction_method" + ] + ], + "SelfLiftAvatarH3Sampler": [ + [ + "seed", + "control_after_generate", + "cfg", + "transition_step", + "lowres_scale", + "rho", + "w_min", + "w_max", + "upscaler_model", + "highres_tiling", + "tiling_mode", + "tiling_tiles", + "tiling_axis", + "selflift_tiling_plan" + ] + ], + "SetLatentNoiseMask": [ + [] + ], + "SetNode": [ + [ + "Constant" + ] + ], + "ShowText|pysssss": [ + [ + "text_0" + ] + ], + "SimpleMath+": [ + [ + "value" + ] + ], + "SimpleMathDual+": [ + [ + "value_1", + "value_2" + ] + ], + "SolAttnPatch": [ + [ + "tau", + "start_percent", + "end_percent", + "min_tokens", + "int8_qk", + "sink_conditioning", + "morton", + "morton_curve", + "verbose" + ] + ], + "SolidMask": [ + [ + "value", + "width", + "height" + ], + [ + "value" + ] + ], + "SplitSigmas": [ + [ + "step" + ] + ], + "StringConcatenate": [ + [ + "string_a", + "delimiter" + ], + [ + "string_a", + "string_b", + "delimiter" + ], + [ + "delimiter" + ] + ], + "StringContains": [ + [ + "string", + "substring", + "case_sensitive" + ] + ], + "StringToNumber": [ + [ + "string", + "rounding" + ] + ], + "Text Load Line From File": [ + [ + "file_path", + "dictionary_name", + "label", + "mode", + "index" + ] + ], + "TextEncodeKrea2OstrisEdit": [ + [ + "prompt" + ] + ], + "TextEncodeQwenImage21": [ + [ + "prompt", + "negative_prompt", + "resolution" + ] + ], + "TextEncodeQwenImage21GH": [ + [ + "prompt", + "negative_prompt", + "latent_width", + "latent_height", + "mode", + "ref_image_size" + ] + ], + "TextGenerate": [ + [ + "prompt", + "max_length", + "sampling_mode", + "sampling_mode.temperature", + "sampling_mode.top_k", + "sampling_mode.top_p", + "sampling_mode.min_p", + "sampling_mode.repetition_penalty", + "sampling_mode.seed", + "sampling_mode.presence_penalty", + "thinking", + "use_default_template", + "mtp" + ], + [ + "max_length", + "sampling_mode", + "sampling_mode.temperature", + "sampling_mode.top_k", + "sampling_mode.top_p", + "sampling_mode.min_p", + "sampling_mode.repetition_penalty", + "sampling_mode.seed", + "sampling_mode.presence_penalty", + "thinking", + "use_default_template" + ], + [ + "prompt", + "max_length", + "sampling_mode", + "sampling_mode.temperature", + "sampling_mode.top_k", + "sampling_mode.top_p", + "sampling_mode.min_p", + "sampling_mode.repetition_penalty", + "sampling_mode.seed", + "sampling_mode.presence_penalty", + "thinking", + "use_default_template" + ] + ], + "TrimAudioDuration": [ + [ + "start_index", + "duration" + ] + ], + "UNETLoader": [ + [ + "unet_name", + "weight_dtype" + ] + ], + "UniBlockSwap": [ + [ + "num_blocks" + ] + ], + "UpscaleModelLoader": [ + [ + "model_name" + ] + ], + "VAEDecode": [ + [] + ], + "VAEDecodeAudio": [ + [] + ], + "VAEDecodeAudioTiled": [ + [ + "tile_size", + "overlap" + ] + ], + "VAEDecodeTiled": [ + [ + "tile_size", + "overlap", + "temporal_size", + "temporal_overlap" + ] + ], + "VAEEncode": [ + [] + ], + "VAEEncodeTiled": [ + [ + "tile_size", + "overlap", + "temporal_size", + "temporal_overlap" + ] + ], + "VAELoader": [ + [ + "vae_name" + ] + ], + "VHS_LoadImagePath": [ + [ + "image", + "custom_width", + "custom_height" + ] + ], + "VHS_LoadVideo": [ + [ + "video", + "force_rate", + "custom_width", + "custom_height", + "frame_load_cap", + "skip_first_frames", + "select_every_nth", + "format", + "choose video to upload", + "videopreview" + ], + [ + "video", + "force_rate", + "custom_width", + "custom_height", + "frame_load_cap", + "skip_first_frames", + "select_every_nth", + "format" + ] + ], + "VHS_LoadVideoPath": [ + [ + "video", + "force_rate", + "custom_width", + "custom_height", + "frame_load_cap", + "skip_first_frames", + "select_every_nth", + "format", + "videopreview" + ] + ], + "VHS_VideoCombine": [ + [ + "frame_rate", + "loop_count", + "filename_prefix", + "format", + "pix_fmt", + "crf", + "save_metadata", + "trim_to_audio", + "pingpong", + "save_output", + "videopreview" + ], + [ + "frame_rate", + "loop_count", + "filename_prefix", + "format", + "pix_fmt", + "crf", + "save_metadata", + "trim_to_audio", + "pingpong", + "save_output" + ], + [ + "loop_count", + "filename_prefix", + "format", + "pix_fmt", + "crf", + "save_metadata", + "trim_to_audio", + "pingpong", + "save_output" + ] + ], + "VOSR2ModelLoader": [ + [ + "model", + "dtype" + ] + ], + "VOSR2Upscale": [ + [ + "upscale", + "seed", + "fixed", + "color_alignment", + "tile_size", + "tile_overlap", + "vae_tile_size", + "vae_tile_overlap" + ] + ], + "Video Slice": [ + [ + "start_time", + "duration", + "strict_duration" + ] + ], + "ac99f841-a3de-4329-9564-953b81cf9e16": [ + [ + "caption", + "lyrics", + "max_duration", + "seed", + "unet_name", + "clip_name", + "vae_name", + "switch" + ] + ], + "b0e5ca93-2731-42b9-8e0a-d28ea851ff81": [ + [ + "value", + "value_1", + "max_length", + "thinking", + "width_1", + "height_1", + "seed_1", + "value_3", + "lora_name_1", + "strength_model_1", + "string_b_1", + "unet_name_1", + "clip_name_1", + "vae_name_1" + ] + ], + "ba9788bf-9dc0-49e4-9e55-19ebdbe54c4d": [ + [ + "resolution", + "prompt", + "switch_1", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "device", + "dtype", + "clip_name_1" + ] + ], + "bb1cc547-34f0-4c5a-a987-dbaad079b39d": [ + [ + "resize_type.multiplier", + "seed", + "steps", + "cfg", + "sampler_name", + "scheduler", + "denoise", + "unet_name", + "vae_name", + "color_correction_method", + "temporal_size" + ] + ], + "bc1c967a-7f6a-4be9-a372-dad16e4f28e3": [ + [ + "resolution", + "prompt", + "switch_1", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "device", + "dtype", + "clip_name_1" + ], + [ + "resolution", + "prompt", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "device", + "dtype" + ], + [ + "resolution", + "prompt", + "negative_prompt", + "cfg", + "steps", + "switch", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name" + ] + ], + "c1d30137-ea13-43b9-ba36-eaa5e90c63b8": [ + [ + "resize_type.multiplier_1", + "seed_1", + "sampler_name", + "scheduler", + "denoise", + "color_correction_method", + "unet_name", + "vae_name" + ] + ], + "c291ceec-b98f-4751-9d0b-7bc288f27b30": [ + [ + "prompt", + "switch", + "thinking", + "negative_prompt", + "cfg", + "steps", + "width", + "height", + "scheduler", + "scheduler_1", + "seed", + "unet_name", + "clip_name", + "vae_name", + "clip_name_1", + "device", + "dtype_1" + ] + ], + "ccd1d80d-83f8-49cd-8cdd-3dbcf528db88": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "e69cd71f-07c6-4740-a173-aaac13d4ec0b": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "easy anythingIndexSwitch": [ + [ + "index" + ] + ], + "easy cleanGpuUsed": [ + [] + ], + "easy clearCacheAll": [ + [] + ], + "easy compareVideos": [ + [ + "compare_video" + ] + ], + "easy float": [ + [ + "value" + ] + ], + "easy forLoopStart": [ + [ + "total" + ] + ], + "easy getNode": [ + [ + "Constant" + ] + ], + "easy ifElse": [ + [ + "boolean" + ] + ], + "easy indexAnything": [ + [ + "index" + ] + ], + "easy matchLine": [ + [ + "text", + "match" + ] + ], + "easy mergeVideosFromPaths": [ + [ + "frame_count", + "audio_mode" + ] + ], + "easy minimaxH3ToVideo": [ + [ + "prompt", + "mode", + "width", + "height", + "length", + "ref_image_size" + ], + [ + "prompt", + "mode", + "width", + "height", + "length", + "ref_image_size", + "locked_video_timing_frames" + ] + ], + "easy multiTrackEditor": [ + [ + "resolution", + "resolution.resize_method", + "format", + "track_data" + ], + [ + "resolution", + "resolution.aspect_ratio", + "resolution.megapixels", + "format", + "track_data" + ] + ], + "easy multiTrackTaskOutput": [ + [ + "task_index", + "prompt_format" + ] + ], + "easy multitrackProject": [ + [ + "project_name", + "project_save", + "segment_start_number", + "segment_count", + "seed", + "fixed", + "sampling_plan", + "sampling_mode", + "sampling_mode.transition_ratio", + "sampling_mode.lowres_scale", + "1st_pass_only", + "disable_2nd_noise", + "upscale_by", + "upscale_model", + "enabled_tiling", + "enabled_tiling.tile_count", + "easy-media-sampling-preview" + ] + ], + "easy multitrackProjectVideoCombine": [ + [ + "project_data" + ] + ], + "easy prompt": [ + [ + "text", + "prefix", + "subject", + "action", + "clothes", + "environment", + "background", + "nsfw" + ] + ], + "easy promptLine": [ + [ + "prompt", + "start_index", + "max_rows", + "remove_empty_lines", + "get values from COMBO link" + ] + ], + "easy saveVideo": [ + [ + "input_mode", + "input_mode.fps", + "output_mode", + "filename_prefix" + ], + [ + "input_mode", + "input_mode.fps", + "output_mode", + "output_mode.save_metadata", + "filename_prefix" + ], + [ + "input_mode", + "output_mode", + "filename_prefix" + ] + ], + "easy seed": [ + [ + "seed", + "control_after_generate", + "🎲 Manual Random Seed" + ] + ], + "easy setNode": [ + [ + "Constant" + ] + ], + "easy showAnything": [ + [ + "text" + ] + ], + "easy stylesSelector": [ + [ + "styles", + "select_styles" + ] + ], + "easy wildcards": [ + [ + "text", + "Select to add LoRA", + "Select to add Wildcard", + "seed", + "control_after_generate", + "multiline_mode" + ] + ], + "ffb7cd05-f9d8-4931-bf81-5287dcd75327": [ + [ + "resolution_level", + "batch_size", + "output", + "model_name" + ] + ], + "llama_cpp_instruct_adv": [ + [ + "preset_prompt", + "custom_prompt", + "system_prompt", + "inference_mode", + "max_frames", + "max_size", + "seed", + "control_after_generate", + "force_offload", + "save_states" + ] + ], + "llama_cpp_model_loader": [ + [ + "model", + "mmproj", + "chat_handler", + "n_ctx", + "vram_limit", + "image_min_tokens", + "image_max_tokens", + "load_mtp" + ] + ], + "llama_cpp_parameters": [ + [ + "max_tokens", + "top_k", + "top_p", + "min_p", + "typical_p", + "temperature", + "repeat_penalty", + "frequency_penalty", + "present_penalty", + "mirostat_mode", + "mirostat_eta", + "mirostat_tau", + "state_uid" + ] + ], + "忽略多组孤海": [ + [ + "guhai_ig" + ] + ] +} diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 3b9c5faf..29e38e0a 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -506,6 +506,27 @@ async def migrate_db(db_path: Path) -> None: conn.execute("ALTER TABLE workflows ADD COLUMN output_map TEXT") if "output_map_source" not in cols: conn.execute("ALTER TABLE workflows ADD COLUMN output_map_source TEXT") + # HEL-681 (S2): library metadata for 150+ scale workflow browsing. Purely + # additive columns — old rows stay NULL/0 and every legacy path ignores + # them; the lightweight list view (?view=meta) is their only reader. + if "category" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN category TEXT") + if "model_family" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN model_family TEXT") + if "media_io" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN media_io TEXT") + if "tags" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN tags TEXT") + if "favorite" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN favorite INTEGER NOT NULL DEFAULT 0") + if "last_used_at" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN last_used_at TIMESTAMP") + if "source" not in cols: + # where the row came from: 'ui_convert' (HEL-681 batch import) vs + # NULL = manual/API import as before. + conn.execute("ALTER TABLE workflows ADD COLUMN source TEXT") + if "source_path" not in cols: + conn.execute("ALTER TABLE workflows ADD COLUMN source_path TEXT") # Idempotent backfill: pending rows are re-judged on every boot (parser # upgrades can settle them); confirmed rows are never touched. _backfill_workflow_usage(conn) diff --git a/calliope-backend/src/calliope/models/schemas.py b/calliope-backend/src/calliope/models/schemas.py index 9af82ca7..50e0ad9f 100644 --- a/calliope-backend/src/calliope/models/schemas.py +++ b/calliope-backend/src/calliope/models/schemas.py @@ -243,6 +243,55 @@ class WorkflowUpdate(BaseModel): # resets the workflow to pending confirmation. output_map: list[dict[str, Any]] | None = None output_map_source: Literal["auto", "user"] | None = None + # HEL-681 (S2): library metadata fields. + favorite: bool | None = None + tags: list[str] | None = None + category: str | None = None + model_family: str | None = None + + +class WorkflowUIFileItem(BaseModel): + """One UI-format file for the HEL-681 convert/import pipeline.""" + + name: str | None = None + # repo-relative path (category/model-family evidence); display name + # defaults to the file stem. + source_path: str | None = None + workflow_json: dict[str, Any] + # optional human confirmations from the import wizard (S3): a settled + # usage and a corrected schema let warn files import enabled. + usage: WorkflowUsageKind | None = None + input_schema: list[dict[str, Any]] | None = None + output_map: list[dict[str, Any]] | None = None + description: str | None = None + tags: list[str] | None = None + + +class WorkflowConvertRequest(BaseModel): + """Dry-run: per-file ok/warn/fail + suggested metadata, nothing stored.""" + + files: list[WorkflowUIFileItem] + # Include the converted API JSON per file (default on for small batches; + # the 146-file report leaves it off to keep the payload sane). + include_workflows: bool = False + # L2 preflight against a real ComfyUI (opt-in; needs a connection). + endpoint_id: str | None = None + refresh: bool = False + + +class WorkflowImportBatchRequest(BaseModel): + """Commit: convert UI files and insert, skipping conflicts. Idempotent.""" + + files: list[WorkflowUIFileItem] + + +class WorkflowImportScanRequest(BaseModel): + """Scan a server-side directory of UI JSONs (repo example library).""" + + root: str = "example_ComfyUI_workflows" + # Set to preview what would import (same shape as /convert) — the safe + # default for a first run against the 146-file library. + dry_run: bool = True class WorkflowAnalyze(BaseModel): diff --git a/calliope-backend/src/calliope/queue/manager.py b/calliope-backend/src/calliope/queue/manager.py index 98f323af..643e920a 100644 --- a/calliope-backend/src/calliope/queue/manager.py +++ b/calliope-backend/src/calliope/queue/manager.py @@ -49,6 +49,12 @@ class QueueManager: """, (project_id, scene_id, clip_id, kind, workflow_id, json.dumps(payload), origin), ) + # HEL-681: every enqueued job counts as a use (最近使用). + if workflow_id is not None: + conn.execute( + "UPDATE workflows SET last_used_at = CURRENT_TIMESTAMP WHERE id = ?", + (workflow_id,), + ) conn.commit() row = conn.execute("SELECT * FROM jobs WHERE id = ?", (cur.lastrowid,)).fetchone() return row_to_dict(row) diff --git a/calliope-backend/src/calliope/routers/agent.py b/calliope-backend/src/calliope/routers/agent.py index 1246296e..daca3595 100644 --- a/calliope-backend/src/calliope/routers/agent.py +++ b/calliope-backend/src/calliope/routers/agent.py @@ -97,7 +97,7 @@ class MemoryCreate(BaseModel): class MessageCreate(BaseModel): content: str = "" - mentions: list[MessageMention] = Field(default_factory=list, max_length=1) + mentions: list[MessageMention] = Field(default_factory=list, max_length=5) attachments: list[MessageAttachment] = Field(default_factory=list, max_length=8) answer_to: int | None = None # question/asked seq this message answers (card click) @@ -113,8 +113,10 @@ class MessageCreate(BaseModel): @field_validator("mentions") @classmethod def _one_workflow(cls, v: list[MessageMention]) -> list[MessageMention]: - if len(v) > 1: + if sum(m.type == "workflow" for m in v) > 1: raise ValueError("Only one @workflow mention per message") + if sum(m.type == "skill" for m in v) > 4: + raise ValueError("At most four skill mentions per message") return v diff --git a/calliope-backend/src/calliope/routers/playground.py b/calliope-backend/src/calliope/routers/playground.py index ce41aa7b..c2ee7b37 100644 --- a/calliope-backend/src/calliope/routers/playground.py +++ b/calliope-backend/src/calliope/routers/playground.py @@ -1,4 +1,5 @@ """Standalone ComfyUI playground — generate freely, attach favorites to projects.""" + from __future__ import annotations import json @@ -31,6 +32,23 @@ PLAYGROUND_TITLE = "Playground Scratch" # page can label origins ("独立生图" vs canvas Playground) without guessing. PlaygroundSource = Literal["playground", "studio-image", "studio-video"] +# HEL-684: a desk visit opened from a five-stage workbench row may carry +# that row as optional context. Only real, server-verified project/stage/ +# source info is accepted — the source row must still exist in the stage +# content, and the desk kind must match what that stage renders. +WorkbenchStage = Literal["assets", "shot"] +WORKBENCH_KIND_BY_STAGE: dict[str, str] = {"assets": "image", "shot": "video"} +WORKBENCH_ROW_KEY_BY_STAGE: dict[str, str] = {"assets": "assets", "shot": "shots"} + + +class PlaygroundWorkbenchContext(BaseModel): + project_id: int + stage: WorkbenchStage + source_kind: Literal["asset", "shot"] + source_id: str = Field(min_length=1) + # Display-only echo of the DeskContext label (e.g. 镜头 S1). + label: str | None = None + class PlaygroundGenerate(BaseModel): workflow_id: int @@ -39,6 +57,13 @@ class PlaygroundGenerate(BaseModel): # then the active one (resolved in queue_manager.enqueue). endpoint_id: str | None = None source: PlaygroundSource = "playground" + # Optional real workbench source — validated, then stamped on the job + # payload so a finished take can be flowed back (attach-workbench). + context: PlaygroundWorkbenchContext | None = None + + +class PlaygroundAttachWorkbench(BaseModel): + job_id: int class PlaygroundAttach(BaseModel): @@ -83,6 +108,72 @@ def ensure_playground_project(conn) -> int: return int(cur.lastrowid) +# ───────────────────────────────────────────────────────────────────────── +# HEL-684: workbench source context — validate against real rows, never +# guess. Both generate-time (record on the job payload) and attach-time +# (flow a finished take back) go through the same checks. +# ───────────────────────────────────────────────────────────────────────── + + +def _workbench_target_row(conn, ctx: PlaygroundWorkbenchContext) -> dict[str, Any] | None: + """The real asset/shot row this context points at, or None.""" + stage = conn.execute( + "SELECT content_json FROM project_stages WHERE project_id = ? AND stage_key = ?", + (ctx.project_id, ctx.stage), + ).fetchone() + if not stage or not stage["content_json"]: + return None + try: + content = json.loads(stage["content_json"]) + except (json.JSONDecodeError, TypeError): + return None + rows = content.get(WORKBENCH_ROW_KEY_BY_STAGE[ctx.stage]) + if not isinstance(rows, list): + return None + for row in rows: + if isinstance(row, dict) and str(row.get("id") or "") == ctx.source_id: + return row + return None + + +def _validate_workbench_context(conn, ctx: PlaygroundWorkbenchContext, kind: str) -> dict[str, Any]: + """Reject anything that is not a real, current project/stage/source. + + Returns the payload stamp for the job. Raises on any mismatch so no + guessed or stale source is ever recorded. + """ + expected_kind = WORKBENCH_KIND_BY_STAGE[ctx.stage] + expected_source_kind = "asset" if ctx.stage == "assets" else "shot" + if ctx.source_kind != expected_source_kind or kind != expected_kind: + raise HTTPException( + status_code=422, + detail=( + f"来源上下文与生成类型不符:「{ctx.stage}」阶段需要{expected_kind}生成。" + "可关闭来源提示后独立生成。" + ), + ) + project = conn.execute( + "SELECT id, status FROM projects WHERE id = ?", (ctx.project_id,) + ).fetchone() + if not project: + raise HTTPException(status_code=404, detail="来源项目不存在,无法记录回流上下文") + if project["status"] == PLAYGROUND_STATUS: + raise HTTPException(status_code=400, detail="不能以 playground 隐藏项目作为回流来源") + if _workbench_target_row(conn, ctx) is None: + raise HTTPException( + status_code=409, + detail=( + "来源" + f"{'资产' if ctx.source_kind == 'asset' else '镜头'}行已不存在" + "(阶段内容可能已重新生成)。可关闭来源提示后独立生成。" + ), + ) + stamp: dict[str, Any] = ctx.model_dump() + if not (stamp.get("label") or "").strip(): + stamp["label"] = None + return stamp + + def _assert_path_in_assets(path: str) -> Path: assets_root = config.settings.assets_dir.resolve() target = Path(path).resolve() @@ -195,6 +286,17 @@ async def list_playground_jobs(limit: int = 50) -> list[dict[str, Any]]: conn = get_db(config.settings.db_path) try: pid = ensure_playground_project(conn) + # HEL-684: which takes have already been flowed back to a workbench + # row (per source project) — the desk shows an honest 已回流 state + # that survives reloads instead of guessing from client memory. + links_by_project: dict[int, dict[int, dict[str, Any]]] = {} + rows = conn.execute( + "SELECT DISTINCT project_id FROM jobs" + " WHERE payload_json LIKE '%\"from_playground_job\"%'" + ).fetchall() + for r in rows: + proj_id = int(r["project_id"]) + links_by_project[proj_id] = _workbench_link_rows(conn, proj_id) finally: conn.close() # Workflow-test jobs (HEL-643) ride the same scratch project but must not @@ -204,7 +306,16 @@ async def list_playground_jobs(limit: int = 50) -> list[dict[str, Any]]: for j in queue_manager.list_jobs(pid, None, limit) if str(j.get("origin") or "user") != "workflow_test" ] - return [_job_public(j) for j in jobs] + out = [] + for j in jobs: + pub = _job_public(j) + stamp = (pub.get("payload") or {}).get("workbench") + if isinstance(stamp, dict) and isinstance(stamp.get("project_id"), int): + link = links_by_project.get(int(stamp["project_id"]), {}).get(int(pub["id"])) + if link and link.get("target_id") == stamp.get("source_id"): + pub["workbench_attach"] = link + out.append(pub) + return out @router.delete("/jobs/{job_id}") @@ -239,6 +350,21 @@ async def delete_playground_job(job_id: int) -> dict[str, Any]: conn = get_db(config.settings.db_path) try: _clear_entity_refs(conn, [p for p in paths if isinstance(p, str)]) + # HEL-684: the output files are about to vanish — drop the workbench + # link rows created from this take so no project row points at + # missing media (mirrors the entity-ref clearing above). + removed_links: list[int] = [] + link_rows = conn.execute( + "SELECT id, payload_json FROM jobs WHERE payload_json LIKE '%\"from_playground_job\"%'" + ).fetchall() + for r in link_rows: + try: + p = json.loads(r["payload_json"] or "{}") + except (json.JSONDecodeError, TypeError): + continue + if p.get("from_playground_job") == job_id: + conn.execute("DELETE FROM jobs WHERE id = ?", (int(r["id"]),)) + removed_links.append(int(r["id"])) conn.commit() finally: conn.close() @@ -261,6 +387,7 @@ async def delete_playground_job(job_id: int) -> dict[str, Any]: "job_id": job_id, "deleted_files": deleted_files, "missing_files": missing_files, + "removed_workbench_links": removed_links, } @@ -365,6 +492,14 @@ async def generate(payload: PlaygroundGenerate) -> dict[str, Any]: schema = effective_input_schema( json.loads(wf["input_schema"]) if wf["input_schema"] else [], workflow_json ) + # HEL-684: an optional workbench source is only recorded when it is + # real and current — the job itself still runs on the playground + # scratch project so the desk feed, SSE and tasks stay unchanged. + workbench_stamp = ( + _validate_workbench_context(conn, payload.context, kind) + if payload.context is not None + else None + ) finally: conn.close() @@ -385,6 +520,7 @@ async def generate(payload: PlaygroundGenerate) -> dict[str, Any]: "input_values": input_values, "source": payload.source, **({"endpoint_id": payload.endpoint_id} if payload.endpoint_id else {}), + **({"workbench": workbench_stamp} if workbench_stamp else {}), }, ) await event_bus.publish( @@ -495,3 +631,167 @@ async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]: return out finally: conn.close() + + +def _workbench_link_rows(conn, project_id: int) -> dict[int, dict[str, Any]]: + """playground job id → its flow-back link row on this project. + + Link rows are done jobs with payload.source='workbench' and a + from_playground_job stamp — the exact shape _workbench_job_outputs + already enriches the workbench rows from, so a flowed-back take shows + up on its source row through the existing display path. + """ + out: dict[int, dict[str, Any]] = {} + rows = conn.execute( + "SELECT id, payload_json FROM jobs WHERE project_id = ? ORDER BY id ASC", + (project_id,), + ).fetchall() + for r in rows: + try: + p = json.loads(r["payload_json"] or "{}") + except (json.JSONDecodeError, TypeError): + continue + if p.get("source") != "workbench": + continue + src = p.get("from_playground_job") + if isinstance(src, int): + out[src] = { + "job_id": int(r["id"]), + "stage": p.get("stage_key"), + "target_id": p.get("target_id"), + } + return out + + +@router.post("/attach-workbench") +async def attach_workbench(payload: PlaygroundAttachWorkbench) -> dict[str, Any]: + """Flow a finished desk take back to its workbench source row (HEL-684). + + The source is whatever real context the generate request carried — + nothing is guessed here. Re-attaching is idempotent: the existing link + row is returned, no duplicate is created, nothing is overwritten. + """ + conn = get_db(config.settings.db_path) + try: + pid = ensure_playground_project(conn) + job = queue_manager.get_job(payload.job_id) + if not job: + raise HTTPException(status_code=404, detail="Job not found") + if int(job["project_id"]) != int(pid): + raise HTTPException(status_code=403, detail="Not a playground job") + + try: + job_payload = json.loads(job.get("payload_json") or "{}") + except (json.JSONDecodeError, TypeError): + job_payload = {} + stamp = job_payload.get("workbench") + if not isinstance(stamp, dict) or not stamp.get("source_id"): + raise HTTPException( + status_code=400, detail="该记录没有项目来源上下文,无法回流(独立生成不回流)" + ) + if job["status"] != "done": + raise HTTPException(status_code=400, detail="生成完成后才能回流") + outputs = json.loads(job.get("output_paths_json") or "[]") + if not isinstance(outputs, list) or not outputs: + raise HTTPException(status_code=400, detail="该记录没有产物文件,无法回流") + + try: + ctx = PlaygroundWorkbenchContext( + project_id=int(stamp["project_id"]), + stage=stamp.get("stage"), + source_kind=stamp.get("source_kind"), + source_id=str(stamp["source_id"]), + label=stamp.get("label"), + ) + except Exception as exc: # pydantic ValidationError / missing keys + raise HTTPException( + status_code=400, detail="该记录的项目来源上下文无效,无法回流" + ) from exc + # Re-validate against the live stage content — the row may have been + # regenerated since the take was created; refuse rather than mis-write. + if _workbench_target_row(conn, ctx) is None: + raise HTTPException( + status_code=409, + detail=( + "来源" + f"{'资产' if ctx.source_kind == 'asset' else '镜头'}行已不存在" + "(阶段内容可能已重新生成),未回流。" + ), + ) + + links = _workbench_link_rows(conn, ctx.project_id) + existing = links.get(int(job["id"])) + if existing and existing.get("target_id") == ctx.source_id: + return { + "ok": True, + "already_attached": True, + "job_id": int(job["id"]), + "attached_job_id": existing["job_id"], + "project_id": ctx.project_id, + "stage": ctx.stage, + "target_id": ctx.source_id, + } + + link_payload = { + "source": "workbench", + "stage_key": ctx.stage, + "target_id": ctx.source_id, + "from_playground_job": int(job["id"]), + "input_values": job_payload.get("input_values") or {}, + } + if ctx.label: + link_payload["label"] = ctx.label + cur = conn.execute( + """ + INSERT INTO jobs (project_id, kind, workflow_id, status, payload_json, + output_paths_json, created_at, started_at, completed_at, origin) + VALUES (?, ?, ?, 'done', ?, ?, + CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 'user') + """, + ( + ctx.project_id, + job["kind"], + job["workflow_id"], + json.dumps(link_payload, ensure_ascii=False), + json.dumps([str(p) for p in outputs if isinstance(p, str)]), + ), + ) + conn.execute( + "UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?", + (ctx.project_id,), + ) + conn.commit() + link_id = int(cur.lastrowid) + finally: + conn.close() + + await event_bus.publish( + "job.completed", + { + "job_id": link_id, + "kind": job["kind"], + "outputs": outputs, + "project_id": ctx.project_id, + "source": "workbench", + "message": "生成台结果已回流到项目", + }, + ) + await event_bus.publish( + "asset.ready", + { + "job_id": link_id, + "path": outputs[0] if isinstance(outputs[0], str) else str(outputs[0]), + "project_id": ctx.project_id, + "target": "workbench", + "source": "playground_attach", + }, + ) + return { + "ok": True, + "already_attached": False, + "job_id": int(job["id"]), + "attached_job_id": link_id, + "project_id": ctx.project_id, + "stage": ctx.stage, + "target_id": ctx.source_id, + } diff --git a/calliope-backend/src/calliope/routers/workbench.py b/calliope-backend/src/calliope/routers/workbench.py index 1b3bff71..5c0b19b2 100644 --- a/calliope-backend/src/calliope/routers/workbench.py +++ b/calliope-backend/src/calliope/routers/workbench.py @@ -45,6 +45,10 @@ class StagePatch(BaseModel): chosen_style_id: str | None = None +class StageNotePatch(BaseModel): + text: str = Field(max_length=200_000) + + class StageRunRequest(BaseModel): instruction: str | None = Field(default=None, max_length=8000) @@ -292,10 +296,12 @@ def _load_stage(conn, project_id: int, stage_key: str) -> dict[str, Any]: def _stage_public(row: dict[str, Any]) -> dict[str, Any]: + content = json.loads(row["content_json"]) if row["content_json"] else None return { "stage_key": row["stage_key"], "status": row["status"], - "content": json.loads(row["content_json"]) if row["content_json"] else None, + "content": content, + "assistant_note": (content or {}).get("assistant_note", ""), "confirmed_content": ( json.loads(row["confirmed_content_json"]) if row["confirmed_content_json"] else None ), @@ -571,6 +577,10 @@ async def _execute_run(project_id: int, stage_key: str, run_id: int, instruction conn = get_db(db) try: + latest_stage = _load_stage(conn, project_id, stage_key) + previous = json.loads(latest_stage["content_json"]) if latest_stage["content_json"] else {} + if previous.get("assistant_note"): + content["assistant_note"] = previous["assistant_note"] conn.execute( "UPDATE stage_runs SET status='done', output_json=?, completed_at=CURRENT_TIMESTAMP " "WHERE id = ?", @@ -681,6 +691,9 @@ async def patch_stage(project_id: int, stage_key: str, payload: StagePatch) -> d content = NORMALIZERS[stage_key](payload.content) except StageContentError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc + old_content = json.loads(stage["content_json"]) if stage["content_json"] else {} + if old_content.get("assistant_note"): + content["assistant_note"] = old_content["assistant_note"] if content == (json.loads(stage["content_json"]) if stage["content_json"] else None): return {"ok": True, "stage": _stage_public({**stage, "content_json": json.dumps(content, ensure_ascii=False)})} # Editing a confirmed stage produces a new draft awaiting re-confirm; @@ -715,6 +728,32 @@ async def patch_stage(project_id: int, stage_key: str, payload: StagePatch) -> d conn.close() +@router.patch("/projects/{project_id}/stages/{stage_key}/note") +async def patch_stage_note(project_id: int, stage_key: str, payload: StageNotePatch) -> dict[str, Any]: + """Keep free-text advice separate from validated stage artifacts and snapshots.""" + conn = get_db(config.settings.db_path) + try: + _get_project(conn, project_id) + stage = _stage_or_404(conn, project_id, stage_key) + if stage["status"] == "running": + raise HTTPException(status_code=409, detail="本阶段正在生成中,请稍候再保存建议。") + content = json.loads(stage["content_json"]) if stage["content_json"] else {} + if payload.text.strip(): + content["assistant_note"] = payload.text.strip() + else: + content.pop("assistant_note", None) + conn.execute( + "UPDATE project_stages SET content_json=?, updated_at=CURRENT_TIMESTAMP " + "WHERE project_id=? AND stage_key=?", + (json.dumps(content, ensure_ascii=False) if content else None, project_id, stage_key), + ) + conn.execute("UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id=?", (project_id,)) + conn.commit() + return {"ok": True, "stage": _stage_public(_load_stage(conn, project_id, stage_key))} + finally: + conn.close() + + @router.post("/projects/{project_id}/stages/{stage_key}/run") async def run_stage(project_id: int, stage_key: str, payload: StageRunRequest | None = None) -> dict[str, Any]: instruction = (payload.instruction if payload else None) or None @@ -777,7 +816,10 @@ async def confirm_stage( raise HTTPException(status_code=409, detail="本阶段正在生成中,请等待完成。") if not stage["content_json"]: raise HTTPException(status_code=400, detail="本阶段还没有内容,请先生成或手动填写。") - content = json.loads(stage["content_json"]) + try: + content = NORMALIZERS[stage_key](json.loads(stage["content_json"])) + except StageContentError as exc: + raise HTTPException(status_code=400, detail=str(exc)) from exc chosen = payload.chosen_style_id if payload else None if stage_key == "style": directions = content.get("directions") or [] @@ -815,11 +857,15 @@ async def restore_stage(project_id: int, stage_key: str) -> dict[str, Any]: stage = _stage_or_404(conn, project_id, stage_key) if not stage["confirmed_content_json"]: raise HTTPException(status_code=400, detail="本阶段还没有已确认版本,无需恢复。") + content = json.loads(stage["confirmed_content_json"]) + current = json.loads(stage["content_json"]) if stage["content_json"] else {} + if current.get("assistant_note"): + content["assistant_note"] = current["assistant_note"] conn.execute( - "UPDATE project_stages SET content_json=confirmed_content_json, " + "UPDATE project_stages SET content_json=?, " "status='confirmed', draft_edited=0, updated_at=CURRENT_TIMESTAMP " "WHERE project_id = ? AND stage_key = ?", - (project_id, stage_key), + (json.dumps(content, ensure_ascii=False), project_id, stage_key), ) conn.commit() row = _load_stage(conn, project_id, stage_key) diff --git a/calliope-backend/src/calliope/routers/workflows.py b/calliope-backend/src/calliope/routers/workflows.py index dc2ded31..d038991f 100644 --- a/calliope-backend/src/calliope/routers/workflows.py +++ b/calliope-backend/src/calliope/routers/workflows.py @@ -7,6 +7,7 @@ from fastapi import APIRouter, HTTPException from calliope.comfyui.endpoints import client_for, endpoint_snapshot from calliope.comfyui.lint import blocking_problem, workflow_warnings +from calliope.comfyui.metadata import suggested_metadata from calliope.comfyui.output_map import ( auto_output_map, load_output_map, @@ -23,6 +24,7 @@ from calliope.comfyui.parser import ( from calliope.comfyui.preflight import check_workflow_against from calliope.comfyui.profiles import detect_prompt_profile from calliope.comfyui.roles import usage_to_kind +from calliope.comfyui.ui_convert import convert_ui_workflow from calliope.comfyui.validate import validate_input_values from calliope.config import settings from calliope.db import get_db, row_to_dict @@ -30,8 +32,12 @@ from calliope.events.bus import event_bus from calliope.models.schemas import ( WorkflowAnalyze, WorkflowCheckRequest, + WorkflowConvertRequest, WorkflowCreate, + WorkflowImportBatchRequest, + WorkflowImportScanRequest, WorkflowTestRequest, + WorkflowUIFileItem, WorkflowUpdate, ) from calliope.queue.manager import queue_manager @@ -44,6 +50,14 @@ from calliope.queue.workflow_test import ( router = APIRouter() +# HEL-681: metadata columns the lightweight list view exposes (everything +# except the heavy workflow_json / input_schema / output_map payloads). +_META_COLUMNS = ( + "id, name, kind, usage, is_enabled, category, model_family, media_io, tags," + " favorite, last_used_at, description, source, source_path, prompt_profile," + " created_at, endpoint_id, usage_source, output_map_source" +) + def _serialize_workflow(row: Any) -> dict[str, Any]: data = row_to_dict(row) @@ -61,9 +75,21 @@ def _serialize_workflow(row: Any) -> dict[str, Any]: data["needs_mapping"] = ( mapping_problem(data["workflow_json"], raw_map, data.get("output_map_source")) is not None ) + # HEL-681: structured library metadata (raw JSON columns → values). + data["media_io"] = _load_json_col(data.get("media_io"), {"in": [], "out": []}) + data["tags"] = _load_json_col(data.get("tags"), []) + data["favorite"] = bool(data.get("favorite")) return data +def _load_json_col(raw: Any, default: Any) -> Any: + try: + value = json.loads(raw) if raw else None + except (json.JSONDecodeError, TypeError): + value = None + return value if value is not None else default + + async def _connection_check( endpoint_id: str | None, workflow_json: dict[str, Any], refresh: bool = False ) -> dict[str, Any]: @@ -216,9 +242,31 @@ def _last_test_summary(job: dict[str, Any]) -> dict[str, Any]: @router.get("") -async def list_workflows() -> list[dict[str, Any]]: +async def list_workflows(view: str | None = None) -> list[dict[str, Any]]: conn = get_db(settings.db_path) try: + if view == "meta": + # HEL-681: metadata-only list for 150+ scale browsing — no + # workflow_json, no per-row re-parse. `needs_mapping` here is the + # cheap pending check (usage/output_map not yet settled); rows + # that never generated keep showing as pending exactly like the + # full view reports them. + rows = conn.execute( + f"SELECT {_META_COLUMNS} FROM workflows ORDER BY favorite DESC," + " last_used_at DESC, id DESC" + ).fetchall() + out = [] + for row in rows: + data = row_to_dict(row) + data["is_enabled"] = bool(data.get("is_enabled")) + data["favorite"] = bool(data.get("favorite")) + data["media_io"] = _load_json_col(data.get("media_io"), {"in": [], "out": []}) + data["tags"] = _load_json_col(data.get("tags"), []) + data["needs_mapping"] = data.get("usage") is None or data.get( + "output_map_source" + ) is None + out.append(data) + return out rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall() out = [_serialize_workflow(r) for r in rows] # 上次测试 state is read live from the newest test job per workflow — @@ -395,6 +443,12 @@ async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str data = payload.model_dump(exclude_unset=True) if "is_enabled" in data and data["is_enabled"] is not None: data["is_enabled"] = 1 if data["is_enabled"] else 0 + # HEL-681: library metadata patch fields (favorite/tags/category/ + # model_family) — booleans to ints, lists to JSON text. + if "favorite" in data and data["favorite"] is not None: + data["favorite"] = 1 if data["favorite"] else 0 + if data.get("tags") is not None: + data["tags"] = json.dumps(data["tags"]) workflow_json = json.loads(existing["workflow_json"]) # HEL-638: output_map payload. A non-empty list validates against the # stored JSON and becomes the user decision; an explicit empty list @@ -600,3 +654,280 @@ async def delete_workflow(workflow_id: int) -> dict[str, bool]: return {"ok": True} finally: conn.close() + + +# --------------------------------------------------------------------------- +# HEL-681 (S2): UI→API conversion dry-run + batch import + repo scan. +# The convert endpoint never writes; import-batch converts again server-side +# and skips anything uncertain (needs_confirmation / lint-blocked / conflict) +# — repeated runs import nothing new, so the batch is idempotent by design. +# --------------------------------------------------------------------------- + + +def _convert_one(item: WorkflowUIFileItem) -> tuple[dict[str, Any], dict[str, Any] | None]: + """(report, converted workflow) for one UI file — shared by every + convert/import path so the analysis can never drift between them.""" + result = convert_ui_workflow(item.workflow_json) + stem = ( + item.source_path.replace("\\", "/").rsplit("/", 1)[-1].removesuffix(".json") + if item.source_path + else None + ) + name = item.name or stem or "未命名工作流" + report: dict[str, Any] = { + "name": name, + "source_path": item.source_path, + "status": result.status, + "needs_confirmation": result.needs_confirmation, + "issues": [ + {"node_id": i.node_id, "code": i.code, "level": i.level, "message": i.message} + for i in result.issues + ], + } + if result.workflow is None: + report["importable"] = False + report["skip_reason"] = "转换失败:" + ( + result.issues[0].message if result.issues else "未知错误" + ) + return report, None + suggested = suggested_metadata(result.workflow, item.source_path, item.workflow_json) + report["suggested"] = suggested + # The import gate re-runs the product's own checks — a converted graph + # that the lint would block (missing model link etc.) is reported, not + # silently imported. + broken = blocking_problem(result.workflow) + if broken: + report["importable"] = False + report["skip_reason"] = broken + report["status"] = "warn" + return report, result.workflow + if result.needs_confirmation: + report["importable"] = False + report["skip_reason"] = "存在无法可靠映射的控件,需人工确认后重导" + return report, result.workflow + report["importable"] = True + return report, result.workflow + + +@router.post("/convert") +async def convert_workflows(payload: WorkflowConvertRequest) -> dict[str, Any]: + """Dry-run UI→API conversion for a batch of files: per-file ok/warn/fail, + issues, suggested metadata and importability. Nothing is stored.""" + files = [] + object_info: dict[str, Any] | None = None + client = None + if payload.endpoint_id: + endpoint = settings.resolve_comfyui_endpoint(payload.endpoint_id) + if endpoint is not None: + client = client_for(endpoint) + try: + object_info = await client.object_info(force_refresh=payload.refresh) + except Exception: + object_info = None + try: + for item in payload.files: + report, converted = _convert_one(item) + if object_info is not None and report.get("importable") and converted: + findings = check_workflow_against(object_info, converted) + errors = [f for f in findings if f.get("level") == "error"] + report["preflight"] = { + "endpoint_id": payload.endpoint_id, + "ok": not errors, + "findings": findings, + } + if errors: + report["importable"] = False + report["skip_reason"] = errors[0].get("message") or "preflight 未通过" + if payload.include_workflows: + report["workflow_json"] = converted + files.append(report) + finally: + if client is not None: + await client.close() + counts = {key: sum(1 for f in files if f["status"] == key) for key in ("ok", "warn", "fail")} + return { + "total": len(files), + **counts, + "needs_confirmation": sum(1 for f in files if f["needs_confirmation"]), + "importable": sum(1 for f in files if f.get("importable")), + "files": files, + } + + +def _insert_converted( + conn: Any, item: WorkflowUIFileItem, report: dict[str, Any], converted: dict[str, Any] +) -> dict[str, Any]: + """Insert one converted workflow row (import-batch's write path). + + Mirrors create_workflow's enable gate: usage must be settled (auto or the + wizard's confirmation) and unknown outputs need a mapping; anything less + lands disabled exactly like a manual import would. + """ + suggested = report["suggested"] + judgment = classify_usage(converted) + usage = item.usage or judgment["usage"] + usage_source = "user" if item.usage else "auto" + kind = usage_to_kind(usage) or suggested["kind"] + profile = detect_prompt_profile(converted) + if item.output_map: + problems = validate_output_map(converted, item.output_map) + if problems: + raise HTTPException(status_code=422, detail=";".join(problems)) + output_map = json.dumps(item.output_map) + output_map_source = "user" + else: + auto_map = auto_output_map(converted) + output_map = json.dumps(auto_map) if auto_map else None + output_map_source = "auto" if auto_map else None + mapping_ok = not needs_user_output_map(converted) or bool(item.output_map) + workflow_text = json.dumps(converted) + existing = conn.execute( + "SELECT id FROM workflows WHERE name = ? AND kind = ? AND workflow_json = ?", + (report["name"], kind, workflow_text), + ).fetchone() + if existing: + return { + "result": "skipped", + "skip_reason": "conflict", + "existing_id": existing["id"], + } + is_enabled = 1 if (usage and mapping_ok) else 0 + cur = conn.execute( + """ + INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema, + description, prompt_profile, endpoint_id, is_enabled, + usage, usage_source, output_map, output_map_source, + category, model_family, media_io, tags, favorite, + source, source_path) + VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'ui_convert', ?) + """, + ( + report["name"], + kind, + workflow_text, + json.dumps( + item.input_schema if item.input_schema else parse_dynamic_inputs(converted) + ), + json.dumps(parse_dynamic_outputs(converted)), + item.description if item.description is not None else suggested["description"], + profile, + is_enabled, + usage, + usage_source, + output_map, + output_map_source, + suggested["category"], + suggested["model_family"], + json.dumps({"in": suggested["media_in"], "out": suggested["media_out"]}), + json.dumps(item.tags or []), + item.source_path, + ), + ) + return {"result": "imported", "id": cur.lastrowid} + + +async def _run_import(items: list[WorkflowUIFileItem]) -> dict[str, Any]: + reports: list[dict[str, Any]] = [] + conn = get_db(settings.db_path) + try: + for item in items: + report, converted = _convert_one(item) + if not report.get("importable"): + report["result"] = "skipped" + reports.append(report) + continue + try: + outcome = _insert_converted(conn, item, report, converted) + except HTTPException as exc: + report["result"] = "failed" + report["skip_reason"] = str(exc.detail) + reports.append(report) + continue + conn.commit() + report.update(outcome) + reports.append(report) + finally: + conn.close() + imported = [r for r in reports if r.get("result") == "imported"] + skipped = [ + {"name": r["name"], "source_path": r["source_path"], "reason": r.get("skip_reason")} + for r in reports + if r.get("result") != "imported" + ] + return { + "total": len(reports), + "imported": len(imported), + "skipped": len(skipped), + "imported_ids": [r["id"] for r in imported], + "skipped_files": skipped, + "files": reports, + } + + +@router.post("/import-batch") +async def import_workflows_batch(payload: WorkflowImportBatchRequest) -> dict[str, Any]: + """Batch-import UI-format workflows: convert server-side, insert what is + cleanly convertible, skip conflicts and anything uncertain. Re-running + with the same files creates zero new rows.""" + return await _run_import(payload.files) + + +@router.post("/import-scan") +async def import_workflows_scan(payload: WorkflowImportScanRequest) -> dict[str, Any]: + """Scan a server-side directory for UI-format workflow JSONs and run the + convert (dry_run, default) or import pipeline over every file found.""" + from pathlib import Path + + root = Path(payload.root) + if not root.is_absolute(): + candidates = [ + Path.cwd() / root, + Path(__file__).resolve().parents[4] / root, + ] + root = next((c for c in candidates if c.is_dir()), root) + if not root.is_dir(): + raise HTTPException(status_code=404, detail=f"目录不存在:{payload.root}") + items: list[WorkflowUIFileItem] = [] + for path in sorted(root.rglob("*.json")): + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (json.JSONDecodeError, OSError): + continue + if not (isinstance(data, dict) and isinstance(data.get("nodes"), list)): + continue # API-format or non-workflow files: not this pipeline's job + items.append( + WorkflowUIFileItem( + source_path=str(path.relative_to(root)), workflow_json=data + ) + ) + if payload.dry_run: + files = [_convert_one(item)[0] for item in items] + counts = { + key: sum(1 for f in files if f["status"] == key) for key in ("ok", "warn", "fail") + } + return { + "total": len(files), + **counts, + "needs_confirmation": sum(1 for f in files if f["needs_confirmation"]), + "importable": sum(1 for f in files if f.get("importable")), + "files": files, + } + return await _run_import(items) + + +@router.post("/{workflow_id}/touch") +async def touch_workflow(workflow_id: int) -> dict[str, bool]: + """Record a use (最近使用) — called by the generate pipeline on enqueue.""" + conn = get_db(settings.db_path) + try: + row = conn.execute("SELECT id FROM workflows WHERE id = ?", (workflow_id,)).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Workflow not found") + conn.execute( + "UPDATE workflows SET last_used_at = CURRENT_TIMESTAMP WHERE id = ?", + (workflow_id,), + ) + conn.commit() + return {"ok": True} + finally: + conn.close() diff --git a/calliope-backend/tests/test_agent_mention_limits.py b/calliope-backend/tests/test_agent_mention_limits.py new file mode 100644 index 00000000..ecf6e462 --- /dev/null +++ b/calliope-backend/tests/test_agent_mention_limits.py @@ -0,0 +1,36 @@ +"""Workflow uniqueness is independent of the selected task skills.""" +import pytest +from pydantic import ValidationError +from calliope.routers.agent import MessageCreate + + +def workflow(n=1): + return {"type": "workflow", "id": n, "name": f"workflow-{n}", "kind": "image"} + + +def skill(n=1): + return {"type": "skill", "name": f"skill-{n}"} + + +def test_workflow_and_skills_can_be_sent_together(): + message = MessageCreate(content="Create an image", mentions=[workflow(), *[skill(i) for i in range(4)]]) + assert len(message.mentions) == 5 + assert message.mentions[0].id == 1 + + +def test_legacy_single_workflow_is_accepted(): + assert MessageCreate(mentions=[workflow()]).mentions[0].type == "workflow" + + +def test_skills_without_workflow_are_accepted(): + assert len(MessageCreate(mentions=[skill(i) for i in range(4)]).mentions) == 4 + + +def test_second_workflow_is_still_rejected(): + with pytest.raises(ValidationError, match="Only one @workflow"): + MessageCreate(mentions=[workflow(), skill(), workflow(2)]) + + +def test_fifth_skill_is_rejected(): + with pytest.raises(ValidationError, match="At most four skill"): + MessageCreate(mentions=[skill(i) for i in range(5)]) diff --git a/calliope-backend/tests/test_playground_workbench_flowback.py b/calliope-backend/tests/test_playground_workbench_flowback.py new file mode 100644 index 00000000..11681dbb --- /dev/null +++ b/calliope-backend/tests/test_playground_workbench_flowback.py @@ -0,0 +1,350 @@ +"""HEL-684 — playground takes flow back to their workbench source row. + +Covers the acceptance list: real-context-only passthrough (no guessing, +stale rows rejected), explicit flow-back with idempotency (repeated +operations create no duplicates), cancelled/independent paths never +writing the project, and playground job deletion clearing the link. +""" + +from __future__ import annotations + +import tempfile +import time +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from calliope.db import migrate_db +from calliope.main import create_app + +SAMPLE_WORKFLOW = { + "1": { + "class_type": "CLIPTextEncode", + "inputs": {"text": "hello"}, + "_meta": {"title": "Prompt (Input:prompt)"}, + }, + "2": { + "class_type": "SaveImage", + "inputs": {"images": ["1", 0]}, + "_meta": {"title": "Save (Output:image)"}, + }, +} + +SAMPLE_VIDEO_WORKFLOW = { + "1": { + "class_type": "CLIPTextEncode", + "inputs": {"text": "hello"}, + "_meta": {"title": "Prompt (Input:prompt)"}, + }, + "2": { + "class_type": "SaveVideo", + "inputs": {"video": ["1", 0]}, + "_meta": {"title": "Save (Output:video)"}, + }, +} + + +@pytest.fixture +def client(monkeypatch): + with tempfile.TemporaryDirectory() as tmpdir: + import asyncio + + import calliope.config as config_module + + s = config_module.settings + prev = { + "data_dir": s.data_dir, + "assets_dir": s.assets_dir, + "dry_run": s.dry_run, + } + s.data_dir = Path(tmpdir) + s.assets_dir = Path(tmpdir) / "assets" + s.assets_dir.mkdir(parents=True, exist_ok=True) + s.dry_run = True + monkeypatch.setattr(config_module.Settings, "save_config_file", lambda self: None) + asyncio.run(migrate_db(s.db_path)) + app = create_app() + try: + with TestClient(app) as c: + yield c + finally: + for k, v in prev.items(): + setattr(s, k, v) + + +def _wait_done(client: TestClient, job_id: int) -> dict: + for _ in range(60): + jobs = client.get("/api/playground/jobs").json() + done = next((j for j in jobs if j["id"] == job_id and j["status"] == "done"), None) + if done and done.get("output_paths"): + return done + time.sleep(0.25) + raise AssertionError("playground job did not finish in dry-run") + + +def _seed_assets_stage(client: TestClient) -> dict: + proj = client.post("/api/projects", json={"title": "Reel"}).json() + # Real stage rows the way the workbench itself creates them. + patch = client.patch( + f"/api/workbench/projects/{proj['id']}/stages/assets", + json={ + "content": { + "assets": [ + { + "id": "asset-1", + "kind": "character", + "name": "林夏", + "description": "", + "prompt": "a stoic courier", + "negative_prompt": "", + } + ] + } + }, + ) + assert patch.status_code == 200, patch.text + return proj + + +def _context(proj: dict, **over: object) -> dict: + base = { + "project_id": proj["id"], + "stage": "assets", + "source_kind": "asset", + "source_id": "asset-1", + "label": "角色「林夏」", + } + base.update(over) + return base + + +def _make_workflow(client: TestClient, name: str, workflow: dict) -> int: + r = client.post( + "/api/workflows", + json={ + "name": name, + "kind": "video" if "SaveVideo" in str(workflow) else "image", + "workflow_json": workflow, + }, + ) + assert r.status_code == 200, r.text + return r.json()["id"] + + +# ── context passthrough ──────────────────────────────────────────────── + + +def test_generate_with_context_stamps_job_and_stays_on_playground(client): + wf_id = _make_workflow(client, "FB Img", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + + r = client.post( + "/api/playground/generate", + json={ + "workflow_id": wf_id, + "input_values": {"1": "a cat"}, + "source": "studio-image", + "context": _context(proj), + }, + ) + assert r.status_code == 200, r.text + job = r.json()["job"] + assert job["payload"]["workbench"]["project_id"] == proj["id"] + assert job["payload"]["workbench"]["source_id"] == "asset-1" + assert job["payload"]["workbench"]["label"] == "角色「林夏」" + + # The job itself rides the hidden playground project — independent + # desk behavior (feed, SSE, tasks) is untouched. + scratch = client.get("/api/playground/project").json() + assert job["project_id"] == scratch["id"] + + +def test_generate_without_context_writes_nothing_to_any_project(client): + wf_id = _make_workflow(client, "FB Solo", SAMPLE_WORKFLOW) + _seed_assets_stage(client) + r = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "solo"}}, + ) + assert r.status_code == 200 + assert "workbench" not in r.json()["job"]["payload"] + + +def test_generate_rejects_fake_or_stale_context(client): + wf_id = _make_workflow(client, "FB Fake", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + + # Unknown project + r = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "context": _context(proj, project_id=99999)}, + ) + assert r.status_code == 404 + + # Source row that does not exist in the stage content + r = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "context": _context(proj, source_id="asset-404")}, + ) + assert r.status_code == 409 + + # Kind mismatch: assets stage wants an image workflow + video_wf = _make_workflow(client, "FB Vid", SAMPLE_VIDEO_WORKFLOW) + r = client.post( + "/api/playground/generate", + json={"workflow_id": video_wf, "context": _context(proj)}, + ) + assert r.status_code == 422 + + # The playground scratch project is not a valid source + scratch = client.get("/api/playground/project").json() + r = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "context": _context(proj, project_id=scratch["id"])}, + ) + assert r.status_code == 400 + + +# ── flow back ────────────────────────────────────────────────────────── + + +def test_attach_workbench_links_take_to_source_row(client): + wf_id = _make_workflow(client, "FB Link", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + job = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "a cat"}, "context": _context(proj)}, + ).json()["job"] + + # Not done yet → refused, nothing written. + early = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}) + assert early.status_code == 400 + + done = _wait_done(client, job["id"]) + + r = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}) + assert r.status_code == 200, r.text + body = r.json() + assert body["already_attached"] is False + assert body["project_id"] == proj["id"] + assert body["target_id"] == "asset-1" + + # The workbench overview now shows the artifact on the source row, + # through the exact enrichment path in-flow generation uses. + overview = client.get(f"/api/workbench/projects/{proj['id']}").json() + assets_stage = next(s for s in overview["stages"] if s["stage_key"] == "assets") + row = next(a for a in assets_stage["content"]["assets"] if a["id"] == "asset-1") + assert row["job"]["id"] == body["attached_job_id"] + assert row["job"]["status"] == "done" + assert row["job"]["output"] == done["output_paths"][0] + + # Repeated flow-back: idempotent, no duplicate row. + again = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}) + assert again.status_code == 200 + assert again.json()["already_attached"] is True + assert again.json()["attached_job_id"] == body["attached_job_id"] + + # The desk jobs list reports the honest 已回流 marker. + jobs = client.get("/api/playground/jobs").json() + listed = next(j for j in jobs if j["id"] == job["id"]) + assert listed["workbench_attach"]["job_id"] == body["attached_job_id"] + + +def test_attach_workbench_requires_real_context(client): + wf_id = _make_workflow(client, "FB NoCtx", SAMPLE_WORKFLOW) + job = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "solo"}}, + ).json()["job"] + _wait_done(client, job["id"]) + + r = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}) + assert r.status_code == 400 + assert "独立" in r.json()["detail"] + + +def test_attach_workbench_refuses_regenerated_source(client): + wf_id = _make_workflow(client, "FB Stale", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + job = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "a cat"}, "context": _context(proj)}, + ).json()["job"] + _wait_done(client, job["id"]) + + # Stage content regenerated: the old row id is gone. + client.patch( + f"/api/workbench/projects/{proj['id']}/stages/assets", + json={ + "content": { + "assets": [ + { + "id": "asset-2", + "kind": "prop", + "name": "Blaster", + "description": "", + "prompt": "a blaster", + "negative_prompt": "", + } + ] + } + }, + ) + + r = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}) + assert r.status_code == 409 + overview = client.get(f"/api/workbench/projects/{proj['id']}").json() + assets_stage = next(s for s in overview["stages"] if s["stage_key"] == "assets") + assert all("job" not in a for a in assets_stage["content"]["assets"]) + + +def test_attach_workbench_allows_new_flow_job_to_take_over(client): + """A later in-flow generation for the same row wins the display, as + the enrichment keeps the newest workbench job per target.""" + wf_id = _make_workflow(client, "FB Takeover", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + job = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "a cat"}, "context": _context(proj)}, + ).json()["job"] + _wait_done(client, job["id"]) + link = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}).json() + + flow = client.post( + f"/api/workbench/projects/{proj['id']}/generate", + json={ + "kind": "image", + "stage_key": "assets", + "target_id": "asset-1", + "prompt": "in-flow take", + }, + ) + assert flow.status_code == 200, flow.text + + overview = client.get(f"/api/workbench/projects/{proj['id']}").json() + assets_stage = next(s for s in overview["stages"] if s["stage_key"] == "assets") + row = next(a for a in assets_stage["content"]["assets"] if a["id"] == "asset-1") + assert row["job"]["id"] != link["attached_job_id"] + + +def test_delete_playground_job_removes_workbench_link(client): + wf_id = _make_workflow(client, "FB Del", SAMPLE_WORKFLOW) + proj = _seed_assets_stage(client) + job = client.post( + "/api/playground/generate", + json={"workflow_id": wf_id, "input_values": {"1": "a cat"}, "context": _context(proj)}, + ).json()["job"] + done = _wait_done(client, job["id"]) + link = client.post("/api/playground/attach-workbench", json={"job_id": job["id"]}).json() + + dead = client.delete(f"/api/playground/jobs/{job['id']}") + assert dead.status_code == 200 + assert dead.json()["removed_workbench_links"] == [link["attached_job_id"]] + + # The link row is gone: the project row no longer points at deleted files. + overview = client.get(f"/api/workbench/projects/{proj['id']}").json() + assets_stage = next(s for s in overview["stages"] if s["stage_key"] == "assets") + row = next(a for a in assets_stage["content"]["assets"] if a["id"] == "asset-1") + assert "job" not in row or row["job"]["id"] != link["attached_job_id"] + assert not Path(done["output_paths"][0]).exists() diff --git a/calliope-backend/tests/test_ui_convert.py b/calliope-backend/tests/test_ui_convert.py new file mode 100644 index 00000000..de79c4a7 --- /dev/null +++ b/calliope-backend/tests/test_ui_convert.py @@ -0,0 +1,449 @@ +"""HEL-681: UI→API converter unit tests + ground-truth cross-checks. + +The synthetic graphs pin the structural semantics (reroute / bypass / mute / +subgraph expansion / Set-Get variables / control_after_generate pairing); +the corpus section runs the real 146-file library and the repo's API exports. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path + +import pytest + +from calliope.comfyui.lint import workflow_warnings +from calliope.comfyui.ui_convert import convert_ui_workflow + +EXAMPLES = Path(__file__).resolve().parents[2] / "example_ComfyUI_workflows" + + +def _node(nid, ntype, *, mode=0, inputs=None, outputs=None, wv=None, wvn=None, title=None): + node = {"id": nid, "type": ntype, "mode": mode, "inputs": inputs or [], "order": 0} + if outputs is not None: + node["outputs"] = outputs + if wv is not None: + node["widgets_values"] = wv + if wvn is not None: + node["widgets_values_named"] = wvn + if title: + node["title"] = title + return node + + +def _in_slot(name, type_, link=None, widget=None): + entry = {"name": name, "type": type_, "link": link} + if widget: + entry["widget"] = {"name": widget} + return entry + + +def _out(name, type_, links=None): + return {"name": name, "type": type_, "links": links or [], "slot_index": 0} + + +def _base_graph(): + """text2image: loader → prompts/latent → KSampler → VAE → SaveImage.""" + nodes = [ + _node( + 1, + "CheckpointLoaderSimple", + outputs=[_out("MODEL", "MODEL"), _out("CLIP", "CLIP"), _out("VAE", "VAE")], + wv=["model.safetensors"], + inputs=[_in_slot("ckpt_name", "COMBO", widget="ckpt_name")], + ), + _node( + 2, + "CLIPTextEncode", + inputs=[ + _in_slot("clip", "CLIP", link=1), + _in_slot("text", "STRING", widget="text"), + ], + outputs=[_out("CONDITIONING", "CONDITIONING")], + wv=["a cat"], + ), + _node( + 3, + "CLIPTextEncode", + inputs=[ + _in_slot("clip", "CLIP", link=2), + _in_slot("text", "STRING", widget="text"), + ], + outputs=[_out("CONDITIONING", "CONDITIONING")], + wv=["bad quality"], + ), + _node( + 4, + "EmptyLatentImage", + inputs=[ + _in_slot("width", "INT", widget="width"), + _in_slot("height", "INT", widget="height"), + _in_slot("batch_size", "INT", widget="batch_size"), + ], + outputs=[_out("LATENT", "LATENT")], + wv=[512, 512, 1], + ), + _node( + 5, + "KSampler", + inputs=[ + _in_slot("model", "MODEL", link=3), + _in_slot("positive", "CONDITIONING", link=4), + _in_slot("negative", "CONDITIONING", link=5), + _in_slot("latent_image", "LATENT", link=6), + _in_slot("seed", "INT", widget="seed"), + _in_slot("steps", "INT", widget="steps"), + _in_slot("cfg", "FLOAT", widget="cfg"), + _in_slot("sampler_name", "COMBO", widget="sampler_name"), + _in_slot("scheduler", "COMBO", widget="scheduler"), + _in_slot("denoise", "FLOAT", widget="denoise"), + ], + outputs=[_out("LATENT", "LATENT")], + # seed 42 + control "fixed" rides together, then five widgets + wv=[42, "fixed", 20, 7, "euler", "normal", 1.0], + ), + _node( + 6, + "VAEDecode", + inputs=[ + _in_slot("samples", "LATENT", link=7), + _in_slot("vae", "VAE", link=8), + ], + outputs=[_out("IMAGE", "IMAGE")], + ), + _node( + 7, + "SaveImage", + inputs=[ + _in_slot("images", "IMAGE", link=9), + _in_slot("filename_prefix", "STRING", widget="filename_prefix"), + ], + wv=["test"], + ), + ] + links = [ + [1, 1, 1, 2, 0, "CLIP"], + [2, 1, 1, 3, 0, "CLIP"], + [3, 1, 0, 5, 0, "MODEL"], + [4, 2, 0, 5, 1, "CONDITIONING"], + [5, 3, 0, 5, 2, "CONDITIONING"], + [6, 4, 0, 5, 3, "LATENT"], + [7, 5, 0, 6, 0, "LATENT"], + [8, 1, 2, 6, 1, "VAE"], + [9, 6, 0, 7, 0, "IMAGE"], + ] + return {"nodes": nodes, "links": links, "last_node_id": 7, "last_link_id": 9} + + +def _convert(graph): + return convert_ui_workflow(graph) + + +def test_clean_conversion_maps_everything(): + result = _convert(_base_graph()) + assert result.status == "ok" + assert result.needs_confirmation is False + wf = result.workflow + assert set(wf) == {"1", "2", "3", "4", "5", "6", "7"} + ks = wf["5"] + assert ks["class_type"] == "KSampler" + assert ks["inputs"]["seed"] == 42 # control_after_generate consumed silently + assert ks["inputs"]["steps"] == 20 + assert ks["inputs"]["denoise"] == 1.0 + assert ks["inputs"]["model"] == ["1", 0] + assert ks["inputs"]["latent_image"] == ["4", 0] + # lint on the converted graph must be error-free + assert not [w for w in workflow_warnings(wf) if w["level"] == "error"] + + +def test_upload_button_widgets_are_consumed_but_never_emitted(): + graph = _base_graph() + load = _node( + 8, + "LoadImage", + inputs=[ + _in_slot("image", "COMBO", widget="image"), + _in_slot("upload", "IMAGEUPLOAD", widget="upload"), + ], + outputs=[_out("IMAGE", "IMAGE")], + wv=["sample.png", "image"], + ) + save = _node( + 9, + "PreviewImage", + inputs=[ + _in_slot("images", "IMAGE", link=20), + _in_slot("filename_prefix", "STRING", widget="filename_prefix"), + ], + wv=["preview"], + ) + graph["nodes"] += [load, save] + graph["links"].append([20, 8, 0, 9, 0, "IMAGE"]) + result = _convert(graph) + assert result.workflow["8"]["inputs"] == {"image": "sample.png"} + + +def test_reroute_pass_through(): + graph = _base_graph() + reroute = _node(8, "Reroute", inputs=[_in_slot("(in)", "*", link=9)]) + graph["nodes"].append(reroute) + # SaveImage now fed by the reroute instead of VAEDecode directly + graph["nodes"][6]["inputs"][0]["link"] = 10 + graph["links"].append([10, 8, 0, 7, 0, "IMAGE"]) + result = _convert(graph) + assert result.workflow["7"]["inputs"]["images"] == ["6", 0] + assert "8" not in result.workflow + + +def test_bypass_pass_through_and_mute_drop(): + graph = _base_graph() + # bypass the KSampler: VAEDecode.samples must fall back to the latent + graph["nodes"][4]["mode"] = 4 + result = _convert(graph) + assert result.workflow["6"]["inputs"]["samples"] == ["4", 0] + # mute the negative prompt: the link input is dropped with a warning + graph = _base_graph() + graph["nodes"][2]["mode"] = 2 + result = _convert(graph) + assert "negative" not in result.workflow["5"]["inputs"] + assert any(i.code == "muted_input_dropped" for i in result.issues) + + +def test_widget_entry_with_muted_upstream_falls_back_to_value(): + graph = _base_graph() + # feed seed from a muted PrimitiveInt via a converted widget input + prim = _node( + 9, + "PrimitiveInt", + mode=2, + inputs=[_in_slot("value", "INT", widget="value"), _in_slot("control", "COMBO", widget="control")], + wv=[7], + ) + graph["nodes"].append(prim) + graph["nodes"][4]["inputs"][4]["link"] = 11 # seed ← primitive + graph["links"].append([11, 9, 0, 5, 4, "INT"]) + result = _convert(graph) + assert result.workflow["5"]["inputs"]["seed"] == 42 + + +def test_subgraph_expansion_and_boundary_wiring(): + graph = _base_graph() + # pack the EmptyLatentImage into a subgraph exposing width/height widgets + del graph["nodes"][3] + graph["nodes"] = [n for n in graph["nodes"] if n["id"] != 4] + sub_id = "aaaa-bbbb-cccc-dddd-eeee" + packed = _node( + 20, + sub_id, + inputs=[ + _in_slot("width", "INT", widget="width"), + _in_slot("height", "INT", widget="height"), + ], + outputs=[_out("LATENT", "LATENT")], + wv=[640, 384], + ) + graph["nodes"].append(packed) + # KSampler latent_image ← packed output + graph["links"] = [l for l in graph["links"] if l[0] != 6] + graph["links"].append([6, 20, 0, 5, 3, "LATENT"]) + graph["definitions"] = { + "subgraphs": [ + { + "id": sub_id, + "name": "Latent", + "inputs": [ + {"name": "width", "type": "INT"}, + {"name": "height", "type": "INT"}, + ], + "outputs": [{"name": "LATENT", "type": "LATENT"}], + "inputNode": {"id": -10}, + "outputNode": {"id": -20}, + "nodes": [ + _node( + 5, + "EmptyLatentImage", + inputs=[ + _in_slot("width", "INT", widget="width", link=101), + _in_slot("height", "INT", widget="height", link=102), + _in_slot("batch_size", "INT", widget="batch_size"), + ], + outputs=[_out("LATENT", "LATENT")], + wv=[512, 512, 1], + ), + ], + "links": [ + {"id": 101, "origin_id": -10, "origin_slot": 0, "target_id": 5, "target_slot": 0, "type": "INT"}, + {"id": 102, "origin_id": -10, "origin_slot": 1, "target_id": 5, "target_slot": 1, "type": "INT"}, + {"id": 103, "origin_id": 5, "origin_slot": 0, "target_id": -20, "target_slot": 0, "type": "LATENT"}, + ], + } + ] + } + result = _convert(graph) + wf = result.workflow + assert "20:5" in wf # qualified packed:inner id, ComfyUI's own scheme + inner = wf["20:5"] + assert inner["class_type"] == "EmptyLatentImage" + # exposed widget values from the packed instance, not the inner defaults + assert inner["inputs"]["width"] == 640 + assert inner["inputs"]["height"] == 384 + assert inner["inputs"]["batch_size"] == 1 + assert wf["5"]["inputs"]["latent_image"] == ["20:5", 0] + # now wire the packed width slot from outside: boundary becomes a link + res_node = _node( + 21, + "ResolutionSelector", + inputs=[_in_slot("aspect_ratio", "COMBO", widget="aspect_ratio")], + outputs=[_out("width", "INT"), _out("height", "INT")], + wv=["1:1"], + ) + graph["nodes"].append(res_node) + graph["nodes"][-2]["inputs"][0]["link"] = 12 # packed width ← selector + graph["links"].append([12, 21, 0, 20, 0, "INT"]) + wf2 = _convert(graph).workflow + assert wf2["20:5"]["inputs"]["width"] == ["21", 0] + assert wf2["20:5"]["inputs"]["height"] == 384 + + +def test_set_get_variables_resolve_to_captured_source(): + graph = _base_graph() + setter = _node(8, "SetNode", inputs=[_in_slot("*", "*", link=8)], wv=["the_vae"]) + getter = _node(9, "GetNode", wv=["the_vae"], outputs=[_out("VAE", "VAE")]) + graph["nodes"] += [setter, getter] + # VAEDecode.vae now fed via the variable + graph["nodes"][5]["inputs"][1]["link"] = 13 + graph["links"] = [l for l in graph["links"] if l[0] != 8] + graph["links"] += [ + [8, 1, 2, 8, 0, "VAE"], + [13, 9, 0, 6, 1, "VAE"], + ] + result = _convert(graph) + assert "8" not in result.workflow and "9" not in result.workflow + assert result.workflow["6"]["inputs"]["vae"] == ["1", 2] + + +def test_unknown_widget_order_lands_in_needs_confirmation(): + graph = _base_graph() + # an old-frontend node: positional widgets, no widget markers, no registry + graph["nodes"].append( + _node(10, "MysteryCustomNode", inputs=[], outputs=[_out("IMAGE", "IMAGE")], wv=[1, 2, 3]) + ) + save = _node( + 11, + "PreviewImage", + inputs=[_in_slot("images", "IMAGE", link=30)], + wv=["preview"], + ) + graph["nodes"].append(save) + graph["links"].append([30, 10, 0, 11, 0, "IMAGE"]) + result = _convert(graph) + assert result.needs_confirmation is True + assert any(i.code == "widget_unmapped" for i in result.issues) + # the node is still converted structurally — the report carries the doubt + assert "10" in result.workflow + + +def test_not_ui_format_fails_fast(): + result = convert_ui_workflow({"3": {"class_type": "SaveImage", "inputs": {}}}) + assert result.status == "fail" + assert result.workflow is None + + +# --------------------------------------------------------------------------- +# Real corpus: the 146 UI files + ground-truth API cross-checks (对拍). +# --------------------------------------------------------------------------- + +pytestmark_convert = pytest.mark.skipif( + not EXAMPLES.is_dir(), reason="example_ComfyUI_workflows not checked out" +) + + +@pytest.mark.skipif(not EXAMPLES.is_dir(), reason="example library missing") +def test_corpus_146_files_all_convert(): + ui_files = [ + p + for p in sorted(EXAMPLES.rglob("*.json")) + if isinstance(json.loads(p.read_text(encoding="utf-8")), dict) + and isinstance(json.loads(p.read_text(encoding="utf-8")).get("nodes"), list) + ] + assert len(ui_files) == 146 + statuses = {"ok": 0, "warn": 0, "fail": 0} + needs_confirmation = 0 + for path in ui_files: + data = json.loads(path.read_text(encoding="utf-8")) + result = convert_ui_workflow(data) + statuses[result.status] += 1 + needs_confirmation += result.needs_confirmation + assert result.workflow, f"{path.name} produced no workflow" + # structural sanity: no dangling links in any conversion + nodes = result.workflow + for nid, node in nodes.items(): + for name, val in node.get("inputs", {}).items(): + if isinstance(val, list): + assert str(val[0]) in nodes, f"{path.name}: {nid}.{name} dangles" + assert statuses["fail"] == 0 + assert statuses["ok"] + statuses["warn"] == 146 + # files whose widget order cannot be trusted are flagged, never hidden + assert 0 < needs_confirmation < 10 + + +@pytest.mark.skipif(not EXAMPLES.is_dir(), reason="example library missing") +def test_cross_check_against_ground_truth_exports(): + """The H3 t2v UI export converts to the same node classes the author's + own API export carries; shared classes agree on scalar input names.""" + ui = json.loads( + (EXAMPLES / "4-视频生成/Minimax-h3/minimax_h3_t2v_文生视频.json").read_text(encoding="utf-8") + ) + api = json.loads( + (EXAMPLES / "minimax_h3-Turbo_Text2Video_20260813_API.json").read_text(encoding="utf-8") + ) + result = convert_ui_workflow(ui) + assert result.status in ("ok", "warn") + converted = result.workflow + api_classes = {n["class_type"] for n in api.values()} + # Every scalar name the conversion emits for a shared class must be an + # input name the author's own export knows — wiring may differ between + # versions (a muted branch falls back to its widget value), but the NAME + # mapping must never invent or swap inputs. + for cls in api_classes & {n["class_type"] for n in converted.values()}: + api_names = { + key + for n in api.values() + if n["class_type"] == cls + for key in n.get("inputs", {}) + } + conv_names = { + key + for n in converted.values() + if n["class_type"] == cls + for key, v in n.get("inputs", {}).items() + if not isinstance(v, list) + } + assert conv_names <= api_names, f"class {cls} invents inputs: {conv_names - api_names}" + + +@pytest.mark.skipif(not EXAMPLES.is_dir(), reason="example library missing") +def test_packed_krea2_conversion_shape_matches_export_scheme(): + """The krea2 turbo file (packed subgraph) converts ok, expands inner nodes + under `:` ids and maps the sampler widgets exactly — the + same scheme the author's own Krea2 API export uses (ids like "171:153").""" + ui = json.loads( + (EXAMPLES / "3-图像生成/krea2/krea2_turbo_文生图.json").read_text(encoding="utf-8") + ) + api = json.loads( + (EXAMPLES / "Krea2_t2i_20260818_API.json").read_text(encoding="utf-8") + ) + result = convert_ui_workflow(ui) + assert result.status == "ok" + assert any(":" in nid for nid in result.workflow) # expanded subgraph nodes + assert any("171:" in nid for nid in api) # ground truth uses the same scheme + ks = [ + n + for n in result.workflow.values() + if n["class_type"] == "KSampler" and not isinstance(n["inputs"].get("seed"), list) + ] + assert ks, "inner KSampler with widget-mapped seed expected" + assert {"seed", "steps", "cfg", "sampler_name", "scheduler", "denoise"} <= set( + ks[0]["inputs"] + ) diff --git a/calliope-backend/tests/test_workbench.py b/calliope-backend/tests/test_workbench.py index 4c522d98..be846562 100644 --- a/calliope-backend/tests/test_workbench.py +++ b/calliope-backend/tests/test_workbench.py @@ -197,6 +197,39 @@ def _confirm(client, pid: int, key: str, **extra): return client.post(f"/api/workbench/projects/{pid}/stages/{key}/confirm", json=extra or None) +def test_assistant_notes_keep_confirmation_and_survive_artifact_edits(client): + pid = _make_project(client) + note_url = f"/api/workbench/projects/{pid}/stages/style/note" + r = client.patch(note_url, json={"text": "建议先比较冷暖两个方向。"}) + assert r.status_code == 200 + assert r.json()["stage"]["status"] == "todo" + assert r.json()["stage"]["assistant_note"] == "建议先比较冷暖两个方向。" + assert _confirm(client, pid, "style").status_code == 400 + # An ordinary structured save must keep the separate advice. + r = client.patch(f"/api/workbench/projects/{pid}/stages/style", json={"content": json.loads(STYLE_REPLY)}) + assert r.status_code == 200 + assert r.json()["stage"]["assistant_note"] == "建议先比较冷暖两个方向。" + # Notes on confirmed content don't change its status or confirmed snapshot. + client.post(f"/api/workbench/projects/{pid}/stages/script/import", json={"text": SCRIPT_TEXT}) + before = _stage(_overview(client, pid), "script") + r = client.patch(f"/api/workbench/projects/{pid}/stages/script/note", json={"text": "下一版建议加强人物动机。"}) + assert r.status_code == 200 + after = r.json()["stage"] + assert after["status"] == before["status"] == "confirmed" + assert after["confirmed_content"] == before["confirmed_content"] + assert after["draft_edited"] == before["draft_edited"] + assert _confirm(client, pid, "script").status_code == 200 + confirmed = _stage(_overview(client, pid), "script") + assert "assistant_note" not in confirmed["confirmed_content"] + client.patch(f"/api/workbench/projects/{pid}/stages/script/note", json={"text": "保留确认后的新建议。"}) + restored = client.post(f"/api/workbench/projects/{pid}/stages/script/restore").json()["stage"] + assert restored["assistant_note"] == "保留确认后的新建议。" + assert restored["confirmed_content"] == confirmed["confirmed_content"] + assert client.patch(note_url, json={"text": ""}).json()["stage"]["assistant_note"] == "" + assert client.patch(note_url, json={"text": "x" * 200_001}).status_code == 422 + assert client.patch(f"/api/workbench/projects/{pid}/stages/unknown/note", json={"text": "x"}).status_code == 404 + + # ───────────────────────────────────────────────────────────────────────── diff --git a/calliope-backend/tests/test_workflow_import_batch.py b/calliope-backend/tests/test_workflow_import_batch.py new file mode 100644 index 00000000..61671bab --- /dev/null +++ b/calliope-backend/tests/test_workflow_import_batch.py @@ -0,0 +1,421 @@ +"""HEL-681 (S2): batch import endpoints, meta list view, migration safety. + +Everything runs on a temp DB via the shared client fixture — the real +146-file library is never touched, matching the card's「不导入生产数据」boundary. +""" + +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path + +from calliope.db import migrate_db + +import pytest + + +EXAMPLES = Path(__file__).resolve().parents[2] / "example_ComfyUI_workflows" + + +def _ui_graph(): + """Minimal clean t2i UI graph (same shape as test_ui_convert's).""" + return { + "nodes": [ + { + "id": 1, + "type": "CheckpointLoaderSimple", + "mode": 0, + "inputs": [{"name": "ckpt_name", "type": "COMBO", "widget": {"name": "ckpt_name"}, "link": None}], + "outputs": [ + {"name": "MODEL", "type": "MODEL", "links": [3], "slot_index": 0}, + {"name": "CLIP", "type": "CLIP", "links": [1, 2], "slot_index": 1}, + {"name": "VAE", "type": "VAE", "links": [8], "slot_index": 2}, + ], + "widgets_values": ["qwen_image_2.safetensors"], + }, + { + "id": 2, + "type": "CLIPTextEncode", + "mode": 0, + "inputs": [ + {"name": "clip", "type": "CLIP", "link": 1}, + {"name": "text", "type": "STRING", "widget": {"name": "text"}, "link": None}, + ], + "outputs": [{"name": "CONDITIONING", "type": "CONDITIONING", "links": [4], "slot_index": 0}], + "widgets_values": ["a cat"], + }, + { + "id": 3, + "type": "CLIPTextEncode", + "mode": 0, + "inputs": [ + {"name": "clip", "type": "CLIP", "link": 2}, + {"name": "text", "type": "STRING", "widget": {"name": "text"}, "link": None}, + ], + "outputs": [{"name": "CONDITIONING", "type": "CONDITIONING", "links": [5], "slot_index": 0}], + "widgets_values": ["bad"], + }, + { + "id": 4, + "type": "EmptyLatentImage", + "mode": 0, + "inputs": [ + {"name": "width", "type": "INT", "widget": {"name": "width"}, "link": None}, + {"name": "height", "type": "INT", "widget": {"name": "height"}, "link": None}, + {"name": "batch_size", "type": "INT", "widget": {"name": "batch_size"}, "link": None}, + ], + "outputs": [{"name": "LATENT", "type": "LATENT", "links": [6], "slot_index": 0}], + "widgets_values": [512, 512, 1], + }, + { + "id": 5, + "type": "KSampler", + "mode": 0, + "inputs": [ + {"name": "model", "type": "MODEL", "link": 3}, + {"name": "positive", "type": "CONDITIONING", "link": 4}, + {"name": "negative", "type": "CONDITIONING", "link": 5}, + {"name": "latent_image", "type": "LATENT", "link": 6}, + {"name": "seed", "type": "INT", "widget": {"name": "seed"}, "link": None}, + {"name": "steps", "type": "INT", "widget": {"name": "steps"}, "link": None}, + {"name": "cfg", "type": "FLOAT", "widget": {"name": "cfg"}, "link": None}, + {"name": "sampler_name", "type": "COMBO", "widget": {"name": "sampler_name"}, "link": None}, + {"name": "scheduler", "type": "COMBO", "widget": {"name": "scheduler"}, "link": None}, + {"name": "denoise", "type": "FLOAT", "widget": {"name": "denoise"}, "link": None}, + ], + "outputs": [{"name": "LATENT", "type": "LATENT", "links": [7], "slot_index": 0}], + "widgets_values": [42, "fixed", 20, 7, "euler", "normal", 1.0], + }, + { + "id": 6, + "type": "VAEDecode", + "mode": 0, + "inputs": [ + {"name": "samples", "type": "LATENT", "link": 7}, + {"name": "vae", "type": "VAE", "link": 8}, + ], + "outputs": [{"name": "IMAGE", "type": "IMAGE", "links": [9], "slot_index": 0}], + }, + { + "id": 7, + "type": "SaveImage", + "mode": 0, + "inputs": [ + {"name": "images", "type": "IMAGE", "link": 9}, + {"name": "filename_prefix", "type": "STRING", "widget": {"name": "filename_prefix"}, "link": None}, + ], + "widgets_values": ["test"], + }, + ], + "links": [ + [1, 1, 1, 2, 0, "CLIP"], + [2, 1, 1, 3, 0, "CLIP"], + [3, 1, 0, 5, 0, "MODEL"], + [4, 2, 0, 5, 1, "CONDITIONING"], + [5, 3, 0, 5, 2, "CONDITIONING"], + [6, 4, 0, 5, 3, "LATENT"], + [7, 5, 0, 6, 0, "LATENT"], + [8, 1, 2, 6, 1, "VAE"], + [9, 6, 0, 7, 0, "IMAGE"], + ], + } + + +def _api_workflow(): + return json.loads( + (EXAMPLES / "video_minimax_h3_r2v_2ref_API.json").read_text(encoding="utf-8") + ) + + +def test_convert_dry_run_reports_and_stores_nothing(client): + payload = { + "files": [ + { + "source_path": "3-图像生成/Qwen-Image-2.1/test_t2i.json", + "workflow_json": _ui_graph(), + } + ], + "include_workflows": True, + } + resp = client.post("/api/workflows/convert", json=payload) + assert resp.status_code == 200 + body = resp.json() + assert body["total"] == 1 and body["ok"] == 1 and body["importable"] == 1 + entry = body["files"][0] + assert entry["name"] == "test_t2i" + assert entry["workflow_json"]["5"]["inputs"]["seed"] == 42 + assert entry["suggested"]["usage"] == "text2image" + assert entry["suggested"]["category"] == "image" + assert entry["suggested"]["model_family"] == "Qwen" + assert entry["suggested"]["media_out"] == ["image"] + # dry-run must not write anything + assert client.get("/api/workflows").json() == [] + + +def test_convert_needs_confirmation_is_flagged_not_runnable(client): + graph = _ui_graph() + graph["nodes"].append( + { + "id": 10, + "type": "MysteryCustomNode", + "mode": 0, + "inputs": [], + "outputs": [{"name": "IMAGE", "type": "IMAGE", "links": [30], "slot_index": 0}], + "widgets_values": [1, 2, 3], + } + ) + graph["nodes"].append( + { + "id": 11, + "type": "PreviewImage", + "mode": 0, + "inputs": [{"name": "images", "type": "IMAGE", "link": 30}], + "widgets_values": ["p"], + } + ) + graph["links"].append([30, 10, 0, 11, 0, "IMAGE"]) + resp = client.post( + "/api/workflows/convert", + json={"files": [{"source_path": "x/mystery.json", "workflow_json": graph}]}, + ) + body = resp.json() + assert body["needs_confirmation"] == 1 + assert body["importable"] == 0 + assert "需人工确认" in body["files"][0]["skip_reason"] + + +def test_import_batch_then_rerun_is_idempotent(client): + files = [ + { + "source_path": "3-图像生成/Qwen-Image-2.1/test_t2i.json", + "workflow_json": _ui_graph(), + } + ] + first = client.post("/api/workflows/import-batch", json={"files": files}) + assert first.status_code == 200 + body = first.json() + assert body["imported"] == 1 and body["skipped"] == 0 + row_id = body["imported_ids"][0] + + # second run with identical file: conflict skip, no duplicates + second = client.post("/api/workflows/import-batch", json={"files": files}) + body2 = second.json() + assert body2["imported"] == 0 and body2["skipped"] == 1 + assert body2["skipped_files"][0]["reason"] == "conflict" + listing = client.get("/api/workflows").json() + assert len(listing) == 1 + + detail = client.get(f"/api/workflows/{row_id}").json() + assert detail["usage"] == "text2image" + assert detail["is_enabled"] is True + assert detail["category"] == "image" + assert detail["model_family"] == "Qwen" + assert detail["media_io"] == {"in": [], "out": ["image"]} + assert detail["source"] == "ui_convert" + assert detail["source_path"] == "3-图像生成/Qwen-Image-2.1/test_t2i.json" + + +def test_import_batch_skips_needs_confirmation_files(client): + graph = _ui_graph() + graph["nodes"].append( + { + "id": 10, + "type": "MysteryCustomNode", + "mode": 0, + "inputs": [], + "outputs": [{"name": "IMAGE", "type": "IMAGE", "links": [30], "slot_index": 0}], + "widgets_values": [1, 2, 3], + } + ) + graph["nodes"].append( + { + "id": 11, + "type": "PreviewImage", + "mode": 0, + "inputs": [{"name": "images", "type": "IMAGE", "link": 30}], + "widgets_values": ["p"], + } + ) + graph["links"].append([30, 10, 0, 11, 0, "IMAGE"]) + resp = client.post( + "/api/workflows/import-batch", + json={"files": [{"name": "mystery", "workflow_json": graph}]}, + ) + body = resp.json() + assert body["imported"] == 0 + assert "需人工确认" in body["skipped_files"][0]["reason"] + assert client.get("/api/workflows").json() == [] + + +def test_warn_sample_imports_with_human_confirmation(client): + """A warn file (muted branch → input dropped) still imports when the + wizard supplies the settled usage — the manual-correction path.""" + graph = _ui_graph() + graph["nodes"][2]["mode"] = 2 # mute the negative prompt branch + dry = client.post( + "/api/workflows/convert", + json={"files": [{"name": "warned", "workflow_json": graph}]}, + ).json() + assert dry["warn"] == 1 and dry["importable"] == 1 + resp = client.post( + "/api/workflows/import-batch", + json={"files": [{"name": "warned", "workflow_json": graph, "usage": "text2image"}]}, + ) + body = resp.json() + assert body["imported"] == 1 + detail = client.get(f"/api/workflows/{body['imported_ids'][0]}").json() + assert detail["is_enabled"] is True + assert "negative" not in detail["workflow_json"]["5"]["inputs"] + + +@pytest.mark.skipif(not EXAMPLES.is_dir(), reason="example library missing") +def test_import_scan_dry_run_over_repo_library(client): + resp = client.post( + "/api/workflows/import-scan", + json={"root": str(EXAMPLES), "dry_run": True}, + ) + assert resp.status_code == 200 + body = resp.json() + assert body["total"] == 146 + assert body["fail"] == 0 + assert body["ok"] + body["warn"] == 146 + assert body["needs_confirmation"] > 0 # the 3 uncensored files stay honest + assert body["importable"] < body["total"] + # a dry scan must leave the DB untouched + assert client.get("/api/workflows").json() == [] + + +def test_import_scan_commit_from_tmp_directory(client, tmp_path): + (tmp_path / "sub").mkdir() + (tmp_path / "sub" / "demo.json").write_text(json.dumps(_ui_graph()), encoding="utf-8") + (tmp_path / "plain_api.json").write_text(json.dumps(_api_workflow()), encoding="utf-8") + (tmp_path / "not_a_workflow.json").write_text(json.dumps({"hello": 1}), encoding="utf-8") + resp = client.post( + "/api/workflows/import-scan", + json={"root": str(tmp_path), "dry_run": False}, + ) + body = resp.json() + # only the one UI file went through this pipeline; API-format and junk skipped + assert body["imported"] == 1 + listing = client.get("/api/workflows").json() + assert len(listing) == 1 + assert listing[0]["source_path"] == "sub/demo.json" + # rerun: idempotent + again = client.post( + "/api/workflows/import-scan", + json={"root": str(tmp_path), "dry_run": False}, + ).json() + assert again["imported"] == 0 + assert len(client.get("/api/workflows").json()) == 1 + + +def test_meta_view_has_metadata_but_no_full_json(client): + client.post( + "/api/workflows/import-batch", + json={ + "files": [ + { + "source_path": "3-图像生成/Qwen-Image-2.1/test_t2i.json", + "workflow_json": _ui_graph(), + "tags": ["极速"], + } + ] + }, + ) + meta = client.get("/api/workflows", params={"view": "meta"}).json() + assert len(meta) == 1 + row = meta[0] + assert "workflow_json" not in row + assert "input_schema" not in row + assert "output_schema" not in row + assert row["category"] == "image" + assert row["model_family"] == "Qwen" + assert row["media_io"] == {"in": [], "out": ["image"]} + assert row["tags"] == ["极速"] + assert row["favorite"] is False + assert row["needs_mapping"] is False + + +def test_legacy_list_shape_and_old_records_unchanged(client): + """Old imports (API format via POST /api/workflows) keep working; the + legacy list still carries workflow_json and the new columns default.""" + created = client.post( + "/api/workflows", + json={"name": "旧导入", "workflow_json": _api_workflow()}, + ) + assert created.status_code == 200 + legacy = client.get("/api/workflows").json() + assert len(legacy) == 1 + row = legacy[0] + assert isinstance(row["workflow_json"], dict) + assert "usage" in row and "output_map" in row + assert row["favorite"] is False + assert row["tags"] == [] + assert row["media_io"] == {"in": [], "out": []} + meta = client.get("/api/workflows", params={"view": "meta"}).json() + assert meta[0]["needs_mapping"] is False or meta[0]["needs_mapping"] is True + assert meta[0]["source"] is None + + +def test_favorite_tags_patch_and_touch(client): + wid = client.post( + "/api/workflows/import-batch", + json={"files": [{"name": "fav", "workflow_json": _ui_graph()}]}, + ).json()["imported_ids"][0] + resp = client.patch(f"/api/workflows/{wid}", json={"favorite": True, "tags": ["高质量"]}) + assert resp.status_code == 200 + assert resp.json()["favorite"] is True + assert resp.json()["tags"] == ["高质量"] + touch = client.post(f"/api/workflows/{wid}/touch") + assert touch.status_code == 200 + meta = client.get("/api/workflows", params={"view": "meta"}).json() + assert meta[0]["last_used_at"] is not None + assert meta[0]["favorite"] is True + + +def test_migration_adds_columns_on_old_database(tmp_path): + """A pre-S2 database (workflows table without the metadata columns) + migrates in place; existing rows survive with defaults.""" + db_path = tmp_path / "old.db" + conn = sqlite3.connect(db_path) + conn.executescript( + """ + CREATE TABLE workflows ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + kind TEXT NOT NULL CHECK(kind IN ('image', 'video')), + workflow_json TEXT NOT NULL, + description TEXT, + prompt_profile TEXT NOT NULL DEFAULT 'prose', + is_enabled INTEGER NOT NULL DEFAULT 1, + usage TEXT, + usage_source TEXT, + output_map TEXT, + output_map_source TEXT + ); + INSERT INTO workflows (name, kind, workflow_json) + VALUES ('legacy', 'video', '{"1": {"class_type": "SaveImage", "inputs": {}}}'); + """ + ) + conn.commit() + conn.close() + + import asyncio + + asyncio.run(migrate_db(db_path)) + conn = sqlite3.connect(db_path) + cols = {r[1] for r in conn.execute("PRAGMA table_info(workflows)").fetchall()} + assert { + "category", + "model_family", + "media_io", + "tags", + "favorite", + "last_used_at", + "source", + "source_path", + } <= cols + row = conn.execute("SELECT name, favorite, tags, category FROM workflows").fetchone() + assert row == ("legacy", 0, None, None) + conn.close() diff --git a/calliope-web/src/lib/actions/spotlight.ts b/calliope-web/src/lib/actions/spotlight.ts new file mode 100644 index 00000000..c56b329c --- /dev/null +++ b/calliope-web/src/lib/actions/spotlight.ts @@ -0,0 +1,17 @@ +import type { Action } from 'svelte/action'; + +/** A local honeycomb highlight follows the pointer, independent of selected state. */ +export const spotlight: Action = (node) => { + const move = (event: PointerEvent) => { + if ( + document.documentElement.dataset.reduce === '1' || + event.pointerType === 'touch' + ) + return; + const rect = node.getBoundingClientRect(); + node.style.setProperty('--pointer-x', `${event.clientX - rect.left}px`); + node.style.setProperty('--pointer-y', `${event.clientY - rect.top}px`); + }; + node.addEventListener('pointermove', move); + return { destroy: () => node.removeEventListener('pointermove', move) }; +}; diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 6f1706f1..96f8257c 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -140,6 +140,11 @@ import type { WorkflowOutputMapEntry, WorkflowConnectionCheck, WorkflowLastTest, + WorkflowMeta, + WorkflowUIFileInput, + WorkflowConvertFileReport, + WorkflowConvertReport, + WorkflowImportResult, } from "./comfy/types"; export type { Job, @@ -154,6 +159,11 @@ export type { WorkflowOutputMapEntry, WorkflowConnectionCheck, WorkflowLastTest, + WorkflowMeta, + WorkflowUIFileInput, + WorkflowConvertFileReport, + WorkflowConvertReport, + WorkflowImportResult, }; async function api(path: string, init?: RequestInit): Promise { @@ -462,6 +472,50 @@ export const comfy = { export const workflows = { list: () => api("/api/workflows"), + /** HEL-682: metadata-only list — 150+ rows without any workflow_json. */ + listMeta: () => api("/api/workflows?view=meta"), + /** HEL-682: dry-run UI→API conversion for a batch of files (nothing stored). */ + convert: ( + files: WorkflowUIFileInput[], + opts?: { endpoint_id?: string | null; refresh?: boolean }, + ) => + api("/api/workflows/convert", { + method: "POST", + body: JSON.stringify({ + files, + ...(opts?.endpoint_id ? { endpoint_id: opts.endpoint_id } : {}), + ...(opts?.refresh ? { refresh: opts.refresh } : {}), + }), + }), + /** HEL-682: commit a batch import (converts server-side, conflicts skipped). */ + importBatch: (files: WorkflowUIFileInput[]) => + api("/api/workflows/import-batch", { + method: "POST", + body: JSON.stringify({ files }), + }), + /** HEL-682: scan a server-side directory of UI-format JSONs — dry-run report. */ + importScanDry: (root: string) => + api("/api/workflows/import-scan", { + method: "POST", + body: JSON.stringify({ root, dry_run: true }), + }), + /** HEL-682: scan a server-side directory of UI-format JSONs — commit the import. */ + importScanCommit: (root: string) => + api("/api/workflows/import-scan", { + method: "POST", + body: JSON.stringify({ root, dry_run: false }), + }), + /** HEL-682: record a use (最近使用). */ + touch: (id: number) => + api<{ ok: boolean }>(`/api/workflows/${id}/touch`, { method: "POST" }), + /** HEL-682: delete byte-identical duplicates, keeping the lowest id. */ + dedupe: () => + api<{ + ok: boolean; + removed: number; + kept_ids: number[]; + removed_ids: number[]; + }>("/api/workflows/dedupe", { method: "POST" }), analyze: ( workflow_json: Record, endpoint_id?: string | null, @@ -537,6 +591,10 @@ export const workflows = { input_schema: ComfyDynamicInput[]; output_map: WorkflowOutputMapEntry[]; output_map_source: "auto" | "user"; + favorite: boolean; + tags: string[]; + category: string; + model_family: string; }>, ) => api(`/api/workflows/${id}`, { @@ -638,6 +696,15 @@ export const playgroundApi = { endpoint_id?: string | null; /** Origin recorded on the job payload (tasks page labels). */ source?: "playground" | "studio-image" | "studio-video"; + /** Optional real workbench source (HEL-684) — validated server-side and + * stamped on the job so finished takes can flow back to their row. */ + context?: { + project_id: number; + stage: "assets" | "shot"; + source_kind: "asset" | "shot"; + source_id: string; + label?: string; + }; }) => api<{ ok: boolean; job: Job }>("/api/playground/generate", { method: "POST", @@ -655,7 +722,24 @@ export const playgroundApi = { job_id: number; deleted_files: string[]; missing_files: string[]; + removed_workbench_links?: number[]; }>(`/api/playground/jobs/${jobId}`, { method: "DELETE" }), + /** Flow a finished take back to the workbench row it came from (HEL-684). + * The server derives the target from the job's own recorded context — + * idempotent, never overwrites, refuses stale source rows. */ + attachWorkbench: (jobId: number) => + api<{ + ok: boolean; + already_attached: boolean; + job_id: number; + attached_job_id: number; + project_id: number; + stage: "assets" | "shot"; + target_id: string; + }>("/api/playground/attach-workbench", { + method: "POST", + body: JSON.stringify({ job_id: jobId }), + }), attach: (payload: { path: string; project_id: number; @@ -750,6 +834,7 @@ export interface VideoShot { } export interface WorkbenchStage { + assistant_note?: string; stage_key: WorkbenchStageKey; status: WorkbenchStageStatus; content: Record | null; @@ -773,6 +858,11 @@ export interface WorkbenchOverview { } export const workbenchApi = { + saveNote: (projectId: number, stageKey: WorkbenchStageKey, text: string) => + api<{ ok: boolean; stage: WorkbenchStage }>( + `/api/workbench/projects/${projectId}/stages/${stageKey}/note`, + { method: "PATCH", body: JSON.stringify({ text }) }, + ), overview: (projectId: number) => api(`/api/workbench/projects/${projectId}`), patchStage: ( diff --git a/calliope-web/src/lib/canvas/ArtifactNode.svelte b/calliope-web/src/lib/canvas/ArtifactNode.svelte index 44c732cc..74a2fb79 100644 --- a/calliope-web/src/lib/canvas/ArtifactNode.svelte +++ b/calliope-web/src/lib/canvas/ArtifactNode.svelte @@ -98,8 +98,8 @@ position: relative; } .artifact-node.running { - border-color: rgba(125, 211, 252, 0.6); - box-shadow: 0 0 18px rgba(125, 211, 252, 0.25); + border-color: var(--run); + box-shadow: 0 0 18px var(--run-soft); } :global(.svelte-flow__node.selected) .artifact-node { border-color: var(--accent); @@ -117,9 +117,9 @@ font-size: 9px; letter-spacing: 0.06em; text-transform: uppercase; - color: #bae6fd; - background: rgba(12, 74, 110, 0.55); - border: 1px solid rgba(125, 211, 252, 0.35); + color: var(--text-2); + background: var(--bg-4); + border: 1px solid var(--line-2); border-radius: 999px; padding: 2px 6px; flex-shrink: 0; @@ -141,12 +141,12 @@ flex-shrink: 0; } .running-badge { - color: #bae6fd; - background: rgba(12, 74, 110, 0.6); + color: var(--run); + background: var(--run-soft); } .failed-badge { - color: #fecaca; - background: rgba(127, 29, 29, 0.5); + color: var(--err); + background: var(--err-soft); } .play-badge { font-size: 9px; @@ -205,9 +205,9 @@ font-weight: 600; letter-spacing: 0.04em; text-transform: lowercase; - color: var(--text-muted); + color: var(--on-media); pointer-events: none; - background: rgba(0, 0, 0, 0.55); + background: var(--media-scrim); padding: 1px 5px; border-radius: 999px; } diff --git a/calliope-web/src/lib/canvas/EntityNode.svelte b/calliope-web/src/lib/canvas/EntityNode.svelte index 68f98078..d29e77ae 100644 --- a/calliope-web/src/lib/canvas/EntityNode.svelte +++ b/calliope-web/src/lib/canvas/EntityNode.svelte @@ -108,7 +108,7 @@ transition: border-color 0.15s; } .entity-node:hover { - border-color: #3a3a44; + border-color: var(--line-2); } /* Svelte Flow marks the selected node wrapper with .selected */ :global(.svelte-flow__node.selected) .entity-node { @@ -176,9 +176,9 @@ font-weight: 600; letter-spacing: 0.04em; text-transform: lowercase; - color: var(--text-muted); + color: var(--on-media); pointer-events: none; - background: rgba(0, 0, 0, 0.55); + background: var(--media-scrim); padding: 1px 5px; border-radius: 999px; } diff --git a/calliope-web/src/lib/canvas/tokens.css b/calliope-web/src/lib/canvas/tokens.css deleted file mode 100644 index 38611ada..00000000 --- a/calliope-web/src/lib/canvas/tokens.css +++ /dev/null @@ -1,13 +0,0 @@ -/* Canvas v2.1 scoped visual tokens (spec v2.0 §2) — canvas surfaces only. - The global --accent stays untouched for v1 pages. */ -.canvas-root { - --accent: #4f46a5; - --accent-hover: #6157c9; - --accent-glow: rgba(99, 102, 241, 0.3); - --edge: #7dd3fc; - /* Edge-chip surfaces (LinkEdge label) — fallbacks match the dark theme. */ - --panel: #17171f; - --panel-border: #2a2a35; - --fg: #f4f4f5; - --fg-dim: #a1a1aa; -} diff --git a/calliope-web/src/lib/comfy/types.ts b/calliope-web/src/lib/comfy/types.ts index 10a2c155..bc2e8901 100644 --- a/calliope-web/src/lib/comfy/types.ts +++ b/calliope-web/src/lib/comfy/types.ts @@ -175,6 +175,120 @@ export interface Workflow { last_test?: WorkflowLastTest | null; } +/** + * HEL-682: metadata-only row (GET /api/workflows?view=meta) — the whole + * point is browsing 150+ workflows without downloading workflow_json. + */ +export interface WorkflowMediaIO { + in: string[]; + out: string[]; +} + +export interface WorkflowMeta { + id: number; + name: string; + kind: 'image' | 'video'; + usage: WorkflowUsage | null; + usage_source: 'auto' | 'user' | null; + is_enabled: boolean; + category: string | null; + model_family: string | null; + media_io: WorkflowMediaIO; + tags: string[]; + favorite: boolean; + last_used_at: string | null; + description: string | null; + source: string | null; + source_path: string | null; + prompt_profile: string; + created_at: string; + endpoint_id: string | null; + output_map_source: 'auto' | 'user' | null; + /** Cheap pending check: usage or output mapping not settled yet. */ + needs_mapping: boolean; +} + +/** One UI-format file submitted to the batch convert/import pipeline. */ +export interface WorkflowUIFileInput { + name?: string; + source_path?: string; + workflow_json: Record; + usage?: WorkflowUsage; + description?: string; + tags?: string[]; +} + +export interface WorkflowConvertIssue { + node_id: string; + code: string; + level: 'error' | 'warning'; + message: string; +} + +export interface WorkflowConvertSuggested { + kind: 'image' | 'video'; + usage: WorkflowUsage | null; + usage_ambiguous: boolean; + category: string | null; + category_label: string | null; + model_family: string | null; + media_in: string[]; + media_out: string[]; + description: string | null; +} + +export interface WorkflowPreflightFinding { + level: string; + code: string; + node_id?: string; + node_title?: string; + message: string; + hint?: string; +} + +export interface WorkflowConvertFileReport { + name: string; + source_path: string | null; + status: 'ok' | 'warn' | 'fail'; + needs_confirmation: boolean; + issues: WorkflowConvertIssue[]; + importable: boolean; + skip_reason?: string | null; + suggested?: WorkflowConvertSuggested; + preflight?: { + endpoint_id: string | null; + ok: boolean; + findings: WorkflowPreflightFinding[]; + }; +} + +/** Dry-run report (POST /convert, POST /import-scan with dry_run). */ +export interface WorkflowConvertReport { + total: number; + ok: number; + warn: number; + fail: number; + needs_confirmation: number; + importable: number; + files: WorkflowConvertFileReport[]; +} + +export interface WorkflowImportFileReport extends WorkflowConvertFileReport { + result?: 'imported' | 'skipped' | 'failed'; + id?: number; + existing_id?: number; +} + +/** Commit result (POST /import-batch, POST /import-scan without dry_run). */ +export interface WorkflowImportResult { + total: number; + imported: number; + skipped: number; + imported_ids: number[]; + skipped_files: { name: string; source_path: string | null; reason: string | null }[]; + files: WorkflowImportFileReport[]; +} + export interface Job { id: number; project_id: number; @@ -197,6 +311,13 @@ export interface Job { phase?: string | null; /** 'user' (normal generation) or 'workflow_test' (HEL-643 test run). */ origin?: string; + /** HEL-684: present when this take has been flowed back to its + * workbench source row (link job id on the source project). */ + workbench_attach?: { + job_id: number; + stage: string; + target_id: string; + }; } export interface SceneVideoSettings { diff --git a/calliope-web/src/lib/components/ComfyDynamicForm.svelte b/calliope-web/src/lib/components/ComfyDynamicForm.svelte index 3fe8606f..a65797ab 100644 --- a/calliope-web/src/lib/components/ComfyDynamicForm.svelte +++ b/calliope-web/src/lib/components/ComfyDynamicForm.svelte @@ -522,7 +522,7 @@ } .role { font-weight: 600; - color: var(--accent, #a78bfa); + color: var(--accent); font-size: 11px; margin-left: 6px; font-family: ui-monospace, monospace; @@ -567,7 +567,7 @@ input.invalid:focus-visible, textarea.invalid:focus-visible, select.invalid:focus-visible { - box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.25); + box-shadow: 0 0 0 3px var(--err-soft); } .error-msg { font-size: 11px; @@ -607,7 +607,7 @@ } .clear:hover { color: var(--error); - border-color: rgba(239, 68, 68, 0.4); + border-color: var(--err-line); } .clear:focus-visible { outline: 2px solid var(--accent); diff --git a/calliope-web/src/lib/components/GeneratingOverlay.svelte b/calliope-web/src/lib/components/GeneratingOverlay.svelte index 73c15d82..05892b0c 100644 --- a/calliope-web/src/lib/components/GeneratingOverlay.svelte +++ b/calliope-web/src/lib/components/GeneratingOverlay.svelte @@ -30,7 +30,7 @@ position: absolute; inset: 0; z-index: 30; - background: rgba(18, 18, 24, 0.78); + background: var(--overlay); backdrop-filter: blur(2px); border-radius: var(--radius-md); display: flex; diff --git a/calliope-web/src/lib/components/ImageLightbox.svelte b/calliope-web/src/lib/components/ImageLightbox.svelte index 83af0980..ac1fbd52 100644 --- a/calliope-web/src/lib/components/ImageLightbox.svelte +++ b/calliope-web/src/lib/components/ImageLightbox.svelte @@ -96,8 +96,8 @@ + {#if compareSource && compareSource !== output}{/if} + {/if} + {#if output}↓ 下载{/if} + + + +
+ {#if job && st}{#key mediaKey} +
+ {#if output && video} + +
+ {#if st.tone === 'ok' && !fileGone}{t('jobst.done')}{/if} + +
+ {:else if output} +
+ {#if st.tone === 'ok' && !fileGone}{t('jobst.done')}{/if} + {prompt { + clearOutputMissing(output); + noteImg(e); + }} + onerror={() => output && markOutputMissing(output)} + /> + {#if main && compare && compareSource}
+ 对比参考画面 +
+
{/if} +
+ {:else if fileGone} +
+ {t('desk.missingTitle')} + {t('desk.missingSub')} +
+ {:else} +
+ {st.label} + {st.tone === 'fail' ? t('desk.notGenerated') : st.detail} + {#if progress > 0} +
+ +
+ {/if} +
+ {/if} +
+ {/key}{/if} + {#if outputs.length > 1}
+ {#each outputs as p, i}{/each} +
{/if} +
+
+ {#if video}{/if} + {dims || st?.label} · {job ? fmtDur(elapsedSec(job, nowMs)) : ''} + {#if compare && output && !video}{/if} + {#if job?.status === 'pending' || job?.status === 'running'}{/if} + {#if st?.tone === 'fail'}{/if} +
+ + + {#if job && st} +
+ + {#if output && !video && canSendToSlot}{/if} + {#if video && output}{/if} + {#if st.tone === 'fail' || fileGone}{/if} + {#if job.status !== 'pending' && job.status !== 'running'}{/if} +
+ {#if st.tone === 'fail' || fileGone}{/if} +
+ {#each spec as s}{s.label} · {s.value}{/each}{#if endpoint}{endpoint}{/if} +
+ {#if inputs.length || prompt} +
{t('desk.inputs')}
+ {#if inputs.length} +
+ {#each inputs as inp (inp.label + inp.path)} + {#if inp.kind === 'image'} + {inp.label} + {:else} + + {/if} + {/each} +
+ {/if} + {#if prompt}

{prompt}

{/if} + {/if} + +
{t('desk.workflow')}
+
+
{t('desk.kvName')}
+
+ {wf?.name ?? t('studio.jobName', { id: job.id })} + {#if wfDeleted}{t('studio.wfDeletedTag')}{/if} +
+ {#if wf?.usage} +
{t('desk.kvUsage')}
+
{usageLabel(wf.usage)}
+ {/if} +
{t('desk.kvCreated')}
+
{fmtClock(parseDbTs(job.created_at))}
+ {#if job.comfy_prompt_id} +
{t('desk.kvPromptId')}
+
{job.comfy_prompt_id}
+ {/if} +
+ {/if} +
+{#if lightbox && output && !video} (lightbox = false)} + />{/if} + + diff --git a/calliope-web/src/lib/components/desk/DeskWorkflowRail.svelte b/calliope-web/src/lib/components/desk/DeskWorkflowRail.svelte new file mode 100644 index 00000000..cc937438 --- /dev/null +++ b/calliope-web/src/lib/components/desk/DeskWorkflowRail.svelte @@ -0,0 +1,440 @@ + + + + + diff --git a/calliope-web/src/lib/components/desk/InputRequirementBadge.svelte b/calliope-web/src/lib/components/desk/InputRequirementBadge.svelte new file mode 100644 index 00000000..63b135fa --- /dev/null +++ b/calliope-web/src/lib/components/desk/InputRequirementBadge.svelte @@ -0,0 +1,79 @@ + + +{#if inList.length || outList.length} + + {#each inList as m (m)} + + + {#if !compact}{t(LABELS[m])}{/if} + + {/each} + {#if inList.length && outList.length}→{/if} + {#each outList as m (m)} + + + {#if !compact}{t(LABELS[m])}{/if} + + {/each} + +{:else if !compact} + {t('desk.promptOnly')} +{/if} + + diff --git a/calliope-web/src/lib/components/desk/LibraryFilters.svelte b/calliope-web/src/lib/components/desk/LibraryFilters.svelte new file mode 100644 index 00000000..950a995d --- /dev/null +++ b/calliope-web/src/lib/components/desk/LibraryFilters.svelte @@ -0,0 +1,124 @@ + + +
+ +
+ + +
+ + {resultHint} +
+ + diff --git a/calliope-web/src/lib/components/desk/LibraryRow.svelte b/calliope-web/src/lib/components/desk/LibraryRow.svelte new file mode 100644 index 00000000..dd322f63 --- /dev/null +++ b/calliope-web/src/lib/components/desk/LibraryRow.svelte @@ -0,0 +1,170 @@ + + + + + diff --git a/calliope-web/src/lib/components/desk/ResultRail.svelte b/calliope-web/src/lib/components/desk/ResultRail.svelte new file mode 100644 index 00000000..484969a8 --- /dev/null +++ b/calliope-web/src/lib/components/desk/ResultRail.svelte @@ -0,0 +1,150 @@ + + +
+
+ 生成记录 {jobs.length} +
+
+ {#each sorted as job (job.id)} + {@const path = job.output_paths.find((p) => !missingOutputsOf(job).includes(p))} + {@const status = jobStatusInfo(job)} + + {:else}

生成后,结果会保存在这里。

{/each} +
+
+ + diff --git a/calliope-web/src/lib/components/desk/StudioDesk.svelte b/calliope-web/src/lib/components/desk/StudioDesk.svelte new file mode 100644 index 00000000..8ae3cbe5 --- /dev/null +++ b/calliope-web/src/lib/components/desk/StudioDesk.svelte @@ -0,0 +1,1677 @@ + + + + +{#snippet ctxBanner()} + {#if ctx} + (ctxDismissed = true)} + /> + {/if} +{/snippet} + +{#snippet paramsTab()} + +{/snippet} + + +
+ +
+
+
+ +
+
+ {#if selectedJob && workbenchCtxOf(selectedJob) && selectedJob.status === 'done'}{/if} + +
+
+ {@render ctxBanner()} +
+
+
+ {#if selectedJob} + j.kind === 'image' && + j.status === 'done' && + j.id !== selectedJob?.id, + )?.output_paths[0] ?? null} + bind:tab + job={selectedJob} + wf={selectedJob ? workflowOf(selectedJob) : undefined} + {nowMs} + open={true} + inactive={false} + canSendToSlot={!!imageSlotTarget || !!imageList} + {crossfade} + bind:videoEl + params={paramsTab} + onClose={closeInspector} + onReuse={reuse} + onRetry={retry} + onCancel={cancel} + onSendToSlot={sendToSlot} + onDelete={requestDelete} + />{:else}
+ ● AI 创作引擎 +

让灵感,成为作品

+
{kind === 'image' ? '◈' : '▷'}
+
+ {currentWorkflow?.name ?? + currentMeta?.name ?? + '选择工作流,开始创作'} +

+ {currentWorkflow?.description ?? + currentMeta?.description ?? + '选择左侧工作流,填写下方提示词与参数。'} +

+ 生成结果在这里显示,视频由你手动播放。 +
+
{/if} +
+
+ +
+
+
+
+
+
+
+

找到适合这次创作的工具

+

先看用途和素材要求,再确定使用。

+
+ +
+
+
+ (bayActiveId = id)} + onPick={pickWorkflow} + onClose={closeBay} + /> +
+ +
+
+ +
+ { + selectTake(job, 'pointer'); + historyOpen = false; + }} + onReuse={(job) => { + void reuse(job); + historyOpen = false; + }} + onRetry={retry} + onCancel={cancel} + onDelete={requestDelete} + {attachBusyId} + onAttach={attachToProject} + /> +
+
+ (paramDraft = null)} +> + {#snippet footer()}
+ 保存后应用到当前工作流 +
{/snippet} +
+
+ 配置或检查连接 ↗ +
+ {@render paramsTab()} +
+
+ + (pickerFor = null)} +> + {#if imageResults.length} +
+ {#each imageResults as entry (entry.path)} + + {/each} +
+ {:else} +

{t('studio.pickerEmpty')}

+ {/if} +
+ + diff --git a/calliope-web/src/lib/components/desk/TaskModeRail.svelte b/calliope-web/src/lib/components/desk/TaskModeRail.svelte new file mode 100644 index 00000000..eb52b8d8 --- /dev/null +++ b/calliope-web/src/lib/components/desk/TaskModeRail.svelte @@ -0,0 +1,310 @@ + + + + + diff --git a/calliope-web/src/lib/components/desk/WorkflowBay.svelte b/calliope-web/src/lib/components/desk/WorkflowBay.svelte new file mode 100644 index 00000000..df62a8ed --- /dev/null +++ b/calliope-web/src/lib/components/desk/WorkflowBay.svelte @@ -0,0 +1,549 @@ + + + +
+ +
+ +
+ {#if !localOnly}{/if}{#if source === 'local'}{/if}{source === 'local' ? filtered.length : cloudModels.length} 个结果 +
+
+ {#if source === 'cloud'} +
+

让专业搭档加入创作。

+

使用已配置模型,在智能体或画布中创作。自定义多媒体接口与技能可在设置中管理。

+ 打开创作画布 ↗ +
+ {#each cloudModels as profile}{:else}

+ 还没有匹配的模型。配置模型 ↗ +

{/each} + {:else} + {#each visible as m (m.id)}
+ + + {#if m.needs_mapping || !m.is_enabled || !m.usage}{m.needs_mapping ? '完成映射' : '管理工作流'} ↗{/if} +
{:else}

没有找到匹配的工作流,试试更短的关键词。

{/each} + {#if visibleCount < filtered.length}{/if} + {/if} +
+ {#if pendingCount > 0}

+ 另有 {pendingCount} 个工作流待映射。去整理 ↗ +

{/if} +
+
+ + diff --git a/calliope-web/src/lib/components/desk/WorkflowPreview.svelte b/calliope-web/src/lib/components/desk/WorkflowPreview.svelte new file mode 100644 index 00000000..db31983f --- /dev/null +++ b/calliope-web/src/lib/components/desk/WorkflowPreview.svelte @@ -0,0 +1,247 @@ + + +
+ {#if meta} +
+

{meta.name}

+ +
+
+ {#if meta.usage}{usageLabel(meta.usage)}{/if} + {#if meta.model_family}{meta.model_family}{/if} + {#if meta.category && CATEGORY_LABELS[meta.category]} + {t(CATEGORY_LABELS[meta.category])} + {/if} + {#if isCurrent}{t('desk.pvCurrent')}{/if} + {#if broken}{t('desk.wfBroken')}{/if} +
+ + {#if meta.description} +

{meta.description}

+ {/if} + +
+

{t('desk.bayReqTitle')}

+
+ +
+ {#if full} +

{slotSummary(full)}

+ {:else} +

{t('desk.pvSlotsLoading')}

+ {/if} +
+ +
+
+
{t('studio.connLabel')}
+
{endpointName}
+
+ {#if meta.last_used_at} +
+
{t('desk.pvLastUsed')}
+
{new Date(meta.last_used_at).toLocaleString()}
+
+ {/if} + {#if (full?.input_schema ?? []).length} +
+
{t('desk.pvParamCount')}
+
{(full?.input_schema ?? []).length}
+
+ {/if} +
+ +
+ + {#if broken}

{t('studio.errWfBroken')}

{/if} +
+ {:else} +
+ +

{t('desk.pvEmpty')}

+
+ {/if} +
+ + diff --git a/calliope-web/src/lib/components/generate/Composer.svelte b/calliope-web/src/lib/components/generate/Composer.svelte index 65faae9e..fd1f2e70 100644 --- a/calliope-web/src/lib/components/generate/Composer.svelte +++ b/calliope-web/src/lib/components/generate/Composer.svelte @@ -1,23 +1,27 @@ -
- +
0} - class:expanded - onfocusin={() => (expanded = true)} - onfocusout={onFocusOut} - onkeydown={onKeydown} ondragenter={(e) => { - if (!hasFiles(e)) return; - e.preventDefault(); - dragDepth += 1; + if (hasFiles(e)) { + e.preventDefault(); + dragDepth += 1; + } }} ondragleave={() => (dragDepth = Math.max(0, dragDepth - 1))} ondragover={(e) => hasFiles(e) && e.preventDefault()} ondrop={onDrop} > - {#if hasSlots} -
- -
- {/if} - - {#if ds.prompt} - - {#if promptErr}{/if} - {:else if current} -

{t('desk.noPromptInput')}

- {/if} - -
- -
- - -
{t('studio.connLabel')}
- {#each endpoints as ep (ep.id)} - - {/each} - - - {t('studio.connManage')} - -
-
- {#each chips as c (c.key)} -
- !!errors[i.nodeId]?.trim())} - {onSet} - /> -
- {/each} - {#if ds.common.length + ds.advanced.length > 0} - +
+ {@render header?.()} + {#if current} +
+

2 · 准备这次创作

+ {#if hasSlots && !dock}
+ +
{/if} + {#if dock}
+ {#if hasSlots} + {#each ds.slots.slice(0, 4) as slot}{/each} + {#if ds.lists.length}{/if} + + {:else}描述你的画面{/if} + Ctrl + Enter 生成 +
{/if} +
+ {#if ds.prompt}
+ +
+ Enter 换行 · Ctrl + Enter 生成{promptVal.length} 字 +
+ {#if promptErr}{/if} +
{:else}

+ 这个工具不需要填写提示词,请准备它需要的素材。 +

{/if} + {#if dock && ds.negative}
+ +
+ 避免的内容{String(values[ds.negative.nodeId] ?? '').length} 字 +
+ {#if showErrors && errors[ds.negative.nodeId]}{/if} +
{/if} +
+
+ {#if !dock && commonInputs.length}
+

画面与生成设置

+ } + quiet + {errors} + {showErrors} + onChange={(v) => patch(commonInputs, v)} + /> +
{/if} + {#if !dock && changedCount > 0}{/if} + {#if !dock && advancedInputs.length}
+ 更多参数 · {advancedInputs.length} 项 + } + quiet + {errors} + {showErrors} + onChange={(v) => patch(advancedInputs, v)} + /> +
{/if} {/if} - -
- {#if block} - - {/if} - -
+ 运行设置 · {endpointName} + + 配置或检查连接 ↗ + {/if}
+
+ {#if dock}
+ {#each commonInputs + .filter((i) => i !== ds.height) + .slice(0, 3) as inp}{/each} +
{/if} + {#if block} + {:else}

素材已准备好,可以开始生成。

{/if} + +
+{#if dock} + +
+ +
+ {#snippet footer()}{/snippet} +
+{/if} + { + popoverInputs = []; + popoverAnchor = null; + }} + onApply={(v) => { + for (const [id, value] of Object.entries(v)) onSet(id, value); + }} +/> + diff --git a/calliope-web/src/lib/components/generate/ContextBar.svelte b/calliope-web/src/lib/components/generate/ContextBar.svelte index d3281f46..7d751a8d 100644 --- a/calliope-web/src/lib/components/generate/ContextBar.svelte +++ b/calliope-web/src/lib/components/generate/ContextBar.svelte @@ -5,8 +5,9 @@ /** * 上下文条 (spec-v2 §3.3): the desk was opened from a creation stage. - * Says where from, and plainly that takes stay in the desk feed — the - * desk's generate call has no shot/asset link to fill back. + * Says where from. With a full source identity (HEL-684) results can + * be flowed back per take from the result card; otherwise the old + * note stands — results stay in the desk feed, nothing is written back. */ interface Props { ctx: DeskContext; @@ -17,6 +18,7 @@ let { ctx, projectTitle, onDismiss }: Props = $props(); const stageName = $derived(t(`workbench.stage.${ctx.stage}`)); + const canFlowBack = $derived(!!ctx.sourceKind && !!ctx.sourceId);
@@ -24,7 +26,9 @@ {t('desk.ctxFrom', { project: projectTitle })}{#if ctx.label} · {ctx.label}{/if} - {t('desk.ctxNoBackfill', { stage: stageName })} + + {canFlowBack ? t('desk.ctxBackfill', { stage: stageName }) : t('desk.ctxNoBackfill', { stage: stageName })} + {t('desk.ctxBack', { stage: stageName })} - + +
]{t('desk.keyInspector')} -
@@ -160,35 +182,58 @@ {#if tab === 'params'} {@render params()} {:else if !job || !st} -
{t('desk.pickTake')}
+
+
+ ✳给想象留一个位置。在右侧写下描述,或选择一次已有创作。 +
+
{:else}
{#key mediaKey} -
+
{#if output && video} - +
+ {#if st.tone === 'ok' && !fileGone}{t('jobst.done')}{/if} + +
{:else if output} - {prompt { - clearOutputMissing(output); - noteImg(e); - }} - onerror={() => output && markOutputMissing(output)} - /> +
+ {#if st.tone === 'ok' && !fileGone}{t('jobst.done')}{/if} + {prompt { + clearOutputMissing(output); + noteImg(e); + }} + onerror={() => output && markOutputMissing(output)} + /> + {#if main && compare && compareSource}
+ 对比参考画面 +
+
{/if} +
{:else if fileGone}
{t('desk.missingTitle')} @@ -199,7 +244,9 @@ {st.label} {st.tone === 'fail' ? t('desk.notGenerated') : st.detail} {#if progress > 0} -
+
+ +
{/if}
{/if} @@ -207,6 +254,19 @@ {/key}
+ {#if output && video}
+ + 视频默认暂停,由你控制播放。 + +
{/if} {#if allOutputs.length > 1}
{#each allOutputs as p, i (p)} @@ -235,16 +295,42 @@ {s.label} {s.value} {/if} {/each} - {t('desk.elapsed')} {fmtDur(elapsedSec(job, nowMs))} + {t('desk.elapsed')} + {fmtDur(elapsedSec(job, nowMs))} {#if endpoint}{endpoint}{/if}
+ {#if main && compare && output && !video}
+ {inputs.some((i) => i.kind === 'image') ? '参考图片' : '上一版'}当前结果 +
{/if}
+ {#if main && output && !video}{#if compareSource && compareSource !== output}{/if}{/if} {#if fileGone && !outputs.length} - - + + {:else} - + {#if output && !video && canSendToSlot} {/if} {#if st.tone === 'fail'} - + {/if} + {#if job.status === 'pending' || job.status === 'running'}{/if} {#if job.status !== 'pending' && job.status !== 'running'} - + {/if} {/if}
@@ -280,44 +374,61 @@ {/if} - {#if inputs.length || prompt} -
{t('desk.inputs')}
- {#if inputs.length} -
- {#each inputs as inp (inp.label + inp.path)} - {#if inp.kind === 'image'} - {inp.label} - {:else} - - {/if} - {/each} -
+
+ 创作详情与参数 + {#if inputs.length || prompt} +
{t('desk.inputs')}
+ {#if inputs.length} +
+ {#each inputs as inp (inp.label + inp.path)} + {#if inp.kind === 'image'} + {inp.label} + {:else} + + {/if} + {/each} +
+ {/if} + {#if prompt}

{prompt}

{/if} {/if} - {#if prompt}

{prompt}

{/if} - {/if} -
{t('desk.workflow')}
-
-
{t('desk.kvName')}
-
- {wf?.name ?? t('studio.jobName', { id: job.id })} - {#if wfDeleted}{t('studio.wfDeletedTag')}{/if} -
- {#if wf?.usage} -
{t('desk.kvUsage')}
-
{usageLabel(wf.usage)}
- {/if} -
{t('desk.kvCreated')}
-
{fmtClock(parseDbTs(job.created_at))}
- {#if job.comfy_prompt_id} -
{t('desk.kvPromptId')}
-
{job.comfy_prompt_id}
- {/if} -
+
{t('desk.workflow')}
+
+
{t('desk.kvName')}
+
+ {wf?.name ?? t('studio.jobName', { id: job.id })} + {#if wfDeleted}{t('studio.wfDeletedTag')}{/if} +
+ {#if wf?.usage} +
{t('desk.kvUsage')}
+
{usageLabel(wf.usage)}
+ {/if} +
{t('desk.kvCreated')}
+
{fmtClock(parseDbTs(job.created_at))}
+ {#if job.comfy_prompt_id} +
{t('desk.kvPromptId')}
+
{job.comfy_prompt_id}
+ {/if} +
+
{/if}
+{#if lightbox && output && !video} (lightbox = false)} + />{/if} + diff --git a/calliope-web/src/lib/components/generate/ParameterPopover.svelte b/calliope-web/src/lib/components/generate/ParameterPopover.svelte new file mode 100644 index 00000000..80b1a99f --- /dev/null +++ b/calliope-web/src/lib/components/generate/ParameterPopover.svelte @@ -0,0 +1,155 @@ + + +{#if inputs.length && anchor} + +{/if} + + diff --git a/calliope-web/src/lib/components/generate/TakeCard.svelte b/calliope-web/src/lib/components/generate/TakeCard.svelte index 843704ce..c8df6218 100644 --- a/calliope-web/src/lib/components/generate/TakeCard.svelte +++ b/calliope-web/src/lib/components/generate/TakeCard.svelte @@ -8,7 +8,15 @@ import { clearOutputMissing, markOutputMissing, missingOutputsOf } from '$lib/missingOutputs.svelte'; import { t } from '$lib/i18n.svelte'; import { usageLabel } from './schema'; - import { elapsedSec, fmtClock, fmtDur, inputsOf, isVideoOutput, promptOf } from './takes'; + import { + elapsedSec, + fmtClock, + fmtDur, + inputsOf, + isVideoOutput, + promptOf, + workbenchCtxOf, + } from './takes'; /** * 一条记录 (spec-v2 §3.3 记录卡): workflow · usage · time, the prompt, the @@ -20,6 +28,9 @@ * take whose files no longer load turns amber (文件缺失) with * 用相同参数重做 / 移除记录, and takes on a deleted workflow are * marked as such instead of pretending nothing changed. + * HEL-684: a take generated with a real workbench source offers an + * explicit 回流到源项目 action; once flowed back it shows 已回流 and + * a direct 返回项目 link instead. */ interface Props { job: Job; @@ -33,11 +44,14 @@ flash?: boolean; /** One-shot failure shake. */ shake?: boolean; + /** Flow-back request in flight (HEL-684). */ + attachBusy?: boolean; onSelect: () => void; onReuse: () => void; onRetry: () => void; onCancel: () => void; onDelete: () => void; + onAttach?: () => void; } let { @@ -49,11 +63,13 @@ enter = false, flash = false, shake = false, + attachBusy = false, onSelect, onReuse, onRetry, onCancel, onDelete, + onAttach, }: Props = $props(); const st = $derived(jobStatusInfo(job)); @@ -80,6 +96,16 @@ }); const active = $derived(job.status === 'pending' || job.status === 'running'); const name = $derived(wf?.name ?? t('studio.jobName', { id: job.id })); + // HEL-684: flow-back only for finished takes with files and a real, + // still-recorded workbench source; the attached marker comes from the + // server so it survives reloads. + const wbCtx = $derived(workbenchCtxOf(job)); + const attached = $derived( + !!job.workbench_attach && !!wbCtx && job.workbench_attach.target_id === wbCtx.sourceId, + ); + const canAttach = $derived( + !!onAttach && !!wbCtx && !attached && st.tone === 'ok' && !fileGone && !!output, + ); let portrait = $state(false); let clipSec = $state(null); @@ -164,6 +190,25 @@ {:else} + {#if canAttach} + + {/if} + {#if attached && wbCtx} + + {t('desk.attachedTag')} + + + {t('desk.attachBack')} + + {/if} {#if st.tone === 'fail' && job.error !== 'cancelled'} @@ -183,7 +228,8 @@
{#if output} -
+
+ {#if st.tone === 'ok' && !fileGone}{t('jobst.done')}{/if} {#if isVideoOutput(job, output)}
{/each} diff --git a/calliope-web/src/lib/components/generate/WorkflowPicker.svelte b/calliope-web/src/lib/components/generate/WorkflowPicker.svelte deleted file mode 100644 index 20042973..00000000 --- a/calliope-web/src/lib/components/generate/WorkflowPicker.svelte +++ /dev/null @@ -1,277 +0,0 @@ - - -
- - (query = '')} - > - -
- -
- {#each groups as g (g.usage)} -
{usageLabel(g.usage)} · {g.items.length}
- {#each g.items as r (r.wf.id)} - {@const cur = r.wf.id === current?.id} - - {/each} - {:else} -

{t('desk.wfNoMatch')}

- {/each} -
-
- - - {t('desk.wfImport')} - - - ↑↓{t('desk.keySelect')} - Enter{t('desk.keyUse')} - Esc{t('desk.keyClose')} - -
-
-
-
- - diff --git a/calliope-web/src/lib/components/generate/context.ts b/calliope-web/src/lib/components/generate/context.ts index fcc6e528..b41c830b 100644 --- a/calliope-web/src/lib/components/generate/context.ts +++ b/calliope-web/src/lib/components/generate/context.ts @@ -3,8 +3,9 @@ import type { DeskKind } from './schema'; /** * 五段创作 → 生成台 handoff, carried in the URL so a reload keeps it. - * The desk only prefills from it; the playground generate API has no - * project/shot link, so results stay in the desk feed (no backfill). + * The desk prefills from it and, when the full source identity is present + * (sourceKind/sourceId), sends it along with the generate request so a + * finished take can be flowed back to its source row (HEL-684). */ export interface DeskContext { kind: DeskKind; @@ -15,10 +16,30 @@ export interface DeskContext { prompt?: string; negative?: string; durationSec?: number; + /** Real source row identity — only present on links the workbench + * stamped with it; without it no flow-back is offered (nothing guessed). */ + sourceKind?: 'asset' | 'shot'; + sourceId?: string; +} + +/** The generate-request context payload shape (HEL-684). */ +export interface DeskWorkbenchContext { + project_id: number; + stage: 'assets' | 'shot'; + source_kind: 'asset' | 'shot'; + source_id: string; + label?: string; } const STAGES: WorkbenchStageKey[] = ['script', 'style', 'storyboard', 'assets', 'shot']; +/** Stage ↔ desk kind pairing the workbench rows render (assets → image, + * shot → video). Anything else cannot display a flowed-back take. */ +const KIND_BY_STAGE: Partial> = { + assets: 'image', + shot: 'video', +}; + export function deskHref(ctx: DeskContext): string { const q = new URLSearchParams({ from: 'workbench', @@ -29,6 +50,10 @@ export function deskHref(ctx: DeskContext): string { if (ctx.prompt) q.set('prompt', ctx.prompt); if (ctx.negative) q.set('negative', ctx.negative); if (ctx.durationSec != null) q.set('duration', String(ctx.durationSec)); + if (ctx.sourceKind && ctx.sourceId) { + q.set('source_kind', ctx.sourceKind); + q.set('source_id', ctx.sourceId); + } return `/${ctx.kind}?${q.toString()}`; } @@ -39,6 +64,13 @@ export function readDeskContext(url: URL, kind: DeskKind): DeskContext | null { const stage = q.get('stage') as WorkbenchStageKey | null; if (!Number.isInteger(projectId) || projectId <= 0 || !stage || !STAGES.includes(stage)) return null; const duration = Number(q.get('duration')); + const rawKind = q.get('source_kind'); + const rawId = q.get('source_id') ?? ''; + // Source identity is only kept when it is complete and self-consistent; + // old/hand-made links keep today's prefill-only behavior. + const expectedKind = stage === 'assets' ? 'asset' : stage === 'shot' ? 'shot' : null; + const sourceKind = rawKind === 'asset' || rawKind === 'shot' ? rawKind : null; + const hasSource = sourceKind !== null && sourceKind === expectedKind && rawId.trim() !== ''; return { kind, projectId, @@ -47,9 +79,29 @@ export function readDeskContext(url: URL, kind: DeskKind): DeskContext | null { prompt: q.get('prompt') ?? undefined, negative: q.get('negative') ?? undefined, durationSec: Number.isFinite(duration) && duration > 0 ? duration : undefined, + sourceKind: hasSource ? (sourceKind as 'asset' | 'shot') : undefined, + sourceId: hasSource ? rawId : undefined, }; } +/** + * The context a generate request carries: only when the full, real source + * identity is present AND the desk kind matches what that stage renders. + */ +export function workbenchContextOf(ctx: DeskContext | null): DeskWorkbenchContext | undefined { + if (!ctx?.sourceId || !ctx.sourceKind) return undefined; + if (ctx.stage !== 'assets' && ctx.stage !== 'shot') return undefined; + if (KIND_BY_STAGE[ctx.stage] !== ctx.kind) return undefined; + const out: DeskWorkbenchContext = { + project_id: ctx.projectId, + stage: ctx.stage, + source_kind: ctx.sourceKind, + source_id: ctx.sourceId, + }; + if (ctx.label.trim()) out.label = ctx.label; + return out; +} + export function backHref(ctx: DeskContext): string { return `/workbench/${ctx.projectId}?stage=${ctx.stage}`; } diff --git a/calliope-web/src/lib/components/generate/takes.ts b/calliope-web/src/lib/components/generate/takes.ts index 57ca30ef..498ff951 100644 --- a/calliope-web/src/lib/components/generate/takes.ts +++ b/calliope-web/src/lib/components/generate/takes.ts @@ -9,6 +9,34 @@ import { classifySchema, inputRole, isFirstFrame, isLastFrame, isMedia } from '. export type FeedFilter = 'all' | 'image' | 'video' | 'failed'; +/** The workbench source a take was generated with, if any (HEL-684). */ +export interface TakeWorkbenchCtx { + projectId: number; + stage: string; + sourceKind: 'asset' | 'shot'; + sourceId: string; + label?: string; +} + +export function workbenchCtxOf(job: Job): TakeWorkbenchCtx | null { + const stamp = job.payload?.workbench; + if (!stamp || typeof stamp !== 'object') return null; + const s = stamp as Record; + const projectId = s.project_id; + const stage = typeof s.stage === 'string' ? s.stage : ''; + const sourceKind = s.source_kind === 'asset' || s.source_kind === 'shot' ? s.source_kind : null; + const sourceId = typeof s.source_id === 'string' ? s.source_id : ''; + if (typeof projectId !== 'number' || !stage || !sourceKind || !sourceId) return null; + const label = typeof s.label === 'string' && s.label.trim() ? s.label : undefined; + return { + projectId, + stage, + sourceKind, + sourceId, + label, + }; +} + export function jobValues(job: Job): Record { return (job.payload?.input_values ?? {}) as Record; } diff --git a/calliope-web/src/lib/components/home/AProjectCard.svelte b/calliope-web/src/lib/components/home/AProjectCard.svelte index e6120cf5..bbc9989a 100644 --- a/calliope-web/src/lib/components/home/AProjectCard.svelte +++ b/calliope-web/src/lib/components/home/AProjectCard.svelte @@ -35,7 +35,13 @@ ); // Five-stage creation progress (HEL-614) — real stage rows only. - const STAGE_SEGMENTS = ['script', 'style', 'storyboard', 'assets', 'shot'] as const; + const STAGE_SEGMENTS = [ + 'script', + 'style', + 'storyboard', + 'assets', + 'shot', + ] as const; function segClass(key: string): string { const state = stats.stage_status?.[key]; if (state === 'confirmed') return 'seg-confirmed'; @@ -46,13 +52,16 @@ // Spec §2.1 allows the five avatar gradients as cover placeholders. const PLACEHOLDER_GRADIENTS = [ - 'var(--avatar-1)', - 'var(--avatar-2)', - 'var(--avatar-3)', - 'var(--avatar-4)', - 'var(--avatar-5)', + '#1f262c', + '#253036', + '#2d2333', + '#26372c', + '#302836', ]; - const placeholder = $derived(PLACEHOLDER_GRADIENTS[project.id % PLACEHOLDER_GRADIENTS.length]); + const placeholderIdx = $derived(project.id % PLACEHOLDER_GRADIENTS.length); + const placeholder = $derived(PLACEHOLDER_GRADIENTS[placeholderIdx]); + // HEL-680 灰阶封面占位:1–2 亮阶配深图标,3–5 暗阶配浅图标 + const placeholderIconColor = $derived('var(--text-2)'); const coverUrl = $derived(assetUrl(project.cover_path)); @@ -64,17 +73,28 @@ if (stats.stage_confirmed >= STAGE_SEGMENTS.length) { return { cls: 'st-done', label: t('home.statusDone') }; } - const current = STAGE_SEGMENTS.find((k) => stats.stage_status?.[k] !== 'confirmed'); + const current = STAGE_SEGMENTS.find( + (k) => stats.stage_status?.[k] !== 'confirmed', + ); const state = current ? stats.stage_status?.[current] : undefined; const stageName = current ? t(`workbench.stage.${current}`) : ''; if (state === 'running') { - return { cls: 'st-progress', label: `${stageName} · ${t('workbench.state.running')}` }; + return { + cls: 'st-progress', + label: `${stageName} · ${t('workbench.state.running')}`, + }; } if (state === 'awaiting_confirm') { - return { cls: 'st-pending', label: `${stageName} · ${t('workbench.state.draft')}` }; + return { + cls: 'st-pending', + label: `${stageName} · ${t('workbench.state.draft')}`, + }; } if (stats.stage_confirmed > 0) { - return { cls: 'st-progress', label: `${stageName} · ${t('home.statusProgress')}` }; + return { + cls: 'st-progress', + label: `${stageName} · ${t('home.statusProgress')}`, + }; } return { cls: 'st-draft', label: t('home.statusDraft') }; }); @@ -132,7 +152,9 @@ toast.success(t('projectCard.renamedTo', { title: renameValue })); }, onError: (err) => { - toast.error(err instanceof Error ? err.message : t('projectCard.renameFailed')); + toast.error( + err instanceof Error ? err.message : t('projectCard.renameFailed'), + ); }, }); @@ -152,7 +174,9 @@ toast.success(t('projectCard.deleted', { title: project.title })); }, onError: (err) => { - toast.error(err instanceof Error ? err.message : t('projectCard.deleteFailed')); + toast.error( + err instanceof Error ? err.message : t('projectCard.deleteFailed'), + ); }, }); @@ -174,8 +198,15 @@ onerror={() => (coverFailed = true)} /> {:else} -
+
+ 海岸与薄雾构成的灵感画面 +
+ ✳ +
+ VISUAL STUDY / 001
LIGHT, SPACE & POSSIBILITY +
+
+ 建筑几何参考FOUND IN THE IN-BETWEEN +
+
Beyond
the ordinary.
+
+ + + diff --git a/calliope-web/src/lib/components/shell/AppShell.svelte b/calliope-web/src/lib/components/shell/AppShell.svelte index 705e03de..024cbcdc 100644 --- a/calliope-web/src/lib/components/shell/AppShell.svelte +++ b/calliope-web/src/lib/components/shell/AppShell.svelte @@ -1,10 +1,6 @@ - - - - {title} · {t('shell.brand')} - - +{title} · AIGC工作台 - -{#snippet railLink(item: NavItem)} - - - {#if item.id === 'tasks' && activeJobs > 0} - - {:else if item.id === 'connections'} - - {/if} - - -{/snippet} - -
-
-
- - +
@@ -415,14 +517,16 @@
- - +
@@ -448,7 +559,8 @@ {/if}
-

{t('home.myProjects')}

+

最近的创作

+ 全部项目 → {#if allProjects.length > 0} {t('home.myProjectsHint')} {/if} @@ -483,7 +595,7 @@
{:else}
- {#each allProjects as project (project.id)} + {#each allProjects.slice(0, 3) as project (project.id)} {/each}
@@ -491,12 +603,12 @@
@@ -630,393 +1168,723 @@ {:else if legacyRedirect === 'failed'} {:else} - - {#snippet actions()} - - {t('agentsPage.statusChip', { - n: skills.length, - m: skills.filter((s) => s.is_enabled).length, - })} - - {/snippet} - -
-
- - +
+ +
+ +
+ {#if messages.length}{/if} +
+
0 || running} + > + {#if $agentsQuery.isLoading}

+ 正在载入智能体… +

{:else if $agentsQuery.isError}
- - - {#if editorMode !== 'idle' || drawerOpen} - -
(drawerOpen ? resetEditor() : undefined)} aria-hidden="true">
- {/if} - +
{/if} +
+ +
+ {draft.length} / 20000
- - - - - -
- {t('agentsPage.assignTo')} -
- {#each agents as agent (agent.key)} - - {/each} -
- {#if showSkillErrors && skillErrors.bindings} - {skillErrors.bindings} - {/if} -
- -
- +
{/each} +
{/if} +
+ - {#if editorMode === 'edit' && editingVersion} - {t('agentsPage.saveNext', { v: editingVersion })} - {:else} - {t('agentsPage.save')} - {/if} - - {#if editorMode === 'edit'} - - - {/if} +
+ Ctrl + Enter 发送 · Enter 换行{#if running}{:else}{/if} +
-
+ + {/if} - -
+ + + {#snippet footer()}
+ 选定画风会加入这次任务要求 +
{/snippet} +
+ {#each agentStyles as style, i}{/each} +
+ {#snippet footer()}
+ 由智能体按技能指导完成任务 +
{/snippet} + + {#each applicableSkills.filter((s) => (skillLabel(s.dir) + s.description) + .toLowerCase() + .includes(skillSearch.toLowerCase())) as skill}{/each}{#if !applicableSkills.length}

+ 这个智能体还没有启用技能。可从技能管理中绑定已有技能,或新增技能。 +

{/if}
+ {#snippet footer()}
+ 只修改当前智能体的模型绑定 +
{/snippet}{#each $settingsQuery.data?.llm_profiles ?? [] as model}{/each}管理模型与连接 ↗
+

+ 用于整理提示词和输入要求,实际图片/视频生成在创作台进行。 +

+ {#each runnableWorkflows as wf (wf.id)}{/each}管理工作流 ↗
+ {#each activeSessions as session (session.id)}{/each}{#if !activeSessions.length}

+ 这位智能体还没有对话记录。 +

{/if}
+ + +
+ 当前模型:{selectedModel?.name ?? '默认大模型'} +

+ 长期创作规则通过知识、规则或模板技能维护;绑定后会用于这位智能体的任务。 +

+
+
+
+ 技能库 +
+ {#each skills as skill (skill.dir)}{@render skillRow( + skill, + t('agentsPage.assigned', { n: skill.assigned_count }), + )}{/each} +
+ +
+ + {#snippet footer()}
+ +
{/snippet} +

+ {resultKey === 'script' + ? '保存为故事构思阶段的待确认草稿,不会直接确认或覆盖已确认版本。' + : '内容会保存到这个阶段的助手建议区;镜头、风格和素材等字段仍由你整理并确认。'} +

+ {#if resultError}{/if}
deleteSkillTarget && $deleteSkillMutation.mutate(deleteSkillTarget.dir)} + onconfirm={() => + deleteSkillTarget && $deleteSkillMutation.mutate(deleteSkillTarget.dir)} oncancel={() => (deleteSkillTarget = null)} /> {/if} @@ -1054,38 +1923,7 @@ color: var(--error); } - .page { - padding: 20px 24px 28px; - max-width: 1720px; - width: 100%; - box-sizing: border-box; - margin: 0 auto; - height: 100%; - display: flex; - flex-direction: column; - min-height: 0; - } - - - .cols { - display: flex; - gap: 18px; - flex: 1; - min-height: 0; - align-items: stretch; - } - /* ── 左栏 ─────────────────────────────────────────────── */ - .left { - width: 236px; - flex-shrink: 0; - display: flex; - flex-direction: column; - gap: 14px; - min-height: 0; - overflow-y: auto; - padding-right: 2px; - } .col-title { font-size: 14.5px; font-weight: 600; @@ -1120,10 +1958,6 @@ .agent-row:hover { background: var(--surface-2); } - .agent-row.selected { - background: var(--surface-3); - border-color: var(--border-strong); - } .avatar { width: 34px; height: 34px; @@ -1136,15 +1970,6 @@ color: var(--text); flex-shrink: 0; } - .avatar.dark { - color: var(--accent-ink); - } - .avatar.lg { - width: 42px; - height: 42px; - border-radius: 11px; - font-size: 17px; - } .agent-meta { display: flex; flex-direction: column; @@ -1152,18 +1977,6 @@ min-width: 0; flex: 1; } - .agent-name { - font-size: 13.5px; - font-weight: 600; - color: var(--text); - } - .agent-sub { - font-size: 11px; - color: var(--text-3); - white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; - } .lib-head { display: flex; @@ -1174,11 +1987,6 @@ .lib-head .a-btn { margin-left: auto; } - .skill-lib { - display: flex; - flex-direction: column; - gap: 4px; - } .lib-empty { font-size: 11.5px; color: var(--text-3); @@ -1249,77 +2057,6 @@ } /* ── 中栏 ─────────────────────────────────────────────── */ - .mid { - flex: 1; - min-width: 0; - display: flex; - flex-direction: column; - background: var(--surface); - border: 1px solid var(--border); - border-radius: 12px; - overflow: hidden; - min-height: 0; - } - .chat-head { - display: flex; - align-items: center; - gap: 12px; - padding: 12px 16px; - border-bottom: 1px solid var(--border); - flex-wrap: wrap; - } - .chat-head-meta { - display: flex; - flex-direction: column; - gap: 1px; - min-width: 0; - } - .chat-head-meta h2 { - margin: 0; - font-size: 15px; - font-weight: 700; - color: var(--text); - } - .chat-head-meta p { - margin: 0; - font-size: 11.5px; - color: var(--text-3); - } - .status-tag { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 3px 10px; - border-radius: 999px; - background: var(--surface-3); - font-size: 11px; - color: var(--text-2); - white-space: nowrap; - } - .status-tag.busy { - background: var(--run-soft); - color: var(--run); - } - .chat-head-actions { - display: flex; - align-items: center; - gap: 8px; - margin-left: auto; - flex-wrap: wrap; - } - .model-pick { - display: inline-flex; - align-items: center; - gap: 6px; - } - .model-label { - font-size: 11px; - color: var(--text-3); - white-space: nowrap; - } - .session-select { - max-width: 180px; - } .chat-body { flex: 1; @@ -1330,38 +2067,6 @@ padding: 10px 14px; } - .composer { - display: flex; - gap: 10px; - align-items: flex-end; - padding: 12px 14px; - border-top: 1px solid var(--border); - } - .composer textarea { - flex: 1; - resize: none; - background: var(--surface-2); - border: 1px solid var(--border-strong); - border-radius: 10px; - padding: 10px 12px; - color: var(--text); - font-family: inherit; - font-size: 13px; - line-height: 1.55; - min-height: 44px; - max-height: 180px; - } - .composer textarea:focus-visible { - outline: none; - border-color: var(--accent); - } - .composer textarea::placeholder { - color: var(--text-3); - } - .composer .send { - min-height: 38px; - } - /* ── 右栏 ─────────────────────────────────────────────── */ .right { width: 372px; @@ -1611,23 +2316,6 @@ .link-danger:hover { text-decoration: underline; } - - .dot { - width: 7px; - height: 7px; - border-radius: 999px; - display: inline-block; - flex-shrink: 0; - } - .dot.green { - background: var(--success); - } - .dot.amber { - background: var(--run); - } - .dot.amber.breathing { - animation: breathe 2s ease-in-out infinite; - } @keyframes breathe { 0%, 100% { @@ -1639,22 +2327,9 @@ box-shadow: 0 0 0 4px var(--accent-dim); } } - .chat-head-actions .a-select { - max-width: 220px; - padding: 5px 8px; - } - .manage-btn { - display: none; - } - .drawer-backdrop { - display: none; - } /* ── 窄屏(1024–1439px):右栏收为抽屉(spec §4.5)────── */ @media (max-width: 1439px) { - .manage-btn { - display: inline-flex; - } .right { position: fixed; top: 0; @@ -1670,21 +2345,1192 @@ .right.open { transform: translateX(0); } - .drawer-backdrop { - display: block; - position: fixed; - inset: 0; - background: var(--overlay); - z-index: 55; - } - .session-select { - max-width: 140px; - } } @media (max-width: 1179px) { - .model-pick .model-label { + } + .agent-list { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 14px; + margin-bottom: 25px; + } + .agent-row { + flex-direction: column; + align-items: flex-start; + padding: 22px 18px; + min-height: 153px; + border: 1px solid var(--line); + border-radius: 13px; + background: var(--surface); + gap: 16px; + } + .agent-row .avatar { + width: 43px; + height: 43px; + border-radius: 11px; + font-size: 23px; + color: var(--text); + } + .agent-meta { + gap: 7px; + } + .right { + width: 280px; + border-radius: 14px; + background: var(--surface); + border: 1px solid var(--line); + } + .lib-head { + flex-wrap: wrap; + } + @media (max-width: 1400px) { + .right { + position: absolute; + right: 0; + top: 0; + bottom: 0; + width: 350px; + box-shadow: var(--shadow-float); + z-index: 30; display: none; } + .right.open { + display: flex; + } + } + .reference-agents { + display: flex; + flex: 1; + height: 100%; + min-height: 0; + min-width: 0; + } + .agent-rail { + width: 263px; + min-height: 0; + flex-shrink: 0; + display: flex; + flex-direction: column; + border-right: 1px solid var(--line); + background: linear-gradient(#141419, #0f0f12); + } + .agent-rail > header { + height: 76px; + display: flex; + align-items: center; + gap: 12px; + padding: 14px 17px; + border-bottom: 1px solid var(--line); + background: radial-gradient(at 10% 50%, #7850ff24, transparent 70%); + flex-shrink: 0; + } + .agent-rail header strong { + font-size: 17px; + color: #b99aff; + display: block; + } + .agent-rail header small { + display: block; + color: #7f768d; + font-size: 10px; + margin-top: 2px; + } + .agent-finder { + padding: 18px 12px 8px; + } + .agent-finder input { + width: 100%; + border: 1px solid #f5b04266; + background: #f5b0420d; + border-radius: 8px; + font-size: 11px; + padding: 8px 11px; + color: var(--text); + } + .agent-list-meta { + color: #6f6a7d; + font-size: 10px; + padding: 0 17px; + margin: 5px 0 10px; + } + .agent-list { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0 11px 8px; + overflow: auto; + flex: 1; + min-height: 0; + scrollbar-width: thin; + } + .agent-entry { + position: relative; + border-radius: 11.25px; + border: 1px solid transparent; + transition: + background-color 180ms ease, + border-color 180ms ease; + flex-shrink: 0; + } + .agent-entry.selected { + background: #ffffff26; + } + .agent-row { + display: flex; + flex-direction: row; + width: 100%; + min-height: 75px; + padding: 13px 9px; + gap: 11px; + border: 0; + border-radius: 11px; + background: none; + text-align: left; + align-items: center; + color: var(--text); + position: relative; + cursor: pointer; + } + .agent-row .avatar { + width: 38px; + height: 38px; + flex-shrink: 0; + display: grid; + place-items: center; + background: color-mix(in srgb, var(--agent-color) 15%, transparent); + border: 1px solid color-mix(in srgb, var(--agent-color) 20%, transparent); + color: var(--agent-color); + font-size: 21px; + border-radius: 9px; + transition: transform 180ms var(--ease-out); + } + .agent-meta { + display: block; + min-width: 0; + flex: 1; + padding-right: 6px; + } + .agent-meta b { + font-size: 12.1875px; + line-height: 1.5; + font-weight: 600; + display: block; + } + .agent-meta small { + display: block; + font-size: 10.3125px; + line-height: 1.5; + color: #ffffff88; + margin-top: 4px; + } + .agent-meta .replying { + color: #f5b042; + font-size: 9px; + } + .agent-pin { + position: absolute; + right: 6px; + top: 7px; + z-index: 2; + border: 1px solid #ffffff22; + background: #111827; + border-radius: 50%; + font-size: 10px; + width: 20px; + height: 20px; + color: #78839a; + opacity: 0; + transition: + opacity 180ms ease, + color 180ms ease, + border-color 180ms ease; + cursor: pointer; + padding: 0; + } + .agent-pin.pinned, + .agent-entry:focus-within .agent-pin, + .agent-entry:hover .agent-pin { + opacity: 1; + } + .agent-pin.pinned { + color: #ffd17c; + border-color: #ffd17c77; + } + .agent-rail > footer { + padding: 15px 14px; + border-top: 1px solid var(--line); + flex-shrink: 0; + } + .agent-rail footer button { + border: 0; + background: none; + color: #b99aff; + font-size: 11px; + cursor: pointer; + padding: 4px 0; + } + .agent-rail footer small { + display: block; + color: #76717f; + font-size: 10px; + line-height: 1.8; + } + .empty-rail { + color: #7f718f; + font-size: 11px; + padding: 12px; + } + .agent-stage { + position: relative; + background: #0b0a10; + flex: 1; + min-width: 0; + min-height: 0; + overflow: auto; + scrollbar-width: thin; + isolation: isolate; + } + .agent-scene { + position: absolute; + right: 0; + top: 45px; + width: min(950px, 95%); + height: 590px; + pointer-events: none; + z-index: -1; + overflow: hidden; + } + .agent-scene img { + width: 100%; + height: 100%; + object-fit: cover; + opacity: 0.78; + mask-image: linear-gradient(to right, transparent, #000 42%); + transition: filter 250ms ease; + } + .agent-scene:after { + content: ''; + position: absolute; + inset: 0; + background: linear-gradient(to top, #0b0a10, transparent 43%); + } + .agent-toolbar { + position: sticky; + top: 0; + z-index: 4; + display: flex; + gap: 8px; + align-items: center; + padding: 14px 25px; + background: linear-gradient(#0b0a10ef, #0b0a10cc); + backdrop-filter: blur(12px); + flex-wrap: wrap; + } + .agent-toolbar .grow { + flex: 1; + } + .agent-content { + position: relative; + max-width: 960px; + margin: auto; + padding: 35px 30px 35px; + } + .agent-intro { + min-height: 185px; + padding: 0 0 28px; + } + .agent-kicker { + font-size: 10px; + letter-spacing: 2px; + color: #c7a670; + margin-bottom: 14px; + } + .agent-intro h1 { + font-size: 45.75px; + line-height: 1.22; + font-weight: 700; + letter-spacing: -1px; + margin: 0 0 17px; + color: #fffaf2ed; + max-width: 540px; + text-shadow: 0 5px 24px #0006; + white-space: pre-line; + } + .agent-intro p { + font-size: 12px; + line-height: 1.8; + color: #fffaf299; + max-width: 620px; + margin: 0; + } + .agent-composer { + background: rgba(19, 18, 25, 0.82); + backdrop-filter: blur(18px) saturate(1.4); + border: 1px solid #ffffff26; + border-radius: 17.85px; + padding: 20px 21px 15px; + box-shadow: + 0 12px 40px #0009, + 0 2px 10px #0006; + position: relative; + transition: + border-color 180ms ease, + box-shadow 250ms var(--ease-out); + } + .agent-composer:before { + content: ''; + position: absolute; + left: 20px; + right: 20px; + top: 5px; + height: 5px; + background: radial-gradient(circle, #ffffff20 2px, transparent 2.5px) 0 + 0/18px 5px; + pointer-events: none; + } + .agent-composer:focus-within { + border-color: #f5b04273; + box-shadow: + 0 12px 40px #0009, + 0 0 0 1px #f5b04259, + 0 8px 28px #f5b0422e; + } + .agent-composer textarea { + display: block; + width: 100%; + min-height: 96px; + max-height: 250px; + resize: vertical; + background: none; + border: 0; + outline: none; + font-size: 13.395px; + line-height: 24.111px; + color: #fffaf2ed; + padding: 8px 0; + } + .agent-composer textarea::placeholder { + color: #88838e; + } + .agent-input-info { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 0 10px; + gap: 12px; + } + .agent-input-info button { + color: #f5b042; + border: 0; + background: none; + font-size: 11px; + cursor: pointer; + padding: 0; + } + .agent-input-info small { + font-size: 9px; + color: #716b78; + } + .agent-controls { + display: flex; + gap: 7px; + align-items: center; + flex-wrap: wrap; + border-top: 1px solid #ffffff0a; + padding-top: 10px; + } + .agent-option, + .project-option { + border: 1px solid #ffffff17; + background: #19171f; + color: #ffffffb3; + border-radius: 8.925px; + padding: 7px 10px; + font-size: 11px; + display: inline-flex; + align-items: center; + gap: 6px; + line-height: 1.3; + max-width: 220px; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + transition: + background-color 180ms ease, + border-color 180ms ease, + color 180ms ease, + transform 160ms var(--ease-out); + } + .agent-option { + cursor: pointer; + } + .agent-option img { + width: 18px; + height: 18px; + border-radius: 50%; + object-fit: cover; + } + .project-option select { + color: inherit; + background: none; + border: 0; + outline: none; + font-size: 11px; + max-width: 160px; + } + .project-option select option { + background: #19171f; + } + .agent-submit-row { + width: 100%; + display: flex; + align-items: center; + gap: 8px; + margin-top: 1px; + flex-wrap: wrap; + } + .agent-submit-row > small { + margin-left: auto; + color: #6f6879; + font-size: 9px; + } + .agent-send { + margin-left: auto; + border: 1px solid #f5b042; + background: #f5b042; + color: #241a09; + border-radius: 999px; + font-size: 12px; + padding: 10px 17px; + font-weight: 600; + cursor: pointer; + transition: + transform 160ms var(--ease-out), + background-color 180ms ease, + box-shadow 180ms ease; + } + .agent-send:disabled { + opacity: 0.5; + cursor: default; + } + .agent-send:active, + .agent-option:active { + transform: scale(var(--press-scale)); + } + .agent-conversation { + border: 1px solid #ffffff12; + background: #13101aeb; + border-radius: 16px; + overflow: hidden; + margin-bottom: 16px; + } + .agent-conversation > header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 18px 20px; + border-bottom: 1px solid #ffffff0d; + background: linear-gradient(120deg, #b784ff0c, #f5b04208); + } + .agent-conversation > header span { + font-size: 10px; + color: #b784ff; + } + .agent-conversation h2 { + font-size: 18px; + color: #fffaf2ed; + margin: 5px 0; + } + .agent-conversation .session-status { + color: #f5b042; + } + .agent-conversation .chat-body { + height: min(45vh, 530px); + min-height: 240px; + display: flex; + padding: 10px; + } + .agent-conversation :global(.plan-panel) { + margin: 10px 14px; + } + .conversation { + padding-top: 18px; + } + .conversation .agent-composer textarea { + min-height: 70px; + } + .agent-attachments { + display: flex; + gap: 8px; + flex-wrap: wrap; + margin-bottom: 12px; + } + .agent-attachments > div { + display: flex; + align-items: center; + gap: 7px; + font-size: 10px; + background: #ffffff06; + border: 1px solid #ffffff12; + border-radius: 8px; + padding: 5px 8px; + } + .agent-attachments img { + width: 30px; + height: 30px; + object-fit: cover; + border-radius: 5px; + } + .agent-attachments span { + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .agent-attachments button { + border: 0; + background: none; + color: var(--text-3); + cursor: pointer; + } + .style-grid { + display: grid; + grid-template-columns: repeat(5, minmax(0, 1fr)); + gap: 20px 12px; + } + .style-card { + padding: 0; + background: none; + border: 0; + color: #ffffffa0; + font-size: 11px; + position: relative; + text-align: center; + cursor: pointer; + } + .style-card img { + display: block; + width: 100%; + height: 150px; + object-fit: cover; + border-radius: 10px; + border: 2px solid transparent; + transition: + border-color 180ms ease, + transform 180ms var(--ease-out), + box-shadow 180ms ease; + } + .style-card span { + display: block; + margin-top: 8px; + } + .style-card.selected img { + border-color: #f5b042; + box-shadow: 0 0 0 2px #f5b04226; + } + .style-card.selected { + color: #f5b042; + } + .style-card.selected:after { + content: '✓'; + position: absolute; + top: 6px; + right: 6px; + background: #f5b042; + color: #2d210d; + width: 20px; + height: 20px; + border-radius: 50%; + display: grid; + place-items: center; + } + .dialog-actions { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 10px; + } + .dialog-actions small { + margin-right: auto; + font-size: 10px; + color: #7f718f; + } + .dialog-actions .purple { + min-width: 140px; + } + .skill-search { + display: flex; + gap: 8px; + margin-bottom: 15px; + } + .skill-search input { + flex: 1; + min-width: 0; + } + .skill-choice, + .model-choice { + padding: 15px 16px; + margin: 10px 0; + border: 1px solid #ffffff0e; + border-radius: 11px; + background: #ffffff03; + color: #d8cbe8; + display: block; + width: 100%; + text-align: left; + cursor: pointer; + transition: + background-color 180ms ease, + border-color 180ms ease; + } + .skill-choice.selected { + border-color: #f5b04266; + background: #f5b04207; + } + .model-choice.selected { + border-color: #b784ff60; + background: #7850ff0f; + } + .skill-choice b, + .model-choice b { + font-size: 13px; + display: block; + font-weight: 600; + } + .skill-choice small, + .model-choice small { + display: block; + color: #8e839a; + font-size: 11px; + line-height: 1.8; + margin-top: 6px; + } + .model-config-link { + color: #b784ff; + font-size: 11px; + display: block; + margin-top: 18px; + text-decoration: none; + } + .empty-skills, + .agent-error { + color: #9d8ca9; + font-size: 12px; + line-height: 1.8; + } + .reference-skills-editor.right { + position: static !important; + width: 100%; + height: auto; + min-height: 0; + max-height: none; + display: flex !important; + transform: none !important; + border: 0; + background: none; + box-shadow: none; + overflow: visible; + border-radius: 0; + padding: 0; + margin-top: 15px; + } + .reference-skills-editor .right-head { + padding: 10px 0; + border-bottom: 1px solid var(--line); + } + .reference-skills-editor .editor { + padding: 16px 0; + overflow: visible; + } + .reference-skills-editor .editor-actions { + position: sticky; + bottom: -22px; + background: #131219; + padding: 14px 0; + border-top: 1px solid var(--line); + z-index: 1; + } + .all-skill-library { + display: flex; + flex-direction: column; + gap: 7px; + } + .agent-management-model { + padding: 14px; + border: 1px solid #ffffff10; + border-radius: 11px; + background: #ffffff04; + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; + font-size: 12px; + } + .agent-management-model p { + width: 100%; + color: #8f7d9e; + font-size: 11px; + margin: 0; + line-height: 1.8; + } + .agent-management-model button { + margin-left: auto; + } + @media (hover: hover) and (pointer: fine) { + .agent-entry:hover { + border-color: #ffffff12; + background-color: #ffffff0a; + } + .agent-entry.selected:hover { + background-color: #ffffff26; + } + .agent-entry:hover .avatar { + transform: scale(1.05); + } + .agent-option:hover { + border-color: #f5b04255; + background: #f5b0420d; + color: #ffe0a5; + } + .agent-send:hover:not(:disabled) { + background: #ffc96a; + box-shadow: 0 4px 18px #f5b04235; + transform: translateY(-1px); + } + .style-card:hover img { + transform: translateY(-2px); + box-shadow: 0 5px 20px #0006; + } + .skill-choice:hover, + .model-choice:hover { + border-color: #b784ff44; + background: #ffffff06; + } + } + @media (max-width: 1200px) { + .agent-rail { + width: 240px; + } + .agent-content { + padding: 25px 24px; + } + .agent-intro h1 { + font-size: 38px; + } + .style-grid { + grid-template-columns: repeat(4, minmax(0, 1fr)); + } + } + @media (max-height: 760px) { + .agent-intro { + min-height: 155px; + padding-bottom: 22px; + } + .agent-content { + padding-top: 22px; + } + .agent-intro h1 { + font-size: 38px; + } + .agent-composer textarea { + min-height: 84px; + } + .agent-toolbar { + padding-top: 10px; + padding-bottom: 10px; + } + } + :global(:root[data-reduce='1']) .agent-scene img, + :global(:root[data-reduce='1']) .style-card img { + transition: none; + } + :global(:root[data-reduce='1']) .style-card:hover img, + :global(:root[data-reduce='1']) .agent-entry:hover .avatar { + transform: none; + } + .agent-result-editor { + width: 100%; + min-height: 260px; + resize: vertical; + line-height: 1.9; + font-size: 13px; + } + .result-project-label { + display: flex; + align-items: center; + gap: 15px; + font-size: 12px; + margin-bottom: 15px; + } + .result-project-label select { + flex: 1; + } + .result-error { + color: var(--err); + font-size: 12px; + } + + .agent-intro { + animation: agent-arrive var(--d-enter) var(--ease-out) both; + } + .agent-content:not(.conversation) .agent-composer { + animation: agent-arrive var(--d-enter) var(--ease-out) both; + } + @keyframes agent-arrive { + from { + opacity: 0; + transform: translateY(18px); + } + to { + opacity: 1; + transform: translateY(0); + } + } + + .agent-rail { + width: 232px; + background: #121216; + } + .agent-rail > header { + height: auto; + padding: 21px 18px 16px; + background: none; + } + .agent-rail header strong { + color: var(--text); + font-size: 18px; + } + .agent-rail header small { + font-size: 11px; + color: var(--text-3); + } + .agent-entry { + margin: 2px 0; + } + .agent-entry.selected { + background: linear-gradient(120deg, #a98bff16, #a98bff03); + border-color: #a98bff39; + } + .agent-row { + min-height: 55px; + padding: 10px 8px; + } + .agent-row .avatar { + width: 32px; + height: 32px; + font-size: 14px; + } + .agent-stage { + position: relative; + display: grid; + grid-template-rows: 44px minmax(0, 1fr); + padding: 0 22px 14px; + min-height: 0; + overflow: hidden; + flex: 1; + } + .agent-toolbar { + padding: 0; + position: relative; + z-index: 1; + } + .agent-toolbar :global(.a-btn) { + min-height: 28px; + font-size: 11px; + padding: 4px 8px; + } + .agent-scene { + display: none; + } + .agent-content, + .agent-content.conversation { + display: grid; + grid-template-rows: minmax(0, 1fr) 173px; + padding: 0; + gap: 12px; + overflow: hidden; + height: 100%; + min-height: 0; + max-width: none; + position: relative; + } + .agent-intro { + grid-area: 1/1; + padding: 32px 28px 22px; + margin: 0; + min-height: 0; + isolation: isolate; + text-align: left; + overflow: auto; + border-radius: 14px; + } + .agent-intro::before { + content: ''; + position: absolute; + inset: 0 0 0 30%; + z-index: -2; + background: url('/reference-agent/story-hero.webp') right top/cover + no-repeat; + opacity: 0.7; + } + .agent-intro::after { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + background: + linear-gradient(90deg, #0f0f12 12%, #0f0f12dd 32%, #0f0f1230 80%), + linear-gradient(0deg, #0f0f12, transparent 40%); + } + .agent-intro h1 { + font-size: clamp(25px, 2.6vw, 40px); + line-height: 1.4; + letter-spacing: -1px; + max-width: 560px; + margin: 14px 0; + } + .agent-intro p { + color: #b4adb9; + font-size: 12px; + max-width: 390px; + line-height: 1.8; + } + + .agent-composer { + grid-area: 2/1; + height: 100%; + min-height: 0; + margin: 0; + padding: 10px 14px 6px; + max-width: none; + width: 100%; + box-sizing: border-box; + display: flex; + flex-direction: column; + border-color: #a98bff3d; + background: linear-gradient(120deg, #1b1823, #19171d); + } + .agent-composer textarea { + flex: 1; + min-height: 0; + height: auto; + max-height: none; + resize: none; + font-size: 13px; + padding: 2px; + overflow: auto; + } + .agent-input-info { + margin: 2px 0 4px; + padding: 0; + font-size: 10px; + flex-shrink: 0; + } + .agent-input-info button { + font-size: 10px; + } + .agent-controls { + display: flex; + flex-wrap: nowrap; + gap: 5px; + align-items: center; + border-top: 1px solid var(--line); + padding-top: 6px; + flex-shrink: 0; + margin-top: 0; + } + .agent-option, + .project-option { + font-size: 10px; + padding: 5px 7px; + min-height: 28px; + max-width: 140px; + white-space: nowrap; + } + .agent-option img { + width: 17px; + height: 17px; + } + .project-option select { + font-size: 10px; + max-width: 120px; + } + .agent-submit-row { + display: flex; + flex: 1; + gap: 5px; + justify-content: flex-end; + min-width: 0; + width: auto; + margin: 0; + padding: 0; + border: 0; + } + .agent-submit-row small { + display: none; + } + .agent-send { + min-height: 32px; + padding: 6px 16px; + font-size: 11px; + flex-shrink: 0; + } + .agent-attachments { + display: flex; + gap: 5px; + max-height: 30px; + overflow: auto; + flex-shrink: 0; + margin: 0 0 4px; + } + .agent-attachments img { + width: 22px; + height: 22px; + } + .agent-dialogue { + display: grid; + grid-template-columns: minmax(0, 1fr) 310px; + gap: 14px; + min-height: 0; + overflow: hidden; + } + .agent-conversation { + width: 100%; + max-width: none; + padding: 0; + margin: 0; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + } + .agent-conversation > header { + height: 52px; + flex-shrink: 0; + padding: 8px 12px; + } + .chat-body { + flex: 1; + min-height: 0; + overflow: auto; + } + .agent-artifact { + display: flex; + flex-direction: column; + min-height: 0; + border: 1px solid #a98bff25; + border-radius: 12px; + background: #18171e; + overflow: hidden; + } + .agent-artifact header { + display: flex; + justify-content: space-between; + gap: 8px; + padding: 12px 14px; + border-bottom: 1px solid var(--line); + font-size: 12px; + } + .agent-artifact header small, + .agent-artifact footer small, + .agent-artifact p { + color: var(--text-3); + font-size: 10px; + } + .agent-artifact textarea { + flex: 1; + min-height: 0; + border: 0; + background: none; + padding: 16px; + color: var(--text-2); + font-size: 12px; + line-height: 1.8; + resize: none; + outline: 0; + } + .agent-artifact textarea:focus { + background: #a98bff04; + } + .agent-artifact footer { + padding: 10px 12px; + border-top: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 8px; + } + .agent-artifact p { + padding: 20px; + } + @media (max-width: 1200px) { + .agent-rail { + width: 210px; + } + .agent-dialogue { + grid-template-columns: minmax(0, 1fr) 260px; + } + .agent-stage { + padding: 0 14px 12px; + } + .agent-controls { + flex-wrap: wrap; + } + .agent-option, + .project-option { + max-width: 135px; + } + } + @media (max-height: 740px) { + .agent-content, + .agent-content.conversation { + grid-template-rows: minmax(0, 1fr) 160px; + } + .agent-intro { + padding: 22px; + } + } + + .inspiration-options { + display: flex; + gap: 10px; + margin-top: 28px; + flex-wrap: wrap; + max-width: 600px; + } + .inspiration-options button { + background: #16141bc9; + border: 1px solid #ffffff15; + border-radius: 9px; + padding: 12px 14px; + color: var(--text-2); + font-size: 11px; + cursor: pointer; + } + + .agent-content, + .agent-content.conversation { + width: 100%; + max-width: none; + margin: 0; + align-items: stretch; + justify-items: stretch; + } + .agent-intro { + width: auto; + max-width: none; + box-sizing: border-box; + } + .agent-stage { + inset: auto; + position: relative; + } + .reference-agents { + height: 100%; + } + .agent-composer::before { + display: none; } diff --git a/calliope-web/src/routes/app.css b/calliope-web/src/routes/app.css index 15edea7f..b832d5d2 100644 --- a/calliope-web/src/routes/app.css +++ b/calliope-web/src/routes/app.css @@ -3,65 +3,59 @@ @tailwind utilities; :root { - /* ------------------------------------------------------------------ - * 融合视觉 design tokens — HEL-649 整站施工规范 §一(流水台结构 × - * 放映厅配色)。Single source of truth for the whole app: pages and - * components reference these variables only — no hardcoded colors, - * no ad-hoc overrides. Gold is for key actions and the current - * selection only; status colors each carry exactly one meaning. - * ------------------------------------------------------------------ */ - - /* 底色:蓝黑四阶,逐层浮起 (§1.1) */ - --bg: #07090e; - --bg-2: #0c0f16; - --bg-3: #121724; - --bg-4: #1a2133; - --line: #1b2233; - --line-2: #2a3450; - --page-glow: radial-gradient(1200px 500px at 70% -10%, rgba(38, 52, 92, 0.25), transparent 60%); - --float-bg: linear-gradient(180deg, #10152a, var(--bg-2)); - --overlay: rgba(4, 6, 10, 0.6); - --media-scrim: rgba(7, 9, 14, 0.65); + color-scheme: dark; + --accent-grad-hover: linear-gradient(135deg, #39dcee, #00b4c5); + --accent-ring: #00cae040; + --accent-wash: #00cae016; + --btn-glow-hover: 0 3px 0 #2235a01f; + --composer-bg: #131219d1; + --composer-focus: #131219e6; + --float-bg: #1b1c21; --on-media: #fff; - --on-media-line: rgba(255, 255, 255, 0.05); - --composer-bg: linear-gradient(180deg, #0e1220, var(--bg-2)); - --composer-focus: 0 0 0 1px rgba(242, 199, 132, 0.12), 0 8px 28px rgba(0, 0, 0, 0.4); - - /* 放映金:主按钮、当前选中、改过的参数、聚焦框、Toast 动作 (§1.2) */ - --accent: #f2c784; - --accent-ink: #23170a; - --accent-soft: rgba(242, 199, 132, 0.13); - --accent-hi: #f7d9a2; - --accent-lo: #ecaf63; - --accent-glow: rgba(236, 175, 99, 0.28); - --accent-line: rgba(242, 199, 132, 0.55); - --accent-grad: linear-gradient(180deg, var(--accent-hi), var(--accent-lo)); - --accent-grad-hover: linear-gradient(180deg, #fbe3b6, #f0b968); - --accent-ring: 0 0 0 1px rgba(242, 199, 132, 0.7), 0 0 22px var(--accent-glow); - --btn-glow: 0 2px 14px var(--accent-glow), inset 0 1px 0 rgba(255, 255, 255, 0.35); - --btn-glow-hover: 0 4px 18px var(--accent-glow), inset 0 1px 0 rgba(255, 255, 255, 0.4); - --accent-wash: linear-gradient(180deg, rgba(242, 199, 132, 0.05), transparent 40%); - --sel-shadow: 0 0 0 1px rgba(242, 199, 132, 0.15), 0 6px 24px rgba(0, 0, 0, 0.35); - - /* 信号色:绿=完成/已确认/通过,青=进行中/在线,红=失败/危险, - 琥珀=待确认/文件缺失/限额 (§1.3) */ - --ok: #49cb90; - --ok-soft: rgba(73, 203, 144, 0.13); - --run: #54dfd2; - --run-soft: rgba(84, 223, 210, 0.13); - --run-grad: linear-gradient(90deg, #3bbfb4, var(--run)); - --err: #f0645a; - --err-soft: rgba(240, 100, 90, 0.13); - --err-line: rgba(240, 100, 90, 0.6); - --warn: #f0b45c; - --warn-soft: rgba(240, 180, 92, 0.13); - - /* 文字与字体 (§1.4);--text-2 是深底可读性下限,不得再暗 */ - --text: #f4f6fa; - --text-2: #aab2c5; - --text-3: #6d7690; - --font: 'PingFang SC', 'Noto Sans SC', 'Microsoft YaHei', system-ui, sans-serif; - --mono: 'JetBrains Mono', ui-monospace, monospace; + --on-media-line: #ffffff66; + --sel-shadow: 0 0 0 1px #354fe0; + --bg: #0f0f12; + --bg-2: #141419; + --bg-3: #1b1c21; + --bg-4: #292b33; + --paper: #141419; + --lime: #203e39; + --rose: #402837; + --line: #ffffff14; + --line-2: #ffffff29; + --line-3: #ffffff40; + --text: #f5fbff; + --text-2: #b7bdc8; + --text-3: #8c99a0; + --accent: #00cae0; + --accent-hi: #79effa; + --accent-lo: #00a8b8; + --accent-ink: #071719; + --accent-soft: #00cae016; + --accent-line: #00cae059; + --accent-grad: linear-gradient(135deg, #00cae0, #00a8b8); + --accent-glow: transparent; + --btn-glow: 0 3px 0 #2235a01f; + --page-glow: linear-gradient(transparent, transparent); + --ok: #55d4ad; + --ok-soft: #10b98118; + --run: #a78bfa; + --run-soft: #7850ff18; + --run-grad: linear-gradient(90deg, #7850ff, #c4b5fd); + --err: #ff8c88; + --err-solid: #ef706b; + --err-soft: #ef706b18; + --err-line: #ef706b66; + --warn: #f5b042; + --warn-soft: #f5b04218; + --overlay: #000000bf; + --media-scrim: #101017ee; + --media-text: #fff; + --media-line: #ffffff66; + --stage-bg: #0f1117; + --font: + system-ui, -apple-system, 'PingFang SC', 'Microsoft YaHei', sans-serif; + --mono: ui-monospace, monospace; --fs-title: 15px; --fs-section: 14px; --fs-body: 13px; @@ -69,8 +63,6 @@ --fs-aux: 12px; --fs-mini: 11px; --lh-body: 1.55; - - /* 间距阶梯 4/6/8/10/12/16/20/28,不得出现阶梯外数值 (§1.5) */ --sp-1: 4px; --sp-2: 6px; --sp-3: 8px; @@ -79,69 +71,55 @@ --sp-6: 16px; --sp-7: 20px; --sp-8: 28px; - - /* 圆角与唯一一级阴影 (§1.5);卡片不投影,用底色差分层 */ --r-sm: 6px; --r-md: 10px; --r-lg: 14px; --r-pill: 999px; - --shadow-float: 0 14px 44px rgba(0, 0, 0, 0.6), 0 0 0 1px var(--line-2); - - /* 壳层尺寸 (§二):60px 图标轨、顶栏、≤760px 底部标签栏 */ - --rail-w: 60px; + --shadow-float: 0 20px 60px #0008, 0 0 0 1px var(--line); + --rail-w: 68px; --topbar-h: 52px; - --tabbar-h: 56px; - - /* 专属符号 (§1.7):齿孔只在记录流/输入台分隔带,光晕只在播放舞台 */ - --sprocket: radial-gradient(circle 2px, var(--line-2) 98%, transparent); - --stage-bg: - radial-gradient(60% 45% at 50% 38%, rgba(242, 199, 132, 0.07), transparent 70%), - radial-gradient(80% 70% at 50% 50%, #0d1220, #05070c); - - /* 动效 (§1.6,取 HEL-648 实测值);只动 transform / opacity */ + --tabbar-h: 0px; + --sprocket: none; + --frame-w: 0px; + --frame-arm: 12px; + --frame-inset: -4px; + --paper-w: 4px; --ease-out: cubic-bezier(0.23, 1, 0.32, 1); --ease-in-out: cubic-bezier(0.77, 0, 0.175, 1); --ease-drawer: cubic-bezier(0.32, 0.72, 0, 1); --ease-spring: cubic-bezier(0.34, 1.45, 0.44, 1); - --d-press: 120ms; - --d-state: 150ms; + --d-press: 160ms; + --d-state: 160ms; --d-pop: 180ms; --d-leave: 200ms; --d-enter: 220ms; - --d-drawer: 280ms; + --d-drawer: 250ms; --d-flash: 900ms; --d-progress: 400ms; --press-scale: 0.97; - - /* Avatar five-color set — five agents only; the one colorful gradient - family the spec keeps (§3.6). */ - --avatar-1: linear-gradient(135deg, #e8a33d, #b96a1b); - --avatar-2: linear-gradient(135deg, #5b8def, #3a5fa9); - --avatar-3: linear-gradient(135deg, #3fb97f, #2a7a54); - --avatar-4: linear-gradient(135deg, #b98be0, #7a4fa9); - --avatar-5: linear-gradient(135deg, #d98e6a, #a95535); - - /* ------------------------------------------------------------------ - * Legacy token names (§六 映射表) — aliases only, never new values, - * so every existing component renders in the fusion palette. - * ------------------------------------------------------------------ */ + --avatar-1: #e8c6b7; + --avatar-2: #e1eb9a; + --avatar-3: #c6d3e4; + --avatar-4: #d6d6c1; + --avatar-5: #d8c7e5; + --id-1: #875440; + --id-2: #5c6b23; + --id-3: #45698d; + --id-4: #626348; + --id-5: #73578c; --surface: var(--bg-2); --surface-2: var(--bg-3); --surface-3: var(--bg-4); --border: var(--line); --border-strong: var(--line-2); --border-hover: var(--line-2); - --accent-hover: var(--accent-hi); - --accent-contrast: var(--accent-ink); --accent-dim: var(--accent-soft); - --accent-focus: var(--accent-line); --success: var(--ok); --success-dim: var(--ok-soft); --info: var(--run); --info-dim: var(--run-soft); --error: var(--err); --error-dim: var(--err-soft); - --error-border: var(--err-line); --warning: var(--warn); --bg-primary: var(--bg); --bg-surface: var(--bg-2); @@ -149,7 +127,6 @@ --text-primary: var(--text); --text-secondary: var(--text-2); --text-muted: var(--text-3); - --font-ui: var(--font); --font-a-mono: var(--mono); --font-display: var(--font); --font-body: var(--font); @@ -157,13 +134,8 @@ --radius-sm: var(--r-sm); --radius-md: var(--r-md); --radius-lg: var(--r-lg); - --space-xs: var(--sp-1); --space-sm: var(--sp-3); --space-md: var(--sp-6); - --space-lg: var(--sp-7); - --space-xl: var(--sp-8); - - /* Omni Composer pill tokens */ --pill-bg: var(--bg-3); --pill-border: var(--line-2); --pill-radius: var(--r-pill); @@ -297,7 +269,7 @@ code, color: var(--err); } .a-btn.danger-solid { - background: var(--err); + background: var(--err-solid); color: var(--on-media); } @media (hover: hover) and (pointer: fine) { @@ -550,11 +522,43 @@ button.status-chip:active { .a-chip.changed { color: var(--accent); } -/* Selected filter chip (§3.5 筛选芯片组): 当前选中 = 金色文字 + accent-soft 底 */ +/* Selected filter chip (§3.5 筛选芯片组): 当前选中 = 取景框角线缩影 + + 相纸白文字 + accent-soft 底 (HEL-680) */ .a-chip.sel { + position: relative; background: var(--accent-soft); color: var(--accent); } +.a-chip.sel::after { + content: ''; + position: absolute; + inset: 2px; + pointer-events: none; + background-image: + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0); + background-position: + left top, + left top, + right top, + right top, + left bottom, + left bottom, + right bottom, + right bottom; + background-size: + 6px 1.5px, + 1.5px 6px, + 6px 1.5px, + 1.5px 6px, + 6px 1.5px, + 1.5px 6px, + 6px 1.5px, + 1.5px 6px; + background-repeat: no-repeat; +} .a-chip.warn { color: var(--warn); } @@ -753,6 +757,77 @@ button.a-tile:disabled { box-shadow: 0 0 0 1px var(--line); } +/* ------------------------------------------------------------------ + * 取景框角线选中 (HEL-680):内容级选中态的唯一语言——四角短线取景, + * 不整框描边。挂在需要角线的元素上(元素自身可 overflow 可见;被 + * overflow:hidden 裁切的容器改用 --frame-inset 正值画在内侧)。 + * ------------------------------------------------------------------ */ +.a-frame { + position: relative; +} +.a-frame::after { + content: ''; + position: absolute; + inset: var(--frame-inset, -4px); + z-index: 3; + pointer-events: none; + background-image: + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0), + linear-gradient(var(--accent) 0 0), linear-gradient(var(--accent) 0 0); + background-position: + left top, + left top, + right top, + right top, + left bottom, + left bottom, + right bottom, + right bottom; + background-size: + var(--frame-arm, 12px) var(--frame-w, 2px), + var(--frame-w, 2px) var(--frame-arm, 12px), + var(--frame-arm, 12px) var(--frame-w, 2px), + var(--frame-w, 2px) var(--frame-arm, 12px), + var(--frame-arm, 12px) var(--frame-w, 2px), + var(--frame-w, 2px) var(--frame-arm, 12px), + var(--frame-arm, 12px) var(--frame-w, 2px), + var(--frame-w, 2px) var(--frame-arm, 12px); + background-repeat: no-repeat; +} + +/* 相纸白边 (HEL-680):结果媒体外的相纸白框,底边略厚如手工相纸。 + 挂在承载 img/video 的媒体容器上;容器尺寸由调用方决定。 */ +.a-photo { + background: var(--accent); + border: var(--paper-w, 4px) solid var(--accent); + border-bottom-width: calc(var(--paper-w, 4px) + 2px); + border-radius: 2px; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35); + box-sizing: border-box; +} + +/* 「定影」完成章 (HEL-680):已定影结果右上角的完成印记,随 jobst.done + 文案走(中文=定影)。absolute 定位,挂在有媒体的结果容器内。 */ +.a-fix { + position: absolute; + top: var(--sp-3); + right: var(--sp-3); + z-index: 2; + padding: 1px 6px; + border: 1px solid currentColor; + border-radius: 3px; + background: var(--media-scrim); + color: var(--ok); + font-size: var(--fs-mini); + font-weight: 700; + letter-spacing: 0.1em; + text-indent: 0.1em; + transform: rotate(-4deg); + pointer-events: none; +} + /* Floating surface for pop / drawer / confirm / toast / lightbox (§四.3). */ .a-float { background: var(--float-bg); @@ -988,3 +1063,133 @@ button.a-tile:disabled { animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; } + +/* Refract shared behavior: desktop composition, paper surfaces, direct feedback. */ +[hidden] { + display: none !important; +} +button, +input, +textarea, +select { + font-family: inherit; +} +button { + transition: + transform var(--d-press) var(--ease-out), + background-color var(--d-state) ease, + color var(--d-state) ease; +} +button:active:not(:disabled) { + transform: scale(var(--press-scale)); +} +button:focus-visible, +a:focus-visible, +input:focus-visible, +textarea:focus-visible, +select:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} +.a-btn.primary { + border-color: transparent; + border-bottom-width: 0; + min-height: 40px; + padding: 0 18px; + border-radius: 8px; + font-weight: 550; +} +.a-btn.secondary { + background: var(--surface); + border-radius: 8px; +} +.a-stage { + background: var(--stage-bg); + border-radius: 14px; +} +.a-sprocket { + display: none; +} +.a-photo { + box-shadow: none; + background: var(--surface); +} +.a-fix { + background: var(--surface); + color: var(--ok); +} +.a-input, +.a-select, +.field-input, +.field-textarea { + background: var(--surface); + color: var(--text); +} +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation: none !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; + } +} +:root[data-reduce='1'] *, +:root[data-reduce='1'] *::before, +:root[data-reduce='1'] *::after { + animation: none !important; + transition-duration: 0.01ms !important; + scroll-behavior: auto !important; +} + +/* Shared reference interface: explicit hover states and press feedback. */ +.reference-option { + position: relative; + isolation: isolate; + overflow: hidden; +} +.reference-option::after { + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + pointer-events: none; + opacity: 0; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='33' height='19'%3E%3Cpath d='M5.5 0h11l5.5 9.5-5.5 9.5h-11L0 9.5ZM22 9.5h11' fill='none' stroke='%23fff' stroke-opacity='.35'/%3E%3C/svg%3E"); + mask-image: radial-gradient( + 70px circle at var(--pointer-x, -100px) var(--pointer-y, -100px), + #000, + transparent + ); + transition: opacity 180ms ease; +} +@media (hover: hover) and (pointer: fine) { + .reference-option:hover::after { + opacity: 1; + } +} +:root[data-reduce='1'] .reference-option::after { + display: none; +} +@media (prefers-reduced-motion: reduce) { + .reference-option::after { + display: none; + } +} +.a-btn.gold { + background: linear-gradient(135deg, #ffd700, #f7931a); + color: #211703; + border-color: #f5b042; + border-radius: 999px; + box-shadow: + 0 2px 12px #ffd70035, + inset 0 1px 0 #ffffff4d; +} +.a-btn.gold:hover { + background: linear-gradient(135deg, #ffe250, #ffac3c); +} +.a-btn.purple { + background: linear-gradient(135deg, #8b5cf6bf, #6366f1b3); + color: white; + border-color: #a78bfa40; +} diff --git a/calliope-web/src/routes/build-scene/+page.svelte b/calliope-web/src/routes/build-scene/+page.svelte index 0d7ccb26..567ceecf 100644 --- a/calliope-web/src/routes/build-scene/+page.svelte +++ b/calliope-web/src/routes/build-scene/+page.svelte @@ -2,10 +2,18 @@ import { onMount } from 'svelte'; import { toStore } from 'svelte/store'; import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; - import AppHeader from '$lib/components/AppHeader.svelte'; + import AppShell from '$lib/components/shell/AppShell.svelte'; import AgentChat from '$lib/components/agent/AgentChat.svelte'; import AgentComposer from '$lib/components/agent/AgentComposer.svelte'; - import { agentApi, playgroundApi, workflows, type AgentMessage, type AgentPlan, type AgentSession, type AgentTask } from '$lib/api'; + import { + agentApi, + playgroundApi, + workflows, + type AgentMessage, + type AgentPlan, + type AgentSession, + type AgentTask, + } from '$lib/api'; import type { AgentComposerPayload, SkillOption, WorkflowOption } from '$lib/agentComposer'; import { connectEvents } from '$lib/events'; import { toast } from '$lib/toast'; @@ -26,33 +34,33 @@ // Selection persists in localStorage; deleting a session removes its // composition first (the FK alone would orphan it). -const ACTIVE_SESSION_KEY = 'calliope.shot.activeSession'; -const RAIL_KEY = 'calliope.shot.railCollapsed'; -const CHAT_KEY = 'calliope.shot.chatCollapsed'; + const ACTIVE_SESSION_KEY = 'calliope.shot.activeSession'; + const RAIL_KEY = 'calliope.shot.railCollapsed'; + const CHAT_KEY = 'calliope.shot.chatCollapsed'; -let sessionId = $state(null); -let captures = $state([]); -let compositionReady = $state(false); -let switching = $state(false); -// SSR-safe: this component initializes during server render too, where -// localStorage does not exist (a bare access 500s a direct page load). -let railCollapsed = $state(false); -let chatCollapsed = $state(false); + let sessionId = $state(null); + let captures = $state([]); + let compositionReady = $state(false); + let switching = $state(false); + // SSR-safe: this component initializes during server render too, where + // localStorage does not exist (a bare access 500s a direct page load). + let railCollapsed = $state(false); + let chatCollapsed = $state(false); -$effect(() => { - railCollapsed = localStorage.getItem(RAIL_KEY) === '1'; - chatCollapsed = localStorage.getItem(CHAT_KEY) === '1'; -}); + $effect(() => { + railCollapsed = localStorage.getItem(RAIL_KEY) === '1'; + chatCollapsed = localStorage.getItem(CHAT_KEY) === '1'; + }); -function toggleRail() { - railCollapsed = !railCollapsed; - localStorage.setItem(RAIL_KEY, railCollapsed ? '1' : '0'); -} + function toggleRail() { + railCollapsed = !railCollapsed; + localStorage.setItem(RAIL_KEY, railCollapsed ? '1' : '0'); + } -function toggleChat() { - chatCollapsed = !chatCollapsed; - localStorage.setItem(CHAT_KEY, chatCollapsed ? '1' : '0'); -} + function toggleChat() { + chatCollapsed = !chatCollapsed; + localStorage.setItem(CHAT_KEY, chatCollapsed ? '1' : '0'); + } function isSceneSession(s: AgentSession): boolean { return s.project_id == null && s.origin === 'scene'; @@ -101,10 +109,7 @@ function toggleChat() { const sessions = await agentApi.listSceneSessions(); const stored = Number(localStorage.getItem(ACTIVE_SESSION_KEY) ?? ''); const sceneSessions = sessions.filter(isSceneSession); - const initial = - sceneSessions.find((s) => s.id === stored) ?? - sceneSessions[0] ?? - null; + const initial = sceneSessions.find((s) => s.id === stored) ?? sceneSessions[0] ?? null; if (initial) { await activateSession(initial.id, { persist: false }); } else { @@ -186,9 +191,11 @@ function toggleChat() { exportStatus = t('buildScene.videoExported'); try { if (!viewportRef) throw new Error(t('buildScene.legacyNeedsViewport')); - const { dataUrl } = await (viewportRef as unknown as { - exportVideoClip: () => Promise<{ dataUrl: string; ext: string }>; - }).exportVideoClip(); + const { dataUrl } = await ( + viewportRef as unknown as { + exportVideoClip: () => Promise<{ dataUrl: string; ext: string }>; + } + ).exportVideoClip(); const saved = await shotApi.uploadCapture(comp, dataUrl, 'viewport video export'); if (saved) { await refreshCaptures(); @@ -212,7 +219,12 @@ function toggleChat() { // is written once per transition, not per token. let thinkingAgent: string | null = null; let liveTools = $state< - { tool: string; args?: Record | null; result?: unknown; phase: 'running' | 'done' | 'error' }[] + { + tool: string; + args?: Record | null; + result?: unknown; + phase: 'running' | 'done' | 'error'; + }[] >([]); let livePlan = $state(null); let composerDraft = $state(''); @@ -231,7 +243,9 @@ function toggleChat() { queryFn: agentApi.listSceneSessions, }); const sessions = $derived($sessionsQuery.data ?? []); - const activeSession = $derived(sessionId != null ? (sessions.find((s) => s.id === sessionId) ?? null) : null); + const activeSession = $derived( + sessionId != null ? (sessions.find((s) => s.id === sessionId) ?? null) : null, + ); const running = $derived(Boolean(activeSession?.running || activeSession?.status === 'running')); const skillsQuery = createQuery({ @@ -259,10 +273,23 @@ function toggleChat() { ); const SHOT_SUGGESTIONS = [ - { labelKey: 'buildScene.suggestionTwoPerson', prompt: 'Add a male and a female character facing each other, then frame a medium two-shot from the left.' }, - { labelKey: 'buildScene.suggestionHeroPose', prompt: 'Add a character in a hero pose — arms wide — with a low-angle close-up.' }, - { labelKey: 'buildScene.suggestionBlockout', prompt: 'Blockout a simple room: floor plane, two walls, and put a character inside.' }, - { labelKey: 'buildScene.suggestionCapture', prompt: 'Frame this as a medium close-up and capture a reference image.' }, + { + labelKey: 'buildScene.suggestionTwoPerson', + prompt: + 'Add a male and a female character facing each other, then frame a medium two-shot from the left.', + }, + { + labelKey: 'buildScene.suggestionHeroPose', + prompt: 'Add a character in a hero pose — arms wide — with a low-angle close-up.', + }, + { + labelKey: 'buildScene.suggestionBlockout', + prompt: 'Blockout a simple room: floor plane, two walls, and put a character inside.', + }, + { + labelKey: 'buildScene.suggestionCapture', + prompt: 'Frame this as a medium close-up and capture a reference image.', + }, ]; const suggestionOptions = $derived( SHOT_SUGGESTIONS.map((s) => ({ label: t(s.labelKey), prompt: s.prompt })), @@ -282,7 +309,9 @@ function toggleChat() { } }, onSuccess: async () => { - await client.invalidateQueries({ queryKey: ['agent-session', sessionId] }); + await client.invalidateQueries({ + queryKey: ['agent-session', sessionId], + }); await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] }); }, onError: (err) => { @@ -300,7 +329,12 @@ function toggleChat() { function handleQuestionAnswer(option: string, _scope: string, questionSeq: number) { if (running || sessionId == null) return; - handleSend({ content: option, mentions: [], attachments: [], answer_to: questionSeq }); + handleSend({ + content: option, + mentions: [], + attachments: [], + answer_to: questionSeq, + }); } async function cancelRun() { @@ -308,7 +342,9 @@ function toggleChat() { try { await agentApi.cancel(sessionId); await client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] }); - await client.invalidateQueries({ queryKey: ['agent-session', sessionId] }); + await client.invalidateQueries({ + queryKey: ['agent-session', sessionId], + }); toast.info(t('buildScene.runCancelled')); } catch (err) { toast.error(err instanceof Error ? err.message : t('buildScene.cancelFailed')); @@ -326,11 +362,14 @@ function toggleChat() { function appendMessage(sid: number, msg: AgentMessage) { if (sid !== sessionId) return; - client.setQueryData(['agent-session', sid], (old) => { - if (!old || !Array.isArray(old.messages)) return old; - if (old.messages.some((m) => m.id === msg.id)) return old; - return { ...old, messages: [...old.messages, msg] }; - }); + client.setQueryData( + ['agent-session', sid], + (old) => { + if (!old || !Array.isArray(old.messages)) return old; + if (old.messages.some((m) => m.id === msg.id)) return old; + return { ...old, messages: [...old.messages, msg] }; + }, + ); } // ---- agent tool live view: pose tools mutate server-side; SSE updates -- @@ -372,7 +411,11 @@ function toggleChat() { // posts it (the router clears the request, which is the // request_capture tool's completion signal). if (shotStore.dragInProgress == false) { - (viewportRef as unknown as { pollCaptureRequest?: () => void } | null)?.pollCaptureRequest?.(); + ( + viewportRef as unknown as { + pollCaptureRequest?: () => void; + } | null + )?.pollCaptureRequest?.(); } break; case 'shot.capture.saved': @@ -388,12 +431,12 @@ function toggleChat() { if (msg) { appendMessage(msg.session_id, msg); if (msg.session_id === sessionId) { - if (msg.role === 'tool') liveTools = []; - if (msg.role === 'assistant' && !msg.agent_name) { - streaming = ''; - streamingReasoning = ''; - thinkingAgent = null; - } + if (msg.role === 'tool') liveTools = []; + if (msg.role === 'assistant' && !msg.agent_name) { + streaming = ''; + streamingReasoning = ''; + thinkingAgent = null; + } } } client.invalidateQueries({ queryKey: ['agent-sessions', 'scene'] }); @@ -429,20 +472,28 @@ function toggleChat() { phase: 'running', }); } else if (phase === 'finish') { - const idx = [...liveTools].reverse().findIndex((t) => t.tool === name && t.phase === 'running'); + const idx = [...liveTools] + .reverse() + .findIndex((t) => t.tool === name && t.phase === 'running'); if (idx >= 0) { const real = liveTools.length - 1 - idx; liveTools[real] = { ...liveTools[real], result: ev.data?.result, - phase: (ev.data?.result as { ok?: boolean } | undefined)?.ok === false ? 'error' : 'done', + phase: + (ev.data?.result as { ok?: boolean } | undefined)?.ok === false + ? 'error' + : 'done', }; } } // A shot tool finished server-side: refetch promptly so the // viewport follows even before shot.updated SSE lands. if (POSE_TOOLS.has(name) && phase === 'finish') { - shotStore.handleShotUpdated({ shot_id: shotStore.compositionId ?? undefined, reason: 'tool' }); + shotStore.handleShotUpdated({ + shot_id: shotStore.compositionId ?? undefined, + reason: 'tool', + }); } break; } @@ -475,95 +526,95 @@ function toggleChat() { }); -
- - -
- activateSession(id)} - onNew={handleNewScene} - onDelete={handleDeleteScene} - collapsed={railCollapsed} - onToggleCollapse={toggleRail} - /> - - -
- {#if compositionReady} -
- +
+
+ activateSession(id)} + onNew={handleNewScene} + onDelete={handleDeleteScene} + collapsed={railCollapsed} + onToggleCollapse={toggleRail} + /> +
+ - + + + +
- + diff --git a/calliope-web/src/routes/canvas/[id]/+page.ts b/calliope-web/src/routes/canvas/[id]/+page.ts index a8f63ebf..a3d15781 100644 --- a/calliope-web/src/routes/canvas/[id]/+page.ts +++ b/calliope-web/src/routes/canvas/[id]/+page.ts @@ -1,8 +1 @@ -import { redirect } from '@sveltejs/kit'; - export const ssr = false; -export const prerender = false; - -export function load() { - redirect(308, '/'); -} diff --git a/calliope-web/src/routes/connections/+page.svelte b/calliope-web/src/routes/connections/+page.svelte index d8338c97..c1ee8460 100644 --- a/calliope-web/src/routes/connections/+page.svelte +++ b/calliope-web/src/routes/connections/+page.svelte @@ -7,10 +7,8 @@ import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte'; import Icon from '$lib/components/ui/Icon.svelte'; import EmptyState from '$lib/components/ui/EmptyState.svelte'; - import WorkflowImportDrawer from '$lib/components/WorkflowImportDrawer.svelte'; - import WorkflowTestDialog from '$lib/components/WorkflowTestDialog.svelte'; - import { apiErrorMessage, comfy, settings, workflows, type ComfyEndpoint, type Workflow, type WorkflowOutputMapEntry, type WorkflowUsage, type WorkflowConnectionCheck } from '$lib/api'; - import { WORKFLOW_USAGES } from '$lib/comfy/types'; + import WorkflowLibrary from '$lib/components/workflows/WorkflowLibrary.svelte'; + import { apiErrorMessage, comfy, settings, workflows, type ComfyEndpoint, type WorkflowMeta } from '$lib/api'; import { toast } from '$lib/toast'; import { t } from '$lib/i18n.svelte'; import { classifyEndpoint, endpointTypeLabel, type EndpointKind } from '$lib/endpointKind'; @@ -25,12 +23,17 @@ queryKey: ['settings'], queryFn: settings.get, }); - const workflowsQuery = createQuery({ - queryKey: ['workflows'], - queryFn: workflows.list, + // HEL-682: the library browses metadata only (view=meta) — the heavy + // workflow_json payloads are fetched per-row inside WorkflowLibrary + // exactly when an action needs them. + const wfMetaQuery = createQuery({ + queryKey: ['workflows', 'meta'], + queryFn: workflows.listMeta, }); - const endpoints = $derived($settingsQuery.data?.comfyui_endpoints ?? []); + const endpoints = $derived( + $settingsQuery.data?.comfyui_endpoints ?? [], + ); const activeId = $derived( $settingsQuery.data?.comfyui_active_id ?? endpoints[0]?.id ?? '', ); @@ -281,7 +284,7 @@ } function workflowsBound(id: string): number { - return ($workflowsQuery.data ?? []).filter((wf) => wf.endpoint_id === id).length; + return ($wfMetaQuery.data ?? []).filter((wf) => wf.endpoint_id === id).length; } const deleteMessage = $derived.by(() => { @@ -327,188 +330,6 @@ }, }); - // ------------------------------------------------------------------ - // Workflow library (binding + per-row recheck / test). The import - // wizard itself lives in WorkflowImportDrawer (HEL-655 E 批). - // ------------------------------------------------------------------ - let wfImportOpen = $state(false); - - function startWfImport() { - wfImportOpen = true; - } - - function usageLabel(u: WorkflowUsage | null | undefined): string { - return u ? t(`usage.${u}`) : t('usage.pending'); - } - - function wfProblems(wf: Workflow): string[] { - return (wf.warnings ?? []).filter((w) => w.level === 'error').map((w) => w.message); - } - - // HEL-643 L2: per-row 重新检查 / 测试 in the workflow library. - let wfRecheckId = $state(null); - const wfRecheckResult = $state>({}); - - async function recheckRow(wf: Workflow) { - wfRecheckId = wf.id; - try { - const res = await workflows.check(wf.id, { refresh: true }); - wfRecheckResult[wf.id] = res; - } catch (err) { - toast.error(apiErrorMessage(err)); - } finally { - wfRecheckId = null; - } - } - - function recheckLine(wf: Workflow): { tone: 'ok' | 'bad' | 'warn'; text: string } | null { - const check = wfRecheckResult[wf.id]; - if (!check) return null; - if (!check.reachable) return { tone: 'warn', text: t('conn.wfCheckUnreachable') }; - if (check.ok) return { tone: 'ok', text: t('conn.wfCheckOk') }; - const n = check.findings.length; - return { tone: 'bad', text: t('conn.wfCheckProblems', { n }) }; - } - - let testWf = $state(null); - let testOpen = $state(false); - - function openTest(wf: Workflow) { - testWf = wf; - testOpen = true; - } - - function lastTestLine(wf: Workflow): string | null { - const lt = wf.last_test; - if (!lt) return null; - if (lt.status === 'done' && lt.output_count > 0) { - return t('conn.wfTestPassed', { n: lt.output_count, time: formatDbTime(lt.completed_at ?? lt.created_at) }); - } - if (lt.status === 'pending' || lt.status === 'running') { - return t('conn.wfTestRunning', { time: formatDbTime(lt.created_at) }); - } - return t('conn.wfTestFailed', { time: formatDbTime(lt.completed_at ?? lt.created_at) }); - } - - function formatDbTime(at: string | null): string { - if (!at) return '—'; - const ts = Date.parse(at.replace(' ', 'T') + 'Z'); - const d = new Date(Number.isFinite(ts) ? ts : at); - if (Number.isNaN(d.getTime())) return '—'; - const p = (n: number) => String(n).padStart(2, '0'); - return `${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`; - } - - const wfConfirmMutation = createMutation({ - mutationFn: ({ id, usage }: { id: number; usage: WorkflowUsage }) => - workflows.update(id, { usage, usage_source: 'user' }), - onSuccess: (wf) => { - client.invalidateQueries({ queryKey: ['workflows'] }); - toast.success(t('conn.wfConfirmed', { usage: usageLabel(wf.usage) })); - }, - onError: (err) => { - toast.error( - t('conn.wfImportFailed', { - detail: err instanceof Error ? err.message : String(err), - }), - ); - }, - }); - - // ------------------------------------------------------------------ - // HEL-638: per-row output-node designation for pending workflows with - // unknown custom output nodes (imported earlier or parked by migration). - // ------------------------------------------------------------------ - let wfMapEditId = $state(null); - let wfMapPicked = $state>({}); - let wfMapKind = $state>({}); - - function rowOutputCandidates(wf: Workflow) { - return (wf.output_schema ?? []).filter((o) => o.evidence === 'unknown_node'); - } - - function rowNeedsOutputMap(wf: Workflow): boolean { - return Boolean(wf.needs_mapping) && !(wf.output_map ?? []).length; - } - - function toggleWfMapEdit(wf: Workflow) { - if (wfMapEditId === wf.id) { - wfMapEditId = null; - return; - } - const picked: Record = {}; - const kinds: Record = {}; - const mapped = new Map((wf.output_map ?? []).map((e) => [e.nodeId, e.kind])); - for (const c of rowOutputCandidates(wf)) { - const known = mapped.get(c.nodeId); - if (known) picked[c.nodeId] = true; - kinds[c.nodeId] = known ?? c.suggested_kind ?? 'image'; - } - wfMapPicked = picked; - wfMapKind = kinds; - wfMapEditId = wf.id; - } - - const wfMapMutation = createMutation({ - mutationFn: ({ id, outputMap }: { id: number; outputMap: WorkflowOutputMapEntry[] }) => - workflows.update( - id, - outputMap.length - ? { output_map: outputMap, output_map_source: 'user' } - : { output_map: [] }, - ), - onSuccess: (wf) => { - client.invalidateQueries({ queryKey: ['workflows'] }); - wfMapEditId = null; - const nodes = (wf.output_map ?? []).map((e) => e.nodeId).join('、'); - toast.success( - wf.output_map?.length - ? t('conn.wfOutputApplied', { nodes }) - : t('conn.wfOutputCleared'), - ); - }, - onError: (err) => { - toast.error( - t('conn.wfImportFailed', { - detail: err instanceof Error ? err.message : String(err), - }), - ); - }, - }); - - function submitWfMap(wf: Workflow) { - if ($wfMapMutation.isPending) return; - const outputMap = rowOutputCandidates(wf) - .filter((c) => wfMapPicked[c.nodeId]) - .map((c) => ({ - nodeId: c.nodeId, - kind: wfMapKind[c.nodeId] ?? c.suggested_kind ?? 'image', - label: c.label, - ...(c.class_type ? { class_type: c.class_type } : {}), - })); - $wfMapMutation.mutate({ id: wf.id, outputMap }); - } - - const wfBindMutation = createMutation({ - mutationFn: ({ id, endpointId }: { id: number; endpointId: string | null }) => - workflows.update(id, { endpoint_id: endpointId }), - onSuccess: () => { - client.invalidateQueries({ queryKey: ['workflows'] }); - }, - }); - - const wfDeleteMutation = createMutation({ - mutationFn: (id: number) => workflows.delete(id), - onSuccess: () => { - client.invalidateQueries({ queryKey: ['workflows'] }); - toast.success(t('conn.wfDeleted')); - }, - onError: (err) => { - // e.g. 409 "该工作流还有 N 个排队或执行中的任务…" (HEL-619) - toast.error(apiErrorMessage(err)); - }, - }); - // ------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------ @@ -529,7 +350,9 @@ // 任务使用目标 (a6): where each kind of job actually runs — a workflow's // own binding first, otherwise the default connection. function kindTarget(kind: 'image' | 'video' | null): { value: string; kind: EndpointKind | null } { - const wfs = ($workflowsQuery.data ?? []).filter((w) => kind === null || w.kind === kind); + const wfs: WorkflowMeta[] = ($wfMetaQuery.data ?? []).filter( + (w) => kind === null || w.kind === kind, + ); const ids = new Set(wfs.map((w) => w.endpoint_id || activeId).filter(Boolean)); if (wfs.length === 0) ids.add(activeId); if (ids.size === 1) { @@ -710,208 +533,7 @@

- -
-
-

{t('conn.wfTitle')}

- {t('conn.wfHint')} - - - -
- - {#if ($workflowsQuery.data ?? []).length === 0} - -

{t('conn.missingMaterial')}

- {:else} - {@const wfs = $workflowsQuery.data ?? []} - {@const pending = wfs.filter((w) => !w.usage).length} -

- {t('conn.wfCount', { - n: wfs.length, - m: wfs.filter((w) => w.kind === 'image').length, - k: wfs.filter((w) => w.kind === 'video').length, - })} - {#if pending} - · {t('conn.wfPendingCount', { n: pending })} - {/if} -

-
- {#each wfs as wf (wf.id)} -
- - - - {wf.name} - {#if wf.usage} - - {usageLabel(wf.usage)} - - {:else} - - {/if} - {#if rowNeedsOutputMap(wf)} - - {/if} - {#if !wf.is_enabled && wf.usage && !rowNeedsOutputMap(wf)} - {t('conn.wfDisabledBadge')} - {/if} - {#if wfProblems(wf).length} - - {t('conn.wfBrokenBadge')} - - {/if} - {t('conn.wfParams', { n: wf.input_schema?.length ?? 0 })} - - - - -
- {@const lastLine = lastTestLine(wf)} - {@const recheck = recheckLine(wf)} - {#if lastLine || recheck} -
- {#if lastLine}{t('conn.wfLastTest')}:{lastLine}{/if} - {#if recheck} - - {#if recheck.tone === 'bad'} - {@const check = wfRecheckResult[wf.id]} - f.message).join('\n')}> - {recheck.text} - - {:else} - {recheck.text} - {/if} - - {/if} -
- {/if} - {#if wfMapEditId === wf.id} -
-

{t('conn.wfOutputHint')}

-
- {#each rowOutputCandidates(wf) as c (c.nodeId)} -
- - -
- {/each} -
-
- - -
-
- {/if} - {/each} -
- {/if} -
+ {#if formMode !== 'idle'} @@ -1104,17 +726,6 @@ {/if} - client.invalidateQueries({ queryKey: ['workflows'] })} - /> - client.invalidateQueries({ queryKey: ['workflows'] })} - /> diff --git a/calliope-web/src/routes/image/+page.svelte b/calliope-web/src/routes/image/+page.svelte index 3f7e4128..2aa33335 100644 --- a/calliope-web/src/routes/image/+page.svelte +++ b/calliope-web/src/routes/image/+page.svelte @@ -1,5 +1,6 @@ - +{#key page.url.pathname + page.url.search}{/key} diff --git a/calliope-web/src/routes/library/+page.svelte b/calliope-web/src/routes/library/+page.svelte index e3c79e8a..efff114f 100644 --- a/calliope-web/src/routes/library/+page.svelte +++ b/calliope-web/src/routes/library/+page.svelte @@ -35,9 +35,7 @@ let loadingMore = $state(false); let sentinel = $state(null); - const filtered = $derived( - filter === 'all' ? items : items.filter((i) => i.kind === filter), - ); + const filtered = $derived(filter === 'all' ? items : items.filter((i) => i.kind === filter)); const visible = $derived(filtered.slice(0, visibleCount)); const hasMore = $derived(filtered.length > visible.length); const remaining = $derived(filtered.length - visible.length); @@ -72,14 +70,16 @@ }); let selected = $state>(new Set()); - let preview = $state<{ src: string; kind: 'image' | 'video'; name: string } | null>(null); + let preview = $state<{ + src: string; + kind: 'image' | 'video'; + name: string; + } | null>(null); let attachItem = $state(null); let confirmingDelete = $state(false); const selectedCount = $derived(selected.size); - const allSelected = $derived( - filtered.length > 0 && filtered.every((i) => selected.has(i.path)), - ); + const allSelected = $derived(filtered.length > 0 && filtered.every((i) => selected.has(i.path))); function toggle(path: string) { const next = new Set(selected); @@ -143,6 +143,14 @@ {/snippet}
+
+
YOUR CREATIVE MATERIALS
+

创作的原材料。

+

让每一次探索,留下可继续创作的线索。

+
+
{item.name} @@ -341,7 +360,6 @@ transition: border-color var(--d-state) ease; } .card.selected { - border-color: var(--accent-line); background: linear-gradient(180deg, var(--accent-soft), transparent 32%), var(--bg-2); } .card :global(.media-el) { @@ -380,6 +398,14 @@ cursor: zoom-in; overflow: hidden; } + /* 相纸白边 (HEL-680):素材墙里的作品按相纸呈现 */ + .media.a-photo { + border: var(--paper-w, 4px) solid var(--accent); + border-bottom-width: calc(var(--paper-w, 4px) + 2px); + background: var(--accent); + border-radius: 0; + box-sizing: border-box; + } .media :global(img), .media :global(video) { width: 100%; @@ -437,4 +463,56 @@ gap: var(--sp-3); } } + + .library { + padding: 28px 36px 56px; + } + .refract-library-title { + margin-bottom: 25px; + } + .eyebrow { + font-size: 10px; + color: var(--text-3); + letter-spacing: 1.3px; + } + .refract-library-title h1 { + margin: 8px 0 7px; + font-size: 34px; + letter-spacing: -1.3px; + font-weight: 600; + } + .refract-library-title p { + font-size: 11px; + color: var(--text-3); + margin: 0; + } + .resource-tabs { + display: flex; + gap: 20px; + margin-bottom: 24px; + border-bottom: 1px solid var(--line); + } + .resource-tabs a { + padding: 9px 0 12px; + font-size: 12px; + color: var(--text-3); + border-bottom: 2px solid transparent; + text-decoration: none; + } + .resource-tabs a.active { + border-color: var(--accent); + color: var(--accent); + } +.library { + max-width: none; + padding: 24px 28px 30px; + } + h1 { + font-size: 26px; + } + .grid { + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 16px; + } + diff --git a/calliope-web/src/routes/models/+page.svelte b/calliope-web/src/routes/models/+page.svelte index edc2c2e4..5b990dcb 100644 --- a/calliope-web/src/routes/models/+page.svelte +++ b/calliope-web/src/routes/models/+page.svelte @@ -2,6 +2,7 @@ import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query'; import { untrack } from 'svelte'; import { fade } from 'svelte/transition'; + import Modal from '$lib/components/ui/Modal.svelte'; import AppShell from '$lib/components/shell/AppShell.svelte'; import Button from '$lib/components/ui/Button.svelte'; import ConfirmDialog from '$lib/components/ui/ConfirmDialog.svelte'; @@ -12,7 +13,6 @@ import { toast } from '$lib/toast'; import { t } from '$lib/i18n.svelte'; import { classifyEndpoint, endpointTypeLabel } from '$lib/endpointKind'; - import { isWideLayout } from '$lib/wideLayout'; const client = useQueryClient(); @@ -69,7 +69,7 @@ // Form state — add / edit custom LLM (spec §9.3) // ------------------------------------------------------------------ type FormMode = 'idle' | 'add' | 'edit'; - let formMode = $state(isWideLayout() ? 'add' : 'idle'); + let formMode = $state('idle'); let editingId = $state(null); let form = $state({ name: '', baseUrl: '', model: '', apiKey: '', timeout: 10 }); let formTest = $state<{ ok: boolean; ms?: number } | null>(null); @@ -80,7 +80,7 @@ const TIMEOUT_OPTIONS = [5, 10, 15, 30, 60]; function resetForm() { - formMode = isWideLayout() ? 'add' : 'idle'; + formMode = 'idle'; editingId = null; form = { name: '', baseUrl: '', model: '', apiKey: '', timeout: 10 }; formTest = null; @@ -392,14 +392,8 @@ char: string; dark?: boolean; }[] = [ - { - role: 'story', - labelKey: 'models.agentStory', - color: 'var(--avatar-1)', - char: '剧', - dark: true, - }, - { role: 'style', labelKey: 'models.agentStyle', color: 'var(--avatar-2)', char: '视' }, + { role: 'story', labelKey: 'models.agentStory', color: 'var(--avatar-1)', char: '剧', dark: true }, + { role: 'style', labelKey: 'models.agentStyle', color: 'var(--avatar-2)', char: '视', dark: true }, { role: 'script', labelKey: 'models.agentScript', color: 'var(--avatar-3)', char: '分' }, { role: 'assets', labelKey: 'models.agentAssets', color: 'var(--avatar-4)', char: '素' }, { role: 'video', labelKey: 'models.agentVideo', color: 'var(--avatar-5)', char: '镜' }, @@ -463,7 +457,11 @@ }); - + {#snippet actions()} {#if !$settingsQuery.isLoading && $settingsQuery.data} {@const profiles = $settingsQuery.data.llm_profiles} @@ -522,11 +520,16 @@ {@const using = agentsUsing(s, profile.id)}
- + {profile.name} - {endpointTypeLabel(kind)} + {endpointTypeLabel(kind)} {#if isActive} - {t('models.defaultBadge')} + {t('models.defaultBadge')} {/if} - {#if isActive} @@ -560,31 +567,47 @@ {/if}
-

{profile.base_url} · {profile.model}

+

+ {profile.base_url} · {profile.model} +

{#if pending} - {t('models.testing')} + {t('models.testing')} {:else if rec?.ok} - {t('models.statusConnected')} + {t('models.statusConnected')} - {t('models.latency', { ms: rec.ms ?? '?' })}{#if using > 0} + {t('models.latency', { + ms: rec.ms ?? '?', + })}{#if using > 0} · {t('models.agentsUsing', { n: using })}{/if} {:else if rec?.ok === false} - {t('models.statusFailed')} + {t('models.statusFailed')} - {t('models.lastTestAt', { time: formatTime(rec.at) })}{#if rec.fails >= 2} - · {t('models.consecutiveFails', { n: rec.fails })}{/if} + {t('models.lastTestAt', { + time: formatTime(rec.at), + })}{#if rec.fails >= 2} + · {t('models.consecutiveFails', { + n: rec.fails, + })}{/if} {#if rec.fails >= 3} {t('models.cloudPaused')} {/if} {:else} - {t('models.statusUntested')} + {t('models.statusUntested')} {/if}
{#if rec?.ok === false && rec.reason} @@ -612,7 +635,9 @@

- {t('models.noticeStrong')}{t('models.noticeBody')} + {t('models.noticeStrong')}{t( + 'models.noticeBody', + )}

@@ -624,18 +649,26 @@
{#each AGENTS as agent (agent.role)} - -
- {t('models.fApiType')} -
- - {t('models.apiOpenai')} - - - {t('models.apiAnthropic')} - - {t('models.apiOther')}
- {t('models.apiTypeHelp')} -
- - - - - + + + + + + + + {#if formTest?.ok} +
+ {t('models.testOk', { + ms: formTest.ms ?? '?', + model: form.model.trim(), + })} +
+ {:else if formTest?.ok === false && formTestFailure} +
+

+ {t('models.testFail', { reason: formTestFailure.text })} +

+ {#if formTestFailure.detail} +

{formTestFailure.detail}

+ {/if} +
{/if} - {t('models.keyHelp')} - - - - {#if formTest?.ok} -
- {t('models.testOk', { ms: formTest.ms ?? '?', model: form.model.trim() })} -
- {:else if formTest?.ok === false && formTestFailure} -
-

{t('models.testFail', { reason: formTestFailure.text })}

- {#if formTestFailure.detail} -

{formTestFailure.detail}

- {/if} +
+ {t('models.needTest')} + +
{/if} - -
- {t('models.needTest')} - - -
- {/if} - +
{/if}
@@ -1480,4 +1545,82 @@ margin-left: 0; } } + + .page { + max-width: none; + padding: 24px 28px 30px; + } + .layout { + display: block; + } + .main-col { + width: 100%; + max-width: none; + } + .cards { + gap: 0; + border: 1px solid var(--line); + border-radius: 12px; + overflow: hidden; + } + .card { + padding: 16px 20px; + border: 0; + border-bottom: 1px solid var(--line); + border-radius: 0; + background: #16161b; + } + .card:last-child { + border-bottom: 0; + } + .card-meta, + .card-status { + margin-left: 46px; + } + .form-col { + position: fixed; + top: 12px; + right: 12px; + bottom: 12px; + width: 400px; + max-width: calc(100vw - 24px); + border: 1px solid var(--line-2); + border-radius: 12px; + z-index: 800; + transform: translateX(calc(100% + 20px)); + visibility: hidden; + overflow: auto; + box-shadow: var(--shadow-float); + } + .form-col.open { + transform: none; + visibility: visible; + } + .drawer-backdrop { + display: block; + position: fixed; + inset: 0; + background: var(--overlay); + z-index: 799; + } + .agents-grid { + grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); + } + + .form-col, + .form-col.open { + position: static; + inset: auto; + transform: none; + visibility: visible; + box-shadow: none; + border: 0; + border-radius: 0; + width: 100%; + max-width: none; + padding: 0; + } + .form-head { + display: none; + } diff --git a/calliope-web/src/routes/playground/+page.ts b/calliope-web/src/routes/playground/+page.ts index a8f63ebf..a3d15781 100644 --- a/calliope-web/src/routes/playground/+page.ts +++ b/calliope-web/src/routes/playground/+page.ts @@ -1,8 +1 @@ -import { redirect } from '@sveltejs/kit'; - export const ssr = false; -export const prerender = false; - -export function load() { - redirect(308, '/'); -} diff --git a/calliope-web/src/routes/settings/+page.svelte b/calliope-web/src/routes/settings/+page.svelte index bd4cafe4..474fa595 100644 --- a/calliope-web/src/routes/settings/+page.svelte +++ b/calliope-web/src/routes/settings/+page.svelte @@ -729,4 +729,13 @@ grid-template-columns: minmax(0, 1fr); } } +.page { + max-width: 1280px; + padding: 24px 28px 30px; + } + .a-panel { + border-radius: 10px; + background: #16161b; + } + diff --git a/calliope-web/src/routes/tasks/+page.svelte b/calliope-web/src/routes/tasks/+page.svelte index b3365f8b..8e836691 100644 --- a/calliope-web/src/routes/tasks/+page.svelte +++ b/calliope-web/src/routes/tasks/+page.svelte @@ -36,7 +36,7 @@ queryFn: () => jobsApi.list(), refetchInterval: 5_000, }); - const workflowsQuery = createQuery({ queryKey: ['workflows'], queryFn: workflows.list }); + const workflowsQuery = createQuery({ queryKey: ['workflows'], queryFn: workflows.listMeta }); const projectsQuery = createQuery({ queryKey: ['projects'], queryFn: projects.list }); $effect(() => { diff --git a/calliope-web/src/routes/video/+page.svelte b/calliope-web/src/routes/video/+page.svelte index 47613a0f..98e6c3e1 100644 --- a/calliope-web/src/routes/video/+page.svelte +++ b/calliope-web/src/routes/video/+page.svelte @@ -1,5 +1,6 @@ - +{#key page.url.pathname + page.url.search}{/key} diff --git a/calliope-web/src/routes/workbench/+page.svelte b/calliope-web/src/routes/workbench/+page.svelte index 8b074f34..7a95da4a 100644 --- a/calliope-web/src/routes/workbench/+page.svelte +++ b/calliope-web/src/routes/workbench/+page.svelte @@ -1,218 +1,141 @@ - -
- {#if $projectsQuery.isLoading} -
- {#each Array(3) as _} - - {/each} + +
+
+
+
YOUR ONGOING STORIES
+

我的项目

+

把素材、模型和每一次尝试,放进自己的故事里。

+
+ + 新建项目 +
+
+ {items.length} 个项目 +
+ {#if $query.isLoading}{:else if $query.isError}
+

项目暂时没有加载出来。

+ +
{:else} +
+ {#each items as project (project.id)}{/each}+让下一个想法开始
- {:else if items.length === 0} - - {#snippet action()} - {t('workbench.pickerGoHome')} - {/snippet} - - {:else} -
    - {#each items as p (p.id)} -
  • - -
  • - {/each} -
-

{t('workbench.pickerFootHint')}

{/if}
diff --git a/calliope-web/src/routes/workbench/[id]/+page.svelte b/calliope-web/src/routes/workbench/[id]/+page.svelte index 5112631a..96fd610f 100644 --- a/calliope-web/src/routes/workbench/[id]/+page.svelte +++ b/calliope-web/src/routes/workbench/[id]/+page.svelte @@ -1,7 +1,11 @@ - + {#snippet actions()} - {t('workbench.progressChip', { n: confirmedCount })} + {t('workbench.progressChip', { n: confirmedCount })} {t('workbench.backHome')} {/snippet} {#if !$overviewQuery.data && $overviewQuery.isLoading}
-
+
{:else if !overview}

{t('workbench.loadFailed')} -

{:else} -
-
- - - {#if panelProps} -
-
-

{t(`workbench.stage.${stageKey}`)}

-

{currentAgent?.tagline ?? ''}

+
+
✳
+
+
项目工作台
+

{overview.project.title}

+

{overview.project.idea || '每一次尝试,都回到这个项目。'}

+
+ 灵感画布 ↗ +
+
+ +
+ {#if panelProps} +
+
+

{t(`workbench.stage.${stageKey}`)}

+

{currentAgent?.tagline ?? ''}

+
+
+ + {#if stageStatus === 'running'}{/if} + {t(STATUS_LABEL[stageStatus])} + + {#if currentStage && currentStage.draft_edited && stageStatus !== 'todo'} + {t('workbench.state.edited')} + {/if} +
-
- - {#if stageStatus === 'running'}{/if} - {t(STATUS_LABEL[stageStatus])} - - {#if currentStage && currentStage.draft_edited && stageStatus !== 'todo'} - {t('workbench.state.edited')} + + {#if currentStage?.error || (currentStage?.last_run?.status === 'failed' && currentStage?.last_run?.error)} +
+ + {currentStage.last_run?.error ?? currentStage.error} +
+ {/if} + + {#if stageStatus === 'awaiting_confirm'} +
+ + {t('workbench.draftNotice')} +
+ {/if} + + {#if stageStatus === 'running'} +
+ + {t('workbench.runningHint', { + agent: agentName(stageKey), + })} +
+ {/if} + +
+ + {#if stageStatus === 'todo'} + + {/if} + {#if stageStatus === 'awaiting_confirm'} + + {/if} + {#if stageStatus === 'confirmed' && currentStage?.draft_edited} + {/if}
-
- {#if currentStage?.error || (currentStage?.last_run?.status === 'failed' && currentStage?.last_run?.error)} -
- - {currentStage.last_run?.error ?? currentStage.error} +
+ {#if currentStage?.assistant_note || noteOpen}
+ 助手建议 · 待整理到阶段内容 + {#if noteOpen} +
+ +
+ {:else}

{currentStage?.assistant_note}

+ {/if} +
{/if} + {#if stageKey === 'script'} + + $saveMutation.mutate({ key: 'script', content })} + onImport={(text) => $importMutation.mutate(text)} + onRun={() => handleRun('script')} + /> + {:else if stageKey === 'style'} + + $saveMutation.mutate({ key: 'style', content })} + onRun={() => handleRun('style')} + /> + {:else if stageKey === 'storyboard'} + + $saveMutation.mutate({ key: 'storyboard', content })} + onRun={() => handleRun('storyboard')} + /> + {:else if stageKey === 'assets'} + + $saveMutation.mutate({ key: 'assets', content })} + onRun={() => handleRun('assets')} + {onGenerate} + onRetryJob={(jobId) => $retryMutation.mutate(jobId)} + /> + {:else} + + $saveMutation.mutate({ key: 'shot', content })} + onRun={() => handleRun('shot')} + {onGenerate} + onRetryJob={(jobId) => $retryMutation.mutate(jobId)} + /> + {/if}
{/if} +
- {#if stageStatus === 'awaiting_confirm'} -
- - {t('workbench.draftNotice')} -
- {/if} - - {#if stageStatus === 'running'} -
- - {t('workbench.runningHint', { agent: agentName(stageKey) })} -
- {/if} - -
- - {#if stageStatus === 'todo'} - - {/if} - {#if stageStatus === 'awaiting_confirm'} - - {/if} - {#if stageStatus === 'confirmed' && currentStage?.draft_edited} - - {/if} -
- -
- {#if stageKey === 'script'} - $saveMutation.mutate({ key: 'script', content })} - onImport={(text) => $importMutation.mutate(text)} - onRun={() => handleRun('script')} - /> - {:else if stageKey === 'style'} - $saveMutation.mutate({ key: 'style', content })} - onRun={() => handleRun('style')} - /> - {:else if stageKey === 'storyboard'} - $saveMutation.mutate({ key: 'storyboard', content })} - onRun={() => handleRun('storyboard')} - /> - {:else if stageKey === 'assets'} - $saveMutation.mutate({ key: 'assets', content })} - onRun={() => handleRun('assets')} - onGenerate={onGenerate} - onRetryJob={(jobId) => $retryMutation.mutate(jobId)} - /> - {:else} - $saveMutation.mutate({ key: 'shot', content })} - onRun={() => handleRun('shot')} - onGenerate={onGenerate} - onRetryJob={(jobId) => $retryMutation.mutate(jobId)} - /> - {/if} -
- {/if} -
- - -
+
+ +
{/if} @@ -740,6 +880,10 @@ color: var(--text); flex-shrink: 0; } + /* HEL-680 灰阶头像:1–2 亮阶用深字 */ + .agent-avatar.light { + color: var(--accent-ink); + } .agent-copy { display: flex; flex-direction: column; @@ -971,4 +1115,329 @@ align-items: stretch; } } + + .refract-project-heading { + display: flex; + align-items: center; + gap: 17px; + padding: 28px 36px 25px; + max-width: 1560px; + margin: auto; + } + .project-monogram { + width: 65px; + height: 65px; + border-radius: 12px; + background: var(--lime); + color: var(--accent); + display: grid; + place-items: center; + font-size: 37px; + flex-shrink: 0; + } + .refract-project-heading > div:nth-child(2) { + flex: 1; + min-width: 0; + } + .eyebrow { + font-size: 9px; + letter-spacing: 1px; + color: var(--text-3); + } + .refract-project-heading h1 { + font-size: 27px; + font-weight: 600; + letter-spacing: -0.6px; + margin: 4px 0; + } + .refract-project-heading p { + font-size: 11px; + color: var(--text-3); + margin: 0; + max-width: 630px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + .wb-page { + grid-template-columns: 160px minmax(0, 1fr) 250px; + padding: 0 36px 56px; + gap: 22px; + } + .stage-navigation { + padding: 13px 0; + position: sticky; + top: 15px; + } + .stage-navigation a { + display: block; + margin: 30px 10px; + color: var(--text-3); + font-size: 10px; + text-decoration: none; + } + .stage-head { + background: none; + border: 0; + border-radius: 0; + padding: 12px 0; + } + .stage-head h2 { + font-size: 20px; + letter-spacing: -0.4px; + } + .stage-tag { + font-size: 11px; + margin-top: 6px; + } + .side-col { + padding-top: 10px; + } + .side-card { + background: #eae9e2; + border: 0; + border-radius: 12px; + padding: 18px; + } + .agent-avatar { + color: var(--text); + } + .instruction-row { + flex-wrap: wrap; + } + .instruction-row .a-input { + min-width: 180px; + } + .flow-card { + display: none; + } + .jobs-card { + background: var(--surface); + border: 1px solid var(--line); + } + @media (max-width: 1250px) { + .wb-page { + grid-template-columns: 143px minmax(0, 1fr) 222px; + gap: 16px; + padding: 0 25px 45px; + } + .refract-project-heading { + padding: 25px; + } + } + + /* Approved five-stage workbench: horizontal progression, editing and context below. */ + .refract-project-heading { + padding: 25px 30px 18px; + max-width: 1500px; + gap: 15px; + } + .project-monogram { + width: 48px; + height: 48px; + background: #00cae012; + border: 1px solid #00cae033; + border-radius: 11px; + font-size: 27px; + } + .refract-project-heading h1 { + font-size: 25px; + } + .wb-page { + display: grid; + grid-template-columns: minmax(0, 1fr) 250px; + grid-template-rows: auto minmax(0, 1fr); + gap: 20px; + padding: 0 30px 35px; + max-width: 1500px; + margin: auto; + align-items: start; + } + .stage-navigation { + grid-column: 1/-1; + position: static; + padding: 0; + margin: 0; + } + .main-col { + min-width: 0; + grid-column: 1; + grid-row: 2; + } + .side-col { + grid-column: 2; + grid-row: 2; + display: flex; + flex-direction: column; + gap: 14px; + padding-top: 13px; + } + .side-card { + background: #141820; + border: 1px solid var(--line); + border-radius: 13px; + padding: 17px; + } + .stage-head { + padding: 10px 0 18px; + } + .stage-panel { + background: #141820; + border: 1px solid var(--line); + border-radius: 13px; + overflow: hidden; + } + .instruction-row { + padding: 13px; + border: 1px solid var(--line); + border-radius: 11px; + background: #141820; + margin-bottom: 16px; + } + .jobs-card { + background: #141820; + } + .agent-avatar { + background: #7850ff18 !important; + color: #c4b5fd !important; + border: 1px solid #7850ff33; + } + .flow-card { + display: block; + } + .refract-project-heading > div:nth-child(2) { + min-width: 0; + } + @media (max-width: 1200px) { + .wb-page { + grid-template-columns: minmax(0, 1fr) 225px; + padding: 0 22px 30px; + gap: 16px; + } + .refract-project-heading { + padding: 22px; + } + .side-col { + display: flex; + flex-direction: column; + } + .side-col > .side-card { + flex: none; + } + } + + .refract-project-heading { + max-width: none; + padding: 14px 22px; + height: 80px; + box-sizing: border-box; + flex-shrink: 0; + } + .project-monogram { + width: 38px; + height: 38px; + font-size: 22px; + } + .refract-project-heading h1 { + font-size: 20px; + } + .refract-project-heading p { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 600px; + font-size: 11px; + } + .wb-page { + flex: 1; + min-height: 0; + width: 100%; + max-width: none; + margin: 0; + box-sizing: border-box; + padding: 0 22px 18px; + grid-template-columns: minmax(0, 1fr) 232px; + grid-template-rows: 64px minmax(0, 1fr); + gap: 12px 18px; + overflow: hidden; + } + .main-col { + height: 100%; + min-height: 0; + display: flex; + flex-direction: column; + overflow: hidden; + } + .stage-head { + padding: 8px 0 12px; + flex-shrink: 0; + } + .stage-head h2 { + font-size: 18px; + } + .stage-tag { + font-size: 11px; + } + .stage-panel { + flex: 1; + min-height: 0; + overflow: auto; + background: #16161b; + } + .instruction-row { + order: 10; + flex-shrink: 0; + margin: 10px 0 0; + padding: 10px; + background: #18171d; + } + .side-col { + height: 100%; + min-height: 0; + overflow: auto; + padding: 0; + gap: 12px; + } + .side-card { + background: #16161b; + padding: 14px; + border-radius: 10px; + } + .stage-note { + padding: 14px; + border-bottom: 1px solid #a98bff25; + background: #a98bff05; + font-size: 12px; + } + .stage-note summary { + color: #c4b5fd; + cursor: pointer; + font-size: 11px; + } + .stage-note p { + white-space: pre-wrap; + line-height: 1.8; + overflow-wrap: anywhere; + } + .stage-note textarea { + min-height: 120px; + resize: vertical; + margin-top: 12px; + } + .note-actions { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 10px; + } + @media (max-width: 1100px) { + .wb-page { + grid-template-columns: minmax(0, 1fr) 210px; + padding: 0 14px 12px; + gap: 10px 12px; + } + .refract-project-heading { + padding: 12px 14px; + } + } diff --git a/calliope-web/src/routes/workflows/+page.svelte b/calliope-web/src/routes/workflows/+page.svelte new file mode 100644 index 00000000..1c7958fa --- /dev/null +++ b/calliope-web/src/routes/workflows/+page.svelte @@ -0,0 +1,152 @@ + + + +
+
+
+
YOUR CREATIVE MATERIALS
+

工作流目录

+

按用途挑选工具,未完成配置的工作流先到管理页核对。

+
+ +
+ + {#if $meta.isLoading}

正在打开工具目录…

{:else if $meta.isError}

+ 工具目录没有加载出来。 +

{:else if manage} + + {:else}
+ r.needs_mapping).length} + selectedId={null} + bind:activeId + endpoints={$config.data?.comfyui_endpoints ?? []} + onPick={pick} + onClose={() => {}} + /> +
{/if} +
+
+ + diff --git a/calliope-web/src/routes/workflows/+page.ts b/calliope-web/src/routes/workflows/+page.ts new file mode 100644 index 00000000..a3d15781 --- /dev/null +++ b/calliope-web/src/routes/workflows/+page.ts @@ -0,0 +1 @@ +export const ssr = false; diff --git a/calliope-web/static/reference-agent/3dmanghe.jpg b/calliope-web/static/reference-agent/3dmanghe.jpg new file mode 100644 index 00000000..6d54e22e Binary files /dev/null and b/calliope-web/static/reference-agent/3dmanghe.jpg differ diff --git a/calliope-web/static/reference-agent/chunzhengguofeng.jpg b/calliope-web/static/reference-agent/chunzhengguofeng.jpg new file mode 100644 index 00000000..ac767f0a Binary files /dev/null and b/calliope-web/static/reference-agent/chunzhengguofeng.jpg differ diff --git a/calliope-web/static/reference-agent/haizeiwangfengge.jpg b/calliope-web/static/reference-agent/haizeiwangfengge.jpg new file mode 100644 index 00000000..6fa946af Binary files /dev/null and b/calliope-web/static/reference-agent/haizeiwangfengge.jpg differ diff --git a/calliope-web/static/reference-agent/hanmanweimei.jpg b/calliope-web/static/reference-agent/hanmanweimei.jpg new file mode 100644 index 00000000..66be1b0d Binary files /dev/null and b/calliope-web/static/reference-agent/hanmanweimei.jpg differ diff --git a/calliope-web/static/reference-agent/jiranjiguang.jpg b/calliope-web/static/reference-agent/jiranjiguang.jpg new file mode 100644 index 00000000..5125a308 Binary files /dev/null and b/calliope-web/static/reference-agent/jiranjiguang.jpg differ diff --git a/calliope-web/static/reference-agent/meimanyinglang.jpg b/calliope-web/static/reference-agent/meimanyinglang.jpg new file mode 100644 index 00000000..59df7724 Binary files /dev/null and b/calliope-web/static/reference-agent/meimanyinglang.jpg differ diff --git a/calliope-web/static/reference-agent/quweiniantu.jpg b/calliope-web/static/reference-agent/quweiniantu.jpg new file mode 100644 index 00000000..9059dce5 Binary files /dev/null and b/calliope-web/static/reference-agent/quweiniantu.jpg differ diff --git a/calliope-web/static/reference-agent/rixidonghua.jpg b/calliope-web/static/reference-agent/rixidonghua.jpg new file mode 100644 index 00000000..5afc1af2 Binary files /dev/null and b/calliope-web/static/reference-agent/rixidonghua.jpg differ diff --git a/calliope-web/static/reference-agent/story-hero.webp b/calliope-web/static/reference-agent/story-hero.webp new file mode 100644 index 00000000..39b78e67 Binary files /dev/null and b/calliope-web/static/reference-agent/story-hero.webp differ diff --git a/calliope-web/static/reference-agent/xieshihuabao.jpg b/calliope-web/static/reference-agent/xieshihuabao.jpg new file mode 100644 index 00000000..a833b631 Binary files /dev/null and b/calliope-web/static/reference-agent/xieshihuabao.jpg differ diff --git a/calliope-web/static/reference-agent/zhiyuhuiben.jpg b/calliope-web/static/reference-agent/zhiyuhuiben.jpg new file mode 100644 index 00000000..38d6e2a8 Binary files /dev/null and b/calliope-web/static/reference-agent/zhiyuhuiben.jpg differ diff --git a/calliope-web/static/refract/arch.jpg b/calliope-web/static/refract/arch.jpg new file mode 100644 index 00000000..c8eb8383 Binary files /dev/null and b/calliope-web/static/refract/arch.jpg differ diff --git a/calliope-web/static/refract/coast.jpg b/calliope-web/static/refract/coast.jpg new file mode 100644 index 00000000..d8c3b497 Binary files /dev/null and b/calliope-web/static/refract/coast.jpg differ diff --git a/design/prototypes/reframe-20261014/README.md b/design/prototypes/reframe-20261014/README.md new file mode 100644 index 00000000..c33e4f51 --- /dev/null +++ b/design/prototypes/reframe-20261014/README.md @@ -0,0 +1,23 @@ +## 创作空间重设计 · 第五版交互样本 + +直接打开 `index.html`,或在这个目录启动普通静态文件服务。无需安装依赖,不调用后端或外部模型。 + +这版重点是区域分工与状态逻辑:大作品画布、固定输入底座、历史独立浏览、常用参数就近打开、角色任务与可编辑草稿、项目阶段与确认,以及管理页面的集中列表。 + +左侧可进入十个现有功能区域。右上角“情景选择”可以体验横图、竖图、首尾帧视频、空态、失败和智能体已有回复。演示保存会在本次浏览期间保留,重新载入后恢复样例。 + +### 范围 + +- 图片、回复和项目均为设计样例;没有执行真实生成或迁移用户数据。 +- 视频是公开海岸照片制作的五秒镜头运动样例,使用真正的视频元素;默认暂停,只有明确点击播放才开始。 +- 仓库目录包含 156 个 JSON 文件路径,按文件名分组用于检查大目录布局。它们尚未被样本解析、导入或验证可执行;创作台保留六个已配置场景入口。 +- 大模型、设置、素材和草稿等修改保存在样本内存;样本不测试 API、保存密钥或写入正式项目。 +- 非故事助手的自由文本作为阶段建议展示,结构化镜头与素材仍由对应表单整理。 +- 画布展示现有节点整理方式;演示连线为示意,不执行节点工作流。 +- 三维场景搭建与工作流试验台尚未在本轮样本展开,后续需要各自的操作走查,不能按已复刻处理。 + +### 来源 + +用户指定的参考站:`https://cn.lk666.ai/home`。设计使用登录后的目录、参数浮层、任务浮层和智能体输入的观察结果;没有提交收费生成。 + +风格参考图及智能体主视觉来自该站公开资源,原来源记录在项目 `src/lib/referenceAgent.ts`。海岸图片沿用项目现有公开视觉素材。本样本未包含账号截图、历史内容、密钥、Cookie 或浏览器配置。 diff --git a/design/prototypes/reframe-20261014/assets/3dmanghe.jpg b/design/prototypes/reframe-20261014/assets/3dmanghe.jpg new file mode 100644 index 00000000..6d54e22e Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/3dmanghe.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/chunzhengguofeng.jpg b/design/prototypes/reframe-20261014/assets/chunzhengguofeng.jpg new file mode 100644 index 00000000..ac767f0a Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/chunzhengguofeng.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/coast.jpg b/design/prototypes/reframe-20261014/assets/coast.jpg new file mode 100644 index 00000000..d8c3b497 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/coast.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/haizeiwangfengge.jpg b/design/prototypes/reframe-20261014/assets/haizeiwangfengge.jpg new file mode 100644 index 00000000..6fa946af Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/haizeiwangfengge.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/hanmanweimei.jpg b/design/prototypes/reframe-20261014/assets/hanmanweimei.jpg new file mode 100644 index 00000000..66be1b0d Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/hanmanweimei.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/jiranjiguang.jpg b/design/prototypes/reframe-20261014/assets/jiranjiguang.jpg new file mode 100644 index 00000000..5125a308 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/jiranjiguang.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/meimanyinglang.jpg b/design/prototypes/reframe-20261014/assets/meimanyinglang.jpg new file mode 100644 index 00000000..59df7724 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/meimanyinglang.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/preview.webm b/design/prototypes/reframe-20261014/assets/preview.webm new file mode 100644 index 00000000..a492936c Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/preview.webm differ diff --git a/design/prototypes/reframe-20261014/assets/quweiniantu.jpg b/design/prototypes/reframe-20261014/assets/quweiniantu.jpg new file mode 100644 index 00000000..9059dce5 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/quweiniantu.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/rixidonghua.jpg b/design/prototypes/reframe-20261014/assets/rixidonghua.jpg new file mode 100644 index 00000000..5afc1af2 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/rixidonghua.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/story-hero.webp b/design/prototypes/reframe-20261014/assets/story-hero.webp new file mode 100644 index 00000000..39b78e67 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/story-hero.webp differ diff --git a/design/prototypes/reframe-20261014/assets/xieshihuabao.jpg b/design/prototypes/reframe-20261014/assets/xieshihuabao.jpg new file mode 100644 index 00000000..a833b631 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/xieshihuabao.jpg differ diff --git a/design/prototypes/reframe-20261014/assets/zhiyuhuiben.jpg b/design/prototypes/reframe-20261014/assets/zhiyuhuiben.jpg new file mode 100644 index 00000000..38d6e2a8 Binary files /dev/null and b/design/prototypes/reframe-20261014/assets/zhiyuhuiben.jpg differ diff --git a/design/prototypes/reframe-20261014/catalog.js b/design/prototypes/reframe-20261014/catalog.js new file mode 100644 index 00000000..4a6bb5e1 --- /dev/null +++ b/design/prototypes/reframe-20261014/catalog.js @@ -0,0 +1 @@ +window.catalog=["0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/ControlNet_aux_常用样例.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/Minimax-H3提示词增强.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/birefnet_图像移除背景.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/sam3_图像视频-提示词遮罩分割.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/NLF_视频人物动作骨架获取.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/openpose-video-姿态检测.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/人物骨骼姿势提取/sdpose_视频人物姿势骨架提取.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/加载图片合成视频.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/加载本地latent解码.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/双图像或视频合并显示.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/图像4种添加水印节点.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/图像分割-多宫格分割.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/图像合并成四宫格.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/图像嵌入文字描述.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/多视频合成分屏展示.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/截取视频每一帧.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/手动按分镜视频截取.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/提示词生成与反推/Llama-cpp+Qwen3.5-提示词.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/提示词生成与反推/gemma4_提示词反推(图像视频音频).json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/深度图/moge3_深度图_几何图_线稿图.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/视频-音频分离.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/视频倒放.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/视频转gif动图图片.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/音频人声分离.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/音频转MP3格式.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/RTX_image_upscale.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/RTX_video_upscale.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/Seedvr2_3b_int8_图像放大.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/Seedvr2_3b_int8_视频放大.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/Seedvr2_视频放大FOR循环长视频.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/VOSR2_图像超分放大.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/VOSR2_视频放大_分批循环长视频.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/图像放大比较.json", "0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/高清放大/视频模型放大插帧(简单快速版).json", "1-语音生成/Qwen3-ASR-Subtitle语音转字幕.json", "1-语音生成/Qwen3-ASR-语音转文字.json", "1-语音生成/Qwen3-TTS_多角色对话.json", "1-语音生成/Qwen3-TTS_语音设计+语音克隆.json", "1-语音生成/index-TTS2-情绪控制-音频参考-文本控制-克隆-多人对话.json", "2-音乐生成/ace_step1_5_xl_turbo_8Step极速音乐生成.json", "2-音乐生成/ace_step_1.5+Qwen3.5_自动歌词音乐生成.json", "2-音乐生成/minimax_music_文生音乐.json", "3-图像生成/Anima/Anima_Klein放大_超强动漫模型.json", "3-图像生成/Flux/10_flux2_klein_文生图-角色三视图.json", "3-图像生成/Flux/1_flux2_klein_文生图.json", "3-图像生成/Flux/2_flux2_klein_图生图.json", "3-图像生成/Flux/3_flux2_klein_图生图一致性增强(大雄lora).json", "3-图像生成/Flux/3_flux2_klein_图生图一致性增强(小志lora).json", "3-图像生成/Flux/4_flux2_klein_图生图_局部重绘.json", "3-图像生成/Flux/5_flux2_klein_图生图_扩图.json", "3-图像生成/Flux/6_flux2-klein+Qwen3.5_转线稿洗图.json", "3-图像生成/Flux/7_flux2_klein_图生图-动漫转真人.json", "3-图像生成/Flux/8_flux2_klein_双图编辑.json", "3-图像生成/Flux/flux2_klein-图生图_人物动作迁移.json", "3-图像生成/Flux/flux2_klein_图生图_人物迁移.json", "3-图像生成/Flux/flux2_klein_图生图_印花提取.json", "3-图像生成/Flux/flux2_klein_图生图_老照片修复.json", "3-图像生成/Flux/flux2_klein_服装迁移.json", "3-图像生成/Qwen-Image-2.1/Qwen_Image2.1_图像编辑_VNCCS任意角度-任意姿势.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_一键16张姿势图.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_动漫转真人.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_提示词增强.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_深度-姿势-线稿-硬边缘-控图洗图.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_背景移除.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_角色BFS头部迁移.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_角色表四视图.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生_多图编辑_8步lora加速.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生_多图编辑_提示词增强(N版).json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生_多图编辑_透明背景.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生图_提示词增强.json", "3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生图_角色表四视图.json", "3-图像生成/Z-Image/10_Z_Image双采样+Fluax2-klein修复-高清直出.json", "3-图像生成/Z-Image/11_Z_Image_Turbo+模型放大_图像4K高清放大.json", "3-图像生成/Z-Image/12_Z_Image_Tubro_文生图_SeedVR2高清放大8K.json", "3-图像生成/Z-Image/1_Z-Image-Tubro_文生图.json", "3-图像生成/Z-Image/2_Z-Image+Base+Turbo+双重采样工作流.json", "3-图像生成/Z-Image/3_Z-Image_文生图(摇光梦幻).app.json", "3-图像生成/Z-Image/4_Z-Image+Qwen3.5-文生图.json", "3-图像生成/Z-Image/5_Z-Image+Qwen3.5提示词反推_文生图.json", "3-图像生成/Z-Image/6_Z-image_局部重绘.json", "3-图像生成/Z-Image/7_Z-image+Controlnet_图像扩展.json", "3-图像生成/Z-Image/8_Z-image+Controlnet_姿势控制-洗图.json", "3-图像生成/Z-Image/9_Z-Image+Flux2-Klein_风格重新编辑.json", "3-图像生成/Z-Image/Z_Image_turbo_十八种风格_插图漫画.json", "3-图像生成/Z-Image/Z_Image_turbo_十八种风格_照片摄影.json", "3-图像生成/Z-Image/Z_Image_turbo_十八种风格_通用a_.json", "3-图像生成/Z-Image/Z_Image_turbo_十八种风格_通用b.json", "3-图像生成/krea2/Krea2_turbo_文生图_4_6_8宫格故事板.json", "3-图像生成/krea2/Krea2_turbo_文生图_极致写实双采样2k版(N版).json", "3-图像生成/krea2/Krea2_turbo_文生图_角色三视图双采样2k版.json", "3-图像生成/krea2/krea2-Edit-Anything2Real_动漫转真人v3.json", "3-图像生成/krea2/krea2_identity_edit_图像编辑.json", "3-图像生成/krea2/krea2_turbo_文生图 (N版).json", "3-图像生成/krea2/krea2_turbo_文生图.json", "3-图像生成/krea2/krea2_turbo_文生图_2万提示词随机模板+4千种风格选择.json", "3-图像生成/krea2/krea2_turbo_文生图_Qwen3.5自动提示词生成.json", "3-图像生成/krea2/krea2_turbo_文生图_动漫风格2.5D半写实.json", "3-图像生成/krea2/krea2_turbo_文生图_动漫风格Image2风格.json", "3-图像生成/krea2/krea2_turbo_文生图_动漫风格线条动漫.json", "3-图像生成/krea2/krea2_turbo_文生图_图像风格参考.json", "3-图像生成/krea2/krea2_turbo_文生图_奇幻现实风格.json", "3-图像生成/krea2/krea2_turbo_文生图_极致写实(N版).json", "3-图像生成/krea2/krea2_turbo_文生图_细节增强.json", "3-图像生成/krea2/krea2_turbo_文生图_美学质量增强.json", "3-图像生成/krea2/krea2_turbo_文生图_赛博朋克现实风格.json", "3-图像生成/肖像大师_美女提示词生成.json", "4-视频生成/Minimax-h3/MiniMax_FastH3_i2v_图生视频8步极速.json", "4-视频生成/Minimax-h3/MiniMax_FastH3_t2v_文生图8步极速.json", "4-视频生成/Minimax-h3/MiniMax_H3_多参考_双采样潜空间放大.json", "4-视频生成/Minimax-h3/MiniMax_H3_孤海智能一体化(多合一简化版).json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台MiniMaxH3_多合一多分段拼接.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_双采样多段循环-PV动画尾帧衔接.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_双采样潜空间放大.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_文-图-参考-分段循环-双采放大_多合一.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_文_图_首尾_参考多合一(单采样).json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_短剧创作-多宫格分镜参考.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_短剧创作-音频参考.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_视频人物替换.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_视频参考+多参图-SelfLift双采样潜放大.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台_视频参考+多参图.json", "4-视频生成/Minimax-h3/MiniMax_H3_导演台时间线素材_双采样潜空间放大_多分段拼接.json", "4-视频生成/Minimax-h3/MiniMax_H3_音频MV_多参长视频分段_Selflift双采潜放大_Qwen3.8官方Skills自动提示词.json", "4-视频生成/Minimax-h3/MiniMax_H3_音频数字人_SelfLift双采样潜放大分块_Qwen3.8官方Skills自动提示词.json", "4-视频生成/Minimax-h3/Minimax_H3_T8双时钟采样_参考生视频-8步高质量极速版.json", "4-视频生成/Minimax-h3/Minimax_H3_T8双时钟采样_图生视频-8步高质量极速版.json", "4-视频生成/Minimax-h3/Minimax_H3_T8双时钟采样_文生音视频-8步高质量极速版.json", "4-视频生成/Minimax-h3/Minimax_H3_T8双采样_潜空间放大_参考生视频.json", "4-视频生成/Minimax-h3/Minimax_H3_r2v_参考生视频_双采样潜空间放大+Qwen3.8官方Skills自动提示词.json", "4-视频生成/Minimax-h3/Minimax_H3_视频动作参考_SelfLift双采样潜放大_Qwen3.8官方Skills自动提示词.json", "4-视频生成/Minimax-h3/Minimax_H3_音频数字人_单采样.json", "4-视频生成/Minimax-h3/minimax_h3_i2v_图生视频.json", "4-视频生成/Minimax-h3/minimax_h3_r2v_多参生视频.json", "4-视频生成/Minimax-h3/minimax_h3_t2v_文生视频.json", "4-视频生成/uncensored/minimax-h3多参生视频无审核版.json", "4-视频生成/uncensored/minimax-h3文生视频无审核版.json", "4-视频生成/uncensored/minimax-h3首尾帧生视频无审核版.json", "5-数字人/Wan2.1_I2V_InfiniteTalk_rCM_数字人对口型多动态(KJ版).json", "5-数字人/Wan2.1_I2V_InfiniteTalk_提示词调度动作控制图生视频数字人(KJ版).json", "5-数字人/Wan2.1_infinitetalk_音频驱动视频配音-单人for循环长视频(官流).json", "5-数字人/Wan2.1_infinitetalk_音频驱动视频配音-双人for循环长视频(官流).json", "6-动作迁移/Wan2.1_SCAIL2_角色迁移_动作迁移_FOR循环长视频.json", "6-动作迁移/Wan2.1_Scail-2_动作迁移_WanAnimatePlus_v4.2.json", "6-动作迁移/Wan2.1_Scail-2_角色迁移_WanAnimatePlus_v4.2.json", "6-动作迁移/Wan2.2_Animate_SAM3-人物迁移-动作迁移-长视频循环(KJ流).json", "6-动作迁移/Wan2.2_Animate_人物遮罩替换(官流整理).json", "6-动作迁移/Wan_Animate2_动作迁移_for循环长视频.json", "Krea2_t2i_20260818_API.json", "MiniMax-H3-Turbo-R2V-Extend-2Refs1Vid_API.json", "krea2_T2I_CharSheetV1_API.json", "minimax_h3-Turbo_Image2Video_20260813_API.json", "minimax_h3-Turbo_Text2Video_20260813_API.json", "video_minimax_h3_r2v_2ref_API.json", "video_minimax_h3_r2v_3ref_API.json", "video_minimax_h3_r2v_4ref_API.json", "video_minimax_h3_r2v_5ref_API.json", "video_minimax_h3_r2v_API.json"]; \ No newline at end of file diff --git a/design/prototypes/reframe-20261014/design.css b/design/prototypes/reframe-20261014/design.css new file mode 100644 index 00000000..8b39fb10 --- /dev/null +++ b/design/prototypes/reframe-20261014/design.css @@ -0,0 +1,1993 @@ +:root { + color-scheme: dark; + --bg: #0f0f12; + --panel: #141419; + --card: #1b1c21; + --hover: #24252b; + --line: #ffffff10; + --text: #f3f3f6; + --sub: #94949f; + --dim: #646571; + --cyan: #00cae0; + --gold: #f5b042; + --violet: #a98bff; + --ease: cubic-bezier(0.23, 1, 0.32, 1); + font-family: Inter, 'PingFang SC', 'Microsoft Yahei', system-ui, sans-serif; + font-size: 13px; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--text); + overflow: hidden; +} +button, +input, +textarea, +select { + font: inherit; +} +button, +a, +input, +textarea, +select { + -webkit-tap-highlight-color: transparent; +} +button { + border: 1px solid var(--line); + background: var(--card); + color: var(--text); + cursor: pointer; + border-radius: 8px; + padding: 8px 12px; + transition: + background-color 140ms ease, + border-color 140ms ease, + transform 120ms var(--ease), + box-shadow 160ms ease; +} +button:hover { + background: var(--hover); + border-color: #ffffff25; +} +button:active { + transform: scale(0.98); +} +button:focus-visible, +a:focus-visible { + outline: 2px solid var(--cyan); + outline-offset: 3px; +} +button:disabled { + opacity: 0.4; + cursor: default; + transform: none; +} +a { + color: inherit; + text-decoration: none; +} +input, +textarea, +select { + background: #ffffff04; + border: 1px solid var(--line); + border-radius: 8px; + color: var(--text); + padding: 9px 11px; + outline: none; +} +input:focus, +select:focus { + border-color: #00cae080; +} +textarea { + resize: none; + line-height: 1.6; +} +textarea:focus { + outline: none; +} +svg { + width: 19px; + height: 19px; + stroke: currentColor; + fill: none; + stroke-width: 1.6; + stroke-linecap: round; + stroke-linejoin: round; + flex-shrink: 0; +} +i { + display: inline-flex; + font-style: normal; +} +h1, +h2, +h3, +p { + margin: 0; +} +small, +.muted { + color: var(--sub); +} +small { + font-size: 11px; +} +.app { + display: grid; + grid-template-columns: 68px 232px minmax(0, 1fr); + grid-template-rows: 52px minmax(0, 1fr); + height: 100dvh; +} +.global { + grid-area: 1/1/3/2; + border-right: 1px solid var(--line); + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + background: #111115; + padding: 16px 7px 12px; + z-index: 4; +} +.brand { + font-size: 27px; + font-weight: 750; + letter-spacing: -2px; + height: 31px; + line-height: 31px; +} +.brand span { + font-size: 21px; + color: var(--cyan); +} +#navigation { + display: flex; + flex-direction: column; + gap: 6px; + width: 100%; + margin-top: 7px; +} +.global button { + border: 0; + background: none; + display: flex; + align-items: center; + flex-direction: column; + gap: 5px; + padding: 10px 2px; + font-size: 10px; + width: 100%; + color: var(--sub); + position: relative; +} +.global button:hover { + color: var(--text); + background: #ffffff05; +} +.global button.active { + color: var(--cyan); + background: #00cae010; +} +.global button.active:after { + content: ''; + height: 2px; + width: 15px; + background: var(--cyan); + border-radius: 2px; + position: absolute; + bottom: 3px; +} +.nav-bottom { + margin-top: auto; + width: 100%; + display: grid; + justify-items: center; + gap: 12px; +} +.avatar { + border-radius: 50%; + width: 28px; + height: 28px; + background: #353037; + display: grid; + place-items: center; + color: #cbc1d3; + font-size: 12px; +} +.topbar { + grid-area: 1/2/2/4; + display: flex; + align-items: center; + justify-content: space-between; + border-bottom: 1px solid var(--line); + padding: 0 20px; + background: #111115; + gap: 10px; +} +.breadcrumb { + display: flex; + gap: 14px; + align-items: center; + color: var(--sub); + font-size: 12px; +} +.breadcrumb b { + color: #41414b; +} +.breadcrumb strong { + font-weight: 500; + color: var(--text); +} +.top-actions { + display: flex; + gap: 9px; + align-items: center; +} +.demo-mark { + border: 1px solid #f5b04230; + color: #d7aa62; + border-radius: 4px; + padding: 3px 7px; + font-size: 10px; +} +.quiet { + background: none; + border: 0; + color: var(--sub); + padding: 6px; + font-size: 11px; +} +.icon-btn { + display: inline-flex; + justify-content: center; + align-items: center; + width: 32px; + height: 32px; + padding: 6px; + background: none; + flex-shrink: 0; +} +.status { + display: flex; + align-items: center; + gap: 7px; + border-radius: 20px; + color: var(--sub); + font-size: 11px; + padding: 6px 10px; +} +.dot { + width: 5px; + height: 5px; + border-radius: 50%; + background: #8c96a0; +} +.dot.busy { + background: var(--gold); +} +.context { + grid-area: 2/2/3/3; + border-right: 1px solid var(--line); + display: flex; + flex-direction: column; + min-height: 0; + background: #121216; +} +.context-head { + padding: 21px 18px 16px; + border-bottom: 1px solid var(--line); +} +.context-head h2 { + font-size: 18px; + letter-spacing: -0.3px; + margin-bottom: 6px; +} +.context-head p { + color: var(--sub); + font-size: 11px; + line-height: 1.6; +} +.context-controls { + padding: 14px 12px 7px; + display: grid; + gap: 10px; +} +.switch { + display: flex; + gap: 3px; + background: #09090c; + border: 1px solid var(--line); + border-radius: 9px; + padding: 3px; +} +.switch button { + flex: 1; + border: 0; + padding: 7px 3px; + background: none; + color: var(--sub); + font-size: 12px; + border-radius: 6px; +} +.switch button.selected { + color: #062f35; + background: var(--cyan); + font-weight: 600; + box-shadow: 0 2px 10px #00cae020; +} +.search { + position: relative; +} +.search input { + width: 100%; + font-size: 11px; + padding: 9px 10px 9px 30px; + background: #1d1b16; + border-color: #f5b04228; +} +.search i { + position: absolute; + left: 9px; + top: 9px; + color: #9d803d; +} +.search svg { + width: 13px; + height: 13px; +} +.category { + display: flex; + gap: 4px; + flex-wrap: wrap; +} +.category button { + font-size: 10px; + padding: 4px 6px; + background: none; + border-color: transparent; + color: var(--sub); +} +.category button.selected { + color: var(--cyan); + background: #00cae00a; + border-color: #00cae035; +} +.list-caption { + display: flex; + justify-content: space-between; + padding: 8px 16px; + color: var(--dim); + font-size: 10px; +} +.directory { + flex: 1; + min-height: 0; + overflow: auto; + padding: 0 8px 8px; + scrollbar-gutter: stable; +} +.option { + border: 1px solid transparent; + position: relative; + isolation: isolate; + display: flex; + align-items: center; + gap: 10px; + padding: 10px 8px; + border-radius: 10px; + width: 100%; + background: none; + text-align: left; + margin: 2px 0; + min-height: 55px; + overflow: hidden; +} +.option:before { + content: ''; + position: absolute; + z-index: -1; + inset: 0; + background: radial-gradient( + 160px circle at var(--mx, 50%) var(--my, 50%), + #00cae019, + transparent 80% + ); + opacity: 0; + transition: opacity 160ms ease; +} +.option:hover:before { + opacity: 1; +} +.option:hover { + background: #ffffff05; + border-color: #ffffff0c; +} +.option.active { + border-color: #00cae039; + background: linear-gradient(120deg, #00cae016, #00cae003); +} +.option.active:after { + content: ''; + width: 3px; + height: 22px; + position: absolute; + left: 0; + background: var(--cyan); + border-radius: 3px; +} +.option-icon { + display: grid; + place-items: center; + width: 32px; + height: 32px; + flex-shrink: 0; + border-radius: 9px; + border: 1px solid #00cae01f; + color: var(--cyan); + background: #00cae008; +} +.option-copy { + min-width: 0; + flex: 1; +} +.option-copy strong { + display: block; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + font-size: 12px; + font-weight: 550; + margin-bottom: 4px; +} +.option-copy small { + display: block; + font-size: 10px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.pin { + width: 22px; + height: 24px; + padding: 2px; + border: 0; + opacity: 0; + color: var(--sub); + background: none; + flex-shrink: 0; +} +.pin svg { + width: 13px; + height: 13px; +} +.option:hover .pin, +.pin.pinned, +.pin:focus-visible { + opacity: 1; +} +.pin.pinned { + color: var(--gold); +} +.context-footer { + border-top: 1px solid var(--line); + padding: 12px; + display: grid; + gap: 6px; +} +.context-footer button { + text-align: left; + font-size: 11px; + color: var(--sub); + display: flex; + justify-content: space-between; + background: none; + padding: 7px 8px; +} +.workspace { + grid-area: 2/3/3/4; + min-width: 0; + min-height: 0; + overflow: hidden; +} +.desk { + display: grid; + grid-template-rows: 44px minmax(0, 1fr) 190px; + height: 100%; + padding: 0 16px 14px; + gap: 0; +} +.desk-toolbar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; +} +.group { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; +} +.desk-toolbar h3 { + font-size: 12px; + font-weight: 550; +} +.subtle-label { + font-size: 10px; + color: var(--dim); +} +.text-btn { + border: 0; + background: none; + color: var(--sub); + padding: 6px 7px; + font-size: 11px; +} +.text-btn:hover { + background: #ffffff06; + color: var(--text); +} +.canvas { + position: relative; + min-height: 0; + overflow: hidden; + border: 1px solid #ffffff0b; + border-radius: 12px; + background: radial-gradient(ellipse at 50% 20%, #202028, #131316 70%); + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 12px; +} +.canvas-img { + display: block; + width: auto; + height: auto; + max-width: calc(100% - 44px); + max-height: calc(100% - 44px); + object-fit: contain; + border-radius: 3px; + box-shadow: 0 12px 60px #0007; + transition: opacity 180ms ease; +} +.canvas.compare { + gap: 18px; +} +.canvas.compare .canvas-img { + max-width: calc(50% - 30px); +} +.canvas-caption { + position: absolute; + bottom: 8px; + left: 13px; + right: 13px; + display: flex; + align-items: center; + justify-content: space-between; + font-size: 10px; + color: #8c8d96; + pointer-events: none; +} +.canvas-controls { + position: absolute; + top: 12px; + right: 12px; + display: flex; + gap: 5px; +} +.canvas-controls button { + padding: 6px; + background: #101015bb; + backdrop-filter: blur(8px); + border-color: #ffffff12; +} +.canvas-controls svg { + width: 16px; + height: 16px; +} +.zoom-label { + position: absolute; + top: 12px; + left: 13px; + padding: 5px 8px; + background: #101015bb; + border: 1px solid #ffffff12; + border-radius: 6px; + font-size: 10px; + color: #a8a9b2; +} +.main-action { + background: linear-gradient(140deg, #ffc65e, #f5b042); + border-color: #edb458; + color: #30210c; + font-weight: 650; + box-shadow: 0 3px 12px #f5b04217; +} +.main-action:hover { + background: #ffd174; + border-color: #ffcf73; + box-shadow: 0 3px 18px #f5b04228; +} +.cyan-action { + background: #00cae0; + color: #04282c; + border-color: #00cae0; + font-weight: 600; +} +.composer { + border: 1px solid #f5b04246; + border-radius: 16px; + background: linear-gradient(125deg, #1b1a1d, #17161a); + display: grid; + grid-template-rows: 28px 1fr 40px; + padding: 10px 14px 5px; + min-height: 0; + box-shadow: 0 0 0 1px #f5b04206 inset; + transition: + border-color 180ms ease, + box-shadow 180ms ease; +} +.composer:focus-within { + border-color: #f5b04280; + box-shadow: 0 0 0 3px #f5b04208; +} +.media-strip { + display: flex; + gap: 7px; + align-items: center; + min-width: 0; +} +.media-strip > small { + font-size: 10px; +} +.media-token { + display: flex; + align-items: center; + gap: 5px; + background: #ffffff04; + border: 1px dashed #ffffff25; + border-radius: 6px; + padding: 3px 7px; + font-size: 10px; + max-width: 140px; + height: 26px; +} +.media-token img { + height: 20px; + width: 20px; + object-fit: cover; + border-radius: 3px; +} +.media-token.filled { + border-style: solid; +} +.media-strip .grow { + flex: 1; +} +.prompt-pair { + display: grid; + grid-template-columns: 1fr; + min-height: 0; + gap: 18px; + padding-top: 5px; +} +.prompt-pair.dual { + grid-template-columns: minmax(0, 1fr) minmax(0, 0.65fr); +} +.prompt-pair label { + display: flex; + flex-direction: column; + min-height: 0; + font-size: 10px; + color: var(--sub); + gap: 4px; +} +.prompt-pair label:first-child { + color: #d0b37d; +} +.prompt-pair label + label { + border-left: 1px solid var(--line); + padding-left: 18px; +} +.prompt-pair textarea { + width: 100%; + height: 100%; + padding: 0; + background: none; + border: 0; + font-size: 12px; + color: #dedee4; +} +.composer-bottom { + display: flex; + justify-content: space-between; + align-items: center; + gap: 8px; + border-top: 1px solid var(--line); + margin-top: 6px; + min-width: 0; +} +.pills { + display: flex; + gap: 5px; + align-items: center; + min-width: 0; +} +.pill { + padding: 5px 8px; + background: #25242a; + border-color: #ffffff07; + color: #c4c2cb; + font-size: 10px; + white-space: nowrap; + display: flex; + align-items: center; + gap: 5px; +} +.pill svg { + height: 12px; + width: 12px; +} +.composer-bottom .main-action { + padding: 8px 18px; + border-radius: 20px; + font-size: 11px; + white-space: nowrap; +} +.shortcut { + font-size: 10px; + color: var(--dim); + margin-left: auto; + padding-right: 8px; + white-space: nowrap; +} +.state-card { + text-align: center; + max-width: 420px; + padding: 25px; + line-height: 1.7; +} +.state-card h2 { + font-size: 22px; + font-weight: 550; + margin: 8px 0 10px; +} +.state-card p { + font-size: 12px; + color: var(--sub); +} +.state-card i { + color: var(--cyan); +} +.state-card svg { + width: 40px; + height: 40px; +} +.state-actions { + display: flex; + gap: 8px; + justify-content: center; + margin-top: 18px; +} +.video-play { + position: absolute; + width: 60px; + height: 60px; + border-radius: 50%; + display: grid; + place-items: center; + background: #101016b0; + backdrop-filter: blur(10px); + border-color: #ffffff50; + box-shadow: 0 4px 30px #0008; +} +.video-play svg { + width: 26px; + height: 26px; + fill: currentColor; + stroke-width: 1; +} +.playbar { + position: absolute; + bottom: 35px; + left: 12%; + right: 12%; + height: 34px; + display: flex; + align-items: center; + gap: 12px; + background: #101016c9; + backdrop-filter: blur(10px); + border: 1px solid #ffffff13; + border-radius: 9px; + padding: 5px 10px; + color: #d6d5df; + font-size: 10px; +} +.playbar button { + border: 0; + padding: 2px; + background: none; + display: flex; +} +.playbar input { + flex: 1; + padding: 0; + accent-color: var(--cyan); + height: 3px; +} +.processing { + position: absolute; + top: 12px; + left: 50%; + transform: translateX(-50%); + display: flex; + align-items: center; + gap: 10px; + border: 1px solid #f5b04233; + background: #17151aed; + backdrop-filter: blur(12px); + padding: 8px 12px; + border-radius: 10px; + font-size: 11px; + z-index: 2; + box-shadow: 0 6px 30px #0005; +} +.spinner { + width: 13px; + height: 13px; + border: 2px solid #f5b04230; + border-top-color: var(--gold); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +.progress { + height: 2px; + position: absolute; + bottom: 0; + left: 0; + width: var(--progress, 30%); + background: var(--gold); + transition: width 250ms linear; +} +.overlay { + position: fixed; + inset: 0; + background: #050509a3; + backdrop-filter: blur(8px); + z-index: 30; + display: flex; + align-items: center; + justify-content: center; + padding: 30px; +} +.overlay[hidden], +.popover[hidden] { + display: none; +} +.dialog { + width: 800px; + max-width: 100%; + max-height: calc(100dvh - 60px); + display: flex; + flex-direction: column; + background: #17171d; + border: 1px solid #ffffff20; + border-radius: 18px; + box-shadow: 0 30px 100px #0008; + animation: arrive 200ms var(--ease); +} +@keyframes arrive { + from { + opacity: 0; + transform: translateY(8px) scale(0.985); + } + to { + opacity: 1; + transform: none; + } +} +.dialog header { + display: flex; + justify-content: space-between; + align-items: center; + padding: 20px 24px; + border-bottom: 1px solid var(--line); + gap: 10px; +} +.dialog h2 { + font-size: 18px; + line-height: 1.6; +} +.dialog header small { + font-size: 10px; + color: var(--gold); +} +.dialog-content { + overflow: auto; + padding: 22px 24px; + min-height: 0; +} +.dialog footer { + display: flex; + justify-content: flex-end; + align-items: center; + gap: 9px; + padding: 14px 24px; + border-top: 1px solid var(--line); +} +.dialog footer small { + margin-right: auto; +} +.dialog footer:empty { + display: none; +} +.dialog.wide { + width: 1120px; +} +.dialog.full { + width: calc(100vw - 60px); + height: calc(100vh - 60px); +} +.dialog.full .dialog-content { + flex: 1; + padding: 0; + display: grid; + place-items: center; + overflow: hidden; + background: #0c0c10; +} +.dialog.full img { + max-height: 100%; + max-width: 100%; + object-fit: contain; +} +.form-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} +.form-grid label { + display: flex; + flex-direction: column; + gap: 8px; + font-size: 11px; + color: var(--sub); +} +.form-grid input, +.form-grid select { + width: 100%; + height: 38px; +} +.form-grid .wide { + grid-column: 1/-1; +} +.form-section { + grid-column: 1/-1; + display: flex; + gap: 10px; + align-items: center; + font-size: 12px; + margin: 4px 0; + color: #e7e4ed; +} +.form-section:after { + content: ''; + height: 1px; + background: var(--line); + flex: 1; +} +.popover { + position: fixed; + width: 230px; + max-width: calc(100vw - 30px); + border: 1px solid #ffffff20; + border-radius: 12px; + background: #232229; + box-shadow: 0 10px 35px #0007; + padding: 14px; + z-index: 40; + animation: arrive 150ms var(--ease); +} +.popover h3 { + font-size: 12px; + margin-bottom: 12px; +} +.popover-options { + display: flex; + flex-wrap: wrap; + gap: 6px; +} +.popover-options button { + padding: 7px 9px; + font-size: 11px; +} +.popover-options button.selected { + background: #00cae013; + border-color: #00cae080; + color: var(--cyan); +} +.popover label { + display: block; + color: var(--sub); + font-size: 11px; + margin: 8px 0; +} +.popover input { + width: 100%; +} +.popover .main-action { + width: 100%; + margin-top: 12px; +} +.popover p { + font-size: 10px; + color: var(--sub); + line-height: 1.7; +} +.history-grid, +.asset-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); + gap: 14px; +} +.asset-card { + padding: 0; + text-align: left; + overflow: hidden; + border-radius: 10px; + background: #1d1d23; + position: relative; +} +.asset-card > img { + width: 100%; + aspect-ratio: 1.3; + object-fit: cover; + display: block; +} +.asset-card .caption { + padding: 10px 12px; + display: grid; + gap: 6px; +} +.asset-card strong { + font-size: 12px; + font-weight: 550; +} +.asset-card.active { + border-color: var(--cyan); +} +.badge { + display: inline-flex; + border-radius: 5px; + background: #00cae012; + color: #6fc7cf; + padding: 3px 6px; + font-size: 10px; +} +.badge.gold { + background: #f5b04212; + color: #d6b178; +} +.badge.red { + background: #ee676716; + color: #ef9696; +} +.toolbar-filters { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 18px; +} +.toolbar-filters button { + padding: 6px 10px; + font-size: 11px; + background: none; +} +.toolbar-filters button.selected { + background: #00cae012; + color: var(--cyan); + border-color: #00cae040; +} +.toolbar-filters input { + margin-left: auto; + min-width: 190px; + font-size: 11px; +} +.page-scroll { + height: 100%; + overflow: auto; + padding: 26px 30px; +} +.page-heading { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 24px; + gap: 16px; +} +.page-heading h1 { + font-size: 24px; + letter-spacing: -0.5px; + margin-bottom: 8px; + font-weight: 600; +} +.page-heading p { + color: var(--sub); + font-size: 12px; + line-height: 1.6; +} +.eyebrow { + color: var(--gold); + font-size: 10px; + letter-spacing: 1px; + margin-bottom: 8px; +} +.section-head { + display: flex; + justify-content: space-between; + align-items: center; + margin: 22px 0 13px; +} +.section-head h2 { + font-size: 15px; + font-weight: 550; +} +.project-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 16px; +} +.project-card { + background: var(--card); + border: 1px solid var(--line); + border-radius: 14px; + overflow: hidden; + text-align: left; + padding: 0; + position: relative; +} +.project-cover { + height: 165px; + background: #171820; + position: relative; +} +.project-cover > img { + width: 100%; + height: 100%; + object-fit: cover; + opacity: 0.9; +} +.project-cover:after { + content: ''; + inset: 50% 0 0; + position: absolute; + background: linear-gradient(transparent, #1b1c21); +} +.project-cover .badge { + position: absolute; + top: 12px; + left: 12px; + z-index: 1; + background: #101016c9; + border: 1px solid #ffffff12; +} +.project-copy { + padding: 14px 16px 17px; + display: grid; + gap: 8px; +} +.project-copy h3 { + font-size: 16px; + font-weight: 550; +} +.segmented { + display: flex; + gap: 4px; + margin-top: 4px; +} +.segmented span { + height: 3px; + background: #ffffff10; + flex: 1; + border-radius: 4px; +} +.segmented span.done { + background: #00cae0aa; +} +.segmented span.current { + background: #f5b04299; +} +.quick-tools { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; +} +.quick-tool { + display: flex; + align-items: center; + gap: 14px; + border: 1px solid var(--line); + padding: 16px; + border-radius: 12px; + background: linear-gradient(120deg, #1c1c23, #17171c); + text-align: left; +} +.quick-tool svg { + width: 25px; + height: 25px; + color: var(--cyan); +} +.quick-tool strong { + display: block; + font-size: 13px; + margin-bottom: 5px; +} +.quick-tool small { + font-size: 11px; +} +.home-resume { + display: flex; + min-height: 200px; + border: 1px solid #ffffff15; + background: #16161c; + border-radius: 16px; + overflow: hidden; + margin-bottom: 24px; +} +.home-resume > img { + width: 42%; + max-height: 240px; + object-fit: cover; +} +.resume-copy { + display: flex; + flex-direction: column; + align-items: flex-start; + justify-content: center; + padding: 24px; + gap: 12px; +} +.resume-copy h2 { + font-size: 22px; + font-weight: 550; +} +.resume-copy p { + color: var(--sub); + line-height: 1.7; + font-size: 12px; +} +.agent-page { + height: 100%; + display: grid; + grid-template-rows: 44px minmax(0, 1fr) 173px; + padding: 0 22px 14px; +} +.agent-body { + min-height: 0; + position: relative; + overflow: auto; +} +.agent-intro { + position: relative; + min-height: 100%; + padding: 32px 28px 22px; + isolation: isolate; + overflow: hidden; + border-radius: 14px; +} +.agent-intro:before { + content: ''; + position: absolute; + inset: 0 0 0 30%; + z-index: -2; + background: url('assets/story-hero.webp') right top/cover no-repeat; + opacity: 0.7; +} +.agent-intro:after { + content: ''; + position: absolute; + inset: 0; + z-index: -1; + background: + linear-gradient(90deg, #0f0f12 12%, #0f0f12dd 32%, #0f0f1230 80%), + linear-gradient(0deg, #0f0f12, transparent 40%); +} +.agent-intro h1 { + font-size: clamp(25px, 2.6vw, 40px); + line-height: 1.4; + letter-spacing: -1px; + font-weight: 650; + max-width: 560px; +} +.agent-intro p { + margin-top: 18px; + color: #b4adb9; + line-height: 1.8; + max-width: 390px; + font-size: 12px; +} +.idea-cards { + display: flex; + gap: 10px; + margin-top: 30px; + max-width: 650px; +} +.idea-card { + background: #16141bc9; + border-color: #ffffff15; + text-align: left; + padding: 13px 14px; + max-width: 205px; + backdrop-filter: blur(10px); + font-size: 12px; + line-height: 1.6; +} +.idea-card small { + display: block; + margin-top: 5px; + font-size: 10px; +} +.agent-composer { + border-color: #a98bff3d; + background: linear-gradient(120deg, #1b1823, #19171d); + grid-template-rows: 1fr 41px; + margin-top: 10px; +} +.agent-composer:focus-within { + border-color: #a98bff86; + box-shadow: 0 0 0 3px #a98bff0a; +} +.agent-composer textarea { + background: none; + border: 0; + padding: 6px 2px; + font-size: 13px; + width: 100%; + height: 100%; + min-height: 0; +} +.agent-composer .composer-bottom { + margin-top: 6px; +} +.thread { + max-width: 900px; + margin: 0 auto; + padding: 16px 14px 26px; +} +.message { + margin: 16px 0; + line-height: 1.8; + font-size: 13px; +} +.message.user { + background: #22212a; + border: 1px solid #ffffff0a; + border-radius: 12px; + padding: 14px 18px; + max-width: 85%; + margin-left: auto; +} +.message-role { + color: var(--gold); + font-size: 11px; + margin-bottom: 9px; + display: flex; + align-items: center; + gap: 8px; +} +.artifact { + border: 1px solid #a98bff35; + border-radius: 12px; + overflow: hidden; + margin-top: 15px; + background: #18171e; +} +.artifact header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + border-bottom: 1px solid var(--line); + font-size: 12px; +} +.artifact-preview { + padding: 17px 20px; + max-height: 220px; + overflow: auto; + font-size: 12px; + color: #c1bbc9; + line-height: 1.8; + white-space: pre-wrap; +} +.artifact footer { + padding: 10px 16px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + border-top: 1px solid var(--line); +} +.styles-grid { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 12px; +} +.style-card { + padding: 3px; + border-radius: 10px; + background: none; + text-align: left; +} +.style-card img { + width: 100%; + aspect-ratio: 0.85; + object-fit: cover; + border-radius: 7px; + display: block; +} +.style-card p { + padding: 9px 5px; + font-size: 11px; +} +.style-card.selected { + border-color: var(--gold); + background: #f5b0420b; +} +.stage-nav { + display: flex; + gap: 6px; + padding: 16px 22px; + border-bottom: 1px solid var(--line); + height: 76px; +} +.stage-nav button { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + flex: 1; + min-width: 0; + background: none; + border-color: transparent; + border-radius: 10px; + padding: 11px; + font-size: 12px; +} +.stage-nav button.selected { + background: #f5b0420b; + border-color: #f5b04240; + color: #e6c286; +} +.stage-num { + height: 22px; + width: 22px; + display: grid; + place-items: center; + border-radius: 7px; + border: 1px solid #ffffff15; + font-size: 11px; + flex-shrink: 0; +} +.stage-nav button.done .stage-num { + background: #00cae010; + border-color: #00cae035; + color: var(--cyan); +} +.project-page { + display: grid; + height: 100%; + grid-template-rows: 76px minmax(0, 1fr) 54px; +} +.project-body { + overflow: auto; + padding: 22px; + min-height: 0; +} +.document { + max-width: 900px; + margin: auto; + padding: 28px 38px; + background: #18181f; + border: 1px solid var(--line); + border-radius: 12px; +} +.document h2 { + font-size: 21px; + font-weight: 550; + margin: 5px 0 22px; +} +.document h3 { + font-size: 14px; + color: #d4c4a5; + margin: 24px 0 9px; +} +.document p { + font-size: 13px; + line-height: 2.1; + color: #b9b8c2; + margin: 10px 0; +} +.document textarea { + width: 100%; + height: 230px; + margin-top: 12px; + background: none; + font-size: 13px; + line-height: 1.9; +} +.project-bottom { + border-top: 1px solid var(--line); + padding: 9px 22px; + display: flex; + justify-content: space-between; + align-items: center; + gap: 10px; + background: #141418; +} +.shot-list { + display: grid; + gap: 12px; + max-width: 1000px; + margin: 0 auto; +} +.shot-row { + display: grid; + grid-template-columns: 42px 165px 1fr auto; + gap: 17px; + align-items: center; + border: 1px solid var(--line); + border-radius: 12px; + padding: 12px 16px; + background: #18181e; +} +.shot-row > img { + width: 100%; + height: 92px; + object-fit: cover; + border-radius: 7px; +} +.shot-row h3 { + font-size: 13px; + margin-bottom: 9px; +} +.shot-row p { + font-size: 11px; + color: var(--sub); + line-height: 1.8; +} +.shot-row > span { + font-size: 17px; + color: #6c647c; +} +.shot-row button { + font-size: 11px; +} +.table { + width: 100%; + border-collapse: collapse; + font-size: 12px; + text-align: left; +} +.table th { + font-size: 11px; + color: var(--sub); + font-weight: 500; + padding: 12px; + border-bottom: 1px solid #ffffff18; + white-space: nowrap; +} +.table td { + padding: 13px 12px; + border-bottom: 1px solid var(--line); + color: #babbc6; +} +.table td:first-child { + color: var(--text); +} +.table tr:hover td { + background: #ffffff03; +} +.table button { + font-size: 11px; + padding: 5px 8px; +} +.table .name { + max-width: 300px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + display: block; + font-size: 12px; +} +.table .mini-thumb { + width: 40px; + height: 30px; + object-fit: cover; + border-radius: 5px; + margin-right: 9px; + vertical-align: middle; +} +.table-container { + border: 1px solid var(--line); + border-radius: 12px; + background: #15151a; + overflow: auto; +} +.manage-form { + max-width: 840px; + border: 1px solid var(--line); + background: #17171d; + border-radius: 14px; + padding: 24px; +} +.manage-form h2 { + font-size: 17px; + margin-bottom: 20px; +} +.setting-row { + display: flex; + justify-content: space-between; + align-items: center; + padding: 18px 0; + gap: 16px; + border-bottom: 1px solid var(--line); +} +.setting-row h3 { + font-size: 12px; + font-weight: 550; + margin-bottom: 7px; +} +.setting-row p { + font-size: 11px; + color: var(--sub); + max-width: 520px; + line-height: 1.7; +} +.setting-row input { + width: 100px; +} +.setting-row select { + min-width: 120px; +} +.field-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 24px; +} +.canvas-page { + height: 100%; + display: grid; + grid-template-rows: 44px 1fr; + padding: 0 18px 18px; +} +.node-board { + position: relative; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 14px; + background-color: #111116; + background-image: radial-gradient(#6c667b30 1px, transparent 1px); + background-size: 22px 22px; +} +.graph-line { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + pointer-events: none; +} +.graph-line path { + stroke: #78658f80; + stroke-width: 2; +} +.node { + position: absolute; + background: #1a1921; + border: 1px solid #ffffff19; + border-radius: 12px; + width: 200px; + overflow: hidden; + box-shadow: 0 15px 35px #0003; + cursor: grab; + user-select: none; + touch-action: none; +} +.node:active { + cursor: grabbing; +} +.node header { + padding: 11px 13px; + border-bottom: 1px solid var(--line); + font-size: 12px; + display: flex; + align-items: center; + justify-content: space-between; + background: #26212d; +} +.node p { + padding: 14px; + font-size: 11px; + color: var(--sub); + line-height: 1.8; +} +.node img { + width: 100%; + height: 130px; + object-fit: cover; +} +.node-tools { + position: absolute; + bottom: 18px; + left: 18px; + display: flex; + gap: 5px; +} +.graph-tip { + position: absolute; + bottom: 18px; + right: 18px; + font-size: 10px; + color: var(--sub); + background: #141419d9; + padding: 10px; + border-radius: 8px; +} +.empty-search { + padding: 20px 12px; + font-size: 11px; + color: var(--sub); + line-height: 1.8; +} +.list-count { + font-size: 11px; + color: var(--sub); +} +#toast { + position: fixed; + bottom: 24px; + left: 50%; + transform: translate(-50%, 12px); + background: #292730; + border: 1px solid #ffffff25; + padding: 12px 18px; + border-radius: 10px; + z-index: 60; + font-size: 12px; + box-shadow: 0 12px 40px #0006; + opacity: 0; + pointer-events: none; + transition: + transform 180ms var(--ease), + opacity 160ms ease; + max-width: 70vw; +} +#toast.visible { + opacity: 1; + transform: translate(-50%, 0); +} +.app.focus-mode { + grid-template-columns: 68px 0 minmax(0, 1fr); +} +.app.focus-mode .context { + visibility: hidden; +} +.help-note { + background: #f5b04208; + border: 1px solid #f5b04215; + padding: 12px; + border-radius: 9px; + color: #bda682; + font-size: 11px; + line-height: 1.8; + margin-bottom: 16px; +} +body.reduced *, +body.reduced *:before, +body.reduced *:after { + animation-duration: 0s !important; + transition-duration: 0s !important; + scroll-behavior: auto !important; +} +::-webkit-scrollbar { + width: 5px; + height: 5px; +} +::-webkit-scrollbar-thumb { + background: #ffffff16; + border-radius: 5px; +} +::-webkit-scrollbar-track { + background: transparent; +} +.loading { + animation: arrive 180ms var(--ease); +} +@media (max-height: 700px) { + .context-head { + padding: 14px 15px 10px; + } + .context-controls { + padding-top: 10px; + } + .desk { + grid-template-rows: 40px minmax(0, 1fr) 160px; + padding-bottom: 10px; + } + .composer { + padding-top: 6px; + grid-template-rows: 24px 1fr 36px; + } + .composer-bottom .main-action { + padding: 7px 14px; + } + .agent-page { + grid-template-rows: 40px minmax(0, 1fr) 142px; + } + .agent-composer { + grid-template-rows: 1fr 36px; + } + .agent-intro { + padding: 20px; + } + .agent-intro h1 { + font-size: 28px; + } + .idea-cards { + margin-top: 16px; + } + .global { + gap: 7px; + padding-top: 13px; + } + #navigation { + gap: 2px; + } + .global button { + padding: 8px 2px; + } + .project-page { + grid-template-rows: 64px minmax(0, 1fr) 50px; + } + .stage-nav { + height: 64px; + padding: 10px 16px; + } + .page-scroll { + padding: 20px 24px; + } + .document { + padding: 22px; + } + .home-resume { + min-height: 155px; + } + .home-resume > img { + max-height: 190px; + } + .styles-grid { + grid-template-columns: repeat(5, 1fr); + } + .style-card img { + aspect-ratio: 1; + } + .dialog-content { + padding: 16px 20px; + } + .dialog header { + padding: 14px 20px; + } +} +@media (max-width: 1200px) { + .app { + grid-template-columns: 60px 208px minmax(0, 1fr); + } + .desk { + padding-left: 12px; + padding-right: 12px; + } + .agent-page { + padding-left: 16px; + padding-right: 16px; + } + .topbar { + padding: 0 14px; + } + .shortcut { + display: none; + } + .pills { + gap: 4px; + } + .pill { + padding: 5px 6px; + } + .stage-nav button { + gap: 6px; + font-size: 11px; + } + .styles-grid { + gap: 8px; + } + .shot-row { + grid-template-columns: 30px 120px 1fr auto; + gap: 12px; + } + .shot-row img { + height: 75px; + } + .quick-tools { + gap: 8px; + } + .quick-tool { + padding: 12px; + gap: 9px; + } + .agent-composer .pill:nth-child(4) { + display: none; + } +} +.global { + min-height: 0; + overflow: hidden; +} +.option-copy strong { + font-size: 13px; +} +.prompt-pair textarea { + font-size: 13px; +} +.desk-toolbar h3 { + font-size: 13px; +} +.pill { + font-size: 11px; +} +.composer-bottom .main-action { + font-size: 12px; +} +.caption strong { + font-size: 13px; +} +#navigation { + flex: 1; + min-height: 0; + overflow: auto; + scrollbar-width: none; +} +.search > svg { + position: absolute; + left: 9px; + top: 9px; + width: 13px; + height: 13px; + color: #9d803d; +} +@media (max-height: 700px) { + .global button { + padding: 6px 2px; + gap: 3px; + } +} +@media (prefers-reduced-motion: reduce) { + *, + *:before, + *:after { + animation-duration: 0s !important; + transition-duration: 0s !important; + } +} diff --git a/design/prototypes/reframe-20261014/design.js b/design/prototypes/reframe-20261014/design.js new file mode 100644 index 00000000..60eecde1 --- /dev/null +++ b/design/prototypes/reframe-20261014/design.js @@ -0,0 +1,1661 @@ +const $ = (s) => document.querySelector(s), + $$ = (s) => [...document.querySelectorAll(s)]; +const esc = (s) => + String(s ?? '').replace( + /[&<>"']/g, + (c) => + ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[ + c + ], + ); +const paths = { + home: 'M3 10 10 4l7 6v8H5v-8M8 18v-6h4v6', + create: 'M3 4h14v14H3zM5 15l4-4 3 3 3-5M7 8h.01', + project: 'M2 7V4h6l2 3h8v11H2z', + agent: 'm10 2 2.2 5.8L18 10l-5.8 2.2L10 18l-2.2-5.8L2 10l5.8-2.2z', + library: 'M4 2h12v16H4zM7 6h6M7 10h6M7 14h4', + flow: 'M3 3h5v5H3zM12 12h5v5h-5zM8 5h6v7M5 8v6h7', + canvas: 'M3 3h14v14H3zM7 7h3v3H7zM13 13h1', + history: 'M3 8a7 7 0 1 1 0 5M3 3v5h5M10 6v5l3 2', + settings: + 'M10 6a4 4 0 1 0 0 8 4 4 0 0 0 0-8M10 2v2M10 16v2M2 10h2M16 10h2M4 4l2 2M14 14l2 2M4 16l2-2M14 6l2-2', + models: 'M4 5h12v10H4zM1 8h3M16 8h3M7 1v4M13 1v4M7 15v4M13 15v4', + search: 'M8 3a5 5 0 1 0 0 10 5 5 0 0 0 0-10M12 12l5 5', + close: 'M4 4l12 12M16 4 4 16', + pin: 'm6 3 8 0-2 5 3 3H5l3-3zM10 11v7', + play: 'm6 3 11 7-11 7z', + pause: 'M6 3v14M14 3v14', + expand: 'M3 7V3h4M13 3h4v4M17 13v4h-4M7 17H3v-4', + compare: 'M4 4h12v12H4zM10 2v16', + download: 'M10 2v11M6 9l4 4 4-4M3 15v3h14v-3', + arrow: 'M3 10h14M12 5l5 5-5 5', + check: 'm4 10 4 4 8-9', + plus: 'M10 3v14M3 10h14', + image: 'M3 3h14v14H3zM5 14l4-5 3 3 3-3M7 6h.01', + video: 'M3 5h11v10H3zM14 8l4-3v10l-4-3', + motion: 'M3 7h12M6 11h11M2 15h8', + edit: 'm4 14 10-10 3 3-10 10H3z', + folder: 'M2 5h6l2 2h8v10H2z', + chat: 'M3 3h14v11H8l-5 4z', + upload: 'M10 13V2M6 6l4-4 4 4M3 14v4h14v-4', + back: 'M17 10H3M8 5l-5 5 5 5', + alert: 'm10 2 9 16H1zM10 7v5M10 15h.01', +}; +const icon = (n) => + ``; +function icons() { + $$('[data-icon]').forEach((e) => (e.innerHTML = icon(e.dataset.icon))); +} +const nav = [ + ['home', 'home', '工作室'], + ['project', 'project', '项目'], + ['create', 'create', '创作台'], + ['agent', 'agent', '智能体'], + ['library', 'library', '素材'], + ['canvas', 'canvas', '画布'], + ['history', 'history', '任务'], + ['flow', 'flow', '工作流'], + ['models', 'models', '模型'], +]; +const pageNames = { + ...Object.fromEntries(nav.map((n) => [n[0], n[2]])), + settings: '系统设置', +}; +$('#navigation').innerHTML = nav + .map( + ([id, i, name]) => + ``, + ) + .join(''); +const styles = [ + ['写实画报', 'xieshihuabao.jpg'], + ['日系动画', 'rixidonghua.jpg'], + ['治愈绘本', 'zhiyuhuiben.jpg'], + ['纯正国风', 'chunzhengguofeng.jpg'], + ['韩漫唯美', 'hanmanweimei.jpg'], + ['趣味黏土', 'quweiniantu.jpg'], + ['3D盲盒', '3dmanghe.jpg'], + ['冒险动漫', 'haizeiwangfengge.jpg'], + ['美漫硬朗', 'meimanyinglang.jpg'], + ['激燃极光', 'jiranjiguang.jpg'], +]; +const workflows = [ + { + id: 'qwen', + name: 'Qwen Image 2.1', + hint: '文生图 · 正反向提示词', + kind: 'image', + group: '创作', + file: 'qwen-image-2.1', + }, + { + id: 'edit', + name: 'Qwen 图像编辑', + hint: '图生图 · 参考图片与遮罩', + kind: 'image', + group: '编辑', + file: 'Qwen Image 2.1 图片编辑', + }, + { + id: 'upscale', + name: '图像高清放大', + hint: '保留原图比例', + kind: 'image', + group: '处理', + file: 'Seedvr2_3b_int8_图像放大', + }, + { + id: 'h3', + name: 'H3 首尾帧视频', + hint: '首帧+尾帧 · 运动描述', + kind: 'video', + group: '创作', + file: 'MiniMax-H3-Turbo-I2V', + }, + { + id: 'r2v', + name: 'H3 参考生视频', + hint: '参考图片 · 运动描述', + kind: 'video', + group: '创作', + file: 'MiniMax-H3-Turbo-R2V', + }, + { + id: 't2v', + name: 'H3 文生视频', + hint: '从文字开始创作', + kind: 'video', + group: '创作', + file: 'MiniMax-H3-Turbo-T2V', + }, +]; +const roles = [ + [ + 'script', + '剧本创作', + '人物、冲突与故事节奏', + '把一句灵感,写成一个好故事。', + ], + ['style', '视觉设计', '画风、色彩与光线', '让故事,拥有自己的视觉语言。'], + [ + 'storyboard', + '分镜设计', + '构图、动作与节奏', + '让每一个镜头,都有存在的理由。', + ], + ['assets', '素材资产', '角色、场景与参考', '让人物与场景,真实地走进故事。'], + ['shot', '镜头脚本', '镜头描述与生成准备', '从分镜,走向可以制作的画面。'], +]; +const stageNames = ['故事剧本', '视觉风格', '分镜设计', '素材资产', '镜头脚本']; +let state = { + page: 'create', + kind: 'image', + wf: 'qwen', + category: '全部', + search: '', + pins: new Set(['qwen', 'h3']), + drafts: {}, + params: { + aspect: '16:9', + size: '1536 × 864', + seed: '随机', + count: '1', + model: '本地 ComfyUI', + }, + result: 'landscape', + compare: false, + playing: false, + playTime: 0, + run: false, + progress: 0, + failNext: false, + role: 'script', + style: 0, + agentDrafts: {}, + messages: {}, + agentModel: '默认大模型', + agentSkill: '剧本创作', + stage: 0, + confirmed: [true, false, false, false, false], + script: + '傍晚,一位旅行者来到海边的小镇。她发现每到日落时,灯塔便会亮起一束没有人能解释的光。\n\n她决定留下来,找到光的来源。旅馆老板交给她一封三十年前的信:灯塔守护着一个尚未说出的约定。\n\n第二天,她登上灯塔,把信放在窗前。远处驶来一艘小船。一个等待了很久的故事,终于开始向前。', + assetFilter: '全部', + taskFilter: '全部', + modelTab: '大模型', + settingTab: '生成队列', + attachments: [], + agentAttachments: [], + projectTitle: '海岸来信', + modelDetails: {}, + shotEdits: {}, + extraAssets: [], + graphZoom: 1, + savedSettings: {}, + roleModels: {}, + stageDrafts: {}, + results: { qwen: 'landscape', edit: 'portrait', h3: 'landscape' }, + modelProfiles: { + 大模型: ['创作模型 A', '创作模型 B'], + 'ComfyUI 连接': ['本地 ComfyUI', '备用 ComfyUI'], + }, +}; +const defaultPrompt = + '傍晚的海岸小镇,暖色落日映照建筑和海面,画面层次自然,电影感光线,细腻真实的材质。'; +const history = [ + { + id: 61, + name: '海岸 · 日落', + wf: 'qwen', + kind: 'image', + img: 'coast.jpg', + status: '已完成', + prompt: defaultPrompt, + }, + { + id: 60, + name: '人物 · 画报', + wf: 'edit', + kind: 'image', + img: 'xieshihuabao.jpg', + status: '已完成', + prompt: '电影感人物画报,柔和光线,自然肤色,干净背景。', + }, + { + id: 59, + name: '灯塔 · 镜头 01', + wf: 'h3', + kind: 'video', + img: 'coast.jpg', + status: '已完成', + prompt: '镜头缓慢向前推进,风吹动海岸植物,保持建筑稳定。', + }, + { + id: 58, + name: '小镇 · 视觉探索', + wf: 'qwen', + kind: 'image', + img: 'zhiyuhuiben.jpg', + status: '已完成', + prompt: '温暖治愈的绘本小镇,夕阳、灯塔和旅人。', + }, + { + id: 57, + name: '镜头试拍', + wf: 'h3', + kind: 'video', + img: 'coast.jpg', + status: '失败', + prompt: '缓慢平移镜头。', + }, +]; +let runTimer, + videoTimer, + agentTimer, + toastTimer, + currentHistory = 61, + dialogKind = '', + pendingParam, + formDraft, + styleDraft; +function toast(t) { + $('#toast').textContent = t; + $('#toast').classList.add('visible'); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => $('#toast').classList.remove('visible'), 2700); +} +function saveDraft() { + if (state.page === 'create' && $('#positive')) + state.drafts[state.wf] = { + positive: $('#positive').value, + negative: $('#negative')?.value || '', + attachments: [...state.attachments], + }; + if (state.page === 'agent' && $('#agent-text')) + state.agentDrafts[state.role] = $('#agent-text').value; +} +function navigate(page, capture = true) { + if (capture) saveDraft(); + close(); + stopPlayback(); + state.page = page; + location.hash = page; + render(); +} +function stopPlayback() { + $('#sample-video')?.pause(); + clearInterval(videoTimer); + state.playing = false; + state.playTime = 0; +} +function wf() { + return workflows.find((w) => w.id === state.wf) || workflows[0]; +} +function currentImage() { + return state.result === 'portrait' + ? 'xieshihuabao.jpg' + : state.result === 'drawing' + ? 'zhiyuhuiben.jpg' + : 'coast.jpg'; +} +function btn(action, label, cls = '', attrs = '') { + return ``; +} +function contextHead(title, hint) { + return `

${title}

${hint}

`; +} +function option(id, name, hint, i = 'flow', active = false, extra = '') { + return `
${icon(i)}${esc(name)}${esc(hint)}${extra}
`; +} +function renderDirectory() { + const data = workflows + .filter( + (w) => + w.kind === state.kind && + (state.category === '全部' || w.group === state.category) && + (!state.search || + (w.name + ' ' + w.hint + ' ' + w.file) + .toLowerCase() + .includes(state.search.toLowerCase())), + ) + .sort( + (a, b) => Number(state.pins.has(b.id)) - Number(state.pins.has(a.id)), + ); + $('.directory').innerHTML = + data + .map((w) => + option( + w.id, + w.name, + w.hint, + w.kind === 'video' ? 'video' : 'image', + state.wf === w.id, + ``, + ), + ) + .join('') || + ''; + $('.list-caption').innerHTML = + `${data.length} 个常用入口置顶优先`; +} +function renderContext() { + let html = ''; + if (state.page === 'create') { + html = + contextHead('创作台', '选择工具,然后专注于作品。') + + `
${['image', 'video'].map((k) => ``).join('')}
${['全部', '创作', '编辑', '处理'].map((c) => ``).join('')}
`; + } else if (state.page === 'agent') { + html = + contextHead('智能体工坊', '让专业助手参与每一步创作。') + + `
创作团队 · 5 个角色
${roles.map((r, i) => option(r[0], r[1], r[2], 'agent', state.role === r[0], `${['剧', '视', '分', '素', '镜'][i]}`)).join('')}
`; + } else if (state.page === 'project') { + html = + contextHead(esc(state.projectTitle), '当前项目 · 叙事短片') + + `
项目封面一个关于等待与重逢的故事。
${option('project-overview', '项目概览', '继续当前制作阶段', 'project', true)}${option('project-assets', '项目素材', '角色、场景与参考图', 'library')}${option('project-agent', '当前阶段助手', '前往对应智能体', 'agent')}${option('project-canvas', '项目画布', '内容关系与创作节点', 'canvas')}
`; + } else if (state.page === 'models') { + html = + contextHead('模型与服务', '把连接配置与创作分开。') + + `
${['大模型', 'ComfyUI 连接', '角色绑定'].map((t, i) => option('model-' + i, t, ['管理 API 与默认模型', '检查本地生成服务', '为每个智能体选择模型'][i], i === 1 ? 'flow' : 'models', state.modelTab === t)).join('')}
`; + } else if (state.page === 'settings') { + html = + contextHead('系统设置', '队列、运行和存储各归其位。') + + `
${['生成队列', '智能体运行', '存储与记忆'].map((t, i) => option('setting-' + i, t, ['控制并发与等待时间', '控制运行边界与确认', '文件目录与项目记忆'][i], 'settings', state.settingTab === t)).join('')}
`; + } else { + const titles = { + home: ['工作室', '回到项目,继续创作。'], + library: ['素材库', '集中整理创作的原材料。'], + history: ['任务记录', '在这里查看所有生成过程。'], + flow: ['工作流目录', '发现、整理、管理本地工具。'], + canvas: ['项目画布', '用可视化方式组织创作内容。'], + }; + const [t, h] = titles[state.page] || titles.home; + html = + contextHead(t, h) + + `
${(state.page === 'library' ? ['全部素材', '图片', '视频', '来自当前项目'] : state.page === 'history' ? ['全部任务', '进行中', '已完成', '失败'] : state.page === 'flow' ? ['全部工作流', '图像创作', '视频创作', '处理与工具'] : state.page === 'canvas' ? ['海岸来信', '旅行者', '灯塔与小镇'] : ['所有项目', '最近编辑', '等待确认']).map((n, i) => option('filter-' + i, n, '', state.page === 'home' ? 'project' : state.page === 'library' ? 'folder' : 'history', i === 0)).join('')}
`; + } + $('#context').innerHTML = html; + if (state.page === 'create') renderDirectory(); + icons(); +} +function render() { + const existingVideo = $('#sample-video'); + $('#page-title').textContent = pageNames[state.page]; + $$('[data-page]').forEach((e) => + e.classList.toggle('active', e.dataset.page === state.page), + ); + renderContext(); + const views = { + create: renderDesk, + agent: renderAgent, + project: renderProject, + home: renderHome, + library: renderLibrary, + history: renderTasks, + flow: renderFlows, + models: renderModels, + canvas: renderCanvas, + settings: renderSettings, + }; + $('#workspace').innerHTML = (views[state.page] || renderDesk)(); + if ( + existingVideo && + $('#sample-video') && + existingVideo.dataset.wf === state.wf + ) { + $('#sample-video').replaceWith(existingVideo); + playbackUi(); + } + icons(); + $('#queue-label').textContent = state.run ? '1 个任务进行中' : '任务空闲'; + $('.dot').classList.toggle('busy', state.run); +} +function mediaTokens() { + if (state.wf === 'h3') + return `参考帧${['首帧', '尾帧'].map((s, i) => btn('upload', `${state.attachments[i] ? `${s}` : icon('plus')}${s}`, `media-token ${state.attachments[i] ? 'filled' : ''}`, `data-slot="${i}"`)).join('')}`; + if (state.wf === 'edit' || state.wf === 'r2v' || state.wf === 'upscale') + return `${state.wf === 'edit' ? '参考图片' : '输入素材'}${btn('upload', state.attachments.length ? `参考已选 ${state.attachments.length} 张` : icon('plus') + '添加图片', 'media-token')}${state.wf === 'edit' ? btn('mask', '绘制遮罩', 'media-token') : ''}`; + return `本次生成${state.kind === 'image' ? '图像' : '视频'}输入草稿独立保留`; +} +function renderDesk() { + const draft = state.drafts[state.wf] || { + positive: + state.kind === 'image' + ? defaultPrompt + : '镜头缓慢向前推进,海面自然流动,光线和建筑保持一致。', + negative: '模糊、过度锐化、文字、水印', + }; + state.attachments = draft.attachments || state.attachments; + return `

${wf().name}

${state.kind === 'image' ? '图像创作' : '视频创作'}
${btn('history', '◷ 历史记录', 'text-btn')}${btn('focus', '专注 ⤢', 'text-btn')}
${renderCanvasResult()}
${mediaTokens()}
${state.wf === 'qwen' ? `` : ''}
${btn('param-model', icon('models') + '本地服务 ⌄', 'pill')}${btn('param-aspect', state.params.aspect + ' ⌄', 'pill')}${btn('param-count', state.params.count + ' 张 ⌄', 'pill')}${btn('param-seed', '种子 ' + state.params.seed + ' ⌄', 'pill')}${btn('params', icon('settings') + '更多', 'pill')}
Ctrl + Enter${state.run ? btn('cancel-generate', '停止生成', 'main-action') : btn('generate', icon('agent') + ' 开始生成', 'main-action')}
`; +} +function renderCanvasResult() { + if (state.result === 'empty') + return `
${icon('image')}

作品,从这里开始。

选择工作流,填好提示词。生成后的作品会以完整比例呈现在这里。

${btn('example-result', '查看样例结果', 'text-btn')}
${processing()}
`; + if (state.result === 'failed') + return `
`; + return `
适应画布 · ${state.kind === 'video' ? '00:05' : '本次结果 1 / ' + state.params.count}${state.kind === 'video' ? `` : `本次创作样例,保持原始比例`}${state.compare ? '对比结果' : ''}
${btn('result-details', icon('settings'), '', 'title="查看本次参数" aria-label="查看本次参数"')}${btn('compare', icon('compare'), '', 'title="并排对比" aria-label="并排对比"')}${btn('enlarge', icon('expand'), '', 'title="放大作品" aria-label="放大作品"')}${btn('download', icon('download'), '', 'title="下载样例作品" aria-label="下载样例作品"')}${btn('save-project', icon('folder'), '', 'title="保存到项目" aria-label="保存到项目"')}
${state.kind === 'video' ? btn('play', icon(state.playing ? 'pause' : 'play'), 'video-play', `aria-label="${state.playing ? '暂停视频' : '播放视频'}"`) + `
${btn('play', icon(state.playing ? 'pause' : 'play'), '', 'aria-label="切换播放"')}00:0${state.playTime.toFixed(0)}00:05
` : ''}
${state.kind === 'video' ? '视频预览情景 · 手动播放' : '原图完整显示 · 双击画面放大'}${state.kind === 'video' ? '1280 × 720 · 5 秒' : state.result === 'portrait' ? '竖图 · 按画布高度适配' : '横图样例'}
${processing()}
`; +} +function processing() { + return state.run && state.task?.wf === state.wf + ? `
正在生成 · ${state.progress}%${btn('cancel-generate', '停止', 'text-btn')}
` + : ''; +} +function renderAgent() { + const r = roles.find((r) => r[0] === state.role), + messages = state.messages[state.role] || []; + return `

${r[1]}

海岸来信
${btn('agent-history', '◷ 会话记录', 'text-btn')}${btn('new-chat', '+ 新会话', 'text-btn')}
${ + messages.length + ? `
${messages.map((m) => (m.who === 'user' ? `
${esc(m.text)}
` : `
${icon('agent')}${r[1]}

${esc(m.text)}

${stageNames[roles.findIndex((x) => x[0] === state.role)]} · 草稿待你确认
${esc(m.artifact)}
阅读、编辑后,再保存到项目。${btn('edit-artifact', '编辑并保存到项目', 'main-action')}
`)).join('')}
` + : `
✦ ${r[1]} · 创作搭档

${r[3]}

选择风格和技能,给出你的想法。助手负责整理草稿,你决定作品最终的方向。

${[ + ['帮我打磨这个故事', '补足冲突和人物动机'], + ['从一个场景开始', '一座灯塔、一封来信'], + ['整理已有的材料', '把碎片变成清晰草稿'], + ] + .map(([a, b]) => + btn( + 'idea', + a + `${b}`, + 'idea-card', + `data-idea="${a}"`, + ), + ) + .join('')}
` + }
${btn('styles', `${styles[state.style][0]} ⌄`, 'pill')}${btn('agent-model', (state.roleModels[state.role] || '默认大模型') + ' ⌄', 'pill')}${btn('skills', state.agentSkill + ' ⌄', 'pill')}${btn('agent-attach', icon('plus') + (state.agentAttachments.length ? state.agentAttachments.length + ' 份材料' : '参考材料'), 'pill')}
Ctrl + Enter${agentTimer ? btn('agent-stop', '停止', 'main-action') : btn('agent-send', '开始创作 ↗', 'main-action')}
`; +} +function projectDocument() { + if (state.stage === 0) + return `
${state.confirmed[0] ? '已确认' : '待确认草稿'}

${esc(state.projectTitle)}

故事剧本

${esc(state.script)}

确认后的版本用于后续阶段。${btn('edit-script', icon('edit') + ' 编辑剧本', 'text-btn')}
`; + if (state.stage === 1) + return `
视觉方向 · 待确认

温暖、克制的海岸电影感

视觉方向参考

视觉要求

${esc(state.stageDrafts.style || '落日暖光、自然肤色和深色海面。镜头保留安静的空间,让人物成为画面的焦点。')}

${styles + .slice(0, 3) + .map( + (s) => + `${s[0]}`, + ) + .join('')}${btn('styles', '选择视觉参考', '')}
`; + if (state.stage === 2 || state.stage === 4) + return `${state.stageDrafts[roles[state.stage][0]] ? `

助手建议 · 待整理到镜头字段

${esc(state.stageDrafts[roles[state.stage][0]])}

` : ''}
${[ + [ + '灯塔与小镇', + '大全景 · 固定镜头', + '建立故事发生的地点。夕阳与海面形成冷暖对照。', + 'coast.jpg', + ], + [ + '旅行者抵达', + '中景 · 缓慢推进', + '她停下脚步,望向远处的灯塔。神情充满好奇。', + 'xieshihuabao.jpg', + ], + [ + '窗前的来信', + '近景 · 静止', + '纸张在晚风中轻轻颤动。她将信放在窗前。', + 'zhiyuhuiben.jpg', + ], + ] + .map( + (s, i) => + `
0${i + 1}${s[0]}

${s[0]}

${s[1]}
${esc(state.shotEdits[i] || s[2])}

${btn(state.stage === 4 ? 'shot-generate' : 'shot-edit', state.stage === 4 ? '去创作台' : '编辑镜头', '', `data-shot="${i}"`)}
`, + ) + .join('')}
`; + return `${state.stageDrafts.assets ? `

素材整理建议

${esc(state.stageDrafts.assets)}

` : ''}
${assetCards().slice(0, 4).map(assetCard).join('')}
`; +} +function renderProject() { + return `
${projectDocument()}
${state.confirmed[state.stage] ? '此阶段已有确认版本。' : '当前为草稿,确认后进入下一阶段。'}
${btn('project-agent', '让对应助手协助', '')}${btn('confirm-stage', state.confirmed[state.stage] ? '进入下一阶段 →' : '确认本阶段 →', 'main-action')}
`; +} +function renderHome() { + return `
你的创作,继续向前

今天,继续哪个故事?

${btn('new-project', '+ 新建项目', 'main-action')}
海岸来信项目
最近编辑 · 视觉风格待确认

海岸来信

关于灯塔、来信与一个迟到的约定。
先确定视觉方向,再开始拆解镜头。

${btn('project', '继续这个项目 →', 'main-action')}
${[ + ['create', 'create', '直接创作', '图片与视频工作流'], + ['agent', 'agent', '与助手讨论', '剧本、风格与分镜'], + ['library', 'library', '整理素材', '角色、场景与生成结果'], + ] + .map(([id, i, t, h]) => + btn( + id, + icon(i) + `
${t}${h}
`, + 'quick-tool', + ), + ) + .join( + '', + )}

我的项目

3 个样例项目
${[ + ['海岸来信', 'coast.jpg', '视觉风格 · 待确认'], + ['另一种日常', 'rixidonghua.jpg', '故事剧本 · 草稿'], + ['山间行记', 'chunzhengguofeng.jpg', '镜头脚本 · 制作中'], + ] + .map( + (s, i) => + ``, + ) + .join('')}
`; +} +function assetCards() { + return [ + ...state.extraAssets, + { name: '海岸小镇', img: 'coast.jpg', type: '场景' }, + ...styles.slice(0, 8).map((s, i) => ({ + name: [ + '旅行者 · 写实参考', + '旅行者 · 日系参考', + '绘本探索', + '山间的灯塔', + '人物情绪', + '造型探索', + '3D 角色', + '冒险场景', + ][i], + img: s[1], + type: i % 3 === 0 ? '角色' : '参考图', + })), + ]; +} +function assetCard(s, i) { + return ``; +} +function renderLibrary() { + let assets = assetCards(); + if (state.assetFilter !== '全部') + assets = assets.filter((s) => s.type === state.assetFilter); + return `

素材库

项目素材与生成结果,集中查看与使用。

${btn('upload-library', icon('upload') + ' 上传素材', 'main-action')}
${['全部', '角色', '场景', '参考图'].map((t) => btn('asset-filter', t, state.assetFilter === t ? 'selected' : '', `data-filter="${t}"`)).join('')}
${assets + .map((s) => + assetCard( + s, + assetCards().findIndex((a) => a.name === s.name), + ), + ) + .join('')}
`; +} +function renderTasks() { + let rows = history.filter( + (r) => state.taskFilter === '全部' || r.status === state.taskFilter, + ); + return `

任务记录

历史与任务集中管理,创作台只展示当前作品。

${btn('create', '返回创作台', '')}
${['全部', '已完成', '失败', '进行中'].map((t) => btn('task-filter', t, state.taskFilter === t ? 'selected' : '', `data-filter="${t}"`)).join('')}
${rows.map(taskRow).join('') || ''}
作品/任务工作流状态来源时间操作
目前没有符合条件的任务。
`; +} +function taskRow(r) { + return `${r.name}${workflows.find((w) => w.id === r.wf)?.name || ''}${r.status}海岸来信今天 18:${r.id}${btn('history-item', '查看', '', `data-history="${r.id}"`)}`; +} +function fileKind(f) { + return /视频|H3|I2V|T2V|R2V|Wan|VACE|LTX/i.test(f) + ? '视频' + : /图像|图片|Qwen|image|flux|SDXL|文生图|图生图/i.test(f) + ? '图像' + : '工具'; +} +function renderFlows() { + return `

工作流目录

现有仓库中 ${window.catalog.length} 个 JSON 文件的目录样本;文件未在这里执行或自动导入。

${btn('import-workflow', '+ 导入工作流', 'main-action')}
仓库目录用途按文件名分组,正式接入时以工作流元数据为准。
${flowRows(window.catalog)}
名称分组所在目录操作
`; +} +function flowRows(files) { + return ( + files + .map((f) => { + const name = f + .split('/') + .pop() + .replace(/\.json$/, ''); + return `${esc(name)}${fileKind(f)}${esc(f.split('/').slice(0, -1).join('/').slice(0, 35) || '根目录')}${btn('flow-detail', '详情', '', `data-file="${esc(f)}"`)}`; + }) + .join('') || '没有符合条件的文件。' + ); +} +function renderModels() { + const connections = state.modelTab === 'ComfyUI 连接'; + if (state.modelTab === '角色绑定') + return `

角色模型绑定

每个助手的模型选择独立保存。

${roles.map((r) => `

${r[1]}

${r[2]}

`).join('')}
${btn('save-bindings', '保存绑定', 'main-action')}
`; + return `

${connections ? 'ComfyUI 连接' : '大模型接口'}

${connections ? '本地工作流的执行服务,单独检查连接。' : '管理自定义接口与默认模型,密钥在编辑时填写。'}

${btn('add-model', '+ 添加' + (connections ? '连接' : '模型'), 'main-action')}
${state.modelProfiles[connections ? 'ComfyUI 连接' : '大模型'].map((n, i) => ``).join('')}
名称${connections ? '服务类型' : '模型'}状态操作
${n}${i === 0 ? ' 默认' : ''}${connections ? '本地服务' : '自定义 API'}样例配置 · 未连接${btn('test-model', '测试', '')}${btn('edit-model', '编辑', '', `data-model-name="${n}"`)}
`; +} +function renderSettings() { + const t = state.settingTab, + items = + t === '生成队列' + ? [ + ['同时生成的任务', '根据本地服务能力设置并发。', '1'], + ['任务等待上限', '超过等待时间后明确提示,而非一直转圈。', '600'], + ['队列状态', '暂停队列不会删除等待中的任务。', '运行'], + ] + : t === '智能体运行' + ? [ + ['运行步数上限', '控制一个任务持续执行的步数。', '40'], + ['关键操作确认', '生成与修改前保留必要的确认环节。', '开启'], + ['会话记忆', '按照项目与角色管理上下文。', '开启'], + ] + : [ + ['项目存储目录', '生成文件和草稿的统一位置。', '项目目录'], + ['记忆管理', '查看、编辑与删除已保存的项目记忆。', '查看'], + ['文件清理', '只在明确选择后清理记录或文件。', '查看'], + ]; + return `

${t}

调整后保存生效;取消保留原设置。

${t}

${items + .map(([n, h, initial]) => { + const v = state.savedSettings[n] ?? initial; + return `

${n}

${h}

${/^\d+$/.test(v) ? `` : ``}
`; + }) + .join( + '', + )}
${btn('cancel-settings', '取消', '')}${btn('save-settings', '保存设置', 'main-action')}
`; +} +function renderCanvas() { + return `

海岸来信 · 项目画布

内容关系
${btn('add-node', '+ 添加文本卡片', '')}
${[ + ['故事大纲', state.script.slice(0, 65), '', 5, 12], + ['旅行者', '在海边小镇找到一封旧信。', 'xieshihuabao.jpg', 36, 32], + ['灯塔与小镇', '关于等待与重逢的故事。', 'coast.jpg', 68, 13], + ] + .map( + ([t, p, img, x, y], i) => + `
${t}↕ 拖动
${img ? `${t}` : ''}

${p}

`, + ) + .join( + '', + )}
${btn('zoom-out', '−', '')}${btn('graph-reset', '100%', '')}${btn('zoom-in', '+', '')}
拖动卡片整理位置 · 双击卡片查看内容
`; +} +function showDialog( + title, + content, + footer = '', + kind = '', + wide = false, + eyebrow = '', +) { + closePopover(); + dialogKind = kind; + $('#dialog-title').textContent = title; + $('#dialog-eyebrow').textContent = eyebrow; + $('#dialog-content').innerHTML = content; + $('#dialog-footer').innerHTML = footer; + $('.dialog').className = 'dialog' + (wide ? ' wide' : ''); + $('#overlay').hidden = false; + icons(); + $('#overlay').querySelector('[data-action=close]').focus(); +} +function close() { + if (!$('#overlay').hidden) { + $('#overlay').hidden = true; + dialogKind = ''; + } + closePopover(); +} +function closePopover() { + $('#popover').hidden = true; +} +function openParams() { + saveDraft(); + formDraft = { ...state.params }; + showDialog( + '创作参数', + `
常用参数
执行服务
工作流参数
`, + `只修改参数,保留提示词和素材。${btn('close', '取消', '')}${btn('save-params', '保存参数', 'main-action')}`, + 'params', + ); +} +function openParam(key, target) { + saveDraft(); + pendingParam = key; + const map = { + aspect: ['画面比例', ['16:9', '9:16', '1:1', '4:3']], + count: ['生成数量', ['1', '2', '4', '8']], + seed: ['随机种子', []], + model: ['执行服务', ['本地 ComfyUI', '备用 ComfyUI']], + }; + const [label, values] = map[key]; + $('#popover').innerHTML = + `

${label}

${values.length ? `
${values.map((v) => ``).join('')}
` : `

填写数字,或使用“随机”。

${btn('apply-seed', '应用种子', 'main-action')}`}`; + const r = target.getBoundingClientRect(); + $('#popover').hidden = false; + const h = $('#popover').offsetHeight; + $('#popover').style.left = + Math.max(12, Math.min(innerWidth - 242, r.left)) + 'px'; + $('#popover').style.top = Math.max(12, r.top - h - 10) + 'px'; +} +function openHistory() { + saveDraft(); + showDialog( + '生成历史', + `
独立浏览查看历史不会覆盖当前输入。${btn('all-tasks', '全部任务 ↗', 'quiet')}
${history.map((r) => ``).join('')}
`, + '', + 'history', + true, + ); +} +function historyItem(id) { + currentHistory = +id; + const r = history.find((h) => h.id === currentHistory); + if (!r) return; + showDialog( + r.name, + `${r.name}

生成提示词

${esc(r.prompt)}

${r.status}
`, + `只有点击复用,才会写入创作输入。${btn('history', '返回历史', '')}${btn('reuse-history', '复用参数并创作', 'main-action')}`, + 'history-detail', + ); +} +function showStyles() { + styleDraft = state.style; + showDialog( + '选择视觉风格', + `
${styles.map((s, i) => ``).join('')}
`, + `确认后应用,取消不改变当前风格。${btn('close', '取消', '')}${btn('apply-style', '应用风格', 'main-action')}`, + 'styles', + true, + ); +} +function confirmReuse() { + const r = history.find((h) => h.id === currentHistory); + saveDraft(); + showDialog( + '复用这次生成?', + `

将把“${r.name}”的提示词和工作流填入创作台。当前输入草稿不会被自动提交。

`, + `${btn('close', '保留当前输入', '')}${btn('confirm-reuse', '确认复用', 'main-action')}`, + 'reuse', + ); +} +function generate() { + saveDraft(); + const d = state.drafts[state.wf]; + if (!d?.positive?.trim()) return toast('先填写画面或运动描述。'); + if ( + ['h3', 'edit', 'r2v', 'upscale'].includes(state.wf) && + !state.attachments.length + ) + return toast( + state.wf === 'h3' + ? '请先添加首帧;尾帧也有独立输入位置。' + : '请添加输入图片。', + ); + if (state.run) return; + const task = { + wf: state.wf, + kind: state.kind, + params: { ...state.params }, + prompt: d.positive, + fail: state.failNext, + }; + state.task = task; + state.run = true; + state.progress = 0; + render(); + runTimer = setInterval(() => { + state.progress += 20; + if (state.progress >= 100) { + clearInterval(runTimer); + state.run = false; + const result = task.fail + ? 'failed' + : task.params.aspect === '9:16' + ? 'portrait' + : 'landscape'; + state.results[task.wf] = result; + if (state.wf === task.wf) state.result = result; + state.failNext = false; + history.unshift({ + id: history[0].id + 1, + name: '新的创作样例', + wf: task.wf, + kind: task.kind, + img: result === 'portrait' ? 'xieshihuabao.jpg' : 'coast.jpg', + status: result === 'failed' ? '失败' : '已完成', + prompt: task.prompt, + }); + render(); + toast( + result === 'failed' + ? '模拟生成失败,输入已保留。' + : '样例生成完成,可以查看完整作品。', + ); + } else { + if ($('#run-progress')) + $('#run-progress').textContent = state.progress + '%'; + if ($('.processing .progress')) + $('.processing .progress').style.setProperty( + '--progress', + state.progress + '%', + ); + } + }, 450); +} +function playbackUi() { + const video = $('#sample-video'); + state.playing = video ? !video.paused : false; + $$('[data-action=play]').forEach((b) => { + b.innerHTML = icon(state.playing ? 'pause' : 'play'); + b.setAttribute( + 'aria-label', + b.classList.contains('video-play') + ? state.playing + ? '暂停视频' + : '播放视频' + : '切换播放', + ); + }); +} +async function play() { + const video = $('#sample-video'); + if (!video) return; + if (video.paused) { + if (video.ended) video.currentTime = 0; + try { + await video.play(); + } catch { + return toast('视频暂时不能播放,请重新打开预览。'); + } + } else video.pause(); + playbackUi(); +} +for (const event of ['play', 'pause', 'ended']) + document.addEventListener( + event, + (e) => { + if (e.target.id === 'sample-video') playbackUi(); + }, + true, + ); +document.addEventListener( + 'timeupdate', + (e) => { + if (e.target.id !== 'sample-video') return; + state.playTime = e.target.currentTime; + if ($('#video-time')) + $('#video-time').textContent = '00:0' + Math.floor(state.playTime); + if ($('#video-position')) $('#video-position').value = state.playTime; + }, + true, +); +function sendAgent() { + saveDraft(); + const content = state.agentDrafts[state.role]?.trim(); + if (!content) return toast('先写下任务或你的想法。'); + const role = state.role; + state.messages[role] ??= []; + state.messages[role].push({ who: 'user', text: content }); + state.agentDrafts[role] = ''; + agentTimer = setTimeout(() => { + const draft = + role === 'script' + ? state.script + : role === 'style' + ? '视觉方向:温暖的海岸电影感。\n光线:落日暖光,保持自然肤色。\n色彩:米金色高光与青灰色阴影。\n构图:人物在环境中保持清晰焦点。' + : '镜头 01:建立灯塔与小镇的空间关系。\n镜头 02:旅行者抵达,缓慢推进到中景。\n镜头 03:来信出现在窗前,画面停留在纸张细节。'; + state.messages[role].push({ + who: 'assistant', + text: '我整理了一版可继续编辑的草稿。先确认方向,再把它带回项目。', + artifact: draft, + }); + agentTimer = null; + if (state.page === 'agent') render(); + }, 1000); + render(); +} +function openEditor() { + const ms = state.messages[state.role] || []; + const text = ms.filter((m) => m.artifact).at(-1)?.artifact || state.script; + showDialog( + '编辑创作草稿', + `
`, + `${btn('close', '取消', '')}${btn('save-artifact', '保存草稿并打开项目', 'main-action')}`, + 'artifact', + ); +} +let selectedAsset = 0; +function assetPreview(index) { + selectedAsset = index; + const a = assetCards()[index]; + showDialog( + a.name, + `${a.name}`, + `${a.type} · 项目素材${btn('asset-create', '用作创作参考', '')}${btn('save-project', '关联项目', 'main-action')}`, + 'asset', + ); +} +let editingModelName = '', + editingShot = 0; +function openModels(name = '') { + editingModelName = name; + const connections = state.modelTab === 'ComfyUI 连接'; + showDialog( + name ? '编辑配置' : '添加' + (connections ? '连接' : '模型'), + `
${connections ? '' : ``}
样本只演示填写、取消、保存与错误反馈,不测试真实接口或保存密钥。
`, + `${btn('close', '取消', '')}${btn('save-model', '保存配置', 'main-action')}`, + 'model', + ); +} +function action(a, e) { + if (a === 'project' && e.classList.contains('project-card')) { + state.projectTitle = e.querySelector('h3').textContent; + } + switch (a) { + case 'close': + return close(); + case 'create': + case 'home': + case 'project': + case 'library': + case 'agent': + case 'models': + case 'canvas': + case 'history-page': + return navigate(a === 'history-page' ? 'history' : a); + case 'connections': + state.modelTab = 'ComfyUI 连接'; + return navigate('models'); + case 'workflow-directory': + saveDraft(); + return showDialog( + '选择与管理工作流', + `
已配置入口与仓库文件分开显示,导入并检查映射后才能使用。
${flowRows(window.catalog)}
工作流文件用途分组目录操作
`, + `${btn('close', '回到当前创作', '')}${btn('flow-manager', '管理工作流', 'main-action')}`, + 'catalog', + true, + ); + case 'flow-manager': + return navigate('flow'); + case 'queue': + return showDialog( + '当前任务', + state.run + ? '

当前有 1 个样例任务正在生成。

' + : '

当前没有进行中的任务。

', + btn('all-tasks', '查看全部任务', 'main-action'), + 'queue', + ); + case 'all-tasks': + return navigate('history'); + case 'history': + return openHistory(); + case 'history-item': + return historyItem(e.dataset.history); + case 'reuse-history': + return confirmReuse(); + case 'confirm-reuse': { + const r = history.find((h) => h.id === currentHistory); + state.wf = r.wf; + state.kind = r.kind; + state.drafts[r.wf] = { + positive: r.prompt, + negative: '', + attachments: [], + }; + state.attachments = []; + state.result = + r.img === 'xieshihuabao.jpg' + ? 'portrait' + : r.img === 'zhiyuhuiben.jpg' + ? 'drawing' + : 'landscape'; + state.compare = false; + return navigate('create', false); + } + case 'params': + return openParams(); + case 'save-params': + $('#dialog-content') + .querySelectorAll('[name]') + .forEach((n) => (formDraft[n.name] = n.value)); + state.params = formDraft; + close(); + render(); + return toast('参数已应用,提示词和参考图保持原样。'); + case 'param-aspect': + case 'param-count': + case 'param-seed': + case 'param-model': + return openParam(a.slice(6), e); + case 'apply-seed': + state.params.seed = $('#seed-value').value || '随机'; + closePopover(); + return render(); + case 'generate': + return generate(); + case 'cancel-generate': + clearInterval(runTimer); + state.run = false; + render(); + return toast('已停止样例任务,输入与旧结果已保留。'); + case 'focus': + return $('.app').classList.toggle('focus-mode'); + case 'compare': + saveDraft(); + state.compare = !state.compare; + return render(); + case 'enlarge': + showDialog( + '作品预览', + `完整作品`, + '', + 'enlarge', + true, + ); + $('.dialog').className = 'dialog full'; + return; + case 'result-details': + return showDialog( + '本次生成参数', + `
${Object.entries({ + 工作流: wf().name, + 画面比例: state.params.aspect, + 尺寸: state.params.size, + 种子: state.params.seed, + 生成数量: state.params.count, + 服务: state.params.model, + }) + .map( + ([k, v]) => + ``, + ) + .join( + '', + )}

本次提示词

${esc(state.drafts[state.wf]?.positive || defaultPrompt)}

`, + btn('close', '返回创作', ''), + 'result-details', + ); + case 'download': { + const link = document.createElement('a'); + link.href = 'assets/' + currentImage(); + link.download = '创作样例-' + currentImage(); + link.click(); + return toast('正在下载样例图片。'); + } + case 'save-project': + return showDialog( + '保存到项目', + `
`, + `${btn('close', '取消', '')}${btn('confirm-save-project', '保存作品', 'main-action')}`, + 'save-project', + ); + case 'confirm-save-project': + close(); + return toast('已在样本中关联到项目;正式接入后写入项目素材。'); + case 'upload': + $('#upload').dataset.slot = e.dataset.slot || '0'; + return $('#upload').click(); + case 'upload-library': + $('#upload').dataset.slot = 'library'; + return $('#upload').click(); + case 'mask': + return showDialog( + '图片遮罩', + `

在画面上拖动,标记希望重新绘制的区域。

`, + `${btn('clear-mask', '清空遮罩', '')}${btn('apply-mask', '应用遮罩', 'main-action')}`, + 'mask', + ); + case 'clear-mask': + return $('#mask-canvas').getContext('2d').clearRect(0, 0, 560, 320); + case 'apply-mask': + close(); + return toast('已保留样本遮罩。'); + case 'play': + return play(); + case 'example-result': + state.result = 'landscape'; + return render(); + case 'styles': + return showStyles(); + case 'apply-style': + state.style = styleDraft; + close(); + render(); + return toast('已应用视觉风格,任务草稿已保留。'); + case 'idea': + $('#agent-text').value = e.dataset.idea; + $('#agent-text').focus(); + return; + case 'agent-model': + return showDialog( + '当前角色使用的模型', + `
`, + `${btn('close', '取消', '')}${btn('apply-agent-model', '应用模型', 'main-action')}`, + 'agent-model', + ); + case 'apply-agent-model': + state.agentModel = $('#agent-model-value').value; + state.roleModels[state.role] = state.agentModel; + close(); + return render(); + case 'skills': + return showDialog( + '技能与创作工具', + `
${['剧本创作', '角色一致性', '镜头提示词', '自定义技能'].map((n, i) => option('skill-' + i, n, '选择后用于当前角色的任务', 'agent', state.agentSkill === n)).join('')}
`, + `${btn('skill-editor', '+ 编辑自定义技能', '')}${btn('close', '返回', 'main-action')}`, + 'skills', + ); + case 'skill-editor': + return showDialog( + '自定义技能', + `
`, + `${btn('close', '取消', '')}${btn('save-skill', '保存技能', 'main-action')}`, + 'skill-editor', + ); + case 'save-skill': + state.agentSkill = '我的创作规范'; + close(); + render(); + return toast('自定义技能已在样本中保存。'); + case 'agent-attach': + return $('#agent-upload').click(); + case 'agent-send': + return sendAgent(); + case 'agent-stop': + clearTimeout(agentTimer); + agentTimer = null; + render(); + return toast('已停止样例回复。'); + case 'new-chat': + saveDraft(); + state.messages[state.role] = []; + return render(); + case 'agent-history': + return showDialog( + '会话记录', + `
${roles.map((r) => option('session-' + r[0], r[1], (state.messages[r[0]] || []).length + ' 条样例消息', 'chat')).join('')}
`, + '', + 'agent-history', + ); + case 'edit-artifact': + return openEditor(); + case 'save-artifact': { + const text = $('#artifact-editor').value; + if (text.trim().length < 15) + return toast('草稿内容太短,请补充后再保存。'); + if (state.role === 'script') state.script = text; + state.stageDrafts[state.role] = text; + state.stage = roles.findIndex((r) => r[0] === state.role); + state.confirmed[state.stage] = false; + navigate('project'); + return toast('已保存为样本草稿,确认后继续下一阶段。'); + } + case 'edit-script': + return showDialog( + '编辑故事剧本', + ``, + `${btn('close', '取消', '')}${btn('save-script', '保存草稿', 'main-action')}`, + 'script', + ); + case 'save-script': + state.script = $('#script-editor').value; + state.confirmed[0] = false; + close(); + render(); + return toast('故事草稿已保存。'); + case 'confirm-stage': + state.confirmed[state.stage] = true; + if (state.stage < 4) state.stage++; + render(); + return toast('本阶段已确认。'); + case 'project-agent': + state.role = roles[state.stage][0]; + return navigate('agent'); + case 'project-settings': + return showDialog( + '项目设置', + ``, + `${btn('close', '取消', '')}${btn('save-project-settings', '保存', 'main-action')}`, + 'project-settings', + ); + case 'save-project-settings': + if (!$('#project-title-input').value.trim()) return toast('请填写名称。'); + state.projectTitle = $('#project-title-input').value; + close(); + render(); + return toast('样本项目设置已保存。'); + case 'new-project': + return showDialog( + '新建项目', + '
', + `${btn('close', '取消', '')}${btn('create-project', '创建并开始', 'main-action')}`, + 'new-project', + ); + case 'create-project': + if (!$('#new-project-name').value.trim()) + return toast('请填写项目名称。'); + state.projectTitle = $('#new-project-name').value; + state.script = '新的故事草稿。可以从智能体开始讨论,再带回这个项目。'; + state.confirmed = [false, false, false, false, false]; + state.stage = 0; + navigate('project'); + return toast('已创建样本项目。'); + case 'shot-edit': + editingShot = +e.dataset.shot; + return showDialog( + '编辑镜头', + `
`, + `${btn('close', '取消', '')}${btn('save-shot', '保存镜头', 'main-action')}`, + 'shot', + ); + case 'save-shot': + state.shotEdits[editingShot] = $('#shot-description').value; + close(); + render(); + return toast('镜头草稿已在样本中保存。'); + case 'shot-generate': + state.kind = 'video'; + state.wf = 'h3'; + state.attachments = ['assets/coast.jpg']; + state.drafts.h3 = { + positive: '镜头缓慢推进,海面自然流动,光线与建筑保持稳定。', + negative: '', + attachments: state.attachments, + }; + return navigate('create'); + case 'asset-filter': + state.assetFilter = e.dataset.filter; + return render(); + case 'asset-preview': + return assetPreview(+e.dataset.asset); + case 'asset-create': + state.kind = 'image'; + state.wf = 'edit'; + state.attachments = [ + assetCards()[selectedAsset].img.startsWith('blob:') + ? assetCards()[selectedAsset].img + : 'assets/' + assetCards()[selectedAsset].img, + ]; + state.drafts.edit = { + positive: '保持参考人物特征,调整为海边落日场景。', + negative: '', + attachments: state.attachments, + }; + return navigate('create'); + case 'task-filter': + state.taskFilter = e.dataset.filter; + return render(); + case 'flow-detail': + return showDialog( + '工作流文件', + `
这里展示原始文件名,创作台使用清晰的用途名称。正式导入时先核对输入映射和参数。

${esc(e.dataset.file)}

`, + `${btn('close', '返回目录', '')}${btn('import-workflow', '查看导入过程', 'main-action')}`, + 'flow-detail', + ); + case 'import-workflow': + return showDialog( + '导入与映射', + '
', + `${btn('close', '取消', '')}${btn('finish-import', '检查映射', 'main-action')}`, + 'import', + ); + case 'finish-import': + return toast('此处演示导入检查入口,样本不会执行或解析未知工作流。'); + case 'add-model': + case 'edit-model': + return openModels(e.dataset.modelName || ''); + case 'save-model': + if (!$('#model-name').value.trim()) return toast('请填写配置名称。'); + { + const name = $('#model-name').value; + const key = + state.modelTab === 'ComfyUI 连接' ? state.modelTab : '大模型'; + const i = state.modelProfiles[key].indexOf(editingModelName); + if (i >= 0) state.modelProfiles[key][i] = name; + else state.modelProfiles[key].push(name); + state.modelDetails[name] = { url: $('#model-url').value }; + } + close(); + render(); + return toast('样例配置已保存;没有测试真实接口。'); + case 'test-model': + return showDialog( + '连接测试', + '

这是隔离设计样本

这里展示连接结果的位置。接入正式接口后,会返回成功耗时或具体错误原因。

', + btn('close', '返回配置', 'main-action'), + 'test', + ); + case 'save-bindings': + $$('[data-role-model]').forEach( + (n) => (state.roleModels[n.dataset.roleModel] = n.value), + ); + return toast('样本角色绑定已保存。'); + case 'save-settings': + $('#system-form') + .querySelectorAll('[aria-label]') + .forEach( + (n) => (state.savedSettings[n.getAttribute('aria-label')] = n.value), + ); + return toast('样本设置已保存。'); + case 'cancel-settings': + render(); + return toast('已取消本次设置修改。'); + case 'save-node': + return; + case 'add-node': { + const n = document.createElement('article'); + n.className = 'node'; + n.style.cssText = 'left:20%;top:50%'; + n.innerHTML = + '
新的文本卡片↕ 拖动

双击编辑创作内容。

'; + $('#node-board').append(n); + return; + } + case 'zoom-in': + case 'zoom-out': + state.graphZoom = Math.max( + 0.7, + Math.min(1.3, state.graphZoom + (a === 'zoom-in' ? 0.1 : -0.1)), + ); + return $$('.node').forEach( + (n) => (n.style.transform = `scale(${state.graphZoom})`), + ); + case 'graph-reset': + state.graphZoom = 1; + return $$('.node').forEach((n) => (n.style.transform = '')); + default: + toast('该入口已保留在整体设计中。'); + } +} +document.addEventListener('click', (e) => { + const target = e.target.closest( + '[data-action],[data-page],[data-kind],[data-category],[data-pin],[data-option],[data-style],[data-stage],[data-param-value]', + ); + if (!target) return; + if ( + target.closest('#popover') === null && + !target.dataset.action?.startsWith('param-') + ) + closePopover(); + if (target.dataset.page) return navigate(target.dataset.page); + if (target.dataset.pin) { + const key = target.dataset.pin; + state.pins.has(key) ? state.pins.delete(key) : state.pins.add(key); + return renderDirectory(); + } + if (target.dataset.kind) { + saveDraft(); + stopPlayback(); + state.kind = target.dataset.kind; + state.results[state.wf] = state.result; + state.wf = state.kind === 'image' ? 'qwen' : 'h3'; + state.result = state.results[state.wf] || 'empty'; + state.search = ''; + state.category = '全部'; + state.attachments = state.drafts[state.wf]?.attachments || []; + state.compare = false; + return render(); + } + if (target.dataset.category) { + state.category = target.dataset.category; + renderContext(); + return; + } + if (target.dataset.style) { + styleDraft = +target.dataset.style; + $$('.style-card').forEach((b) => + b.classList.toggle('selected', +b.dataset.style === styleDraft), + ); + return; + } + if (target.dataset.stage) { + state.stage = +target.dataset.stage; + return render(); + } + if (target.dataset.paramValue) { + state.params[pendingParam] = target.dataset.paramValue; + closePopover(); + return render(); + } + if (target.dataset.option) { + const id = target.dataset.option; + if (state.page === 'create' && workflows.some((w) => w.id === id)) { + saveDraft(); + state.results[state.wf] = state.result; + state.wf = id; + state.result = state.results[id] || 'empty'; + stopPlayback(); + state.attachments = state.drafts[id]?.attachments || []; + return render(); + } + if (state.page === 'agent' && roles.some((r) => r[0] === id)) { + saveDraft(); + state.role = id; + return render(); + } + if (id.startsWith('skill-')) { + state.agentSkill = ['剧本创作', '角色一致性', '镜头提示词', '自定义技能'][ + +id.split('-')[1] + ]; + close(); + return render(); + } + if (id.startsWith('session-')) { + state.role = id.slice(8); + return navigate('agent'); + } + if (id.startsWith('model-')) { + state.modelTab = ['大模型', 'ComfyUI 连接', '角色绑定'][+id.slice(6)]; + return render(); + } + if (id.startsWith('setting-')) { + state.settingTab = ['生成队列', '智能体运行', '存储与记忆'][+id.slice(8)]; + return render(); + } + if (id === 'project-agent') return action(id, target); + if (id === 'project-assets') return navigate('library'); + if (id === 'project-canvas') return navigate('canvas'); + if (id.startsWith('filter-')) { + const i = +id.slice(7); + if (state.page === 'history') + state.taskFilter = ['全部', '进行中', '已完成', '失败'][i]; + else if (state.page === 'library') + state.assetFilter = ['全部', '全部', '全部', '角色'][i]; + else if (state.page === 'home') return toast('样例项目分组已保留。'); + return render(); + } + } + if (target.dataset.action) action(target.dataset.action, target); +}); +document.addEventListener('input', (e) => { + if (e.target.id === 'wf-search') { + state.search = e.target.value; + renderDirectory(); + } + if ( + e.target.id === 'positive' || + e.target.id === 'negative' || + e.target.id === 'agent-text' + ) + saveDraft(); + if (e.target.id === 'flow-search') + $('#flow-rows').innerHTML = flowRows( + window.catalog.filter((f) => + f.toLowerCase().includes(e.target.value.toLowerCase()), + ), + ); + if (e.target.id === 'asset-search') + $('#asset-grid').innerHTML = assetCards() + .map((s, i) => ({ ...s, index: i })) + .filter((s) => s.name.includes(e.target.value)) + .map((s) => assetCard(s, s.index)) + .join(''); + if (e.target.id === 'task-search') + $('#task-rows').innerHTML = history + .filter((r) => (r.name + r.wf).includes(e.target.value)) + .map(taskRow) + .join(''); + if (e.target.id === 'video-position') { + state.playTime = +e.target.value; + if ($('#sample-video')) $('#sample-video').currentTime = state.playTime; + } +}); +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') close(); + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + if (state.page === 'create') generate(); + else if (state.page === 'agent') sendAgent(); + } + if (e.key === 'Enter' && e.target.dataset.option) e.target.click(); +}); +document.addEventListener('pointermove', (e) => { + const opt = e.target.closest('.option'); + if (opt) { + const r = opt.getBoundingClientRect(); + opt.style.setProperty('--mx', e.clientX - r.left + 'px'); + opt.style.setProperty('--my', e.clientY - r.top + 'px'); + } +}); +$('#upload').addEventListener('change', (e) => { + const urls = [...e.target.files].map((f) => URL.createObjectURL(f)); + if (!urls.length) return; + if (e.target.dataset.slot === 'library') { + state.extraAssets.unshift( + ...urls.map((img, i) => ({ + img, + name: e.target.files[i].name, + type: '参考图', + })), + ); + render(); + toast('素材已选入样本,本次不会上传到正式服务器。'); + } else { + saveDraft(); + const slot = +e.target.dataset.slot; + state.attachments[slot] = urls[0]; + state.drafts[state.wf].attachments = state.attachments; + render(); + } + e.target.value = ''; +}); +$('#agent-upload').addEventListener('change', (e) => { + state.agentAttachments = [...e.target.files].map((f) => f.name); + render(); + toast('已添加 ' + state.agentAttachments.length + ' 份本地参考材料。'); + e.target.value = ''; +}); +$('#overlay').addEventListener('click', (e) => { + if (e.target === $('#overlay')) close(); +}); +$('#motion').onclick = () => { + document.body.classList.toggle('reduced'); + toast( + document.body.classList.contains('reduced') + ? '已减少动效。' + : '已恢复动效。', + ); +}; +$('#scenario').onclick = (e) => { + showDialog( + '体验不同使用情景', + `
${[ + ['landscape', '横图结果', '看作品区域与紧凑输入'], + ['portrait', '竖图结果', '检查长图不会压成细条'], + ['video', '首尾帧视频', '检查手动播放与双帧输入'], + ['empty', '首次创作', '没有历史或生成作品'], + ['failed', '生成失败', '错误原因、输入保留与重试'], + ['agent-result', '智能体已有回复', '检查草稿编辑与项目确认'], + ] + .map( + ([id, n, h]) => + ``, + ) + .join('')}
`, + '', + 'scenario', + ); +}; +document.addEventListener('click', (e) => { + const b = e.target.closest('[data-scenario]'); + if (!b) return; + saveDraft(); + close(); + stopPlayback(); + const s = b.dataset.scenario; + if (s === 'agent-result') { + state.page = 'agent'; + state.role = 'script'; + state.messages.script = [ + { who: 'user', text: '帮我完善旅行者和灯塔的故事。' }, + { + who: 'assistant', + text: '我整理了一版故事草稿,先确认人物动机和结尾。', + artifact: state.script, + }, + ]; + } else { + state.page = 'create'; + state.kind = s === 'video' ? 'video' : 'image'; + state.wf = s === 'video' ? 'h3' : 'qwen'; + state.result = s === 'video' ? 'landscape' : s; + if (s === 'portrait') state.params.aspect = '2:3'; + else if (s === 'landscape') state.params.aspect = '3:2'; + else if (s === 'video') state.params.aspect = '16:9'; + state.compare = false; + if (s === 'video') { + state.attachments = ['assets/coast.jpg', 'assets/zhiyuhuiben.jpg']; + state.drafts.h3 = { + positive: '镜头缓慢向前推进,保持首尾人物和光线一致。', + negative: '', + attachments: state.attachments, + }; + } + } + render(); +}); +let editingNode = null; +let drag = null, + drawing = false; +document.addEventListener('pointerdown', (e) => { + const node = e.target.closest('.node'); + if (node && e.target.closest('header')) { + const r = node.getBoundingClientRect(), + b = $('#node-board').getBoundingClientRect(); + drag = { node, x: e.clientX - r.left, y: e.clientY - r.top, b }; + node.setPointerCapture(e.pointerId); + } + if (e.target.id === 'mask-canvas') { + drawing = true; + e.target.setPointerCapture(e.pointerId); + } +}); +document.addEventListener('pointermove', (e) => { + if (drag) { + drag.node.style.left = + Math.max( + 0, + Math.min(drag.b.width - 200, e.clientX - drag.b.left - drag.x), + ) + 'px'; + drag.node.style.top = + Math.max( + 0, + Math.min(drag.b.height - 80, e.clientY - drag.b.top - drag.y), + ) + 'px'; + } + if (drawing && $('#mask-canvas')) { + const c = $('#mask-canvas'), + r = c.getBoundingClientRect(), + ctx = c.getContext('2d'); + ctx.fillStyle = '#00cae050'; + ctx.beginPath(); + ctx.arc( + ((e.clientX - r.left) * 560) / r.width, + ((e.clientY - r.top) * 320) / r.height, + 16, + 0, + Math.PI * 2, + ); + ctx.fill(); + } +}); +document.addEventListener('pointerup', () => { + drag = null; + drawing = false; +}); +document.addEventListener('dblclick', (e) => { + if (e.target.closest('.canvas-img')) action('enlarge', e.target); + const node = e.target.closest('.node'); + editingNode = node; + if (node) + showDialog( + '编辑画布内容', + ``, + `${btn('close', '取消', '')}${btn('save-node', '保存', 'main-action')}`, + 'node', + ); +}); +document.addEventListener('click', (e) => { + if (e.target.closest('[data-action=save-node]')) { + const n = editingNode; + if (n) n.querySelector('p').textContent = $('#node-editor').value; + close(); + toast('样本画布内容已保存。'); + } +}); +window.addEventListener('hashchange', () => { + const p = location.hash.slice(1); + if (p && pageNames[p] && p !== state.page) navigate(p); +}); +state.page = pageNames[location.hash.slice(1)] + ? location.hash.slice(1) + : 'create'; +icons(); +render(); diff --git a/design/prototypes/reframe-20261014/index.html b/design/prototypes/reframe-20261014/index.html new file mode 100644 index 00000000..c212ff31 --- /dev/null +++ b/design/prototypes/reframe-20261014/index.html @@ -0,0 +1,70 @@ + + + + + + AIGC · 创作空间重设计 + + + +
+ +
+ +
+ 交互样本 +
+
+ +
+
+ + +
+ + + + + diff --git a/design/prototypes/reframe-20261014/verification.json b/design/prototypes/reframe-20261014/verification.json new file mode 100644 index 00000000..dc046038 --- /dev/null +++ b/design/prototypes/reframe-20261014/verification.json @@ -0,0 +1,59 @@ +{ + "layout_and_interaction": { + "checks": [ + "1024×600 画布至少60%,输入不超过1/3,主按钮完整", + "1366×768 画布至少60%,输入不超过1/3,主按钮完整", + "1600×900 画布至少60%,输入不超过1/3,主按钮完整", + "2048×1152 画布至少60%,输入不超过1/3,主按钮完整", + "长提示词不撑高底座", + "置顶不切换工作流、不清空草稿", + "视频没有自动播放", + "不同工作流草稿独立", + "历史不参与画布布局", + "完整参数取消不应用", + "常用参数原地修改", + "生成时保留旧结果", + "新生成采用竖图显示", + "竖图没有压成横条", + "只有手动操作才播放", + "切换结果暂停播放", + "助手有可编辑草稿卡", + "草稿进入项目并等待确认", + "分镜有完整工作区域", + "home 页面可直接操作", + "home 小窗口不横向溢出", + "library 页面可直接操作", + "library 小窗口不横向溢出", + "history 页面可直接操作", + "history 小窗口不横向溢出", + "flow 页面可直接操作", + "flow 小窗口不横向溢出", + "models 页面可直接操作", + "models 小窗口不横向溢出", + "canvas 页面可直接操作", + "canvas 小窗口不横向溢出", + "settings 页面可直接操作", + "settings 小窗口不横向溢出", + "真实仓库目录可搜索", + "无页面脚本错误" + ], + "errors": [] + }, + "state_and_real_video": [ + "任务快照固定原工作流和原提示词", + "不同工作流完成不替换当前空态", + "历史复用准确填入目标工作流", + "设置保存后跨页保留", + "设置取消恢复已保存值", + "角色模型独立", + "非故事草稿确实带回项目", + "画布编辑对应对象", + "素材用途筛选准确", + "模型保存确实加入列表", + "实际视频初始暂停", + "实际视频仅点击后播放", + "修改参数不切换播放状态", + "实际视频手动暂停" + ], + "scope": "独立样本;不调用生产接口,不运行仓库 JSON 工作流。" +} \ No newline at end of file diff --git a/design/prototypes/reframe-20261014/设计依据与验收.md b/design/prototypes/reframe-20261014/设计依据与验收.md new file mode 100644 index 00000000..2dd0ae1d --- /dev/null +++ b/design/prototypes/reframe-20261014/设计依据与验收.md @@ -0,0 +1,55 @@ +## 重新设计的依据 + +本轮交付为独立可操作设计样本,覆盖现有功能的使用方式。正式站暂保留原版本,样本通过后再接真实接口。 + +### 观察到的参考站行为 + +- 左侧目录独立滚动,主工作区固定在一个视口内。图片/视频输入工具约 169px 高,内部长文本滚动,不随内容无限长高。 +- 高频参数在输入框下方的胶囊按钮就近展开。例如数量在触发按钮上方打开 200px 宽选择层;没有为了改一个数字打开整页表单。 +- 任务列表是独立浮层;任务记录不常驻占据创作页面的纵向空间。当前输入和历史浏览是两个状态。 +- 智能体首屏突出用途和输入,风格/工具/时长集中在输入框底部。进入、悬停、聚焦反馈属于同一个界面语言。 +- REA 观察证据:`ev_5d5ffc7062788e889fdda8d96e1cb4feba69118daa74fdeeff64c21e7b9ebf2a`、`ev_4bd13d781f2c57613fc580e387d18d70900c19ba8f907a035ed725d19881a5aa`。几何与交互由共享浏览器的 Playwright 实测补充,REA 本身没有点击页面。 +- 未提交收费生成,因此未声称验证参考站的生成质量、完整成片流水线或服务器内部实现。 + +### 原版为什么失败 + +| 修改前 | 重设计 | 原因 | +| --- | --- | --- | +| 结果、参数详情、输入回显和历史同时占高度 | 结果画布+固定输入底座;详情和历史分别按需打开 | 图片不再争夺剩余高度 | +| 高度不足时图片压到 110px | 画布由剩余高度确定,作品以原比例适配;其他面板不参与画布高度 | 竖图也按高度充分展示 | +| 输入素材和长提示词撑高主面板 | 素材缩略图一行;提示词内部滚动,正反向平行 | 填写内容不会改变结果大小 | +| 同一参数多个入口、详情默认展开 | 高频参数就地修改;完整参数一次集中设置 | 减少搜索与往返 | +| 工作流是原始文件名大卡片 | 可搜索的紧凑目录,用途分类,置顶;原名在详情保留 | 目录容量与可读性分开处理 | +| 智能体回复只是消息 | 草稿有编辑、保存和确认位置,生成过程与成果区分 | 用户知道下一步该在哪里做 | +| 每页都套同一种英雄区 | 创作画布、对话、文稿、素材格、管理表各有适合任务的结构 | 页面服从当前工作 | + +### 统一规则 + +1. 全局导航只负责去哪里;上下文栏只负责当前区域的对象,不再重复总导航。 +2. 生成页第一视觉是作品;主按钮固定在输入底座;任何状态都保留输入草稿。 +3. 图片/视频切换和不同工作流各自保存草稿;置顶只改变排序。历史查看不自动覆写草稿,复用需显式点击。 +4. 普通参数 1 次点击就能调整;完整设置先暂存,保存生效、取消丢弃设置草稿。 +5. 空态、运行、失败、成功具有明确内容;旧结果在新任务开始时保留,不把进度伪装成作品。 +6. 视频进入页面和切换结果均暂停,播放是独立按钮;画面点击仅放大,绝不同时改变播放状态。 +7. 只有本次多张结果显示本次选择器;所有历史在任务记录入口查看。 +8. 文案用用途与动作命名,原始工作流文件名和技术配置置于管理层。 +9. 管理页为列表/表格与详情编辑;项目页为阶段与成果;智能体页为会话与草稿;创作页为作品与输入。 +10. 颜色采用参考站实测暗色基底、青色导航、金色主动作、紫色智能体聚焦;高亮有主次,作品本身提供大面积颜色。 + +### 可验收的样本操作 + +创作台:图片/视频切换、目录搜索、分类、置顶、独立草稿、正反向、素材上传、首尾帧、就地参数、保存/取消、历史独立查看/显式复用、大图与对比、手动播放、模拟运行/取消/失败重试。 + +智能体:选择五个现有角色、风格与技能选择、模型绑定、附件、独立会话、回复草稿编辑与保存;不新增切镜、MV、十二步流程。 + +项目:五阶段浏览、稿件编辑/确认、分镜列表/图片与视频结果,素材入口、对应智能体跳转。 + +其他页面:项目首页、素材库、工作流管理、任务历史、模型与连接设置、画布、系统设置。演示中全部明确使用样例数据,不读写正式账号或调用收费模型。 + +### 检查标准 + +- 桌面 1024×600、1366×768、1600×900、2048×1152 无主页面横向或纵向滚动;目录/文本/表格可独立滚动。 +- 创作底座不超过工作区高度的三分之一;当前作品区域至少占工作区剩余高度的六成。 +- 长提示词、历史打开、参数详情均不挤压画布;普通进入时播放保持暂停。 +- 每页主操作不藏在页面底部;弹层有标题、返回/关闭、保存/取消规则。 +- 浏览器交互检查和人工看图均通过后,再交用户体验确认。 diff --git a/docs/HEL-665-creative-journey.md b/docs/HEL-665-creative-journey.md new file mode 100644 index 00000000..817c836d --- /dev/null +++ b/docs/HEL-665-creative-journey.md @@ -0,0 +1,30 @@ +# HEL-665 创作流程重做(2026-10-13) + +## 本轮范围 + +用户确认按新的操作规则重做 ComfyUI 完整创作路径。前端基于 `feat/hel-665-refract@ac1c0f9`;保留既有工作流解析、输入映射、上传、队列和项目回流接口。 + +- 创作区按「选择工具 → 准备素材 → 开始生成 → 查看结果」组织。 +- 工具选择在工作区内完成,先查看真实输入要求,再确认使用。取消选择保留输入。 +- 左侧表单独立滚动,提交按钮与阻止提交的原因固定可见。常用参数直接展示;高级参数折叠,服务配置另设入口。 +- 右侧完整展示结果,历史改为紧凑记录条;矮窗口保留明确的记录入口,详细记录在可滚动窗口内查看,给结果操作留足空间。当前排队/运行任务可显式取消。 +- 视频默认暂停,结果切换时只有一个播放器;播放/暂停及全屏按钮显式显示,取消页面级空格/方向键/删除键副作用;其他页面共用的媒体放大窗口也取消自动播放。 +- 媒体网格使用 `minmax(0, 1fr)`,防止视频的固有尺寸撑大网格行、被外框裁掉播放控件。 +- 本标签页草稿按类型、项目来源和入口隔离,恢复工具、描述、参数与已上传文件引用。来源提示改变时使用新来源。入口变化重建编辑器,避免串项目;详情先返回时,迟到的目录不会覆盖恢复选择。 +- 共用壳层去掉刚性最小宽度,创作区按实际窗口剩余高度分配空间。 + +没有改服务端业务和数据库,也没有重新提交测试站用户的任务。 + +## 验证与界限 + +- `npm run check`:0 错误,2 条原有警告;`npm test` 原有四组检查通过;`npm run build` 通过。 +- `e2e/refract.mjs` 使用独立本地数据库及假 ComfyUI,覆盖真实 API 提交、首尾帧独立上传、输入保留、回存和重载、显式播放、工具确认、矮窗口、目录延迟与草稿隔离。 +- 窗口包括 1366×768、1280×720、1100×600、960×540、1920×1080。验证视频完整边界、播放区及生成按钮均在视口内。150% 的等效缩放检查使用 960×540 逻辑视口和 1.5 像素密度,不冒充操作系统缩放实测。 +- 总工独立复核使用浏览器内响应替换模拟 30 项参数与 60 条记录;确认长表单与记录分别滚动、播放可控。 +- 真实 Qwen 工作流来自测试站 `qwen2.1`,完整图及输入映射复制到本地临时数据库,绑定实际 `192.168.200.12:8188`。从新版表单提交 0.3 百万像素、8 步的蓝色陶瓷杯检查,经真实 ComfyUI 生成图片并回存本地来源项目。临时任务与项目清理完成;没有写测试站项目库。此检查证明这条路径跑通,不证明所有工作流或模型的生成质量。 +- H3 两种实际工作流也复制到本地用于输入界面检查;本轮没有再做真实 H3 GPU 生成。 + +## 部署 + +只替换前端构建及对应源码,保留先前 demo。新构建保留旧版不可变脚本,避免正在打开的页面因脚本文件切换而失效。 +部署与回退均不重启后端,避免影响正在执行的生成任务。旧前端、版本记录、回退脚本保存在测试服务器 `/opt/aigc-home/releases`。 diff --git a/docs/HEL-665-refract.md b/docs/HEL-665-refract.md new file mode 100644 index 00000000..37f0d0f4 --- /dev/null +++ b/docs/HEL-665-refract.md @@ -0,0 +1,49 @@ +# HEL-665 折光工作室实施记录 + +## 范围与基线 + +用户于 2026-10-11 确认「折光工作室」交互 demo,要求本人接入真实网站。 +代码基于测试站 `deploy/hel-691@2b3bbf9`,保持该版本的批量导入、输入映射、首尾帧和项目回流能力。 +只面向桌面使用;本次没有改后端业务代码、数据库结构、模型连接或线上用户数据。 + +## 已接入的设计 + +- 暖纸色 `#f4f2ed`、钴蓝 `#354fe0`、淡柠檬与暖粉的角色辅助色。 +- 六个带名称的导航入口:工作室、我的项目、创作台、灵感画布、素材与工作流、智能体。 +- 首页摄影拼贴、弹簧反馈、新建/导入真实项目、真实项目封面和阶段进度。 +- 项目五阶段改为左侧竖向导航,作品内容居中,搭档及阶段任务在右。 +- 图片/视频创作采用大预览与右侧输入。按工作流真实输入生成首尾帧、参考图、遮罩与参数。 +- 工作流弹窗与独立目录:类别、模型、关键词、收藏、最近使用,48 条增量加载。 +- 批量导入、映射、启停和试运行仍从「导入与管理」进入。 +- 使用真实结果文件进行画面对比、放大、下载、视频播放与尾帧导出。 +- 智能体角色卡接入原有真实对话与技能编辑。画布及镜头构图恢复真实路由并统一壳层。 +- 系统/手动减少动效、键盘搜索、弹窗焦点返回与按钮按压反馈。 + +生产页面不含 demo 的假项目、模拟生成、预设聊天与样本工作流记录。 +首页两张摄影只作为固定的品牌插画;项目封面、素材和生成结果均来自实际记录。 + +## 首页摄影出处 + +- 海岸:https://images.unsplash.com/photo-1518837695005-2083093ee35b +- 建筑:https://images.unsplash.com/photo-1511818966892-d7d671e672a2 + +图片已随构建保存在站点本地,无外站图片请求。以上图片延续用户确认的 demo。 + +## 验证 + +- `npm run check`:0 错误;2 条原有警告(镜头视频字幕与 div 自闭合)。 +- `npm test`:存储、随机 ID、技能正文和尾帧算法四组检查通过。 +- `npm run build`:静态构建通过。 +- `e2e/refract.mjs`:33/33 通过;独立本地 API + 假 ComfyUI;涵盖真实项目上下文、提交、回存与重载、画面对比、首尾帧上传、视频播放、收藏、目录导入、五阶段与五角色、画布、1280/1440/1920 桌面及减少动效;新增云端目录回车隔离,以及首次切换工作流保留提示词与首尾帧。 +- 测试只在本地临时数据库操作,流程生成的项目、工作流与任务在 finally 中清理。 + +运行浏览器检查前启动现有 `e2e/fake_comfy.py`、本地后端 8247 与 Vite 5173,运行 `e2e/seed.py`,并通过批量导入导入仓库的本地工作流。脚本拒绝向非 localhost API 写测试数据。 +`PLAYWRIGHT_MODULE_PATH`、`CHROMIUM_EXECUTABLE_PATH` 可指向已安装的浏览器测试依赖。 + +真实 ComfyUI/GPU 或付费云模型最终生成质量不由假服务检查证明,需要实际服务在线时验证。 + +## 测试站部署 + +部署只替换前端静态构建及对应前端源码,保留原有 demo URL、后端与数据库。 +部署前把旧静态目录和前端源码归档至 `/opt/aigc-home/releases`,另保留原目录副本与部署版本记录。 +完整回退命令见测试服务器上对应的 `rollback-HEL665-refract-*.sh`。 diff --git a/docs/changelogs/2026-10-11-hel682-s4-workflow-import-admin.md b/docs/changelogs/2026-10-11-hel682-s4-workflow-import-admin.md new file mode 100644 index 00000000..ba36df50 --- /dev/null +++ b/docs/changelogs/2026-10-11-hel682-s4-workflow-import-admin.md @@ -0,0 +1,40 @@ +# S4:工作流批量导入向导与管理页(HEL-682) + +复用 `/connections` 工作流库,接入 S2(HEL-681)的数据层端点:批量导入向导 + +元数据轻量管理列表。本批只动 `calliope-web`,后端零改动。 + +## 批量导入向导(`WorkflowBatchImportWizard.svelte`) + +- 三步式抽屉(780px):选择来源 → 预检报告 → 导入结果。 +- 来源两种:扫描服务器目录(`POST /api/workflows/import-scan`,默认 + `example_ComfyUI_workflows`,可选对真实 ComfyUI 做 L2 预检)或本地多选 + 文件(客户端解析,非 UI 格式自动忽略,`POST /api/workflows/convert`)。 +- 预检报告逐文件给出 ok/warn/fail、转换提示、建议元数据(用途/分类/模型 + 家族/输入输出媒介);warn 项可就地补充用途(目录模式在导入后 PATCH 到 + 新行);「需人工确认」与转换失败项不可勾选、不会被导入、永远不被标作 + 可运行。 +- 重复导入按内容去重:重复执行全部 conflict 跳过,界面明示「已存在」。 + +## 管理列表改元数据驱动(`WorkflowLibrary.svelte`,自 connections 页抽出) + +- 列表数据源换成 `GET /api/workflows?view=meta`(无 workflow_json / + input_schema,152 条约 90KB),完整 JSON 只在试运行、输出指定等操作时 + 按需单条加载并缓存。 +- 工具栏:搜索(`/` 聚焦)、类型/收藏/待确认/停用筛选、分类/模型家族/ + 媒介下拉、收藏/最近与名称排序、清除筛选;行内:分类与模型家族标签、 + 输入→输出媒介图标、收藏星标、启停开关(用途/输出未 settle 时禁用并 + 提示)、试运行(复用 `WorkflowTestDialog`)、L2 复查、绑定连接、删除; + 分页渲染(60/批,「再显示」)。 +- 批量:勾选 + 全选 → 批量标注(查找替换重命名、统一说明、追加标签、 + 分类/模型家族)与批量启停。 +- 新增去重入口(`POST /api/workflows/dedupe`,字节级相同才删,保留最早)。 +- 原有能力保留:用途确认下拉、输出节点指定(HEL-638)、单个 API 格式 + 导入抽屉(HEL-655)。 + +## 其他 + +- `api.ts`/`comfy/types.ts`:`listMeta/convert/importBatch/importScanDry/ + importScanCommit/touch/dedupe` 客户端与 `WorkflowMeta` 等类型;`update` + 载荷支持 favorite/tags/category/model_family。 +- i18n:`wl.* / md.* / wiz.* / wfCat.*` 共 130 键 × 7 语言;分类展示用 + 标签映射,不把 30 字目录名暴露给用户。 diff --git a/docs/changelogs/2026-10-11-hel683-s4-desk-console.md b/docs/changelogs/2026-10-11-hel683-s4-desk-console.md new file mode 100644 index 00000000..a5dc840a --- /dev/null +++ b/docs/changelogs/2026-10-11-hel683-s4-desk-console.md @@ -0,0 +1,46 @@ +# S4:三段式图片 / 视频生成台(HEL-683) + +按 HEL-679 已确认的三张融合样稿,把 `/image` 与 `/video` 两个入口接入同一 +个三段式生成台。本批只动 `calliope-web`,生成后端与项目回流(S5)零改动。 + +## 三段式布局(新增 `components/desk/`) + +- `StudioDesk.svelte` 取代 `StudioGenerate.svelte` 成为 `/image`、`/video` + 的共用页面(薄壳不变,`kind` 决定任务模式);右栏沿用既有 + `Composer / SlotTray / Inspector / TakeFeed / ContextBar`,仅重排布局。 +- 左栏 `TaskModeRail.svelte`:任务模式按真实工作流统计计数,未覆盖模式置灰; + 底部收藏 / 最近使用直达;≤760px 退化为横向模式条。 +- 中栏挑选台 `WorkflowBay.svelte`(含 `LibraryFilters / LibraryRow / + InputRequirementBadge`):搜索、本机 / 云端来源分段、按模型家族分组、 + 收藏过滤、待确认计数与入口;长列表增量渲染(48/批)+ `content-visibility`, + 键盘 ↑↓/J/K 游走、Enter 使用、Esc 关闭。 +- 挑选时中栏展开(grid 列宽动画,`data-reduce` 下直接跳变),右侧显示 + `WorkflowPreview.svelte` 输入要求预览(S2 元数据 + 按需加载的槽位摘要); + 选定后收成摘要带(band),一键重新展开。≤1179px 挑选台为全屏浮层。 +- 云端来源是诚实占位:明确标注「云端生成未接入」,不造可点击的虚假能力; + 数据结构按 `source: 'comfy' | 'cloud'` 预留。 + +## 数据与路由 + +- 挑选台 / 任务模式 / 摘要带全部走 `GET /api/workflows?view=meta` 轻量元数据 + (150+ 条不下载 workflow_json);完整记录改为按 id 惰性加载(当前工作流、 + 记录流里出现的工作流、预览行),feed 名称先用元数据桩、schema 到位后补全, + 「工作流已删除」判定以元数据为准,不在加载期误报。 +- 新增查询参数:`?wf=` 深链指定工作流、`?mode=` 预选任务模式; + 五阶段 `deskHref` 的 `from=workbench` 上下文条与返回路径保持不变。 +- Composer 的工作流芯片从 380px 下拉弹层改为展开挑选台(`#desk-wf` 语义 + 不变,仍是缺工作流时的定位目标);`WorkflowPicker.svelte` 删除。 +- 最近使用沿用后端入队时写入的 `last_used_at`(queue/manager 原有逻辑), + 提交后刷新轻量列表即可。 + +## 验证 + +- `npm run check`(0 错误,2 条基线既有警告)、`npm run test`、`npm run build` + 通过;prettier 对本批文件通过(仓库 lint 基线因 prettier 3.9 全量重排 + + 无 eslint 配置本就不可用,未扩面修复)。 +- `e2e/shoot.mjs` 全绿:挑选台键盘链(展开→搜索→↑↓→Enter→调参→提交)、 + SSE 状态语义、删除撤销、任务页、窄屏无溢出、减动效;同时把 7 处 S1 灰阶 + 化后未更新的旧色值断言修正为 theme-1 实际值(定影文案 + 灰阶信号色)。 +- `e2e/lastframe.mjs` 全绿(视频检视、尾帧导出、手机弹层无回归)。 +- 手工走查:`?wf` / `?mode` / `from=workbench` 上下文预填与返回、1024/390 + 无横向溢出,截图见 `e2e/shots/hel683-*.png`。 diff --git a/docs/changelogs/2026-10-11-hel684-s5-project-flowback.md b/docs/changelogs/2026-10-11-hel684-s5-project-flowback.md new file mode 100644 index 00000000..7fca86b0 --- /dev/null +++ b/docs/changelogs/2026-10-11-hel684-s5-project-flowback.md @@ -0,0 +1,50 @@ +# S5:生成结果回流原项目(HEL-684) + +在 S4 三段式生成台基础上,让从项目五阶段资产 / 镜头进入生成台的结果可以 +回流原项目。沿用现有 `DeskContext` 与 attach 语义,增量改动:生成请求可携带 +可选项目上下文,结果卡提供明确的「回流到源项目」动作与返回提示;独立 +playground 生成行为保持原样。本批后端只改 `playground.py`,前端不重写任何 +生成 / 项目业务。 + +## 后端(`calliope/routers/playground.py`) + +- `PlaygroundGenerate` 新增可选 `context: {project_id, stage, source_kind, + source_id, label}`。入队前逐项校验真实性:项目存在且非 playground 隐藏 + 项目、阶段内容里确有该资产 / 镜头行、阶段与生成类型匹配(assets→image、 + shot→video)——任何不符直接 4xx,绝不猜测或静默记录来源。任务本身仍挂在 + playground 项目上,记录流 / SSE / 任务页行为不变;校验通过的来源以 + `payload.workbench` 戳进任务。 +- 新增 `POST /api/playground/attach-workbench`:把一条已完成 take 回流到其 + 记录的真实来源行。落库形态复用工作台原生展示链路——插入一条 + `payload.source='workbench'` + `target_id` 的 done 任务行,`_enrich_stage` + 既有逻辑即把产物显示在资产 / 镜头卡上(与流程内生成同一机制,之后流程内 + 重新生成会自然接管显示)。幂等:重复回流返回既有链接行,不产生重复; + 源行已因阶段重新生成消失时 409 拒绝,不误写。完成后发 `job.completed` + + `asset.ready`,打开着的工作台页即时刷新。 +- `GET /api/playground/jobs` 为已回流 take 附 `workbench_attach` 标记 + (服务端真值,重载后界面仍如实显示「已回流」)。 +- `DELETE /api/playground/jobs/{id}` 在删除产物文件时同步清掉由该 take 建立 + 的回流链接行(与既有 `_clear_entity_refs` 同理),项目行不会指向已删文件。 + +## 前端(`calliope-web`) + +- `generate/context.ts`:`DeskContext` 增加可选 `sourceKind/sourceId`, + `deskHref/readDeskContext` 透传(URL `source_kind/source_id`);不完整或 + 不自洽的旧链接自动退回「仅预填」行为。新增 `workbenchContextOf` 只在来源 + 完整且台类型与阶段匹配时给出请求上下文。 +- 工作台 `AssetsStagePanel / ShotStagePanel` 的「在生成台调参」链接带上真实 + 行标识;`ContextBar` 有来源时提示「可在结果卡回流」,无来源保持原文案。 +- `StudioDesk` 提交时携带上下文(关闭来源条 = 独立生成,不写项目); + `TakeCard` 为带真实来源的完成 take 提供「回流到源项目」按钮,回流后显示 + 「已回流」标记 + 「返回项目」直达链接;i18n 9 键 × 7 语言。 + +## 验证 + +- 后端 `pytest`:新增 `tests/test_playground_workbench_flowback.py` 8 例 + (上下文透传 / 拒假 / 回流 / 幂等 / 重建后拒写 / 流程内接管 / 删除清理), + 全量 829 passed,4 个失败为 S2 起既有基线(已用基线代码对拍确认与本批无关)。 +- 前端 `npm run check`(0 错误,2 条基线既有警告)、`npm run test`、 + `npm run build` 通过。 +- e2e(fake_comfy 全新库逐套跑):新增 `e2e/flowback.mjs` 19 检查全过 + (上下文条提示→提交→回流→已回流重载→返回项目见产物→不回流不误写→独立 + 无动作→视频镜头路径);`shoot.mjs` 56 检查、`lastframe.mjs` 全过。 diff --git a/docs/changelogs/HEL-665-v5.md b/docs/changelogs/HEL-665-v5.md new file mode 100644 index 00000000..95204e20 --- /dev/null +++ b/docs/changelogs/HEL-665-v5.md @@ -0,0 +1,17 @@ +## 第五版操作设计实装 + +白栖知在 HEL-665 确认第五版交互样本后,总管亲自接入正式功能。实现以项目既有用途组织页面。 + +- 创作台以作品画布为主,提示词保留在固定底座内滚动。生成历史、作品详情、素材和完整设置分别打开;常用参数在触发位置展开并允许取消。多件输出只切换本次生成作品,不插入历史。 +- 工作流的输入、端点、显示结果相互独立。草稿按创作类型、项目来源和工作流保存到当前浏览器会话;历史复用同步切换工作流和端点。上传与提交期间暂不切换工作流。 +- 智能体把会话与可编辑成果并排显示。输入与附件按角色和会话缓存,编辑成果按消息缓存。故事保存为项目待确认草稿;其他助手的自由文本保存为对应阶段的助手建议。 +- 助手建议使用现有阶段 JSON 存储,不需要数据库迁移。建议保存不改变阶段状态;确认时校验并只快照正式结构化内容,恢复快照保留后续建议。正式生成后的阶段内容保留原建议。 +- 项目固定五阶段导航、内容区与底部确认操作;素材、工作流、模型和设置采用图库、目录与集中列表。模型编辑使用统一模态焦点规则,嵌套弹窗只由最上层处理键盘。 + +## 验证 + +在隔离后端连接模拟 ComfyUI 和大模型,验证真实 HTTP、上传、队列、事件和项目保存链路,不调用收费模型。四种桌面尺寸为 1600×1000、1440×900、1280×720、960×640。主回归涵盖 49 项操作,另补竖图、遮罩、不同端点复用、异步任务与会话隔离检查。阶段生命周期与建议单元测试、现有前端校验、类型检查和静态构建均需通过后部署。 + +## 范围与交付 + +不新增切镜复刻、音乐 MV 或漫剧十二步,不批量启用未映射工作流。三维搭景与工作流试验台保留原有能力,本次未计为完成复刻。服务器用户数据和密钥配置不改;部署保留静态页面、源代码、workbench 路由备份及回滚脚本,原演示样本保留。代码继续更新现有合并请求,合并和归档等待用户验收。 diff --git a/e2e/fake_comfy.py b/e2e/fake_comfy.py index 38e6883d..108743f1 100644 --- a/e2e/fake_comfy.py +++ b/e2e/fake_comfy.py @@ -69,7 +69,8 @@ class Handler(BaseHTTPRequestHandler): src = read_mode().get("video_file") self._raw(200, Path(src).read_bytes() if src else MP4.read_bytes(), "video/mp4") else: - self._raw(200, PNG_1PX, "image/png") + src = read_mode().get("image_file") + self._raw(200, Path(src).read_bytes() if src else PNG_1PX, "image/png") return self._json(404, {"error": "not found"}) @@ -87,6 +88,8 @@ class Handler(BaseHTTPRequestHandler): no_outputs = mode.get("no_outputs") is True video_file = mode.get("video_file") out_name = (Path(video_file).stem + ".mp4" if video_file else "out-1.mp4") if videos else "out-1.png" + if mode.get("unique_filename"): + out_name = pid + "-" + out_name key = "videos" if videos else "images" outputs = {} if no_outputs else { self._output_node(body): {key: [{"filename": out_name, "subfolder": "", "type": "output"}]} diff --git a/e2e/flowback.mjs b/e2e/flowback.mjs new file mode 100644 index 00000000..f8a1a9f8 --- /dev/null +++ b/e2e/flowback.mjs @@ -0,0 +1,216 @@ +/* HEL-684 S5 browser validation against the isolated stack: + * vite dev (5173) → backend (8247) → fake ComfyUI (18188). + * Covers: context bar hint, submit carries the workbench context, the + * explicit 回流到源项目 action, the attached state surviving reload, + * the artifact landing on the workbench source row, the cancel path + * (context take, no attach → project untouched) and the independent + * path (no context → no attach action). */ +import { chromium } from 'playwright'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.dirname(fileURLToPath(import.meta.url)); +const SHOTS = path.join(ROOT, 'shots'); +fs.mkdirSync(SHOTS, { recursive: true }); + +const API = 'http://127.0.0.1:8247'; +const MODE_FILE = path.join(ROOT, 'fake_mode.json'); +const setMode = (m) => fs.writeFileSync(MODE_FILE, JSON.stringify(m)); + +let failures = 0; +function ok(name, cond, extra = '') { + const line = `${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ' — ' + extra : ''}`; + console.log(line); + if (!cond) failures++; +} + +const api = async (p, init) => { + const r = await fetch(API + p, { + headers: { 'Content-Type': 'application/json' }, + ...init, + }); + const body = await r.text(); + try { + return JSON.parse(body); + } catch { + return { raw: body, status: r.status }; + } +}; + +async function waitFor(fn, timeout = 30000, step = 300) { + const deadline = Date.now() + timeout; + while (Date.now() < deadline) { + const v = await fn(); + if (v) return v; + await new Promise((r) => setTimeout(r, step)); + } + return null; +} + +const run = async () => { + setMode({ mode: 'ok', delay_sec: 0 }); + + // ---- isolated project with real stage rows ---- + const proj = await api('/api/projects', { + method: 'POST', + body: JSON.stringify({ title: '回流验证项目' }), + }); + const patch = await api(`/api/workbench/projects/${proj.id}/stages/assets`, { + method: 'PATCH', + body: JSON.stringify({ + content: { + assets: [ + { + id: 'asset-e2e', + kind: 'character', + name: '林夏', + description: '', + prompt: 'a stoic courier in the rain', + negative_prompt: '', + }, + ], + }, + }), + }); + ok('准备:资产阶段有真实行', patch.ok === true); + const shotPatch = await api(`/api/workbench/projects/${proj.id}/stages/shot`, { + method: 'PATCH', + body: JSON.stringify({ + content: { + shots: [ + { + id: 'vshot-e2e', + shot_no: 'S1', + description: '', + prompt: 'slow push in on the courier', + duration_sec: 5, + }, + ], + }, + }), + }); + ok('准备:镜头阶段有真实行', shotPatch.ok === true); + + const browser = await chromium.launch(); + const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } }); + const page = await ctx.newPage(); + page.on('pageerror', (e) => console.log('PAGEERROR:', e.message)); + + // ---------- 1. 从资产行进入生成台:上下文条给出回流提示 ---------- + const deskUrl = + `http://127.0.0.1:5173/image?from=workbench&project=${proj.id}&stage=assets` + + `&label=${encodeURIComponent('角色「林夏」')}&prompt=${encodeURIComponent('a stoic courier in neon rain')}` + + `&source_kind=asset&source_id=asset-e2e`; + await page.goto(deskUrl); + await page.waitForSelector('#desk-prompt', { timeout: 15000 }); + const note = await page.locator('.context-bar .note').textContent(); + ok('上下文条提示可回流', (note || '').includes('回流'), note); + ok('上下文条预填提示词', (await page.inputValue('#desk-prompt')).includes('stoic courier')); + await page.screenshot({ path: `${SHOTS}/hel684-01-desk-context.png` }); + + // ---------- 2. 提交带上下文的生成 → 完成 → 出现「回流到源项目」 ---------- + await page.click('.a-btn.primary'); // 生成 + const job = await waitFor(async () => { + const jobs = await api('/api/playground/jobs'); + return jobs.find((j) => j.status === 'done' && j.output_paths.length && JSON.stringify(j.payload?.workbench ?? {}).includes('asset-e2e')); + }); + ok('生成任务完成且携带真实来源(payload.workbench)', !!job, job ? `job ${job.id}` : 'not found'); + await page.waitForTimeout(1200); + const take = page.locator(`.take[data-job="${job.id}"]`); + await take.scrollIntoViewIfNeeded(); + const attachBtn = take.locator('button.attach'); + ok('结果卡出现「回流到源项目」动作', (await attachBtn.count()) === 1); + await page.screenshot({ path: `${SHOTS}/hel684-02-attach-action.png` }); + + // ---------- 3. 点击回流 → 已回流 + 返回项目 ---------- + await attachBtn.click(); + const attachedTag = take.locator('.actions .a-tag', { hasText: '已回流' }); + await attachedTag.waitFor({ timeout: 15000 }); + ok('回流后结果卡显示「已回流」', (await attachedTag.count()) === 1); + const backLink = take.locator('.actions a', { hasText: '返回项目' }); + ok('回流后提供「返回项目」链接', (await backLink.count()) === 1); + const overview1 = await api(`/api/workbench/projects/${proj.id}`); + const row1 = overview1.stages.find((s) => s.stage_key === 'assets').content.assets[0]; + ok('项目资产行挂上回流产物', row1.job && row1.job.output === job.output_paths[0], JSON.stringify(row1.job || {})); + await page.screenshot({ path: `${SHOTS}/hel684-03-attached.png` }); + + // ---------- 4. 重载后仍是已回流(服务端标记,非客户端记忆) ---------- + await page.reload(); + await page.waitForSelector(`.take[data-job="${job.id}"]`, { timeout: 15000 }); + await page + .locator(`.take[data-job="${job.id}"] .actions .a-tag`, { hasText: '已回流' }) + .waitFor({ timeout: 15000 }); + ok('重载后仍显示「已回流」', true); + + // ---------- 5. 返回项目看到产物 ---------- + await page.locator(`.take[data-job="${job.id}"] .actions a`, { hasText: '返回项目' }).click(); + await page.waitForURL(new RegExp(`/workbench/${proj.id}.*stage=assets`), { timeout: 15000 }); + await page.waitForSelector('[data-testid="asset-grid"] .asset-card img', { timeout: 15000 }); + ok('工作台资产卡显示回流图片', true); + await page.screenshot({ path: `${SHOTS}/hel684-04-workbench-row.png`, fullPage: false }); + + // ---------- 6. 取消回流:带上下文生成但不动回流 → 项目不误写 ---------- + await page.goto(deskUrl); + await page.waitForSelector('#desk-prompt'); + await page.fill('#desk-prompt', 'second take on purpose not attached'); + await page.click('.a-btn.primary'); + const job2 = await waitFor(async () => { + const jobs = await api('/api/playground/jobs'); + return jobs.find((j) => j.status === 'done' && j.id !== job.id && JSON.stringify(j.payload?.workbench ?? {}).includes('asset-e2e')); + }); + ok('第二条带上下文任务完成', !!job2); + await page.waitForTimeout(1000); + const overview2 = await api(`/api/workbench/projects/${proj.id}`); + const row2 = overview2.stages.find((s) => s.stage_key === 'assets').content.assets[0]; + ok('未点回流 → 资产行保持第一份产物(不误写)', row2.job && row2.job.output === job.output_paths[0]); + const jobsOnProject = (await api(`/api/jobs?project_id=${proj.id}`)).length ?? 0; + ok('项目任务数不因未回流而增加', jobsOnProject === 1, `${jobsOnProject} job(s)`); + + // ---------- 7. 独立生成(无上下文)→ 无回流动作 ---------- + await page.goto('http://127.0.0.1:5173/image'); + await page.waitForSelector('#desk-prompt'); + await page.fill('#desk-prompt', 'standalone take without any context'); + await page.click('.a-btn.primary'); + const job3 = await waitFor(async () => { + const jobs = await api('/api/playground/jobs'); + return jobs.find((j) => j.status === 'done' && j.id !== job.id && j.id !== job2?.id && !j.payload?.workbench); + }); + ok('独立任务完成且无来源', !!job3); + await page.waitForTimeout(1000); + ok('独立结果卡没有回流动作', (await page.locator(`.take[data-job="${job3.id}"] button.attach`).count()) === 0); + + // ---------- 8. 镜头(视频)路径:上下文 + 回流 ---------- + setMode({ mode: 'ok', delay_sec: 0, videos: true }); + await page.goto( + `http://127.0.0.1:5173/video?from=workbench&project=${proj.id}&stage=shot` + + `&label=${encodeURIComponent('镜头 S1')}&prompt=${encodeURIComponent('slow push in on the courier')}` + + `&source_kind=shot&source_id=vshot-e2e` + ); + await page.waitForSelector('#desk-prompt', { timeout: 15000 }); + await page.click('.a-btn.primary'); + const vjob = await waitFor(async () => { + const jobs = await api('/api/playground/jobs'); + return jobs.find((j) => j.status === 'done' && j.kind === 'video' && JSON.stringify(j.payload?.workbench ?? {}).includes('vshot-e2e')); + }, 40000); + ok('视频任务完成且携带镜头来源', !!vjob); + await page.waitForTimeout(1200); + await page.locator(`.take[data-job="${vjob.id}"] button.attach`).click(); + await page.waitForSelector(`.take[data-job="${vjob.id}"] .a-tag.ok`, { timeout: 15000 }); + const overview3 = await api(`/api/workbench/projects/${proj.id}`); + const shotRow = overview3.stages.find((s) => s.stage_key === 'shot').content.shots[0]; + ok('镜头行挂上回流视频', shotRow.job && shotRow.job.output === vjob.output_paths[0], JSON.stringify(shotRow.job || {})); + await page.screenshot({ path: `${SHOTS}/hel684-05-shot-flowback.png` }); + + await browser.close(); + if (failures) { + console.log(`\n${failures} check(s) FAILED`); + process.exit(1); + } + console.log('\nall checks passed'); +}; + +run().catch((e) => { + console.error(e); + process.exit(1); +}); diff --git a/e2e/fpages.mjs b/e2e/fpages.mjs index e6e209e5..b7c53b1d 100644 --- a/e2e/fpages.mjs +++ b/e2e/fpages.mjs @@ -96,7 +96,7 @@ const editedColor = await page .first() .evaluate((el) => getComputedStyle(el).color) .catch(() => ''); -ok('已编辑标签用琥珀 rgb(240,180,92)', editedColor === 'rgb(240, 180, 92)', editedColor); +ok('已编辑标签用琥珀例外 rgb(163,145,95)', editedColor === 'rgb(163, 145, 95)', editedColor); // 复制提示词(镜头段 prompt 复制按钮存在性在 UI 层检查 ShotStagePanel) await page.goto(`${BASE}/workbench/${pid}`, { waitUntil: 'networkidle' }); @@ -115,7 +115,12 @@ const railLibrary = await page.locator('.rail a[href="/library"], .nav a[href="/ ok('图标轨/更多含素材库入口', railLibrary >= 1, `count=${railLibrary}`); await shot(page, 'library-1440'); -// ---------- per-page 3-width walk + overflow ---------- +// ---------- per-page 3-width walk + overflow + console errors ---------- +let consoleErrors = []; +page.on('console', (m) => { + if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 160)); +}); +page.on('pageerror', (e) => consoleErrors.push(String(e).slice(0, 160))); const PAGES = [ ['home', '/'], ['workbench', `/workbench/${pid}`], @@ -131,8 +136,10 @@ const PAGES = [ for (const [name, route] of PAGES) { for (const [wname, w] of WIDTHS) { await page.setViewportSize({ width: w, height: 900 }); + consoleErrors = []; await page.goto(`${BASE}${route}`, { waitUntil: 'networkidle' }).catch(() => {}); await page.waitForTimeout(700); + ok(`${name} ${wname} 无控制台错误`, consoleErrors.length === 0, consoleErrors[0] ?? ''); if (wname !== '1440') await shot(page, `${name}-${wname}`); if (w === 390) { const overflow = await page.evaluate( @@ -155,7 +162,7 @@ await page.waitForTimeout(600); const runGradBar = await page.locator('.a-progress').count(); ok('任务页进度条组件(a-progress)', runGradBar >= 0); const testTagNeutral = await page.locator('.tag-test').first().evaluate((el) => getComputedStyle(el).color).catch(() => ''); -ok('测试标签为中性灰', testTagNeutral === '' || testTagNeutral === 'rgb(170, 178, 197)', testTagNeutral); +ok('测试标签为中性灰阶', testTagNeutral === '' || testTagNeutral === 'rgb(168, 166, 156)', testTagNeutral); // ---------- agent chat bubbles ---------- await page.goto(`${BASE}/agents`, { waitUntil: 'networkidle' }); diff --git a/e2e/hel685.mjs b/e2e/hel685.mjs new file mode 100644 index 00000000..d4363528 --- /dev/null +++ b/e2e/hel685.mjs @@ -0,0 +1,210 @@ +/* HEL-685 S6 全站走查:1440/1024/390 截图 + 减动效 / 键盘焦点 / 对比度探针。 + * Runs against the isolated stack (vite 5173 → backend 8247 → fake ComfyUI + * 18188). Screenshots land in e2e/shots/hel685-*.png. */ +import { chromium } from 'playwright'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.dirname(fileURLToPath(import.meta.url)); +const SHOTS = path.join(ROOT, 'shots'); +fs.mkdirSync(SHOTS, { recursive: true }); +const BASE = 'http://127.0.0.1:5173'; +const API = 'http://127.0.0.1:8247'; + +let failures = 0; +function ok(name, cond, extra = '') { + const line = `${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ' — ' + extra : ''}`; + console.log(line); + if (!cond) failures++; +} + +const api = async (p, init) => { + const r = await fetch(API + p, { headers: { 'Content-Type': 'application/json' }, ...init }); + const body = await r.text(); + try { + return JSON.parse(body); + } catch { + return { raw: body, status: r.status }; + } +}; + +// ---------- fixtures: project + confirmed script + canvas ---------- +const proj = await api('/api/projects', { + method: 'POST', + body: JSON.stringify({ title: 'S6走查·灯塔', idea: '灯塔看守人的短篇' }), +}); +const pid = proj.id; +await api(`/api/workbench/projects/${pid}/stages/script/import`, { + method: 'POST', + body: JSON.stringify({ + text: '灯塔看守人老周在暴风雨夜发现一封三十年前的信。\n\n他修好旧船,横过海峡,把回信送到对岸。', + }), +}); +const canvas = await api('/api/canvas', { method: 'POST', body: JSON.stringify({ project_id: pid }) }); +const cid = canvas.canvas?.id ?? canvas.id; +ok('走查项目与画布就绪', !!pid && !!cid, `pid=${pid} cid=${cid}`); + +const browser = await chromium.launch(); +const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } }); +const page = await ctx.newPage(); +const consoleErrors = []; +page.on('console', (m) => { + if (m.type() === 'error') consoleErrors.push(m.text().slice(0, 160)); +}); +page.on('pageerror', (e) => consoleErrors.push(String(e).slice(0, 160))); + +const shot = (name) => page.screenshot({ path: `${SHOTS}/hel685-${name}.png` }); + +// ---------- 1440 desktop set (compare against HEL-679 / theme-1) ---------- +const DESK = [ + ['home-1440', '/'], + ['workbench-1440', `/workbench/${pid}`], + ['image-desk-1440', '/image'], + ['video-desk-1440', '/video'], + ['agents-1440', '/agents'], + ['models-1440', '/models'], + ['connections-1440', '/connections'], + ['tasks-1440', '/tasks'], + ['library-1440', '/library'], + ['canvas-1440', `/canvas/${cid}`], + ['build-scene-1440', '/build-scene'], +]; +for (const [name, route] of DESK) { + consoleErrors.length = 0; + await page.goto(`${BASE}${route}`, { waitUntil: 'networkidle' }).catch(() => {}); + await page.waitForTimeout(700); + ok(`${name} 无控制台错误`, consoleErrors.length === 0, consoleErrors[0] ?? ''); + await shot(name); +} + +// ---------- 1024 / 390 usability set ---------- +const NARROW = [ + ['home', '/'], + ['workbench', `/workbench/${pid}`], + ['image-desk', '/image'], + ['video-desk', '/video'], + ['agents', '/agents'], + ['tasks', '/tasks'], + ['canvas', `/canvas/${cid}`], +]; +for (const [name, route] of NARROW) { + for (const w of [1024, 390]) { + await page.setViewportSize({ width: w, height: 900 }); + await page.goto(`${BASE}${route}`, { waitUntil: 'networkidle' }).catch(() => {}); + await page.waitForTimeout(600); + await shot(`${name}-${w}`); + if (w === 390) { + const overflow = await page.evaluate( + () => document.documentElement.scrollWidth - document.documentElement.clientWidth, + ); + ok(`${name} 390 无横向溢出`, overflow <= 1, `overflow=${overflow}px`); + } + } +} +await page.setViewportSize({ width: 1440, height: 900 }); + +// ---------- reduce-motion probes (顶栏开关 data-reduce=1) ---------- +await page.goto(`${BASE}/`, { waitUntil: 'networkidle' }).catch(() => {}); +await page.waitForTimeout(400); +await page.evaluate(() => (document.documentElement.dataset.reduce = '1')); +const dur = await page.locator('.a-btn').first().evaluate((el) => getComputedStyle(el).transitionDuration); +ok('减动效:过渡时长塌缩到 ≤120ms', parseFloat(dur) <= 0.12, dur); +const spinRule = await page.evaluate(() => { + const ring = document.createElement('div'); + ring.className = 'a-tile-ring'; + ring.innerHTML = ''; + document.body.appendChild(ring); + const name = getComputedStyle(ring.firstChild).animationName; + ring.remove(); + return name; +}); +ok('减动效:上传旋转动画禁用(animation-name=none)', spinRule === 'none', spinRule); +await page.evaluate(() => delete document.documentElement.dataset.reduce); + +// ---------- keyboard focus probe ---------- +await page.goto(`${BASE}/tasks`, { waitUntil: 'networkidle' }).catch(() => {}); +await page.waitForTimeout(400); +await page.keyboard.press('Tab'); +const focusRing = await page.evaluate(() => { + const el = document.activeElement; + if (!el) return null; + const cs = getComputedStyle(el); + return cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) >= 1.5 ? cs.outlineColor : null; +}); +ok('键盘焦点显示相纸白焦点圈', focusRing === 'rgb(245, 244, 238)', String(focusRing)); + +// ---------- text contrast probes (WCAG AA on real elements) ---------- +await page.goto(`${BASE}/`, { waitUntil: 'networkidle' }).catch(() => {}); +await page.waitForTimeout(600); +const lum = (rgbStr) => { + const m = rgbStr.match(/\d+/g).map(Number); + const [r, g, b] = m.map((v) => { + const c = v / 255; + return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4); + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; +}; +const ratio = (a, b) => { + const l1 = lum(a); + const l2 = lum(b); + const [hi, lo] = l1 > l2 ? [l1, l2] : [l2, l1]; + return (hi + 0.05) / (lo + 0.05); +}; +const probeText = async (sel, label, min = 4.5) => { + const el = page.locator(sel).first(); + if (!(await el.count())) return ok(`${label} 探针元素存在`, false, sel); + const { color, bg } = await el.evaluate((e) => { + const bgOf = (node) => { + let n = node; + while (n && n !== document.documentElement) { + const bg = getComputedStyle(n).backgroundColor; + if (bg && bg !== 'rgba(0, 0, 0, 0)' && bg !== 'transparent') return bg; + n = n.parentElement; + } + return 'rgb(33, 33, 32)'; + }; + return { color: getComputedStyle(e).color, bg: bgOf(e) }; + }); + const r = ratio(color, bg); + ok(`${label} 对比度 ${r.toFixed(2)}:1 ≥ ${min}`, r >= min, `${color} on ${bg}`); +}; +await probeText('body', '首页正文文字'); +await page.goto(`${BASE}/settings`, { waitUntil: 'networkidle' }).catch(() => {}); +await page.waitForTimeout(600); +await probeText('.a-panel-lead', '面板次要文字(--text-2 级)'); +await page.goto(`${BASE}/`, { waitUntil: 'networkidle' }).catch(() => {}); +await page.waitForTimeout(400); +// .a-btn.primary 用渐变背景(backgroundColor 透明),对 --accent 实色计算 +const btnContrast = await page.evaluate(() => { + const cs = getComputedStyle(document.documentElement); + const hex = (h) => { + const s = h.replace('#', ''); + const n = parseInt(s.length === 3 ? s.split('').map((c) => c + c).join('') : s, 16); + return `rgb(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255})`; + }; + return { ink: hex(cs.getPropertyValue('--accent-ink').trim()), accent: hex(cs.getPropertyValue('--accent').trim()) }; +}); +const btnRatio = ratio(btnContrast.ink, btnContrast.accent); +ok(`主按钮文字对比度 ${btnRatio.toFixed(2)}:1 ≥ 4.5`, btnRatio >= 4.5, `${btnContrast.ink} on ${btnContrast.accent}`); +// agent identity steps all ≥ text-3 floor (computed from :root tokens) +const idSteps = await page.evaluate(() => + ['--id-1', '--id-2', '--id-3', '--id-4', '--id-5', '--text-3'].map((v) => + getComputedStyle(document.documentElement).getPropertyValue(v).trim(), + ), +); +const bg2 = await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--bg-2').trim()); +const toRgb = (hex) => { + const h = hex.replace('#', ''); + const n = parseInt(h.length === 3 ? h.split('').map((c) => c + c).join('') : h, 16); + return `rgb(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255})`; +}; +for (let i = 0; i < idSteps.length; i++) { + const r = ratio(toRgb(idSteps[i]), toRgb(bg2)); + const label = i < 5 ? `身份灰阶 --id-${i + 1}` : '--text-3 下限'; + ok(`${label} 在面板底上 ≥4.5:1(${r.toFixed(2)}:1)`, r >= 4.5); +} + +await browser.close(); +console.log(failures === 0 ? 'ALL HEL-685 WALKTHROUGH CHECKS PASSED' : `${failures} CHECKS FAILED`); +process.exit(failures === 0 ? 0 : 1); diff --git a/e2e/import.mjs b/e2e/import.mjs index 8ab5837a..f374ae95 100644 --- a/e2e/import.mjs +++ b/e2e/import.mjs @@ -213,8 +213,8 @@ const run = async () => { })), ); ok( - "① 解析 JSON 绿 ✓", - states[0].ok && states[0].color === "rgb(73, 203, 144)", + "① 解析 JSON 亮灰 ✓", + states[0].ok && states[0].color === "rgb(221, 221, 215)", states[0].color, ); ok( @@ -227,8 +227,8 @@ const run = async () => { .textContent(), ); ok( - "③ 核对模型全绿(假 object_info 装齐)", - states[2].ok && states[2].color === "rgb(73, 203, 144)", + "③ 核对模型全亮灰(假 object_info 装齐)", + states[2].ok && states[2].color === "rgb(221, 221, 215)", states[2].color, ); ok("④ 建立输入槽(1 参数 0 媒体)", states[3].ok); @@ -311,7 +311,7 @@ const run = async () => { .evaluate((el) => getComputedStyle(el).color); ok( "无法核查 = 琥珀(非绿非红)", - warnColor === "rgb(240, 180, 92)", + warnColor === "rgb(163, 145, 95)", warnColor, ); ok( @@ -392,7 +392,7 @@ const run = async () => { const chipColor = await page .locator(".drawer-panel .wft-active .chip.run") .evaluate((el) => getComputedStyle(el).color); - ok("进行中状态为信号青", chipColor === "rgb(84, 223, 210)", chipColor); + ok("进行中状态为运行灰", chipColor === "rgb(184, 182, 172)", chipColor); ok( "进行中显示进度条", (await page.locator(".drawer-panel .wft-active .track").count()) === 1, @@ -450,7 +450,7 @@ const run = async () => { .evaluate((el) => getComputedStyle(el).color); ok( "失败判定为红 + 中文标题", - badColor === "rgb(240, 100, 90)", + badColor === "rgb(208, 122, 107)", await page .locator(".drawer-panel .wft-result.bad .wft-verdict") .textContent(), diff --git a/e2e/pagination.mjs b/e2e/pagination.mjs index de08256c..06f00ffa 100644 --- a/e2e/pagination.mjs +++ b/e2e/pagination.mjs @@ -16,6 +16,28 @@ const run = async () => { const base = 'http://127.0.0.1:5173'; let realJobs = []; + // HEL-685 harness fix: fan-out needs ≥1 real take to clone; on a fresh DB + // the list is empty — kick one quick fake-ComfyUI image job, wait for it, + // and only then start intercepting. + { + const probe = await fetch('http://127.0.0.1:8247/api/playground/jobs').then((r) => r.json()); + if (!Array.isArray(probe) || probe.length === 0) { + await fetch('http://127.0.0.1:8247/api/playground/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + workflow_id: 1, + input_values: { 1: { text: 'pagination 基准' }, 2: 42 }, + source: 'studio-image', + }), + }); + for (let i = 0; i < 60; i++) { + await page.waitForTimeout(500); + const jobs = await fetch('http://127.0.0.1:8247/api/playground/jobs').then((r) => r.json()); + if (Array.isArray(jobs) && jobs.some((j) => j.status === 'done')) break; + } + } + } await page.route('**/api/playground/jobs**', async (route) => { const r = await route.fetch(); realJobs = await r.json(); diff --git a/e2e/reference/README.md b/e2e/reference/README.md new file mode 100644 index 00000000..3344a6ec --- /dev/null +++ b/e2e/reference/README.md @@ -0,0 +1,43 @@ +# HEL-692 确认样本的正式功能回归 + +所有写入都使用独立本地后端 `127.0.0.1:8247`,数据在被忽略的 `e2e/shots/reference/data`。本脚本不连接测试服务器,不使用真实模型或 ComfyUI 服务。 + +从仓库根目录依次启动(测试结束后停止这些本地进程): + +```sh +PYTHONPATH=calliope-backend/src python3 e2e/reference/server.py +python3 e2e/fake_comfy.py +python3 e2e/reference/fake_llm.py +npm --prefix calliope-web run dev +``` + +独立终端运行: + +```sh +python3 e2e/seed.py +python3 e2e/reference/seed.py +PLAYWRIGHT_MODULE_PATH=/path/to/playwright-core CHROMIUM_EXECUTABLE_PATH=/path/to/chromium node e2e/reference/check.cjs +PLAYWRIGHT_MODULE_PATH=/path/to/playwright-core CHROMIUM_EXECUTABLE_PATH=/path/to/chromium node e2e/reference/check-copy-fallback.cjs +``` + +检查真实上传、任务、消息、技能引用、模型绑定、故事结果保存、取消/保存参数、工作流筛选、独立草稿、小窗口和手动播放。结果与截图写入 `e2e/shots/reference`。测试会暂改假 ComfyUI 的模式文件,退出时恢复。 + +## 已验证的范围 + +- 25 项浏览器回归及一项真实剪贴板降级回归通过;图像与视频输出由本地假服务提供,智能体回复来自本地兼容模型服务。正式功能仍调用现有后端接口。 +- 引用限额由单条工作流改成一条工作流加最多四个技能;五项模型校验单测通过,第二条工作流仍拒绝。 +- 项目保存使用现有 PATCH 故事草稿接口,由用户在工作台继续确认。其他阶段需要结构化字段,因此明确提供“复制内容并打开项目”,不把自由文本伪装成结构化结果。 +- 实际外部模型质量、真实 GPU 性能和参考站完整成片流程不在这个隔离回归中验证。 + +## 界面与动效变化 + +| 修改前 | 修改后 | +| --- | --- | +| 工作流在另一层挑选台,填写和结果横排 | 左侧常驻列表、右侧结果、下方提示词与参数 | +| 参数窗即时改值 | 在独立草稿中修改,保存时只合并参数,取消不改值 | +| 五个智能体横排,技能和对话三栏 | 有主题主视觉的独立智能体页、侧栏选择、大输入框与集中弹窗 | +| Enter 直接发出长故事 | Enter 换行,Ctrl/Cmd + Enter 发送 | +| 项目阶段竖排 | 五阶段横排,保留原确认和回流接口 | +| 通用悬停色 | 跟随鼠标的蜂窝高亮,选中态独立,置顶按钮独立 | + +主视觉和风格参考图来自用户指定参考站的公开素材,来源见 `calliope-web/src/lib/referenceAgent.ts`。没有收录账号截图、账号历史或登录资料。动效采用实测源站进入曲线与明确的按压/聚焦反馈,系统及手动减少动效都生效。 diff --git a/e2e/reference/check-copy-fallback.cjs b/e2e/reference/check-copy-fallback.cjs new file mode 100644 index 00000000..294bfa63 --- /dev/null +++ b/e2e/reference/check-copy-fallback.cjs @@ -0,0 +1,73 @@ +const { chromium } = require( + process.env.PLAYWRIGHT_MODULE_PATH || 'playwright', +); +const assert = require('node:assert/strict'); +(async () => { + const path = require('node:path'); + const expected = path.resolve(__dirname, '../shots/reference/data'); + const config = await ( + await fetch('http://127.0.0.1:8247/api/settings') + ).json(); + assert.equal( + path.resolve(config.data_dir), + expected, + 'Start the isolated reference server first.', + ); + const b = await chromium.launch({ + executablePath: process.env.CHROMIUM_EXECUTABLE_PATH, + args: ['--no-sandbox', '--disable-dev-shm-usage'], + }); + try { + const c = await b.newContext({ + permissions: ['clipboard-read', 'clipboard-write'], + }); + const p = await c.newPage(); + p.setDefaultTimeout(15000); + await p.goto('http://127.0.0.1:5173/agents'); + await p.locator('.agent-row').filter({ hasText: '视觉设计' }).click(); + const created = p.waitForResponse( + (r) => + r.url().endsWith('/api/agent/sessions') && + r.request().method() === 'POST', + ); + await p.getByRole('button', { name: /新任务/ }).click(); + await created; + await p.waitForFunction(() => + Array.from(document.querySelectorAll('.agent-toolbar button')).some( + (b) => b.textContent.includes('新任务') && !b.disabled, + ), + ); + await p + .locator('.agent-composer textarea') + .fill('需要一个温暖的绘本视觉方向'); + await p.locator('.agent-send').click(); + await p.getByRole('button', { name: /编辑内容并带回项目/ }).waitFor(); + await p.getByRole('button', { name: /编辑内容并带回项目/ }).click(); + await p.locator('.result-project-label select').selectOption('3'); + const text = + '剪贴板降级复制的实际内容。此处用于确认非安全上下文的操作不会误报成功。'; + await p.locator('#agent-result-editor').fill(text); + await p.evaluate(async () => { + window.__testClipboard = navigator.clipboard; + await window.__testClipboard.writeText('INITIAL'); + Object.defineProperty(navigator, 'clipboard', { + value: undefined, + configurable: true, + }); + }); + await p + .getByRole('button', { name: '复制内容并打开项目', exact: true }) + .click(); + await p.waitForURL('**/workbench/3?stage=style'); + const copied = await p.evaluate(() => window.__testClipboard.readText()); + assert.equal(copied, text); + console.log( + 'PASS clipboard unavailable: actual content copied and correct stage opened', + ); + } finally { + await b.close(); + } +})().catch((e) => { + console.error(e); + process.exitCode = 1; +}); diff --git a/e2e/reference/check.cjs b/e2e/reference/check.cjs new file mode 100644 index 00000000..ae674171 --- /dev/null +++ b/e2e/reference/check.cjs @@ -0,0 +1,362 @@ +const { chromium } = require( + process.env.PLAYWRIGHT_MODULE_PATH || "playwright", +); +const assert = require("node:assert/strict"), + fs = require("fs"), + path = require("path"); +const root = path.resolve(__dirname, "../.."), + runtime = path.join(root, "e2e/shots/reference"); +fs.mkdirSync(runtime, { recursive: true }); +const f = JSON.parse(fs.readFileSync(path.join(runtime, "fixtures.json"))), + API = "http://127.0.0.1:8247", + WEB = "http://127.0.0.1:5173"; +const modepath = path.join(root, "e2e/fake_mode.json"), + savedMode = fs.existsSync(modepath) ? fs.readFileSync(modepath) : null; +const checks = [], + errors = []; +const ok = (name, value) => { + assert(value, name); + checks.push(name); + console.log("PASS", name); +}; +async function api(url, body, method) { + const r = await fetch(API + url, { + method: method || (body ? "POST" : "GET"), + headers: { "Content-Type": "application/json" }, + body: body ? JSON.stringify(body) : undefined, + }); + if (!r.ok) throw Error(url + " " + r.status + " " + (await r.text())); + return r.json(); +} +async function wait(fn) { + const end = Date.now() + 18000; + while (Date.now() < end) { + const value = await fn(); + if (value) return value; + await new Promise((r) => setTimeout(r, 150)); + } + throw Error("condition timeout"); +} +function mode(videos = false) { + fs.writeFileSync( + modepath, + JSON.stringify({ + mode: "ok", + delay_sec: 0, + unique_filename: true, + videos, + image_file: path.join(root, "calliope-web/static/refract/coast.jpg"), + }), + ); +} +(async () => { + let b; + try { + const config = await api("/api/settings"); + assert.equal( + path.resolve(config.data_dir), + path.join(runtime, "data"), + "Run the dedicated e2e/reference/server.py before this writing test.", + ); + b = await chromium.launch({ + executablePath: process.env.CHROMIUM_EXECUTABLE_PATH, + args: ["--no-sandbox", "--disable-dev-shm-usage"], + }); + const p = await b.newPage({ viewport: { width: 1440, height: 900 } }); + p.on("pageerror", (e) => errors.push(e.message)); + p.setDefaultTimeout(12000); + await p.goto(WEB + "/image?wf=" + f.dual); + await p.locator("#desk-negative").waitFor(); + ok( + "真实工作流显示正反向左右分栏", + await p + .locator(".prompt-pair") + .evaluate( + (e) => + getComputedStyle(e).gridTemplateColumns.split(" ").length === 2, + ), + ); + await p.locator("#desk-prompt").fill("正向草稿"); + await p.locator("#desk-negative").fill("反向草稿"); + ok( + "工作流列表可应对超过 48 项", + (await p.locator(".workflow-pick").count()) >= 48, + ); + await p.locator(".rail-tools input").fill("Qwen"); + ok( + "列表搜索过滤真实元数据", + (await p.locator(".workflow-pick").count()) === 1, + ); + await p.locator(".row-actions button").first().click(); + ok( + "置顶不切换工作流、不清空草稿", + (await p.locator("#desk-prompt").inputValue()) === "正向草稿", + ); + await p + .getByRole("button", { name: "创作设置", exact: true }) + .first() + .click(); + await p.locator(".modal-panel input[type=number]").first().fill("99"); + await p.getByRole("button", { name: "取消", exact: true }).click(); + await p + .getByRole("button", { name: "创作设置", exact: true }) + .first() + .click(); + ok( + "参数取消不改当前值", + (await p + .locator(".modal-panel input[type=number]") + .first() + .inputValue()) === "42", + ); + await p.locator(".modal-panel input[type=number]").first().fill("101"); + await p.getByRole("button", { name: "保存设置", exact: true }).click(); + await p + .getByRole("button", { name: "创作设置", exact: true }) + .first() + .click(); + ok( + "参数保存应用到当前工作流", + (await p + .locator(".modal-panel input[type=number]") + .first() + .inputValue()) === "101", + ); + await p.keyboard.press("Escape"); + const beforeImage = Math.max( + 0, + ...(await api("/api/playground/jobs")).map((j) => j.id), + ); + mode(); + await p.locator(".gen").click(); + const job = await wait(async () => { + const rows = await api("/api/playground/jobs"); + return rows.find( + (j) => + j.id > beforeImage && j.workflow_id === f.dual && j.status === "done", + ); + }); + ok("真实生成请求提交且取得结果", !!job.output_paths[0]); + ok( + "正反向与种子写入任务", + JSON.stringify(job.payload).includes("正向草稿") && + JSON.stringify(job.payload).includes("反向草稿") && + JSON.stringify(job.payload).includes("101"), + ); + await p.locator(".result-item").first().click(); + await p.screenshot({ path: path.join(runtime, "正式施工-创作台.png") }); + await p.goto(WEB + "/video?wf=" + f.h3); + await p.locator(".a-slot").filter({ hasText: "首帧" }).waitFor(); + const first = p + .locator(".a-slot") + .filter({ has: p.getByText("首帧", { exact: true }) }), + last = p + .locator(".a-slot") + .filter({ has: p.getByText("尾帧", { exact: true }) }); + await first + .locator("input[type=file]") + .setInputFiles(path.join(root, "calliope-web/static/refract/coast.jpg")); + await last + .locator("input[type=file]") + .setInputFiles(path.join(root, "calliope-web/static/refract/arch.jpg")); + await wait( + async () => + (await first.locator("img").count()) && + (await last.locator("img").count()), + ); + ok("H3 首尾帧真实上传保留", true); + const beforeVideo = Math.max( + 0, + ...(await api("/api/playground/jobs")).map((j) => j.id), + ); + mode(true); + await p.locator(".gen").click(); + const video = await wait(async () => { + const rows = await api("/api/playground/jobs"); + return rows.find( + (j) => + j.id > beforeVideo && j.workflow_id === f.h3 && j.status === "done", + ); + }); + await p.locator(".result-item").first().click(); + await p.locator(".main video").waitFor(); + ok( + "视频默认暂停且不自动播放", + await p.locator(".main video").evaluate((v) => v.paused && !v.autoplay), + ); + ok( + "播放按钮明确可见", + await p + .getByRole("button", { name: "播放视频", exact: true }) + .isVisible(), + ); + await p.setViewportSize({ width: 1280, height: 720 }); + ok( + "小窗口播放键仍完整可见", + await p + .getByRole("button", { name: "播放视频", exact: true }) + .evaluate((e) => { + const r = e.getBoundingClientRect(); + return r.top >= 0 && r.bottom <= innerHeight && r.right <= innerWidth; + }), + ); + await p.screenshot({ path: path.join(runtime, "正式施工-首尾帧视频.png") }); + await p.goto(WEB + "/agents"); + await p.getByRole("button", { name: /新任务/ }).click(); + await p.locator(".agent-intro").waitFor(); + ok( + "智能体独立主题页面", + await p + .locator(".agent-scene img") + .evaluate((e) => e.complete && e.naturalWidth > 0), + ); + await p.locator(".agent-composer textarea").fill("故事草稿 A"); + await p.locator(".agent-row").filter({ hasText: "视觉设计" }).click(); + await p.locator(".agent-composer textarea").fill("视觉草稿 B"); + await p.locator(".agent-row").filter({ hasText: "剧本创作" }).click(); + ok( + "五个智能体各自保留草稿", + (await p.locator(".agent-composer textarea").inputValue()) === + "故事草稿 A", + ); + await p.locator(".agent-controls .agent-option").first().click(); + await p.locator(".style-card").filter({ hasText: "日系动画" }).click(); + await p.getByRole("button", { name: "取消", exact: true }).click(); + ok( + "风格取消不应用", + (await p.locator(".agent-controls .agent-option").first().innerText()) === + "治愈绘本", + ); + await p.locator(".agent-controls .agent-option").first().click(); + await p.locator(".style-card").filter({ hasText: "日系动画" }).click(); + await p.getByRole("button", { name: "应用风格", exact: true }).click(); + ok( + "风格应用保留任务", + (await p.locator(".agent-composer textarea").inputValue()) === + "故事草稿 A", + ); + await p + .getByRole("button", { name: /默认大模型⌄|隔离测试模型 B⌄/ }) + .click(); + await p + .locator(".model-choice") + .filter({ hasText: "隔离测试模型 B" }) + .click(); + await p.getByRole("button", { name: "应用模型", exact: true }).click(); + await p.getByRole("button", { name: /隔离测试模型 B⌄/ }).waitFor(); + ok( + "模型选择通过真实设置接口绑定", + Object.values( + (await api("/api/settings")).agent_llm_assignments, + ).includes("reference-model-b"), + ); + await p.getByRole("button", { name: /选择技能/ }).click(); + await p.locator(".skill-choice").nth(1).click(); + await p.getByRole("button", { name: "应用技能", exact: true }).click(); + await p + .locator('select[aria-label="智能体关联项目"]') + .selectOption(String(f.project)); + await p + .locator(".agent-composer input[type=file]") + .setInputFiles(path.join(root, "calliope-web/static/refract/coast.jpg")); + await p.locator(".agent-attachments img").waitFor(); + await p.getByRole("button", { name: /引用工作流/ }).click(); + await p + .locator(".modal-panel .model-choice") + .filter({ hasText: "Qwen·正反向测试" }) + .click(); + await p.locator(".agent-send").click(); + const session = await wait(async () => { + const sessions = await api("/api/agent/sessions?agent_key=script"); + return sessions + .filter((s) => s.project_id === f.project) + .sort((a, b) => b.id - a.id)[0]; + }); + const detail = await wait(async () => { + const d = await api("/api/agent/sessions/" + session.id); + return d.messages.some((m) => m.role === "assistant") ? d : null; + }); + const message = detail.messages.find((m) => m.role === "user"); + ok( + "真实消息包含风格与技能引用", + message.content.includes("日系动画") && + message.mentions.some((m) => m.type === "skill") && + message.mentions.some((m) => m.type === "workflow"), + ); + ok("参考材料真实上传并随任务发送", message.attachments.length === 1); + ok( + "后端智能体回复呈现在对话", + detail.messages.some((m) => m.content.includes("隔离测试模型回复")), + ); + await p + .getByText(/隔离测试模型回复/) + .first() + .waitFor(); + await p.screenshot({ path: path.join(runtime, "正式施工-智能体对话.png") }); + await p.getByRole("button", { name: /编辑内容并带回项目/ }).click(); + await p + .locator("#agent-result-editor") + .fill( + "这是编辑后带回项目的故事文稿。小女孩把折好的纸船放进海面,海风吹了一整夜,第二天纸船带回一片银色的树叶。", + ); + await p + .getByRole("button", { name: "保存到项目草稿", exact: true }) + .click(); + await p.waitForURL("**/workbench/" + f.project + "?stage=script"); + const wb = await api("/api/workbench/projects/" + f.project); + ok( + "智能体结果真实保存为待确认项目草稿", + wb.stages + .find((s) => s.stage_key === "script") + .content.text.includes("编辑后带回项目") && + wb.stages.find((s) => s.stage_key === "script").status === + "awaiting_confirm", + ); + await p.goto(WEB + "/agents"); + await p.getByRole("button", { name: /新任务/ }).click(); + await p.locator(".agent-intro").waitFor(); + await p.setViewportSize({ width: 1600, height: 900 }); + await p.screenshot({ path: path.join(runtime, "正式施工-智能体首页.png") }); + await p.locator(".agent-controls .agent-option").first().click(); + await p.screenshot({ path: path.join(runtime, "正式施工-风格选择.png") }); + await p.keyboard.press("Escape"); + await p.getByRole("button", { name: "智能体设置", exact: true }).click(); + ok( + "技能管理和自定义编辑可访问", + await p + .getByRole("button", { name: "+ 自定义技能", exact: true }) + .isVisible(), + ); + await p.getByRole("button", { name: "+ 自定义技能", exact: true }).click(); + await p.screenshot({ path: path.join(runtime, "正式施工-自定义技能.png") }); + await p.keyboard.press("Escape"); + await p.goto(WEB + "/workbench/" + f.project); + await p.locator("[data-testid=workbench-page]").waitFor(); + ok( + "五阶段横向排列", + await p + .locator(".stepper") + .evaluate((e) => getComputedStyle(e).flexDirection === "row"), + ); + ok( + "项目上下文与真实任务区保留", + (await p.locator(".side-col .side-card").count()) >= 2, + ); + await p.screenshot({ path: path.join(runtime, "正式施工-项目工作台.png") }); + await p.goto(WEB + "/"); + await p.screenshot({ path: path.join(runtime, "正式施工-工作室.png") }); + ok("没有页面脚本错误", errors.length === 0); + fs.writeFileSync( + path.join(runtime, "results.json"), + JSON.stringify({ checks, errors }, null, 2), + ); + console.log("PASS TOTAL", checks.length); + } finally { + if (b) await b.close(); + if (savedMode) fs.writeFileSync(modepath, savedMode); + else if (fs.existsSync(modepath)) fs.unlinkSync(modepath); + } +})().catch((e) => { + console.error(e); + process.exitCode = 1; +}); diff --git a/e2e/reference/fake_llm.py b/e2e/reference/fake_llm.py new file mode 100644 index 00000000..7eeb2bf2 --- /dev/null +++ b/e2e/reference/fake_llm.py @@ -0,0 +1,21 @@ +import json,time +from pathlib import Path +from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer +root=Path(__file__).resolve().parents[1]/'shots/reference' +root.mkdir(parents=True,exist_ok=True) +class Handler(BaseHTTPRequestHandler): + def log_message(self,*args):pass + def do_POST(self): + payload=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0')))) + with (root/'llm-requests.jsonl').open('a') as f:f.write(json.dumps(payload,ensure_ascii=False)+'\n') + content='【隔离测试模型回复】\n纸船带回了一片树叶。女孩望向海面,知道故事才刚刚开始。\n\n已收到任务与指定技能,后续可以继续修改。' + if payload.get('stream'): + self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers() + for chunk in [content[:16],content[16:]]: + body={'id':'reference-check','choices':[{'index':0,'delta':{'content':chunk},'finish_reason':None}]} + self.wfile.write(('data: '+json.dumps(body,ensure_ascii=False)+'\n\n').encode());self.wfile.flush();time.sleep(.05) + self.wfile.write(b'data: [DONE]\n\n') + else: + body={'id':'reference-check','choices':[{'index':0,'message':{'role':'assistant','content':content},'finish_reason':'stop'}]} + data=json.dumps(body,ensure_ascii=False).encode();self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(data) +ThreadingHTTPServer(('127.0.0.1',18189),Handler).serve_forever() diff --git a/e2e/reference/seed.py b/e2e/reference/seed.py new file mode 100644 index 00000000..33e47dfc --- /dev/null +++ b/e2e/reference/seed.py @@ -0,0 +1,21 @@ +import json,urllib.request +from pathlib import Path +BASE='http://127.0.0.1:8247' +def api(path,payload=None,method=None): + req=urllib.request.Request(BASE+path,data=json.dumps(payload).encode() if payload is not None else None,method=method or ('POST' if payload is not None else 'GET'),headers={'Content-Type':'application/json'}) + with urllib.request.urlopen(req) as r:return json.load(r) +image={ '1':{'class_type':'CLIPTextEncode','inputs':{'text':'海边的小女孩'},'_meta':{'title':'(Input:prompt) 正向提示词'}},'2':{'class_type':'CLIPTextEncode','inputs':{'text':'模糊'},'_meta':{'title':'(Input:negative) 反向提示词'}},'3':{'class_type':'PrimitiveInt','inputs':{'value':42},'_meta':{'title':'(Input:seed) 种子'}},'9':{'class_type':'SaveImage','inputs':{'images':'x'},'_meta':{'title':'(Output:image) 图片输出'}}} +h3={ '1':{'class_type':'CLIPTextEncode','inputs':{'text':'缓慢推镜'},'_meta':{'title':'(Input:prompt) 提示词'}},'2':{'class_type':'LoadImage','inputs':{'image':''},'_meta':{'title':'(Input:first_frame) 首帧'}},'3':{'class_type':'LoadImage','inputs':{'image':''},'_meta':{'title':'(Input:last_frame) 尾帧'}},'9':{'class_type':'VHS_VideoCombine','inputs':{'images':'x'},'_meta':{'title':'(Output:video) 视频输出'}}} +expected=Path(__file__).resolve().parents[1]/'shots/reference/data' +assert Path(api('/api/settings')['data_dir']).resolve()==expected.resolve(), 'Start the isolated reference server first' +rows=api('/api/workflows?view=meta');names={w['name']:w['id'] for w in rows} +def wf(name,kind,body): + if name in names:return names[name] + return api('/api/workflows',{'name':name,'kind':kind,'workflow_json':body})['id'] +ids={'dual':wf('Qwen·正反向测试','image',image),'h3':wf('H3·首尾帧测试','video',h3)} +for i in range(60):wf('列表规模测试 '+str(i).zfill(3),'image',image) +project=api('/api/projects',{'title':'HEL692·隔离测试项目','idea':'纸船的故事'}) +ids['project']=project['id'] +profiles=[{k:v for k,v in p.items() if k in ('id','name','base_url','model')} for p in api('/api/settings')['llm_profiles']];profiles.append({'id':'reference-model-b','name':'隔离测试模型 B','base_url':'http://127.0.0.1:18189/v1','model':'reference-test-b','api_key':''});api('/api/settings',{'llm_profiles':profiles}) +(Path(__file__).resolve().parents[1]/'shots/reference/fixtures.json').write_text(json.dumps(ids)) +print(ids) diff --git a/e2e/reference/server.py b/e2e/reference/server.py new file mode 100644 index 00000000..c5b47354 --- /dev/null +++ b/e2e/reference/server.py @@ -0,0 +1,13 @@ +from pathlib import Path +from calliope import config +root=Path(__file__).resolve().parents[1]/'shots/reference' +root.mkdir(parents=True,exist_ok=True) +config.CONFIG_FILE=root/'settings.json' +config.settings=config.Settings(data_dir=root/'data',assets_dir=root/'data/assets',llm_base_url='http://127.0.0.1:18189/v1',llm_model='reference-test',dry_run=False) +if config.CONFIG_FILE.exists():config.settings.load_config_file() +config.settings.ensure_storage_dirs() +config.settings.ensure_llm_profiles() +config.settings.save_config_file() +from calliope.main import create_app +import uvicorn +uvicorn.run(create_app(),host='127.0.0.1',port=8247) diff --git a/e2e/refract.mjs b/e2e/refract.mjs new file mode 100644 index 00000000..c9af8e6a --- /dev/null +++ b/e2e/refract.mjs @@ -0,0 +1,527 @@ +// Integration checks: disposable local backend + fake ComfyUI only. +import { createRequire } from 'node:module'; +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +const { chromium } = createRequire(import.meta.url)( + process.env.PLAYWRIGHT_MODULE_PATH || 'playwright', +); +const ROOT = path.dirname(fileURLToPath(import.meta.url)); +const SHOTS = process.env.REFRACT_SHOTS || path.join(ROOT, 'shots', 'refract'); +fs.mkdirSync(SHOTS, { recursive: true }); +const API = process.env.REFRACT_API || 'http://127.0.0.1:8247', + WEB = process.env.REFRACT_WEB || 'http://127.0.0.1:5173'; +if (!['127.0.0.1', 'localhost'].includes(new URL(API).hostname)) + throw Error('This test writes fixtures: use an isolated local backend.'); +let checks = 0, + failures = 0, + browser; +const errors = [], + projects = [], + workflows = [], + jobs = []; +const ok = (name, value) => { + checks++; + console.log(`${value ? 'PASS' : 'FAIL'} ${name}`); + if (!value) failures++; +}; +async function api(p, body, method) { + const r = await fetch(API + p, { + method: method || (body ? 'POST' : 'GET'), + headers: { 'Content-Type': 'application/json' }, + body: body ? JSON.stringify(body) : undefined, + }); + if (!r.ok) throw Error(`${p} ${r.status} ${await r.text()}`); + return r.json(); +} +async function until(fn) { + const end = Date.now() + 18000; + while (Date.now() < end) { + const r = await fn(); + if (r) return r; + await new Promise((r) => setTimeout(r, 200)); + } + throw Error('Timed out waiting for API state'); +} +const modePath = path.join(ROOT, 'fake_mode.json'), + savedMode = fs.existsSync(modePath) ? fs.readFileSync(modePath) : null; +const mode = (videos = false, photo = 'coast') => + fs.writeFileSync( + modePath, + JSON.stringify({ + mode: 'ok', + delay_sec: 0, + unique_filename: true, + videos, + image_file: path.join(ROOT, '../calliope-web/static/refract/' + photo + '.jpg'), + }), + ); +try { + mode(); + // Remove only this script's marked local fixtures after an interrupted previous run. + const staleProjects = (await api('/api/projects')).filter( + (p) => p.title === '折光·可删除测试项目', + ); + const staleProjectIds = new Set(staleProjects.map((p) => p.id)); + for (const j of await api('/api/playground/jobs')) + if (staleProjectIds.has(j.payload?.workbench?.project_id)) + await api('/api/playground/jobs/' + j.id, null, 'DELETE'); + for (const p of staleProjects) await api('/api/projects/' + p.id, null, 'DELETE'); + for (const w of await api('/api/workflows?view=meta')) + if (['H3 首尾帧·折光回归', 'H3 首尾帧·首次加载回归'].includes(w.name)) + await api('/api/workflows/' + w.id, null, 'DELETE'); + const rows = await api('/api/workflows?view=meta'); + ok('more than 100 imported catalogue entries', rows.length > 100); + const image = rows.find((w) => w.name === '文生图·回归'); + if (!image) throw Error('Run e2e/seed.py first.'); + const h3 = await api('/api/workflows', { + name: 'H3 首尾帧·折光回归', + kind: 'video', + usage: 'image2video', + workflow_json: { + 1: { + class_type: 'CLIPTextEncode', + inputs: { text: 'slow camera' }, + _meta: { title: '(Input:prompt) 画面描述' }, + }, + 2: { + class_type: 'LoadImage', + inputs: { image: '' }, + _meta: { title: '(Input:first_frame) 首帧' }, + }, + 3: { + class_type: 'LoadImage', + inputs: { image: '' }, + _meta: { title: '(Input:last_frame) 尾帧' }, + }, + 9: { + class_type: 'VHS_VideoCombine', + inputs: { images: 'x' }, + _meta: { title: '(Output:video) 视频输出' }, + }, + }, + }); + workflows.push(h3.id); + const h3Copy = await api('/api/workflows', { + name: 'H3 首尾帧·首次加载回归', + kind: h3.kind, + usage: h3.usage, + workflow_json: h3.workflow_json, + }); + workflows.push(h3Copy.id); + + const project = await api('/api/projects', { + title: '折光·可删除测试项目', + idea: '从一个想法开始', + }); + projects.push(project.id); + await api( + `/api/workbench/projects/${project.id}/stages/assets`, + { + content: { + assets: [ + { + id: 'refract-asset', + kind: 'character', + name: '旅人', + prompt: 'traveler on coast', + negative_prompt: '', + }, + ], + }, + }, + 'PATCH', + ); + browser = await chromium.launch({ + executablePath: process.env.CHROMIUM_EXECUTABLE_PATH, + args: ['--no-sandbox', '--disable-dev-shm-usage'], + }); + const context = await browser.newContext({ + viewport: { width: 1440, height: 960 }, + locale: 'zh-CN', + }); + const page = await context.newPage(); + page.setDefaultTimeout(8000); + page.on('pageerror', (e) => errors.push(String(e))); + page.on('console', (m) => { + if (m.type() === 'error') errors.push(m.text()); + }); + await page.goto(WEB + '/'); + await page.locator('.refract-hero').waitFor(); + ok( + 'six primary entries and approved hero', + (await page.locator('.refract-shell>.sidebar .nav-item').count()) === 6, + ); + ok( + 'paper palette', + await page.evaluate( + () => + getComputedStyle(document.documentElement).getPropertyValue('--bg').trim() === '#f4f2ed', + ), + ); + await page.screenshot({ path: SHOTS + '/home.png' }); + await page.goto(WEB + '/workbench'); + await page.locator('.project-grid .a-card').first().waitFor(); + ok('real project grid', (await page.locator('.project-grid .a-card').count()) > 0); + await page.goto(WEB + `/workbench/${project.id}?stage=assets`); + await page.locator('[data-testid="workbench-page"]').waitFor(); + ok( + 'five vertical project stages', + (await page.locator('.stage-navigation .step-btn').count()) === 5 && + (await page.locator('.stepper').evaluate((e) => getComputedStyle(e).flexDirection)) === + 'column', + ); + await page.screenshot({ path: SHOTS + '/project.png' }); + const desk = + WEB + + `/image?wf=${image.id}&from=workbench&project=${project.id}&stage=assets&label=旅人&source_kind=asset&source_id=refract-asset&prompt=traveler%20on%20coast`; + await page.goto(desk); + await page.locator('#desk-prompt').waitFor(); + ok( + 'context prompt and return path', + (await page.inputValue('#desk-prompt')) === 'traveler on coast' && + (await page.locator('.context-bar a.back').count()) === 1, + ); + await page.fill('#desk-prompt', '项目草稿·旅人'); + await page.locator('.sidebar .nav-item[href="/image"]').click(); + await page.waitForURL(WEB + '/image'); + await page.locator('.context-bar').waitFor({ state: 'detached' }); + await page.locator('#desk-prompt').waitFor(); + await page.fill('#desk-prompt', '独立创作草稿'); + await page.goto(desk); + await page.locator('#desk-prompt').waitFor(); + ok( + 'project and standalone drafts stay separate across navigation', + (await page.inputValue('#desk-prompt')) === '项目草稿·旅人', + ); + await page.fill('#desk-prompt', 'traveler on coast'); + const preview = await page.locator('.inspector.main .stage').boundingBox(), + form = await page.locator('.studio-form').boundingBox(); + ok( + 'input and results are adjacent workspace regions', + preview.x > form.x && form.width >= 290 && form.width <= 370, + ); + await page.locator('.model-selector').click(); + await page.locator('.tool-picker .catalogue').waitFor(); + await page.fill('[aria-label="搜索工作流"]', '文生图·回归'); + await until(async () => (await page.locator('.tool-picker .workflow-card').count()) === 1); + ok('tool search stays in workspace', (await page.locator('[role="dialog"]').count()) === 0); + await page.getByRole('button', { name: '查看 文生图·回归', exact: true }).click(); + await page.locator('.tool-detail h3').waitFor(); + ok( + 'tool requirements before confirmation', + await page + .locator('.tool-detail') + .innerText() + .then((s) => s.includes('画面描述')), + ); + await page.keyboard.press('Escape'); + ok( + 'Escape preserves input and restores tool button', + (await page.inputValue('#desk-prompt')) === 'traveler on coast' && + (await page.locator('.model-selector').evaluate((e) => e === document.activeElement)), + ); + ok( + 'common parameters visible inline', + await page + .locator('.composer-scroll .input-section') + .last() + .innerText() + .then((s) => s.includes('生成设置')), + ); + let submitted = page.waitForRequest( + (r) => r.url().endsWith('/api/playground/generate') && r.method() === 'POST', + ); + await page.locator('.studio-form .gen').click(); + ok( + 'submit carries project source identity', + (await submitted).postDataJSON().context?.source_id === 'refract-asset', + ); + const job = await until(async () => + (await api('/api/playground/jobs')).find( + (j) => j.status === 'done' && j.payload?.workbench?.source_id === 'refract-asset', + ), + ); + jobs.push(job.id); + await page.locator('.inspector.main img').first().waitFor(); + await page.locator('.save-project').click(); + await until( + async () => + (await api(`/api/workbench/projects/${project.id}`)).stages.find( + (s) => s.stage_key === 'assets', + ).content.assets[0].job, + ); + ok('output flows to source project asset', true); + await page.reload(); + await page.locator('.save-project').waitFor(); + ok( + 'attachment survives reload', + !!(await api(`/api/workbench/projects/${project.id}`)).stages.find( + (s) => s.stage_key === 'assets', + ).content.assets[0].job, + ); + mode(false, 'arch'); + await page.fill('#desk-prompt', 'second variation'); + await page.locator('.studio-form .gen').click(); + const second = await until(async () => + (await api('/api/playground/jobs')).find( + (j) => + j.status === 'done' && + j.id !== job.id && + j.payload?.workbench?.source_id === 'refract-asset', + ), + ); + jobs.push(second.id); + await page.locator(`.result-item[aria-label^="查看第 ${second.id} 次"]`).click(); + + await page.getByRole('button', { name: '对比画面 ◫' }).click(); + await page.getByRole('slider', { name: '拖动对比画面' }).fill('70'); + ok( + 'comparison follows slider using actual files', + await page.locator('.comparison-layer').evaluate((e) => e.style.clipPath.includes('30%')), + ); + await page.getByRole('button', { name: '结束对比 ◫' }).click(); + await page.getByRole('button', { name: '放大查看 ⤢' }).click(); + ok('real image lightbox', (await page.locator('.backdrop[role=dialog]').count()) > 0); + await page.keyboard.press('Escape'); + await page.getByRole('button', { name: '专注创作 ⤢' }).click(); + ok( + 'focus mode keeps creation available', + !(await page.locator('.refract-shell>.sidebar').isVisible()) && + (await page.locator('.studio-form').isVisible()), + ); + await page.getByRole('button', { name: '退出专注 ⤢' }).click(); + await page.screenshot({ path: SHOTS + '/studio.png' }); + mode(true); + await page.goto(WEB + `/video?wf=${h3.id}`); + await page.locator('#desk-prompt').waitFor(); + const uploads = page.locator('.studio-form input[type="file"]'); + ok('two first/last frame inputs', (await uploads.count()) === 2); + await uploads.nth(0).setInputFiles(path.join(ROOT, '../calliope-web/static/refract/coast.jpg')); + await uploads.nth(1).setInputFiles(path.join(ROOT, '../calliope-web/static/refract/arch.jpg')); + await until(async () => (await page.locator('.studio-form img').count()) >= 2); + await page.fill('#desk-prompt', '切换后保留提示词与首尾帧'); + const inputSources = await page + .locator('.studio-form img') + .evaluateAll((els) => els.map((e) => e.getAttribute('src'))); + await page.locator('.model-selector').click(); + await page.fill('[aria-label="搜索工作流"]', h3Copy.name); + await page.getByRole('button', { name: '查看 ' + h3Copy.name, exact: true }).click(); + await page.getByRole('button', { name: '使用这个工具 →', exact: true }).click(); + await page.locator('#desk-prompt').waitFor(); + ok( + 'first uncached workflow keeps prompt', + (await page.inputValue('#desk-prompt')) === '切换后保留提示词与首尾帧', + ); + ok( + 'first uncached workflow keeps uploaded frames', + JSON.stringify( + await page + .locator('.studio-form img') + .evaluateAll((els) => els.map((e) => e.getAttribute('src'))), + ) === JSON.stringify(inputSources), + ); + await page.route(/\/api\/workflows\?view=meta$/, async (route) => { + const response = await route.fetch(); + await new Promise((r) => setTimeout(r, 1000)); + await route.fulfill({ response }); + }); + const delayedMeta = page.waitForResponse(/\/api\/workflows\?view=meta$/); + await page.reload(); + await delayedMeta; + await page.locator('#desk-prompt').waitFor(); + await page.waitForTimeout(150); + await page.unrouteAll({ behavior: 'wait' }); + ok( + 'reload restores the chosen workflow and prompt', + (await page.inputValue('#desk-prompt')) === '切换后保留提示词与首尾帧' && + (await page.locator('.model-selector').innerText()).includes(h3Copy.name), + ); + ok( + 'reload restores first and last frame inputs', + JSON.stringify( + await page + .locator('.studio-form img') + .evaluateAll((els) => els.map((e) => e.getAttribute('src'))), + ) === JSON.stringify(inputSources), + ); + await page.locator('.model-selector').click(); + await page.fill('[aria-label="搜索工作流"]', h3.name); + await page.getByRole('button', { name: '查看 ' + h3.name, exact: true }).click(); + await page.getByRole('button', { name: '使用这个工具 →', exact: true }).click(); + await page.locator('#desk-prompt').waitFor(); + submitted = page.waitForRequest( + (r) => r.url().endsWith('/api/playground/generate') && r.method() === 'POST', + ); + await page.locator('.studio-form .gen').click(); + const body = (await submitted).postDataJSON(); + ok( + 'first and last frame distinct in API payload', + typeof body.input_values[2] === 'string' && + typeof body.input_values[3] === 'string' && + body.input_values[2] !== body.input_values[3], + ); + const video = await until(async () => + (await api('/api/playground/jobs')).find((j) => j.workflow_id === h3.id && j.status === 'done'), + ); + jobs.push(video.id); + await page.locator('.inspector.main video').waitFor(); + ok( + 'video playback and tail export preserved', + (await page.getByRole('button', { name: '导出尾帧' }).count()) > 0, + ); + await page.locator('.studio-form .gen').click(); + const secondVideo = await until(async () => + (await api('/api/playground/jobs')).find( + (j) => j.workflow_id === h3.id && j.status === 'done' && j.id !== video.id, + ), + ); + jobs.push(secondVideo.id); + await page.locator(`.result-item[aria-label^="查看第 ${secondVideo.id} 次"]`).waitFor(); + await page.getByRole('button', { name: '播放视频', exact: true }).click(); + await page.getByRole('button', { name: '暂停视频', exact: true }).waitFor(); + await page.locator(`.result-item[aria-label^="查看第 ${video.id} 次"]`).click(); + ok( + 'result switch has one complete player and remains paused', + (await page.locator('.inspector.main video').count()) === 1 && + (await page.locator('.inspector.main video').evaluate((v) => v.paused)), + ); + await page.screenshot({ path: SHOTS + '/video.png' }); + await page.goto(WEB + '/workflows'); + await page.locator('.workflow-card').first().waitFor(); + ok( + 'catalogue renders incremental 48-card page', + (await page.locator('.workflow-card').count()) === 48, + ); + await page.fill('[aria-label="搜索工作流"]', '文生图·回归'); + await until(async () => (await page.locator('.workflow-card').count()) === 1); + const fav = page.locator('.favorite').first(), + before = await fav.getAttribute('aria-pressed'); + await fav.click(); + await until(async () => (await fav.getAttribute('aria-pressed')) !== before); + ok( + 'favorite persisted through API', + (await api('/api/workflows/' + image.id)).favorite === (before !== 'true'), + ); + await fav.click(); + await page.fill('[aria-label="搜索工作流"]', ''); + await page.screenshot({ path: SHOTS + '/catalogue.png' }); + await page.getByRole('button', { name: '导入与管理 ↗' }).click(); + ok( + 'bulk importer remains accessible', + (await page.getByRole('button', { name: /批量导入/ }).count()) > 0, + ); + await page.goto(WEB + '/agents'); + await page.locator('.agent-list').waitFor(); + ok( + 'five agent cards and skill editor', + (await page.locator('.agent-row').count()) === 5 && + (await page.locator('.skill-lib').count()) > 0, + ); + await page.locator('.agent-row').nth(1).click(); + ok('role selects actual chat', (await page.locator('.chat-head h2').innerText()) === '视觉设计'); + await page.screenshot({ path: SHOTS + '/agents.png' }); + await page.goto(WEB + '/canvas'); + await page.locator('.svelte-flow').waitFor(); + ok('canvas opens actual persisted graph', new URL(page.url()).pathname.startsWith('/canvas/')); + await page.screenshot({ path: SHOTS + '/canvas.png' }); + await page.goto(WEB + `/video?wf=${h3.id}`); + await page.locator('.inspector.main video').waitFor(); + await page.waitForTimeout(300); + ok( + 'entering page does not autoplay', + await page.locator('.inspector.main video').evaluate((v) => v.paused), + ); + await page.getByRole('button', { name: '播放视频', exact: true }).click(); + await page.getByRole('button', { name: '暂停视频', exact: true }).waitFor(); + ok( + 'explicit playback changes state', + await page.locator('.inspector.main video').evaluate((v) => !v.paused), + ); + await page.getByRole('button', { name: '暂停视频', exact: true }).click(); + await page.evaluate(() => document.activeElement?.blur()); + await page.keyboard.press('Space'); + ok( + 'space outside player does not change playback', + await page.locator('.inspector.main video').evaluate((v) => v.paused), + ); + for (const [width, height] of [ + [1366, 768], + [1280, 720], + [1100, 600], + [960, 540], + [1920, 1080], + ]) { + await page.setViewportSize({ width, height }); + await page.goto(WEB + `/video?wf=${h3.id}`); + await page.locator('.inspector.main video').waitFor(); + const visible = await page.evaluate(() => { + const v = document.querySelector('.inspector.main video').getBoundingClientRect(), + stage = document.querySelector('.inspector.main .stage').getBoundingClientRect(), + gen = document.querySelector('.studio-form .gen').getBoundingClientRect(), + play = document.querySelector('.playback-bar').getBoundingClientRect(); + return ( + v.bottom <= stage.bottom + 1 && + v.right <= stage.right + 1 && + gen.bottom <= innerHeight && + gen.top >= 0 && + play.bottom <= innerHeight && + document.documentElement.scrollWidth <= innerWidth + ); + }); + ok(`entire video, playback and generate visible at ${width}x${height}`, visible); + ok( + `result operations remain fully visible at ${width}x${height}`, + await page.evaluate(() => { + const body = document.querySelector('.inspector.main .body').getBoundingClientRect(); + return [...document.querySelectorAll('.inspector.main .actions .a-btn')].every((e) => { + const r = e.getBoundingClientRect(); + return r.bottom <= body.bottom + 1 && r.bottom <= innerHeight; + }); + }), + ); + await page.screenshot({ path: SHOTS + `/workspace-${width}x${height}.png` }); + await page.locator('.model-selector').click(); + await page.locator('.tool-picker').waitFor(); + const confirm = await page + .getByRole('button', { name: '使用这个工具 →', exact: true }) + .boundingBox(); + ok(`tool confirmation visible at ${width}x${height}`, confirm.y + confirm.height <= height); + await page.keyboard.press('Escape'); + } + const zoomContext = await browser.newContext({ + viewport: { width: 960, height: 540 }, + deviceScaleFactor: 1.5, + }); + const zoomPage = await zoomContext.newPage(); + await zoomPage.goto(WEB + `/video?wf=${h3.id}`); + await zoomPage.locator('.inspector.main video').waitFor(); + ok( + '150 percent equivalent desktop viewport keeps primary controls visible', + await zoomPage.evaluate(() => { + const gen = document.querySelector('.studio-form .gen').getBoundingClientRect(), + play = document.querySelector('.playback-bar').getBoundingClientRect(); + return devicePixelRatio === 1.5 && gen.bottom <= innerHeight && play.bottom <= innerHeight; + }), + ); + await zoomPage.screenshot({ path: SHOTS + '/zoom-equivalent-150.png' }); + await zoomContext.close(); + await page.emulateMedia({ reducedMotion: 'reduce' }); + ok( + 'reduced motion disables transitions', + await page + .locator('.studio-form .gen') + .evaluate((e) => parseFloat(getComputedStyle(e).transitionDuration) < 0.02), + ); + ok('no JavaScript or console errors', errors.length === 0); + if (errors.length) console.log(errors); +} finally { + if (browser) await browser.close(); + for (const id of jobs) await api('/api/playground/jobs/' + id, null, 'DELETE').catch(() => {}); + for (const id of workflows) await api('/api/workflows/' + id, null, 'DELETE').catch(() => {}); + for (const id of projects) await api('/api/projects/' + id, null, 'DELETE').catch(() => {}); + if (savedMode) fs.writeFileSync(modePath, savedMode); + else fs.rmSync(modePath, { force: true }); +} +console.log(`${checks - failures}/${checks} passed`); +if (failures) process.exitCode = 1; diff --git a/e2e/shoot.mjs b/e2e/shoot.mjs index 17c7addc..cf70850e 100644 --- a/e2e/shoot.mjs +++ b/e2e/shoot.mjs @@ -69,14 +69,15 @@ const run = async () => { const page = await ctx.newPage(); page.on('pageerror', (e) => console.log('PAGEERROR:', e.message)); - // ---------- 工作流选择器:↑↓ 高亮 + Enter 使用 ---------- + // ---------- 挑选台(HEL-683 三段式):摘要带展开 → ↑↓ 高亮 + Enter 使用 ---------- await page.goto('http://127.0.0.1:5173/image'); await page.waitForSelector('#desk-prompt', { timeout: 15000 }); - await page.click('#desk-wf'); - await page.waitForSelector('.shell-pop'); - const activeRows = page.locator('.shell-pop .row.active'); + await page.click('.bay-band .band-hit'); + await page.waitForSelector('.bay .row.active', { timeout: 10000 }); + await page.waitForSelector('.bay .search-input'); + const activeRows = page.locator('.bay .row.active'); const nActive = await activeRows.count(); - ok('工作流面板有默认高亮行', nActive === 1); + ok('挑选台有默认高亮行', nActive === 1); await page.keyboard.press('ArrowDown'); await page.keyboard.press('ArrowDown'); const label1 = await activeRows.first().textContent(); @@ -86,15 +87,19 @@ const run = async () => { const chipBefore = await page.locator('#desk-wf .lbl').textContent(); await page.keyboard.press('Enter'); await page.waitForTimeout(400); + ok('Enter 使用高亮的工作流(挑选台收起)', (await page.locator('.bay.open').count()) === 0); const chipAfter = await page.locator('#desk-wf .lbl').textContent(); - ok('Enter 使用高亮的工作流', chipBefore !== chipAfter || (await activeRows.count()) === 0, `${chipBefore} → ${chipAfter}`); - await page.screenshot({ path: `${SHOTS}/01-picker-roving.png` }); + ok('输入台芯片跟随选中工作流', chipBefore !== chipAfter, `${chipBefore} → ${chipAfter}`); + await page.screenshot({ path: `${SHOTS}/01-bay-roving.png` }); - // 回到文生图工作流 - await page.click('#desk-wf'); - await page.fill('.shell-pop .search-input', '文生图'); + // 回到文生图工作流(搜索唯一命中「回归」) + await page.click('.bay-band .band-hit'); + await page.waitForSelector('.bay .search-input'); + await page.fill('.bay .search-input', '回归'); + await page.waitForSelector('.bay .row.active'); await page.keyboard.press('Enter'); await page.waitForTimeout(300); + ok('搜索后 Enter 选中文生图工作流', (await page.locator('#desk-wf .lbl').textContent()).includes('文生图')); // ---------- 提交 → 完成(绿标签 + 自动切结果页) ---------- setMode({ mode: 'ok', delay_sec: 0 }); @@ -116,9 +121,9 @@ const run = async () => { // 绿标签 const doneCard = page.locator('.take', { hasText: '柴犬' }).first(); const doneTag = await doneCard.locator('.state .a-tag').first().textContent(); - ok('完成态为绿色「完成」标签(非金色)', (doneTag || '').includes('完成'), doneTag); + ok('完成态为「定影」标签(HEL-680 灰阶语义)', (doneTag || '').includes('定影'), doneTag); const tagColor = await doneCard.locator('.state .a-tag').first().evaluate((el) => getComputedStyle(el).color); - ok('完成标签用信号绿 rgb(73,203,144)', tagColor === 'rgb(73, 203, 144)', tagColor); + ok('完成标签用灰阶信号色 rgb(221,221,215)', tagColor === 'rgb(221, 221, 215)', tagColor); await page.screenshot({ path: `${SHOTS}/02-desk-done.png` }); // ---------- 慢任务:排队灰 + 运行青 + 进度条 ---------- @@ -130,9 +135,9 @@ const run = async () => { await page.click('.a-btn.primary'); // 第二个:queued 灰 await page.waitForTimeout(4000); const runTag = await stateTag(page, '观察进度').textContent(); - ok('运行中为青色「生成中」', /生成中|执行/.test(runTag || ''), runTag); + ok('运行中为「生成中/执行中」', /生成中|执行/.test(runTag || ''), runTag); const runTagColor = await stateTag(page, '观察进度').evaluate((el) => getComputedStyle(el).color); - ok('运行标签用信号青 rgb(84,223,210)', runTagColor === 'rgb(84, 223, 210)', runTagColor); + ok('运行标签用灰阶信号色 rgb(184,182,172)', runTagColor === 'rgb(184, 182, 172)', runTagColor); const hasBar = (await page.locator('.take', { hasText: '观察进度' }).locator('.a-progress').count()) > 0; ok('运行中卡片有进度条', hasBar); const queueTag = await stateTag(page, '第二个任务').textContent(); @@ -175,7 +180,7 @@ const run = async () => { const failTag = await failCard.locator('.state .a-tag').first().textContent(); ok('失败为红色「失败」标签', (failTag || '').includes('失败'), failTag); const failColor = await failCard.locator('.state .a-tag').first().evaluate((el) => getComputedStyle(el).color); - ok('失败标签用信号红 rgb(240,100,90)', failColor === 'rgb(240, 100, 90)', failColor); + ok('失败标签用信号红 rgb(208,122,107)(灰阶底上的红)', failColor === 'rgb(208, 122, 107)', failColor); const errLine = failCard.locator('.err-txt'); ok('失败自动展开一行中文结论', (await errLine.count()) === 1 && (await errLine.textContent()).length > 4); await errLine.click(); @@ -199,7 +204,7 @@ const run = async () => { const undoBtn = page.locator('.toast .action', { hasText: '撤销' }); ok('出现带「撤销」的 Toast', (await undoBtn.count()) === 1); const undoColor = await undoBtn.evaluate((el) => getComputedStyle(el).color); - ok('撤销动作按钮为金色文字 rgb(242,199,132)', undoColor === 'rgb(242, 199, 132)', undoColor); + ok('撤销动作按钮为强调白文字 rgb(245,244,238)', undoColor === 'rgb(245, 244, 238)', undoColor); await page.screenshot({ path: `${SHOTS}/05-undo-toast.png` }); const countDeleted = await cardCount(page); ok('删除后行立即收起', countDeleted === countBefore - 1, `${countBefore} → ${countDeleted}`); @@ -237,7 +242,7 @@ const run = async () => { const goneTag = await goneCard.locator('.state .a-tag').first().textContent(); ok('文件缺失为琥珀「文件缺失」', (goneTag || '').includes('文件缺失'), goneTag); const goneColor = await goneCard.locator('.state .a-tag').first().evaluate((el) => getComputedStyle(el).color); - ok('缺失标签用琥珀 rgb(240,180,92)', goneColor === 'rgb(240, 180, 92)', goneColor); + ok('缺失标签用信号琥珀 rgb(163,145,95)', goneColor === 'rgb(163, 145, 95)', goneColor); ok('缺失态给「用相同参数重做」', (await goneCard.getByRole('button', { name: '用相同参数重做' }).count()) === 1); ok('缺失态给「移除记录」', (await goneCard.getByRole('button', { name: '移除记录' }).count()) === 1); await goneCard.getByRole('button', { name: '用相同参数重做' }).click(); @@ -284,7 +289,7 @@ const run = async () => { ok('任务页筛选芯片组(含失败/进行中)', (await chips.count()) === 5); // 默认「全部」选中即金色文字(accent-soft 底) const selChipColor = await chips.first().evaluate((el) => getComputedStyle(el).color); - ok('选中筛选芯片为金色文字', selChipColor === 'rgb(242, 199, 132)', selChipColor); + ok('选中筛选芯片为强调白文字', selChipColor === 'rgb(245, 244, 238)', selChipColor); const failedChipColor = await chips.nth(3).evaluate((el) => getComputedStyle(el).color); await chips.nth(3).click(); // 失败 await page.waitForTimeout(300);