798 lines
30 KiB
Python
798 lines
30 KiB
Python
"""Standalone ComfyUI playground — generate freely, attach favorites to projects."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import re
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
from typing import Any, Literal
|
||
from uuid import uuid4
|
||
|
||
from fastapi import APIRouter, File, HTTPException, UploadFile
|
||
from pydantic import BaseModel, Field
|
||
|
||
from calliope import config
|
||
from calliope.agent.prompts import item_reference_prompt
|
||
from calliope.comfyui.lint import blocking_problem
|
||
from calliope.comfyui.output_map import mapping_problem
|
||
from calliope.comfyui.parser import effective_input_schema
|
||
from calliope.comfyui.validate import validate_input_values
|
||
from calliope.db import get_db, row_to_dict
|
||
from calliope.events.bus import event_bus
|
||
from calliope.queue.manager import queue_manager
|
||
|
||
router = APIRouter()
|
||
|
||
PLAYGROUND_STATUS = "system"
|
||
PLAYGROUND_TITLE = "Playground Scratch"
|
||
|
||
|
||
# Where the request came from — recorded on the job payload so the tasks
|
||
# 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
|
||
input_values: dict[str, Any] = Field(default_factory=dict)
|
||
# Optional target connection; omitted → the workflow's bound connection,
|
||
# 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):
|
||
path: str
|
||
project_id: int
|
||
target: Literal["character_sheet", "location", "item", "scene"]
|
||
character_id: int | None = None
|
||
location_id: int | None = None
|
||
item_id: int | None = None # ignored: items always insert a new row
|
||
scene_id: int | None = None
|
||
name: str | None = None
|
||
|
||
|
||
def _job_public(job: dict[str, Any]) -> dict[str, Any]:
|
||
out = dict(job)
|
||
out["payload"] = json.loads(job.get("payload_json") or "{}")
|
||
out["output_paths"] = json.loads(job.get("output_paths_json") or "[]")
|
||
out.pop("payload_json", None)
|
||
out.pop("output_paths_json", None)
|
||
return out
|
||
|
||
|
||
def ensure_playground_project(conn) -> int:
|
||
row = conn.execute(
|
||
"SELECT id FROM projects WHERE status = ? ORDER BY id ASC LIMIT 1",
|
||
(PLAYGROUND_STATUS,),
|
||
).fetchone()
|
||
if row:
|
||
return int(row["id"])
|
||
cur = conn.execute(
|
||
"""
|
||
INSERT INTO projects (title, idea, status)
|
||
VALUES (?, ?, ?)
|
||
""",
|
||
(
|
||
PLAYGROUND_TITLE,
|
||
"System scratch for ComfyUI playground jobs — hidden from project list",
|
||
PLAYGROUND_STATUS,
|
||
),
|
||
)
|
||
conn.commit()
|
||
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()
|
||
try:
|
||
target.relative_to(assets_root)
|
||
except ValueError as exc:
|
||
raise HTTPException(status_code=403, detail="Path outside assets directory") from exc
|
||
if not target.exists() or not target.is_file():
|
||
raise HTTPException(status_code=404, detail="File not found")
|
||
return target
|
||
|
||
|
||
def _safe_unlink_asset(path_str: str) -> bool:
|
||
"""Delete a file if it resolves under assets_dir. Missing files count as already gone."""
|
||
assets_root = config.settings.assets_dir.resolve()
|
||
try:
|
||
target = Path(path_str).resolve()
|
||
target.relative_to(assets_root)
|
||
except (ValueError, OSError):
|
||
return False
|
||
if not target.is_file():
|
||
return False
|
||
try:
|
||
target.unlink()
|
||
return True
|
||
except OSError:
|
||
return False
|
||
|
||
|
||
UPLOAD_KIND_BY_EXT: dict[str, str] = {
|
||
".png": "image",
|
||
".jpg": "image",
|
||
".jpeg": "image",
|
||
".webp": "image",
|
||
".gif": "image",
|
||
".bmp": "image",
|
||
".mp4": "video",
|
||
".webm": "video",
|
||
".mov": "video",
|
||
".mkv": "video",
|
||
".mp3": "audio",
|
||
".wav": "audio",
|
||
".flac": "audio",
|
||
".ogg": "audio",
|
||
# Note: core ComfyUI's LoadAudio file list is typically wav/mp3/ogg/flac/aiff.
|
||
# .m4a uploads succeed here and land in Comfy's input dir, but some builds
|
||
# reject it at /prompt validation — prefer wav/mp3 for ref audio.
|
||
".m4a": "audio",
|
||
# Documents are agent-context material (script uploads projected as text),
|
||
# never Comfy job inputs — the agent routers' kind validators accept them.
|
||
".txt": "document",
|
||
".md": "document",
|
||
".docx": "document",
|
||
}
|
||
|
||
UPLOAD_CHUNK_SIZE = 1024 * 1024 # 1MB
|
||
UPLOAD_MAX_BYTES = 500 * 1024 * 1024 # 500MB
|
||
DOCUMENT_MAX_BYTES = 5 * 1024 * 1024 # 5MB — docs feed the LLM context, not Comfy
|
||
_UPLOAD_PREFIX_RE = re.compile(r"^[0-9a-f]{8}-")
|
||
|
||
|
||
def _kind_for_ext(ext: str) -> str | None:
|
||
return UPLOAD_KIND_BY_EXT.get(ext.lower())
|
||
|
||
|
||
def _uploads_dir() -> Path:
|
||
return config.settings.assets_dir / "uploads"
|
||
|
||
|
||
def _safe_upload_name(filename: str) -> str:
|
||
return re.sub(r"[^A-Za-z0-9._-]", "_", filename)
|
||
|
||
|
||
def _upload_display_name(filename: str) -> str:
|
||
"""Strip the uuid prefix written at upload time (``deadbeef-name.png`` → ``name.png``)."""
|
||
if _UPLOAD_PREFIX_RE.match(filename):
|
||
return filename[9:]
|
||
return filename
|
||
|
||
|
||
def _clear_entity_refs(conn, paths: list[str]) -> None:
|
||
"""If playground outputs were attached to entities, clear those path columns."""
|
||
for path in paths:
|
||
conn.execute("UPDATE characters SET portrait_path = NULL WHERE portrait_path = ?", (path,))
|
||
conn.execute("UPDATE characters SET sheet_path = NULL WHERE sheet_path = ?", (path,))
|
||
conn.execute(
|
||
"UPDATE locations SET reference_image_path = NULL WHERE reference_image_path = ?",
|
||
(path,),
|
||
)
|
||
conn.execute(
|
||
"UPDATE items SET reference_image_path = NULL WHERE reference_image_path = ?",
|
||
(path,),
|
||
)
|
||
conn.execute("UPDATE scenes SET video_path = NULL WHERE video_path = ?", (path,))
|
||
|
||
|
||
@router.get("/project")
|
||
async def playground_project() -> dict[str, Any]:
|
||
conn = get_db(config.settings.db_path)
|
||
try:
|
||
pid = ensure_playground_project(conn)
|
||
row = conn.execute("SELECT * FROM projects WHERE id = ?", (pid,)).fetchone()
|
||
return row_to_dict(row)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
@router.get("/jobs")
|
||
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
|
||
# surface in the studio windows' history — they carry their own dialog.
|
||
jobs = [
|
||
j
|
||
for j in queue_manager.list_jobs(pid, None, limit)
|
||
if str(j.get("origin") or "user") != "workflow_test"
|
||
]
|
||
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}")
|
||
async def delete_playground_job(job_id: int) -> dict[str, Any]:
|
||
"""Delete a playground job row and its output files under assets_dir."""
|
||
conn = get_db(config.settings.db_path)
|
||
try:
|
||
pid = ensure_playground_project(conn)
|
||
finally:
|
||
conn.close()
|
||
|
||
job = queue_manager.get_job(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")
|
||
|
||
paths = json.loads(job.get("output_paths_json") or "[]")
|
||
if not isinstance(paths, list):
|
||
paths = []
|
||
|
||
deleted_files: list[str] = []
|
||
missing_files: list[str] = []
|
||
for p in paths:
|
||
if not isinstance(p, str) or not p.strip():
|
||
continue
|
||
if _safe_unlink_asset(p):
|
||
deleted_files.append(p)
|
||
else:
|
||
missing_files.append(p)
|
||
|
||
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()
|
||
|
||
removed = queue_manager.delete_job(job_id)
|
||
if not removed:
|
||
raise HTTPException(status_code=404, detail="Job not found")
|
||
|
||
await event_bus.publish(
|
||
"job.deleted",
|
||
{
|
||
"job_id": job_id,
|
||
"source": "playground",
|
||
"deleted_files": deleted_files,
|
||
"missing_files": missing_files,
|
||
},
|
||
)
|
||
return {
|
||
"ok": True,
|
||
"job_id": job_id,
|
||
"deleted_files": deleted_files,
|
||
"missing_files": missing_files,
|
||
"removed_workbench_links": removed_links,
|
||
}
|
||
|
||
|
||
@router.post("/uploads")
|
||
async def upload_media(file: UploadFile = File(...)) -> dict[str, Any]:
|
||
"""Store a client-provided media file under assets_dir/uploads for use as a job input."""
|
||
original = Path(file.filename or "upload").name
|
||
ext = Path(original).suffix.lower()
|
||
kind = _kind_for_ext(ext)
|
||
if kind is None:
|
||
allowed = " ".join(sorted(UPLOAD_KIND_BY_EXT))
|
||
raise HTTPException(
|
||
status_code=400,
|
||
detail=f"Unsupported file type '{ext or '(none)'}'. Allowed extensions: {allowed}",
|
||
)
|
||
|
||
uploads = _uploads_dir()
|
||
uploads.mkdir(parents=True, exist_ok=True)
|
||
dest = uploads / f"{uuid4().hex[:8]}-{_safe_upload_name(original)}"
|
||
|
||
size = 0
|
||
max_bytes = DOCUMENT_MAX_BYTES if kind == "document" else UPLOAD_MAX_BYTES
|
||
try:
|
||
with dest.open("wb") as out:
|
||
while chunk := await file.read(UPLOAD_CHUNK_SIZE):
|
||
size += len(chunk)
|
||
if size > max_bytes:
|
||
limit = "5MB" if kind == "document" else "500MB"
|
||
raise HTTPException(status_code=413, detail=f"File too large (max {limit})")
|
||
out.write(chunk)
|
||
except Exception:
|
||
dest.unlink(missing_ok=True)
|
||
raise
|
||
|
||
return {"ok": True, "path": str(dest.resolve()), "name": original, "kind": kind}
|
||
|
||
|
||
@router.get("/uploads")
|
||
async def list_uploaded_media() -> list[dict[str, Any]]:
|
||
"""List previously uploaded media files, newest first."""
|
||
uploads = _uploads_dir()
|
||
if not uploads.is_dir():
|
||
return []
|
||
entries: list[tuple[float, dict[str, Any]]] = []
|
||
for f in uploads.iterdir():
|
||
if not f.is_file():
|
||
continue
|
||
kind = _kind_for_ext(f.suffix)
|
||
if kind is None:
|
||
continue
|
||
stat = f.stat()
|
||
tags = None
|
||
sidecar = Path(str(f) + ".meta.json")
|
||
if sidecar.is_file():
|
||
try:
|
||
meta = json.loads(sidecar.read_text(encoding="utf-8"))
|
||
tags = meta.get("tags") if isinstance(meta, dict) else None
|
||
except (OSError, json.JSONDecodeError):
|
||
tags = None
|
||
entries.append(
|
||
(
|
||
stat.st_mtime,
|
||
{
|
||
"name": _upload_display_name(f.name),
|
||
"path": str(f.resolve()),
|
||
"kind": kind,
|
||
"size": stat.st_size,
|
||
"mtime": datetime.fromtimestamp(stat.st_mtime, tz=timezone.utc).isoformat(),
|
||
"tags": tags,
|
||
},
|
||
)
|
||
)
|
||
entries.sort(key=lambda e: e[0], reverse=True)
|
||
return [item for _, item in entries]
|
||
|
||
|
||
@router.post("/generate")
|
||
async def generate(payload: PlaygroundGenerate) -> dict[str, Any]:
|
||
conn = get_db(config.settings.db_path)
|
||
try:
|
||
pid = ensure_playground_project(conn)
|
||
wf = conn.execute(
|
||
"SELECT id, kind, is_enabled, workflow_json, input_schema, output_map,"
|
||
" output_map_source FROM workflows WHERE id = ?",
|
||
(payload.workflow_id,),
|
||
).fetchone()
|
||
if not wf:
|
||
raise HTTPException(
|
||
status_code=404, detail="工作流不存在(可能已被删除),请刷新页面后重新选择"
|
||
)
|
||
if not wf["is_enabled"]:
|
||
raise HTTPException(
|
||
status_code=400, detail="该工作流已停用,请到「ComfyUI 连接」页启用后再生成"
|
||
)
|
||
kind = wf["kind"]
|
||
workflow_json = json.loads(wf["workflow_json"])
|
||
# HEL-638: a workflow with unknown custom output nodes must have a
|
||
# confirmed output mapping before anything is queued.
|
||
map_problem = mapping_problem(workflow_json, wf["output_map"], wf["output_map_source"])
|
||
if map_problem:
|
||
raise HTTPException(status_code=400, detail=map_problem)
|
||
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()
|
||
|
||
broken = blocking_problem(workflow_json)
|
||
if broken:
|
||
raise HTTPException(status_code=400, detail=broken)
|
||
|
||
input_values, problems = validate_input_values(schema, payload.input_values)
|
||
if problems:
|
||
raise HTTPException(status_code=400, detail="参数有误:" + ";".join(problems))
|
||
|
||
job = queue_manager.enqueue(
|
||
project_id=pid,
|
||
kind=kind,
|
||
workflow_id=payload.workflow_id,
|
||
scene_id=None,
|
||
payload={
|
||
"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(
|
||
"job.created",
|
||
{"job_id": job["id"], "kind": kind, "source": payload.source, "project_id": pid},
|
||
)
|
||
return {"ok": True, "job": _job_public(job)}
|
||
|
||
|
||
@router.post("/attach")
|
||
async def attach_to_project(payload: PlaygroundAttach) -> dict[str, Any]:
|
||
path = str(_assert_path_in_assets(payload.path))
|
||
conn = get_db(config.settings.db_path)
|
||
try:
|
||
project = conn.execute(
|
||
"SELECT id, status FROM projects WHERE id = ?", (payload.project_id,)
|
||
).fetchone()
|
||
if not project:
|
||
raise HTTPException(status_code=404, detail="Project not found")
|
||
if project["status"] == PLAYGROUND_STATUS:
|
||
raise HTTPException(status_code=400, detail="Cannot attach to playground scratch")
|
||
|
||
if payload.target == "character_sheet":
|
||
if not payload.character_id:
|
||
raise HTTPException(status_code=400, detail="character_id required")
|
||
char = conn.execute(
|
||
"SELECT id FROM characters WHERE id = ? AND project_id = ?",
|
||
(payload.character_id, payload.project_id),
|
||
).fetchone()
|
||
if not char:
|
||
raise HTTPException(status_code=404, detail="Character not found")
|
||
conn.execute(
|
||
"UPDATE characters SET sheet_path = ? WHERE id = ?",
|
||
(path, payload.character_id),
|
||
)
|
||
elif payload.target == "location":
|
||
if not payload.location_id:
|
||
raise HTTPException(status_code=400, detail="location_id required")
|
||
loc = conn.execute(
|
||
"SELECT id FROM locations WHERE id = ? AND project_id = ?",
|
||
(payload.location_id, payload.project_id),
|
||
).fetchone()
|
||
if not loc:
|
||
raise HTTPException(status_code=404, detail="Location not found")
|
||
conn.execute(
|
||
"UPDATE locations SET reference_image_path = ? WHERE id = ?",
|
||
(path, payload.location_id),
|
||
)
|
||
elif payload.target == "item":
|
||
# Always insert a new misc. item — Playground attach must not
|
||
# overwrite an existing project item (item_id is ignored).
|
||
raw_name = (payload.name or "").strip()
|
||
if not raw_name:
|
||
stem = Path(path).stem
|
||
raw_name = stem.split("-", 1)[-1] if len(stem) > 9 and stem[8:9] == "-" else stem
|
||
name = raw_name or "Playground item"
|
||
consistency = item_reference_prompt(
|
||
{"name": name, "description": "Added from Playground"}
|
||
)
|
||
cur = conn.execute(
|
||
"""
|
||
INSERT INTO items (
|
||
project_id, name, description, consistency_prompt, reference_image_path
|
||
)
|
||
VALUES (?, ?, ?, ?, ?)
|
||
""",
|
||
(payload.project_id, name, "Added from Playground", consistency, path),
|
||
)
|
||
created_item_id = int(cur.lastrowid)
|
||
elif payload.target == "scene":
|
||
if not payload.scene_id:
|
||
raise HTTPException(status_code=400, detail="scene_id required")
|
||
scene = conn.execute(
|
||
"SELECT id FROM scenes WHERE id = ? AND project_id = ?",
|
||
(payload.scene_id, payload.project_id),
|
||
).fetchone()
|
||
if not scene:
|
||
raise HTTPException(status_code=404, detail="Scene not found")
|
||
conn.execute(
|
||
"UPDATE scenes SET video_path = ? WHERE id = ?",
|
||
(path, payload.scene_id),
|
||
)
|
||
else:
|
||
raise HTTPException(status_code=400, detail="Invalid target")
|
||
|
||
conn.execute(
|
||
"UPDATE projects SET updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||
(payload.project_id,),
|
||
)
|
||
conn.commit()
|
||
await event_bus.publish(
|
||
"asset.ready",
|
||
{
|
||
"path": path,
|
||
"project_id": payload.project_id,
|
||
"target": payload.target,
|
||
"source": "playground_attach",
|
||
},
|
||
)
|
||
out: dict[str, Any] = {
|
||
"ok": True,
|
||
"path": path,
|
||
"target": payload.target,
|
||
"project_id": payload.project_id,
|
||
}
|
||
if payload.target == "item":
|
||
out["item_id"] = created_item_id
|
||
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,
|
||
}
|