Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea3a1c6f06 | ||
|
|
e2b69aff16 | ||
|
|
cb35d9819a | ||
|
|
afbf50447a | ||
|
|
ab48895b99 | ||
|
|
dca216e2c7 | ||
|
|
37cb6ec209 | ||
|
|
31e5906462 | ||
|
|
8d7e58645c | ||
|
|
930cca653f | ||
|
|
15ff2a3cac | ||
|
|
3dfed6780c | ||
|
|
f2ca010fcd | ||
|
|
30851d57f1 | ||
|
|
a1c01f1e90 | ||
|
|
fb6139d45c | ||
|
|
af0417e874 | ||
|
|
b2bcbc10df |
@@ -156,7 +156,8 @@
|
||||
"job.started",
|
||||
"shot.capture.saved",
|
||||
"shot.updated",
|
||||
"story.ready"
|
||||
"story.ready",
|
||||
"workbench.stage.updated"
|
||||
],
|
||||
"prompt_profiles": [
|
||||
"minimax_h3_ref",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Capture successful task replies without treating chat/errors as confirmed work."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db
|
||||
|
||||
|
||||
def complete_task(session_id: int, final: str) -> None:
|
||||
from calliope.agent.harness.plugins.interaction import latest_open_question
|
||||
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if latest_open_question(session_id):
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_status='awaiting_input' WHERE id=?", (session_id,)
|
||||
)
|
||||
else:
|
||||
session = conn.execute(
|
||||
"SELECT * FROM agent_sessions WHERE id=?", (session_id,)
|
||||
).fetchone()
|
||||
message = conn.execute(
|
||||
"SELECT id FROM agent_messages WHERE session_id=? AND role='assistant' "
|
||||
"AND content=? AND (status IS NULL OR status NOT IN ('error','cancelled')) "
|
||||
"ORDER BY id DESC LIMIT 1",
|
||||
(session_id, final),
|
||||
).fetchone()
|
||||
if session and message and final.strip():
|
||||
conn.execute(
|
||||
"INSERT OR IGNORE INTO agent_deliverables "
|
||||
"(session_id,source_message_id,project_id,stage_key,title,content) "
|
||||
"VALUES (?,?,?,?,?,?)",
|
||||
(
|
||||
session_id,
|
||||
message["id"],
|
||||
session["project_id"],
|
||||
session["agent_key"] or "script",
|
||||
session["title"][:200],
|
||||
final,
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_status='awaiting_confirm' WHERE id=?",
|
||||
(session_id,),
|
||||
)
|
||||
else:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_status='completed' WHERE id=?", (session_id,)
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -40,8 +40,10 @@ class AgentRunner:
|
||||
conn = self._db()
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET status = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(status, session_id),
|
||||
"UPDATE agent_sessions SET status = ?, task_status=CASE "
|
||||
"WHEN ? = 'running' THEN 'running' WHEN ? = 'error' THEN 'error' "
|
||||
"ELSE task_status END, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
|
||||
(status, status, status, session_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
@@ -201,7 +203,8 @@ class AgentRunner:
|
||||
).fetchall()]
|
||||
if stuck:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET status = 'idle' WHERE status = 'running'"
|
||||
"UPDATE agent_sessions SET status = 'idle', task_status='interrupted' "
|
||||
"WHERE status = 'running'"
|
||||
)
|
||||
conn.commit()
|
||||
logger.warning(
|
||||
@@ -295,6 +298,15 @@ class AgentRunner:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
conn = self._db()
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_summary=? WHERE id=?",
|
||||
(user_message.strip()[:300], session_id),
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
self._set_status(session_id, "running")
|
||||
task = asyncio.create_task(
|
||||
self._run_session(session_id), name=f"agent-session-{session_id}"
|
||||
@@ -398,6 +410,9 @@ class AgentRunner:
|
||||
session_id=session_id,
|
||||
on_message=self._make_message_sink(session_id, default_agent_name),
|
||||
)
|
||||
from calliope.agent.deliverables import complete_task
|
||||
|
||||
complete_task(session_id, final)
|
||||
# Final answer is persisted + broadcast by the loop's emit() call
|
||||
# (which goes through the message sink). Only set status here.
|
||||
self._set_status(session_id, "idle")
|
||||
@@ -408,6 +423,14 @@ class AgentRunner:
|
||||
content="— run cancelled —",
|
||||
status="cancelled",
|
||||
)
|
||||
conn = self._db()
|
||||
try:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_status='cancelled' WHERE id=?", (session_id,)
|
||||
)
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
self._set_status(session_id, "idle")
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 — surfaced to the chat as the reply
|
||||
|
||||
@@ -311,6 +311,36 @@ CREATE TABLE IF NOT EXISTS project_stages (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_project_stages_project ON project_stages(project_id);
|
||||
|
||||
-- B4: immutable source identity, editable draft, optimistic concurrency.
|
||||
CREATE TABLE IF NOT EXISTS agent_deliverables (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id INTEGER NOT NULL REFERENCES agent_sessions(id) ON DELETE CASCADE,
|
||||
source_message_id INTEGER NOT NULL,
|
||||
project_id INTEGER REFERENCES projects(id) ON DELETE SET NULL,
|
||||
stage_key TEXT NOT NULL CHECK(stage_key IN ('script','style','storyboard','assets','shot')),
|
||||
title TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
revision INTEGER NOT NULL DEFAULT 1,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(session_id, source_message_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS agent_deliverable_versions (
|
||||
deliverable_id INTEGER NOT NULL REFERENCES agent_deliverables(id) ON DELETE CASCADE,
|
||||
revision INTEGER NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY(deliverable_id, revision)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS result_attachments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_key TEXT NOT NULL,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
stage_key TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(source_key, project_id, stage_key)
|
||||
);
|
||||
|
||||
-- Audit trail of agent runs inside the flow (HEL-614): instruction in,
|
||||
-- normalized JSON artifact out, or a Chinese-readable failure reason.
|
||||
CREATE TABLE IF NOT EXISTS stage_runs (
|
||||
@@ -587,6 +617,13 @@ async def migrate_db(db_path: Path) -> None:
|
||||
# born ('chat' = user-created in AI Canvas, 'scene' = auto-created by the
|
||||
# Build Scene rail). The session list excludes origin='scene' so scene
|
||||
# sessions don't pollute the AI Canvas sidebar; Build Scene filters on it.
|
||||
b4_cols = {r[1] for r in conn.execute("PRAGMA table_info(agent_sessions)")}
|
||||
if "task_summary" not in b4_cols:
|
||||
conn.execute("ALTER TABLE agent_sessions ADD COLUMN task_summary TEXT NOT NULL DEFAULT ''")
|
||||
if "task_status" not in b4_cols:
|
||||
conn.execute(
|
||||
"ALTER TABLE agent_sessions ADD COLUMN task_status TEXT NOT NULL DEFAULT 'ready'"
|
||||
)
|
||||
session_cols = {r[1] for r in conn.execute("PRAGMA table_info(agent_sessions)").fetchall()}
|
||||
if "origin" not in session_cols:
|
||||
conn.execute("ALTER TABLE agent_sessions ADD COLUMN origin TEXT NOT NULL DEFAULT 'chat'")
|
||||
|
||||
@@ -20,19 +20,24 @@ from calliope.routers import (
|
||||
agent,
|
||||
assets,
|
||||
canvas,
|
||||
comfyui as comfy,
|
||||
events,
|
||||
jobs,
|
||||
library,
|
||||
playground,
|
||||
projects,
|
||||
results,
|
||||
scenes,
|
||||
settings as settings_router,
|
||||
shots,
|
||||
story,
|
||||
workbench,
|
||||
workflows,
|
||||
)
|
||||
from calliope.routers import (
|
||||
comfyui as comfy,
|
||||
)
|
||||
from calliope.routers import (
|
||||
settings as settings_router,
|
||||
)
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
@@ -141,6 +146,7 @@ def create_app(static_dir: Path | None = None) -> FastAPI:
|
||||
app.include_router(library.router, prefix="/api/library", tags=["library"])
|
||||
app.include_router(canvas.router, prefix="/api/canvas", tags=["canvas"])
|
||||
app.include_router(shots.router, prefix="/api/shots", tags=["shots"])
|
||||
app.include_router(results.router, prefix="/api/results", tags=["results"])
|
||||
app.include_router(agent.router, prefix="/api/agent", tags=["agent"])
|
||||
app.include_router(workbench.router, prefix="/api/workbench", tags=["workbench"])
|
||||
app.include_router(events.router, prefix="/api/events", tags=["events"])
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
"""Editable task deliverables and explicit, idempotent result → stage drafts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from pydantic import BaseModel, Field, model_validator
|
||||
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, row_to_dict
|
||||
from calliope.events.bus import event_bus
|
||||
from calliope.routers.workbench import StageKey
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class DraftPatch(BaseModel):
|
||||
revision: int = Field(ge=1)
|
||||
content: str = Field(min_length=1, max_length=200_000)
|
||||
project_id: int | None = None
|
||||
stage_key: StageKey
|
||||
|
||||
|
||||
class StoreResult(BaseModel):
|
||||
project_id: int = Field(gt=0)
|
||||
stage_key: StageKey
|
||||
deliverable_id: int | None = Field(default=None, gt=0)
|
||||
revision: int | None = Field(default=None, gt=0)
|
||||
job_id: int | None = Field(default=None, gt=0)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def one_source(self):
|
||||
if (self.deliverable_id is None) == (self.job_id is None):
|
||||
raise ValueError("Choose exactly one result source")
|
||||
if self.deliverable_id is not None and self.revision is None:
|
||||
raise ValueError("Deliverable revision is required")
|
||||
return self
|
||||
|
||||
|
||||
def _public(row) -> dict[str, Any]:
|
||||
return row_to_dict(row)
|
||||
|
||||
|
||||
@router.get("/deliverables")
|
||||
def list_deliverables(session_id: int | None = None) -> list[dict[str, Any]]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
sql = "SELECT * FROM agent_deliverables"
|
||||
args = ()
|
||||
if session_id is not None:
|
||||
sql += " WHERE session_id=?"
|
||||
args = (session_id,)
|
||||
return [_public(r) for r in conn.execute(sql + " ORDER BY id DESC", args)]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.get("/deliverables/{draft_id}/versions")
|
||||
def list_versions(draft_id: int) -> list[dict[str, Any]]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
if not conn.execute("SELECT id FROM agent_deliverables WHERE id=?", (draft_id,)).fetchone():
|
||||
raise HTTPException(404, "成果不存在")
|
||||
return [
|
||||
_public(row)
|
||||
for row in conn.execute(
|
||||
"SELECT * FROM agent_deliverable_versions WHERE deliverable_id=? "
|
||||
"ORDER BY revision DESC",
|
||||
(draft_id,),
|
||||
)
|
||||
]
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.patch("/deliverables/{draft_id}")
|
||||
def patch_deliverable(draft_id: int, payload: DraftPatch) -> dict[str, Any]:
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
row = conn.execute("SELECT * FROM agent_deliverables WHERE id=?", (draft_id,)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404, "成果不存在")
|
||||
if payload.project_id is not None:
|
||||
from calliope.routers.workbench import _get_project
|
||||
|
||||
_get_project(conn, payload.project_id)
|
||||
if row["revision"] != payload.revision:
|
||||
raise HTTPException(409, "草稿已更新,请刷新后重试")
|
||||
# A linked session cannot silently move its work into another project.
|
||||
session = conn.execute(
|
||||
"SELECT project_id FROM agent_sessions WHERE id=?", (row["session_id"],)
|
||||
).fetchone()
|
||||
if session["project_id"] is not None and payload.project_id != session["project_id"]:
|
||||
raise HTTPException(409, "成果归属与原会话项目不一致")
|
||||
if not payload.content.strip():
|
||||
raise HTTPException(422, "成果内容不能为空")
|
||||
conn.execute(
|
||||
"INSERT INTO agent_deliverable_versions(deliverable_id,revision,content) "
|
||||
"VALUES (?,?,?)",
|
||||
(draft_id, row["revision"], row["content"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE agent_deliverables SET content=?,project_id=?,stage_key=?,revision=revision+1,"
|
||||
"updated_at=CURRENT_TIMESTAMP WHERE id=?",
|
||||
(payload.content, payload.project_id, payload.stage_key, draft_id),
|
||||
)
|
||||
conn.commit()
|
||||
return _public(
|
||||
conn.execute("SELECT * FROM agent_deliverables WHERE id=?", (draft_id,)).fetchone()
|
||||
)
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
@router.post("/store")
|
||||
async def store_result(payload: StoreResult) -> dict[str, Any]:
|
||||
from calliope.agent.llm import extract_json
|
||||
from calliope.routers.playground import _assert_path_in_assets
|
||||
from calliope.routers.workbench import (
|
||||
NORMALIZERS,
|
||||
StageContentError,
|
||||
_get_project,
|
||||
_stage_or_404,
|
||||
_stage_public,
|
||||
)
|
||||
|
||||
conn = get_db(settings.db_path)
|
||||
try:
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
_get_project(conn, payload.project_id)
|
||||
stage = _stage_or_404(conn, payload.project_id, payload.stage_key)
|
||||
draft = None
|
||||
if payload.deliverable_id is not None:
|
||||
draft = conn.execute(
|
||||
"SELECT * FROM agent_deliverables WHERE id=?", (payload.deliverable_id,)
|
||||
).fetchone()
|
||||
if not draft:
|
||||
raise HTTPException(404, "成果不存在")
|
||||
if draft["revision"] != payload.revision:
|
||||
raise HTTPException(409, "草稿版本已变化,请先保存并刷新")
|
||||
if draft["project_id"] != payload.project_id or draft["stage_key"] != payload.stage_key:
|
||||
raise HTTPException(409, "请先保存成果的项目与阶段归属")
|
||||
session = conn.execute(
|
||||
"SELECT project_id FROM agent_sessions WHERE id=?", (draft["session_id"],)
|
||||
).fetchone()
|
||||
if session["project_id"] is not None and session["project_id"] != payload.project_id:
|
||||
raise HTTPException(409, "会话项目已变化,请重新核对成果归属")
|
||||
source_key = f"deliverable:{draft['id']}:{draft['revision']}"
|
||||
result = {
|
||||
"source_key": source_key,
|
||||
"title": draft["title"],
|
||||
"text": draft["content"],
|
||||
"session_id": draft["session_id"],
|
||||
}
|
||||
else:
|
||||
job = conn.execute("SELECT * FROM jobs WHERE id=?", (payload.job_id,)).fetchone()
|
||||
if not job:
|
||||
raise HTTPException(404, "生成结果不存在")
|
||||
project = conn.execute(
|
||||
"SELECT status FROM projects WHERE id=?", (job["project_id"],)
|
||||
).fetchone()
|
||||
if job["project_id"] != payload.project_id and (
|
||||
not project or project["status"] != "system"
|
||||
):
|
||||
raise HTTPException(409, "此结果属于其他项目")
|
||||
if job["status"] != "done" or job["kind"] not in ("image", "video"):
|
||||
raise HTTPException(409, "仅可存入已完成的图片或视频")
|
||||
paths = json.loads(job["output_paths_json"] or "[]")
|
||||
if (
|
||||
not paths
|
||||
or not isinstance(paths, list)
|
||||
or not all(isinstance(p, str) for p in paths)
|
||||
):
|
||||
raise HTTPException(422, "结果没有产物")
|
||||
for path in paths:
|
||||
if not _assert_path_in_assets(path).is_file():
|
||||
raise HTTPException(410, "产物文件已不存在")
|
||||
source_key = f"job:{job['id']}"
|
||||
result = {
|
||||
"source_key": source_key,
|
||||
"title": f"生成结果 #{job['id']}",
|
||||
"kind": job["kind"],
|
||||
"paths": paths,
|
||||
"job_id": job["id"],
|
||||
}
|
||||
existing = conn.execute(
|
||||
"SELECT id FROM result_attachments WHERE source_key=? AND project_id=? AND stage_key=?",
|
||||
(source_key, payload.project_id, payload.stage_key),
|
||||
).fetchone()
|
||||
if existing:
|
||||
return {"ok": True, "already_attached": True, "stage": _stage_public(stage)}
|
||||
if stage["status"] == "running":
|
||||
raise HTTPException(409, "本阶段正在生成,请稍后再存入")
|
||||
content = json.loads(stage["content_json"] or "{}")
|
||||
if draft:
|
||||
text = draft["content"].strip()
|
||||
# Valid structured artifacts replace only the working draft.
|
||||
# Confirmed snapshots stay intact.
|
||||
parsed = None
|
||||
try:
|
||||
parsed = extract_json(text)
|
||||
except ValueError:
|
||||
if payload.stage_key == "script":
|
||||
parsed = {"text": text}
|
||||
if isinstance(parsed, dict):
|
||||
try:
|
||||
normalized = NORMALIZERS[payload.stage_key](parsed)
|
||||
normalized["incoming_results"] = content.get("incoming_results", [])
|
||||
content = normalized
|
||||
except StageContentError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
incoming = list(content.get("incoming_results") or [])
|
||||
incoming.append(result)
|
||||
content["incoming_results"] = incoming
|
||||
conn.execute(
|
||||
"UPDATE project_stages SET content_json=?,status='awaiting_confirm',draft_edited=1,"
|
||||
"error=NULL,updated_at=CURRENT_TIMESTAMP WHERE project_id=? AND stage_key=?",
|
||||
(json.dumps(content, ensure_ascii=False), payload.project_id, payload.stage_key),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO result_attachments(source_key,project_id,stage_key) VALUES (?,?,?)",
|
||||
(source_key, payload.project_id, payload.stage_key),
|
||||
)
|
||||
if draft:
|
||||
conn.execute(
|
||||
"UPDATE agent_sessions SET task_status='returned' WHERE id=?",
|
||||
(draft["session_id"],),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE projects SET updated_at=CURRENT_TIMESTAMP WHERE id=?", (payload.project_id,)
|
||||
)
|
||||
conn.commit()
|
||||
row = _stage_or_404(conn, payload.project_id, payload.stage_key)
|
||||
out = {"ok": True, "already_attached": False, "stage": _stage_public(row)}
|
||||
finally:
|
||||
conn.close()
|
||||
await event_bus.publish(
|
||||
"workbench.stage.updated",
|
||||
{"project_id": payload.project_id, "stage_key": payload.stage_key},
|
||||
)
|
||||
return out
|
||||
@@ -302,6 +302,7 @@ def _stage_public(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"status": row["status"],
|
||||
"content": content,
|
||||
"assistant_note": (content or {}).get("assistant_note", ""),
|
||||
"incoming_results": (content or {}).get("incoming_results", []),
|
||||
"confirmed_content": (
|
||||
json.loads(row["confirmed_content_json"]) if row["confirmed_content_json"] else None
|
||||
),
|
||||
@@ -692,6 +693,8 @@ async def patch_stage(project_id: int, stage_key: str, payload: StagePatch) -> d
|
||||
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("incoming_results"):
|
||||
content["incoming_results"] = old_content["incoming_results"]
|
||||
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):
|
||||
@@ -820,6 +823,9 @@ async def confirm_stage(
|
||||
content = NORMALIZERS[stage_key](json.loads(stage["content_json"]))
|
||||
except StageContentError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||
raw_content = json.loads(stage["content_json"])
|
||||
if raw_content.get("incoming_results"):
|
||||
content["incoming_results"] = raw_content["incoming_results"]
|
||||
chosen = payload.chosen_style_id if payload else None
|
||||
if stage_key == "style":
|
||||
directions = content.get("directions") or []
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""B4 draft persistence, concurrency, scope, confirmation and migration regression."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sqlite3
|
||||
|
||||
from calliope.agent.deliverables import complete_task
|
||||
from calliope.agent.harness.runner import runner
|
||||
from calliope.config import settings
|
||||
from calliope.db import get_db, migrate_db
|
||||
|
||||
TEXT = (
|
||||
"第一场,清晨海岸,女孩将纸船推向海面,等待父亲归来。"
|
||||
"第二场,纸船带回树叶,女孩沿着灯塔的光继续前行。"
|
||||
)
|
||||
|
||||
|
||||
def setup(client, stage="script"):
|
||||
project = client.post("/api/projects", json={"title": "B4 isolated"}).json()
|
||||
session = client.post(
|
||||
"/api/agent/sessions",
|
||||
json={
|
||||
"project_id": project["id"],
|
||||
"agent_key": stage,
|
||||
},
|
||||
).json()
|
||||
runner._persist_message(session["id"], role="assistant", content=TEXT)
|
||||
complete_task(session["id"], TEXT)
|
||||
draft = client.get("/api/results/deliverables", params={"session_id": session["id"]}).json()[0]
|
||||
return project["id"], session["id"], draft
|
||||
|
||||
|
||||
def store(client, pid, draft, stage="script"):
|
||||
return client.post(
|
||||
"/api/results/store",
|
||||
json={
|
||||
"project_id": pid,
|
||||
"stage_key": stage,
|
||||
"deliverable_id": draft["id"],
|
||||
"revision": draft["revision"],
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_draft_save_refresh_conflict_and_scope(client):
|
||||
pid, sid, draft = setup(client)
|
||||
body = {"revision": 1, "content": TEXT + "新结尾。", "project_id": pid, "stage_key": "script"}
|
||||
saved = client.patch(f"/api/results/deliverables/{draft['id']}", json=body)
|
||||
assert saved.status_code == 200
|
||||
assert saved.json()["revision"] == 2
|
||||
versions = client.get(f"/api/results/deliverables/{draft['id']}/versions").json()
|
||||
assert len(versions) == 1 and versions[0]["content"] == TEXT
|
||||
assert (
|
||||
client.get("/api/results/deliverables", params={"session_id": sid}).json()[0]
|
||||
== saved.json()
|
||||
)
|
||||
assert client.patch(f"/api/results/deliverables/{draft['id']}", json=body).status_code == 409
|
||||
assert store(client, pid, draft).status_code == 409
|
||||
other = client.post("/api/projects", json={"title": "Other"}).json()["id"]
|
||||
assert store(client, other, saved.json()).status_code == 409
|
||||
body.update(revision=2, project_id=other)
|
||||
assert client.patch(f"/api/results/deliverables/{draft['id']}", json=body).status_code == 409
|
||||
assert client.get(f"/api/agent/sessions/{sid}").json()["task_status"] == "awaiting_confirm"
|
||||
|
||||
|
||||
def test_store_idempotency_confirm_restore_and_preserve_snapshot(client):
|
||||
pid, sid, draft = setup(client)
|
||||
url = f"/api/workbench/projects/{pid}/stages/script"
|
||||
old = {"text": TEXT + "已确认的旧版。"}
|
||||
assert client.patch(url, json={"content": old}).status_code == 200
|
||||
snapshot = client.post(url + "/confirm", json={}).json()["stage"]["confirmed_content"]
|
||||
res = store(client, pid, draft)
|
||||
assert res.status_code == 200, res.text
|
||||
stage = res.json()["stage"]
|
||||
assert stage["status"] == "awaiting_confirm"
|
||||
assert stage["confirmed_content"] == snapshot
|
||||
assert stage["content"]["text"] == TEXT
|
||||
assert len(stage["incoming_results"]) == 1
|
||||
assert store(client, pid, draft).json()["already_attached"] is True
|
||||
assert len(store(client, pid, draft).json()["stage"]["incoming_results"]) == 1
|
||||
assert client.get(f"/api/agent/sessions/{sid}").json()["task_status"] == "returned"
|
||||
assert client.post(url + "/restore", json={}).json()["stage"]["content"] == snapshot
|
||||
# A newer source revision is a new explicit handoff, never an automatic update.
|
||||
draft = client.patch(
|
||||
f"/api/results/deliverables/{draft['id']}",
|
||||
json={
|
||||
"revision": 1,
|
||||
"content": TEXT + "新版本。",
|
||||
"project_id": pid,
|
||||
"stage_key": "script",
|
||||
},
|
||||
).json()
|
||||
assert store(client, pid, draft).status_code == 200
|
||||
confirmed = client.post(url + "/confirm", json={}).json()["stage"]["confirmed_content"]
|
||||
assert confirmed["text"].endswith("新版本。")
|
||||
assert len(confirmed["incoming_results"]) == 1
|
||||
stages = client.get(f"/api/workbench/projects/{pid}").json()["stages"]
|
||||
assert all(s["status"] == "todo" for s in stages if s["stage_key"] != "script")
|
||||
|
||||
|
||||
def test_capture_idempotency_and_no_error_artifact(client):
|
||||
_, sid, _ = setup(client)
|
||||
complete_task(sid, TEXT)
|
||||
assert len(client.get("/api/results/deliverables", params={"session_id": sid}).json()) == 1
|
||||
runner._persist_message(sid, role="assistant", content="error", status="error")
|
||||
complete_task(sid, "error")
|
||||
assert len(client.get("/api/results/deliverables", params={"session_id": sid}).json()) == 1
|
||||
|
||||
|
||||
def test_sandbox_assignment_and_running_stage(client):
|
||||
pid, _, draft = setup(client)
|
||||
conn = get_db(settings.db_path)
|
||||
conn.execute("UPDATE project_stages SET status='running' WHERE project_id=?", (pid,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
# Stage rows are created lazily; ensure they exist first.
|
||||
client.get(f"/api/workbench/projects/{pid}")
|
||||
conn = get_db(settings.db_path)
|
||||
conn.execute("UPDATE project_stages SET status='running' WHERE project_id=?", (pid,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
assert store(client, pid, draft).status_code == 409
|
||||
assert client.get("/api/results/deliverables", params={"session_id": 99999}).json() == []
|
||||
|
||||
|
||||
def test_media_paths_scope_and_empty_errors(client):
|
||||
pid, _, _ = setup(client)
|
||||
other = client.post("/api/projects", json={"title": "other"}).json()["id"]
|
||||
path = settings.assets_dir / "b4.txt"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("isolated")
|
||||
conn = get_db(settings.db_path)
|
||||
job = conn.execute(
|
||||
"INSERT INTO jobs(project_id,kind,status,output_paths_json) VALUES (?,'image','done',?)",
|
||||
(pid, json.dumps([str(path)])),
|
||||
).lastrowid
|
||||
conn.commit()
|
||||
conn.close()
|
||||
body = {"job_id": job, "project_id": other, "stage_key": "assets"}
|
||||
assert client.post("/api/results/store", json=body).status_code == 409
|
||||
body["project_id"] = pid
|
||||
result = client.post("/api/results/store", json=body)
|
||||
assert result.status_code == 200, result.text
|
||||
assert result.json()["stage"]["incoming_results"][0]["paths"] == [str(path)]
|
||||
assert client.post("/api/results/store", json=body).json()["already_attached"]
|
||||
assert (
|
||||
client.post(
|
||||
"/api/results/store", json={"project_id": pid, "stage_key": "bogus", "job_id": job}
|
||||
).status_code
|
||||
== 422
|
||||
)
|
||||
assert (
|
||||
client.post(
|
||||
"/api/results/store", json={"project_id": pid, "stage_key": "assets"}
|
||||
).status_code
|
||||
== 422
|
||||
)
|
||||
path.unlink()
|
||||
assert client.post("/api/results/store", json=body).status_code == 404
|
||||
|
||||
|
||||
def test_migration_twice_and_sqlite_backup_rollback(client, tmp_path):
|
||||
pid, sid, draft = setup(client)
|
||||
conn = sqlite3.connect(settings.db_path)
|
||||
backup = sqlite3.connect(tmp_path / "before-b4.db")
|
||||
conn.backup(backup)
|
||||
backup.close()
|
||||
conn.close()
|
||||
asyncio.run(migrate_db(settings.db_path))
|
||||
asyncio.run(migrate_db(settings.db_path))
|
||||
assert client.get("/api/results/deliverables").json()[0]["content"] == draft["content"]
|
||||
conn = get_db(settings.db_path)
|
||||
# Old-code SQL continues reading the original schema and rows.
|
||||
assert (
|
||||
conn.execute(
|
||||
"SELECT title,status,project_id FROM agent_sessions WHERE id=?", (sid,)
|
||||
).fetchone()["project_id"]
|
||||
== pid
|
||||
)
|
||||
assert conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"
|
||||
conn.close()
|
||||
@@ -98,9 +98,9 @@ check(
|
||||
JSON.stringify(stripSkillFrontmatter(plain)),
|
||||
);
|
||||
|
||||
// 5. Static: the page uses the shared helper; no `\A` regex remains.
|
||||
// 5. Static: the extracted skill editor uses the shared helper; no `\A` regex remains.
|
||||
const page = readFileSync(
|
||||
join(ROOT, "src/routes/agents/+page.svelte"),
|
||||
join(ROOT, "src/lib/components/agent/LegacyAgentWorkspace.svelte"),
|
||||
"utf-8",
|
||||
);
|
||||
check(
|
||||
|
||||
@@ -834,6 +834,7 @@ export interface VideoShot {
|
||||
}
|
||||
|
||||
export interface WorkbenchStage {
|
||||
incoming_results?: IncomingResult[];
|
||||
assistant_note?: string;
|
||||
stage_key: WorkbenchStageKey;
|
||||
status: WorkbenchStageStatus;
|
||||
@@ -954,7 +955,65 @@ export const libraryApi = {
|
||||
|
||||
// ── Agents (agentic harness) ────────────────────────────────────────────
|
||||
|
||||
export interface AgentDeliverable {
|
||||
id: number;
|
||||
session_id: number;
|
||||
source_message_id: number;
|
||||
project_id: number | null;
|
||||
stage_key: WorkbenchStageKey;
|
||||
title: string;
|
||||
content: string;
|
||||
revision: number;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
export interface IncomingResult {
|
||||
source_key: string;
|
||||
title: string;
|
||||
text?: string;
|
||||
kind?: string;
|
||||
paths?: string[];
|
||||
session_id?: number;
|
||||
job_id?: number;
|
||||
}
|
||||
export const resultsApi = {
|
||||
versions: (id: number) =>
|
||||
api<{ revision: number; content: string }[]>(
|
||||
`/api/results/deliverables/${id}/versions`,
|
||||
),
|
||||
list: (sessionId?: number) =>
|
||||
api<AgentDeliverable[]>(
|
||||
`/api/results/deliverables${sessionId == null ? "" : `?session_id=${sessionId}`}`,
|
||||
),
|
||||
patch: (
|
||||
id: number,
|
||||
payload: {
|
||||
revision: number;
|
||||
content: string;
|
||||
project_id: number | null;
|
||||
stage_key: WorkbenchStageKey;
|
||||
},
|
||||
) =>
|
||||
api<AgentDeliverable>(`/api/results/deliverables/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(payload),
|
||||
}),
|
||||
store: (payload: {
|
||||
project_id: number;
|
||||
stage_key: WorkbenchStageKey;
|
||||
deliverable_id?: number;
|
||||
revision?: number;
|
||||
job_id?: number;
|
||||
}) =>
|
||||
api<{ ok: boolean; already_attached: boolean; stage: WorkbenchStage }>(
|
||||
"/api/results/store",
|
||||
{ method: "POST", body: JSON.stringify(payload) },
|
||||
),
|
||||
};
|
||||
|
||||
export interface AgentSession {
|
||||
task_summary?: string;
|
||||
task_status?: string;
|
||||
id: number;
|
||||
project_id: number | null;
|
||||
title: string;
|
||||
|
||||
@@ -61,7 +61,7 @@
|
||||
.toast-host {
|
||||
position: fixed;
|
||||
right: 24px;
|
||||
bottom: 24px;
|
||||
bottom: var(--toast-bottom, 24px);
|
||||
/* Above every overlay, incl. the 10000 lightbox, so feedback stays visible. */
|
||||
z-index: 10001;
|
||||
display: flex;
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import { t } from '$lib/i18n.svelte';
|
||||
|
||||
interface Props {
|
||||
studio?: boolean;
|
||||
messages: AgentMessage[];
|
||||
/** In-flight tool calls for the current turn (from agent.tool SSE). */
|
||||
liveTools: { tool: string; args?: Record<string, unknown> | null; result?: unknown; phase: 'running' | 'done' | 'error' }[];
|
||||
@@ -31,6 +32,7 @@
|
||||
}
|
||||
|
||||
let {
|
||||
studio = false,
|
||||
messages,
|
||||
liveTools,
|
||||
streaming,
|
||||
@@ -46,6 +48,21 @@
|
||||
let listEl = $state<HTMLDivElement | null>(null);
|
||||
let pinned = $state(true);
|
||||
|
||||
// A user message starts a turn; keep different named assistants distinct.
|
||||
const studioGroups = $derived.by(() => {
|
||||
const groups: AgentMessage[][] = [];
|
||||
for (const message of messages) {
|
||||
if (!['user', 'assistant', 'tool'].includes(message.role)) continue;
|
||||
const previous = groups.at(-1);
|
||||
const author = previous?.find(m => m.role === 'assistant')?.agent_name;
|
||||
if (!previous || message.role === 'user' || previous[0].role === 'user' ||
|
||||
(message.role === 'assistant' && author !== undefined && message.agent_name !== author)) {
|
||||
groups.push([message]);
|
||||
} else previous.push(message);
|
||||
}
|
||||
return groups;
|
||||
});
|
||||
|
||||
// Derived tool rows carry no status — infer failure from the result shape,
|
||||
// same as the live SSE path does.
|
||||
function toolPhase(m: AgentMessage): 'done' | 'error' {
|
||||
@@ -189,6 +206,35 @@
|
||||
</script>
|
||||
|
||||
<div class="chat" bind:this={listEl} onscroll={onScroll}>
|
||||
{#if studio}
|
||||
{#if loading}<p class="studio-empty">{t('agentChat.loading')}</p>{/if}
|
||||
{#each studioGroups as group (group[0].id)}
|
||||
<div class="studio-msg" class:me={group[0].role==='user'}>
|
||||
<div class="studio-avatar" title={group[0].role==='user'?'我':agentDisplayName(group[0].agent_name)}>{#if group[0].role==='user'}我{:else}<Icon name="project-agent" size={14}/>{/if}</div>
|
||||
<div class="studio-message-body">
|
||||
{#each group as m (m.id)}
|
||||
{#if m.role==='tool'}
|
||||
<AgentToolCard studio name={m.tool_name??'tool'} args={m.tool_args} result={m.tool_result} phase={toolPhase(m)}/>
|
||||
{#each artifactJobs(m) as job(job.id)}<AgentArtifactCard {job}/>{/each}
|
||||
{:else}
|
||||
{#if m.reasoning}<ReasoningPanel reasoning={m.reasoning}/>{/if}
|
||||
<div class="studio-bubble" data-message-id={m.id} class:failed={m.status==='error'||m.status==='cancelled'}>{#if m.status==='steering'}<small>{t('agentChat.steering')}</small>{/if}{#each m.attachments??[] as a (a.path)}<a href={assetUrl(a.path)??'#'} target="_blank" rel="noopener external">{a.name}</a>{/each}{#each bubbleParts(m.content,(m.mentions??[]) as WorkflowMention[]) as part,i (`${i}-${part.type}`)}{#if part.type==='chip'}<span class="wf-chip">{part.text}</span>{:else}{part.text}{/if}{/each}</div>
|
||||
{/if}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{#if lastQuestion && !running}<div class="question-card"><p>{lastQuestion.question}</p><div class="question-options">{#each lastQuestion.options as opt(opt)}<button type="button" class="question-option" onclick={()=>onAnswer?.(opt,lastQuestion.scope,lastQuestion.questionSeq)}>{opt}</button>{/each}</div></div>{/if}
|
||||
{#if running && (liveTools.length || streamingReasoning || streaming)}
|
||||
<div class="studio-msg"><div class="studio-avatar"><Icon name="project-agent" size={14}/></div><div class="studio-message-body">
|
||||
{#each liveTools as tool,i(i)}<AgentToolCard studio name={tool.tool} args={tool.args} result={tool.result} phase={tool.phase}/>{/each}
|
||||
{#if streamingReasoning}<ReasoningPanel reasoning={streamingReasoning}/>{/if}
|
||||
{#if streaming}<div class="studio-bubble">{streaming}</div>{/if}
|
||||
</div></div>
|
||||
{/if}
|
||||
{#if !loading&&!messages.length&&!running}<p class="studio-empty">{t('agentChat.emptyHint')}</p>{/if}
|
||||
{:else}
|
||||
|
||||
{#if loading}
|
||||
<div class="empty">
|
||||
<p class="empty-hint">{t('agentChat.loading')}</p>
|
||||
@@ -329,9 +375,20 @@
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.studio-msg {display:flex;gap:10px;max-width:760px;}
|
||||
.studio-msg.me {align-self:flex-end;flex-direction:row-reverse;}
|
||||
.studio-avatar {width:28px;height:28px;border-radius:var(--agent-radius-8);flex:none;display:grid;place-items:center;background:color-mix(in srgb,var(--sc-agent) 18%,transparent);color:var(--sc-agent);}
|
||||
.studio-msg.me .studio-avatar {background:var(--bg-3);color:var(--tx-2);}
|
||||
.studio-message-body {flex:var(--agent-message-flex);display:flex;flex-direction:column;gap:10px;min-width:0;}
|
||||
.studio-bubble {padding:10px 13px;border-radius:var(--agent-bubble-radius);background:var(--bg-2);border:1px solid var(--line);font-size:13px;line-height:1.65;white-space:pre-wrap;word-break:break-word;}
|
||||
.studio-msg.me .studio-bubble {background:color-mix(in srgb,var(--gold) 10%,transparent);border-color:color-mix(in srgb,var(--gold) 25%,transparent);}
|
||||
.studio-bubble.failed {color:var(--err);border-color:var(--err);}
|
||||
.studio-empty {color:var(--tx-3);font-size:12px;}
|
||||
|
||||
.chat {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -342,7 +399,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
padding: 4px 4px 12px;
|
||||
padding: var(--chat-padding, 4px 4px 12px);
|
||||
}
|
||||
.empty {
|
||||
margin: auto;
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
import { t } from '$lib/i18n.svelte';
|
||||
|
||||
interface Props {
|
||||
studio?: boolean;
|
||||
running: boolean;
|
||||
onSend: (payload: AgentComposerPayload) => void;
|
||||
onCancel: () => void;
|
||||
@@ -34,6 +35,7 @@ interface Props {
|
||||
}
|
||||
|
||||
let {
|
||||
studio = false,
|
||||
running,
|
||||
onSend,
|
||||
onCancel,
|
||||
@@ -549,6 +551,7 @@ let {
|
||||
onpaste={onPaste}
|
||||
></div>
|
||||
<div class="actions">
|
||||
{#if studio}<button type="button" class="b4-chip workflow-shortcut" disabled={busy} onclick={()=>{editorEl?.focus();mentionQuery='';mentionIndex=0;mentionAnchor=caretAnchor();mentionLocked=false;mentionOpen=true;}}>@ 工作流</button>{/if}
|
||||
<input
|
||||
bind:this={fileInput}
|
||||
type="file"
|
||||
@@ -559,29 +562,31 @@ let {
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
class="attach"
|
||||
class={studio ? "b4-chip" : "attach"}
|
||||
title={t('agentComposer.attach')}
|
||||
disabled={busy}
|
||||
onclick={() => fileInput?.click()}
|
||||
>
|
||||
<Icon name="paperclip" size={16} />
|
||||
{#if studio}+ 参考材料{:else}<Icon name="paperclip" size={16} />{/if}
|
||||
</button>
|
||||
{#if studio}<span class="b4-grow"></span>{/if}
|
||||
{#if running}
|
||||
<button type="button" class="send stop" onclick={onCancel} title={t('agentComposer.stopTitle')}>
|
||||
<Icon name="stop" size={14} />
|
||||
<button type="button" class={studio ? "a-btn sm ghost stop" : "send stop"} onclick={onCancel} title={t('agentComposer.stopTitle')}>
|
||||
{#if !studio}<Icon name="stop" size={14} />{/if}
|
||||
{t('common.stop')}
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="send"
|
||||
class={studio ? "a-btn sm primary" : "send"}
|
||||
class:steer={running}
|
||||
onclick={submit}
|
||||
disabled={!sendable}
|
||||
title={running ? t('agentComposer.steerTitle') : t('agentComposer.sendTitle')}
|
||||
>
|
||||
{#if studio}<Icon name="agent-send" size={14} />{/if}
|
||||
{running ? t('agentComposer.steer') : t('common.send')}
|
||||
<Icon name="chevron-right" size={14} />
|
||||
{#if !studio}<Icon name="chevron-right" size={14} />{/if}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -617,8 +622,8 @@ let {
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--border);
|
||||
padding-top: var(--composer-top-padding, 10px);
|
||||
border-top: var(--composer-top-border, 1px) solid var(--border);
|
||||
}
|
||||
.composer.drag-over .box {
|
||||
border-color: var(--accent);
|
||||
@@ -686,18 +691,19 @@ let {
|
||||
}
|
||||
.box {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
align-items: var(--composer-box-align, flex-end);
|
||||
flex-direction: var(--composer-box-direction, row);
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
background: var(--bg-surface);
|
||||
border: 1px solid var(--border);
|
||||
background: var(--composer-box-bg, var(--bg-surface));
|
||||
border: var(--composer-box-border, 1px) solid var(--border);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 8px 8px 8px 12px;
|
||||
padding: var(--composer-box-padding, 8px 8px 8px 12px);
|
||||
}
|
||||
.editor {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
min-height: 28px;
|
||||
min-height: var(--composer-editor-height, 28px);
|
||||
max-height: 160px;
|
||||
overflow-y: auto;
|
||||
color: var(--text-primary);
|
||||
@@ -741,22 +747,26 @@ let {
|
||||
}
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content:var(--composer-actions-justify,normal);
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: var(--composer-actions-gap, 6px);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.attach {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
width: var(--composer-attach-width,36px);
|
||||
height: var(--composer-attach-height,36px);
|
||||
padding:var(--composer-attach-padding,0px);
|
||||
margin-right:var(--composer-attach-margin,0px);
|
||||
border: none;
|
||||
border-radius: var(--radius-md);
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
}
|
||||
.workflow-shortcut {font-size:12px;white-space:nowrap;flex:none;}
|
||||
.attach:hover:not(:disabled) {
|
||||
color: var(--text-primary);
|
||||
background: var(--bg-elevated);
|
||||
@@ -773,11 +783,11 @@ let {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 36px;
|
||||
height: var(--composer-send-height, 36px);
|
||||
padding: 0 14px;
|
||||
border-radius: var(--radius-md);
|
||||
border: 1px solid var(--accent);
|
||||
background: var(--accent);
|
||||
background: var(--composer-send-bg, var(--accent));
|
||||
color: var(--accent-ink);
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
import { t } from '$lib/i18n.svelte';
|
||||
|
||||
interface Props {
|
||||
studio?: boolean;
|
||||
name: string;
|
||||
args?: Record<string, unknown> | null;
|
||||
result?: unknown;
|
||||
phase: 'running' | 'done' | 'error';
|
||||
}
|
||||
|
||||
let { name, args = null, result = null, phase }: Props = $props();
|
||||
let { studio = false, name, args = null, result = null, phase }: Props = $props();
|
||||
let open = $state(false);
|
||||
|
||||
function fmt(value: unknown): string {
|
||||
@@ -21,18 +22,19 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="tool-card" class:error={phase === 'error'}>
|
||||
<div class="tool-card" class:done={studio && phase === 'done'} class:error={phase === 'error'}>
|
||||
<button type="button" class="head" onclick={() => (open = !open)} aria-expanded={open}>
|
||||
<span class="dot" class:running={phase === 'running'}></span>
|
||||
{#if studio}<Icon name="nav-flow" size={14} /><span>调用</span>{:else}<span class="dot" class:running={phase === 'running'}></span>{/if}
|
||||
<span class="name mono">{name}</span>
|
||||
{#if studio && args && Object.keys(args).length}<span class="summary">· {Object.entries(args).map(([key, value]) => `${key}=${JSON.stringify(value)}`).join(' · ')}</span>{/if}
|
||||
{#if phase === 'running'}
|
||||
<span class="state">{t('agentTool.running')}</span>
|
||||
<span class={studio ? "state a-tag" : "state"}>{t('agentTool.running')}</span>
|
||||
{:else if phase === 'error'}
|
||||
<span class="state err-text">{t('agentTool.failed')}</span>
|
||||
<span class={studio ? "state a-tag err-text" : "state err-text"}>{t('agentTool.failed')}</span>
|
||||
{:else}
|
||||
<span class="state ok-text">{t('agentTool.done')}</span>
|
||||
<span class={studio ? "state a-tag ok-text" : "state ok-text"}>{t('agentTool.done')}</span>
|
||||
{/if}
|
||||
<span class="chev"><Icon name="chevron-down" size={13} /></span>
|
||||
{#if !studio}<span class="chev"><Icon name="chevron-down" size={13} /></span>{/if}
|
||||
</button>
|
||||
{#if open}
|
||||
<div class="body">
|
||||
@@ -54,9 +56,10 @@
|
||||
|
||||
<style>
|
||||
.tool-card {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--bg-elevated);
|
||||
font-size: var(--tool-font, inherit);
|
||||
border: 1px solid var(--tool-border, var(--border));
|
||||
border-radius: var(--tool-card-radius, var(--radius-sm));
|
||||
background: var(--tool-card-bg, var(--bg-elevated));
|
||||
overflow: hidden;
|
||||
}
|
||||
.tool-card.error {
|
||||
@@ -67,12 +70,12 @@
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
padding: var(--tool-head-padding, 7px 10px);
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
color: var(--tool-head-color, var(--text-secondary));
|
||||
font-size: var(--tool-head-font, 12px);
|
||||
text-align: left;
|
||||
}
|
||||
.head:hover {
|
||||
@@ -80,14 +83,20 @@
|
||||
background: var(--bg-3);
|
||||
}
|
||||
.name {
|
||||
flex: 1;
|
||||
flex: var(--tool-name-flex, 1);
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
color: var(--text-primary);
|
||||
font-size: var(--tool-name-font, 12px);
|
||||
color: var(--tool-name-color, var(--text-primary));
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.summary {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.dot {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
@@ -115,10 +124,10 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ok-text {
|
||||
color: var(--success);
|
||||
color: var(--tool-ok-color, var(--success));
|
||||
}
|
||||
.err-text {
|
||||
color: var(--error);
|
||||
color: var(--tool-error-color, var(--error));
|
||||
}
|
||||
.chev {
|
||||
display: inline-flex;
|
||||
|
||||
@@ -0,0 +1,982 @@
|
||||
<script lang="ts">
|
||||
import "./workspace.css";
|
||||
import { onMount, untrack } from "svelte";
|
||||
import { page } from "$app/state";
|
||||
import { goto } from "$app/navigation";
|
||||
import { resolve } from "$app/paths";
|
||||
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
|
||||
import { toStore } from "svelte/store";
|
||||
import AppShell from "$lib/components/shell/AppShell.svelte";
|
||||
import type { IconName } from "$lib/components/ui/icons";
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
import AgentChat from "./AgentChat.svelte";
|
||||
import AgentPlanPanel from "./AgentPlanPanel.svelte";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import AgentComposer from "./AgentComposer.svelte";
|
||||
import {
|
||||
agentApi,
|
||||
resultsApi,
|
||||
jobsApi,
|
||||
assetUrl,
|
||||
settings,
|
||||
workflows,
|
||||
workbenchApi,
|
||||
type AgentDeliverable,
|
||||
type AgentSession,
|
||||
type WorkbenchStageKey,
|
||||
} from "$lib/api";
|
||||
import { createUploadManager } from "$lib/comfy/useUpload.svelte";
|
||||
import type { AgentAttachment } from "$lib/agentComposer";
|
||||
import type { AgentComposerPayload } from "$lib/agentComposer";
|
||||
import { connectEvents } from "$lib/events";
|
||||
import { toast } from "$lib/toast";
|
||||
|
||||
const client = useQueryClient();
|
||||
const stageNames: Record<WorkbenchStageKey, string> = {
|
||||
script: "剧本创作",
|
||||
style: "视觉设计",
|
||||
storyboard: "分镜设计",
|
||||
assets: "素材资产",
|
||||
shot: "镜头脚本",
|
||||
};
|
||||
const assistantIcons: Record<string, IconName> = {
|
||||
script: "project-book",
|
||||
style: "nav-palette",
|
||||
storyboard: "project-grid",
|
||||
assets: "project-image",
|
||||
shot: "project-film",
|
||||
};
|
||||
const assistantColors: Record<string, string> = {
|
||||
script: "var(--sc-agent)",
|
||||
style: "var(--gold)",
|
||||
storyboard: "var(--sc-image)",
|
||||
assets: "var(--sc-asset)",
|
||||
shot: "var(--sc-video)",
|
||||
};
|
||||
const assistantDescriptions: Record<string, string> = {
|
||||
script: "故事、人物、场次与台词",
|
||||
style: "风格板、色彩与参考图",
|
||||
storyboard: "镜头拆分、景别与时长",
|
||||
assets: "角色、场景、道具出图",
|
||||
shot: "逐镜视频提示词与生成",
|
||||
};
|
||||
const keys = Object.keys(stageNames) as WorkbenchStageKey[];
|
||||
const registry = createQuery({
|
||||
queryKey: ["agents-registry"],
|
||||
queryFn: agentApi.listNamedAgents,
|
||||
});
|
||||
const config = createQuery({ queryKey: ["settings"], queryFn: settings.get });
|
||||
const skills = createQuery({
|
||||
queryKey: ["b4-skills"],
|
||||
queryFn: () => agentApi.listSkillsAdmin(),
|
||||
});
|
||||
const wfQuery = createQuery({
|
||||
queryKey: ["b4-workflows"],
|
||||
queryFn: workflows.list,
|
||||
});
|
||||
const projects = createQuery({
|
||||
queryKey: ["b4-projects"],
|
||||
queryFn: agentApi.listLinkableProjects,
|
||||
});
|
||||
const sessions = createQuery({
|
||||
queryKey: ["b4-sessions"],
|
||||
queryFn: async () =>
|
||||
(
|
||||
await Promise.all([
|
||||
agentApi.listSessions(),
|
||||
...keys.map(agentApi.listAgentSessions),
|
||||
])
|
||||
)
|
||||
.flat()
|
||||
.sort((a, b) => b.updated_at.localeCompare(a.updated_at)),
|
||||
});
|
||||
const allResults = createQuery({
|
||||
queryKey: ["b4-results"],
|
||||
queryFn: () => resultsApi.list(),
|
||||
});
|
||||
const activeId = $derived(
|
||||
Number(page.url.searchParams.get("session")) || null,
|
||||
);
|
||||
const session = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ["agent-session", activeId],
|
||||
queryFn: () => agentApi.getSession(activeId!),
|
||||
enabled: activeId != null,
|
||||
})),
|
||||
);
|
||||
const taskResults = $derived(
|
||||
($allResults.data ?? []).filter((r) => r.session_id === activeId),
|
||||
);
|
||||
let filter = $state("all");
|
||||
let agentKey = $state<WorkbenchStageKey | "">("");
|
||||
let projectId = $state<number | null>(null);
|
||||
let draft = $state("");
|
||||
let busy = $state(false);
|
||||
let error = $state("");
|
||||
let streaming = $state("");
|
||||
let reasoning = $state("");
|
||||
let particles = $state<HTMLCanvasElement | null>(null);
|
||||
let liveTools = $state<
|
||||
{
|
||||
tool: string;
|
||||
args?: Record<string, unknown>;
|
||||
result?: unknown;
|
||||
phase: "running" | "done" | "error";
|
||||
}[]
|
||||
>([]);
|
||||
const running = $derived($session.data?.running === true);
|
||||
let editing = $state<AgentDeliverable | null>(null);
|
||||
let text = $state("");
|
||||
let targetProject = $state<number | null>(null);
|
||||
let targetStage = $state<WorkbenchStageKey>("script");
|
||||
let saving = $state(false);
|
||||
let dirty = $state(false);
|
||||
let artifactTab = $state("shots");
|
||||
let compareOpen = $state(false);
|
||||
let previousText = $state("");
|
||||
async function comparePrevious() {
|
||||
if (!editing) return;
|
||||
try {
|
||||
const versions = await resultsApi.versions(editing.id);
|
||||
previousText = versions[0]?.content ?? "";
|
||||
compareOpen = true;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
}
|
||||
function parseContent(value: string): Record<string, unknown> | null {
|
||||
try {
|
||||
const start = value.indexOf("{");
|
||||
const end = value.lastIndexOf("}");
|
||||
return JSON.parse(value.slice(start, end + 1));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
function editShot(index: number, key: string, value: string | number) {
|
||||
const data = parseContent(text);
|
||||
if (!data || !Array.isArray(data.shots)) return;
|
||||
data.shots[index] = { ...data.shots[index], [key]: value };
|
||||
text = JSON.stringify(data, null, 2);
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
let selectedSkill = $state("");
|
||||
let uploadInput = $state<HTMLInputElement | null>(null);
|
||||
let attachments = $state<AgentAttachment[]>([]);
|
||||
const uploads = createUploadManager();
|
||||
let uploadBusy = $state(false);
|
||||
async function upload(event: Event) {
|
||||
const files = Array.from((event.target as HTMLInputElement).files ?? []);
|
||||
uploadBusy = true;
|
||||
try {
|
||||
for (const file of files.slice(0, 8 - attachments.length)) {
|
||||
const path = await uploads.upload("b4-reference", file);
|
||||
const meta = uploads.uploadMetaFor(path);
|
||||
attachments.push({ path, name: meta.name, kind: meta.kind });
|
||||
}
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
uploadBusy = false;
|
||||
(event.target as HTMLInputElement).value = "";
|
||||
}
|
||||
}
|
||||
async function assignModel(id: string) {
|
||||
busy = true;
|
||||
try {
|
||||
await settings.update({
|
||||
agent_llm_assignments: {
|
||||
[activeAgent?.llm_role ?? "main"]: id || null,
|
||||
},
|
||||
});
|
||||
await client.invalidateQueries({ queryKey: ["settings"] });
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
const shownTasks = $derived(
|
||||
($sessions.data ?? []).filter(
|
||||
(s) =>
|
||||
filter === "all" ||
|
||||
(filter === "sandbox"
|
||||
? s.project_id == null
|
||||
: s.running ||
|
||||
s.task_status === "awaiting_confirm" ||
|
||||
s.task_status === "awaiting_input"),
|
||||
),
|
||||
);
|
||||
const activeAgent = $derived(
|
||||
($registry.data ?? []).find(
|
||||
(a) => a.key === ($session.data?.agent_key || agentKey),
|
||||
),
|
||||
);
|
||||
const enabledSkills = $derived(
|
||||
($skills.data ?? []).filter(
|
||||
(s) => s.is_enabled && (!agentKey || s.bindings?.[agentKey]),
|
||||
),
|
||||
);
|
||||
const profiles = $derived($config.data?.llm_profiles ?? []);
|
||||
function modelName(key?: string | null) {
|
||||
const a = ($registry.data ?? []).find((a) => a.key === key);
|
||||
const id =
|
||||
(a && $config.data?.agent_llm_assignments?.[a.llm_role]) ||
|
||||
$config.data?.llm_active_id;
|
||||
return (
|
||||
profiles.find((p) => p.id === id)?.name ||
|
||||
$config.data?.llm_model ||
|
||||
"未配置模型"
|
||||
);
|
||||
}
|
||||
function status(s: AgentSession) {
|
||||
return s.running
|
||||
? "运行中"
|
||||
: ({
|
||||
ready: "未开始",
|
||||
awaiting_confirm: "待你确认",
|
||||
returned: "已带回项目",
|
||||
completed: "已完成",
|
||||
error: "失败",
|
||||
cancelled: "已停止",
|
||||
interrupted: "运行中断",
|
||||
awaiting_input: "等待回答",
|
||||
}[s.task_status ?? "ready"] ?? "未开始");
|
||||
}
|
||||
function openResult(r: AgentDeliverable) {
|
||||
editing = r;
|
||||
text = r.content;
|
||||
targetProject = r.project_id;
|
||||
targetStage = r.stage_key;
|
||||
dirty = false;
|
||||
error = "";
|
||||
}
|
||||
async function openTask(id: number) {
|
||||
if (dirty) {
|
||||
error = "请先保存成果草稿,再切换任务。";
|
||||
return false;
|
||||
}
|
||||
streaming = "";
|
||||
reasoning = "";
|
||||
liveTools = [];
|
||||
await goto(resolve(`/agents?session=${id}`));
|
||||
return true;
|
||||
}
|
||||
async function launchAssistant(key: WorkbenchStageKey) {
|
||||
if (busy || uploadBusy) return;
|
||||
agentKey = key;
|
||||
if (draft.trim()) {
|
||||
await send({
|
||||
content: draft,
|
||||
mentions: [],
|
||||
attachments: [...attachments],
|
||||
});
|
||||
return;
|
||||
}
|
||||
busy = true;
|
||||
try {
|
||||
const s = await agentApi.createSession({
|
||||
agent_key: key,
|
||||
project_id: projectId,
|
||||
});
|
||||
await openTask(s.id);
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
async function home() {
|
||||
if (dirty) {
|
||||
error = "请先保存成果草稿,再新建任务。";
|
||||
return;
|
||||
}
|
||||
editing = null;
|
||||
error = "";
|
||||
agentKey = "";
|
||||
await goto(resolve("/agents"));
|
||||
}
|
||||
$effect(() => {
|
||||
const id = activeId,
|
||||
results = taskResults;
|
||||
untrack(() => {
|
||||
if (editing?.session_id !== id) {
|
||||
editing = null;
|
||||
dirty = false;
|
||||
}
|
||||
if (!editing && results.length) openResult(results[0]);
|
||||
});
|
||||
});
|
||||
onMount(() => {
|
||||
if (!particles) return;
|
||||
const canvas = particles,
|
||||
ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
const points = Array.from({ length: 46 }, () => ({
|
||||
x: Math.random(),
|
||||
y: Math.random(),
|
||||
v: 0.15 + Math.random() * 0.35,
|
||||
s: Math.random() * 1.6 + 0.4,
|
||||
a: Math.random() * 0.5 + 0.15,
|
||||
}));
|
||||
const resize = () => {
|
||||
canvas.width = canvas.clientWidth;
|
||||
canvas.height = canvas.clientHeight;
|
||||
};
|
||||
resize();
|
||||
const observer = new ResizeObserver(resize);
|
||||
observer.observe(canvas);
|
||||
let raf = 0;
|
||||
const frame = () => {
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
if (
|
||||
!activeId &&
|
||||
document.documentElement.dataset.reduce !== "1" &&
|
||||
!matchMedia("(prefers-reduced-motion: reduce)").matches
|
||||
) {
|
||||
const color =
|
||||
getComputedStyle(document.documentElement)
|
||||
.getPropertyValue("--particle")
|
||||
.trim() || "168,121,255";
|
||||
for (const point of points) {
|
||||
point.y -= point.v / Math.max(1, canvas.height);
|
||||
point.x +=
|
||||
(Math.sin((point.y * canvas.height) / 60) * 0.2) /
|
||||
Math.max(1, canvas.width);
|
||||
if (point.y < 0) {
|
||||
point.y = 1;
|
||||
point.x = Math.random();
|
||||
}
|
||||
ctx.beginPath();
|
||||
ctx.arc(
|
||||
point.x * canvas.width,
|
||||
point.y * canvas.height,
|
||||
point.s,
|
||||
0,
|
||||
7,
|
||||
);
|
||||
ctx.fillStyle = `rgba(${color},${point.a})`;
|
||||
ctx.fill();
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(frame);
|
||||
};
|
||||
frame();
|
||||
return () => {
|
||||
cancelAnimationFrame(raf);
|
||||
observer.disconnect();
|
||||
};
|
||||
});
|
||||
async function refresh() {
|
||||
await Promise.all([
|
||||
client.invalidateQueries({ queryKey: ["b4-sessions"] }),
|
||||
client.invalidateQueries({ queryKey: ["b4-results"] }),
|
||||
client.invalidateQueries({ queryKey: ["agent-session"] }),
|
||||
]);
|
||||
}
|
||||
onMount(() =>
|
||||
connectEvents((ev) => {
|
||||
if (ev.type.startsWith("job."))
|
||||
void client.invalidateQueries({ queryKey: ["b4-jobs"] });
|
||||
if (ev.type === "events.resync" || ev.type === "agent.session.updated") {
|
||||
void refresh();
|
||||
return;
|
||||
}
|
||||
if (
|
||||
ev.data?.session_id !== activeId &&
|
||||
(ev.data?.message as { session_id?: number } | undefined)
|
||||
?.session_id !== activeId
|
||||
)
|
||||
return;
|
||||
if (ev.type === "agent.token")
|
||||
streaming += String(ev.data?.content ?? "");
|
||||
if (ev.type === "agent.thinking")
|
||||
reasoning += String(ev.data?.content ?? "");
|
||||
if (ev.type === "agent.message") {
|
||||
streaming = "";
|
||||
void client.invalidateQueries({
|
||||
queryKey: ["agent-session", activeId],
|
||||
});
|
||||
}
|
||||
if (ev.type === "agent.plan" || ev.type === "agent.task")
|
||||
void client.invalidateQueries({
|
||||
queryKey: ["agent-session", activeId],
|
||||
});
|
||||
if (ev.type === "agent.tool") {
|
||||
const tool = String(ev.data?.tool ?? "");
|
||||
if (ev.data?.phase === "start")
|
||||
liveTools.push({
|
||||
tool,
|
||||
args: ev.data?.args as Record<string, unknown>,
|
||||
phase: "running",
|
||||
});
|
||||
else {
|
||||
const index = liveTools
|
||||
.map((t) => t.tool === tool && t.phase === "running")
|
||||
.lastIndexOf(true);
|
||||
if (index >= 0)
|
||||
liveTools[index] = {
|
||||
...liveTools[index],
|
||||
result: ev.data?.result,
|
||||
phase:
|
||||
(ev.data?.result as { ok?: boolean })?.ok === false
|
||||
? "error"
|
||||
: "done",
|
||||
};
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
async function send(payload: AgentComposerPayload) {
|
||||
if (busy || uploadBusy) return;
|
||||
busy = true;
|
||||
error = "";
|
||||
try {
|
||||
let sid = activeId;
|
||||
if (!sid) {
|
||||
const s = await agentApi.createSession({
|
||||
project_id: projectId,
|
||||
agent_key: agentKey || null,
|
||||
});
|
||||
sid = s.id;
|
||||
await goto(resolve(`/agents?session=${sid}`));
|
||||
}
|
||||
const skill = enabledSkills.find((s) => s.dir === selectedSkill);
|
||||
if (
|
||||
skill &&
|
||||
payload.mentions.filter((m) => m.type === "skill").length < 4 &&
|
||||
!payload.mentions.some(
|
||||
(m) => m.type === "skill" && m.name === skill.dir,
|
||||
)
|
||||
)
|
||||
payload.mentions.push({
|
||||
type: "skill",
|
||||
name: skill.dir,
|
||||
description: skill.description,
|
||||
});
|
||||
await agentApi.postMessage(sid, payload);
|
||||
draft = "";
|
||||
attachments = [];
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
async function save() {
|
||||
if (!editing || saving) return null;
|
||||
saving = true;
|
||||
error = "";
|
||||
try {
|
||||
const r = await resultsApi.patch(editing.id, {
|
||||
revision: editing.revision,
|
||||
content: text,
|
||||
project_id: targetProject,
|
||||
stage_key: targetStage,
|
||||
});
|
||||
openResult(r);
|
||||
await client.invalidateQueries({ queryKey: ["b4-results"] });
|
||||
toast.success("草稿已保存");
|
||||
return r;
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
return null;
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
async function returnToProject() {
|
||||
if (!editing || !targetProject || saving) return;
|
||||
const r = dirty ? await save() : editing;
|
||||
if (!r) return;
|
||||
saving = true;
|
||||
error = "";
|
||||
try {
|
||||
const res = await resultsApi.store({
|
||||
deliverable_id: r.id,
|
||||
revision: r.revision,
|
||||
project_id: targetProject,
|
||||
stage_key: targetStage,
|
||||
});
|
||||
toast.success(
|
||||
res.already_attached ? "该版本已带回项目" : "已带回项目,等待确认",
|
||||
);
|
||||
await refresh();
|
||||
await goto(resolve(`/workbench/${targetProject}?stage=${targetStage}`));
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
const projectJobs = createQuery(
|
||||
toStore(() => ({
|
||||
queryKey: ["b4-jobs", targetProject],
|
||||
queryFn: () => jobsApi.list(targetProject!),
|
||||
enabled: targetProject != null,
|
||||
})),
|
||||
);
|
||||
function shotJob(id: string) {
|
||||
return ($projectJobs.data ?? []).find(
|
||||
(j) =>
|
||||
j.payload?.stage_key === targetStage &&
|
||||
j.payload?.target_id === id &&
|
||||
j.status === "done" &&
|
||||
j.output_paths?.length,
|
||||
);
|
||||
}
|
||||
const structuredShots = $derived.by(() => {
|
||||
const data = parseContent(text);
|
||||
return Array.isArray(data?.shots)
|
||||
? (data.shots as {
|
||||
id: string;
|
||||
description?: string;
|
||||
prompt?: string;
|
||||
duration_sec?: number;
|
||||
}[])
|
||||
: [];
|
||||
});
|
||||
async function redraw(shot: {
|
||||
id: string;
|
||||
description?: string;
|
||||
prompt?: string;
|
||||
duration_sec?: number;
|
||||
}) {
|
||||
if (!targetProject || saving || !shot.id) return;
|
||||
saving = true;
|
||||
error = "";
|
||||
try {
|
||||
await workbenchApi.generate(targetProject, {
|
||||
kind: targetStage === "shot" ? "video" : "image",
|
||||
stage_key: targetStage,
|
||||
target_id: shot.id,
|
||||
prompt: shot.prompt || shot.description || "",
|
||||
duration_sec: shot.duration_sec,
|
||||
});
|
||||
toast.success(`仅镜头 ${shot.id} 已入队`);
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
{#snippet header()}
|
||||
<header class="b4-header">
|
||||
{#if activeId}<div class="b4-crumb"><button onclick={home}>智能体</button>/<b>{$session.data?.title ?? "加载任务…"}</b></div><span class="a-tag sc">{$session.data ? status($session.data) : "加载中"}</span>{:else}<div class="b4-crumb"><button onclick={home}><b>智能体</b></button></div><span class="b4-subtitle">把创作任务交给助手,成果回到项目等你确认</span>{/if}<span class="b4-grow"></span>{#if activeId}<span class="b4-chip"
|
||||
><Icon name="agent-cpu" size={14}/><b>{modelName($session.data?.agent_key)}</b></span
|
||||
>{/if}<a class="a-btn secondary sm" href={resolve("/agents?legacy=1")}
|
||||
>原会话与技能管理</a
|
||||
>
|
||||
</header>
|
||||
{/snippet}
|
||||
{#snippet shellHeader()}{/snippet}
|
||||
<AppShell active="agents" title="智能体" workspace pageHeader={shellHeader}>
|
||||
<div class="b4" class:task-view={activeId != null}>
|
||||
{@render header()}
|
||||
<div class="aurora fx-only"><i></i><i></i><i></i></div>
|
||||
<canvas class="particles fx-only" bind:this={particles} aria-hidden="true"
|
||||
></canvas>
|
||||
<div class={activeId ? "atask" : "agent-grid"}>
|
||||
<aside class="tasklist">
|
||||
<div class="tl-h">
|
||||
<button class="a-btn scene" onclick={home}
|
||||
><Icon name="plus" size={14} />新任务</button
|
||||
>{#if !activeId}<div class="b4-seg">
|
||||
{#each [["active", "进行中"], ["all", "全部"], ["sandbox", "沙盒"]] as [value, label] (value)}<button
|
||||
class:on={filter === value}
|
||||
onclick={() => (filter = value)}>{label}</button
|
||||
>{/each}
|
||||
</div>{/if}
|
||||
</div>
|
||||
<div class="tl-b">
|
||||
{#each shownTasks as s (s.id)}<button
|
||||
class="titem"
|
||||
data-session-id={s.id}
|
||||
class:on={s.id === activeId}
|
||||
onclick={() => openTask(s.id)}
|
||||
title={s.task_summary || s.title}
|
||||
><b>{s.title}</b><span class="meta"
|
||||
><i class="dot" style:--agent-task-dot={s.running ? "var(--agent-task-running)" : s.task_status === "returned" ? "var(--agent-task-returned)" : s.task_status === "awaiting_confirm" ? "var(--agent-task-confirm)" : "var(--agent-task-idle)"}></i>{status(s)}<span class="b4-grow"></span>{s
|
||||
.project?.title ?? "沙盒"}</span
|
||||
></button
|
||||
>{:else}<p class="b4-empty">
|
||||
{$sessions.isPending ? "加载任务…" : "暂无任务"}
|
||||
</p>{/each}
|
||||
</div>
|
||||
</aside>
|
||||
{#if !activeId}
|
||||
<div class="agent-home">
|
||||
<div class="ahero">
|
||||
<div class="hero-copy">
|
||||
<span class="eyebrow">主创智能体 · 统筹五个阶段助手</span>
|
||||
<h2>从一个想法,到一组能直接开拍的镜头</h2>
|
||||
<p class="muted">
|
||||
它会先列计划,再调用剧本、视觉、分镜、素材与镜头助手;每一步的成果都是可编辑草稿,你确认后才写入项目。
|
||||
</p>
|
||||
<div class="steps">
|
||||
{#each ["说出想法", "确认计划", "编辑成果", "带回项目"] as label, i (label)}<span
|
||||
><i>{i + 1}</i>{label}</span
|
||||
>{/each}
|
||||
</div>
|
||||
<div class="big-input">
|
||||
<textarea
|
||||
aria-label="任务想法"
|
||||
bind:value={draft}
|
||||
placeholder="描述你的创作想法、目标与要求…"
|
||||
></textarea>
|
||||
<div class="b4-row">
|
||||
<label class="b4-chip"
|
||||
><Icon name="nav-project" size={14} />绑定:<select
|
||||
aria-label="绑定项目"
|
||||
bind:value={projectId}
|
||||
><option value={null}>沙盒</option
|
||||
>{#each $projects.data ?? [] as p (p.id)}<option
|
||||
value={p.id}>{p.title}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
><label class="b4-chip"
|
||||
><Icon name="agent-cpu" size={14} /><select
|
||||
aria-label="任务模型"
|
||||
disabled={busy}
|
||||
value={$config.data?.agent_llm_assignments?.[
|
||||
activeAgent?.llm_role ?? "main"
|
||||
] ?? ""}
|
||||
onchange={(e) => assignModel(e.currentTarget.value)}
|
||||
><option value="">{modelName(agentKey)}</option
|
||||
>{#each profiles as p (p.id)}<option value={p.id}
|
||||
>{p.name}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
><label class="b4-chip"
|
||||
><Icon name="project-book" size={14} />技能
|
||||
<select aria-label="任务技能" bind:value={selectedSkill}
|
||||
><option value="">不指定</option
|
||||
>{#each enabledSkills as s (s.dir)}<option value={s.dir}
|
||||
>{s.name}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
><input
|
||||
hidden
|
||||
type="file"
|
||||
bind:this={uploadInput}
|
||||
multiple
|
||||
accept="image/*,video/*,audio/*,.txt,.md,.docx"
|
||||
onchange={upload}
|
||||
/><button
|
||||
class="b4-chip"
|
||||
disabled={uploadBusy || busy}
|
||||
onclick={() => uploadInput?.click()}
|
||||
><Icon name="upload" size={14} />参考材料{attachments.length
|
||||
? ` · ${attachments.length}`
|
||||
: ""}</button
|
||||
><span class="b4-grow"></span><button
|
||||
class="a-btn primary"
|
||||
disabled={busy || uploadBusy || !draft.trim()}
|
||||
onclick={() =>
|
||||
send({
|
||||
content: draft,
|
||||
mentions: [],
|
||||
attachments: [...attachments],
|
||||
})}><Icon name="agent-send" size={14} />开始任务</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="orb fx-only">
|
||||
<div class="ring r2"></div>
|
||||
<div class="ring"></div>
|
||||
<div class="core"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div class="sec-h">
|
||||
<h2>阶段助手</h2>
|
||||
<span class="dim">每个助手对应项目的一个阶段,也可以单独调用</span
|
||||
>
|
||||
</div>
|
||||
<div class="roster">
|
||||
{#each $registry.data ?? [] as a, i (a.key)}<button
|
||||
class="acard"
|
||||
style:--c={assistantColors[a.key]}
|
||||
disabled={busy || uploadBusy}
|
||||
onclick={() => launchAssistant(a.key as WorkbenchStageKey)}
|
||||
><span class="num">0{i + 1}</span><span class="ic"
|
||||
><Icon name={assistantIcons[a.key]} size={18} /></span
|
||||
>
|
||||
<div class="tx">
|
||||
<b>{stageNames[a.key as WorkbenchStageKey]}</b>
|
||||
<p>{assistantDescriptions[a.key]}</p>
|
||||
<div class="b4-row">
|
||||
<span class="a-tag">{a.skill_count} 个技能</span><span
|
||||
class="b4-grow"
|
||||
></span><span class="dim">{modelName(a.key)}</span>
|
||||
</div>
|
||||
</div></button
|
||||
>{/each}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mini-row">
|
||||
<div class="panel">
|
||||
<h3>最近成果<span class="dim">点开即可编辑,再带回项目</span></h3>
|
||||
<div class="outrow">
|
||||
{#each ($allResults.data ?? []).slice(0, 4) as r (r.id)}<button
|
||||
class="outcard"
|
||||
data-deliverable-id={r.id}
|
||||
onclick={async () => {
|
||||
if (await openTask(r.session_id)) openResult(r);
|
||||
}}
|
||||
><div class="t"><Icon name="file" size={24} /></div>
|
||||
<div class="d">
|
||||
<b>{r.title}</b><span class="dim"
|
||||
>{stageNames[r.stage_key]} · 草稿 v{r.revision}</span
|
||||
>
|
||||
</div></button
|
||||
>{:else}<p class="b4-empty">
|
||||
暂无成果,完成任务后将在这里显示。
|
||||
</p>{/each}
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h3>
|
||||
技能库<span class="a-tag">{($skills.data ?? []).length}</span
|
||||
><span class="b4-grow"></span><a
|
||||
class="a-btn sm ghost"
|
||||
href={resolve("/agents?legacy=1")}>管理</a
|
||||
>
|
||||
</h3>
|
||||
<div class="skills">
|
||||
{#each ($skills.data ?? [])
|
||||
.filter((s) => s.is_enabled)
|
||||
.slice(0, 7) as s (s.dir)}<button
|
||||
class="skill"
|
||||
title={s.description}
|
||||
onclick={() => {
|
||||
selectedSkill = s.dir;
|
||||
agentKey = "";
|
||||
}}><i></i>{s.name}</button
|
||||
>{:else}<span class="dim">尚未添加技能</span>{/each}<a
|
||||
class="skill dim"
|
||||
href={resolve("/agents?legacy=1")}>+ 学习新技能</a
|
||||
>
|
||||
</div>
|
||||
<p class="dim">
|
||||
技能 = 可复用的规则 +
|
||||
示例。可从对话中“记住这个做法”生成,也可导入 Markdown。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="convo">
|
||||
<div class="convo-b">
|
||||
{#if $session.data?.plan}<AgentPlanPanel
|
||||
plan={$session.data.plan}
|
||||
/>{/if}<AgentChat
|
||||
studio
|
||||
messages={$session.data?.messages ?? []}
|
||||
{liveTools}
|
||||
{streaming}
|
||||
streamingReasoning={reasoning}
|
||||
{running}
|
||||
loading={$session.isPending}
|
||||
onAnswer={(option, _scope, seq) =>
|
||||
send({
|
||||
content: option,
|
||||
mentions: [],
|
||||
attachments: [],
|
||||
answer_to: seq,
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div class="convo-in">
|
||||
<AgentComposer
|
||||
studio
|
||||
{running}
|
||||
onSend={send}
|
||||
onCancel={() => {
|
||||
if (activeId) void agentApi.cancel(activeId);
|
||||
}}
|
||||
workflows={($wfQuery.data ?? [])
|
||||
.filter((w) => w.is_enabled)
|
||||
.map((w) => ({
|
||||
id: w.id,
|
||||
name: w.name,
|
||||
kind: w.kind as "image" | "video",
|
||||
}))}
|
||||
skills={($skills.data ?? [])
|
||||
.filter((s) => s.is_enabled)
|
||||
.map((s) => ({
|
||||
name: s.dir,
|
||||
description: s.description,
|
||||
tags: s.tags,
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<aside class="artifact">
|
||||
<div class="art-h">
|
||||
<div class="b4-row">
|
||||
<b>{editing ? stageNames[editing.stage_key] : "成果"} · 草稿</b
|
||||
><span class="a-tag sc">未确认</span><span class="b4-grow"
|
||||
></span><span class="dim mono art-meta"
|
||||
>{structuredShots.length
|
||||
? `${structuredShots.length} 镜 · ${structuredShots.reduce((sum, shot) => sum + (Number(shot.duration_sec) || 0), 0)}s`
|
||||
: editing
|
||||
? `v${editing.revision}`
|
||||
: ""}</span
|
||||
>
|
||||
</div>
|
||||
{#if taskResults.length > 1}<div class="b4-seg">
|
||||
{#each taskResults as r (r.id)}<button
|
||||
class:on={editing?.id === r.id}
|
||||
onclick={() => {
|
||||
if (!dirty) openResult(r);
|
||||
else error = "请先保存当前成果";
|
||||
}}>成果 {r.id}</button
|
||||
>{/each}
|
||||
</div>{/if}
|
||||
<div class="b4-seg art-tabs">
|
||||
<button
|
||||
class:on={artifactTab === "shots"}
|
||||
onclick={() => (artifactTab = "shots")}>镜头</button
|
||||
>
|
||||
<button disabled title="当前成果没有角色数据">角色</button>
|
||||
<button
|
||||
class:on={artifactTab === "text"}
|
||||
onclick={() => (artifactTab = "text")}>原文</button
|
||||
>
|
||||
<button onclick={comparePrevious} disabled={!editing}
|
||||
>对比上一版</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
<div class="art-b">
|
||||
{#if editing}
|
||||
{#if structuredShots.length && artifactTab === "shots"}
|
||||
{#each structuredShots as shot, i (shot.id)}
|
||||
<div class="shot">
|
||||
<div class="th">
|
||||
<span>{String(i + 1).padStart(2, "0")}</span
|
||||
>{#if shotJob(shot.id)?.kind === "video"}<video
|
||||
src={assetUrl(shotJob(shot.id)!.output_paths![0]) ??
|
||||
""}
|
||||
controls
|
||||
muted
|
||||
preload="metadata"
|
||||
aria-label={`镜头 ${shot.id} 视频`}
|
||||
|
||||
></video>{:else if shotJob(shot.id)?.output_paths?.[0]}<img
|
||||
src={assetUrl(shotJob(shot.id)!.output_paths![0]) ??
|
||||
""}
|
||||
alt={`镜头 ${shot.id} 草图`}
|
||||
/>{:else}<small class="dim">暂无草图</small>{/if}
|
||||
</div>
|
||||
<div class="shot-copy">
|
||||
<textarea
|
||||
aria-label={`镜头 ${shot.id} 描述`}
|
||||
value={shot.description || shot.prompt || ""}
|
||||
oninput={(e) =>
|
||||
editShot(
|
||||
i,
|
||||
shot.description != null ? "description" : "prompt",
|
||||
e.currentTarget.value,
|
||||
)}
|
||||
></textarea>
|
||||
<div class="b4-row">
|
||||
<label class="a-tag mono"
|
||||
><input
|
||||
aria-label={`镜头 ${shot.id} 时长`}
|
||||
type="number"
|
||||
min="0.1"
|
||||
step="0.1"
|
||||
value={shot.duration_sec ?? 3}
|
||||
oninput={(e) =>
|
||||
editShot(
|
||||
i,
|
||||
"duration_sec",
|
||||
Number(e.currentTarget.value),
|
||||
)}
|
||||
/>s</label
|
||||
><span class="b4-grow"></span><button
|
||||
class="a-btn sm ghost"
|
||||
disabled={saving || !targetProject || dirty}
|
||||
onclick={() => redraw(shot)}><Icon name="project-refresh" size={14}/>重画</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/each}
|
||||
{:else}<textarea
|
||||
class="draft-editor"
|
||||
aria-label="成果草稿"
|
||||
bind:value={text}
|
||||
oninput={() => (dirty = true)}
|
||||
></textarea>{/if}
|
||||
{:else}<p class="b4-empty">
|
||||
暂无成果。任务完成后,真实回复将在这里形成可编辑草稿。
|
||||
</p>{/if}
|
||||
</div>
|
||||
<div class="art-f">
|
||||
<label class="b4-row dim"
|
||||
>带回到<span class="b4-chip"><select
|
||||
aria-label="成果项目"
|
||||
bind:value={targetProject}
|
||||
onchange={() => (dirty = true)}
|
||||
disabled={!editing}
|
||||
><option value={null}>选择项目</option
|
||||
>{#each $projects.data ?? [] as p (p.id)}<option value={p.id}
|
||||
>{p.title}</option
|
||||
>{/each}</select
|
||||
> · <select
|
||||
class="stage-select"
|
||||
aria-label="成果阶段"
|
||||
bind:value={targetStage}
|
||||
onchange={() => (dirty = true)}
|
||||
disabled={!editing}
|
||||
>{#each keys as key (key)}<option value={key}
|
||||
>{stageNames[key]}</option
|
||||
>{/each}</select
|
||||
></span></label
|
||||
>
|
||||
<div class="b4-row">
|
||||
<button
|
||||
class="a-btn secondary"
|
||||
disabled={!editing || saving}
|
||||
onclick={save}>保存草稿</button
|
||||
><button
|
||||
class="a-btn primary"
|
||||
disabled={!editing || !targetProject || saving}
|
||||
onclick={returnToProject}
|
||||
><Icon name="arrow-right" size={14} />带回项目待确认</button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
{/if}
|
||||
</div>
|
||||
{#if error}<div class="b4-error" role="alert">
|
||||
{error}<button class="a-btn sm ghost" onclick={() => (error = "")}
|
||||
>关闭</button
|
||||
>
|
||||
</div>{/if}
|
||||
</div>
|
||||
</AppShell>
|
||||
|
||||
<Modal bind:open={compareOpen} title="对比上一版" size="lg">
|
||||
<div class="b4-compare">
|
||||
<section>
|
||||
<h3>上一保存版本</h3>
|
||||
<pre>{previousText || "尚无上一保存版本"}</pre>
|
||||
</section>
|
||||
<section>
|
||||
<h3>当前草稿{dirty ? " · 未保存" : ""}</h3>
|
||||
<pre>{text}</pre>
|
||||
</section>
|
||||
</div>
|
||||
</Modal>
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -43,6 +43,7 @@
|
||||
} from '$lib/components/generate/takes';
|
||||
import './InputRequirementBadge.svelte';
|
||||
import WorkflowBay from './WorkflowBay.svelte';
|
||||
import StoreResultModal from '$lib/components/generate/StoreResultModal.svelte';
|
||||
import DeskWorkflowRail from './DeskWorkflowRail.svelte';
|
||||
import {
|
||||
apiErrorMessage,
|
||||
@@ -1034,8 +1035,10 @@
|
||||
// stale rows — the toast just reports what happened.
|
||||
// ------------------------------------------------------------------
|
||||
let attachBusyId = $state<number | null>(null);
|
||||
let storeJobId = $state<number | null>(null);
|
||||
|
||||
async function attachToProject(job: Job) {
|
||||
if (!workbenchCtxOf(job)) { storeJobId = job.id; return; }
|
||||
if (attachBusyId != null) return;
|
||||
attachBusyId = job.id;
|
||||
try {
|
||||
@@ -1236,7 +1239,6 @@
|
||||
inactive={false}
|
||||
canSendToSlot={!!imageSlotTarget || !!imageList}
|
||||
canAttach={!!selectedJob &&
|
||||
!!workbenchCtxOf(selectedJob) &&
|
||||
selectedJob.status === 'done'}
|
||||
attachBusy={attachBusyId === selectedJob?.id}
|
||||
onAttach={() => selectedJob && attachToProject(selectedJob)}
|
||||
@@ -1854,3 +1856,5 @@
|
||||
color: var(--text-3);
|
||||
}
|
||||
</style>
|
||||
|
||||
<StoreResultModal jobId={storeJobId} onclose={()=>storeJobId=null} />
|
||||
|
||||
@@ -165,6 +165,7 @@
|
||||
<h3>2 · 准备这次创作</h3>
|
||||
{#if hasSlots && !dock}<div class="slots">
|
||||
<SlotTray
|
||||
allowScene={current?.kind === 'video'}
|
||||
bind:this={tray}
|
||||
bind:busy={slotBusy}
|
||||
{ds}
|
||||
@@ -374,6 +375,7 @@
|
||||
>
|
||||
<div class="media-editor">
|
||||
<SlotTray
|
||||
allowScene={current?.kind === 'video'}
|
||||
bind:this={tray}
|
||||
bind:busy={slotBusy}
|
||||
{ds}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from "$app/paths";
|
||||
import { assetUrl } from "$lib/api";
|
||||
import { shotApi, type Capture } from "$lib/shot/api";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import { toast } from "$lib/toast";
|
||||
|
||||
let {
|
||||
open = $bindable(false),
|
||||
onPick,
|
||||
}: { open?: boolean; onPick: (path: string) => void } = $props();
|
||||
let compositions = $state<Array<{ id: number; title: string }>>([]);
|
||||
let compositionId = $state("");
|
||||
let captures = $state<Capture[]>([]);
|
||||
let loading = $state(false);
|
||||
let request = 0;
|
||||
$effect(() => {
|
||||
if (!open) {
|
||||
request++;
|
||||
return;
|
||||
}
|
||||
const version = ++request;
|
||||
loading = true;
|
||||
shotApi
|
||||
.listCompositions()
|
||||
.then((rows) => {
|
||||
if (version !== request) return;
|
||||
compositions = rows;
|
||||
compositionId = rows.length ? String(rows[0].id) : "";
|
||||
})
|
||||
.catch((error) => toast.error(String(error)))
|
||||
.finally(() => {
|
||||
if (version === request) loading = false;
|
||||
});
|
||||
});
|
||||
$effect(() => {
|
||||
if (!open || !compositionId) {
|
||||
captures = [];
|
||||
return;
|
||||
}
|
||||
const id = Number(compositionId);
|
||||
let active = true;
|
||||
captures = [];
|
||||
shotApi.listCaptures(id).then((rows) => {
|
||||
if (active)
|
||||
captures = rows.filter((c) => c.kind === "image" && c.file_path);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
});
|
||||
</script>
|
||||
|
||||
<Modal bind:open title="从三维搭景截取">
|
||||
<p>选择已保存的搭景截图,填入当前工作流声明的图片槽。</p>
|
||||
<a
|
||||
class="a-btn secondary sm"
|
||||
href={resolve("/build-scene")}
|
||||
target="_blank"
|
||||
rel="noopener">打开三维搭景</a
|
||||
>
|
||||
{#if loading}<p>正在读取截图…</p>{:else if !compositions.length}<p>
|
||||
暂无搭景,请先保存截图。
|
||||
</p>{:else}
|
||||
<label class="field"
|
||||
><span class="field-label">场景</span><select
|
||||
class="field-input"
|
||||
bind:value={compositionId}
|
||||
>{#each compositions as comp (comp.id)}<option value={String(comp.id)}
|
||||
>{comp.title}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
>
|
||||
<div class="capture-choices">
|
||||
{#each captures as capture (capture.id)}<button
|
||||
class="a-btn secondary"
|
||||
onclick={() => {
|
||||
if (capture.file_path) {
|
||||
onPick(capture.file_path);
|
||||
open = false;
|
||||
}
|
||||
}}
|
||||
><img
|
||||
src={assetUrl(capture.file_path) ?? ""}
|
||||
alt={capture.label ?? "搭景截图"}
|
||||
/><span>{capture.label ?? `截图 ${capture.id}`}</span></button
|
||||
>{:else}<p>该场景暂无图片截图。</p>{/each}
|
||||
</div>{/if}
|
||||
</Modal>
|
||||
|
||||
<style>
|
||||
.capture-choices {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: var(--sp-4);
|
||||
margin-top: var(--sp-5);
|
||||
}
|
||||
.capture-choices button {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: var(--sp-3);
|
||||
height: auto;
|
||||
white-space: normal;
|
||||
}
|
||||
.capture-choices img {
|
||||
width: 100%;
|
||||
aspect-ratio: 16/9;
|
||||
object-fit: contain;
|
||||
}
|
||||
</style>
|
||||
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import SceneCapturePicker from './SceneCapturePicker.svelte';
|
||||
import MediaSlot from '$lib/components/studio/MediaSlot.svelte';
|
||||
import RefImageGrid from '$lib/components/studio/RefImageGrid.svelte';
|
||||
import { mediaFileProblem } from '$lib/comfy/imageFile';
|
||||
@@ -16,6 +17,7 @@
|
||||
*/
|
||||
interface Props {
|
||||
ds: DeskSchema;
|
||||
allowScene?: boolean;
|
||||
values: FormValues;
|
||||
showErrors: boolean;
|
||||
errors: Record<string, string>;
|
||||
@@ -25,7 +27,34 @@
|
||||
onFromResults: (nodeId: string) => void;
|
||||
}
|
||||
|
||||
let { ds, values, showErrors, errors, busy = $bindable(false), onSet, onFromResults }: Props = $props();
|
||||
let { ds, allowScene = false, values, showErrors, errors, busy = $bindable(false), onSet, onFromResults }: Props = $props();
|
||||
|
||||
let sceneOpen = $state(false);
|
||||
let sceneNode = $state("");
|
||||
$effect(() => {
|
||||
void ds;
|
||||
sceneOpen = false;
|
||||
sceneNode = "";
|
||||
});
|
||||
function pickScene(path: string) {
|
||||
const slot = ds.slots.find(
|
||||
(s) => s.inp.nodeId === sceneNode && s.mediaKind === "image" && !s.mask,
|
||||
);
|
||||
const list = ds.lists.find(
|
||||
(g) => g.nodeId === sceneNode && g.kind === "image_list",
|
||||
);
|
||||
if (!allowScene) return;
|
||||
if (slot) onSet(sceneNode, path);
|
||||
else if (list) {
|
||||
const paths = listPaths(values, list);
|
||||
if (paths.length >= (list.max ?? 9)) {
|
||||
toast.error("参考图数量已达上限");
|
||||
return;
|
||||
}
|
||||
onSet(sceneNode, [...paths, path]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const uploads = createUploadManager();
|
||||
type Reject = { name: string; message: string };
|
||||
@@ -149,6 +178,7 @@
|
||||
if (unplaced) toast.error(t('desk.dropNoSlot', { n: unplaced }));
|
||||
}
|
||||
</script>
|
||||
<SceneCapturePicker bind:open={sceneOpen} onPick={pickScene}/>
|
||||
|
||||
{#if ds.slots.length || ds.lists.length}
|
||||
<div class="tray">
|
||||
@@ -169,6 +199,7 @@
|
||||
anchorId={`slot-${s.inp.nodeId}`}
|
||||
onFile={(f) => slotFile(s, f)}
|
||||
onFromResults={() => onFromResults(s.inp.nodeId)}
|
||||
onFromScene={allowScene && s.mediaKind === "image" && !s.mask ? () => { sceneNode = s.inp.nodeId; sceneOpen = true; } : undefined}
|
||||
onClear={() => {
|
||||
setRejects(s.inp.nodeId, []);
|
||||
onSet(s.inp.nodeId, '');
|
||||
@@ -193,6 +224,7 @@
|
||||
onReplace={(i, file) => groupReplace(entry, i, file)}
|
||||
onRemove={(i) => onSet(entry.nodeId, listPaths(values, entry).filter((_, j) => j !== i))}
|
||||
onDismissReject={(i) => setRejects(entry.nodeId, (rejects[entry.nodeId] ?? []).filter((_, j) => j !== i))}
|
||||
onFromScene={allowScene && entry.kind === "image_list" ? () => { sceneNode = entry.nodeId; sceneOpen = true; } : undefined}
|
||||
onFromResults={entry.kind === 'image_list' ? () => onFromResults(entry.nodeId) : undefined}
|
||||
/>
|
||||
{/each}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<script lang="ts">
|
||||
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import { agentApi, resultsApi, type WorkbenchStageKey } from "$lib/api";
|
||||
import { toast } from "$lib/toast";
|
||||
let { jobId, onclose }: { jobId: number | null; onclose: () => void } =
|
||||
$props();
|
||||
const client = useQueryClient();
|
||||
const projects = createQuery({
|
||||
queryKey: ["b4-projects"],
|
||||
queryFn: agentApi.listLinkableProjects,
|
||||
});
|
||||
let projectId = $state<number | null>(null);
|
||||
let stage = $state<WorkbenchStageKey>("assets");
|
||||
let busy = $state(false),
|
||||
error = $state("");
|
||||
async function store() {
|
||||
if (!jobId || !projectId || busy) return;
|
||||
busy = true;
|
||||
error = "";
|
||||
try {
|
||||
const res = await resultsApi.store({
|
||||
job_id: jobId,
|
||||
project_id: projectId,
|
||||
stage_key: stage,
|
||||
});
|
||||
await client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
toast.success(
|
||||
res.already_attached
|
||||
? "该结果已存入此阶段"
|
||||
: "已存入项目草稿,等待确认",
|
||||
);
|
||||
onclose();
|
||||
} catch (e) {
|
||||
error = e instanceof Error ? e.message : String(e);
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<Modal open={jobId != null} title="存入项目草稿" {onclose} dismissible={!busy}>
|
||||
<p>选择项目和阶段,结果将在该阶段等待确认。</p>
|
||||
<label class="field"
|
||||
>项目<select aria-label="存入项目" bind:value={projectId}
|
||||
><option value={null}>选择项目</option
|
||||
>{#each $projects.data ?? [] as p (p.id)}<option value={p.id}
|
||||
>{p.title}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
>
|
||||
<label class="field"
|
||||
>阶段<select aria-label="存入阶段" bind:value={stage}
|
||||
>{#each [["script", "剧本创作"], ["style", "视觉设计"], ["storyboard", "分镜设计"], ["assets", "素材资产"], ["shot", "镜头脚本"]] as [value, label] (value)}<option
|
||||
{value}>{label}</option
|
||||
>{/each}</select
|
||||
></label
|
||||
>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#snippet footer()}<button class="a-btn" disabled={busy} onclick={onclose}
|
||||
>取消</button
|
||||
><button class="a-btn primary" disabled={!projectId || busy} onclick={store}
|
||||
>存入待确认草稿</button
|
||||
>{/snippet}
|
||||
</Modal>
|
||||
@@ -105,7 +105,7 @@
|
||||
!!job.workbench_attach && !!wbCtx && job.workbench_attach.target_id === wbCtx.sourceId,
|
||||
);
|
||||
const canAttach = $derived(
|
||||
!!onAttach && !!wbCtx && !attached && st.tone === 'ok' && !fileGone && !!output,
|
||||
!!onAttach && !attached && st.tone === 'ok' && !fileGone && !!output,
|
||||
);
|
||||
|
||||
let portrait = $state(false);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -22,7 +22,7 @@
|
||||
* real queue and connection status. Individual tools keep their routes. */
|
||||
interface Props {
|
||||
workspace?: boolean;
|
||||
pageHeader?: import("svelte").Snippet;
|
||||
pageHeader?: import("svelte").Snippet<[{ openSearch: () => void }]>;
|
||||
active: NavId;
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
@@ -282,7 +282,7 @@
|
||||
class="app-body"
|
||||
style:background={pageHeader ? "var(--manage-page-background)" : undefined}
|
||||
>
|
||||
{#if pageHeader}{@render pageHeader()}{:else}
|
||||
{#if pageHeader}{@render pageHeader({ openSearch: openPalette })}{:else}
|
||||
<header class="topbar">
|
||||
<div class="breadcrumb">
|
||||
{currentNav?.label ?? title}<span>/</span><span class="page-name"
|
||||
|
||||
@@ -48,19 +48,23 @@
|
||||
>
|
||||
<span class="preview" data-theme={item.id} aria-hidden="true"
|
||||
><span class="rail"></span><span class="list"
|
||||
><i></i><i></i><i></i></span
|
||||
><i></i><i></i><i></i>{#if tiles}<i></i>{/if}</span
|
||||
><span class="stage"
|
||||
><i></i><b
|
||||
>{#if tiles}<em></em>{/if}</b
|
||||
></span
|
||||
></span
|
||||
>{#if tiles}<span class="preview-text"></span>{/if}</span
|
||||
>
|
||||
<span class="copy"
|
||||
><strong
|
||||
>{item.name}{#if tiles && item.id === "night"}
|
||||
<span class="mg-tag theme-default">默认</span>{/if}</strong
|
||||
><small>{tiles ? item.description.split(" · ")[0] : item.english}</small
|
||||
>{#if !tiles}<span>{item.description}</span>{/if}</span
|
||||
>{tiles && item.id === "night"
|
||||
? item.name + " "
|
||||
: item.name}{#if tiles && item.id === "night"}<span
|
||||
class="mg-tag theme-default">默认</span
|
||||
>{/if}</strong
|
||||
><small>{tiles ? item.tone : item.english}</small>{#if !tiles}<span
|
||||
>{item.description}</span
|
||||
>{/if}</span
|
||||
>
|
||||
<span class="check" class:tile-check={tiles} aria-hidden="true"
|
||||
>{$theme === item.id ? "✓" : ""}</span
|
||||
@@ -80,14 +84,17 @@
|
||||
}
|
||||
.choices.tiles {
|
||||
--choice-check-width: 0px;
|
||||
--choice-hover-background: var(--bg-2);
|
||||
--choice-display: flex;
|
||||
--choice-box-sizing: border-box;
|
||||
--choice-gap: 6px;
|
||||
--choice-copy-gap: 6px;
|
||||
--choice-tone-align: stretch;
|
||||
--choice-preview-art: var(--theme-preview-art);
|
||||
--choice-preview-radius: 8px;
|
||||
--choice-art-border: 0;
|
||||
--choice-dock-radius: 3px;
|
||||
--choice-dock-width: 100%;
|
||||
--choice-dock-background: var(--bg-3);
|
||||
--choice-radius: 12px;
|
||||
--choice-name-size: var(--manage-theme-name-size);
|
||||
--choice-name-line: var(--manage-theme-line);
|
||||
@@ -96,6 +103,12 @@
|
||||
--choice-selected: color-mix(in srgb, var(--gold) 60%, transparent);
|
||||
--choice-shadow: 0 0 0 3px color-mix(in srgb, var(--gold) 14%, transparent);
|
||||
}
|
||||
.tiles .preview {
|
||||
--choice-art-shadow: 0 0 0 1px var(--line-2);
|
||||
--choice-dock-border: 1px solid var(--line-2);
|
||||
--choice-dock-background: var(--bg-3);
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.tile-check {
|
||||
display: none;
|
||||
}
|
||||
@@ -121,7 +134,7 @@
|
||||
}
|
||||
.choice:hover {
|
||||
border-color: var(--line-3);
|
||||
background: var(--bg-3);
|
||||
background: var(--choice-hover-background, var(--bg-3));
|
||||
}
|
||||
.choice.selected {
|
||||
border-color: var(--choice-selected, var(--gold));
|
||||
@@ -139,7 +152,8 @@
|
||||
box-sizing: var(--choice-box-sizing, content-box);
|
||||
grid-column: 1 / -1;
|
||||
height: 64px;
|
||||
border-radius: var(--r-sm);
|
||||
border-radius: var(--choice-preview-radius, var(--r-sm));
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
display: grid;
|
||||
grid-template-columns: 12px 22px 1fr;
|
||||
@@ -179,6 +193,7 @@
|
||||
background: var(--sc-image);
|
||||
}
|
||||
.stage {
|
||||
position: relative;
|
||||
padding: 5px 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -188,13 +203,16 @@
|
||||
flex: 1;
|
||||
border-radius: 3px;
|
||||
background: var(--choice-preview-art, var(--bg-3));
|
||||
border: 1px solid var(--line-2);
|
||||
border: var(--choice-art-border, 1px solid var(--line-2));
|
||||
box-shadow: var(--choice-art-shadow, none);
|
||||
}
|
||||
.stage b {
|
||||
box-sizing: var(--choice-box-sizing, content-box);
|
||||
border: var(--choice-dock-border, 0);
|
||||
height: 9px;
|
||||
width: var(--choice-dock-width, 18px);
|
||||
align-self: end;
|
||||
border-radius: 2px;
|
||||
border-radius: var(--choice-dock-radius, 2px);
|
||||
background: var(--choice-dock-background, var(--grad-gold));
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
@@ -205,6 +223,16 @@
|
||||
border-radius: 2px;
|
||||
background: var(--grad-gold);
|
||||
}
|
||||
.preview-text {
|
||||
position: absolute;
|
||||
left: 40px;
|
||||
top: 6px;
|
||||
width: 20px;
|
||||
height: 3px;
|
||||
border-radius: 2px;
|
||||
background: var(--tx-1);
|
||||
opacity: 0.85;
|
||||
}
|
||||
.copy {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
anchorId?: string;
|
||||
onFile: (file: File) => void;
|
||||
onFromResults?: () => void;
|
||||
onFromScene?: () => void;
|
||||
onClear: () => void;
|
||||
}
|
||||
|
||||
@@ -48,6 +49,7 @@
|
||||
anchorId,
|
||||
onFile,
|
||||
onFromResults,
|
||||
onFromScene,
|
||||
onClear,
|
||||
}: Props = $props();
|
||||
|
||||
@@ -108,6 +110,7 @@
|
||||
<span>{label}</span>
|
||||
{#if required}<span class="req" aria-hidden="true">*</span>{/if}
|
||||
{#if hint}<span>{hint}</span>{/if}
|
||||
{#if onFromScene}<button type="button" class="a-btn ghost xs" onclick={onFromScene}>从三维搭景截取</button>{/if}
|
||||
{#if allowFromResults && onFromResults}
|
||||
<button type="button" class="a-btn ghost xs" onclick={onFromResults}>
|
||||
{t('studio.slotFromResultsShort')}
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
onRemove: (index: number) => void;
|
||||
onDismissReject: (index: number) => void;
|
||||
onFromResults?: () => void;
|
||||
onFromScene?: () => void;
|
||||
}
|
||||
|
||||
let {
|
||||
@@ -64,6 +65,7 @@
|
||||
onRemove,
|
||||
onDismissReject,
|
||||
onFromResults,
|
||||
onFromScene,
|
||||
}: Props = $props();
|
||||
|
||||
let addInput = $state<HTMLInputElement | null>(null);
|
||||
@@ -133,6 +135,7 @@
|
||||
<span>{label}</span>
|
||||
<span class="req" aria-hidden="true">*</span>
|
||||
<span class="mono">{hintLabel}</span>
|
||||
{#if onFromScene}<button type="button" class="a-btn ghost xs" onclick={onFromScene}>从三维搭景截取</button>{/if}
|
||||
{#if allowFromResults && onFromResults && remaining > 0}
|
||||
<button type="button" class="a-btn ghost xs" onclick={onFromResults}>
|
||||
{t('studio.slotFromResultsShort')}
|
||||
|
||||
@@ -4,6 +4,34 @@
|
||||
* Each entry is SVG inner content rendered by Icon.svelte via {@html}.
|
||||
*/
|
||||
export const icons = {
|
||||
"agent-cpu":
|
||||
'<rect x="6" y="6" width="12" height="12" rx="2"/><path d="M9 2v4M15 2v4M9 18v4M15 18v4M2 9h4M2 15h4M18 9h4M18 15h4"/>',
|
||||
"agent-send": '<path d="M4 12 20 4l-6 16-3-7z"/>',
|
||||
// Approved B3 sample geometry; retain existing tool icon contracts.
|
||||
"project-check": '<path d="M5 12.5 10 17l9-10"/>',
|
||||
"project-grid":
|
||||
'<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>',
|
||||
"project-book":
|
||||
'<path d="M4 4h6a3 3 0 0 1 3 3v13a2 2 0 0 0-2-2H4zM20 4h-5a3 3 0 0 0-3 3"/><path d="M20 4v14h-6"/>',
|
||||
"project-folder-in":
|
||||
'<path d="M3 6a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M12 10v6M9 13l3 3 3-3"/>',
|
||||
"project-film":
|
||||
'<rect x="2" y="4" width="20" height="16" rx="2"/><path d="M7 4v16M17 4v16M2 9h5M2 15h5M17 9h5M17 15h5"/>',
|
||||
"project-image":
|
||||
'<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><path d="m21 15-5-5L5 21"/>',
|
||||
"project-refresh": '<path d="M20 11a8 8 0 1 0-2.3 5.7M20 4v7h-7"/>',
|
||||
"project-cube":
|
||||
'<path d="M12 2 3 7v10l9 5 9-5V7z"/><path d="M3 7l9 5 9-5M12 12v10"/>',
|
||||
"project-search": '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
|
||||
"project-arrow": '<path d="M5 12h14M13 6l6 6-6 6"/>',
|
||||
"project-agent":
|
||||
'<path d="M12 3l1.8 4.6L18.5 9l-4.7 1.4L12 15l-1.8-4.6L5.5 9l4.7-1.4z"/><path d="M18.5 15l.9 2.1 2.1.9-2.1.9-.9 2.1-.9-2.1-2.1-.9 2.1-.9z"/>',
|
||||
"project-lib":
|
||||
'<rect x="3" y="5" width="18" height="15" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5-9 9"/>',
|
||||
"project-canvas":
|
||||
'<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/>',
|
||||
"project-queue":
|
||||
'<path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="16" r="3"/>',
|
||||
"search-manage": '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
|
||||
"upload-manage": '<path d="M12 16V4M6 9l6-6 6 6M4 20h16"/>',
|
||||
"film-manage":
|
||||
|
||||
@@ -74,6 +74,12 @@
|
||||
function jobActive(job: WorkbenchAsset['job']): boolean {
|
||||
return !!job && (job.status === 'pending' || job.status === 'running');
|
||||
}
|
||||
|
||||
export function saveDraft() {
|
||||
if (editing) save();
|
||||
else if (stage.content) onSave?.(stage.content);
|
||||
}
|
||||
export function hasUnsavedDraft() { return editing; }
|
||||
</script>
|
||||
|
||||
{#if editing}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<script lang="ts">
|
||||
import { assetUrl, type IncomingResult } from "$lib/api";
|
||||
import { resolve } from "$app/paths";
|
||||
let { results }: { results: IncomingResult[] } = $props();
|
||||
</script>
|
||||
|
||||
{#each results as result (result.source_key)}
|
||||
<details class="stage-note" open data-testid="incoming-result">
|
||||
<summary>{result.title} · 待整理成果</summary>
|
||||
{#if result.text}<p>{result.text}</p>{/if}
|
||||
{#each result.paths ?? [] as path (path)}<a
|
||||
class="a-btn sm"
|
||||
href={assetUrl(path) ?? "#"}
|
||||
target="_blank"
|
||||
rel="noopener external"
|
||||
>查看{result.kind === "video" ? "视频" : "图片"}产物</a
|
||||
>{/each}
|
||||
{#if result.session_id}<a
|
||||
class="a-btn sm ghost"
|
||||
href={resolve(`/agents?session=${result.session_id}`)}>回智能体编辑</a
|
||||
>{/if}
|
||||
</details>
|
||||
{/each}
|
||||
@@ -0,0 +1,730 @@
|
||||
<script lang="ts">
|
||||
import "$lib/components/workbench/project.css";
|
||||
import IncomingResults from "./IncomingResults.svelte";
|
||||
import Modal from "$lib/components/ui/Modal.svelte";
|
||||
import StudioHeader from "$lib/components/workbench/StudioHeader.svelte";
|
||||
import { resolve } from "$app/paths";
|
||||
import { goto } from "$app/navigation";
|
||||
import { untrack } from "svelte";
|
||||
import { page as pageStore } from "$app/state";
|
||||
import {
|
||||
createMutation,
|
||||
createQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/svelte-query";
|
||||
import {
|
||||
agentApi,
|
||||
assetUrl,
|
||||
jobsApi,
|
||||
settings,
|
||||
workbenchApi,
|
||||
type WorkbenchStageKey,
|
||||
} from "$lib/api";
|
||||
import { connectEvents } from "$lib/events";
|
||||
import { parseDbTs } from "$lib/dbtime";
|
||||
import { handleJobEvent, progressFor } from "$lib/jobProgress";
|
||||
import { storageSet } from "$lib/storage";
|
||||
import { toast } from "$lib/toast";
|
||||
import AppShell from "$lib/components/shell/AppShell.svelte";
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
import Skeleton from "$lib/components/ui/Skeleton.svelte";
|
||||
import StageStepper from "$lib/components/workbench/StageStepper.svelte";
|
||||
import ScriptStagePanel from "$lib/components/workbench/ScriptStagePanel.svelte";
|
||||
import StyleStagePanel from "$lib/components/workbench/StyleStagePanel.svelte";
|
||||
import StoryboardStagePanel from "$lib/components/workbench/StoryboardStagePanel.svelte";
|
||||
import AssetsStagePanel from "$lib/components/workbench/AssetsStagePanel.svelte";
|
||||
import ShotStagePanel from "$lib/components/workbench/ShotStagePanel.svelte";
|
||||
import { t } from "$lib/i18n.svelte";
|
||||
|
||||
/**
|
||||
* 五段创作工作台 (a2): stepper + stage artifact panel + agent/task side
|
||||
* column. Only confirmed snapshots flow downstream; drafts are clearly
|
||||
* flagged and never treated as final. In-flow generation rides the shared
|
||||
* queue (HEL-612) so tasks and results come back to this project.
|
||||
*/
|
||||
|
||||
const client = useQueryClient();
|
||||
let { projectId: suppliedId }: { projectId: number } = $props();
|
||||
const projectId = untrack(() => suppliedId);
|
||||
let editor = $state<{saveDraft:()=>void;hasUnsavedDraft:()=>boolean}|null>(null);
|
||||
let compareOpen = $state(false);
|
||||
|
||||
const STAGE_ORDER: WorkbenchStageKey[] = [
|
||||
"script",
|
||||
"style",
|
||||
"storyboard",
|
||||
"assets",
|
||||
"shot",
|
||||
];
|
||||
|
||||
const overviewQuery = createQuery({
|
||||
queryKey: ["workbench", projectId],
|
||||
queryFn: () => workbenchApi.overview(projectId),
|
||||
refetchInterval: 2500,
|
||||
});
|
||||
const jobsQuery = createQuery({
|
||||
queryKey: ["jobs", projectId],
|
||||
queryFn: () => jobsApi.list(projectId),
|
||||
refetchInterval: 5000,
|
||||
});
|
||||
const agentsQuery = createQuery({
|
||||
queryKey: ["agents-registry"],
|
||||
queryFn: agentApi.listNamedAgents,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const settingsQuery = createQuery({
|
||||
queryKey: ["settings"],
|
||||
queryFn: settings.get,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const overview = $derived($overviewQuery.data);
|
||||
const stages = $derived(overview?.stages ?? []);
|
||||
|
||||
// ?stage= selects the open stage; default = first not-confirmed one.
|
||||
const urlStage = $derived(
|
||||
pageStore.url.searchParams.get("stage") as WorkbenchStageKey | null,
|
||||
);
|
||||
const fallbackStage = $derived.by(() => {
|
||||
for (const key of STAGE_ORDER) {
|
||||
const s = stages.find((x) => x.stage_key === key);
|
||||
if (!s || s.status !== "confirmed") return key;
|
||||
}
|
||||
return "shot";
|
||||
});
|
||||
const stageKey = $derived(
|
||||
urlStage && STAGE_ORDER.includes(urlStage) ? urlStage : fallbackStage,
|
||||
);
|
||||
const currentStage = $derived(stages.find((s) => s.stage_key === stageKey));
|
||||
|
||||
function selectStage(key: string) {
|
||||
if (Number(pageStore.params.id) !== projectId) return;
|
||||
noteOpen = false;
|
||||
const url = new URL(pageStore.url);
|
||||
url.searchParams.set("stage", key);
|
||||
goto(resolve(`/workbench/${pageStore.params.id}${url.search}${url.hash}`), {
|
||||
keepFocus: true,
|
||||
noScroll: true,
|
||||
});
|
||||
}
|
||||
|
||||
function advanceAfterConfirm(key: WorkbenchStageKey) {
|
||||
const idx = STAGE_ORDER.indexOf(key);
|
||||
if (idx >= 0 && idx < STAGE_ORDER.length - 1) {
|
||||
selectStage(STAGE_ORDER[idx + 1]);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Live job feed (shared queue) ───────────────────────────────────
|
||||
$effect(() => {
|
||||
const off = connectEvents((ev) => {
|
||||
handleJobEvent(ev);
|
||||
if (ev.type.startsWith("job.")) {
|
||||
client.invalidateQueries({ queryKey: ["jobs", projectId] });
|
||||
if (ev.type === "job.completed" || ev.type === "job.failed") {
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["projects"] });
|
||||
}
|
||||
}
|
||||
});
|
||||
return off;
|
||||
});
|
||||
|
||||
// ── Stage mutations ────────────────────────────────────────────────
|
||||
const instructions = $state<Record<string,string>>({});
|
||||
let runWatchKey = $state<WorkbenchStageKey | null>(null);
|
||||
let chosenStyleId = $state<string | null>(null);
|
||||
|
||||
let noteOpen = $state(false),
|
||||
noteText = $state(""),
|
||||
noteBusy = $state(false);
|
||||
$effect(() => {
|
||||
void stageKey;
|
||||
noteOpen = false;
|
||||
noteText = '';
|
||||
compareOpen = false;
|
||||
});
|
||||
async function saveNote() {
|
||||
noteBusy = true;
|
||||
try {
|
||||
await workbenchApi.saveNote(projectId, stageKey, noteText);
|
||||
await client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
noteOpen = false;
|
||||
toast.success("助手建议已保存");
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : String(e));
|
||||
} finally {
|
||||
noteBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Keep the chosen style selector in sync with the stage payload.
|
||||
let lastStyleSync = $state("");
|
||||
$effect(() => {
|
||||
const styleStage = stages.find((s) => s.stage_key === "style");
|
||||
if (!styleStage) return;
|
||||
const directions = (
|
||||
styleStage.content as unknown as { directions?: { id: string }[] } | null
|
||||
)?.directions;
|
||||
const stamp = JSON.stringify(directions ?? []) + styleStage.chosen_style_id;
|
||||
if (stamp === lastStyleSync) return;
|
||||
lastStyleSync = stamp;
|
||||
const ids = (directions ?? []).map((d) => d.id);
|
||||
chosenStyleId =
|
||||
styleStage.chosen_style_id && ids.includes(styleStage.chosen_style_id)
|
||||
? styleStage.chosen_style_id
|
||||
: (ids[0] ?? null);
|
||||
});
|
||||
|
||||
// Toast once a watched run finishes (success or Chinese failure reason).
|
||||
$effect(() => {
|
||||
if (!runWatchKey) return;
|
||||
const stage = stages.find((s) => s.stage_key === runWatchKey);
|
||||
if (!stage || stage.status === "running") return;
|
||||
if (stage.status === "awaiting_confirm") {
|
||||
toast.success(t("workbench.runDone", { agent: agentName(runWatchKey) }));
|
||||
} else if (stage.last_run?.status === "failed" && stage.last_run.error) {
|
||||
toast.error(stage.last_run.error);
|
||||
}
|
||||
runWatchKey = null;
|
||||
});
|
||||
|
||||
function agentName(key: string): string {
|
||||
const agent = ($agentsQuery.data ?? []).find((a) => a.key === key);
|
||||
return agent ? agent.name : key;
|
||||
}
|
||||
|
||||
function busyFor(key: WorkbenchStageKey): boolean {
|
||||
const stage = stages.find((s) => s.stage_key === key);
|
||||
return stage?.status === "running";
|
||||
}
|
||||
|
||||
const runMutation = createMutation({
|
||||
mutationFn: (args: {key: WorkbenchStageKey; instruction: string}) =>
|
||||
workbenchApi.runStage(projectId, args.key, args.instruction || undefined),
|
||||
onSuccess: (_data, args) => {
|
||||
runWatchKey = args.key;
|
||||
if ((instructions[args.key] ?? '').trim() === args.instruction) instructions[args.key] = '';
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.runFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const saveMutation = createMutation({
|
||||
mutationFn: (args: {
|
||||
key: WorkbenchStageKey;
|
||||
content: Record<string, unknown>;
|
||||
}) =>
|
||||
workbenchApi.patchStage(projectId, args.key, { content: args.content }),
|
||||
onSuccess: () => {
|
||||
toast.success(t("workbench.draftSaved"));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["projects"] });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.saveFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const confirmMutation = createMutation({
|
||||
mutationFn: (key: WorkbenchStageKey) =>
|
||||
workbenchApi.confirmStage(
|
||||
projectId,
|
||||
key,
|
||||
key === "style" ? chosenStyleId : undefined,
|
||||
),
|
||||
onSuccess: (_data, key) => {
|
||||
toast.success(t("workbench.confirmed", { agent: agentName(key) }));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["projects"] });
|
||||
advanceAfterConfirm(key);
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.confirmFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const restoreMutation = createMutation({
|
||||
mutationFn: (key: WorkbenchStageKey) =>
|
||||
workbenchApi.restoreStage(projectId, key),
|
||||
onSuccess: () => {
|
||||
toast.success(t("workbench.restored"));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.restoreFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const importMutation = createMutation({
|
||||
mutationFn: (text: string) => workbenchApi.importScript(projectId, text),
|
||||
onSuccess: () => {
|
||||
toast.success(t("workbench.script.importDone"));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["projects"] });
|
||||
selectStage("style");
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.script.importFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const generateMutation = createMutation({
|
||||
mutationFn: (payload: {
|
||||
kind: "image" | "video";
|
||||
stage_key: WorkbenchStageKey;
|
||||
target_id?: string;
|
||||
prompt: string;
|
||||
negative_prompt?: string;
|
||||
duration_sec?: number;
|
||||
}) => workbenchApi.generate(projectId, payload),
|
||||
onSuccess: (data) => {
|
||||
toast.success(t("workbench.jobSubmitted"));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["jobs", projectId] });
|
||||
void data;
|
||||
},
|
||||
onError: (err) => {
|
||||
toast.error(
|
||||
err instanceof Error ? err.message : t("workbench.jobSubmitFailed"),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const retryMutation = createMutation({
|
||||
mutationFn: (jobId: number) => jobsApi.retry(jobId),
|
||||
onSuccess: () => {
|
||||
toast.success(t("workbench.jobRequeued"));
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["jobs", projectId] });
|
||||
},
|
||||
});
|
||||
|
||||
const cancelMutation = createMutation({
|
||||
mutationFn: (jobId: number) => jobsApi.cancel(jobId),
|
||||
onSuccess: () => {
|
||||
client.invalidateQueries({ queryKey: ["jobs", projectId] });
|
||||
client.invalidateQueries({ queryKey: ["workbench", projectId] });
|
||||
},
|
||||
});
|
||||
|
||||
function onGenerate(payload: {
|
||||
kind: "image" | "video";
|
||||
targetId: string;
|
||||
prompt: string;
|
||||
negativePrompt?: string;
|
||||
durationSec?: number;
|
||||
}) {
|
||||
$generateMutation.mutate({
|
||||
kind: payload.kind,
|
||||
stage_key: stageKey,
|
||||
target_id: payload.targetId,
|
||||
prompt: payload.prompt,
|
||||
negative_prompt: payload.negativePrompt,
|
||||
duration_sec: payload.durationSec,
|
||||
});
|
||||
}
|
||||
|
||||
// ── Sidebar: agent + tasks ─────────────────────────────────────────
|
||||
const currentAgent = $derived(
|
||||
($agentsQuery.data ?? []).find((a) => a.key === stageKey) ?? null,
|
||||
);
|
||||
const currentModelName = $derived.by(() => {
|
||||
const agent = currentAgent;
|
||||
const s = $settingsQuery.data;
|
||||
if (!agent || !s) return null;
|
||||
const pid = s.agent_llm_assignments?.[agent.llm_role];
|
||||
const profile = (s.llm_profiles ?? []).find((p) => p.id === pid);
|
||||
return profile?.name ?? null;
|
||||
});
|
||||
|
||||
function openAgentChat() {
|
||||
if (!currentAgent) return;
|
||||
storageSet("calliope.agents.activeKey", currentAgent.key);
|
||||
goto(resolve("/agents"));
|
||||
}
|
||||
|
||||
const projectJobs = $derived(
|
||||
($jobsQuery.data ?? []).filter(
|
||||
(j) => j.project_id === projectId &&
|
||||
(j.kind === "image" || j.kind === "video") &&
|
||||
(j.payload?.stage_key ?? (j.payload?.workbench as {stage?:string}|undefined)?.stage) === stageKey,
|
||||
),
|
||||
);
|
||||
|
||||
function jobTime(raw: string | null | undefined): string {
|
||||
const ts = parseDbTs(raw);
|
||||
if (!Number.isFinite(ts)) return "";
|
||||
return new Date(ts).toLocaleTimeString([], {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function jobProgressPct(id: number): number | null {
|
||||
const entry = progressFor(id);
|
||||
return entry?.progress ?? null;
|
||||
}
|
||||
|
||||
// ── Header state helpers ───────────────────────────────────────────
|
||||
|
||||
const STAGE_LABEL: Record<string, string> = {
|
||||
script: "故事",
|
||||
style: "风格",
|
||||
storyboard: "分镜",
|
||||
assets: "素材",
|
||||
shot: "镜头脚本",
|
||||
};
|
||||
const STATUS_LABEL: Record<string, string> = {
|
||||
todo: "workbench.state.todo",
|
||||
running: "workbench.state.running",
|
||||
awaiting_confirm: "workbench.state.draft",
|
||||
confirmed: "workbench.state.confirmed",
|
||||
};
|
||||
const STATUS_CLASS: Record<string, string> = {
|
||||
todo: "",
|
||||
running: "run",
|
||||
awaiting_confirm: "warn",
|
||||
confirmed: "ok",
|
||||
};
|
||||
|
||||
const stageStatus = $derived(currentStage?.status ?? "todo");
|
||||
const isLastStage = $derived(stageKey === "shot");
|
||||
|
||||
const panelProps = $derived.by(() => {
|
||||
const stage = currentStage;
|
||||
if (!stage) return null;
|
||||
return { stage };
|
||||
});
|
||||
|
||||
function handleRun(key: WorkbenchStageKey) {
|
||||
$runMutation.mutate({key,instruction:(instructions[key] ?? '').trim()});
|
||||
}
|
||||
</script>
|
||||
|
||||
<AppShell
|
||||
active="workbench"
|
||||
title={overview?.project.title ?? "项目"}
|
||||
workspace
|
||||
>
|
||||
{#snippet pageHeader({ openSearch })}<StudioHeader
|
||||
title={overview?.project.title ?? "项目"}
|
||||
project
|
||||
onSearch={openSearch}
|
||||
/>{/snippet}
|
||||
{#if !$overviewQuery.data && $overviewQuery.isLoading}<div class="project-load-pad">
|
||||
<Skeleton height="64px" /><Skeleton height="280px" />
|
||||
</div>
|
||||
{:else if !overview}<div class="project-load-pad">
|
||||
<p class="load-error">
|
||||
{t("workbench.loadFailed")}<button
|
||||
class="a-btn ghost"
|
||||
onclick={() => $overviewQuery.refetch()}
|
||||
>{t("workbench.retryLoad")}</button
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="project-workspace" data-testid="workbench-page">
|
||||
<StageStepper {stages} activeKey={stageKey} onSelect={selectStage} />
|
||||
<div class="project-body">
|
||||
<section class="project-main">
|
||||
{#if currentStage?.error || (currentStage?.last_run?.status === "failed" && currentStage?.last_run?.error)}<div
|
||||
class="error-banner"
|
||||
data-testid="stage-error"
|
||||
>
|
||||
{currentStage.last_run?.error ?? currentStage.error}
|
||||
</div>{/if}
|
||||
{#if stageStatus === "awaiting_confirm"}<div
|
||||
class="project-draftbar"
|
||||
data-testid="draft-banner"
|
||||
>
|
||||
<Icon name="project-agent" size={18} /><span
|
||||
><b>{currentAgent?.name ?? STAGE_LABEL[stageKey] + "助手"}</b
|
||||
>交回了本阶段草稿。确认后才会交给下一阶段使用。</span
|
||||
><span class="b3-grow"></span><button
|
||||
class="a-btn ghost sm"
|
||||
onclick={openAgentChat}>在智能体中打开</button
|
||||
><button
|
||||
class="a-btn secondary sm"
|
||||
disabled={!currentStage?.confirmed_content}
|
||||
onclick={() => (compareOpen = true)}>对比已确认版</button
|
||||
>
|
||||
</div>{/if}
|
||||
{#if stageStatus === "running"}<div
|
||||
class="project-draftbar"
|
||||
data-testid="running-banner"
|
||||
>
|
||||
<span class="breath"></span>{t("workbench.runningHint", {
|
||||
agent: agentName(stageKey),
|
||||
})}
|
||||
</div>{/if}
|
||||
<div class="project-content">
|
||||
{#if panelProps}
|
||||
<div class="stage-panel">
|
||||
<IncomingResults results={currentStage?.incoming_results??[]} />
|
||||
{#if currentStage?.assistant_note || noteOpen}<details
|
||||
class="stage-note"
|
||||
open
|
||||
>
|
||||
<summary>助手建议 · 待整理到阶段内容</summary>
|
||||
{#if noteOpen}<textarea
|
||||
class="a-input"
|
||||
aria-label="编辑阶段助手建议"
|
||||
bind:value={noteText}
|
||||
></textarea>
|
||||
<div class="note-actions">
|
||||
<button
|
||||
class="a-btn ghost sm"
|
||||
disabled={noteBusy}
|
||||
onclick={() => (noteOpen = false)}>取消</button
|
||||
><button
|
||||
class="a-btn secondary sm"
|
||||
disabled={noteBusy}
|
||||
onclick={saveNote}>保存建议</button
|
||||
>
|
||||
</div>
|
||||
{:else}<p>{currentStage?.assistant_note}</p>
|
||||
<button
|
||||
class="a-btn ghost sm"
|
||||
disabled={busyFor(stageKey)}
|
||||
onclick={() => {
|
||||
noteText = currentStage?.assistant_note ?? "";
|
||||
noteOpen = true;
|
||||
}}>编辑建议</button
|
||||
>{/if}
|
||||
</details>{/if}
|
||||
{#if stageKey === "script"}
|
||||
<ScriptStagePanel
|
||||
bind:this={editor}
|
||||
stage={panelProps.stage}
|
||||
projectIdea={overview.project.idea}
|
||||
busy={busyFor("script")}
|
||||
onSave={(content) =>
|
||||
$saveMutation.mutate({ key: "script", content })}
|
||||
onImport={(text) => $importMutation.mutate(text)}
|
||||
onRun={() => handleRun("script")}
|
||||
/>
|
||||
{:else if stageKey === "style"}
|
||||
<StyleStagePanel
|
||||
bind:this={editor}
|
||||
stage={panelProps.stage}
|
||||
bind:chosenStyleId
|
||||
busy={busyFor("style")}
|
||||
onSave={(content) =>
|
||||
$saveMutation.mutate({ key: "style", content })}
|
||||
onRun={() => handleRun("style")}
|
||||
/>
|
||||
{:else if stageKey === "storyboard"}
|
||||
<StoryboardStagePanel
|
||||
bind:this={editor}
|
||||
{projectId}
|
||||
stage={panelProps.stage}
|
||||
busy={busyFor("storyboard")}
|
||||
onSave={(content) =>
|
||||
$saveMutation.mutate({ key: "storyboard", content })}
|
||||
onRun={() => handleRun("storyboard")}
|
||||
/>
|
||||
{:else if stageKey === "assets"}
|
||||
<AssetsStagePanel
|
||||
bind:this={editor}
|
||||
stage={panelProps.stage}
|
||||
{projectId}
|
||||
busy={busyFor("assets")}
|
||||
onSave={(content) =>
|
||||
$saveMutation.mutate({ key: "assets", content })}
|
||||
onRun={() => handleRun("assets")}
|
||||
{onGenerate}
|
||||
onRetryJob={(jobId) => $retryMutation.mutate(jobId)}
|
||||
/>
|
||||
{:else}
|
||||
<ShotStagePanel
|
||||
bind:this={editor}
|
||||
stage={panelProps.stage}
|
||||
{projectId}
|
||||
busy={busyFor("shot")}
|
||||
onSave={(content) =>
|
||||
$saveMutation.mutate({ key: "shot", content })}
|
||||
onRun={() => handleRun("shot")}
|
||||
{onGenerate}
|
||||
onRetryJob={(jobId) => $retryMutation.mutate(jobId)}
|
||||
/>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
<aside class="project-side">
|
||||
<section class="project-assistant">
|
||||
<h3>本阶段助手</h3>
|
||||
<div class="project-agent">
|
||||
<span class="agent-icon"><Icon name="project-grid" size={20} /></span>
|
||||
<div class="b3-grow">
|
||||
<b>{currentAgent?.name ?? STAGE_LABEL[stageKey] + "助手"}</b
|
||||
><small
|
||||
>{currentModelName ?? "未配置模型"} · {currentAgent?.skill_count ??
|
||||
0} 个技能</small
|
||||
>
|
||||
</div>
|
||||
<button
|
||||
class="a-btn ghost sm"
|
||||
disabled={!currentAgent}
|
||||
onclick={openAgentChat}>对话</button
|
||||
>
|
||||
</div>
|
||||
<div class="stage-input-wrap"><textarea
|
||||
class="stage-instruction"
|
||||
bind:value={instructions[stageKey]}
|
||||
placeholder="补充要求(可选):节奏更慢、第 3 镜改俯拍…"
|
||||
disabled={busyFor(stageKey)}
|
||||
data-testid="stage-instruction"
|
||||
></textarea></div>
|
||||
<div class="b3-row">
|
||||
<button
|
||||
class="a-btn secondary sm b3-grow"
|
||||
disabled={busyFor(stageKey) || $runMutation.isPending}
|
||||
onclick={() => handleRun(stageKey)}
|
||||
data-testid="stage-run-btn"
|
||||
><Icon name="project-refresh" size={14} />{stageStatus === "todo"
|
||||
? "生成本阶段"
|
||||
: "重新生成本阶段"}</button
|
||||
><button
|
||||
class="a-btn ghost sm"
|
||||
disabled={!currentStage?.confirmed_content ||
|
||||
busyFor(stageKey) ||
|
||||
$restoreMutation.isPending}
|
||||
onclick={() => $restoreMutation.mutate(stageKey)}
|
||||
data-testid="stage-restore-btn">恢复已确认版</button
|
||||
>
|
||||
</div>
|
||||
{#if stageKey === "shot"}<a
|
||||
class="a-btn secondary sm"
|
||||
href={resolve("/build-scene")}>三维搭景 · 截取参考图</a
|
||||
>{/if}
|
||||
</section>
|
||||
<section class="project-task-heading">
|
||||
<h3>阶段任务 <span class="a-tag">{projectJobs.length}</span></h3>
|
||||
<span class="b3-grow"></span><a
|
||||
class="a-btn ghost sm"
|
||||
href={resolve("/tasks")}>全部</a
|
||||
>
|
||||
</section>
|
||||
<div class="project-tasks">
|
||||
{#if projectJobs.length === 0}
|
||||
<p class="jobs-empty">{t("workbench.tasksEmpty")}</p>
|
||||
{:else}
|
||||
<ul class="jobs-list" data-testid="workbench-jobs">
|
||||
{#each projectJobs.slice(0, 8) as job (job.id)}
|
||||
{@const live = jobProgressPct(job.id)}
|
||||
<li class="job-row">
|
||||
<span class="job-kind kind-{job.kind}">
|
||||
<Icon
|
||||
name={job.kind === "image" ? "image" : "film"}
|
||||
size={12}
|
||||
/>
|
||||
</span>
|
||||
<span class="job-body">
|
||||
<span class="job-prompt"
|
||||
>{job.payload?.prompt ??
|
||||
job.payload?.source ??
|
||||
`#${job.id}`}</span
|
||||
>
|
||||
<span class="job-time mono"
|
||||
>{jobTime(job.created_at)}</span
|
||||
>
|
||||
</span>
|
||||
<span class="job-state st-{job.status}">
|
||||
{#if job.status === "running"}
|
||||
<span class="breath"></span>
|
||||
{#if live != null}{Math.round(live)}%{:else}{t(
|
||||
"workbench.jobRunning",
|
||||
)}{/if}
|
||||
{:else if job.status === "pending"}
|
||||
{t("workbench.jobQueued")}
|
||||
{:else if job.status === "done"}
|
||||
{t("workbench.jobDone")}
|
||||
{:else}
|
||||
{t("workbench.jobFailed")}
|
||||
{/if}
|
||||
</span>
|
||||
{#if job.status === "pending" || job.status === "running"}
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
title={t("workbench.cancelJob")}
|
||||
onclick={() => $cancelMutation.mutate(job.id)}
|
||||
>
|
||||
<Icon name="stop" size={12} />
|
||||
</button>
|
||||
{:else if job.status === "failed"}
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
title={t("workbench.retryJob")}
|
||||
onclick={() => $retryMutation.mutate(job.id)}
|
||||
>
|
||||
<Icon name="project-refresh" size={12} />
|
||||
</button>
|
||||
{:else if job.output_paths?.[0]}
|
||||
<a
|
||||
class="icon-btn"
|
||||
href={assetUrl(job.output_paths[0]) ?? "#"}
|
||||
target="_blank"
|
||||
rel="noopener external"
|
||||
title={t("workbench.openOutput")}
|
||||
>
|
||||
<Icon name="external-link" size={12} />
|
||||
</a>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
{/if}
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
<footer class="project-footer">
|
||||
<span class="a-tag {STATUS_CLASS[stageStatus]}"
|
||||
>{t(STATUS_LABEL[stageStatus])}</span
|
||||
><span class="project-save-state"
|
||||
>{currentStage?.draft_edited
|
||||
? "已编辑 · 草稿待确认"
|
||||
: "确认后才会交给下一阶段使用"}</span
|
||||
><span class="b3-grow"></span><button class="a-btn secondary" disabled={busyFor(stageKey) || !currentStage?.content || $saveMutation.isPending} onclick={() => editor?.saveDraft()} data-testid="stage-save-btn">保存草稿</button><button
|
||||
class="a-btn primary"
|
||||
disabled={stageStatus !== "awaiting_confirm" ||
|
||||
$confirmMutation.isPending || !!editor?.hasUnsavedDraft()}
|
||||
onclick={() => $confirmMutation.mutate(stageKey)}
|
||||
data-testid="stage-confirm-btn"
|
||||
><Icon name="project-check" size={14} />{isLastStage
|
||||
? "确认镜头脚本"
|
||||
: `确认${STAGE_LABEL[stageKey]},进入${STAGE_LABEL[STAGE_ORDER[STAGE_ORDER.indexOf(stageKey) + 1]]}阶段`}</button
|
||||
>
|
||||
</footer>
|
||||
</div>{/if}
|
||||
</AppShell>
|
||||
<Modal bind:open={compareOpen} title="对比已确认版"
|
||||
><div class="project-compare">
|
||||
<section>
|
||||
<h3>已确认版</h3>
|
||||
<pre>{JSON.stringify(currentStage?.confirmed_content, null, 2)}</pre>
|
||||
</section>
|
||||
<section>
|
||||
<h3>当前草稿</h3>
|
||||
<pre>{JSON.stringify(currentStage?.content, null, 2)}</pre>
|
||||
</section>
|
||||
</div></Modal
|
||||
>
|
||||
|
||||
@@ -46,6 +46,12 @@
|
||||
importOpen = false;
|
||||
importText = '';
|
||||
}
|
||||
|
||||
export function saveDraft() {
|
||||
if (editing) save();
|
||||
else if (stage.content) onSave?.(stage.content);
|
||||
}
|
||||
export function hasUnsavedDraft() { return editing; }
|
||||
</script>
|
||||
|
||||
{#if stage.status === 'todo' && !text}
|
||||
|
||||
@@ -67,6 +67,12 @@
|
||||
function jobActive(job: VideoShot['job']): boolean {
|
||||
return !!job && (job.status === 'pending' || job.status === 'running');
|
||||
}
|
||||
|
||||
export function saveDraft() {
|
||||
if (editing) save();
|
||||
else if (stage.content) onSave?.(stage.content);
|
||||
}
|
||||
export function hasUnsavedDraft() { return editing; }
|
||||
</script>
|
||||
|
||||
{#if editing}
|
||||
@@ -165,6 +171,7 @@
|
||||
<PromptBlock label={t('workbench.vshot.promptLabel')} text={shot.prompt} />
|
||||
<div class="vshot-foot">
|
||||
{#if projectId}
|
||||
<a class="a-btn ghost sm" href={resolve('/build-scene')}>三维搭景</a>
|
||||
<a
|
||||
class="a-btn ghost sm"
|
||||
href={resolve(deskHref({
|
||||
|
||||
@@ -1,343 +1,97 @@
|
||||
<script lang="ts">
|
||||
import type { WorkbenchStage } from '$lib/api';
|
||||
import { t } from '$lib/i18n.svelte';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import type { WorkbenchStage } from "$lib/api";
|
||||
import { t } from "$lib/i18n.svelte";
|
||||
|
||||
/**
|
||||
* Five-stage stepper (a2): one step per agent with the fusion status
|
||||
* colors — gray=待开始, cyan=进行中 (+breath), amber=待确认,
|
||||
* green=已确认, --info=用户改过草稿. A step unlocks when itself or any
|
||||
* earlier stage has content; later steps stay clickable only after the
|
||||
* previous one is confirmed.
|
||||
*/
|
||||
interface Props {
|
||||
stages: WorkbenchStage[];
|
||||
activeKey: string;
|
||||
onSelect: (key: string) => void;
|
||||
}
|
||||
/**
|
||||
* Five-stage stepper (a2): one step per agent with the fusion status
|
||||
* colors — gray=待开始, cyan=进行中 (+breath), amber=待确认,
|
||||
* green=已确认, --info=用户改过草稿. A step unlocks when itself or any
|
||||
* earlier stage has content; later steps stay clickable only after the
|
||||
* previous one is confirmed.
|
||||
*/
|
||||
interface Props {
|
||||
stages: WorkbenchStage[];
|
||||
activeKey: string;
|
||||
onSelect: (key: string) => void;
|
||||
}
|
||||
|
||||
let { stages, activeKey, onSelect }: Props = $props();
|
||||
let { stages, activeKey, onSelect }: Props = $props();
|
||||
|
||||
const ORDER = ['script', 'style', 'storyboard', 'assets', 'shot'];
|
||||
const ORDER = ["script", "style", "storyboard", "assets", "shot"];
|
||||
|
||||
function label(key: string): string {
|
||||
return t(`workbench.stage.${key}`);
|
||||
}
|
||||
function label(key: string): string {
|
||||
return (
|
||||
{
|
||||
script: "故事",
|
||||
style: "风格",
|
||||
storyboard: "分镜",
|
||||
assets: "素材",
|
||||
shot: "镜头脚本",
|
||||
} as Record<string, string>
|
||||
)[key];
|
||||
}
|
||||
|
||||
function stateOf(
|
||||
stage: WorkbenchStage,
|
||||
): 'todo' | 'running' | 'draft' | 'edited' | 'confirmed' {
|
||||
if (stage.status === 'running') return 'running';
|
||||
if (stage.status === 'confirmed' && !stage.draft_edited) return 'confirmed';
|
||||
if (stage.status === 'confirmed' && stage.draft_edited) return 'edited';
|
||||
if (stage.status === 'awaiting_confirm')
|
||||
return stage.draft_edited ? 'edited' : 'draft';
|
||||
return 'todo';
|
||||
}
|
||||
function stateOf(
|
||||
stage: WorkbenchStage,
|
||||
): "todo" | "running" | "draft" | "edited" | "confirmed" {
|
||||
if (stage.status === "running") return "running";
|
||||
if (stage.status === "confirmed" && !stage.draft_edited) return "confirmed";
|
||||
if (stage.status === "confirmed" && stage.draft_edited) return "edited";
|
||||
if (stage.status === "awaiting_confirm")
|
||||
return stage.draft_edited ? "edited" : "draft";
|
||||
return "todo";
|
||||
}
|
||||
|
||||
function stateLabel(stage: WorkbenchStage): string {
|
||||
const s = stateOf(stage);
|
||||
if (s === 'running') return t('workbench.state.running');
|
||||
if (s === 'confirmed') return `✓ ${t('workbench.state.confirmed')}`;
|
||||
if (s === 'edited') return t('workbench.state.edited');
|
||||
if (s === 'draft') return t('workbench.state.draft');
|
||||
return t('workbench.state.todo');
|
||||
}
|
||||
function stateLabel(stage: WorkbenchStage): string {
|
||||
const s = stateOf(stage);
|
||||
if (s === "running") return t("workbench.state.running");
|
||||
if (s === "confirmed") return `✓ ${t("workbench.state.confirmed")}`;
|
||||
if (s === "edited") return t("workbench.state.edited");
|
||||
if (s === "draft") return t("workbench.state.draft");
|
||||
return t("workbench.state.todo");
|
||||
}
|
||||
|
||||
function unlocked(stages: WorkbenchStage[], key: string): boolean {
|
||||
const idx = ORDER.indexOf(key);
|
||||
if (idx <= 0) return true;
|
||||
const prev = stages.find((s) => s.stage_key === ORDER[idx - 1]);
|
||||
return prev?.status === 'confirmed';
|
||||
}
|
||||
function unlocked(stages: WorkbenchStage[], key: string): boolean {
|
||||
const idx = ORDER.indexOf(key);
|
||||
if (idx <= 0) return true;
|
||||
const prev = stages.find((s) => s.stage_key === ORDER[idx - 1]);
|
||||
return prev?.status === "confirmed";
|
||||
}
|
||||
</script>
|
||||
|
||||
<ol class="stepper" data-testid="workbench-stepper">
|
||||
{#each ORDER as key, i (key)}
|
||||
{@const stage = stages.find((s) => s.stage_key === key)}
|
||||
{@const state = stage ? stateOf(stage) : 'todo'}
|
||||
{@const open = stage ? unlocked(stages, key) : i === 0}
|
||||
<li class="step">
|
||||
{#if i > 0}<span class="bar" class:bar-done={unlocked(stages, key)}
|
||||
></span>{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="step-btn"
|
||||
class:active={activeKey === key}
|
||||
class:locked={!open}
|
||||
data-stage={key}
|
||||
data-state={state}
|
||||
onclick={() => onSelect(key)}
|
||||
aria-current={activeKey === key ? 'step' : undefined}
|
||||
title={open
|
||||
? label(key)
|
||||
: t('workbench.lockedStep', { stage: label(ORDER[i - 1]) })}
|
||||
>
|
||||
<span class="avatar"
|
||||
>{state === 'confirmed' ? '✓' : String(i + 1).padStart(2, '0')}</span
|
||||
>
|
||||
<span class="step-copy">
|
||||
<span class="step-name">{label(key)}</span>
|
||||
<span class="step-state st-{state}">
|
||||
{#if state === 'running'}<span class="breath" aria-hidden="true"
|
||||
></span>{/if}
|
||||
{stage ? stateLabel(stage) : t('workbench.state.todo')}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
{#each ORDER as key, i (key)}
|
||||
{@const stage = stages.find((s) => s.stage_key === key)}
|
||||
{@const state = stage ? stateOf(stage) : "todo"}
|
||||
{@const open = stage ? unlocked(stages, key) : i === 0}
|
||||
<li class="step">
|
||||
{#if i > 0}<span class="bar" class:bar-done={unlocked(stages, key)}
|
||||
></span>{/if}
|
||||
<button
|
||||
type="button"
|
||||
class="step-btn"
|
||||
class:active={activeKey === key}
|
||||
class:locked={!open}
|
||||
data-stage={key}
|
||||
data-state={state}
|
||||
onclick={() => onSelect(key)}
|
||||
aria-current={activeKey === key ? "step" : undefined}
|
||||
title={open
|
||||
? label(key)
|
||||
: t("workbench.lockedStep", { stage: label(ORDER[i - 1]) })}
|
||||
>
|
||||
<span class="avatar">{#if state === "confirmed"}<Icon name="project-check" size={18}/>{:else}{String(i + 1)}{/if}</span
|
||||
>
|
||||
<span class="step-copy">
|
||||
<span class="step-name">{label(key)}</span>
|
||||
<span class="step-state st-{state}">
|
||||
{#if state === "running"}<span class="breath" aria-hidden="true"
|
||||
></span>{/if}
|
||||
{stage ? stateLabel(stage) : t("workbench.state.todo")}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
{/each}
|
||||
</ol>
|
||||
|
||||
<style>
|
||||
.stepper {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 12px 0 4px;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.step {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.bar {
|
||||
width: 26px;
|
||||
height: 2px;
|
||||
background: var(--surface-3);
|
||||
border-radius: 1px;
|
||||
}
|
||||
.bar-done {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.step-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 9px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
transition:
|
||||
background-color 150ms cubic-bezier(0.16, 1, 0.3, 1),
|
||||
border-color 150ms;
|
||||
}
|
||||
.step-btn:hover:not(.locked) {
|
||||
background: var(--surface-3);
|
||||
}
|
||||
.step-btn.active {
|
||||
background: var(--surface-2);
|
||||
border-color: var(--border-strong);
|
||||
/* §3.2 当前段:金色下划 2px 内阴影 + 段名金色。 */
|
||||
box-shadow: inset 0 -2px 0 var(--accent);
|
||||
}
|
||||
.step-btn.active .step-name {
|
||||
color: var(--accent);
|
||||
}
|
||||
.step-btn[data-state='confirmed']:not(.active) .step-name {
|
||||
color: var(--success);
|
||||
}
|
||||
.step-btn.locked {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.avatar {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--text);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.step-copy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 58px;
|
||||
}
|
||||
|
||||
.step-name {
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.step-state {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 10.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.st-todo {
|
||||
color: var(--text-3);
|
||||
}
|
||||
.st-running {
|
||||
color: var(--run);
|
||||
}
|
||||
.st-draft {
|
||||
color: var(--warn);
|
||||
}
|
||||
.st-edited {
|
||||
color: var(--warn);
|
||||
}
|
||||
.st-confirmed {
|
||||
color: var(--success);
|
||||
}
|
||||
|
||||
.step-btn.active[data-state='running'] .avatar,
|
||||
.step-btn[data-state='running'] .avatar {
|
||||
box-shadow: 0 0 10px var(--run-soft);
|
||||
}
|
||||
|
||||
.breath {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--run);
|
||||
animation: wb-breath 2s cubic-bezier(0.16, 1, 0.3, 1) infinite;
|
||||
}
|
||||
|
||||
@keyframes wb-breath {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.breath {
|
||||
animation: none;
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
.stepper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: 7px;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
.step {
|
||||
display: block;
|
||||
}
|
||||
.bar {
|
||||
display: none;
|
||||
}
|
||||
.step-btn {
|
||||
width: 100%;
|
||||
padding: 12px 10px;
|
||||
border: 0;
|
||||
gap: 10px;
|
||||
}
|
||||
.avatar {
|
||||
width: 27px;
|
||||
height: 27px;
|
||||
background: none !important;
|
||||
border: 1px solid var(--line-2);
|
||||
border-radius: 50%;
|
||||
font: 9px var(--mono);
|
||||
color: var(--text-3);
|
||||
font-weight: 400;
|
||||
}
|
||||
.step-btn.active {
|
||||
background: #e8eafe;
|
||||
box-shadow: none;
|
||||
}
|
||||
.step-btn.active .avatar {
|
||||
background: var(--accent) !important;
|
||||
border-color: var(--accent);
|
||||
color: white;
|
||||
}
|
||||
.step-name {
|
||||
font-size: 11px;
|
||||
font-weight: 550;
|
||||
}
|
||||
.step-state {
|
||||
font-size: 9px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.step-copy {
|
||||
min-width: 0;
|
||||
}
|
||||
.step-btn.locked {
|
||||
opacity: 0.7;
|
||||
cursor: pointer;
|
||||
}
|
||||
.step-btn[data-state='confirmed'] .avatar {
|
||||
border-color: var(--ok);
|
||||
color: var(--ok);
|
||||
}
|
||||
|
||||
.stepper {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: stretch;
|
||||
gap: 8px;
|
||||
padding: 0;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.step {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-width: 130px;
|
||||
}
|
||||
.bar {
|
||||
display: none;
|
||||
}
|
||||
.step-btn {
|
||||
width: 100%;
|
||||
border: 1px solid #ffffff10;
|
||||
border-radius: 10px;
|
||||
background: #12171c;
|
||||
padding: 12px;
|
||||
gap: 10px;
|
||||
}
|
||||
.step-btn.active {
|
||||
background: #00cae012;
|
||||
border-color: #00cae080;
|
||||
box-shadow: none;
|
||||
}
|
||||
.step-btn.active .avatar {
|
||||
background: #00cae012 !important;
|
||||
color: var(--accent);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
.step-btn.active .step-name {
|
||||
color: #86e8f1;
|
||||
}
|
||||
.step-state {
|
||||
margin-top: 3px;
|
||||
}
|
||||
.step-btn[data-state='confirmed'] .avatar {
|
||||
color: var(--ok);
|
||||
}
|
||||
.step-btn.locked {
|
||||
opacity: 0.65;
|
||||
}
|
||||
.step-btn:hover:not(.active) {
|
||||
background: #ffffff07;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,339 +1,349 @@
|
||||
<script lang="ts">
|
||||
import type { StoryboardShot, WorkbenchStage } from '$lib/api';
|
||||
import Icon from '$lib/components/ui/Icon.svelte';
|
||||
import { t } from '$lib/i18n.svelte';
|
||||
import { resolve } from "$app/paths";
|
||||
import { assetUrl } from "$lib/api";
|
||||
import { deskHref } from "$lib/components/generate/context";
|
||||
import type { StoryboardShot, WorkbenchStage } from "$lib/api";
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
import { t } from "$lib/i18n.svelte";
|
||||
|
||||
interface Props {
|
||||
stage: WorkbenchStage;
|
||||
onSave?: (content: Record<string, unknown>) => void;
|
||||
onRun?: (instruction?: string) => void;
|
||||
busy?: boolean;
|
||||
}
|
||||
interface Props {
|
||||
stage: WorkbenchStage;
|
||||
projectId?: number;
|
||||
onSave?: (content: Record<string, unknown>) => void;
|
||||
onRun?: (instruction?: string) => void;
|
||||
busy?: boolean;
|
||||
}
|
||||
|
||||
let { stage, onSave, onRun, busy = false }: Props = $props();
|
||||
let { stage, projectId, onSave, onRun, busy = false }: Props = $props();
|
||||
|
||||
let editing = $state(false);
|
||||
let draft = $state<StoryboardShot[]>([]);
|
||||
let editing = $state(false);
|
||||
let selectedShot = $state<string | null>(null);
|
||||
let draft = $state<StoryboardShot[]>([]);
|
||||
|
||||
const shots = $derived(
|
||||
Array.isArray((stage.content as { shots?: unknown } | null)?.shots)
|
||||
? ((stage.content as unknown as { shots: StoryboardShot[] }).shots ?? [])
|
||||
: [],
|
||||
);
|
||||
const totalDuration = $derived(shots.reduce((acc, s) => acc + (s.duration_sec || 0), 0));
|
||||
const shots = $derived(
|
||||
Array.isArray((stage.content as { shots?: unknown } | null)?.shots)
|
||||
? ((stage.content as unknown as { shots: StoryboardShot[] }).shots ?? [])
|
||||
: [],
|
||||
);
|
||||
const totalDuration = $derived(
|
||||
shots.reduce((acc, s) => acc + (s.duration_sec || 0), 0),
|
||||
);
|
||||
|
||||
function startEdit() {
|
||||
draft = shots.map((s) => ({ ...s }));
|
||||
editing = true;
|
||||
}
|
||||
function startEdit() {
|
||||
draft = shots.map((s) => ({ ...s }));
|
||||
editing = true;
|
||||
}
|
||||
|
||||
function save() {
|
||||
const clean = draft.filter((s) => s.description.trim());
|
||||
if (!clean.length) return;
|
||||
onSave?.({ shots: clean });
|
||||
editing = false;
|
||||
}
|
||||
function save() {
|
||||
const clean = draft.filter((s) => s.description.trim());
|
||||
if (!clean.length) return;
|
||||
onSave?.({ shots: clean });
|
||||
editing = false;
|
||||
}
|
||||
|
||||
function addShot() {
|
||||
draft = [
|
||||
...draft,
|
||||
{
|
||||
id: `shot-new-${draft.length + 1}-${Date.now() % 1000}`,
|
||||
scene: `${draft.length + 1}`,
|
||||
shot_size: '中景',
|
||||
camera: '固定',
|
||||
description: '',
|
||||
dialog: '',
|
||||
duration_sec: 3,
|
||||
},
|
||||
];
|
||||
}
|
||||
function addShot() {
|
||||
draft = [
|
||||
...draft,
|
||||
{
|
||||
id: `shot-new-${draft.length + 1}-${Date.now() % 1000}`,
|
||||
scene: `${draft.length + 1}`,
|
||||
shot_size: "中景",
|
||||
camera: "固定",
|
||||
description: "",
|
||||
dialog: "",
|
||||
duration_sec: 3,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function removeShot(id: string) {
|
||||
draft = draft.filter((s) => s.id !== id);
|
||||
}
|
||||
function removeShot(id: string) {
|
||||
draft = draft.filter((s) => s.id !== id);
|
||||
}
|
||||
|
||||
export function saveDraft() {
|
||||
if (editing) save();
|
||||
else if (stage.content) onSave?.(stage.content);
|
||||
}
|
||||
export function hasUnsavedDraft() { return editing; }
|
||||
</script>
|
||||
|
||||
{#if editing}
|
||||
<div class="editor">
|
||||
<div class="edit-list">
|
||||
{#each draft as shot, i (shot.id)}
|
||||
<div class="shot-edit">
|
||||
<div class="shot-edit-head">
|
||||
<span class="shot-index mono">{String(i + 1).padStart(2, '0')}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn danger"
|
||||
title={t('workbench.board.remove')}
|
||||
onclick={() => removeShot(shot.id)}
|
||||
>
|
||||
<Icon name="trash" size={13} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="shot-fields">
|
||||
<input class="a-input w-xs" bind:value={shot.scene} placeholder={t('workbench.board.scene')} />
|
||||
<input class="a-input w-xs" bind:value={shot.shot_size} placeholder={t('workbench.board.size')} />
|
||||
<input class="a-input w-xs" bind:value={shot.camera} placeholder={t('workbench.board.camera')} />
|
||||
<input
|
||||
class="a-input w-xs mono"
|
||||
type="number"
|
||||
min="0.5"
|
||||
step="0.5"
|
||||
bind:value={shot.duration_sec}
|
||||
placeholder={t('workbench.board.duration')}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
class="a-input"
|
||||
rows="2"
|
||||
bind:value={shot.description}
|
||||
placeholder={t('workbench.board.descPh')}
|
||||
></textarea>
|
||||
<input class="a-input" bind:value={shot.dialog} placeholder={t('workbench.board.dialogPh')} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="editor-foot">
|
||||
<button type="button" class="a-btn ghost" onclick={addShot}>
|
||||
<Icon name="plus" size={13} />
|
||||
{t('workbench.board.add')}
|
||||
</button>
|
||||
<div class="foot-btns">
|
||||
<button type="button" class="a-btn ghost" onclick={() => (editing = false)}>
|
||||
{t('workbench.cancelEdit')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn primary"
|
||||
disabled={!draft.some((s) => s.description.trim())}
|
||||
onclick={save}
|
||||
>
|
||||
{t('workbench.saveDraft')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="editor">
|
||||
<div class="edit-list">
|
||||
{#each draft as shot, i (shot.id)}
|
||||
<div class="shot-edit">
|
||||
<div class="shot-edit-head">
|
||||
<span class="shot-index mono">{String(i + 1).padStart(2, "0")}</span
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn danger"
|
||||
title={t("workbench.board.remove")}
|
||||
onclick={() => removeShot(shot.id)}
|
||||
>
|
||||
<Icon name="trash" size={13} />
|
||||
</button>
|
||||
</div>
|
||||
<div class="shot-fields">
|
||||
<input
|
||||
class="a-input w-xs"
|
||||
bind:value={shot.scene}
|
||||
placeholder={t("workbench.board.scene")}
|
||||
/>
|
||||
<input
|
||||
class="a-input w-xs"
|
||||
bind:value={shot.shot_size}
|
||||
placeholder={t("workbench.board.size")}
|
||||
/>
|
||||
<input
|
||||
class="a-input w-xs"
|
||||
bind:value={shot.camera}
|
||||
placeholder={t("workbench.board.camera")}
|
||||
/>
|
||||
<input
|
||||
class="a-input w-xs mono"
|
||||
type="number"
|
||||
min="0.5"
|
||||
step="0.5"
|
||||
bind:value={shot.duration_sec}
|
||||
placeholder={t("workbench.board.duration")}
|
||||
/>
|
||||
</div>
|
||||
<textarea
|
||||
class="a-input"
|
||||
rows="2"
|
||||
bind:value={shot.description}
|
||||
placeholder={t("workbench.board.descPh")}
|
||||
></textarea>
|
||||
<input
|
||||
class="a-input"
|
||||
bind:value={shot.dialog}
|
||||
placeholder={t("workbench.board.dialogPh")}
|
||||
/>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="editor-foot">
|
||||
<button type="button" class="a-btn ghost" onclick={addShot}>
|
||||
<Icon name="plus" size={13} />
|
||||
{t("workbench.board.add")}
|
||||
</button>
|
||||
<div class="foot-btns">
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn ghost"
|
||||
onclick={() => (editing = false)}
|
||||
>
|
||||
{t("workbench.cancelEdit")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn primary"
|
||||
disabled={!draft.some((s) => s.description.trim())}
|
||||
onclick={save}
|
||||
>
|
||||
{t("workbench.saveDraft")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{:else if shots.length === 0}
|
||||
<div class="todo-card">
|
||||
<p class="todo-title">{t('workbench.board.todoTitle')}</p>
|
||||
<p class="todo-body">{t('workbench.board.todoBody')}</p>
|
||||
<button type="button" class="a-btn primary" disabled={busy} onclick={() => onRun?.()}>
|
||||
<Icon name="sparkle" size={14} />
|
||||
{t('workbench.board.generate')}
|
||||
</button>
|
||||
</div>
|
||||
<div class="todo-card">
|
||||
<p class="todo-title">{t("workbench.board.todoTitle")}</p>
|
||||
<p class="todo-body">{t("workbench.board.todoBody")}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn primary"
|
||||
disabled={busy}
|
||||
onclick={() => onRun?.()}
|
||||
>
|
||||
<Icon name="sparkle" size={14} />
|
||||
{t("workbench.board.generate")}
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<div class="board-table" data-testid="storyboard-table">
|
||||
<div class="bt-head">
|
||||
<span class="col-no">#</span>
|
||||
<span class="col-scene">{t('workbench.board.scene')}</span>
|
||||
<span class="col-size">{t('workbench.board.size')}</span>
|
||||
<span class="col-camera">{t('workbench.board.camera')}</span>
|
||||
<span class="col-desc">{t('workbench.board.desc')}</span>
|
||||
<span class="col-dialog">{t('workbench.board.dialog')}</span>
|
||||
<span class="col-dur mono">{t('workbench.board.duration')}</span>
|
||||
</div>
|
||||
{#each shots as shot, i (shot.id)}
|
||||
<div class="bt-row">
|
||||
<span class="col-no mono">{String(i + 1).padStart(2, '0')}</span>
|
||||
<span class="col-scene">{shot.scene}</span>
|
||||
<span class="col-size"><span class="tag">{shot.shot_size}</span></span>
|
||||
<span class="col-camera">{shot.camera}</span>
|
||||
<span class="col-desc">{shot.description}</span>
|
||||
<span class="col-dialog">{shot.dialog || '—'}</span>
|
||||
<span class="col-dur mono">{shot.duration_sec}s</span>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="view-foot">
|
||||
<span class="hint mono">{t('workbench.board.summary', { n: shots.length, sec: totalDuration })}</span>
|
||||
<div class="foot-btns">
|
||||
{#if stage.status !== 'running'}
|
||||
<button type="button" class="a-btn ghost" disabled={busy} onclick={startEdit}>
|
||||
<Icon name="edit" size={13} />
|
||||
{t('workbench.editDraft')}
|
||||
</button>
|
||||
<button type="button" class="a-btn ghost" disabled={busy} onclick={() => onRun?.()}>
|
||||
<Icon name="retry" size={13} />
|
||||
{t('workbench.regenerate')}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div class="storyboard-grid" data-testid="storyboard-table">
|
||||
{#each shots as shot, i (shot.id)}
|
||||
{@const media = (shot as StoryboardShot & { job?: { output?: string } })
|
||||
.job?.output}
|
||||
<article class="storyboard-card" class:selected={selectedShot === shot.id}>
|
||||
<button type="button" class="storyboard-image" aria-label={`选择镜头 ${i+1}`} aria-pressed={selectedShot === shot.id} onclick={() => selectedShot = shot.id}>
|
||||
{#if media}<img
|
||||
src={assetUrl(media) ?? ""}
|
||||
alt={shot.description}
|
||||
/>{:else}<span class="storyboard-missing">暂无草图</span>{/if}<span
|
||||
class="shot-time"
|
||||
>{String(i + 1).padStart(2, "0")} · {shot.duration_sec}s</span
|
||||
><span class="shot-media-state a-tag">{media ? "草图" : "待画"}</span>
|
||||
</button>
|
||||
<div class="storyboard-copy">
|
||||
<div class="b3-row">
|
||||
<b>{shot.shot_size}</b><span class="shot-scene"
|
||||
>场 {shot.scene}</span
|
||||
>
|
||||
</div>
|
||||
<p>{shot.description}</p>
|
||||
<div class="b3-row">
|
||||
<span class="shot-dialog" title={shot.dialog}
|
||||
>台词 {shot.dialog || "—"}</span
|
||||
><span class="b3-grow"></span>{#if projectId}<a
|
||||
class="a-btn ghost sm"
|
||||
href={resolve(
|
||||
deskHref({
|
||||
kind: "video",
|
||||
projectId,
|
||||
stage: "storyboard",
|
||||
label: `分镜 ${i + 1}`,
|
||||
prompt: shot.description,
|
||||
durationSec: shot.duration_sec,
|
||||
}),
|
||||
)}><Icon name="project-film" size={14} />去生视频</a
|
||||
>{/if}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="view-foot">
|
||||
<span class="hint mono"
|
||||
>{t("workbench.board.summary", {
|
||||
n: shots.length,
|
||||
sec: totalDuration,
|
||||
})}</span
|
||||
>
|
||||
<div class="foot-btns">
|
||||
{#if stage.status !== "running"}
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn ghost"
|
||||
disabled={busy}
|
||||
onclick={startEdit}
|
||||
>
|
||||
<Icon name="edit" size={13} />
|
||||
{t("workbench.editDraft")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="a-btn ghost"
|
||||
disabled={busy}
|
||||
onclick={() => onRun?.()}
|
||||
>
|
||||
<Icon name="retry" size={13} />
|
||||
{t("workbench.regenerate")}
|
||||
</button>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.todo-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 22px;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.todo-title {
|
||||
margin: 0;
|
||||
font-size: 14.5px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
.todo-body {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-2);
|
||||
}
|
||||
.todo-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
padding: 22px;
|
||||
border: 1px dashed var(--border-strong);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.todo-title {
|
||||
margin: 0;
|
||||
font-size: 14.5px;
|
||||
font-weight: 600;
|
||||
color: var(--text);
|
||||
}
|
||||
.todo-body {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.7;
|
||||
color: var(--text-2);
|
||||
}
|
||||
|
||||
.board-table {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
overflow-x: auto;
|
||||
}
|
||||
.bt-head,
|
||||
.bt-row {
|
||||
display: grid;
|
||||
grid-template-columns: 34px 64px 76px 76px minmax(220px, 1fr) minmax(140px, 0.8fr) 56px;
|
||||
gap: 10px;
|
||||
align-items: start;
|
||||
padding: 10px 14px;
|
||||
min-width: 680px;
|
||||
}
|
||||
.bt-head {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--text-3);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--surface-2);
|
||||
position: sticky;
|
||||
top: 0;
|
||||
}
|
||||
.bt-row {
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--text);
|
||||
}
|
||||
.bt-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.col-no {
|
||||
color: var(--text-3);
|
||||
}
|
||||
.col-scene,
|
||||
.col-camera {
|
||||
color: var(--text-2);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.col-desc {
|
||||
color: var(--text);
|
||||
}
|
||||
.col-dialog {
|
||||
color: var(--text-2);
|
||||
}
|
||||
.col-dur {
|
||||
text-align: right;
|
||||
color: var(--text-2);
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tag {
|
||||
display: inline-block;
|
||||
padding: 1px 8px;
|
||||
border-radius: 999px;
|
||||
background: var(--surface-3);
|
||||
color: var(--text-2);
|
||||
font-size: 10.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.edit-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.shot-edit {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.shot-edit-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.shot-index {
|
||||
color: var(--text-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
.shot-fields {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.a-input.mono {
|
||||
font-family: var(--font-a-mono);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
.a-input.w-xs {
|
||||
width: 110px;
|
||||
flex: 1;
|
||||
min-width: 96px;
|
||||
}
|
||||
|
||||
.editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.edit-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.shot-edit {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 14px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.shot-edit-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
.shot-index {
|
||||
color: var(--text-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
.shot-fields {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
.a-input.mono {
|
||||
font-family: var(--font-a-mono);
|
||||
font-size: 11.5px;
|
||||
}
|
||||
.a-input.w-xs {
|
||||
width: 110px;
|
||||
flex: 1;
|
||||
min-width: 96px;
|
||||
}
|
||||
.editor-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.editor-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.view-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
.hint {
|
||||
font-size: 11.5px;
|
||||
color: var(--text-3);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.foot-btns {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 7px;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-3);
|
||||
cursor: pointer;
|
||||
}
|
||||
.icon-btn:hover {
|
||||
background: var(--surface-3);
|
||||
color: var(--text);
|
||||
}
|
||||
.icon-btn.danger:hover {
|
||||
background: var(--error-dim);
|
||||
color: var(--error);
|
||||
}
|
||||
.view-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
.hint {
|
||||
font-size: 11.5px;
|
||||
color: var(--text-3);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.foot-btns {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.icon-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
border-radius: 7px;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-3);
|
||||
cursor: pointer;
|
||||
}
|
||||
.icon-btn:hover {
|
||||
background: var(--surface-3);
|
||||
color: var(--text);
|
||||
}
|
||||
.icon-btn.danger:hover {
|
||||
background: var(--error-dim);
|
||||
color: var(--error);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<script lang="ts">
|
||||
import { resolve } from "$app/paths";
|
||||
import Icon from "$lib/components/ui/Icon.svelte";
|
||||
let {
|
||||
title,
|
||||
project = false,
|
||||
onSearch,
|
||||
}: { title: string; project?: boolean; onSearch: () => void } = $props();
|
||||
</script>
|
||||
|
||||
<header class="studio-header">
|
||||
<div class="studio-crumb">
|
||||
{#if project}<a href={resolve("/")}>工作室</a><span>/</span>{/if}<b
|
||||
>{title}</b
|
||||
>
|
||||
</div>
|
||||
{#if !project}<span class="studio-greeting">晚上好,今天从哪里继续?</span
|
||||
>{/if}
|
||||
<span class="b3-grow"></span>
|
||||
{#if project}<a class="a-btn ghost sm" href={resolve("/canvas")}
|
||||
><Icon name="project-canvas" size={14} />灵感画布</a
|
||||
><a class="a-btn ghost sm" href={resolve("/library")}
|
||||
><Icon name="project-lib" size={14} />项目素材</a
|
||||
>{:else}<button
|
||||
class="studio-search"
|
||||
onclick={onSearch}
|
||||
aria-keyshortcuts="Control+K Meta+K"
|
||||
><Icon name="project-search" size={14} /><span>搜索项目、工作流、素材…</span><kbd
|
||||
>Ctrl K</kbd
|
||||
></button
|
||||
>{/if}
|
||||
</header>
|
||||
@@ -59,6 +59,12 @@
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
export function saveDraft() {
|
||||
if (editing) save();
|
||||
else if (stage.content) onSave?.(stage.content);
|
||||
}
|
||||
export function hasUnsavedDraft() { return editing; }
|
||||
</script>
|
||||
|
||||
{#if editing}
|
||||
|
||||
@@ -0,0 +1,838 @@
|
||||
.home,
|
||||
.home *,
|
||||
.studio-header,
|
||||
.studio-header *,
|
||||
.project-workspace,
|
||||
.project-workspace * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
/* HEL-731: approved sample 01/08/16, shared by studio and project panels.
|
||||
Theme values live in static/themes.css; no per-page theme overrides. */
|
||||
.b3-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.b3-grow {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.b3-empty {
|
||||
color: var(--tx-3);
|
||||
font-size: 12px;
|
||||
margin: 0;
|
||||
}
|
||||
.home {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) var(--project-side-width);
|
||||
gap: 20px;
|
||||
padding: 20px 24px 28px;
|
||||
max-width: 1680px;
|
||||
--scene: var(--gold);
|
||||
}
|
||||
.home .main-col {
|
||||
min-width: 0;
|
||||
}
|
||||
.studio-hero {
|
||||
position: relative;
|
||||
border-radius: var(--project-hero-radius);
|
||||
overflow: hidden;
|
||||
min-height: 250px;
|
||||
display: grid;
|
||||
grid-template-columns: 1.1fr 1fr;
|
||||
border: 1px solid var(--line-2);
|
||||
background: var(--studio-hero-bg);
|
||||
}
|
||||
.hero-art {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
opacity: 0.9;
|
||||
}
|
||||
.hero-shade {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
color-mix(in srgb, var(--bg-0) 96%, transparent) 0%,
|
||||
color-mix(in srgb, var(--bg-0) 85%, transparent) 38%,
|
||||
color-mix(in srgb, var(--bg-0) 15%, transparent) 75%,
|
||||
color-mix(in srgb, var(--bg-0) 30%, transparent)
|
||||
);
|
||||
}
|
||||
.hero-copy {
|
||||
position: relative;
|
||||
padding: 26px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
justify-content: center;
|
||||
}
|
||||
.studio-eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 22px;
|
||||
padding: 0 9px;
|
||||
border-radius: var(--project-eyebrow-radius);
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.5px;
|
||||
width: max-content;
|
||||
color: color-mix(in srgb, var(--scene) 75%, var(--hi));
|
||||
border: 1px solid color-mix(in srgb, var(--scene) 45%, transparent);
|
||||
background: color-mix(in srgb, var(--scene) 10%, transparent);
|
||||
}
|
||||
.studio-display {
|
||||
font: 700 var(--fs-display)/1.25 var(--project-display-font);
|
||||
letter-spacing: 0.5px;
|
||||
margin: 0;
|
||||
}
|
||||
.studio-display em {
|
||||
font-style: normal;
|
||||
background: var(--display-grad);
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
.hero-copy > .b3-row {
|
||||
margin-top: 6px;
|
||||
}
|
||||
.hero-description {
|
||||
color: var(--tx-2);
|
||||
max-width: 420px;
|
||||
margin: 0;
|
||||
}
|
||||
.studio-stages {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
max-width: 440px;
|
||||
}
|
||||
.studio-stages div {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.studio-stages i {
|
||||
height: 3px;
|
||||
border-radius: 3px;
|
||||
background: rgb(var(--ink) / 0.12);
|
||||
}
|
||||
.studio-stages .done i {
|
||||
background: var(--gold);
|
||||
}
|
||||
.studio-stages .cur i {
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
var(--gold) 50%,
|
||||
rgb(var(--ink) / 0.12) 50%
|
||||
);
|
||||
}
|
||||
.studio-stages .done,
|
||||
.studio-stages .cur {
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.studio-quick {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
.studio-quick > * {
|
||||
border-radius: var(--project-card-radius);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--bg-2);
|
||||
padding: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform var(--t-base) var(--ease-out),
|
||||
border-color var(--t-base);
|
||||
color: var(--tx-1);
|
||||
font: inherit;
|
||||
text-decoration: none;
|
||||
text-align: left;
|
||||
}
|
||||
.studio-quick > *:hover {
|
||||
transform: translateY(-2px);
|
||||
border-color: color-mix(in srgb, var(--scene) 45%, transparent);
|
||||
}
|
||||
.studio-quick .qi {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 10px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: color-mix(in srgb, var(--scene) 15%, transparent);
|
||||
color: var(--scene);
|
||||
}
|
||||
.studio-quick b {
|
||||
font-size: 14px;
|
||||
}
|
||||
.studio-quick p {
|
||||
font-size: 12px;
|
||||
color: var(--tx-3);
|
||||
margin: 0;
|
||||
}
|
||||
.home .projects-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: 24px 0 12px;
|
||||
}
|
||||
.home .projects-head h2 {
|
||||
margin: 0;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.studio-filters {
|
||||
display: flex;
|
||||
width: 200px;
|
||||
border: 1px solid var(--line-2);
|
||||
border-radius: 9px;
|
||||
padding: 3px;
|
||||
}
|
||||
.studio-filters button {
|
||||
flex: 1;
|
||||
background: none;
|
||||
color: var(--tx-3);
|
||||
border: 0;
|
||||
font: inherit;
|
||||
font-size: 12px;
|
||||
border-radius: 7px;
|
||||
padding: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.studio-filters .on {
|
||||
background: var(--bg-3);
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.home .cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(176px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.studio-side {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
.studio-side-card {
|
||||
border-radius: var(--project-card-radius);
|
||||
background: var(--bg-1);
|
||||
border: 1px solid var(--line);
|
||||
padding: 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.studio-side-card h3 {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.studio-side-card small {
|
||||
font-size: 11px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.waiting-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--sc-agent);
|
||||
box-shadow: 0 0 8px var(--sc-agent);
|
||||
}
|
||||
.home .confirm-item {
|
||||
border-radius: var(--project-confirm-radius);
|
||||
border: 1px solid color-mix(in srgb, var(--sc-agent) 35%, transparent);
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--sc-agent) 10%, transparent),
|
||||
transparent
|
||||
);
|
||||
padding: 10px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
.studio-outputs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 6px;
|
||||
}
|
||||
.studio-outputs a {
|
||||
aspect-ratio: 1;
|
||||
overflow: hidden;
|
||||
border-radius: 6px;
|
||||
background: var(--bg-2);
|
||||
}
|
||||
.studio-outputs img,
|
||||
.studio-outputs video {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.home .panel-empty {
|
||||
padding: 24px;
|
||||
color: var(--tx-3);
|
||||
border: 1px dashed var(--line-2);
|
||||
border-radius: var(--project-card-radius);
|
||||
text-align: center;
|
||||
}
|
||||
.home .job-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.home .job-row {
|
||||
min-width: 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
.home .job-top,
|
||||
.home .job-side {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
.home .job-name {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.home .job-meta {
|
||||
font-size: 11px;
|
||||
color: var(--tx-3);
|
||||
margin: 4px 0 0;
|
||||
}
|
||||
.home .job-status {
|
||||
font-size: 11px;
|
||||
}
|
||||
.home .failed-text {
|
||||
color: var(--err);
|
||||
}
|
||||
.home .running-text {
|
||||
color: var(--sc-video);
|
||||
}
|
||||
.home .done-text {
|
||||
color: var(--ok);
|
||||
}
|
||||
.home .retry-link {
|
||||
background: none;
|
||||
border: 0;
|
||||
color: var(--tx-2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.project-workspace {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
--scene: var(--sc-project);
|
||||
}
|
||||
.project-workspace .stepper {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 0;
|
||||
margin: 0;
|
||||
padding: 0 var(--s4);
|
||||
list-style: none;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--bg-1);
|
||||
flex: none;
|
||||
height: 58px;
|
||||
}
|
||||
.project-workspace .step {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
}
|
||||
.project-workspace .bar {
|
||||
display: none;
|
||||
}
|
||||
.project-workspace .step-btn {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 0 14px;
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
color: var(--tx-3);
|
||||
transition: color var(--t-base);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.project-workspace .step-btn:hover,
|
||||
.project-workspace .step-btn.active {
|
||||
color: var(--tx-1);
|
||||
}
|
||||
.project-workspace .avatar {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 8px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
font: 700 11px var(--mono);
|
||||
border: 1px solid var(--line-3);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.project-workspace .step-copy {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.project-workspace .step-name {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.project-workspace .step-state {
|
||||
font-size: 11px;
|
||||
}
|
||||
.project-workspace [data-state="confirmed"] .avatar {
|
||||
background: color-mix(in srgb, var(--gold) 16%, transparent);
|
||||
border-color: color-mix(in srgb, var(--gold) 50%, transparent);
|
||||
color: var(--gold);
|
||||
}
|
||||
.project-workspace [data-state="draft"] .avatar,
|
||||
.project-workspace [data-state="edited"] .avatar {
|
||||
border-color: var(--sc-agent);
|
||||
color: var(--sc-agent);
|
||||
box-shadow: var(--project-draft-shadow);
|
||||
}
|
||||
.project-workspace .step-btn.active::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 14px;
|
||||
right: 14px;
|
||||
bottom: -1px;
|
||||
height: 2px;
|
||||
background: var(--gold);
|
||||
box-shadow: var(--project-active-shadow);
|
||||
}
|
||||
.project-workspace .step + .step::before {
|
||||
content: "";
|
||||
align-self: center;
|
||||
width: 12px;
|
||||
margin: 0 -6px;
|
||||
height: 1px;
|
||||
background: var(--line-3);
|
||||
z-index: 1;
|
||||
}
|
||||
.project-body {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) var(--project-side-width);
|
||||
min-height: 0;
|
||||
}
|
||||
.project-main {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
.project-draftbar {
|
||||
margin: 14px 18px 0;
|
||||
border-radius: var(--project-draft-radius);
|
||||
padding: 10px 12px 10px 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
color-mix(in srgb, var(--sc-agent) 14%, transparent),
|
||||
color-mix(in srgb, var(--sc-agent) 4%, transparent)
|
||||
);
|
||||
border: 1px solid color-mix(in srgb, var(--sc-agent) 35%, transparent);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.project-draftbar > svg {
|
||||
color: var(--sc-agent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.project-content {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding: 14px 18px 18px;
|
||||
}
|
||||
.project-side {
|
||||
border-left: 1px solid var(--line);
|
||||
background: var(--project-side-bg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
.project-assistant {
|
||||
padding: 14px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
.project-assistant h3,
|
||||
.project-task-heading h3 {
|
||||
margin: 0;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.project-agent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 10px;
|
||||
border-radius: var(--project-draft-radius);
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--sc-agent) 12%, transparent),
|
||||
rgb(var(--ink) / 0.02)
|
||||
);
|
||||
border: 1px solid color-mix(in srgb, var(--sc-agent) 25%, transparent);
|
||||
}
|
||||
.project-agent b {
|
||||
font-size: 13px;
|
||||
}
|
||||
.project-agent small {
|
||||
display: block;
|
||||
color: var(--tx-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
.agent-icon {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: 10px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: color-mix(in srgb, var(--sc-agent) 20%, transparent);
|
||||
color: var(--sc-agent);
|
||||
}
|
||||
.stage-input-wrap {
|
||||
height: 70px;
|
||||
color: var(--tx-3);
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--line-2);
|
||||
background: var(--well);
|
||||
border-radius: var(--r-sm);
|
||||
}
|
||||
.stage-instruction {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
resize: none;
|
||||
background: none;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
font: 400 12.5px/1.55 var(--font);
|
||||
color: var(--tx-1);
|
||||
padding: 0;
|
||||
}
|
||||
.stage-instruction::placeholder {
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.project-task-heading {
|
||||
padding: 14px 14px 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.project-tasks {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
.project-tasks .jobs-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
.project-tasks .job-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 4px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.project-tasks .job-body {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-size: 12px;
|
||||
}
|
||||
.project-tasks .job-prompt {
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.project-tasks .job-time,
|
||||
.project-tasks .job-state {
|
||||
color: var(--tx-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
.project-tasks .jobs-empty {
|
||||
color: var(--tx-3);
|
||||
font-size: 12px;
|
||||
}
|
||||
.project-footer {
|
||||
flex: none;
|
||||
min-height: var(--project-footer-height);
|
||||
border-top: 1px solid var(--line);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 0 18px;
|
||||
background: color-mix(in srgb, var(--bg-1) 85%, transparent);
|
||||
}
|
||||
.project-save-state {
|
||||
font-size: 12px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.project-workspace .stage-note {
|
||||
padding: 14px;
|
||||
margin-bottom: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: var(--project-card-radius);
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.project-workspace .note-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.project-workspace .stage-note textarea {
|
||||
width: 100%;
|
||||
min-height: 100px;
|
||||
}
|
||||
.project-workspace .stage-note p {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.project-compare {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 16px;
|
||||
}
|
||||
.project-compare pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
font-size: 12px;
|
||||
max-height: 60vh;
|
||||
overflow: auto;
|
||||
}
|
||||
.project-workspace .error-banner {
|
||||
color: var(--err);
|
||||
padding: 14px 18px;
|
||||
}
|
||||
.project-load-pad {
|
||||
padding: 24px;
|
||||
}
|
||||
.project-workspace .icon-btn {
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--tx-2);
|
||||
cursor: pointer;
|
||||
}
|
||||
.storyboard-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
|
||||
gap: 12px;
|
||||
align-content: start;
|
||||
}
|
||||
.storyboard-card {
|
||||
border-radius: var(--project-shot-radius);
|
||||
background: var(--bg-2);
|
||||
border: 1px solid var(--line);
|
||||
overflow: hidden;
|
||||
transition:
|
||||
border-color var(--t-base),
|
||||
transform var(--t-base) var(--ease-out);
|
||||
}
|
||||
.storyboard-card:hover {
|
||||
border-color: var(--line-3);
|
||||
transform: translateY(-2px);
|
||||
}
|
||||
.storyboard-card.selected {
|
||||
border-color: color-mix(in srgb, var(--gold) 50%, transparent);
|
||||
}
|
||||
.storyboard-image {
|
||||
width: 100%;
|
||||
border: 0;
|
||||
padding: 0;
|
||||
font: inherit;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
aspect-ratio: 16/9;
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
background: var(--gen-bg);
|
||||
}
|
||||
.storyboard-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
.storyboard-missing {
|
||||
font-size: 12px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.shot-time {
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
top: 8px;
|
||||
font: 700 11px var(--mono);
|
||||
background: var(--media-scrim);
|
||||
color: var(--media-text);
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.shot-media-state {
|
||||
--tag-background: var(--project-media-tag-bg);
|
||||
--tag-color: var(--project-media-tag-color);
|
||||
--tag-border: var(--project-media-tag-border);
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
top: 8px;
|
||||
}
|
||||
.storyboard-copy {
|
||||
padding: 9px 11px 11px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.storyboard-copy p {
|
||||
color: var(--tx-2);
|
||||
margin: 0;
|
||||
display: -webkit-box;
|
||||
-webkit-line-clamp: 2;
|
||||
-webkit-box-orient: vertical;
|
||||
overflow: hidden;
|
||||
}
|
||||
.shot-scene,
|
||||
.shot-dialog {
|
||||
color: var(--tx-3);
|
||||
font-size: 11px;
|
||||
}
|
||||
.shot-dialog {
|
||||
max-width: 50%;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.studio-header {
|
||||
height: var(--head);
|
||||
flex: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--s3);
|
||||
padding: 0 var(--s4);
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--project-header-bg);
|
||||
backdrop-filter: blur(10px);
|
||||
position: relative;
|
||||
z-index: 3;
|
||||
}
|
||||
.studio-crumb {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
color: var(--tx-3);
|
||||
font-size: 12px;
|
||||
}
|
||||
.studio-crumb b {
|
||||
color: var(--tx-1);
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.studio-crumb a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
.studio-greeting {
|
||||
font-size: 12px;
|
||||
color: var(--tx-3);
|
||||
}
|
||||
.studio-search {
|
||||
width: 280px;
|
||||
height: 34px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--well);
|
||||
border: 1px solid var(--line-2);
|
||||
padding: 0 10px;
|
||||
color: var(--tx-3);
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.studio-search kbd {
|
||||
margin-left: auto;
|
||||
font: 500 10.5px/1 var(--mono);
|
||||
color: var(--tx-3);
|
||||
border: 1px solid var(--line-2);
|
||||
border-bottom-width: 2px;
|
||||
padding: 3px 5px;
|
||||
border-radius: 4px;
|
||||
background: var(--bg-2);
|
||||
}
|
||||
/* Configure the existing controls at the page boundary, keeping their source shared. */
|
||||
.home,
|
||||
.project-workspace,
|
||||
.studio-header {
|
||||
--icon-stroke: var(--project-icon-stroke);
|
||||
--button-height: 32px;
|
||||
--button-font-size: 12.5px;
|
||||
--button-weight: 500;
|
||||
--button-radius: var(--project-button-radius);
|
||||
--tag-height: 18px;
|
||||
--tag-padding: 6px;
|
||||
--tag-radius: 4px;
|
||||
--tag-font-size: 11px;
|
||||
--tag-border-width: 1px;
|
||||
--tag-border: var(--line);
|
||||
--tag-background: rgb(var(--ink) / 0.05);
|
||||
--tag-color: var(--tx-2);
|
||||
--tag-warn-color: var(--sc-agent);
|
||||
--tag-warn-background: rgb(var(--ink) / 0.05);
|
||||
--tag-warn-border: color-mix(in srgb, var(--sc-agent) 40%, transparent);
|
||||
--button-sm-font-size: 12px;
|
||||
--button-sm-height: 26px;
|
||||
--button-sm-padding: 9px;
|
||||
--button-sm-radius: var(--project-button-sm-radius);
|
||||
--button-primary-height: 32px;
|
||||
--button-primary-padding: 12px;
|
||||
--button-primary-radius: var(--project-button-radius);
|
||||
--button-primary-weight: 700;
|
||||
--button-primary-border-width: 0px;
|
||||
--button-primary-disabled-opacity: 1;
|
||||
--button-primary-disabled-filter: var(--project-button-disabled-filter);
|
||||
--button-primary-disabled-bg: var(--project-button-disabled-bg);
|
||||
--button-primary-disabled-color: var(--project-button-disabled-color);
|
||||
--button-secondary-bg: var(--bg-3);
|
||||
--button-secondary-border: var(--line-2);
|
||||
--button-secondary-hover-border: var(--line-3);
|
||||
--button-secondary-padding: 12px;
|
||||
--button-secondary-active-transform: translateY(1px);
|
||||
--button-secondary-radius: var(--project-button-radius);
|
||||
}
|
||||
@@ -7,24 +7,28 @@ export const THEMES = [
|
||||
id: "night",
|
||||
name: "夜片场",
|
||||
english: "Nocturne",
|
||||
tone: "深色 · 默认",
|
||||
description: "墨黑与钨丝金 · 沉浸式创作",
|
||||
},
|
||||
{
|
||||
id: "day",
|
||||
name: "日光棚",
|
||||
english: "Daylight",
|
||||
tone: "浅色",
|
||||
description: "暖白纸面 · 白天办公与长时间审稿",
|
||||
},
|
||||
{
|
||||
id: "grade",
|
||||
name: "调色间",
|
||||
english: "Grading",
|
||||
tone: "中性深灰",
|
||||
description: "中性深灰 · 判断作品色彩",
|
||||
},
|
||||
{
|
||||
id: "bluehour",
|
||||
name: "蓝调时刻",
|
||||
english: "Blue Hour",
|
||||
tone: "深蓝",
|
||||
description: "靛蓝与珊瑚 · 提案与灵感发散",
|
||||
},
|
||||
] as const;
|
||||
|
||||
+804
-1173
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -69,7 +69,7 @@ code,
|
||||
justify-content: center;
|
||||
gap: var(--sp-2);
|
||||
min-height: var(--button-height, 34px);
|
||||
padding: 0 var(--sp-6);
|
||||
padding: 0 var(--button-padding, var(--sp-6));
|
||||
border-radius: var(--button-radius, var(--r-md));
|
||||
border: 1px solid transparent;
|
||||
font-family: inherit;
|
||||
@@ -94,8 +94,12 @@ code,
|
||||
.a-btn.sm {
|
||||
min-height: var(--button-sm-height, 28px);
|
||||
padding: 0 var(--button-sm-padding, var(--sp-4));
|
||||
font-size: var(--fs-aux);
|
||||
font-size: var(--button-sm-font-size, var(--fs-aux));
|
||||
border-radius: var(--button-sm-radius, var(--r-sm));
|
||||
--button-secondary-size-radius: var(
|
||||
--button-sm-radius,
|
||||
var(--button-secondary-radius, 8px)
|
||||
);
|
||||
}
|
||||
.a-btn.xs {
|
||||
min-height: 24px;
|
||||
@@ -107,7 +111,7 @@ code,
|
||||
width: 100%;
|
||||
}
|
||||
.a-btn.primary {
|
||||
border-color: transparent;
|
||||
border: var(--button-primary-border-width, 1px) solid transparent;
|
||||
border-bottom-width: 0;
|
||||
min-height: var(--button-primary-height, 40px);
|
||||
padding: 0 var(--button-primary-padding, 18px);
|
||||
@@ -119,10 +123,23 @@ code,
|
||||
}
|
||||
.a-btn.secondary {
|
||||
background: var(--button-secondary-bg, var(--surface));
|
||||
border-radius: var(--button-secondary-radius, 8px);
|
||||
border-color: var(--line);
|
||||
border-radius: var(
|
||||
--button-secondary-size-radius,
|
||||
var(--button-secondary-radius, 8px)
|
||||
);
|
||||
border-color: var(--button-secondary-border, var(--line));
|
||||
--button-padding: var(--button-secondary-padding, var(--sp-6));
|
||||
--button-active-transform: var(
|
||||
--button-secondary-active-transform,
|
||||
scale(var(--press-scale))
|
||||
);
|
||||
color: var(--text);
|
||||
}
|
||||
.a-btn.scene {
|
||||
background: color-mix(in srgb, var(--scene) 16%, transparent);
|
||||
border-color: color-mix(in srgb, var(--scene) 45%, transparent);
|
||||
color: color-mix(in srgb, var(--scene) 70%, var(--hi));
|
||||
}
|
||||
.a-btn.ghost {
|
||||
background: transparent;
|
||||
color: var(--text-2);
|
||||
@@ -143,7 +160,7 @@ code,
|
||||
box-shadow: var(--btn-glow-hover);
|
||||
}
|
||||
.a-btn.secondary:hover:not(:disabled) {
|
||||
border-color: var(--line-2);
|
||||
border-color: var(--button-secondary-hover-border, var(--line-2));
|
||||
background: var(--bg-4);
|
||||
}
|
||||
.a-btn.ghost:hover:not(:disabled) {
|
||||
@@ -160,7 +177,7 @@ code,
|
||||
}
|
||||
}
|
||||
.a-btn:active:not(:disabled) {
|
||||
transform: scale(var(--press-scale));
|
||||
transform: var(--button-active-transform, scale(var(--press-scale)));
|
||||
}
|
||||
/* 禁用必须在旁边给出中文原因(§1.2),由调用方渲染。 */
|
||||
.a-btn:disabled,
|
||||
@@ -170,6 +187,15 @@ code,
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
/* Primary disabled state is configurable only where a page supplies the tokens. */
|
||||
.a-btn.primary:disabled,
|
||||
.a-btn.primary[aria-disabled="true"] {
|
||||
opacity: var(--button-primary-disabled-opacity, 0.45);
|
||||
filter: var(--button-primary-disabled-filter, none);
|
||||
background: var(--button-primary-disabled-bg, var(--accent-grad));
|
||||
color: var(--button-primary-disabled-color, var(--accent-ink));
|
||||
}
|
||||
|
||||
/* Top-bar status capsule (queue / connection / save state) — §二 顶栏胶囊. */
|
||||
.status-chip {
|
||||
display: inline-flex;
|
||||
@@ -247,12 +273,13 @@ button.status-chip:active {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--sp-1);
|
||||
height: 20px;
|
||||
padding: 0 var(--sp-2);
|
||||
border-radius: var(--r-sm);
|
||||
background: var(--bg-4);
|
||||
color: var(--text-2);
|
||||
font-size: var(--fs-aux);
|
||||
height: var(--tag-height, 20px);
|
||||
padding: 0 var(--tag-padding, var(--sp-2));
|
||||
border: var(--tag-border-width, 0px) solid var(--tag-border, transparent);
|
||||
border-radius: var(--tag-radius, var(--r-sm));
|
||||
background: var(--tag-background, var(--bg-4));
|
||||
color: var(--tag-color, var(--text-2));
|
||||
font-size: var(--tag-font-size, var(--fs-aux));
|
||||
white-space: nowrap;
|
||||
box-sizing: border-box;
|
||||
transition:
|
||||
@@ -276,8 +303,9 @@ button.status-chip:active {
|
||||
background: var(--err-soft);
|
||||
}
|
||||
.a-tag.warn {
|
||||
color: var(--warn);
|
||||
background: var(--warn-soft);
|
||||
color: var(--tag-warn-color, var(--warn));
|
||||
background: var(--tag-warn-background, var(--warn-soft));
|
||||
border-color: var(--tag-warn-border, transparent);
|
||||
}
|
||||
|
||||
/* Real-progress bar (§1.3):<div class="a-progress" style="--p:.42"><i></i></div>.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,54 @@
|
||||
/* HEL-726 approved themes. Loaded before the app for first-paint safety. */
|
||||
:root,
|
||||
[data-theme="night"] {
|
||||
--agent-shot-radius: 10px;
|
||||
--agent-media-label-layer: 1;
|
||||
--agent-bubble-radius: 12px;
|
||||
--agent-tool-radius: 10px;
|
||||
--agent-chip-radius: var(--r-pill);
|
||||
--agent-orb-shadow: 0 0 80px
|
||||
color-mix(in srgb, var(--sc-agent) 60%, transparent);
|
||||
--agent-ring-shadow: 0 0 12px var(--gold);
|
||||
--agent-hero-border: color-mix(in srgb, var(--sc-agent) 28%, transparent);
|
||||
--agent-input-bg: color-mix(in srgb, var(--bg-0) 60%, transparent);
|
||||
--agent-input-border: rgb(var(--ink) / 0.12);
|
||||
--agent-input-focus-border: color-mix(in srgb, var(--gold) 60%, transparent);
|
||||
--agent-seg-bg: var(--well);
|
||||
--agent-seg-selected-bg: var(--bg-3);
|
||||
--agent-seg-shadow: var(--sh-1);
|
||||
/* Match the sample's local fallback glyphs even while webfonts are loaded. */
|
||||
--agent-number-font: "Cascadia Mono", Consolas, monospace;
|
||||
--agent-hero-shrink: 0;
|
||||
--agent-input-select-max: none;
|
||||
--agent-task-running: var(--sc-agent);
|
||||
--agent-task-returned: var(--ok);
|
||||
--agent-task-confirm: var(--gold);
|
||||
--agent-task-idle: var(--tx-3);
|
||||
--agent-page-direction: column;
|
||||
--agent-header-font: 13px;
|
||||
--agent-header-spacing: 0px;
|
||||
--agent-header-bg: var(--glass);
|
||||
--agent-crumb-font: 12px;
|
||||
--agent-crumb-title-font: 14px;
|
||||
--agent-crumb-title-weight: 600;
|
||||
--agent-message-flex: 1;
|
||||
--agent-task-aurora-opacity: 0.6;
|
||||
--agent-duration-width: auto;
|
||||
--agent-duration-gap: 0px;
|
||||
--agent-footer-font: 11.5px;
|
||||
--agent-art-meta-font: 11px;
|
||||
--agent-duration-bg: transparent;
|
||||
--agent-duration-font: var(--mono);
|
||||
--agent-radius-22: 22px;
|
||||
--agent-radius-16: 16px;
|
||||
--agent-radius-14: 14px;
|
||||
--agent-radius-12: 12px;
|
||||
--agent-radius-10: 10px;
|
||||
--agent-radius-9: 9px;
|
||||
--agent-radius-8: 8px;
|
||||
--agent-radius-7: 7px;
|
||||
--agent-radius-6: 6px;
|
||||
|
||||
color-scheme: dark;
|
||||
/* surfaces: ink black with a faint blue cast, never pure #000 */
|
||||
--bg-0: #07080c;
|
||||
@@ -44,6 +92,30 @@
|
||||
--fs-body: 13px;
|
||||
--fs-small: 12px;
|
||||
--fs-micro: 11px;
|
||||
--studio-hero-bg: #0b0c11;
|
||||
--project-footer-height: 56px;
|
||||
--project-side-width: 340px;
|
||||
--project-media-tag-bg: rgba(7, 8, 12, 0.62);
|
||||
--project-media-tag-color: #ddd;
|
||||
--project-media-tag-border: rgba(255, 255, 255, 0.16);
|
||||
--project-icon-stroke: 1.7;
|
||||
--project-hero-radius: var(--r-xl);
|
||||
--project-button-radius: var(--r-sm);
|
||||
--project-button-sm-radius: 5px;
|
||||
--project-button-disabled-filter: grayscale(0.8) brightness(0.6);
|
||||
--project-button-disabled-bg: var(--grad-gold);
|
||||
--project-button-disabled-color: var(--tx-inv);
|
||||
--project-header-bg: var(--glass);
|
||||
--project-eyebrow-radius: var(--r-pill);
|
||||
--project-draft-shadow: 0 0 12px
|
||||
color-mix(in srgb, var(--sc-agent) 35%, transparent);
|
||||
--project-shot-radius: 12px;
|
||||
--project-active-shadow: 0 0 12px var(--gold);
|
||||
--project-side-bg: var(--bg-1);
|
||||
--project-display-font: var(--font);
|
||||
--project-card-radius: var(--r-lg);
|
||||
--project-confirm-radius: 10px;
|
||||
--project-draft-radius: 12px;
|
||||
--slot-size: 56px;
|
||||
--prompt-height: 60px;
|
||||
--desk-dock-radius: 14px;
|
||||
@@ -277,6 +349,11 @@
|
||||
}
|
||||
|
||||
[data-theme="day"] {
|
||||
--project-button-disabled-filter: none;
|
||||
--project-button-disabled-bg: #e3ddd2;
|
||||
--project-button-disabled-color: #8d877d;
|
||||
--project-active-shadow: none;
|
||||
--project-draft-shadow: none;
|
||||
--rail-active-shadow: none;
|
||||
color-scheme: light;
|
||||
--bg-0: #e9e4da;
|
||||
@@ -360,6 +437,14 @@
|
||||
}
|
||||
|
||||
[data-theme="grade"] {
|
||||
--project-card-radius: 4px;
|
||||
--project-hero-radius: 4px;
|
||||
--project-eyebrow-radius: 3px;
|
||||
--project-confirm-radius: 10px;
|
||||
--project-draft-radius: 4px;
|
||||
--project-shot-radius: 4px;
|
||||
--project-active-shadow: none;
|
||||
--project-draft-shadow: none;
|
||||
--rail-active-shadow: none;
|
||||
--rail-nav-radius: 4px;
|
||||
--rail-brand-radius: 4px;
|
||||
@@ -460,6 +545,11 @@
|
||||
}
|
||||
|
||||
[data-theme="bluehour"] {
|
||||
--project-shot-radius: 14px;
|
||||
--project-button-radius: 10px;
|
||||
--project-button-sm-radius: 8px;
|
||||
--project-header-bg: color-mix(in srgb, #0f1838 55%, transparent);
|
||||
--project-side-bg: color-mix(in srgb, var(--bg-1) 78%, transparent);
|
||||
--rail-nav-radius: 14px;
|
||||
--desk-head-bg: color-mix(in srgb, #0f1838 55%, transparent);
|
||||
color-scheme: dark;
|
||||
@@ -596,6 +686,7 @@
|
||||
--composer-bg: var(--desk-dock-bg);
|
||||
--composer-focus: var(--bg-2);
|
||||
--float-bg: var(--bg-2);
|
||||
--toast-bottom: 24px;
|
||||
--on-media: #fff;
|
||||
--on-media-line: #ffffff66;
|
||||
--sel-shadow: 0 0 0 1px var(--gold);
|
||||
@@ -750,3 +841,162 @@ html.theme-anim *::after {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Keep transient feedback clear of the project’s fixed primary actions. */
|
||||
:root:has(.project-workspace) {
|
||||
--toast-bottom: calc(var(--project-footer-height) + 24px);
|
||||
}
|
||||
|
||||
/* B4 grade geometry from the approved multi-theme sample. */
|
||||
:root[data-theme="grade"] {
|
||||
--agent-radius-22: 4px;
|
||||
--agent-radius-16: 4px;
|
||||
--agent-radius-14: 4px;
|
||||
--agent-radius-12: 4px;
|
||||
--agent-radius-10: 4px;
|
||||
--agent-radius-9: 4px;
|
||||
--agent-radius-8: 4px;
|
||||
--agent-radius-7: 4px;
|
||||
--agent-radius-6: 4px;
|
||||
}
|
||||
|
||||
:where(.b4, .b4-header) {
|
||||
--button-height: 32px;
|
||||
--button-padding: 12px;
|
||||
--button-radius: var(--project-button-radius);
|
||||
--button-font-size: 12.5px;
|
||||
--button-weight: 500;
|
||||
--button-sm-height: 26px;
|
||||
--button-sm-padding: 9px;
|
||||
--button-sm-font-size: 12px;
|
||||
--button-sm-radius: var(--project-button-sm-radius);
|
||||
--button-secondary-bg: var(--bg-3);
|
||||
--button-secondary-border: var(--line-2);
|
||||
--button-secondary-padding: 12px;
|
||||
--button-secondary-radius: var(--project-button-radius);
|
||||
--button-primary-height: 32px;
|
||||
--button-primary-padding: 12px;
|
||||
--button-primary-radius: var(--project-button-radius);
|
||||
--button-primary-weight: 700;
|
||||
--button-primary-border-width: 0px;
|
||||
--button-primary-disabled-opacity: 1;
|
||||
--button-primary-disabled-filter: var(--project-button-disabled-filter);
|
||||
--button-primary-disabled-bg: var(--project-button-disabled-bg);
|
||||
--button-primary-disabled-color: var(--project-button-disabled-color);
|
||||
}
|
||||
|
||||
.b4 {
|
||||
--chat-padding: 0px;
|
||||
--composer-top-padding: 0px;
|
||||
--composer-top-border: 0px;
|
||||
--composer-box-align: stretch;
|
||||
--composer-box-direction: column;
|
||||
--composer-box-bg: transparent;
|
||||
--composer-box-border: 0px;
|
||||
--composer-box-padding: 0px;
|
||||
--composer-editor-height: 44px;
|
||||
--composer-send-height: 26px;
|
||||
--composer-send-bg: var(--grad-gold);
|
||||
--composer-actions-gap: 8px;
|
||||
}
|
||||
|
||||
.b4 .composer {
|
||||
--button-primary-height: var(--button-sm-height);
|
||||
--button-primary-padding: var(--button-sm-padding);
|
||||
--button-primary-radius: var(--button-sm-radius);
|
||||
}
|
||||
|
||||
[data-theme="day"] {
|
||||
--agent-orb-shadow: 0 18px 50px rgba(109, 69, 208, 0.28);
|
||||
--agent-ring-shadow: none;
|
||||
--agent-hero-border: rgba(109, 69, 208, 0.22);
|
||||
--agent-input-bg: rgba(255, 255, 255, 0.75);
|
||||
--agent-input-border: rgba(38, 30, 18, 0.14);
|
||||
--agent-input-focus-border: rgba(38, 30, 18, 0.14);
|
||||
--agent-seg-bg: var(--bg-0);
|
||||
--agent-seg-selected-bg: #fff;
|
||||
--agent-seg-shadow:
|
||||
0 1px 2px rgba(60, 44, 20, 0.14), 0 0 0 1px rgba(38, 30, 18, 0.06);
|
||||
}
|
||||
[data-theme="grade"] {
|
||||
--agent-header-spacing: 0.2px;
|
||||
--agent-chip-radius: 3px;
|
||||
--agent-orb-shadow: 0 0 40px rgba(165, 152, 216, 0.25);
|
||||
--agent-ring-shadow: none;
|
||||
}
|
||||
|
||||
.b4 .shot {
|
||||
--button-sm-height: 22px;
|
||||
}
|
||||
|
||||
[data-theme="grade"] {
|
||||
--agent-shot-radius: 4px;
|
||||
--agent-bubble-radius: 4px;
|
||||
--agent-tool-radius: 4px;
|
||||
}
|
||||
[data-theme="bluehour"] {
|
||||
--agent-header-bg: color-mix(in srgb, #0f1838 55%, transparent);
|
||||
--agent-shot-radius: 14px;
|
||||
--agent-bubble-radius: 14px;
|
||||
--agent-tool-radius: 14px;
|
||||
}
|
||||
.b4 {
|
||||
--tool-card-radius: var(--agent-tool-radius);
|
||||
--tool-card-bg: var(--bg-1);
|
||||
--tool-head-padding: 8px 12px;
|
||||
--tool-name-font: 11.5px;
|
||||
--tool-font: 12px;
|
||||
--tool-head-font: 12px;
|
||||
--tool-head-color: var(--tx-2);
|
||||
--tool-border: var(--line);
|
||||
--tool-name-flex: 0 0 auto;
|
||||
--tool-name-color: var(--sc-image);
|
||||
--tool-ok-color: var(--ok);
|
||||
--tool-error-color: var(--err);
|
||||
}
|
||||
|
||||
:where(.b4, .b4-header) {
|
||||
--tag-height: 18px;
|
||||
--tag-padding: 6px;
|
||||
--tag-border-width: 1px;
|
||||
--tag-border: var(--line);
|
||||
--tag-radius: 4px;
|
||||
--tag-background: rgb(var(--ink) / 0.05);
|
||||
--tag-color: var(--tx-2);
|
||||
--tag-font-size: 11px;
|
||||
}
|
||||
.b4 .roster .acard {
|
||||
--tag-color: var(--c);
|
||||
--tag-border: color-mix(in srgb, var(--c) 35%, transparent);
|
||||
}
|
||||
:where(.b4, .b4-header) .a-tag.sc {
|
||||
--tag-color: var(--agent-status-color, var(--sc-agent));
|
||||
--tag-background: var(--agent-status-background, rgb(var(--ink) / 0.05));
|
||||
--tag-border: color-mix(in srgb, var(--sc-agent) 40%, transparent);
|
||||
}
|
||||
|
||||
.b4 .studio-msg.me {
|
||||
--agent-message-flex: initial;
|
||||
}
|
||||
|
||||
.b4-header {
|
||||
--agent-status-color: color-mix(in srgb, var(--sc-agent) 80%, var(--hi));
|
||||
--agent-status-background: color-mix(
|
||||
in srgb,
|
||||
var(--sc-agent) 10%,
|
||||
transparent
|
||||
);
|
||||
}
|
||||
|
||||
.b4 .tool-card.done {
|
||||
--tag-border: color-mix(in srgb, var(--ok) 30%, transparent);
|
||||
--tag-background: color-mix(in srgb, var(--ok) 7%, transparent);
|
||||
}
|
||||
.b4 .tool-card.error {
|
||||
--tag-border: color-mix(in srgb, var(--err) 30%, transparent);
|
||||
--tag-background: color-mix(in srgb, var(--err) 7%, transparent);
|
||||
}
|
||||
|
||||
.b4 .art-f .stage-select {
|
||||
--agent-select-weight: 400;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
HEL-731(B3)将工作室与项目五阶段接到已确认的夜片场四主题样本。基底固定为 `fix/hel-771-theme-tile-details @ a1c01f1e90b0b1ce76300291eae51785604180d4`,不合并既有请求、不部署、不迁移数据。
|
||||
|
||||
- 工作室首页改为真实项目继续创作、四个入口、项目筛选、待确认、队列与媒体墙。移除旧 hero 和重复覆盖规则。没有数据时显示空态,不写死样本项目、计数或图片。
|
||||
- `ProjectWorkbench.svelte` 复用五阶段 API 与已有编辑组件;顶部阶段条、右侧助手、镜头缩略图网格、固定保存和确认、确认快照对比。编辑中禁止确认旧内容。阶段要求分别保存;任务同时按项目和阶段过滤。路由按项目 ID 重建组件,异步完成不能把导航或输入带到另一项目。
|
||||
- 镜头脚本保留完整项目/阶段/镜头来源的创作台入口及原有显式结果回流,新增搭景入口。分镜仅携带真实分镜上下文和提示词预填,不伪造可回流的镜头脚本 ID。
|
||||
- 视频声明的非遮罩图片槽及参考图片列表可选择真实搭景截图,遵守列表数量上限;无图声明的文生图仍无图片/遮罩槽。复用 Modal、MediaSlot、RefImageGrid、shotApi,未新增依赖或生成 API。
|
||||
- 所有布局样式集中在 `project.css`,主题差异集中在 `themes.css`。样本图标加入已有 Icon 注册表,旧图标保持原契约。AppShell 页头 snippet 新增搜索回调;全局搜索快捷键继续由原组件负责。共享按钮、标签仅新增可配置 token,默认值保持原样;AProjectCard 同时影响项目列表,保留改名/删除。
|
||||
|
||||
验证:干净 `npm ci`;lint、Svelte check(0 errors / 0 warnings)、build、前端脚本测试;工作台生命周期和来源回流 pytest 18 passed。B3 浏览器 64 项、创作台 42 项、无图声明 7 项,运行异常均为 0。旧 B1 脚本将 B2 已移除的 `.wf-test-btn` 选择器更新为真实“试运行”按钮,等待数据加载,保留原行为断言,无检查豁免。
|
||||
|
||||
四主题 × 三尺寸 × 工作室/项目共 24 组原始样本与实际并排图,附 DOM 数值 CSV/JSON、原始样本、操作截图和 Playwright trace。三尺寸的页头、阶段条、右栏、底栏、按钮及输入几何按样本对齐。1280 档原始样本的描述文字较长,hero 和镜头卡会多换一行;证据保留原图与原始数值,另附仅替换这两处描述为隔离夹具文字的复测,24 组高度差均为 0。真实项目数、阶段状态、版本、产物和空态不替换为演示数据。
|
||||
|
||||
已验证真实 Three.js 截图 → 工作流声明槽 → 假 ComfyUI 视频生成 → 原镜头显式回流;另一项目不收到产物;项目视频默认暂停且可手动播放。五阶段生成/确认/恢复/导入通过隔离 pytest;保存、确认、恢复、对比、阶段切换、长内容滚动、主题与搜索通过浏览器操作。
|
||||
|
||||
限制:只使用隔离库和假生成服务,未调用真实 GPU 或收费服务。主题卡追加 144 组回归,DOM 差异 0;136 组原始截图逐像素一致,另外 8 组仍有 1–13 个像素、最大色阶差 2,原图全部保留,不据此宣布视觉通过。未部署,需总工独立审核;B4/B5 与整套样本仍未完成。pytest 有既存 Pydantic 字段 alias 警告,build 有依赖内未使用导入提示;lint/check 均无警告。回滚仅需切回上述精确基底,无数据库回滚步骤。
|
||||
|
||||
复测:安装仓库既有依赖后,设置本机 Playwright/Chromium 库路径,运行 `python3 e2e/run-hel731.py`;用 `HEL731_TESTS=e2e/hel731.cjs,e2e/hel729.cjs,e2e/hel742.cjs` 同时运行相关回归。样本通过 CLI 下载至上级 `attachments`,SHA-256 为 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`。随后运行 `node e2e/hel731-normalize.mjs`、`python3 scripts/report-hel731.py` 生成对照与数值证据。
|
||||
@@ -0,0 +1,56 @@
|
||||
HEL-732 / B4:智能体任务、可编辑成果与显式存入项目草稿
|
||||
|
||||
基底:`leefer/hel-731-studio-project` @ `8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb`。保留 B1–B3 及其返工。没有新增依赖、云接口、部署动作或线上数据操作。
|
||||
|
||||
## 行为与模块边界
|
||||
|
||||
- `/agents` 使用已确认 HTML 的首页/任务结构:真实任务列表、主创输入、五个阶段助手、最近成果、技能库;任务页复用 `AgentChat`、工具卡、`AgentPlanPanel`、上传与工作流/技能选择逻辑。没有模型或成果时显示真实空态。
|
||||
- 原页面完整移动为 `LegacyAgentWorkspace.svelte`,`/agents?legacy=1` 保留原会话、模型绑定、技能编辑与版本恢复;原 `?project=&task=` 深链继续走原画布交接。静态技能回归检查随编辑器移动到实际组件路径,检查规则未放宽。
|
||||
- runner 在成功结束一轮时,把最终真实回复捕获为独立成果草稿;错误、取消、提问暂停不会冒充完成成果。会话新增任务摘要和状态,聊天/工具日志仍是原来源。旧会话无需被伪造回填成新成果。
|
||||
- 成果支持文本编辑、分镜文字/时长编辑、版本冲突检查、项目/阶段归属、刷新恢复、真实上一保存版本对比。逐镜重画沿用现有 `workbench.generate`,传入唯一目标镜头;不改变生成协议或批量入队语义。
|
||||
- 创作台无来源的已完成结果打开通用项目/阶段选择器;有来源的结果继续走 B3 原回流。项目页增加待整理成果区;原固定确认底栏、确认快照、恢复、阶段隔离和视频手动播放保留。
|
||||
- 共享组件新增可选 `studio` 呈现及有默认值的 composer token;原画布等调用方维持默认呈现。`.a-btn.scene` 统一加入原按钮来源,页面不再建立第二套按钮样式。新页视觉值与主题差异在 `static/themes.css`;范围限定 `.b4`,不改 B3 按钮 token。
|
||||
|
||||
## API
|
||||
|
||||
- `GET /api/results/deliverables[?session_id=]`:持久化成果列表。
|
||||
- `PATCH /api/results/deliverables/{id}`:`revision, content, project_id, stage_key`;成功增加版本,旧版本先写入历史;陈旧版本返回 409。绑定项目的原会话不允许静默把成果移动到别的项目。
|
||||
- `GET /api/results/deliverables/{id}/versions`:真实保存历史。
|
||||
- `POST /api/results/store`:`project_id, stage_key`,且恰好选择 `deliverable_id + revision` 或 `job_id`。
|
||||
- 成果按已保存归属存入;独立生成的 system 项目产物允许选择目标,已有业务项目产物拒绝跨项目误存;文件必须存在于合法 assets 目录,job 必须为已完成图片/视频。运行中的阶段拒绝写入。
|
||||
- 幂等键为 `deliverable:{id}:{revision}` 或 `job:{id}`,加项目和阶段唯一约束;事务内写入阶段与幂等记录,并发重试不会重复附加。陈旧成果版本、无产物、无效阶段、误归属均拒绝。
|
||||
- 合法结构化内容经原 `NORMALIZERS` 进入工作草稿;纯文本剧本沿用原剧本文字校验。其他非结构化回复/媒体保存在 `incoming_results` 待整理区,供人整理进阶段内容;原阶段确认仍要求合法阶段结构,不把附件本身当成已经完成整阶段。
|
||||
- 写入只把目标阶段置 `awaiting_confirm`;绝不写 `confirmed_content_json`,不确认或推进下一阶段。确认/编辑保留附加成果,恢复恢复原已确认快照。已经存入后再恢复,不会因重复 POST 自动复活被恢复掉的草稿;用户可以保存新版本后再次显式带回。
|
||||
|
||||
## 增量迁移和精确回退
|
||||
|
||||
新增 `agent_sessions.task_summary/task_status`,新增 `agent_deliverables`、`agent_deliverable_versions`、`result_attachments`。迁移由既有 `migrate_db` 执行,旧列与旧状态语义保留。
|
||||
|
||||
`e2e/hel732-migration.py` 在独立目录导出精确基底代码并创建旧版库,使用 SQLite Backup API 备份,再运行新迁移两次,逐字段比较全部已有项目、会话、消息和阶段,校验 `integrity_check/foreign_key_check`,由真实旧版应用启动并读取会话和已确认阶段,最后将迁移前备份恢复到另一离线文件,比较旧表和旧结构。证据包含迁移前备份、迁移后导出、恢复文件及 SHA256;均为合成隔离数据,不是用户库。
|
||||
|
||||
后续部署由总工执行,步骤不得省略:
|
||||
|
||||
1. 暂停写入并停止应用/队列,记录旧/新代码 SHA,备份配置和媒体;用 SQLite Backup API 制作一致数据库备份,执行完整性校验并记录 SHA256。不要仅复制运行中的主 `.db` 而漏掉 WAL。
|
||||
2. 在备份副本验证新版本启动、两次迁移和关键读写,再升级代码;本卡没有在测试站执行该步骤。
|
||||
3. **只回代码**:旧版已实际读取迁移后库;新增列/表可留在库中。但旧 UI 看不到新成果/版本记录,旧版阶段编辑/重新确认会去掉它不理解的 `incoming_results`。所以不能承诺代码回退保留 B4 新交互语义,回代码后应冻结这些编辑并留存迁移后导出。
|
||||
4. **精确回退数据**:停止所有数据库持有者;先用 Backup API 导出升级后的库以保留新写入。将当前 `.db` 和可能存在的 `-wal/-shm` 改名归档,不把旧 WAL 混入恢复库。把迁移前备份复制为新的数据库文件,校验 SHA256/完整性,再启动精确旧代码 SHA。隔离演练证明恢复文件与迁移前备份 SHA256 相同、旧表逐行相同且无新增表/列。
|
||||
5. 精确数据回退会舍弃备份之后的业务写入;有新数据时必须先导出并由负责人决定是否允许,不能在线 DROP 新表/列或以“只加列”断言无风险。媒体文件也应按一致备份与引用核对,不自动删除。
|
||||
|
||||
## 自测与视觉证据
|
||||
|
||||
执行脚本:`e2e/run-hel732.py`(循环回环端口,前台收集结果并在 finally 关闭每个子进程)、`e2e/hel732.cjs`、`e2e/hel732-visual.cjs`、`e2e/hel732-migration.py`;复跑 B3 `e2e/hel731.cjs`。Python/Playwright 和本机共享库通过环境变量指向既有安装,不增加项目依赖。
|
||||
|
||||
图证保留原 HTML 原始状态图;另交仅替换真实数据内容的参考图与实际页面并排图,覆盖四主题与三档尺寸、首页/任务两页。参考数据归一化没有改样本 CSS、布局、字号或尺寸;演示任务、模型计数和占位图未写入产品。尺寸/样式实测表和操作记录、完整 Playwright trace 随任务附件交付。最终视觉一致性仍须总工独立重拍审核,整套样本尚未完成。
|
||||
|
||||
|
||||
## 2026-10-22 已批准的小窗口修正
|
||||
|
||||
主卡批准记录 `01a16270-5747-7dc5-8ff0-981f813364d5` 解除顶部裁切阻塞。统一 token `--agent-hero-shrink: 0` 由原 `.ahero` 规则消费;继续使用 `.agent-home` 原有滚动,不改字号、网格、圆角或其他页面。
|
||||
|
||||
真实选择器的额外 `max-width:90px` 把 `reference-test` 截短,改变 flex spacer 是否换行,导致 1280 下**首页开始任务** x=390、原样本 x=760。它不是成果栏按钮偏移。改为统一 token `--agent-input-select-max:none`,保留 field-sizing 与原 spacer,让真实文字按样本自然宽度参与排版;当前 1280 开始按钮 x=760、1366 x=398、1440 x=920,均与内容对齐的参考一致。成果回流的 `.art-f .primary` 在三尺寸分别 x=1047.171875/1133.171875/1207.171875,原位置未修改;实际项目与阶段 select 保留,并单独测量、聚焦,未伪造样本中不存在的 select。
|
||||
|
||||
`e2e/hel732-visual.cjs` 保留未改 CSS 的原样本图与数值,在独立浏览器参考页仅施加已批准的 flex-shrink:0,另存批准版截图;参考页只按真实测试状态替换内容/选中状态/真实缩略图;任务聊天用样本原有气泡/工具模板填入真实消息序列,不复制应用 DOM/CSS,不保留虚假的演示计划/运行态,原 HTML 文件哈希始终为 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`。三者清楚标注,未经修改的原演示状态也保留。24 组首页/任务对照、156 组实际选择器测量通过;这只覆盖指定选择器,不冒充全像素相同或独立审核。
|
||||
|
||||
新增 `e2e/hel732-layout.cjs` 通过真实应用与隔离假模型,在四主题×三窗口中验证:输入和焦点、正常点击开始任务并产生持久化成果、滚动到下面的最近成果/技能、无横向溢出、真实项目/阶段选择器和保存/回流按钮完整可见且可聚焦。截图测量脚本等待原文视图的异步渲染后再读取内容,避免旧 DOM 值造成误报。B4 功能链路与 B3 相关布局/确认/恢复回归重新通过,前端干净安装、lint/check(0错0警告)、test、build 通过。
|
||||
|
||||
本轮没有修改后端或迁移逻辑;既有 118 项后端测试、迁移和旧代码兼容证据继续保留,重新核对备份/导出/恢复文件 SHA256 与 integrity_check,未将其宣称为本轮独立复审。原迁移回退限制仍有效。四主题/全页面最终目检和独立审核交总管安排;本批完成施工待审核,整套样本未宣称完成,无部署、合并、线上数据/配置/密钥或真实生成操作。
|
||||
@@ -0,0 +1,34 @@
|
||||
# HEL-769 · 主题卡内部预览还原
|
||||
|
||||
基于完整 `fix/hel-767-sample-alignment@2004f527ccb689c84219282e3b706a95490c8b07`,隔离分支 `fix/hel-769-theme-preview`,新 PR 目标为 `fix/hel-767-sample-alignment`。不合并、部署或修改既有 PR。
|
||||
|
||||
## 实现
|
||||
|
||||
产品代码只修改 `calliope-web/src/lib/components/shell/ThemeChoices.svelte`:复用原组件与现有主题 token,恢复 tiles 内第四条列表线、20×3px 短文字线、固定 8px 预览圆角、主画面外描边与底条独立边框。底条显式继承 tiles 的 border-box,避免 padding 增加高度。外框、名称和说明的排版来源保持原有值。
|
||||
|
||||
主画面描边和底条颜色相关自定义属性在带 `data-theme` 的预览容器内解析,避免在外层 choices 提前解析为当前页面主题的颜色。预览内部使用对应卡片自己的 `--line-2`、`--bg-3` 和 `--tx-1`。没有新 CSS 补偿覆盖、依赖、检查豁免、业务演示数据或后端修改。compact 继续使用原有默认参数,新增图形只用于 tiles。
|
||||
|
||||
## 原件核实
|
||||
|
||||
原 HTML 由 Multica 附件下载,SHA256 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`,原件未经编辑。实际浏览器测量:主画面高 39px、底条高 9px、角标 14×5px、文字线 20×3px。旧报告角标样本 14×9px 的数字不成立,不照搬。所有尺寸、配色和圆角以本次原件逐主题运行测量为准。
|
||||
|
||||
## 复现与证据
|
||||
|
||||
运行 `npm ci`、`npm run lint`、`npm run check`、`npm test`、`npm run build`。构建完成后从仓库根运行 `python3 scripts/verify-hel769.py`,设置 `PLAYWRIGHT_MODULE` 指向已有 Playwright `index.mjs`,必要时设置浏览器运行库 `LD_LIBRARY_PATH`。原 HTML 放在仓库同级 `materials/夜片场-多主题交互样本.html`。
|
||||
|
||||
验证脚本沿用 HEL-767 的 API 契约隔离方式,临时 SQLite 和媒体夹具在 finally 中删除,动态 localhost 静态服务器和浏览器在 finally 中关闭。所有非本机 origin 拦截,未列出的 API 写操作失败,不访问用户库、真实 GPU 或付费接口。
|
||||
|
||||
完整矩阵保留五管理页 × 四主题 × 三窗口的整页 sample/actual/pair;设置页额外保留内部元素 DOM 原始值、内部近景 sample/actual/3 倍并排图,以及每张卡悬停的预览原图。`dimensions.md` 列出样本/实际/差值。交互沿用既有守护,覆盖主题选择、悬停、切换、键盘、记忆、减少动效、搜索、侧栏和管理页业务。逐文件 SHA256/大小清单与包索引随附件交付。
|
||||
|
||||
真实任务来源文字与样本演示文案不同,自动列宽随内容变化;无输出任务使用媒介图标。空连接、空素材和设置真实字段继续保持现有业务,不把样本虚构记录写入产品。
|
||||
|
||||
## 回滚与边界
|
||||
|
||||
使用 `git revert <HEL-769 head>` 正常推送;不 reset 或强推。没有服务器、用户配置或数据变更。未验证真实 GPU/付费生成、用户库、全站其他历史业务或后续 HEL-731~733;本次只施工和自测,须总管安排独立复核。
|
||||
|
||||
## 本次结果
|
||||
|
||||
- `npm ci`、lint、check(0 errors / 0 warnings)、四组既有前端守护、build 全部通过。build 保留既有 @xyflow 未使用导入和超过 500kB chunk 提示。
|
||||
- 完整矩阵 60 组,11,809 项断言通过;补充交互与布局守护 121 项通过,两个运行均无 pageerror 或意外 API 写请求。四卡 × 四主题 × 三窗口的内部坐标/尺寸最大偏差 0px,主画面、底条、角标、文字线及四列表线的颜色/边框/圆角逐项匹配。外框高度 130.421875px、标题 12.5px/19.375px、说明 11px/17.05px 保持原值。
|
||||
- 原始 PNG 像素核对也保留在 `pixel-results.json`:48 个普通态预览裁切中 40 个逐像素一致,另 8 个存在最大单通道 1/255 的栅格差异;DOM 几何和 computed 绘制值一致。悬停裁切包含圆角边缘与父卡背景的抗锯齿,原始差异如实保留,不将它们改图或声称所有 PNG 为零差异。
|
||||
- 额外检查四主题的设置卡选中、localStorage 保存及刷新恢复;12 组合下工作流三栏与任务整宽八列全部通过。完整/减少动效、520ms 主题显影和 1600ms 队列运行环沿用既有验证并通过。
|
||||
@@ -0,0 +1,24 @@
|
||||
# HEL-771 · 主题卡三处对齐
|
||||
|
||||
基于 `b2bcbc10df97f448cfa3f3f17bf3febad8c7a8ed`,分支 `fix/hel-771-theme-tile-details`,PR base `fix/hel-769-theme-preview`。不修改 PR #8、不合并、不部署。
|
||||
|
||||
产品仅修改 `src/lib/theme.ts` 和 `src/lib/components/shell/ThemeChoices.svelte`(均在 calliope-web 下):主题定义增加 tiles 专用 tone;复用 `.choice:hover` 的单一背景规则,以 tiles 变量保持 bg-2,compact 默认仍为 bg-3;夜卡默认徽标前在名称文本节点末尾补一个空格,避免格式化工具消除 HTML 空白,同时避免分离文本节点的逐段小数舍入。不改预览几何、字号、行高、卡高或 compact 文案和布局,不加依赖或检查豁免。
|
||||
|
||||
纠正 HEL-769 记录中的定性:悬停整卡差异来源是 `.choice:hover` 将背景由 bg-2 改为 bg-3 的计算样式差异,不是父卡背景抗锯齿。HEL-770 原始测量、定位 JSON 和图片保留在本卡附件的 inputs/review 中,并核对原清单全部 18 项大小及 SHA256。
|
||||
|
||||
复现:将未经编辑的原 HTML 放在仓库同级 `materials/夜片场-多主题交互样本.html`,哈希必须为 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`。
|
||||
|
||||
- `cd calliope-web`,运行 `npm ci`、`npm run lint`、`npm run check`、`npm test`、`npm run build`。
|
||||
- 仓库根运行 `node scripts/verify-hel771.mjs` 和 `python3 scripts/compare-hel771.py`。Playwright 通过已有环境提供(`PLAYWRIGHT_MODULE`),浏览器库通过 `LD_LIBRARY_PATH` 提供,不改项目依赖。
|
||||
- 对照 1440×900、1366×768、1280×720 × 四页面主题 × 四卡 × 普通/选中/悬停,共 144 对。选中态为在固定页面主题下仅切换卡片选中 class 的视觉夹具,真实点击、键盘和保存另由既有交互守护验证。
|
||||
- 复用 HEL-770 DOM 测量函数,增加默认徽标几何;记录每张卡、预览内部、文字、背景/边框、徽标的原始 JSON 和未经修改的 PNG。比较脚本按文件计算整卡逐像素差异,生成并排图与三倍近景。
|
||||
- `HEL769_SKIP_VISUAL=1 python3 scripts/verify-hel769.py` 验证现有 121 项交互和布局守护;完整运行同脚本验证原管理页矩阵及搜索框/侧栏/任务八列/工作流三栏,保留原始结果。
|
||||
|
||||
所有服务在 localhost 随机端口,API 为隔离假服务,外部来源被拦截;未触真实 GPU、付费生成、用户库/配置或 HEL-731~733。临时 SQLite/媒体由既有脚本临时目录清理,浏览器及服务在 finally 关闭。没有独立架构文档,施工前按 README 的前后端目录边界、既有主题/组件结构和 HEL-767/769 交付记录核对,未扩展模块范围。
|
||||
|
||||
## 最终自测结果
|
||||
|
||||
- npm ci(268 包)、lint、check(0 错误 0 警告)、四组既有前端守护与 build 通过;build 保留既有第三方未使用导入与大 chunk 提示。
|
||||
- 144 对卡片状态的文字、徽标位置、卡高、字号/行高、背景/边框与预览内部几何/样式全部零差异。主画面39px、底条9px、角标14×5px、短文字线20×3px及四条列表线保持。
|
||||
- 整卡原始像素:138/144 对完全一致;其余6对仅圆角边缘1~8像素有差异,最大单通道2/255,均为普通态。选中态48/48、悬停态48/48均整卡逐像素一致。原图和逐项统计完整保留,不以裁边、改图或容差过滤隐藏差异;像素统计供独立复核,未宣称所有截图零差异。
|
||||
- 最终版本交互守护121项通过;管理页60组/11,809项断言通过,零pageerror。证据范围仅本卡三项返工与既有定向守护,未宣称整套样本完成。
|
||||
@@ -0,0 +1,14 @@
|
||||
HEL-774 在 HEL-731 / PR #10 上按确认 HTML 样本定点返工,目标仍为 `fix/hel-771-theme-tile-details @ a1c01f1e90b0b1ce76300291eae51785604180d4`。
|
||||
|
||||
- `project.css` 两页作用域的次级按钮改回 `--bg-3`、`--line-2`、水平 12px;悬停边框为样本 `--line-3`,按下为样本 `translateY(1px)`。小按钮保留既有 9px,主按钮仍为 12px。
|
||||
- `app.css` 仅为现有共享按钮增加带原值回退的 token 参数。尺寸规则仍由原 sm/lg/xs 定义负责,没有追加第二套组件样式,也未改动主题配色。
|
||||
- 移除 `.confirm-item` 的 12.5px,按样本继承 13px。两页现有 `.a-tag` 均仅含文本;逐一实测将 gap 从 4px 改为 0px 后宽度不变,保留共享标签契约。
|
||||
- `.sec-h`、日期内容/格式、后端、确认语义、B4/B5 均未改动。
|
||||
|
||||
复测使用 `e2e/run-hel774.py` 和 `e2e/hel774.cjs`,复用既有依赖与隔离假服务;四主题三尺寸两页共 24 组原始截图、次级按钮状态数值/局部图、空态和保存/跳转操作 trace 随 HEL-774 交付。测试中“禁用”包含显式标记的临时 DOM 状态夹具;未将样本项目、媒体或数字写入产品。原始页面截图和同文按钮数值分开保留。截图为施工员自测材料,仍需总工独立重拍复审与总管接续目检。
|
||||
|
||||
pytest 口径:本次只收集 `tests/test_workbench.py`(10项)与 `tests/test_playground_workbench_flowback.py`(8项),合计18项。原 HEL-731 的18项是工作台生命周期+来源回流的合计;HEL-773 单文件10项仅含前者。后端没有变更,不重复运行已通过的整套昂贵行为测试。lint、Svelte check(0错误0警告)、build、前端脚本和本次针对性浏览器验证日志交任务附件;构建的既有依赖导入/包大小提示保持如实记录。
|
||||
|
||||
未部署、未合并、无数据迁移或线上数据操作,无新增依赖。清理由 runner 的 finally 停止其启动的精确子进程组并移除隔离库;保留原始证据与校验清单供复审。
|
||||
|
||||
补充总管在施工中新增的稳定态要求:等待全部有限动画结束、字体和图片就绪后,比较弹层与搜索弹层背景实测为不透明,Escape关闭均恢复触发器焦点,无需改弹层。另复现保存成功提示确实挡住固定保存/确认按钮(1440档toast底876、footer顶844,两按钮中心命中toast)。修复仅在统一`themes.css`中定义项目底栏56px与提示间距token,ToastHost消费原24px默认值;有项目工作区时提示距底为56+24px,其他页面仍24px。底栏复用同一高度token,没有叠加新组件样式。四主题三尺寸补测提示与底栏不重叠、保存/确认命中、实际点击、提示消失后的长滚动底栏;最终24组页面重新拍摄,稳定弹层/提示证据另列stability/。变更后重新lint/check/build,不以旧截图冒充新状态。
|
||||
@@ -0,0 +1,11 @@
|
||||
HEL-776 接续 PR #10,按原 HTML 样本修正 B3 工作室/项目按钮的两项偏差;不改变业务逻辑。
|
||||
|
||||
- 共享按钮的 sm 规则将已有小号圆角参数传给次级变体,次级规则消费该尺寸参数后再回退到原普通圆角。B3 小号最终为 night/day/grade 5px、bluehour 8px;非 B3 未配置小号参数,仍回退到原次级圆角 8px。没有新增一套按钮样式。
|
||||
- 共享按钮明确主按钮禁用状态的参数入口。B3 边界设置 opacity=1,主题源提供 grayscale(.8) brightness(.6),day 单独提供 filter:none、背景 #e3ddd2 和文字 #8d877d。阴影继续由原通用禁用规则清除。非 B3 的参数回退保留 opacity=.45、原背景/文字与无滤镜;次级按钮禁用态未改。
|
||||
- 原生 disabled、aria-disabled 样式入口、确认条件、异步请求、防重复提交与保存逻辑全部沿用。没有变更后端或依赖。
|
||||
|
||||
自测由 e2e/run-hel776.py 启动一次性真实 API/数据库及本地假服务,e2e/hel776.cjs 核对四主题×三窗口×工作室/项目页的普通、小号次级按钮 normal/hover/active 最终数值;用真实未保存编辑产生主按钮禁用态,真实保存恢复可用,逐值比较原样本的 opacity/filter/background/color/shadow 等属性,并验证禁用无请求、pending 只提交一次、确认成功。搜索/比较稳定打开与焦点恢复,以及提示条不遮固定操作另作定向保护。样本按钮状态夹具只存在于样本浏览器页面,产品保留真实数据。
|
||||
|
||||
B1/B2 的 /create、/workflows、/tasks、/settings、/models 四主题控件对照精确旧版 app.css;补充非 B3 普通/sm 主次按钮 enabled/native disabled/aria-disabled 状态夹具,并在对照时移除本轮新增主按钮状态规则,避免旧 CSS 无法覆盖较高优先级规则导致无效验证。
|
||||
|
||||
本轮实跑 lint、Svelte check(0 errors / 0 warnings)、build、现有前端脚本及上述定向浏览器验证。复用 HEL-775 的工作台10项+来源回流8项后端18 passed记录,纯样式增量没有重复执行;没有复跑无关完整页面截图矩阵。原始日志、并排局部图、JSON/CSV、trace、清理记录通过任务附件交付,施工员自测不能代替独立复审与总管图片目检。未部署、未合并、未新增依赖。
|
||||
@@ -0,0 +1,17 @@
|
||||
HEL-787:B4 Agent 局部视觉修正(待独立复验)
|
||||
|
||||
基底为原 PR #11 的 `feat/hel-732-agent-results@ab48895b99b463bd8151da204d5a87eb3a526963`,目标保持 `leefer/hel-731-studio-project@8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb`。
|
||||
|
||||
- `workspace.css`:只将镜头 img/video 绝对定位于既有 16:9 媒体盒,保留 contain、控件与手动播放。短文案首行从 104 恢复 66.375 高;盒从 86×86 恢复 86×48.375。长文案自然换行时行高可增加,媒体仍保持 16:9。
|
||||
- `AgentComposer.svelte`:Studio 入口复用已有 b4-chip 与 a-btn sm/primary/ghost;参考材料恢复“+ 参考材料”,左侧相邻;发送复用 agent-send 图标并前置。旧聊天保留原类名与表现。逻辑、上传、提及、键盘/中文输入、停止/引导及错误处理未改。
|
||||
- `static/themes.css`:沿用统一按钮/胶囊 token,composer 只消费 sm 尺寸;动作间距 8px。编号局部 token 采用样本在本系统实际使用的本地回退栈,不全局改字体、不加字体请求。正常网络加载 JetBrains Mono 时和字体不可用时,01–05 均实测为 DejaVuSansMono-Bold(原样本相同),800 请求解析为本地 Bold;原应用为仅加载 500 的 JetBrains Mono 合成粗体。字形宽 43.2→43.34375,与样本相等。
|
||||
|
||||
验证:干净 npm ci,npm run lint,npm run check(0 errors / 0 warnings),npm test,npm run build,git diff --check 均通过。构建器保留原有第三方未使用导入/大 chunk 提示,没有新增诊断。
|
||||
|
||||
四主题×1440×900/1366×768/1280×720:24 组首页/任务原样本同内容截图;12 组 Studio 按钮位置、宽高、圆角、字号字重、颜色背景/渐变一致(几何容差 <0.2px),真实 fill 进入双方空闲可发送态;missing=[]。原 HTML SHA256 仍为 0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4。参考保留原 CSS/结构,只映射真实内容、媒体及状态;JSON 回复使用 API 原文并按原文换行。首页保留先前已批准的 flex-shrink:0。应用媒体按本卡明确要求 contain,样本背景图 cover 保留原样,不借改样本掩盖差异。其他真实控件/工具卡与样本的既有结构差异仍交独立目检,不宣称整页像素完全相同。
|
||||
|
||||
CDP 实际渲染字体:5 编号×4 主题×正常网络/字体不可用,共 40 对,平台字体、字形宽高均一致;附局部图。媒体验证包含 100×100、100×180、240×100 图片和 240×400 视频,等待真实 load/metadata,盒均为 86×48.375,长文案行高由文字决定,无横向溢出,视频元数据后 paused=true、autoplay=false,手动播放/暂停成功。空镜状态保留。
|
||||
|
||||
真实 UI 操作:上传入口与上传、工作流/技能选择、方向键/Enter、Shift+Enter、中文组合 Enter 不误发、点击和键盘发送、运行中引导与停止、错误反馈、工具展开收起、主题切换保留编辑、保存刷新、上一版本及带回原项目待确认通过。运行态/错误测试使用隔离网络夹具;消息发送、上传和保存/带回走隔离应用。原有 e2e/hel732-layout.cjs 的 12 组输入、开始任务、滚动、选择器、焦点和无溢出测试通过。
|
||||
|
||||
证据脚本、完整日志、局部图与数据随 HEL-787 附件交付;不把本次局部验证冒充后端/API/迁移复审。contracts.json 原修复保留。无依赖、后端协议、数据库或原样本变更,无真实 GPU/收费生成、部署、合并或强推。测试站仍是 B3。隔离服务均由 foreground runner finally 回收,交付前再次核验端口与子进程。
|
||||
@@ -0,0 +1,17 @@
|
||||
HEL-791:B4 页头、工具卡与同状态证据补正
|
||||
|
||||
继续原分支 `feat/hel-732-agent-results` / PR #11,目标保持 `leefer/hel-731-studio-project@8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb`。施工起点 `afbf50447aff8eb0c14952079c6ee2fc57a7fb6f`。
|
||||
|
||||
- `static/themes.css` 为本批视觉值的统一来源;`workspace.css`、`AgentWorkspace.svelte` 消费页头、面包屑、标签、时长、选择器与任务状态点 token。页头回到本页容器内,恢复样本氛围层坐标;原来嵌在选择器内而未注册的关键帧移到顶层。真实项目/技能/阶段选择、管理入口、时长编辑与保存保留。首页标题保留样本14px/600,页头容器为13px。日光棚输入聚焦的边框按样本保留浅色主题描边,焦点光晕保持原值。
|
||||
- `AgentChat.svelte` 保留消息序列、原文、换行和不同助手身份。连续同一助手的消息/工具放在正文列,短回复铺满正文列;没有跨用户消息合并,也没有把 planner 与分镜设计合成同一作者。模板不再向原文插入空格。
|
||||
- `AgentToolCard.svelte` 复用原组件,以可选 studio 呈现显示工具图标、“调用”、真实参数摘要、完成/错误状态标签;展开仍显示真实参数与返回值,旧调用方保持默认外观。
|
||||
|
||||
1440 样例实测:页头 14→13px,面包屑标题为样本原有的14px/600;短助手回复127.3→609px;工具卡647×35.8→609×36.594,x=388、y=176.875,与映射真实内容的参考一致;4s 标签27.25×18,仍是真实可编辑 number input。页头状态标签颜色/背景/边框及三层光晕的固定时间点计算样式与参考一致。
|
||||
|
||||
同状态证据使用隔离真实 API 的两任务、两成果及三张图片,逐项映射全部条目、选中任务ID、项目/技能选择值、原文换行、工具开合、输入焦点和真实可发送输入;没有改 disabled、删除业务条目或复制应用 DOM/CSS。保留原样本状态、仅内容映射参考、仅首页批准的 hero flex-shrink:0 参考和实际应用四种边界。原 HTML SHA256 为 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`。
|
||||
|
||||
仍需总管裁定的真实结构边界:页头的原会话/技能管理入口在样本无对应业务动作;原样本含“设计演示”标记与演示技能组合;真实成果可分别选择项目/阶段,参考只是一枚静态 chip;planner 与分镜设计是两个不同作者,工具行没有持久化作者字段,不能据图伪造作者归属;样本只有背景图 cover,没有视频控制与“暂无草图”概念。三张图均映射,应用按已通过 V1 保留 contain;视频手动播放与空镜以应用独立实测为准。镜头编号沿用原标签与 token,只修正覆盖层级,防止横图遮住编号。没有把这些冲突自行接受为整页通过。
|
||||
|
||||
验证及24组图片、局部、状态断言和完整日志随 HEL-791 附件交付。前端 lint、check(0错0警告)、既有 test、build、diff check;相关真实操作覆盖工具参数与展开收起、上传、中文/键盘发送与禁用、停止与错误、时长/描述保存刷新、带回原项目待确认、旧聊天和12组小窗口交互。后端/API/迁移原验证保留,本轮不重跑无关后端全量,不改后端、协议、数据库、contracts.json、原样本或依赖。
|
||||
|
||||
施工自测完成待独立复审;未部署、合并或启动 HEL-733,测试站仍为 B3。最终整页是否达到样本门禁由总管接续目检与总工独立复审决定。
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Loopback-only OpenAI-compatible model: actual tools execute inside the isolated app."""
|
||||
import json
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
|
||||
OUT=Path('e2e/shots/hel732');OUT.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 (OUT/'model-requests.jsonl').open('a') as f: f.write(json.dumps(payload,ensure_ascii=False)+'\n')
|
||||
msgs=payload.get('messages',[])
|
||||
last_user=max((i for i,m in enumerate(msgs) if m.get('role')=='user'),default=-1)
|
||||
has_tool=any(m.get('role')=='tool' for m in msgs[last_user+1:])
|
||||
text='第一场,清晨的海岸,女孩将纸船放入海水,等待父亲归来。第二场,纸船带回一片树叶,她望向海平面,知道旅程才刚刚开始。'
|
||||
if 'B4_STORYBOARD' in json.dumps(msgs,ensure_ascii=False):
|
||||
text='以下是可编辑分镜成果:\n```json\n'+json.dumps({'shots':[{'id':f'b4-shot-{i}','description':f'隔离验证镜头 {i},女孩沿海岸走向灯塔。','duration_sec':4} for i in range(1,4)]},ensure_ascii=False)+'\n```'
|
||||
if msgs and str(msgs[0].get('content','')).startswith('You are the planner'):
|
||||
text=json.dumps({'mode':'single','tasks':[],'note':'隔离模型单任务'})
|
||||
delta={'content':text}
|
||||
if payload.get('tools') and not has_tool:
|
||||
delta={'tool_calls':[{'index':0,'id':'b4-workspace','type':'function','function':{'name':'get_workspace','arguments':'{"sections":["scenes"]}'}}]}
|
||||
if payload.get('stream'):
|
||||
self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers()
|
||||
self.wfile.write(('data: '+json.dumps({'id':'b4-fake','choices':[{'index':0,'delta':delta,'finish_reason':None}]},ensure_ascii=False)+'\n\n').encode())
|
||||
self.wfile.write(b'data: [DONE]\n\n');self.wfile.flush()
|
||||
else:
|
||||
data=json.dumps({'choices':[{'index':0,'message':{'role':'assistant',**delta},'finish_reason':'stop'}]},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()
|
||||
+5
-4
@@ -436,10 +436,11 @@ async function shot(p, name) {
|
||||
.filter({ hasText: "待配置测试工具" })
|
||||
.click();
|
||||
await p.waitForURL("**/workflows?manage=1&wf=" + pending.id);
|
||||
ok(
|
||||
"待配置导向真实管理和测试入口",
|
||||
await p.locator(".wf-test-btn").first().isVisible(),
|
||||
);
|
||||
// B2 replaced the old wf-test-btn class with the same real test action.
|
||||
// Wait for its data-driven detail panel; keep the original behavior assertion.
|
||||
const workflowTest = p.getByRole("button", { name: "试运行", exact: true });
|
||||
await workflowTest.waitFor();
|
||||
ok("待配置导向真实管理和测试入口", await workflowTest.isVisible());
|
||||
// Source project round-trip uses original API and explicit attachment.
|
||||
await api(
|
||||
"/api/workbench/projects/" + f.project + "/stages/assets",
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Explain content-driven height differences without altering the frozen sample or product.
|
||||
// Original sample screenshots remain in the evidence pack. This second pass changes only
|
||||
// the two descriptive strings to the isolated fixture strings and measures their reflow.
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import {pathToFileURL} from 'node:url';
|
||||
const {chromium}=await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const out='e2e/shots/hel731';
|
||||
const measurements=JSON.parse(await fs.readFile(out+'/measurements.json','utf8'));
|
||||
const browser=await chromium.launch({args:['--no-sandbox']});
|
||||
const results=[];
|
||||
try{
|
||||
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
const page=await browser.newPage({viewport:{width,height}});
|
||||
await page.goto(pathToFileURL(path.resolve('../attachments/夜片场-多主题交互样本.html')).href);
|
||||
await page.evaluate(t=>{document.documentElement.dataset.theme=t;document.documentElement.classList.add('reduce');document.querySelector('.hero .copy p').textContent='纸船带回一片树叶';document.querySelectorAll('#projShots .scard .bd p').forEach(e=>e.textContent='女孩沿着海岸走向灯塔,纸船随海风起伏。');},theme);
|
||||
for(const [name,ref,actual] of [['studio','.hero','.studio-hero'],['project','.scard','.storyboard-card']]){
|
||||
await page.evaluate(name=>document.querySelectorAll('.page').forEach(e=>e.classList.toggle('on',e.id==='p-'+name)),name);await page.waitForTimeout(350);
|
||||
const box=await page.locator(ref).first().boundingBox();const a=measurements.find(x=>x.width===width&&x.theme===theme&&x.selector===actual).actual;
|
||||
results.push({theme,width,page:name,sampleWithFixtureDescription:box,actual:a,deltaHeight:a.height-box.height});
|
||||
await page.screenshot({path:`${out}/${name}-${theme}-${width}-sample-description-normalized.png`});
|
||||
}await page.close();
|
||||
}
|
||||
await fs.writeFile(out+'/description-reflow.json',JSON.stringify(results,null,2));
|
||||
console.log('normalized reflow comparisons',results.length,'maximum height delta',Math.max(...results.map(r=>Math.abs(r.deltaHeight))));
|
||||
}finally{await browser.close()}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
// B3: real local API, disposable database and fake ComfyUI only.
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE_PATH || 'playwright');
|
||||
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict');
|
||||
const API='http://127.0.0.1:8247',WEB='http://127.0.0.1:5173',out='e2e/shots/hel731';
|
||||
fs.mkdirSync(out,{recursive:true}); const checks=[],errors=[];
|
||||
const ok=(name,value)=>{assert(value,name);checks.push(name);console.log('PASS',name)};
|
||||
async function api(p,b,method){const r=await fetch(API+p,{method:method||(b?'POST':'GET'),headers:{'Content-Type':'application/json'},body:b?JSON.stringify(b):undefined});if(!r.ok)throw Error(p+' '+await r.text());return r.json()}
|
||||
async function wait(fn){for(let i=0;i<120;i++){const x=await fn();if(x)return x;await new Promise(r=>setTimeout(r,150))}throw Error('condition timeout')}
|
||||
const base=id=>'/api/workbench/projects/'+id;
|
||||
const fixtures={
|
||||
script:{text:'第一场:清晨的海岸,女孩把一只纸船放入海水。她等候着父亲的归来。第二场:纸船带回一片树叶,女孩望向海平面,知道旅程才刚刚开始。'},
|
||||
style:{directions:[{id:'s1',name:'晨光',description:'暖光',prompt:'warm light'},{id:'s2',name:'蓝调',description:'冷光',prompt:'blue hour'}]},
|
||||
storyboard:{shots:Array.from({length:12},(_,i)=>({id:'board-'+i,scene:'1',shot_size:'远景',camera:'固定',description:'女孩沿着海岸走向灯塔,纸船随海风起伏。',dialog:i%2?'你好':'',duration_sec:5}))},
|
||||
assets:{assets:[{id:'asset-a',kind:'character',name:'海边女孩',description:'女孩',prompt:'girl on coast'}]},
|
||||
shot:{shots:[{id:'shot-a',shot_no:'S1',description:'女孩走向灯塔',prompt:'girl walks toward lighthouse',duration_sec:4}]}
|
||||
};
|
||||
(async()=>{
|
||||
const b=await chromium.launch({executablePath:process.env.CHROMIUM_EXECUTABLE_PATH,args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
const sample=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../attachments/夜片场-多主题交互样本.html'))});await new Promise(r=>sample.listen(0,'127.0.0.1',r));
|
||||
const c=await b.newContext({viewport:{width:1440,height:900}});await c.tracing.start({screenshots:true,snapshots:true,sources:true});const p=await c.newPage();p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message));
|
||||
try{
|
||||
const f=JSON.parse(fs.readFileSync('e2e/shots/reference/fixtures.json'));
|
||||
const proj=await api('/api/projects',{title:'隔离验证 · 海岸来信',idea:'纸船带回一片树叶'}),other=await api('/api/projects',{title:'隔离验证 · 独立项目'});
|
||||
for(const [stage,content] of Object.entries(fixtures)){
|
||||
await api(base(proj.id)+'/stages/'+stage,{content},'PATCH');
|
||||
if(stage==='script'||stage==='style')await api(base(proj.id)+'/stages/'+stage+'/confirm',stage==='style'?{chosen_style_id:'s1'}:{});
|
||||
}
|
||||
// Verify real UI selection, compare modal and explicit confirmation.
|
||||
await p.goto(WEB+'/workbench/'+proj.id+'?stage=storyboard');await p.locator('.storyboard-card').first().waitFor();
|
||||
ok('分镜显示12张真实镜头卡',(await p.locator('.storyboard-card').count())===12);
|
||||
ok('固定确认首屏可见',await p.locator('[data-testid=stage-confirm-btn]').isVisible());
|
||||
await api(base(proj.id)+'/stages/storyboard/confirm',{});
|
||||
await api(base(proj.id)+'/stages/storyboard',{content:{shots:fixtures.storyboard.shots.map((x,i)=>i?x:{...x,description:'已编辑的第一个镜头'})}},'PATCH');
|
||||
await p.reload();await p.getByRole('button',{name:'对比已确认版',exact:true}).click();await p.locator('.project-compare').waitFor();await p.screenshot({path:out+'/compare-modal.png'});await p.keyboard.press('Escape');
|
||||
await p.locator('[data-testid=stage-restore-btn]').click();await wait(async()=>JSON.stringify((await api(base(proj.id))).stages.find(s=>s.stage_key==='storyboard').content)===JSON.stringify(fixtures.storyboard));ok('恢复真实确认快照',true);
|
||||
await api(base(proj.id)+'/stages/storyboard',{content:fixtures.storyboard},'PATCH');
|
||||
await api(base(proj.id)+'/stages/storyboard',{content:{shots:fixtures.storyboard.shots.map((x,i)=>i?x:{...x,description:'等待确认的新草稿'})}},'PATCH');
|
||||
await p.reload();await p.locator('[data-testid=stage-confirm-btn]').click();await wait(async()=>new URL(p.url()).searchParams.get('stage')==='assets');ok('仅显式确认后进入下一阶段',true);
|
||||
// Fixed footer saves the panel's edited draft and prevents stale confirmation.
|
||||
await p.goto(WEB+'/workbench/'+proj.id+'?stage=storyboard');await p.locator('.storyboard-card').first().waitFor();
|
||||
await p.getByRole('button',{name:'编辑',exact:true}).click();await p.locator('.shot-edit textarea').first().fill('通过固定底栏保存的新镜头描述');
|
||||
ok('编辑期间禁止确认旧内容',await p.locator('[data-testid=stage-confirm-btn]').isDisabled());
|
||||
await p.locator('[data-testid=stage-save-btn]').click();await wait(async()=>JSON.stringify(await api(base(proj.id))).includes('通过固定底栏保存的新镜头描述'));ok('固定底栏保存实际编辑草稿',true);
|
||||
for(const stage of ['script','style','storyboard','assets','shot']){
|
||||
await p.locator(`[data-stage=${stage}]`).click();await p.screenshot({path:`${out}/stage-${stage}.png`});
|
||||
ok('阶段切换 '+stage,new URL(p.url()).searchParams.get('stage')===stage);
|
||||
}
|
||||
await p.locator('[data-stage=storyboard]').click();await p.locator('[data-testid=stage-instruction]').fill('分镜专属要求');await p.locator('[data-stage=style]').click();ok('阶段要求不串阶段',await p.locator('[data-testid=stage-instruction]').inputValue()==='');await p.locator('[data-stage=storyboard]').click();ok('切回阶段保留要求',await p.locator('[data-testid=stage-instruction]').inputValue()==='分镜专属要求');await p.locator('[data-testid=stage-instruction]').fill('');
|
||||
await p.locator('[data-stage=storyboard]').click();await p.locator('.project-content').evaluate(e=>e.scrollTop=e.scrollHeight);await p.screenshot({path:out+'/long-scroll.png'});ok('长内容滚动时固定确认可用',await p.locator('[data-testid=stage-confirm-btn]').isVisible());
|
||||
// Project navigation stays scoped; edits from the old component cannot write into the new project.
|
||||
await p.goto(WEB+'/workbench/'+other.id+'?stage=script');await p.locator('[data-testid=workbench-page]').waitFor();ok('跨项目不带旧镜头',await p.locator('.storyboard-card').count()===0);
|
||||
// Script import uses the original import endpoint.
|
||||
await api(base(other.id)+'/stages/script/import',{text:fixtures.script.text});ok('剧本导入保留正式确认语义',(await api(base(other.id))).stages.find(s=>s.stage_key==='script').status==='confirmed');
|
||||
// Create a real 3D composition, render it in the existing viewport and save a screenshot.
|
||||
await p.goto(WEB+'/build-scene');await p.waitForTimeout(2000);await p.screenshot({path:out+'/scene-entry.png'});
|
||||
await p.locator('canvas').first().waitFor();
|
||||
await p.locator('.toolbar .capture').click();
|
||||
const scene = await wait(async () => (await api('/api/shots')).find(s => s.title));
|
||||
const cap = await wait(async () => (await api('/api/shots/'+scene.id+'/captures'))[0]);
|
||||
ok('真实三维视口截图写入隔离存储',!!cap.file_path);
|
||||
// Five-stage source -> real declared image slot -> fake generation -> explicit source attachment.
|
||||
const q=new URLSearchParams({kind:'video',wf:String(f.h3),from:'workbench',project:String(proj.id),stage:'shot',source_kind:'shot',source_id:'shot-a',label:'镜头 S1',prompt:fixtures.shot.shots[0].prompt});
|
||||
await p.goto(WEB+'/create?'+q);await p.locator('#desk-prompt').waitFor();
|
||||
await p.getByRole('button',{name:'管理素材',exact:false}).click();await p.getByRole('button',{name:'从三维搭景截取',exact:true}).first().click();await p.locator('.capture-choices button').first().click();
|
||||
await p.getByRole('button',{name:'从三维搭景截取',exact:true}).nth(1).click();await p.locator('.capture-choices button').first().click();
|
||||
await p.screenshot({path:out+'/capture-selected.png'});await p.getByRole('button',{name:'完成',exact:true}).click();
|
||||
fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',delay_sec:0,videos:true,unique_filename:true}));
|
||||
const before=Math.max(0,...(await api('/api/playground/jobs')).map(j=>j.id));await p.locator('.gen').click();
|
||||
const job=await wait(async()=>(await api('/api/playground/jobs')).find(j=>j.id>before&&j.status==='done'));
|
||||
ok('假服务生成保留来源镜头',JSON.stringify(job.payload).includes('shot-a'));
|
||||
await p.getByRole('button',{name:'存入项目',exact:true}).click();await wait(async()=>JSON.stringify(await api(base(proj.id))).includes(job.output_paths[0]));ok('截图参考生成结果回流来源项目',true);
|
||||
ok('回流不串项目',!JSON.stringify(await api(base(other.id))).includes(job.output_paths[0]));
|
||||
await p.goto(WEB+'/workbench/'+proj.id+'?stage=shot');await p.locator('.vshot-video').waitFor();
|
||||
ok('镜头阶段显示本阶段任务',await p.locator('[data-testid=workbench-jobs] .job-row').count()===1);
|
||||
ok('项目回流视频默认暂停',await p.locator('.vshot-video').evaluate(v=>v.paused));
|
||||
ok('项目视频手动播放',await p.locator('.vshot-video').evaluate(async v=>{await v.play();return !v.paused}));await p.screenshot({path:out+'/project-video-playing.png'});await p.locator('.vshot-video').evaluate(v=>v.pause());await p.screenshot({path:out+'/project-video-paused.png'});
|
||||
|
||||
await p.locator('[data-stage=storyboard]').click();ok('分镜阶段不混入镜头任务',await p.locator('[data-testid=workbench-jobs] .job-row').count()===0);
|
||||
// Text-only workflows must retain no image slots.
|
||||
await p.goto(WEB+'/create?kind=image&wf='+f.dual);await p.locator('#desk-prompt').waitFor();ok('文生图无伪造图片槽',await p.locator('.a-slot').count()===0);
|
||||
// Stable data state for visual evidence; these records live only in this disposable DB.
|
||||
await api(base(proj.id)+'/stages/storyboard',{content:fixtures.storyboard},'PATCH');
|
||||
const sp=await c.newPage();const measures=[];
|
||||
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.setViewportSize({width,height});await sp.setViewportSize({width,height});
|
||||
await p.evaluate(t=>{localStorage.setItem('aigc-theme',t)},theme);
|
||||
await sp.goto('http://127.0.0.1:'+sample.address().port);await sp.evaluate(t=>{document.documentElement.dataset.theme=t;document.documentElement.classList.add('reduce')},theme);
|
||||
for(const page of ['studio','project']){
|
||||
await p.goto(WEB+(page==='studio'?'/':'/workbench/'+proj.id+'?stage=storyboard'));
|
||||
await p.locator(page==='studio'?'.studio-hero':'.storyboard-card').first().waitFor();
|
||||
await sp.evaluate(v=>{document.querySelectorAll('.page').forEach(e=>e.classList.toggle('on',e.id==='p-'+v))},page);
|
||||
await sp.waitForTimeout(350);await p.waitForTimeout(100);
|
||||
if(page==='project')await p.getByRole('button',{name:'选择镜头 3',exact:true}).click();
|
||||
await p.screenshot({path:`${out}/${page}-${theme}-${width}-actual.png`});await sp.screenshot({path:`${out}/${page}-${theme}-${width}-sample.png`});
|
||||
const selectors=page==='studio'?[['.hero','.studio-hero'],['.copy','.hero-copy'],['.display','.studio-display'],['.studio-wrap','.home'],['.quick','.studio-quick']]:[['.stepper','.stepper'],['.proj-side','.project-side'],['.proj-foot','.project-footer'],['.scard','.storyboard-card'],['.ps-sec .input','.stage-input-wrap'],['#confirmStage','[data-testid=stage-confirm-btn]']];
|
||||
ok(`主题 ${theme} ${page} ${width}`, await p.evaluate(t=>document.documentElement.dataset.theme===t,theme));
|
||||
const measure=async(pg,sel)=>pg.locator(sel).first().evaluate(e=>{const b=e.getBoundingClientRect(),s=getComputedStyle(e);return {x:b.x,y:b.y,width:b.width,height:b.height,font:s.fontSize,weight:s.fontWeight,radius:s.borderRadius,color:s.color,background:s.backgroundColor}});
|
||||
for(const [ref,actual] of selectors)measures.push({page,theme,width,selector:actual,sample:await measure(sp,ref),actual:await measure(p,actual)});
|
||||
if(page==='project')ok(`固定确认 ${theme} ${width}`,await p.locator('[data-testid=stage-confirm-btn]').evaluate(e=>e.getBoundingClientRect().bottom<=innerHeight));
|
||||
}
|
||||
}
|
||||
await p.goto(WEB+'/');await p.locator('.studio-search').click();await p.screenshot({path:out+'/search-open.png'});await p.keyboard.press('Escape');await p.keyboard.press('Control+k');ok('工作室搜索快捷键保留',await p.getByRole('dialog').isVisible());await p.keyboard.press('Escape');
|
||||
await p.getByRole('button',{name:'主题',exact:true}).click();await p.locator('.choices .choice').filter({hasText:'日光棚'}).click();await p.waitForTimeout(600);await p.screenshot({path:out+'/theme-operation.png'});ok('主题操作生效',await p.evaluate(()=>document.documentElement.dataset.theme==='day'));await p.keyboard.press('Escape');
|
||||
await p.route('**/api/projects',route=>route.fulfill({json:[]}));await p.reload();await p.locator('.studio-hero').waitFor();await p.screenshot({path:out+'/empty-studio.png'});ok('空态不展示样本项目',!(await p.locator('.studio-hero').innerText()).includes('雾港来信'));await p.unroute('**/api/projects');
|
||||
fs.writeFileSync(out+'/measurements.json',JSON.stringify(measures,null,2));fs.writeFileSync(out+'/results.json',JSON.stringify({checks,errors},null,2));ok('无浏览器运行错误',errors.length===0);
|
||||
}finally{await c.tracing.stop({path:out+'/interaction-trace.zip'});await b.close();await new Promise(r=>sample.close(r));}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,12 @@
|
||||
// Review-only proposal: temporary browser style; never change product/sample code.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs');const out='e2e/shots/hel732';
|
||||
(async()=>{const b=await chromium.launch({args:['--no-sandbox']});const rows=[];
|
||||
try {for(const [width,height] of [[1366,768],[1280,720]]){
|
||||
const p=await b.newPage({viewport:{width,height}});await p.goto('http://127.0.0.1:5173/agents');await p.locator('.roster .acard').first().waitFor();
|
||||
const measure=()=>p.evaluate(()=>{const hero=document.querySelector('.ahero').getBoundingClientRect(),button=document.querySelector('.big-input .primary').getBoundingClientRect();return {heroHeight:hero.height,heroBottom:hero.bottom,buttonTop:button.top,buttonBottom:button.bottom,clipped:button.bottom>hero.bottom,viewport:innerHeight}});
|
||||
const before=await measure();await p.screenshot({path:`${out}/conflict-${width}-actual.png`,animations:'disabled'});
|
||||
await p.locator('.ahero').evaluate(e=>e.style.flexShrink='0');const proposal=await measure();await p.screenshot({path:`${out}/proposal-${width}-browser-only.png`,animations:'disabled'});
|
||||
rows.push({width,height,before,proposal,temporaryRule:'.ahero {flex-shrink:0}',productCodeChanged:false});await p.close();
|
||||
}fs.writeFileSync(out+'/conflict.json',JSON.stringify(rows,null,2));console.log('RECORDED visual blocker and browser-only proposal',rows);
|
||||
}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,42 @@
|
||||
// Real controls, normal pointer input and isolated application/model chain at every viewport/theme.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs'),assert=require('node:assert/strict');
|
||||
const out='e2e/shots/hel732',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247';
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
const rows=[],errors=[],checks=[];
|
||||
const board=JSON.parse(fs.readFileSync(out+'/fixture-state.json')).board;
|
||||
const measure=async(page,selector)=>page.locator(selector).first().evaluate(e=>{const r=e.getBoundingClientRect();return {selector:e.getAttribute('aria-label')||e.className,x:r.x,y:r.y,width:r.width,height:r.height,right:r.right,bottom:r.bottom,visible:r.x>=0&&r.y>=0&&r.right<=innerWidth&&r.bottom<=innerHeight,hit:e.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2))}});
|
||||
try{
|
||||
for(const [width,height]of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
const context=await browser.newContext({viewport:{width,height}}),p=await context.newPage();
|
||||
p.on('pageerror',e=>errors.push(e.message));
|
||||
await p.goto(WEB+'/agents');await p.locator('.roster .acard').first().waitFor();
|
||||
await p.evaluate(theme=>{document.documentElement.dataset.theme=theme;localStorage.setItem('aigc-theme',theme)},theme);
|
||||
const home={hero:await measure(p,'.ahero'),input:await measure(p,'[aria-label="任务想法"]'),start:await measure(p,'.big-input .primary')};
|
||||
assert(home.input.visible&&home.input.hit&&home.start.visible&&home.start.hit,JSON.stringify(home));
|
||||
assert(home.start.bottom<=home.hero.bottom);
|
||||
assert(await p.locator('.agent-home').evaluate(e=>e.scrollWidth<=e.clientWidth));
|
||||
await p.getByLabel('任务想法').fill(`小窗口真实启动 ${theme} ${width},请调用工具读取工作区并写一段海岸故事。`);
|
||||
await p.getByLabel('任务想法').click();assert(await p.getByLabel('任务想法').evaluate(e=>e===document.activeElement));
|
||||
await p.screenshot({path:`${out}/layout-input-${theme}-${width}.png`,animations:'disabled'});
|
||||
await p.locator('.mini-row').scrollIntoViewIfNeeded();
|
||||
await p.waitForFunction(()=>{const r=document.querySelector('.mini-row').getBoundingClientRect();return r.bottom<=innerHeight+1&&r.top>=0});
|
||||
await p.screenshot({path:`${out}/layout-scrolled-${theme}-${width}.png`,animations:'disabled'});
|
||||
await p.getByRole('button',{name:'开始任务',exact:true}).click();
|
||||
await p.waitForURL(/session=\d+/);const session=Number(new URL(p.url()).searchParams.get('session'));
|
||||
await p.waitForFunction(async({API,session})=>(await(await fetch(API+'/api/results/deliverables?session_id='+session)).json()).length>0,{API,session});
|
||||
checks.push(`输入、焦点、自然滚动和正常点击启动真实会话 ${theme} ${width}`);
|
||||
await p.goto(WEB+'/agents?session='+board);await p.locator('.shot-copy textarea').first().waitFor();
|
||||
const controls={};for(const selector of ['.art-f','[aria-label="成果项目"]','[aria-label="成果阶段"]','.art-f .secondary','.art-f .primary']){
|
||||
controls[selector]=await measure(p,selector);assert(controls[selector].visible&&controls[selector].hit,JSON.stringify(controls[selector]));
|
||||
}
|
||||
for(const label of ['成果项目','成果阶段']){await p.getByLabel(label).focus();assert(await p.getByLabel(label).evaluate(e=>e===document.activeElement));}
|
||||
for(const selector of ['.art-f .secondary','.art-f .primary']){await p.locator(selector).focus();assert(await p.locator(selector).evaluate(e=>e===document.activeElement));}
|
||||
assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||
await p.screenshot({path:`${out}/layout-footer-${theme}-${width}.png`,animations:'disabled'});
|
||||
rows.push({theme,width,height,home,controls});await context.close();
|
||||
}
|
||||
assert.deepEqual(errors,[]);fs.writeFileSync(out+'/layout-checks.json',JSON.stringify({rows,checks,errors},null,2));console.log('PASS 12 theme/viewport input/start/scroll/real selector/focus/overflow checks');
|
||||
}finally{await browser.close()}
|
||||
})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Executable isolated backup / migration / old-code read / exact restore exercise.
|
||||
No service, user database or production configuration is opened.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import tarfile
|
||||
|
||||
BASE='8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb'
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
OUT=ROOT/'e2e/shots/hel732/migration'
|
||||
OUT.mkdir(parents=True,exist_ok=True)
|
||||
OLD=OUT/'old-code';OLD.mkdir(exist_ok=True)
|
||||
archive=subprocess.run(['git','archive',BASE,'calliope-backend/src'],cwd=ROOT,check=True,stdout=subprocess.PIPE).stdout
|
||||
(OUT/'old-code.tar').write_bytes(archive)
|
||||
with tarfile.open(OUT/'old-code.tar') as tf:tf.extractall(OLD,filter='data')
|
||||
DB=OUT/'isolated.db'
|
||||
if DB.exists():DB.rename(OUT/f'previous-{__import__("time").time_ns()}.db')
|
||||
checks=[]
|
||||
def old_run(mode):
|
||||
code='''import asyncio,json,sys
|
||||
from pathlib import Path
|
||||
from calliope import config
|
||||
from calliope.db import migrate_db,get_db
|
||||
config.settings.data_dir=Path(sys.argv[1]).parent
|
||||
config.settings.db_name=Path(sys.argv[1]).name
|
||||
config.settings.assets_dir=Path(sys.argv[1]).parent/'assets'
|
||||
config.settings.dry_run=True
|
||||
config.Settings.save_config_file=lambda self:None
|
||||
if sys.argv[2]=='create':
|
||||
asyncio.run(migrate_db(config.settings.db_path))
|
||||
c=get_db(config.settings.db_path)
|
||||
p=c.execute("INSERT INTO projects(title,status) VALUES ('B3 isolated legacy','draft')").lastrowid
|
||||
c.execute("INSERT INTO agent_sessions(project_id,title,status) VALUES (?,'Legacy session','idle')",(p,))
|
||||
c.execute("INSERT INTO agent_messages(session_id,role,content) VALUES (1,'user','Existing legacy message')")
|
||||
c.execute("INSERT INTO jobs(project_id,kind,status,payload_json,output_paths_json) VALUES (1,'image','done',?,'[]')",(json.dumps({'legacy':True}),))
|
||||
content=json.dumps({'text':'Legacy confirmed story text, sufficiently long to preserve the old confirmation behavior.'})
|
||||
c.execute("INSERT INTO project_stages(project_id,stage_key,status,content_json,confirmed_content_json) VALUES (?,'script','confirmed',?,?)",(p,content,content))
|
||||
c.commit();c.close()
|
||||
else:
|
||||
from calliope.main import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
with TestClient(create_app()) as client:
|
||||
s=client.get('/api/agent/sessions/1');assert s.status_code==200,s.text
|
||||
assert any(m['content']=='Existing legacy message' for m in s.json()['messages'])
|
||||
jobs=client.get('/api/jobs?project_id=1');assert jobs.status_code==200,jobs.text
|
||||
assert jobs.json()[0]['status']=='done' and jobs.json()[0]['payload']['legacy'] is True
|
||||
w=client.get('/api/workbench/projects/1');assert w.status_code==200,w.text
|
||||
stage=w.json()['stages'][0];assert stage['status']=='confirmed'
|
||||
assert stage['content']==stage['confirmed_content']
|
||||
print(json.dumps({'session':s.json()['title'],'stage':stage['status'],'message_count':len(s.json()['messages'])}))
|
||||
'''
|
||||
env=os.environ.copy();env['PYTHONPATH']=str(OLD/'calliope-backend/src')
|
||||
result=subprocess.run([__import__('sys').executable,'-c',code,str(DB),mode],cwd=OUT,env=env,text=True,capture_output=True,check=True)
|
||||
(OUT/f'old-{mode}.log').write_text(result.stdout+result.stderr)
|
||||
checks.append('old code '+mode+' succeeded')
|
||||
old_run('create')
|
||||
def backup(src,dst):
|
||||
a=sqlite3.connect(src);b=sqlite3.connect(dst);a.backup(b);b.close();a.close()
|
||||
backup(DB,OUT/'pre-b4-backup.db')
|
||||
def dump(path):
|
||||
c=sqlite3.connect(path);rows={name:c.execute(f'SELECT * FROM {name}').fetchall() for name in ['projects','agent_sessions','agent_messages','project_stages','jobs']};c.close();return rows
|
||||
before=dump(DB)
|
||||
from calliope.db import migrate_db,get_db
|
||||
asyncio.run(migrate_db(DB));asyncio.run(migrate_db(DB))
|
||||
c=get_db(DB)
|
||||
for table,rows in before.items():
|
||||
current=c.execute(f'SELECT * FROM {table}').fetchall()
|
||||
# New columns are appended; every pre-existing field is equal.
|
||||
assert [tuple(r)[:len(rows[0])] for r in current]==rows
|
||||
assert c.execute('PRAGMA integrity_check').fetchone()[0]=='ok'
|
||||
assert c.execute('PRAGMA foreign_key_check').fetchall()==[]
|
||||
cols=[r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')]
|
||||
assert cols.count('task_summary')==1 and cols.count('task_status')==1
|
||||
c.close();checks+=['migrate twice; no duplicate columns/tables','all original rows/fields preserved','integrity_check and foreign_key_check passed']
|
||||
old_run('read')
|
||||
# New-only payload survives an old-code read and startup.
|
||||
c=get_db(DB)
|
||||
c.execute("INSERT INTO agent_deliverables(session_id,source_message_id,project_id,stage_key,title,content) VALUES (1,1,1,'script','B4 isolated','New isolated deliverable')")
|
||||
c.commit();c.close()
|
||||
backup(DB,OUT/'post-b4-export.db')
|
||||
# Exact rollback to an offline copy of the old backup; never overwrite a live DB.
|
||||
backup(OUT/'pre-b4-backup.db',OUT/'restored.db')
|
||||
assert dump(OUT/'restored.db')==before
|
||||
c=sqlite3.connect(OUT/'restored.db')
|
||||
assert 'task_summary' not in [r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')]
|
||||
assert c.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='agent_deliverables'").fetchone()[0]==0
|
||||
c.close();checks.append('exact pre-migration backup restored: old rows and old schema equal')
|
||||
manifest={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in OUT.glob('*.db')}
|
||||
(OUT/'report.json').write_text(json.dumps({'base':BASE,'checks':checks,'sha256':manifest},indent=2))
|
||||
print(json.dumps({'checks':checks,'sha256':manifest},indent=2))
|
||||
@@ -0,0 +1,68 @@
|
||||
// Same-page/state comparison: normalize reference CONTENT only, retain its original CSS/layout.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict');
|
||||
const out='e2e/shots/hel732',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247';
|
||||
const api=async p=>(await fetch(API+p)).json();
|
||||
const style=loc=>loc.evaluate(e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return Object.fromEntries(['fontSize','fontWeight','letterSpacing','lineHeight','padding','gap','borderRadius','borderTopWidth','borderTopColor','backgroundColor','backgroundImage','color','boxShadow','filter','gridTemplateColumns'].map(k=>[k,s[k]]).concat([['x',r.x],['y',r.y],['width',r.width],['height',r.height]]))});
|
||||
(async()=>{
|
||||
const state=JSON.parse(fs.readFileSync(out+'/fixture-state.json'));
|
||||
const registry=await api('/api/agent/agents'),skills=await api('/api/agent/skills?all=true'),results=await api('/api/results/deliverables');
|
||||
const session=await api('/api/agent/sessions/'+state.board),shots=JSON.parse(state.br.content).shots;
|
||||
const sessions=(await Promise.all([api('/api/agent/sessions'),...registry.map(a=>api('/api/agent/sessions?agent_key='+a.key))])).flat().sort((a,b)=>b.updated_at.localeCompare(a.updated_at));
|
||||
const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../evidence/reference/夜片场-多主题交互样本.html'))});await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
const rows=[],originalRows=[],operations=[];
|
||||
try{
|
||||
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
const c=await b.newContext({viewport:{width,height}}),a=await c.newPage(),s=await c.newPage();
|
||||
await a.goto(WEB+'/agents');await a.locator('.roster .acard').first().waitFor();await a.evaluate(t=>{document.documentElement.dataset.theme=t;localStorage.setItem('aigc-theme',t);document.documentElement.dataset.reduce='0'},theme);
|
||||
await s.goto('http://127.0.0.1:'+server.address().port);await s.evaluate(({theme,registry,skills,results,sessions,board})=>{
|
||||
go('agents');document.documentElement.dataset.theme=theme;document.querySelectorAll('#p-agents .seg button').forEach((e,i)=>e.classList.toggle('on',i===1));
|
||||
const clear=e=>{while(e.firstChild)e.removeChild(e.firstChild)};
|
||||
for(const id of ['taskList','taskList2']){const list=document.getElementById(id);clear(list);for(const task of sessions){const item=document.createElement('div');item.className='titem'+(id==='taskList2'&&task.id===board?' on':'');const title=document.createElement('b');title.className='ellipsis';title.textContent=task.title;const meta=document.createElement('div');meta.className='meta';const dot=document.createElement('span');dot.className='dot';dot.style.background='var(--sc-agent)';const grow=document.createElement('span');grow.className='grow';meta.append(dot,({returned:'已带回项目',awaiting_confirm:'待你确认',ready:'未开始'}[task.task_status]||task.task_status||'未开始'),grow,task.project?.title||'沙盒');item.append(title,meta);list.append(item);}}
|
||||
const chips=document.querySelector('#p-agents .big-input .row').querySelectorAll('.chip');chips[0].querySelector('b').textContent='沙盒';chips[1].querySelector('b').textContent='reference-test';chips[2].querySelector('b').textContent='不指定';
|
||||
|
||||
document.querySelectorAll('#roster .acard').forEach((e,i)=>{e.querySelector('.bg').style.backgroundImage='none';e.querySelector('.tag').textContent=registry[i].skill_count+' 个技能';e.querySelector('.dim').textContent='reference-test';});
|
||||
const skillBox=document.querySelector('#p-agents .skills');clear(skillBox);for(const skill of skills.filter(x=>x.is_enabled)){const el=document.createElement('span');el.className='skill';el.append(document.createElement('i'),skill.name);skillBox.append(el);}const learn=document.createElement('span');learn.className='skill dim';learn.textContent='+ 学习新技能';skillBox.append(learn);
|
||||
document.querySelector('#p-agents .mini-row .panel:last-child .tag').textContent=String(skills.length);
|
||||
const outs=document.querySelector('#agentOuts');clear(outs);for(const r of results.slice(0,4)){const card=document.createElement('div');card.className='outcard';const thumb=document.createElement('div');thumb.className='t';const data=document.createElement('div');data.className='d';const title=document.createElement('b');title.textContent=r.title;const sub=document.createElement('span');sub.className='dim';sub.textContent=({script:'剧本创作',storyboard:'分镜设计'}[r.stage_key]||r.stage_key)+' · 草稿 v'+r.revision;data.append(title,sub);card.append(thumb,data);outs.append(card);}
|
||||
const input=document.querySelector('#p-agents .big-input textarea');input.placeholder='描述你的创作想法、目标与要求…';document.querySelector('#p-agents .big-input .primary').disabled=true;
|
||||
},{theme,registry,skills,results,sessions,board:state.board});
|
||||
await s.screenshot({path:`${out}/home-${theme}-${width}-original-content.png`,animations:'disabled'});
|
||||
for(const selector of ['.ahero','.big-input','.big-input .primary'])originalRows.push({theme,width,height,selector,style:await style(s.locator(selector).first())});
|
||||
await s.locator('.ahero').evaluate(e=>e.style.flexShrink='0');
|
||||
await a.screenshot({path:`${out}/home-${theme}-${width}-actual.png`,animations:'disabled'});await s.screenshot({path:`${out}/home-${theme}-${width}-approved-content.png`,animations:'disabled'});
|
||||
for(const [name,actual,ref] of [['hero','.ahero','.ahero'],['title','.ahero h2','.ahero h2'],['assistant','.roster .acard','.roster .acard'],['input','.big-input','.big-input'],['tasklist','.tasklist','.tasklist'],['primary','.big-input .primary','.big-input .primary']])rows.push({theme,width,height,page:'home',name,actual:await style(a.locator(actual).first()),sample:await style(s.locator(ref).first())});
|
||||
await a.goto(WEB+'/agents?session='+state.board);await a.locator('.shot-copy textarea').first().waitFor();const thumbnails=await a.locator('.shot .th').evaluateAll(es=>es.map(e=>e.querySelector('img')?.src||''));await s.evaluate(({shots,session,thumbnails})=>{
|
||||
go('agent-task');
|
||||
// Align real message/event state using the sample's own message/tool templates, never application DOM/CSS.
|
||||
const page=document.querySelector('#p-agent-task'),body=page.querySelector('.convo-b');
|
||||
const userTemplate=body.querySelector('.msg.me').cloneNode(true),avatar=body.querySelector('.msg:not(.me) .av').cloneNode(true),toolTemplate=body.querySelector('details.tool').cloneNode(true);
|
||||
body.replaceChildren();
|
||||
for(const m of session.messages){
|
||||
if((m.role==='user'||m.role==='assistant')&&m.content){const row=userTemplate.cloneNode(true);row.classList.toggle('me',m.role==='user');if(m.role==='assistant')row.querySelector('.av').replaceWith(avatar.cloneNode(true));row.querySelector('.bub').textContent=m.content;body.append(row);}
|
||||
else if(m.role==='tool'){const tool=toolTemplate.cloneNode(true);tool.querySelector('code').textContent=m.tool_name;tool.querySelector('.dim')?.remove();tool.querySelector('.tag').textContent='完成';tool.querySelector('pre').textContent=JSON.stringify(m.tool_result,null,2);body.append(tool);}
|
||||
}
|
||||
page.querySelector('.ph .chip b').textContent='reference-test';page.querySelectorAll('.ph .chip')[1]?.remove();
|
||||
page.querySelector('.art-h .row>b').textContent='分镜设计 · 草稿';page.querySelector('.art-h .seg').querySelectorAll('button')[2].textContent='原文';
|
||||
page.querySelector('.art-f .chip b').textContent=session.project?.title||'沙盒';
|
||||
page.querySelector('.convo-in textarea').placeholder='向智能体提问,或用 @ 提及技能…';page.querySelector('.convo-in .ghost')?.remove();page.querySelector('.convo-in .primary').disabled=true;
|
||||
document.querySelector('#p-agent-task .crumb b').textContent=session.title;document.querySelector('#p-agent-task .ph>.tag').textContent='已带回项目';document.querySelector('#p-agent-task .art-h .row>.dim').textContent=shots.length+' 镜 · '+shots.reduce((sum,s)=>sum+(Number(s.duration_sec)||0),0)+'s';
|
||||
const list=document.querySelector('#shotList');const originals=Array.from(list.children);list.replaceChildren();for(const [i,shot]of shots.entries()){const el=originals[i].cloneNode(true);el.querySelector('.th').style.backgroundImage=thumbnails[i]?`url("${thumbnails[i]}")`:'none';el.querySelector('[contenteditable]').textContent=shot.description;el.querySelector('.tag.mono').textContent=shot.duration_sec+'s';list.append(el);}
|
||||
},{shots,session,thumbnails});
|
||||
await a.screenshot({path:`${out}/task-${theme}-${width}-actual.png`,animations:'disabled'});await s.screenshot({path:`${out}/task-${theme}-${width}-reference-content.png`,animations:'disabled'});
|
||||
for(const [name,actual,ref] of [['columns','.atask','.atask'],['artifact','.artifact','.artifact'],['header','.art-h','.art-h'],['footer','.art-f','.art-f'],['shot','.shot','.shot'],['save','.art-f .secondary','.art-f .btn:not(.primary)'],['primary','.art-f .primary','.art-f .primary']])rows.push({theme,width,height,page:'task',name,actual:await style(a.locator(actual).first()),sample:await style(s.locator(ref).first())});
|
||||
if(width===1440&&theme==='night'){
|
||||
await a.getByLabel('镜头 b4-shot-1 描述').fill('主题切换保持未保存编辑');await a.evaluate(async()=>{const {setTheme}=await import('/src/lib/theme.ts');setTheme('day')});await a.waitForFunction(()=>document.documentElement.dataset.theme==='day');assert.equal(await a.getByLabel('镜头 b4-shot-1 描述').inputValue(),'主题切换保持未保存编辑');operations.push('切换主题保持未保存成果文本');await a.screenshot({path:out+'/operation-theme-edit-preserved.png'});
|
||||
await a.getByRole('button',{name:'原文',exact:true}).click();await a.waitForFunction(()=>document.querySelector('[aria-label=成果草稿]')?.value.includes('主题切换保持未保存编辑'));assert((await a.getByLabel('成果草稿').inputValue()).includes('主题切换保持未保存编辑'));operations.push('逐镜编辑与原文视图同步');await a.screenshot({path:out+'/operation-raw-edit.png'});
|
||||
await a.reload();await a.locator('.shot-copy textarea').first().waitFor();await a.getByRole('button',{name:'对比上一版',exact:true}).click();await a.getByRole('dialog').waitFor();await a.screenshot({path:out+'/operation-version-comparison.png'});await a.keyboard.press('Escape');
|
||||
const tool=a.locator('.tool-card .head').first();await tool.click();await a.locator('.tool-card .body').first().waitFor();operations.push('工具详情真实参数与返回值可展开');await a.screenshot({path:out+'/operation-tool-expanded.png'});
|
||||
await a.evaluate(()=>document.documentElement.dataset.reduce='1');assert.equal(await a.locator('.b4 .aurora').evaluate(e=>getComputedStyle(e).display),'none');operations.push('减少动效隐藏本页装饰光晕与粒子');
|
||||
}
|
||||
await c.close();
|
||||
}
|
||||
fs.writeFileSync(out+'/original-style-values.json',JSON.stringify(originalRows,null,2));
|
||||
fs.writeFileSync(out+'/style-values.json',JSON.stringify(rows,null,2));
|
||||
const compareKeys=['x','y','width','height','padding','borderRadius','fontSize','fontWeight','letterSpacing','filter','backgroundColor','backgroundImage','boxShadow','gridTemplateColumns'];const differences=rows.flatMap(r=>compareKeys.filter(k=>r.actual[k]!==r.sample[k]).map(k=>({theme:r.theme,width:r.width,page:r.page,name:r.name,property:k,actual:r.actual[k],sample:r.sample[k]})));fs.writeFileSync(out+'/measured-differences.json',JSON.stringify(differences,null,2));assert.deepEqual(differences,[],'Measured sample differences must be corrected');fs.writeFileSync(out+'/operations.json',JSON.stringify(operations,null,2));console.log('PASS normalized visual pairs: 24; measured selector pairs:',rows.length,'operations:',operations.length);
|
||||
}finally{await b.close();await new Promise(r=>server.close(r));}
|
||||
})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,82 @@
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict');
|
||||
const API='http://127.0.0.1:8247',WEB='http://127.0.0.1:5173',out='e2e/shots/hel732';
|
||||
fs.mkdirSync(out,{recursive:true});const checks=[],errors=[];
|
||||
const ok=(n,v)=>{assert(v,n);checks.push(n);console.log('PASS',n)};
|
||||
async function api(p,b,method){const r=await fetch(API+p,{method:method||(b?'POST':'GET'),headers:{'Content-Type':'application/json'},body:b?JSON.stringify(b):undefined});if(!r.ok)throw Error(p+' '+await r.text());return r.json()}
|
||||
async function wait(fn){for(let i=0;i<120;i++){const r=await fn();if(r)return r;await new Promise(r=>setTimeout(r,150))}throw Error('condition timeout')}
|
||||
(async()=>{
|
||||
const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
const c=await b.newContext({viewport:{width:1440,height:900}});await c.tracing.start({screenshots:true,snapshots:true,sources:true});const p=await c.newPage();p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message));
|
||||
const sample=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../evidence/reference/夜片场-多主题交互样本.html'))});await new Promise(r=>sample.listen(0,'127.0.0.1',r));
|
||||
try{
|
||||
const project=await api('/api/projects',{title:'B4 隔离项目',idea:'海岸与纸船'}),other=await api('/api/projects',{title:'B4 另一个项目'});
|
||||
await p.goto(WEB+'/agents');await p.locator('.roster .acard').first().waitFor();
|
||||
ok('首页五个真实阶段助手',await p.locator('.roster .acard').count()===5);
|
||||
ok('无成果显示真实空态',(await p.locator('.outrow').innerText()).includes('暂无成果'));
|
||||
await p.getByLabel('绑定项目',{exact:true}).selectOption(String(project.id));
|
||||
await p.getByLabel('任务技能').selectOption({index:1});
|
||||
await p.getByLabel('任务想法').fill('请调用工具查看项目,然后写一个海岸纸船的完整故事。');
|
||||
await p.getByRole('button',{name:'开始任务',exact:true}).click();
|
||||
const sid=await wait(async()=>Number(new URL(p.url()).searchParams.get('session'))||null);
|
||||
const r=await wait(async()=>(await api('/api/results/deliverables?session_id='+sid))[0]);
|
||||
ok('真实会话链路产生持久化成果',r.content.length>30);
|
||||
const s=await api('/api/agent/sessions/'+sid);ok('任务摘要与状态持久化',s.task_summary.includes('海岸')&&s.task_status==='awaiting_confirm');
|
||||
ok('假模型通过应用实际调用工具',s.messages.some(m=>m.role==='tool'&&m.tool_name==='get_workspace'));
|
||||
ok('技能选择传入真实会话',s.messages.some(m=>m.role==='user'&&m.mentions?.some(x=>x.type==='skill')));
|
||||
await p.getByLabel('成果草稿').waitFor();const edited=r.content+'【浏览器编辑并保存】';await p.getByLabel('成果草稿').fill(edited);await p.getByRole('button',{name:'保存草稿',exact:true}).click();
|
||||
await wait(async()=>(await api('/api/results/deliverables?session_id='+sid))[0].revision===2);
|
||||
await p.reload();await p.getByLabel('成果草稿').waitFor();ok('编辑保存刷新恢复',await p.getByLabel('成果草稿').inputValue()===edited);
|
||||
await p.getByRole('button',{name:'带回项目待确认',exact:true}).click();await p.locator('[data-testid=incoming-result]').waitFor();
|
||||
const wb=await api('/api/workbench/projects/'+project.id),stage=wb.stages.find(x=>x.stage_key==='script');
|
||||
ok('带回指定项目阶段且仅待确认',stage.status==='awaiting_confirm'&&stage.content.text===edited&&stage.confirmed_content===null);
|
||||
ok('其他项目未出现成果',!JSON.stringify(await api('/api/workbench/projects/'+other.id)).includes('浏览器编辑'));
|
||||
await p.locator('[data-testid=stage-confirm-btn]').click();await wait(async()=>(await api('/api/workbench/projects/'+project.id)).stages[0].status==='confirmed');ok('真实项目页显式确认',true);
|
||||
const nr=(await api('/api/results/deliverables?session_id='+sid))[0];const body={deliverable_id:nr.id,revision:nr.revision,project_id:project.id,stage_key:'script'};
|
||||
ok('重复提交幂等',(await api('/api/results/store',body)).already_attached===true);
|
||||
const bad=await fetch(API+'/api/results/store',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...body,project_id:other.id})});ok('跨项目误存被拒绝',bad.status===409);
|
||||
// Actual structured reply and a single image job; no GPU/paid model.
|
||||
const board=await api('/api/agent/sessions',{project_id:project.id,agent_key:'storyboard',title:'B4 分镜隔离任务'});
|
||||
await api('/api/agent/sessions/'+board.id+'/messages',{content:'B4_STORYBOARD 请读取工作区并给出三个镜头。'});
|
||||
const br=await wait(async()=>(await api('/api/results/deliverables?session_id='+board.id))[0]);
|
||||
const parsed=JSON.parse(br.content.split('```json')[1].split('```')[0]);
|
||||
const saved=await api('/api/results/deliverables/'+br.id,{revision:br.revision,content:JSON.stringify(parsed,null,2),project_id:project.id,stage_key:'storyboard'},'PATCH');
|
||||
await api('/api/results/store',{project_id:project.id,stage_key:'storyboard',deliverable_id:saved.id,revision:saved.revision});
|
||||
await p.goto(WEB+'/agents?session='+board.id);await p.getByRole('button',{name:'重画',exact:true}).first().waitFor();
|
||||
await p.getByLabel('镜头 b4-shot-1 描述').fill('逐镜编辑后的真实描述');await p.getByLabel('镜头 b4-shot-1 时长').fill('6');await p.getByRole('button',{name:'保存草稿',exact:true}).click();
|
||||
await wait(async()=>(await api('/api/results/deliverables?session_id='+board.id))[0].revision===3);
|
||||
await p.getByRole('button',{name:'对比上一版',exact:true}).click();await p.getByRole('dialog').waitFor();ok('成果对比读取真实上一保存版本',(await p.getByRole('dialog').innerText()).includes('隔离验证镜头 1'));await p.getByRole('dialog').getByRole('button',{name:'关闭对话框',exact:true}).click();
|
||||
await p.reload();await p.getByLabel('镜头 b4-shot-1 描述').waitFor();ok('逐镜文字与时长保存刷新恢复',(await p.getByLabel('镜头 b4-shot-1 描述').inputValue())==='逐镜编辑后的真实描述'&&(await p.getByLabel('镜头 b4-shot-1 时长').inputValue())==='6');
|
||||
|
||||
const before=(await api('/api/jobs?project_id='+project.id)).length;
|
||||
await p.getByRole('button',{name:'重画',exact:true}).nth(1).click();
|
||||
const jobs=await wait(async()=>{const rows=await api('/api/jobs?project_id='+project.id);return rows.length>before?rows:null});
|
||||
ok('单镜重画仅新增一个任务',jobs.length===before+1);
|
||||
ok('单镜重画保留指定镜头',jobs[0].payload.target_id==='b4-shot-2');
|
||||
// Independent take → chooser → specific stage draft, original flow-back stays separately covered by B3.
|
||||
fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',delay_sec:0,videos:false,unique_filename:true}));
|
||||
const f=JSON.parse(fs.readFileSync('e2e/shots/reference/fixtures.json'));
|
||||
await p.goto(WEB+'/create?kind=image&wf='+f.dual);await p.locator('#desk-prompt').waitFor();await p.locator('#desk-prompt').fill('B4 isolated independent image');
|
||||
const maxJob=Math.max(0,...(await api('/api/playground/jobs')).map(x=>x.id));await p.locator('.gen').click();
|
||||
const job=await wait(async()=>(await api('/api/playground/jobs')).find(j=>j.id>maxJob&&j.status==='done'));
|
||||
await p.getByRole('button',{name:'存入项目',exact:true}).click();await p.getByLabel('存入项目',{exact:true}).selectOption(String(other.id));await p.getByLabel('存入阶段').selectOption('assets');
|
||||
await p.getByRole('button',{name:'存入待确认草稿'}).click();
|
||||
const mediaStage=await wait(async()=>(await api('/api/workbench/projects/'+other.id)).stages.find(s=>s.stage_key==='assets'&&s.incoming_results?.length));
|
||||
ok('独立生成经通用选择器存入指定阶段',mediaStage.incoming_results[0].paths[0]===job.output_paths[0]&&mediaStage.status==='awaiting_confirm');
|
||||
await p.goto(WEB+'/agents?legacy=1');await p.locator('.agent-rail').waitFor();ok('原会话及技能管理仍可达',true);
|
||||
fs.writeFileSync(out+'/fixture-state.json',JSON.stringify({project,other,sid,board:board.id,br:(await api('/api/results/deliverables?session_id='+board.id))[0]},null,2));
|
||||
const sp=await c.newPage();const measures=[];
|
||||
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.setViewportSize({width,height});await sp.setViewportSize({width,height});
|
||||
await p.goto(WEB+'/agents');await p.evaluate(t=>{document.documentElement.dataset.theme=t;localStorage.setItem('aigc-theme',t);document.documentElement.dataset.reduce='0'},theme);await p.locator('.roster .acard').first().waitFor();
|
||||
await sp.goto('http://127.0.0.1:'+sample.address().port);await sp.evaluate(t=>{go('agents');document.documentElement.dataset.theme=t;document.documentElement.dataset.reduce='0'},theme);
|
||||
await p.screenshot({animations:"disabled",path:`${out}/home-${theme}-${width}-actual.png`});await sp.screenshot({animations:"disabled",path:`${out}/home-${theme}-${width}-sample.png`});
|
||||
measures.push({width,height,theme,page:'home',actual:await p.locator('.ahero').evaluate(e=>({width:e.offsetWidth,padding:getComputedStyle(e).padding,title:getComputedStyle(e.querySelector('h2')).fontSize,weight:getComputedStyle(e.querySelector('h2')).fontWeight})),sample:await sp.locator('.ahero').evaluate(e=>({width:e.offsetWidth,padding:getComputedStyle(e).padding,title:getComputedStyle(e.querySelector('h2')).fontSize,weight:getComputedStyle(e.querySelector('h2')).fontWeight}))});
|
||||
await p.goto(WEB+'/agents?session='+board.id);await p.locator('.shot-copy textarea').first().waitFor();await sp.evaluate(()=>go('agent-task'));
|
||||
await p.screenshot({animations:"disabled",path:`${out}/task-${theme}-${width}-actual.png`});await sp.screenshot({animations:"disabled",path:`${out}/task-${theme}-${width}-sample.png`});
|
||||
ok(`任务页成果底栏可见 ${theme} ${width}`,await p.locator('.art-f').evaluate(e=>{const r=e.getBoundingClientRect();return r.bottom<=innerHeight&&r.top>=0}));
|
||||
measures.push({width,height,theme,page:'task',actual:await p.locator('.atask').evaluate(e=>({columns:getComputedStyle(e).gridTemplateColumns,height:e.offsetHeight})),sample:await sp.locator('.atask').evaluate(e=>({columns:getComputedStyle(e).gridTemplateColumns,height:e.offsetHeight}))});
|
||||
}
|
||||
fs.writeFileSync(out+'/measurements.json',JSON.stringify(measures,null,2));ok('浏览器无运行时错误',errors.length===0);
|
||||
}finally{fs.writeFileSync(out+'/checks.json',JSON.stringify({checks,errors},null,2));await c.tracing.stop({path:out+'/trace.zip'});await b.close();await new Promise(r=>sample.close(r));}
|
||||
})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Supplemental requirements added to HEL-774: stable dialogs, focus return and unobstructed actions.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs'),assert=require('node:assert/strict'),http=require('node:http');
|
||||
const WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247',out='../evidence/stability';fs.mkdirSync(out,{recursive:true});
|
||||
const records=[],checks=[];const ok=(name,v)=>{assert(v,name);checks.push(name);console.log('PASS',name)};
|
||||
const api=async(path,body,method)=>{const r=await fetch(API+path,{method:method||(body?'POST':'GET'),headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(15000)});assert(r.ok);return r.json()};
|
||||
async function settled(p){await p.evaluate(async()=>{await document.fonts.ready;await Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})));await Promise.all([...document.images].filter(i=>!i.complete).map(i=>new Promise(r=>{i.onload=r;i.onerror=r})))})}
|
||||
(async()=>{
|
||||
const b=await chromium.launch({executablePath:process.env.CHROMIUM_EXECUTABLE_PATH,args:['--no-sandbox','--disable-dev-shm-usage']});const c=await b.newContext();await c.tracing.start({screenshots:true,snapshots:true});const p=await c.newPage();p.setDefaultTimeout(15000);
|
||||
const sample=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../attachments/夜片场-多主题交互样本.html'))});await new Promise(r=>sample.listen(0,'127.0.0.1',r));const sp=await c.newPage();
|
||||
try{
|
||||
const proj=(await api('/api/projects')).find(x=>x.title==='隔离验证 · 海岸来信');const path='/api/workbench/projects/'+proj.id+'/stages/storyboard';
|
||||
await api(path+'/confirm',{});const stage=(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard');await api(path,{content:{...stage.content,shots:stage.content.shots.map((s,i)=>i?s:{...s,description:'稳定态对比用实际草稿'})}},'PATCH');
|
||||
const sizes=(process.env.HEL774_BEFORE==='1'||process.env.HEL774_QUICK==='1')?[[1440,900]]:[[1440,900],[1366,768],[1280,720]],themes=(process.env.HEL774_BEFORE==='1'||process.env.HEL774_QUICK==='1')?['night']:['night','day','grade','bluehour'];
|
||||
for(const [width,height] of sizes)for(const theme of themes){
|
||||
const name=theme+'-'+width;await p.setViewportSize({width,height});await sp.setViewportSize({width,height});await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);await p.goto(WEB+'/workbench/'+proj.id+'?stage=storyboard');await p.locator('.storyboard-card').first().waitFor();await settled(p);
|
||||
// Modal: stable background and finished animation; close by Escape and check exact invoker.
|
||||
const compare=p.getByRole('button',{name:'对比已确认版',exact:true});await compare.click();await p.getByRole('dialog').waitFor();await settled(p);
|
||||
let style=await p.locator('.modal-panel').evaluate(e=>{const s=getComputedStyle(e);return {background:s.backgroundColor,opacity:s.opacity,transform:s.transform,float:getComputedStyle(document.documentElement).getPropertyValue('--float-bg')}});records.push({name,kind:'compare',style});await p.screenshot({path:`${out}/${name}-compare-stable.png`});ok(name+' compare opaque after animation',style.opacity==='1'&&!['rgba(0, 0, 0, 0)','transparent'].includes(style.background));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(name+' compare returns focus',await compare.evaluate(e=>document.activeElement===e));
|
||||
// Produce a real save toast, then hit-test both primary actions while it is visible.
|
||||
await p.getByRole('button',{name:'编辑',exact:true}).click();await p.locator('.shot-edit textarea').first().fill('稳定保存 '+name);await p.locator('[data-testid=stage-save-btn]').click();await p.locator('.toast.success').waitFor();await settled(p);
|
||||
const hit=await p.locator('.project-footer').evaluate(e=>{const footer=e.getBoundingClientRect();return {footerTop:footer.top,toast:[...document.querySelectorAll('.toast')].map(t=>{const r=t.getBoundingClientRect();return {top:r.top,bottom:r.bottom,left:r.left,right:r.right}}),buttons:[...e.querySelectorAll('button')].map(b=>{const r=b.getBoundingClientRect(),x=r.left+r.width/2,y=r.top+r.height/2;const top=document.elementFromPoint(x,y);return {text:b.textContent.trim(),disabled:b.disabled,centerHit:top===b||b.contains(top),topElement:top?.className}})}});records.push({name,kind:'toast',hit});await p.screenshot({path:`${out}/${name}-toast-visible.png`});
|
||||
if(process.env.HEL774_BEFORE!=='1'){
|
||||
ok(name+' toast above fixed footer',hit.toast.every(t=>t.bottom<=hit.footerTop));ok(name+' save/confirm centers hit actual buttons',hit.buttons.every(b=>b.centerHit));
|
||||
// Actual mouse save with toast present proves the overlay does not intercept it.
|
||||
await p.locator('[data-testid=stage-save-btn]').click();ok(name+' save clickable with toast',true);
|
||||
}
|
||||
await p.waitForTimeout(300);while(await p.locator('.toast .dismiss').count())await p.locator('.toast .dismiss').first().click();await p.locator('.toast').waitFor({state:'detached'});await settled(p);
|
||||
await p.locator('.project-content').evaluate(e=>e.scrollTop=e.scrollHeight);await p.screenshot({path:`${out}/${name}-long-scroll-clear-footer.png`});ok(name+' footer visible after toast clears',await p.locator('[data-testid=stage-confirm-btn]').isVisible());
|
||||
await p.goto(WEB);const search=p.locator('.studio-search');await search.click();await p.getByRole('dialog').waitFor();await settled(p);style=await p.locator('.modal-panel').evaluate(e=>{const s=getComputedStyle(e);return {background:s.backgroundColor,opacity:s.opacity,transform:s.transform}});records.push({name,kind:'search',style});await p.screenshot({path:`${out}/${name}-search-stable.png`});ok(name+' search opaque after animation',style.opacity==='1'&&!['rgba(0, 0, 0, 0)','transparent'].includes(style.background));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(name+' search returns focus',await search.evaluate(e=>document.activeElement===e));
|
||||
// Re-shoot the complete unmodified sample/app pairs on this exact final product revision.
|
||||
if(process.env.HEL774_BEFORE!=='1'){
|
||||
await sp.goto('http://127.0.0.1:'+sample.address().port);await sp.evaluate(t=>{document.documentElement.dataset.theme=t;document.documentElement.classList.add('reduce')},theme);
|
||||
for(const page of ['studio','project']){await p.goto(WEB+(page==='studio'?'/':'/workbench/'+proj.id+'?stage=storyboard'));await p.locator(page==='studio'?'.studio-hero':'.storyboard-card').first().waitFor();await sp.evaluate(page=>document.querySelectorAll('.page').forEach(e=>e.classList.toggle('on',e.id==='p-'+page)),page);await settled(p);await settled(sp);await p.mouse.move(0,0);await p.screenshot({path:`../evidence/images/${page}-${theme}-${width}-actual.png`});await sp.screenshot({path:`../evidence/images/${page}-${theme}-${width}-sample.png`})}
|
||||
}
|
||||
}
|
||||
if(process.env.HEL774_BEFORE!=='1'){
|
||||
await p.goto(WEB+'/workbench/'+proj.id+'?stage=storyboard');await p.locator('.storyboard-card').first().waitFor();
|
||||
await p.locator('[data-testid=stage-save-btn]').click();await p.locator('.toast.success').waitFor();await settled(p);await p.screenshot({path:out+'/confirm-click-with-toast.png'});
|
||||
await Promise.all([p.waitForURL('**?stage=assets'),p.locator('[data-testid=stage-confirm-btn]').click()]);
|
||||
ok('actual confirm clickable with toast and advances only explicitly',(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard').status==='confirmed');await p.screenshot({path:out+'/confirm-click-result.png'});
|
||||
}
|
||||
|
||||
}finally{fs.writeFileSync(out+(process.env.HEL774_BEFORE==='1'?'/before.json':process.env.HEL774_QUICK==='1'?'/quick-results.json':'/results.json'),JSON.stringify({records,checks},null,2));await c.tracing.stop({path:out+(process.env.HEL774_QUICK==='1'?'/quick-trace.zip':'/trace.zip')});await b.close();await new Promise(r=>sample.close(r))}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,93 @@
|
||||
// HEL-774 focused repair verification. Uses only the runner's disposable real API records.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH || 'playwright');
|
||||
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict');
|
||||
const out='../evidence', WEB='http://127.0.0.1:5173', API='http://127.0.0.1:8247';
|
||||
const resume=process.env.HEL774_ONLY_OPS==='1';
|
||||
const previous=resume?JSON.parse(fs.readFileSync('../evidence/results.json')):{checks:[]};
|
||||
const rows=resume?JSON.parse(fs.readFileSync('../evidence/measurements.json')):[],checks=previous.checks,errors=[],tags=resume?JSON.parse(fs.readFileSync('../evidence/tags.json')):[];
|
||||
const ok=(name,value)=>{assert(value,name);checks.push(name);console.log('PASS',name)};
|
||||
const api=async(path,body,method)=>{const r=await fetch(API+path,{method:method||(body?'POST':'GET'),headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined,signal:AbortSignal.timeout(15000)});assert(r.ok,await r.clone().text());return r.json()};
|
||||
const fingerprint=loc=>loc.evaluate(e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return Object.fromEntries(['backgroundColor','borderTopColor','borderTopWidth','paddingLeft','paddingRight','fontSize','fontWeight','borderRadius','transform','opacity'].map(k=>[k,s[k]]).concat([['width',r.width],['height',r.height]]))});
|
||||
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
(async()=>{
|
||||
fs.mkdirSync(out+'/images',{recursive:true});fs.mkdirSync(out+'/closeups',{recursive:true});
|
||||
const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../attachments/夜片场-多主题交互样本.html'))});
|
||||
const browser=await chromium.launch({executablePath:process.env.CHROMIUM_EXECUTABLE_PATH,args:['--no-sandbox','--disable-dev-shm-usage']});
|
||||
await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
const ctx=await browser.newContext();await ctx.tracing.start({screenshots:true,snapshots:true,sources:true});
|
||||
const p=await ctx.newPage(),sp=await ctx.newPage();p.on('pageerror',e=>errors.push(e.message));p.setDefaultTimeout(15000);
|
||||
try{
|
||||
const projects=await api('/api/projects'),proj=projects.find(x=>x.title==='隔离验证 · 海岸来信');assert(proj);
|
||||
const projectPath='/workbench/'+proj.id+'?stage=storyboard';
|
||||
if(!resume)for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.setViewportSize({width,height});await sp.setViewportSize({width,height});
|
||||
await sp.goto('http://127.0.0.1:'+server.address().port);await sp.evaluate(t=>{document.documentElement.dataset.theme=t;document.documentElement.classList.add('reduce')},theme);
|
||||
await p.goto(WEB);await p.evaluate(t=>{localStorage.setItem('aigc-theme',t)},theme);
|
||||
for(const page of ['studio','project']){
|
||||
const name=`${page}-${theme}-${width}`;
|
||||
await p.goto(WEB+(page==='studio'?'/':projectPath));await p.locator(page==='studio'?'.confirm-item':'.storyboard-card').first().waitFor();
|
||||
await sp.evaluate(v=>document.querySelectorAll('.page').forEach(e=>e.classList.toggle('on',e.id==='p-'+v)),page);
|
||||
await p.mouse.move(0,0);await sp.mouse.move(0,0);await wait(400);
|
||||
await p.screenshot({path:`${out}/images/${name}-actual.png`});await sp.screenshot({path:`${out}/images/${name}-sample.png`});
|
||||
const scope=page==='studio'?'.home':'.project-workspace';
|
||||
const selectors=await p.locator(scope+' .a-btn.secondary').evaluateAll(els=>els.map((e,i)=>({i,text:e.textContent.trim(),classes:e.className,disabled:!!e.disabled,tag:e.tagName})));
|
||||
ok(name+' secondary controls present',selectors.length>0);
|
||||
for(const item of selectors){
|
||||
const al=p.locator(scope+' .a-btn.secondary').nth(item.i);
|
||||
// Same text on a sample control, preserving the original sample's class rules.
|
||||
const id='hel774-reference';await sp.evaluate(({id,text,small})=>{document.getElementById(id)?.remove();const e=document.createElement('button');e.id=id;e.className='btn'+(small?' sm':'');e.textContent=text;e.style.position='fixed';e.style.left='100px';e.style.top='100px';document.querySelector('.page.on').append(e)}, {id,text:item.text,small:item.classes.split(' ').includes('sm')});
|
||||
const sl=sp.locator('#'+id);
|
||||
// Every actual secondary instance, including small controls. Disabled anchors are ARIA fixtures.
|
||||
for(const state of ['normal','hover','active','disabled']){
|
||||
await al.evaluate(e=>{e.removeAttribute('disabled');e.removeAttribute('aria-disabled')});await sl.evaluate(e=>e.disabled=false);
|
||||
await p.mouse.move(0,0);await sp.mouse.move(0,0);
|
||||
if(state==='disabled'){await al.evaluate(e=>e.tagName==='BUTTON'?e.disabled=true:e.setAttribute('aria-disabled','true'));await sl.evaluate(e=>e.disabled=true)}
|
||||
if(state==='hover'||state==='active'){await al.hover();await sl.hover()}
|
||||
if(state==='active'){await p.mouse.down();await sp.mouse.down()}
|
||||
await wait(220);const actual=await fingerprint(al),sample=await fingerprint(sl);
|
||||
rows.push({page,theme,width,text:item.text,classes:item.classes,state,syntheticDisabled:state==='disabled',sample,actual});
|
||||
const props=['backgroundColor','borderTopColor','borderTopWidth','paddingLeft','paddingRight','fontSize','fontWeight'];
|
||||
if(state==='active')props.push('transform');
|
||||
for(const key of props)assert.equal(actual[key],sample[key],`${name} ${item.text} ${state} ${key}`);
|
||||
if(!item.classes.includes('b3-grow'))assert(Math.abs(actual.width-sample.width)<0.05,`${name} ${item.text} ${state} width ${actual.width} vs ${sample.width}`);
|
||||
if(item.i===0 && (state==='normal'||state==='hover'||state==='disabled')){await al.screenshot({path:`${out}/closeups/${name}-${state}-actual.png`});await sl.screenshot({path:`${out}/closeups/${name}-${state}-sample.png`})}
|
||||
if(state==='active'){await p.mouse.move(0,0);await sp.mouse.move(0,0);await p.mouse.up();await sp.mouse.up()}
|
||||
}
|
||||
await al.evaluate((e,disabled)=>{e.removeAttribute('aria-disabled');if(disabled)e.setAttribute('disabled','');else e.removeAttribute('disabled')},item.disabled);await sl.evaluate(e=>e.remove());
|
||||
}
|
||||
await p.mouse.move(0,0);await sp.mouse.move(0,0);
|
||||
if(page==='studio'){
|
||||
const a=await fingerprint(p.locator('.confirm-item').first()),s=await fingerprint(sp.locator('.confirm-item').first());rows.push({page,theme,width,selector:'.confirm-item',actual:a,sample:s});ok(name+' confirmation font inherits sample 13px',a.fontSize===s.fontSize&&a.fontSize==='13px');
|
||||
await p.locator('.confirm-item').first().screenshot({path:`${out}/closeups/${name}-confirm-actual.png`});await sp.locator('.confirm-item').first().screenshot({path:`${out}/closeups/${name}-confirm-sample.png`});
|
||||
}
|
||||
const tagRows=await p.locator(scope+' .a-tag').evaluateAll(els=>els.map(e=>{const before=e.getBoundingClientRect();const saved=e.style.columnGap;e.style.columnGap='0px';const after=e.getBoundingClientRect();e.style.columnGap=saved;return {text:e.textContent.trim(),elements:e.children.length,childNodes:[...e.childNodes].filter(n=>n.nodeType!==3||n.textContent.trim()).map(n=>n.nodeType),before:before.width,after:after.width,gap:getComputedStyle(e).columnGap}}));tags.push({page,theme,width,tags:tagRows});ok(name+' single-content tags unaffected by gap',tagRows.every(t=>t.elements===0&&t.before===t.after));
|
||||
// Primary and small variants keep their own existing padding.
|
||||
ok(name+' primary padding preserved',await p.locator(scope+' .a-btn.primary').first().evaluate(e=>getComputedStyle(e).paddingLeft==='12px'));
|
||||
}
|
||||
// Keep actual empty state evidence, without manufacturing demo projects or media.
|
||||
await p.route('**/api/projects',r=>r.fulfill({json:[]}));await p.goto(WEB);await p.locator('.studio-hero').waitFor();await wait(100);await p.screenshot({path:`${out}/images/empty-${theme}-${width}.png`});ok(`empty ${theme} ${width}`,await p.locator('.studio-display').innerText().then(t=>t.includes('从一个想法开始')));await p.unroute('**/api/projects');
|
||||
}
|
||||
// Meaningful operation checks for the affected buttons, with actual API persistence.
|
||||
await p.goto(WEB);await p.locator('.studio-hero .secondary').waitFor();const heroHref=await p.locator('.studio-hero .secondary').getAttribute('href');await Promise.all([p.waitForURL(WEB+heroHref),p.locator('.studio-hero .secondary').click()]);ok('studio secondary opens real project stage',new URL(p.url()).pathname+new URL(p.url()).search===heroHref);
|
||||
await p.goto(WEB+projectPath);await p.locator('.storyboard-card').first().waitFor();await p.getByRole('button',{name:'编辑',exact:true}).click();await p.locator('.shot-edit textarea').first().fill('HEL774 次级保存按钮实际操作');ok('editing prevents stale confirmation',await p.locator('[data-testid=stage-confirm-btn]').isDisabled());await p.route('**/stages/storyboard',async route=>{if(route.request().method()==='PATCH')await wait(1000);await route.continue()});await p.locator('[data-testid=stage-save-btn]').click();await p.locator('[data-testid=stage-save-btn]:disabled').waitFor();ok('save secondary disabled while request pending',await p.locator('[data-testid=stage-save-btn]').isDisabled());await p.screenshot({path:out+'/images/operation-save-pending.png'});for(let n=0;n<50;n++){if(JSON.stringify(await api('/api/workbench/projects/'+proj.id)).includes('HEL774 次级保存按钮实际操作'))break;await wait(100)}ok('secondary saves actual edited draft',JSON.stringify(await api('/api/workbench/projects/'+proj.id)).includes('HEL774 次级保存按钮实际操作'));await p.screenshot({path:out+'/images/operation-save.png'});await p.unroute('**/stages/storyboard');
|
||||
await p.goto(WEB);await Promise.all([p.waitForURL('**/workbench/**'),p.locator('.confirm-item .secondary').first().click()]);ok('pending secondary navigates to draft',p.url().includes('/workbench/'));
|
||||
await p.goto(WEB);await p.locator('.studio-search').click();ok('search remains functional',await p.getByRole('dialog').isVisible());await p.keyboard.press('Escape');await p.keyboard.press('Control+k');ok('search shortcut preserved',await p.getByRole('dialog').isVisible());await p.keyboard.press('Escape');
|
||||
// B1/B2: compare live shared controls with exact previous shared declarations applied via CSSOM.
|
||||
const protections=[];
|
||||
for(const route of ['/create','/workflows','/tasks','/settings']){
|
||||
await p.goto(WEB+route);await wait(800);
|
||||
ok(route+' sidebar retained',await p.locator('aside.sidebar').isVisible());
|
||||
for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.mouse.move(0,0);await p.evaluate(t=>document.documentElement.dataset.theme=t,theme);await wait(600);
|
||||
const buttons=p.locator('.a-btn:visible');const count=await buttons.count();
|
||||
const baseline=await buttons.evaluateAll(es=>es.map(e=>{const s=getComputedStyle(e),b=e.getBoundingClientRect();return {text:e.textContent.trim(),bg:s.backgroundColor,border:s.borderTopColor,pad:s.paddingLeft,width:b.width,height:b.height,font:s.fontSize}}));
|
||||
await p.evaluate(()=>{window.hel774Rules=[];for(const sheet of document.styleSheets){let rules;try{rules=sheet.cssRules}catch{continue}for(const r of rules){if(!r.selectorText)continue;const sel=r.selectorText;if(sel==='.a-btn'){window.hel774Rules.push([r,r.style.cssText]);r.style.padding='0 var(--sp-6)'}if(sel==='.a-btn.secondary'){window.hel774Rules.push([r,r.style.cssText]);r.style.borderColor='var(--line)';r.style.removeProperty('--button-padding');r.style.removeProperty('--button-active-transform')}}}});
|
||||
const previous=await buttons.evaluateAll(es=>es.map(e=>{const s=getComputedStyle(e),b=e.getBoundingClientRect();return {text:e.textContent.trim(),bg:s.backgroundColor,border:s.borderTopColor,pad:s.paddingLeft,width:b.width,height:b.height,font:s.fontSize}}));
|
||||
await p.evaluate(()=>window.hel774Rules.forEach(([r,css])=>r.style.cssText=css));assert.deepEqual(baseline,previous,route+' default controls changed');protections.push({route,theme,count,baseline,previous});
|
||||
await p.screenshot({path:`${out}/images/protect-${route.slice(1)}-${theme}.png`});
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(out+'/protections.json',JSON.stringify(protections,null,2));
|
||||
ok('no browser errors',errors.length===0);
|
||||
}finally{fs.writeFileSync(out+'/measurements.json',JSON.stringify(rows,null,2));fs.writeFileSync(out+'/tags.json',JSON.stringify(tags,null,2));fs.writeFileSync(out+'/results.json',JSON.stringify({checks,errors},null,2));await ctx.tracing.stop({path:out+'/interaction-trace.zip'});await browser.close();await new Promise(r=>server.close(r))}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,93 @@
|
||||
// HEL-776: real isolated pages; sample controls are state fixtures, never product data.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright');
|
||||
const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict'),cp=require('node:child_process');
|
||||
const out='../evidence',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247';
|
||||
const rows=[],checks=[],errors=[],protections=[];
|
||||
const ok=(name,v)=>{assert(v,name);checks.push(name);console.log('PASS',name)};
|
||||
const wait=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
const api=async(path,body,method)=>{const r=await fetch(API+path,{method:method||(body?'POST':'GET'),headers:{'Content-Type':'application/json'},body:body?JSON.stringify(body):undefined});assert(r.ok,await r.clone().text());return r.json()};
|
||||
const style=loc=>loc.evaluate(e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return Object.fromEntries(['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','paddingLeft','paddingRight','fontSize','fontWeight','borderTopColor','borderTopWidth','transform'].map(k=>[k,s[k]]).concat([['height',r.height]]))});
|
||||
async function settled(p){await p.evaluate(async()=>{await document.fonts.ready;await Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{})))});await wait(180)}
|
||||
(async()=>{
|
||||
fs.mkdirSync(out+'/closeups',{recursive:true});fs.mkdirSync(out+'/operations',{recursive:true});
|
||||
const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../materials/夜片场-多主题交互样本.html'))});await new Promise(r=>server.listen(0,'127.0.0.1',r));
|
||||
const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']});const c=await b.newContext();await c.tracing.start({screenshots:process.env.HEL776_PROTECT_ONLY!=='1',snapshots:true,sources:true});
|
||||
const p=await c.newPage(),sp=await c.newPage();p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message));
|
||||
const proj=(await api('/api/projects')).find(x=>x.title==='隔离验证 · 海岸来信'),path='/api/workbench/projects/'+proj.id+'/stages/storyboard',url=WEB+'/workbench/'+proj.id+'?stage=storyboard';
|
||||
try{
|
||||
if(process.env.HEL776_PROTECT_ONLY!=='1'){
|
||||
for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.setViewportSize({width,height});await sp.setViewportSize({width,height});await sp.goto('http://127.0.0.1:'+server.address().port);await sp.evaluate(t=>document.documentElement.dataset.theme=t,theme);
|
||||
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);
|
||||
for(const page of ['studio','project']){
|
||||
await p.goto(page==='studio'?WEB:url);await p.locator(page==='studio'?'.studio-hero':'.storyboard-card').first().waitFor();await settled(p);
|
||||
const scope=page==='studio'?'.home':'.project-workspace';
|
||||
const controls=p.locator(scope+' .a-btn.secondary');
|
||||
for(let i=0;i<await controls.count();i++){
|
||||
const al=controls.nth(i),item=await al.evaluate(e=>({text:e.textContent.trim(),small:e.classList.contains('sm'),disabled:e.disabled,aria:e.getAttribute('aria-disabled')}));
|
||||
await sp.evaluate(item=>{document.querySelector('#fixture')?.remove();const e=document.createElement('button');e.id='fixture';e.className='btn'+(item.small?' sm':'');e.textContent=item.text;Object.assign(e.style,{position:'fixed',left:'100px',top:'100px'});document.body.append(e)},item);
|
||||
const sl=sp.locator('#fixture');
|
||||
for(const state of ['normal','hover','active']){
|
||||
await al.evaluate(e=>{e.removeAttribute('disabled');e.removeAttribute('aria-disabled')});await p.mouse.move(0,0);await sp.mouse.move(0,0);
|
||||
if(state!=='normal'){await al.hover();await sl.hover()}if(state==='active'){await p.mouse.down();await sp.mouse.down()}
|
||||
await wait(180);const actual=await style(al),sample=await style(sl);rows.push({page,theme,width,text:item.text,small:item.small,state,actual,sample});
|
||||
for(const k of ['backgroundColor','borderTopColor','borderTopWidth','borderRadius','paddingLeft','paddingRight','fontSize','fontWeight','height',...(state==='active'?['transform']:[])])assert.equal(actual[k],sample[k],`${page}/${theme}/${width}/${item.text}/${state}/${k}`);
|
||||
if(state==='active'){await p.mouse.move(0,0);await sp.mouse.move(0,0);await p.mouse.up();await sp.mouse.up()}
|
||||
}
|
||||
await al.evaluate((e,item)=>{if(item.disabled)e.setAttribute('disabled','');if(item.aria!==null)e.setAttribute('aria-disabled',item.aria)},item);
|
||||
}
|
||||
ok(`${page} ${theme} ${width}: every normal/small secondary normal/hover/active equals sample`,true);
|
||||
}
|
||||
// Native disabled confirmation caused by an actual unsaved edit, then actual save restores it.
|
||||
await p.goto(url);await p.locator('.storyboard-card').first().waitFor();await p.getByRole('button',{name:'编辑',exact:true}).click();await p.locator('.shot-edit textarea').first().fill('HEL776 '+theme+' '+width);
|
||||
const confirm=p.locator('[data-testid=stage-confirm-btn]');ok(`${theme} ${width} unsaved draft disables confirmation`,await confirm.isDisabled());
|
||||
let confirms=0;const onRequest=req=>{if(req.method()==='POST'&&req.url().endsWith('/stages/storyboard/confirm'))confirms++};p.on('request',onRequest);
|
||||
await sp.evaluate(text=>{document.querySelector('#fixture')?.remove();const e=document.createElement('button');e.id='fixture';e.className='btn primary';e.textContent=text;e.disabled=true;Object.assign(e.style,{position:'fixed',left:'100px',top:'100px'});document.body.append(e)},await confirm.innerText());
|
||||
for(const state of ['disabled','enabled']){
|
||||
if(state==='enabled'){
|
||||
await p.locator('[data-testid=stage-save-btn]').click();await p.locator('.toast.success').waitFor();await p.waitForFunction(()=>!document.querySelector('[data-testid=stage-confirm-btn]').disabled);await sp.locator('#fixture').evaluate(e=>e.disabled=false);
|
||||
ok(`${theme} ${width} save actually persists draft`,JSON.stringify(await api('/api/workbench/projects/'+proj.id)).includes('HEL776 '+theme+' '+width));
|
||||
}
|
||||
await p.mouse.move(0,0);await sp.mouse.move(0,0);await settled(p);const actual=await style(confirm),sample=await style(sp.locator('#fixture'));rows.push({page:'project',theme,width,kind:'primary',state,actual,sample});
|
||||
for(const k of ['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','height','paddingLeft','fontSize'])assert.equal(actual[k],sample[k],`${theme}/${width}/primary/${state}/${k}`);
|
||||
if(width===1440){await confirm.screenshot({path:`${out}/closeups/${theme}-${state}-actual.png`});await sp.locator('#fixture').screenshot({path:`${out}/closeups/${theme}-${state}-sample.png`});await p.screenshot({path:`${out}/operations/${theme}-${state}.png`})}
|
||||
if(state==='disabled'){
|
||||
const r=await confirm.boundingBox();await p.mouse.click(r.x+r.width/2,r.y+r.height/2);await confirm.evaluate(e=>e.click());await wait(150);ok(`${theme} ${width} disabled native click sends zero requests`,confirms===0);
|
||||
}
|
||||
}
|
||||
const hits=await p.locator('.project-footer').evaluate(e=>{const top=e.getBoundingClientRect().top;return {top,toasts:[...document.querySelectorAll('.toast')].map(t=>t.getBoundingClientRect().bottom),buttons:[...e.querySelectorAll('button')].map(b=>{const r=b.getBoundingClientRect(),hit=document.elementFromPoint(r.x+r.width/2,r.y+r.height/2);return b===hit||b.contains(hit)})}});
|
||||
ok(`${theme} ${width} toast avoids footer and actions remain hittable`,hits.buttons.every(Boolean)&&hits.toasts.every(bottom=>bottom<=hits.top));
|
||||
// Bound pending confirmation to verify native duplicate prevention; release to real API.
|
||||
let release;const gate=new Promise(r=>release=r);await p.route('**/stages/storyboard/confirm',async r=>{await gate;await r.continue()});
|
||||
const response=p.waitForResponse(r=>r.url().endsWith('/stages/storyboard/confirm')&&r.request().method()==='POST');await confirm.click();await p.locator('[data-testid=stage-confirm-btn]:disabled').waitFor();await confirm.evaluate(e=>e.click());ok(`${theme} ${width} pending confirmation sends one request`,confirms===1);release();assert((await response).ok());await p.waitForURL('**?stage=assets');p.off('request',onRequest);await p.unroute('**/stages/storyboard/confirm');
|
||||
ok(`${theme} ${width} confirmation succeeds after save`,(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard').status==='confirmed');
|
||||
// Restore awaiting_confirm through the real draft API, never through a status fixture.
|
||||
const data=(await api('/api/workbench/projects/'+proj.id)).stages.find(s=>s.stage_key==='storyboard');await api(path,{content:{...data.content,shots:data.content.shots.map((s,i)=>i?s:{...s,description:s.description+' · next'})}},'PATCH');
|
||||
}
|
||||
// Search + comparison focus and stable panel regression, all themes at 1440.
|
||||
await p.setViewportSize({width:1440,height:900});
|
||||
for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);await p.reload();const trigger=p.locator('.studio-search');await trigger.click();await p.getByRole('dialog').waitFor();await settled(p);ok(theme+' search stable opacity',await p.locator('.modal-panel').evaluate(e=>getComputedStyle(e).opacity==='1'));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(theme+' search focus restored',await trigger.evaluate(e=>e===document.activeElement));
|
||||
await p.goto(url);const compare=p.getByRole('button',{name:'对比已确认版',exact:true});await compare.click();await p.getByRole('dialog').waitFor();await settled(p);ok(theme+' compare stable opacity',await p.locator('.modal-panel').evaluate(e=>getComputedStyle(e).opacity==='1'));await p.keyboard.press('Escape');await p.getByRole('dialog').waitFor({state:'detached'});ok(theme+' compare focus restored',await compare.evaluate(e=>e===document.activeElement));
|
||||
}
|
||||
}
|
||||
// Compare each live B1/B2 control with the exact pre-repair shared CSS in the same DOM.
|
||||
const old=cp.execFileSync('git',['show','930cca6:calliope-web/src/routes/app.css'],{encoding:'utf8'});
|
||||
for(const route of ['/create','/workflows','/tasks','/settings','/models'])for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.goto(WEB+route);await p.locator('aside.sidebar').waitFor();await p.evaluate(t=>document.documentElement.dataset.theme=t,theme);await wait(600);await p.mouse.move(0,0);ok(route+' '+theme+' sidebar present',await p.locator('aside.sidebar').isVisible());
|
||||
const read=()=>p.locator('.a-btn').evaluateAll(es=>es.map(e=>{const s=getComputedStyle(e);return {text:e.textContent.trim(),classes:e.className,style:Object.fromEntries(['opacity','filter','backgroundColor','backgroundImage','color','boxShadow','borderRadius','paddingLeft','height','fontSize'].map(k=>[k,s[k]]))}}));
|
||||
await p.evaluate(()=>{const host=document.createElement('div');host.id='hel776-default-fixtures';for(const classes of ['primary','primary sm','secondary','secondary sm'])for(const state of ['enabled','disabled','aria-disabled']){const b=document.createElement('button');b.className='a-btn '+classes;b.textContent=classes+' '+state;if(state==='disabled')b.disabled=true;if(state==='aria-disabled')b.setAttribute('aria-disabled','true');host.append(b)}document.body.append(host)});
|
||||
const actual=await read();await p.evaluate(()=>{window.hel776StateRules=[];for(const sheet of document.styleSheets){let rules;try{rules=sheet.cssRules}catch{continue}for(const r of rules)if(r.selectorText?.includes('.a-btn.primary:disabled')){window.hel776StateRules.push([r,r.style.cssText]);r.style.cssText=''}}});const oldSheet=await p.addStyleTag({content:old});await wait(200);const previous=await read();assert.deepEqual(actual,previous,route+' '+theme+' default controls');await oldSheet.evaluate(e=>e.remove());await p.evaluate(()=>{window.hel776StateRules.forEach(([r,s])=>r.style.cssText=s);document.querySelector('#hel776-default-fixtures').remove()});protections.push({route,theme,actual,previous});
|
||||
}
|
||||
if(process.env.HEL776_PROTECT_ONLY==='1')for(const theme of ['night','day','grade','bluehour']){
|
||||
await p.goto(WEB);await p.evaluate(t=>localStorage.setItem('aigc-theme',t),theme);await p.reload();await p.locator('.studio-hero').waitFor();await settled(p);
|
||||
const al=p.locator('.home .a-btn.secondary.sm').first();await sp.goto('http://127.0.0.1:'+server.address().port);await sp.evaluate(({theme,text})=>{document.documentElement.dataset.theme=theme;const e=document.createElement('button');e.className='btn sm';e.id='small';e.textContent=text;document.body.append(e)}, {theme,text:await al.innerText()});await al.screenshot({path:out+'/closeups/'+theme+'-small-actual.png'});await sp.locator('#small').screenshot({path:out+'/closeups/'+theme+'-small-sample.png'});
|
||||
}
|
||||
ok('no browser page errors',errors.length===0);
|
||||
}finally{
|
||||
fs.writeFileSync(out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-measurements.json':'/measurements.json'),JSON.stringify(rows,null,2));fs.writeFileSync(out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-results.json':'/results.json'),JSON.stringify({checks,errors,protections},null,2));
|
||||
await c.tracing.stop({path:out+(process.env.HEL776_PROTECT_ONLY==='1'?'/protection-trace.zip':'/trace.zip')});console.log('TRACE_SAVED');
|
||||
// Bound browser shutdown; always collect an exit code instead of hanging after evidence.
|
||||
await Promise.race([b.close(),wait(5000).then(()=>{if(b.isConnected())throw Error('browser shutdown exceeded 5s')})]);await new Promise(r=>server.close(r));
|
||||
}
|
||||
})().then(()=>process.exit(0)).catch(e=>{console.error(e);process.exit(1)});
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Run the isolated regression stack in the foreground and always stop children."""
|
||||
import os, signal, socket, subprocess, time, urllib.request
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
os.chdir(root)
|
||||
py=os.environ.get('HEL731_PYTHON', 'python3')
|
||||
logs=root/'e2e/shots/hel731'; logs.mkdir(parents=True,exist_ok=True)
|
||||
env=os.environ.copy()
|
||||
env['PYTHONPATH']=str(root/'calliope-backend/src')
|
||||
for port in [8247,5173,18188,18189]:
|
||||
with socket.socket() as probe:
|
||||
assert probe.connect_ex(('127.0.0.1',port)) != 0, f'Test port {port} is already in use'
|
||||
# Every run gets fresh disposable state; retain prior evidence instead of deleting it.
|
||||
reference=root/'e2e/shots/reference'
|
||||
if reference.exists():reference.rename(reference.with_name('reference.previous-'+str(time.time_ns())))
|
||||
mode_path=root/'e2e/fake_mode.json'
|
||||
saved_mode=mode_path.read_bytes() if mode_path.exists() else None
|
||||
processes=[]; handles=[]
|
||||
try:
|
||||
for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/reference/fake_llm.py']),('web',['npm','--prefix',os.environ.get('HEL731_WEB_DIR',os.environ.get('HEL729_WEB_DIR','calliope-web')),'run','dev'])]:
|
||||
h=open(logs/(name+'.log'),'w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True))
|
||||
for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']:
|
||||
for i in range(100):
|
||||
try:
|
||||
urllib.request.urlopen(url,timeout=2); break
|
||||
except Exception:
|
||||
if any(p.poll() is not None for p in processes): raise RuntimeError('A test service failed')
|
||||
if i==99:raise
|
||||
time.sleep(.2)
|
||||
for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True)
|
||||
failures=[]
|
||||
scripts=os.environ.get('HEL731_TESTS',os.environ.get('HEL729_TESTS','e2e/hel731.cjs')).split(',')
|
||||
for script in scripts:
|
||||
print('RUN',script,flush=True)
|
||||
result=subprocess.run(['node',script],env=env)
|
||||
if result.returncode:failures.append(script)
|
||||
print('FAILED SCRIPTS',failures,flush=True)
|
||||
if failures:raise SystemExit(1)
|
||||
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:os.killpg(p.pid,signal.SIGTERM)
|
||||
for p in processes:
|
||||
try:p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
|
||||
for h in handles:h.close()
|
||||
|
||||
if saved_mode is not None:mode_path.write_bytes(saved_mode)
|
||||
elif mode_path.exists():mode_path.unlink()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Run the isolated regression stack in the foreground and always stop children."""
|
||||
import os, signal, socket, subprocess, time, urllib.request
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
os.chdir(root)
|
||||
py=os.environ.get('HEL732_PYTHON', 'python3')
|
||||
logs=root/'e2e/shots/hel732'; logs.mkdir(parents=True,exist_ok=True)
|
||||
env=os.environ.copy()
|
||||
env['PYTHONPATH']=str(root/'calliope-backend/src')
|
||||
for port in [8247,5173,18188,18189]:
|
||||
with socket.socket() as probe:
|
||||
assert probe.connect_ex(('127.0.0.1',port)) != 0, f'Test port {port} is already in use'
|
||||
# Every run gets fresh disposable state; retain prior evidence instead of deleting it.
|
||||
reference=root/'e2e/shots/reference'
|
||||
reuse_fixture=os.environ.get('HEL732_REUSE_FIXTURE')=='1'
|
||||
if reference.exists() and not reuse_fixture:reference.rename(reference.with_name('reference.previous-'+str(time.time_ns())))
|
||||
mode_path=root/'e2e/fake_mode.json'
|
||||
saved_mode=mode_path.read_bytes() if mode_path.exists() else None
|
||||
processes=[]; handles=[]
|
||||
try:
|
||||
for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/fake_agent_b4.py']),('web',['npm','--prefix',os.environ.get('HEL732_WEB_DIR',os.environ.get('HEL729_WEB_DIR','calliope-web')),'run','dev'])]:
|
||||
h=open(logs/(name+'.log'),'w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True))
|
||||
for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']:
|
||||
for i in range(100):
|
||||
try:
|
||||
urllib.request.urlopen(url,timeout=2); break
|
||||
except Exception:
|
||||
if any(p.poll() is not None for p in processes): raise RuntimeError('A test service failed')
|
||||
if i==99:raise
|
||||
time.sleep(.2)
|
||||
if not reuse_fixture:
|
||||
for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True)
|
||||
failures=[]
|
||||
scripts=os.environ.get('HEL732_TESTS',os.environ.get('HEL729_TESTS','e2e/hel732.cjs')).split(',')
|
||||
for script in scripts:
|
||||
print('RUN',script,flush=True)
|
||||
result=subprocess.run(['node',script],env=env)
|
||||
if result.returncode:failures.append(script)
|
||||
print('FAILED SCRIPTS',failures,flush=True)
|
||||
if failures:raise SystemExit(1)
|
||||
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:os.killpg(p.pid,signal.SIGTERM)
|
||||
for p in processes:
|
||||
try:p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
|
||||
print("STOPPED TEST CHILDREN", [{"pid":p.pid,"exit":p.returncode} for p in processes],flush=True)
|
||||
for h in handles:h.close()
|
||||
|
||||
if saved_mode is not None:mode_path.write_bytes(saved_mode)
|
||||
elif mode_path.exists():mode_path.unlink()
|
||||
@@ -0,0 +1,56 @@
|
||||
"""HEL-773: run the isolated stack, keep it alive for the audit script, then stop children."""
|
||||
import os, signal, socket, subprocess, time, urllib.request
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
os.chdir(root)
|
||||
(root/'e2e/shots/hel731').mkdir(parents=True,exist_ok=True)
|
||||
py=os.environ.get('HEL731_PYTHON','python3')
|
||||
env=os.environ.copy()
|
||||
env['PYTHONPATH']=str(root/'calliope-backend/src')
|
||||
for port in [8247,5173,18188,18189]:
|
||||
with socket.socket() as probe:
|
||||
assert probe.connect_ex(('127.0.0.1',port))!=0, f'Test port {port} is already in use'
|
||||
reference=root/'e2e/shots/reference'
|
||||
if reference.exists():reference.rename(reference.with_name('reference.previous-'+str(time.time_ns())))
|
||||
processes=[];handles=[]
|
||||
try:
|
||||
for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/reference/fake_llm.py']),('web',['npm','--prefix','calliope-web','run','dev'])]:
|
||||
h=open(f'../evidence/checks/{name}.log','w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True))
|
||||
for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']:
|
||||
for i in range(100):
|
||||
try:
|
||||
urllib.request.urlopen(url,timeout=2);break
|
||||
except Exception:
|
||||
if any(p.poll() is not None for p in processes):raise RuntimeError('A test service failed')
|
||||
if i==99:raise
|
||||
time.sleep(.2)
|
||||
for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True)
|
||||
# seed one project with storyboard content like hel731.cjs does
|
||||
import json,urllib.request as u
|
||||
def api(p,b=None,method=None):
|
||||
req=u.Request('http://127.0.0.1:8247'+p,data=json.dumps(b).encode() if b is not None else None,method=method or ('POST' if b is not None else 'GET'),headers={'Content-Type':'application/json'})
|
||||
return json.loads(u.urlopen(req, timeout=15).read())
|
||||
proj=api('/api/projects',{'title':'隔离验证 · 海岸来信','idea':'纸船带回一片树叶'})
|
||||
fixtures={'script':{'text':'第一场:清晨的海岸,女孩把一只纸船放入海水。她等候着父亲的归来。第二场:纸船带回一片树叶,女孩望向海平面,知道旅程才刚刚开始。'},
|
||||
'style':{'directions':[{'id':'s1','name':'晨光','description':'暖光','prompt':'warm light'},{'id':'s2','name':'蓝调','description':'冷光','prompt':'blue hour'}]},
|
||||
'storyboard':{'shots':[{'id':'board-'+str(i),'scene':'1','shot_size':'远景','camera':'固定','description':'女孩沿着海岸走向灯塔,纸船随海风起伏。','dialog':('你好' if i%2 else ''),'duration_sec':5} for i in range(12)]},
|
||||
'assets':{'assets':[{'id':'asset-a','kind':'character','name':'海边女孩','description':'女孩','prompt':'girl on coast'}]},
|
||||
'shot':{'shots':[{'id':'shot-a','shot_no':'S1','description':'女孩走向灯塔','prompt':'girl walks toward lighthouse','duration_sec':4}]}}
|
||||
for stage,content in fixtures.items():
|
||||
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}",{'content':content},'PATCH')
|
||||
if stage in ('script','style'):
|
||||
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}/confirm",({'chosen_style_id':'s1'} if stage=='style' else {}))
|
||||
print('stack ready, project',proj['id'])
|
||||
result=subprocess.run(['node',os.environ.get('HEL774_SCRIPT','e2e/hel774.cjs')],env=env)
|
||||
print('TEST_PROCESS_EXIT',result.returncode,flush=True)
|
||||
raise SystemExit(result.returncode)
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:os.killpg(p.pid,signal.SIGTERM)
|
||||
for p in processes:
|
||||
try:p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
|
||||
for h in handles:h.close()
|
||||
import shutil
|
||||
if reference.exists():shutil.rmtree(reference)
|
||||
print('CLEANUP: all exact child process groups stopped; disposable reference DB removed',flush=True)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""HEL-776: run the isolated stack, keep it alive for the audit script, then stop children."""
|
||||
import os, signal, socket, subprocess, time, urllib.request
|
||||
from pathlib import Path
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
os.chdir(root)
|
||||
(root/'e2e/shots/hel731').mkdir(parents=True,exist_ok=True)
|
||||
py=os.environ.get('HEL731_PYTHON','python3')
|
||||
env=os.environ.copy()
|
||||
env['PYTHONPATH']=str(root/'calliope-backend/src')
|
||||
for port in [8247,5173,18188,18189]:
|
||||
with socket.socket() as probe:
|
||||
assert probe.connect_ex(('127.0.0.1',port))!=0, f'Test port {port} is already in use'
|
||||
reference=root/'e2e/shots/reference'
|
||||
assert not reference.exists(), 'Refuse to overwrite existing isolation data'
|
||||
processes=[];handles=[]
|
||||
try:
|
||||
for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/reference/fake_llm.py']),('web',['npm','--prefix','calliope-web','run','dev'])]:
|
||||
h=open(f'../evidence/checks/{name}.log','w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True))
|
||||
for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']:
|
||||
for i in range(100):
|
||||
try:
|
||||
urllib.request.urlopen(url,timeout=2);break
|
||||
except Exception:
|
||||
if any(p.poll() is not None for p in processes):raise RuntimeError('A test service failed')
|
||||
if i==99:raise
|
||||
time.sleep(.2)
|
||||
for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True)
|
||||
# seed one project with storyboard content like hel731.cjs does
|
||||
import json,urllib.request as u
|
||||
def api(p,b=None,method=None):
|
||||
req=u.Request('http://127.0.0.1:8247'+p,data=json.dumps(b).encode() if b is not None else None,method=method or ('POST' if b is not None else 'GET'),headers={'Content-Type':'application/json'})
|
||||
return json.loads(u.urlopen(req, timeout=15).read())
|
||||
proj=api('/api/projects',{'title':'隔离验证 · 海岸来信','idea':'纸船带回一片树叶'})
|
||||
fixtures={'script':{'text':'第一场:清晨的海岸,女孩把一只纸船放入海水。她等候着父亲的归来。第二场:纸船带回一片树叶,女孩望向海平面,知道旅程才刚刚开始。'},
|
||||
'style':{'directions':[{'id':'s1','name':'晨光','description':'暖光','prompt':'warm light'},{'id':'s2','name':'蓝调','description':'冷光','prompt':'blue hour'}]},
|
||||
'storyboard':{'shots':[{'id':'board-'+str(i),'scene':'1','shot_size':'远景','camera':'固定','description':'女孩沿着海岸走向灯塔,纸船随海风起伏。','dialog':('你好' if i%2 else ''),'duration_sec':5} for i in range(12)]},
|
||||
'assets':{'assets':[{'id':'asset-a','kind':'character','name':'海边女孩','description':'女孩','prompt':'girl on coast'}]},
|
||||
'shot':{'shots':[{'id':'shot-a','shot_no':'S1','description':'女孩走向灯塔','prompt':'girl walks toward lighthouse','duration_sec':4}]}}
|
||||
for stage,content in fixtures.items():
|
||||
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}",{'content':content},'PATCH')
|
||||
if stage in ('script','style'):
|
||||
api(f"/api/workbench/projects/{proj['id']}/stages/{stage}/confirm",({'chosen_style_id':'s1'} if stage=='style' else {}))
|
||||
print('stack ready, project',proj['id'],flush=True)
|
||||
Path('../evidence/checks/processes.json').write_text(json.dumps([{'pid':p.pid,'args':p.args} for p in processes],indent=2))
|
||||
result=subprocess.run(['node','e2e/hel776.cjs'],env=env)
|
||||
print('TEST_PROCESS_EXIT',result.returncode,flush=True)
|
||||
raise SystemExit(result.returncode)
|
||||
finally:
|
||||
daemon=json.loads(subprocess.check_output(['multica','daemon','status','--output','json']))['pid']
|
||||
assert all(p.pid != daemon for p in processes)
|
||||
for p in processes:
|
||||
if p.poll() is None:os.killpg(p.pid,signal.SIGTERM)
|
||||
for p in processes:
|
||||
try:p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait()
|
||||
for h in handles:h.close()
|
||||
import shutil
|
||||
if reference.exists():shutil.rmtree(reference)
|
||||
print('CLEANUP: all exact child process groups stopped; disposable reference DB removed',flush=True)
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Compare the unmodified captures and DOM measurements from verify-hel771.mjs."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageChops, ImageDraw
|
||||
|
||||
OUT = Path(os.environ.get('HEL771_OUT', Path(__file__).resolve().parents[2] / 'evidence' / 'tiles'))
|
||||
r = json.loads((OUT / 'measurements.json').read_text())
|
||||
summary = {'groups': len(r['groups']), 'differences': [], 'pixels': []}
|
||||
|
||||
def compare(a,b,prefix):
|
||||
if isinstance(a,dict):
|
||||
for k in a:
|
||||
if k in ('cardClass','ariaChecked'): continue
|
||||
compare(a[k],b[k],prefix+'.'+k)
|
||||
elif isinstance(a,list):
|
||||
if len(a)!=len(b): summary['differences'].append([prefix,a,b])
|
||||
else:
|
||||
for i,(x,y) in enumerate(zip(a,b)): compare(x,y,f'{prefix}.{i}')
|
||||
elif a!=b:
|
||||
summary['differences'].append([prefix,a,b])
|
||||
|
||||
for g in r['groups']:
|
||||
compare(g['app'],g['sample'],g['name'])
|
||||
a=Image.open(OUT/(g['name']+'-app.png')).convert('RGB')
|
||||
b=Image.open(OUT/(g['name']+'-sample.png')).convert('RGB')
|
||||
assert a.size==b.size
|
||||
d=ImageChops.difference(a,b)
|
||||
pixels=sum(1 for p in d.get_flattened_data() if p!=(0,0,0))
|
||||
summary['pixels'].append({'name':g['name'],'different_pixels':pixels,'total_pixels':a.width*a.height,'max_channel_delta':max(x[1] for x in d.getextrema())})
|
||||
if g['width']==1440 and g['theme']=='night' and g['card'] in (0,1):
|
||||
pair=Image.new('RGB',(a.width*2,a.height+24),'#151515')
|
||||
ImageDraw.Draw(pair).text((5,5),'Original (left) / App (right)',fill='white')
|
||||
pair.paste(b,(0,24));pair.paste(a,(a.width,24))
|
||||
pair.resize((pair.width*3,pair.height*3),Image.Resampling.NEAREST).save(OUT/(g['name']+'-pair-3x.png'))
|
||||
for p in OUT.glob('*-full-app.png'):
|
||||
a=Image.open(p);b=Image.open(str(p).replace('-app.png','-sample.png'))
|
||||
pair=Image.new('RGB',(a.width*2,a.height+24),'#151515')
|
||||
ImageDraw.Draw(pair).text((8,5),'Original (left) / App (right)',fill='white')
|
||||
pair.paste(b,(0,24));pair.paste(a,(a.width,24));pair.save(str(p).replace('-app.png','-pair.png'))
|
||||
(OUT/'comparison.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2))
|
||||
print('groups:',len(r['groups']),'DOM differences:',len(summary['differences']),'pixel-identical:',sum(p['different_pixels']==0 for p in summary['pixels']))
|
||||
print(json.dumps(summary['differences'][:8],ensure_ascii=False,indent=2))
|
||||
assert not summary['differences'], 'DOM mismatch'
|
||||
# Pixel statistics are evidence, not a hidden tolerance gate: retain every raw pair.
|
||||
print('Non-identical raw pairs:', json.dumps([p for p in summary['pixels'] if p['different_pixels']], ensure_ascii=False))
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Package B3 evidence without changing or retouching application screenshots."""
|
||||
import csv
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from PIL import Image
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
source = root / 'e2e/shots/hel731'
|
||||
out = root.parent / 'evidence/hel731'
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
for path in source.iterdir():
|
||||
if path.is_file() and path.name != 'interaction-trace.zip':
|
||||
shutil.copy2(path, out / path.name)
|
||||
for actual in out.glob('*-actual.png'):
|
||||
reference = actual.with_name(actual.name.replace('-actual', '-sample'))
|
||||
left, right = Image.open(reference), Image.open(actual)
|
||||
pair = Image.new('RGB', (left.width + right.width, max(left.height, right.height)))
|
||||
pair.paste(left, (0, 0)); pair.paste(right, (left.width, 0))
|
||||
pair.save(actual.with_name(actual.name.replace('-actual', '-pair')))
|
||||
measurements = json.loads((source / 'measurements.json').read_text())
|
||||
with (out / 'measurements.csv').open('w', newline='') as handle:
|
||||
writer = csv.writer(handle)
|
||||
writer.writerow(['page', 'theme', 'viewport', 'selector', 'property', 'sample', 'actual', 'delta'])
|
||||
for row in measurements:
|
||||
for key, sample in row['sample'].items():
|
||||
actual = row['actual'][key]
|
||||
delta = round(actual - sample, 5) if isinstance(sample, (int, float)) else ''
|
||||
writer.writerow([row['page'], row['theme'], row['width'], row['selector'], key, sample, actual, delta])
|
||||
logs = out / 'checks'; logs.mkdir(exist_ok=True)
|
||||
for name in ['lint-b3.log', 'check-b3.log', 'build-b3.log', 'pytest-b3.log', 'frontend-test-b3.log', 'browser-b3.log', 'final-browser-b3.log', 'related-browser-b3.log', 'normalize-b3.log', 'theme-regression-b3.log']:
|
||||
shutil.copy2(root / name, logs / name)
|
||||
for suite in ['hel729', 'hel742']:
|
||||
shutil.copy2(root / f'e2e/shots/{suite}/results.json', logs / f'{suite}-results.json')
|
||||
shutil.copy2(root.parent / 'attachments/夜片场-多主题交互样本.html', out / 'approved-sample.html')
|
||||
print('Evidence copied to', out.name)
|
||||
@@ -0,0 +1,996 @@
|
||||
/** Run via verify-hel769.py; explicit API fake, local-only origins, no user data. */
|
||||
import fs from "node:fs/promises";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
const { chromium } = await import(
|
||||
process.env.PLAYWRIGHT_MODULE || "playwright"
|
||||
);
|
||||
const out = process.env.HEL769_OUT,
|
||||
data = process.env.HEL769_DATA;
|
||||
const fixture = JSON.parse(
|
||||
await fs.readFile(path.join(data, "fixtures.json"), "utf8"),
|
||||
);
|
||||
let jobs = structuredClone(fixture.jobs),
|
||||
apiError = false,
|
||||
imageFixture;
|
||||
const result = {
|
||||
checks: [],
|
||||
measurements: [],
|
||||
errors: [],
|
||||
mutations: [],
|
||||
externalBlocked: [],
|
||||
apiReads: [],
|
||||
};
|
||||
const check = (v, n) => {
|
||||
result.checks.push({ name: n, pass: !!v });
|
||||
if (!v) throw Error(n);
|
||||
};
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const p = new URL(req.url, "http://local").pathname;
|
||||
let f = path.join("calliope-web/build", decodeURIComponent(p));
|
||||
if (!path.extname(f)) f = path.join("calliope-web/build", "index.html");
|
||||
const bytes = await fs.readFile(f);
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
f.endsWith(".js")
|
||||
? "text/javascript"
|
||||
: f.endsWith(".css")
|
||||
? "text/css"
|
||||
: f.endsWith(".html")
|
||||
? "text/html"
|
||||
: "application/octet-stream",
|
||||
);
|
||||
res.end(bytes);
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
const browser = await chromium.launch({
|
||||
headless: true,
|
||||
args: ["--no-sandbox"],
|
||||
});
|
||||
try {
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 900 },
|
||||
timezoneId: "Asia/Shanghai",
|
||||
recordVideo: {
|
||||
dir: path.join(out, "recordings"),
|
||||
size: { width: 1440, height: 900 },
|
||||
},
|
||||
});
|
||||
await context.addInitScript(() => {
|
||||
localStorage.setItem("aigc-lang", "zh");
|
||||
localStorage.setItem("aigc-reduce-motion", "1");
|
||||
window.__sse = [];
|
||||
window.EventSource = class {
|
||||
constructor() {
|
||||
window.__sse.push(this);
|
||||
setTimeout(() => this.onopen?.(), 0);
|
||||
}
|
||||
addEventListener(t, f) {
|
||||
(this.handlers ??= {})[t] = f;
|
||||
}
|
||||
close() {}
|
||||
};
|
||||
});
|
||||
await context.route("**/*", async (route) => {
|
||||
const req = route.request(),
|
||||
u = new URL(req.url());
|
||||
if (["data:", "blob:", "file:"].includes(u.protocol))
|
||||
return route.continue();
|
||||
if (u.origin !== base) {
|
||||
result.externalBlocked.push(u.origin);
|
||||
return route.abort();
|
||||
}
|
||||
if (!u.pathname.startsWith("/api/")) return route.continue();
|
||||
const json = (body) => route.fulfill({ json: body });
|
||||
if (u.pathname === "/api/file") {
|
||||
if (u.searchParams.get("path")?.endsWith(".mp4")) {
|
||||
const bytes = await fs.readFile(path.join(data, "video.mp4"));
|
||||
const range = req.headers()["range"]?.match(/bytes=(\d+)-(\d*)/);
|
||||
if (range) {
|
||||
const start = +range[1],
|
||||
end = range[2]
|
||||
? Math.min(+range[2], bytes.length - 1)
|
||||
: bytes.length - 1;
|
||||
return route.fulfill({
|
||||
status: 206,
|
||||
body: bytes.subarray(start, end + 1),
|
||||
contentType: "video/mp4",
|
||||
headers: {
|
||||
"Accept-Ranges": "bytes",
|
||||
"Content-Range": `bytes ${start}-${end}/${bytes.length}`,
|
||||
"Content-Length": String(end - start + 1),
|
||||
},
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
body: bytes,
|
||||
contentType: "video/mp4",
|
||||
headers: {
|
||||
"Accept-Ranges": "bytes",
|
||||
"Content-Length": String(bytes.length),
|
||||
},
|
||||
});
|
||||
}
|
||||
return route.fulfill({
|
||||
body:
|
||||
imageFixture ||
|
||||
Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR1kAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
),
|
||||
contentType: "image/png",
|
||||
});
|
||||
}
|
||||
const session = {
|
||||
id: 769,
|
||||
title: "HEL769 isolated session",
|
||||
project_id: null,
|
||||
origin: u.searchParams.get("origin") === "scene" ? "scene" : "chat",
|
||||
messages: [],
|
||||
plan: null,
|
||||
running: false,
|
||||
};
|
||||
const graph = {
|
||||
canvas: {
|
||||
id: 769,
|
||||
title: "HEL769 isolated canvas",
|
||||
project_id: null,
|
||||
agent_session_id: 769,
|
||||
viewport_json: null,
|
||||
},
|
||||
nodes: [],
|
||||
edges: [],
|
||||
};
|
||||
if (u.pathname === "/api/agent/sessions" && req.method() === "GET")
|
||||
return json([session]);
|
||||
if (u.pathname === "/api/agent/sessions/769") return json(session);
|
||||
if (u.pathname === "/api/canvas" && req.method() === "POST") {
|
||||
result.mutations.push({
|
||||
path: u.pathname,
|
||||
method: "POST",
|
||||
purpose: "isolated canvas ensure only",
|
||||
});
|
||||
return json(graph);
|
||||
}
|
||||
if (u.pathname === "/api/canvas/769") return json(graph);
|
||||
if (u.pathname === "/api/shots/by-session/769")
|
||||
return json({
|
||||
id: 769,
|
||||
title: "HEL769 isolated composition",
|
||||
scene: { objects: [], cameraTrack: [] },
|
||||
});
|
||||
if (u.pathname === "/api/shots/769/captures") return json([]);
|
||||
if (u.pathname === "/api/shots") return json([]);
|
||||
if (
|
||||
u.pathname === "/api/agent/projects" ||
|
||||
u.pathname === "/api/agent/skills"
|
||||
)
|
||||
return json([]);
|
||||
if (u.pathname === "/api/agent/sessions" && req.method() === "POST")
|
||||
return json(session);
|
||||
if (req.method() !== "GET") {
|
||||
result.mutations.push({ path: u.pathname, method: req.method() });
|
||||
const m = u.pathname.match(/^\/api\/jobs\/(\d+)\/(cancel|retry)$/);
|
||||
if (m) {
|
||||
const j = jobs.find((j) => j.id === +m[1]);
|
||||
j.status = m[2] === "cancel" ? "failed" : "pending";
|
||||
j.error = m[2] === "cancel" ? "cancelled" : null;
|
||||
return json(j);
|
||||
}
|
||||
const d = u.pathname.match(/^\/api\/playground\/jobs\/(\d+)$/);
|
||||
if (d && req.method() === "DELETE") {
|
||||
jobs = jobs.filter((j) => j.id !== +d[1]);
|
||||
return json({ ok: true });
|
||||
}
|
||||
if (u.pathname.includes("test")) return json({ ok: true });
|
||||
result.errors.push(`Unexpected mutation ${req.method()} ${u.pathname}`);
|
||||
return route.fulfill({
|
||||
status: 503,
|
||||
body: "Unlisted fixture mutation blocked",
|
||||
});
|
||||
}
|
||||
result.apiReads.push(u.pathname);
|
||||
if (u.pathname === "/api/jobs") {
|
||||
if (apiError)
|
||||
return route.fulfill({ status: 500, body: "HEL769 isolated error" });
|
||||
return json(jobs);
|
||||
}
|
||||
if (u.pathname === "/api/workflows") return json(fixture.workflows);
|
||||
if (u.pathname === "/api/projects")
|
||||
return json([{ id: 1, title: "雾港来信" }]);
|
||||
if (u.pathname === "/api/settings")
|
||||
return json({
|
||||
comfyui_endpoints: [],
|
||||
llm_profiles: [],
|
||||
queue_concurrency: 2,
|
||||
queue_poll_timeout_sec: 1800,
|
||||
queue_poll_interval_sec: 1,
|
||||
queue_max_retries: 1,
|
||||
data_dir: "HEL769-isolated-fixture",
|
||||
dry_run: false,
|
||||
});
|
||||
if (u.pathname === "/api/comfyui/endpoints")
|
||||
return json({ endpoints: [], active_id: null });
|
||||
if (u.pathname.includes("/jobs")) return json([]);
|
||||
if (u.pathname.includes("/sessions")) return json([]);
|
||||
if (
|
||||
u.pathname === "/api/library/media" ||
|
||||
u.pathname === "/api/agent/agents" ||
|
||||
u.pathname === "/api/agent/memories"
|
||||
)
|
||||
return json([]);
|
||||
const wf = u.pathname.match(/^\/api\/workflows\/(\d+)$/);
|
||||
if (wf)
|
||||
return json({
|
||||
...fixture.workflows.find((w) => w.id === +wf[1]),
|
||||
workflow_json: {},
|
||||
output_map: [
|
||||
{
|
||||
nodeId: "2",
|
||||
kind: fixture.workflows.find((w) => w.id === +wf[1]).kind,
|
||||
},
|
||||
],
|
||||
});
|
||||
return json({});
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", (e) => result.errors.push(e.message));
|
||||
const ref = await context.newPage();
|
||||
await ref.goto(
|
||||
pathToFileURL(path.resolve("../materials/夜片场-多主题交互样本.html"))
|
||||
.href,
|
||||
);
|
||||
await ref.evaluate(() => {
|
||||
go("tasks");
|
||||
document.documentElement.classList.add("capture", "reduce");
|
||||
});
|
||||
// Reuse the corresponding original synthetic still only inside this API fake.
|
||||
// Canvas avoids capturing a parent page during its opacity entrance animation.
|
||||
imageFixture = Buffer.from(
|
||||
await ref.evaluate(async () => {
|
||||
const img = new Image();
|
||||
img.src = still(64, 96, 64);
|
||||
await img.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = 48;
|
||||
canvas.height = 32;
|
||||
canvas.getContext("2d").drawImage(img, 0, 0, 48, 32);
|
||||
return canvas.toDataURL("image/png").split(",")[1];
|
||||
}),
|
||||
"base64",
|
||||
);
|
||||
const progress = () =>
|
||||
page.evaluate(() => {
|
||||
for (const es of window.__sse)
|
||||
for (const [id, pct] of [
|
||||
[1, 62],
|
||||
[2, 35],
|
||||
])
|
||||
es.handlers?.["job.progress"]?.({
|
||||
data: JSON.stringify({
|
||||
type: "job.progress",
|
||||
data: { job_id: id, progress: pct, phase: "comfy_running" },
|
||||
}),
|
||||
});
|
||||
});
|
||||
const measure = (p, selectors) =>
|
||||
p.evaluate(
|
||||
(selectors) =>
|
||||
Object.fromEntries(
|
||||
Object.entries(selectors).map(([k, s]) => {
|
||||
const e = document.querySelector(s);
|
||||
if (!e) return [k, null];
|
||||
const r = e.getBoundingClientRect(),
|
||||
c = getComputedStyle(e);
|
||||
return [
|
||||
k,
|
||||
{
|
||||
x: r.x,
|
||||
y: r.y,
|
||||
width: r.width,
|
||||
height: r.height,
|
||||
font: c.fontSize,
|
||||
line: c.lineHeight,
|
||||
weight: c.fontWeight,
|
||||
border: c.border,
|
||||
borderRight: c.borderRight,
|
||||
backgroundImage: c.backgroundImage,
|
||||
opacity: c.opacity,
|
||||
shadow: c.boxShadow,
|
||||
svg: e.matches("svg") ? e.innerHTML : undefined,
|
||||
radius: c.borderRadius,
|
||||
color: c.color,
|
||||
background: c.backgroundColor,
|
||||
},
|
||||
];
|
||||
}),
|
||||
),
|
||||
selectors,
|
||||
);
|
||||
for (const [width, height] of process.env.HEL769_SKIP_VISUAL
|
||||
? []
|
||||
: [
|
||||
[1440, 900],
|
||||
[1366, 768],
|
||||
[1280, 720],
|
||||
])
|
||||
for (const theme of ["night", "day", "grade", "bluehour"])
|
||||
for (const [route, sample] of [
|
||||
["workflows", "workflows"],
|
||||
["connections", "models"],
|
||||
["tasks", "tasks"],
|
||||
["library", "library"],
|
||||
["settings", "settings"],
|
||||
]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
await ref.setViewportSize({ width, height });
|
||||
await page.goto(base + "/" + route);
|
||||
await page.locator(".management-header").waitFor();
|
||||
if (route === "tasks") {
|
||||
await page.locator(".task-table tbody tr").first().waitFor();
|
||||
await progress();
|
||||
}
|
||||
if (route === "settings")
|
||||
await page.locator(".choices.tiles").waitFor();
|
||||
await page.evaluate((theme) => {
|
||||
localStorage.setItem("aigc-theme", theme);
|
||||
window.dispatchEvent(
|
||||
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
|
||||
);
|
||||
}, theme);
|
||||
await ref.evaluate(
|
||||
({ sample, theme }) => {
|
||||
go(sample);
|
||||
setTheme(theme);
|
||||
},
|
||||
{ sample, theme },
|
||||
);
|
||||
await page.waitForTimeout(650);
|
||||
const name = `${route}-${theme}-${width}`;
|
||||
const actualSelectors = {
|
||||
header: ".management-header",
|
||||
brand: ".refract-shell > .sidebar .brand",
|
||||
divider: ".refract-shell > .sidebar hr",
|
||||
foot: ".sidebar-bottom",
|
||||
queue: ".queue-dot",
|
||||
theme: ".sidebar-bottom button",
|
||||
settings: '.sidebar-bottom a[href="/settings"]',
|
||||
themeCard: ".tiles .choice",
|
||||
themePreview: ".tiles .preview",
|
||||
themeName: ".tiles .copy strong",
|
||||
themeTone: ".tiles .copy small",
|
||||
};
|
||||
const sampleSelectors = {
|
||||
header: `#p-${sample} .ph`,
|
||||
brand: ".rail .brand",
|
||||
divider: ".rail hr",
|
||||
foot: ".rail .foot",
|
||||
queue: ".rail .queue-dot",
|
||||
theme: "#themeBtn",
|
||||
settings: '.rail [data-go="settings"]',
|
||||
themeCard: ".ttile",
|
||||
themePreview: ".ttile .tprev",
|
||||
themeName: ".ttile b",
|
||||
themeTone: ".ttile small",
|
||||
};
|
||||
for (let i = 0; i < 9; i++) {
|
||||
actualSelectors[`nav${i}`] =
|
||||
`.refract-shell > .sidebar nav a:nth-child(${i < 6 ? i + 1 : i - 5})`;
|
||||
if (i >= 6)
|
||||
actualSelectors[`nav${i}`] =
|
||||
`.refract-shell > .sidebar .management a:nth-child(${i - 5})`;
|
||||
sampleSelectors[`nav${i}`] = `.rail > .nav:nth-of-type(${i + 1})`;
|
||||
}
|
||||
if (route === "settings")
|
||||
for (let i = 1; i <= 4; i++)
|
||||
for (const [key, a, b] of [
|
||||
["Card", ".choice", ".ttile"],
|
||||
["Preview", ".preview", ".tprev"],
|
||||
["Name", ".copy strong", "b"],
|
||||
["Tone", ".copy small", "small"],
|
||||
]) {
|
||||
actualSelectors[`theme${key}${i}`] =
|
||||
key === "Card"
|
||||
? `.tiles .choice:nth-child(${i})`
|
||||
: `.tiles .choice:nth-child(${i}) ${a}`;
|
||||
sampleSelectors[`theme${key}${i}`] =
|
||||
key === "Card"
|
||||
? `.ttile:nth-child(${i})`
|
||||
: `.ttile:nth-child(${i}) ${b}`;
|
||||
}
|
||||
if (route === "settings") {
|
||||
for (let i = 1; i <= 4; i++) {
|
||||
for (const [key, a, b] of [
|
||||
["Rail", ".rail", ".r"], ["List", ".list", ".l"],
|
||||
["Stage", ".stage", ".m"], ["Art", ".stage > i", ".art"],
|
||||
["Dock", ".stage > b", ".dk"], ["Badge", ".stage em", ".dk > span"],
|
||||
["Text", ".preview-text", ".tx"],
|
||||
...[1,2,3,4].map(n => [`Line${n}`, `.list i:nth-child(${n})`, `.l i:nth-child(${n})`]),
|
||||
]) {
|
||||
actualSelectors[`internal${key}${i}`] = `.tiles .choice:nth-child(${i}) .preview ${a}`;
|
||||
sampleSelectors[`internal${key}${i}`] = `.ttile:nth-child(${i}) .tprev ${b}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (route !== "settings")
|
||||
for (const key of [
|
||||
"themeCard",
|
||||
"themePreview",
|
||||
"themeName",
|
||||
"themeTone",
|
||||
]) {
|
||||
delete actualSelectors[key];
|
||||
delete sampleSelectors[key];
|
||||
}
|
||||
if (route === "tasks") {
|
||||
Object.assign(actualSelectors, {
|
||||
table: ".task-table",
|
||||
head: ".task-table thead",
|
||||
row: ".task-table tbody tr",
|
||||
thumbnail: ".task-thumbnail",
|
||||
segment: ".task-tabs",
|
||||
search: ".task-search",
|
||||
progress: ".task-progress",
|
||||
});
|
||||
Object.assign(sampleSelectors, {
|
||||
table: "#p-tasks .tbl",
|
||||
head: "#p-tasks thead",
|
||||
row: "#taskTable tr",
|
||||
thumbnail: "#taskTable td>div",
|
||||
segment: "#p-tasks .seg",
|
||||
search: "#p-tasks .input",
|
||||
progress: "#taskTable .bar",
|
||||
});
|
||||
}
|
||||
const railState = (p, actual) =>
|
||||
p.evaluate((actual) => {
|
||||
const selectors = actual
|
||||
? [
|
||||
".refract-shell > .sidebar nav a",
|
||||
'.sidebar-bottom a[href="/settings"]',
|
||||
".sidebar-bottom button:last-of-type",
|
||||
]
|
||||
: [
|
||||
".rail > .nav",
|
||||
'.rail [data-go="settings"]',
|
||||
'.rail [data-go="spec"]',
|
||||
];
|
||||
const nodes = [
|
||||
...document.querySelectorAll(selectors[0]),
|
||||
...selectors.slice(1).map((x) => document.querySelector(x)),
|
||||
];
|
||||
const geometry = (svg) => {
|
||||
const use = svg.querySelector("use");
|
||||
const root = use
|
||||
? document.querySelector(use.getAttribute("href"))
|
||||
: svg;
|
||||
return [...root.children].map((n) => [
|
||||
n.tagName,
|
||||
[...n.attributes].map((a) => [a.name, a.value]).sort(),
|
||||
]);
|
||||
};
|
||||
const selected = nodes.find((n) =>
|
||||
actual
|
||||
? n.getAttribute("aria-current") === "page"
|
||||
: n.classList.contains("on"),
|
||||
);
|
||||
const pseudo = selected
|
||||
? getComputedStyle(selected, "::before")
|
||||
: null;
|
||||
return {
|
||||
icons: nodes
|
||||
.filter((n) => n?.querySelector("svg"))
|
||||
.map((n) => {
|
||||
const svg = n.querySelector("svg"),
|
||||
c = getComputedStyle(svg);
|
||||
return {
|
||||
geometry: geometry(svg),
|
||||
width: c.width,
|
||||
height: c.height,
|
||||
stroke: c.strokeWidth,
|
||||
color: c.color,
|
||||
};
|
||||
}),
|
||||
selected: pseudo
|
||||
? Object.fromEntries(
|
||||
[
|
||||
"left",
|
||||
"top",
|
||||
"bottom",
|
||||
"width",
|
||||
"borderRadius",
|
||||
"backgroundColor",
|
||||
"boxShadow",
|
||||
].map((k) => [k, pseudo[k]]),
|
||||
)
|
||||
: null,
|
||||
};
|
||||
}, actual);
|
||||
const railActual = await railState(page, true),
|
||||
railSample = await railState(ref, false);
|
||||
result.railProbe = { railActual, railSample };
|
||||
check(
|
||||
JSON.stringify(railActual) === JSON.stringify(railSample),
|
||||
`${name}: rail icon paths, sizes, strokes, colors and selected indicator match`,
|
||||
);
|
||||
const measured = {
|
||||
route,
|
||||
theme,
|
||||
width,
|
||||
height,
|
||||
railActual,
|
||||
railSample,
|
||||
actual: await measure(page, actualSelectors),
|
||||
sample: await measure(ref, sampleSelectors),
|
||||
};
|
||||
result.measurements.push(measured);
|
||||
await page.screenshot({ path: path.join(out, name + "-actual.png") });
|
||||
await ref.screenshot({ path: path.join(out, name + "-sample.png") });
|
||||
for (const key of Object.keys(sampleSelectors)) {
|
||||
if (key === "progress") continue; // auto columns depend on honest source text; reported separately
|
||||
for (const axis of ["x", "y", "width", "height"]) {
|
||||
// Table column width distribution is data-dependent, the outer table and thumbnail dimensions are fixed.
|
||||
if (key === "thumbnail" && axis === "x") continue;
|
||||
check(
|
||||
measured.actual[key] &&
|
||||
measured.sample[key] &&
|
||||
Math.abs(
|
||||
measured.actual[key][axis] - measured.sample[key][axis],
|
||||
) < 0.1,
|
||||
`${name}: ${key} ${axis} matches sample`,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (route === "settings") {
|
||||
for (const key of Object.keys(sampleSelectors).filter(k => k.startsWith("internal") || k.startsWith("themePreview"))) {
|
||||
for (const prop of ["radius", "shadow", "background", "backgroundImage", "opacity", "borderRight"]) {
|
||||
check(measured.actual[key][prop] === measured.sample[key][prop], `${name}: ${key} ${prop} matches`);
|
||||
}
|
||||
}
|
||||
for (let card = 1; card <= 4; card++) {
|
||||
await page.locator(`.tiles .choice:nth-child(${card})`).hover();
|
||||
await ref.locator(`.ttile:nth-child(${card})`).hover();
|
||||
await page.locator(`.tiles .choice:nth-child(${card}) .preview`).screenshot({path:path.join(out, `${name}-card${card}-hover-actual.png`)});
|
||||
await ref.locator(`.ttile:nth-child(${card}) .tprev`).screenshot({path:path.join(out, `${name}-card${card}-hover-sample.png`)});
|
||||
}
|
||||
await page.mouse.move(1200, 600);
|
||||
await ref.mouse.move(1200, 600);
|
||||
await page.locator(".choices.tiles").screenshot({path:path.join(out, name + "-internal-actual.png")});
|
||||
await ref.locator("#themeTiles").screenshot({path:path.join(out, name + "-internal-sample.png")});
|
||||
}
|
||||
for (const key of [
|
||||
"brand",
|
||||
"queue",
|
||||
"theme",
|
||||
"settings",
|
||||
...Array.from({ length: 9 }, (_, i) => `nav${i}`),
|
||||
])
|
||||
check(
|
||||
measured.actual[key].radius === measured.sample[key].radius,
|
||||
`${name}: ${key} radius matches sample`,
|
||||
);
|
||||
if (route === "settings")
|
||||
for (const key of [
|
||||
"themeName",
|
||||
"themeTone",
|
||||
...Array.from({ length: 4 }, (_, i) => `themeName${i + 1}`),
|
||||
...Array.from({ length: 4 }, (_, i) => `themeTone${i + 1}`),
|
||||
])
|
||||
check(
|
||||
measured.actual[key].line === measured.sample[key].line,
|
||||
`${name}: ${key} line height`,
|
||||
);
|
||||
check(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
`${name}: no overflow`,
|
||||
);
|
||||
}
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator(".task-table tbody tr").first().waitFor();
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
if (process.env.HEL769_SKIP_VISUAL) {
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator("tbody tr").first().waitFor();
|
||||
}
|
||||
await page.locator(".task-tabs button").nth(1).click();
|
||||
check((await page.locator("tbody tr").count()) === 3, "active filter");
|
||||
await page.locator(".task-tabs button").nth(2).click();
|
||||
check((await page.locator("tbody tr").count()) === 1, "failed filter");
|
||||
await page.locator(".task-tabs button").nth(3).click();
|
||||
check((await page.locator("tbody tr").count()) === 3, "image filter");
|
||||
await page.locator(".task-tabs button").nth(4).click();
|
||||
check((await page.locator("tbody tr").count()) === 3, "video filter");
|
||||
await page.locator(".task-tabs button").first().click();
|
||||
await page.getByRole("searchbox").fill("镜头 07");
|
||||
await page.waitForTimeout(100);
|
||||
check((await page.locator("tbody tr").count()) === 1, "search by task title");
|
||||
await page.getByRole("searchbox").fill("HEL769 absent");
|
||||
await page.waitForTimeout(100);
|
||||
check((await page.locator("tbody tr").count()) === 0, "search empty");
|
||||
await page.screenshot({ path: path.join(out, "search-empty.png") });
|
||||
await page.getByRole("searchbox").fill("");
|
||||
await page.getByRole("button", { name: "查看任务 #6", exact: true }).click();
|
||||
await page.getByRole("dialog").waitFor();
|
||||
const video = page.locator("video");
|
||||
await video.evaluate(
|
||||
(v) =>
|
||||
new Promise((r) =>
|
||||
v.readyState >= 1
|
||||
? r()
|
||||
: v.addEventListener("loadedmetadata", r, { once: true }),
|
||||
),
|
||||
);
|
||||
check(
|
||||
await video.evaluate(
|
||||
(v) =>
|
||||
v.paused && v.controls && !v.autoplay && !v.muted && v.volume === 1,
|
||||
),
|
||||
"video manual playback with sound",
|
||||
);
|
||||
await video.hover();
|
||||
const videoBox = await video.boundingBox();
|
||||
await video.click({ position: { x: 26, y: videoBox.height - 28 } });
|
||||
await page.waitForTimeout(250);
|
||||
check(
|
||||
await video.evaluate((v) => !v.paused && v.currentTime > 0),
|
||||
"explicit video play",
|
||||
);
|
||||
await video.evaluate((v) => {
|
||||
v.pause();
|
||||
v.currentTime = 0.7;
|
||||
v.volume = 0.4;
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
result.videoState = await video.evaluate((v) => ({
|
||||
paused: v.paused,
|
||||
time: v.currentTime,
|
||||
volume: v.volume,
|
||||
duration: v.duration,
|
||||
seekable: v.seekable.length,
|
||||
error: v.error?.message,
|
||||
}));
|
||||
check(
|
||||
result.videoState.paused &&
|
||||
result.videoState.time > 0.6 &&
|
||||
Math.abs(result.videoState.volume - 0.4) < 0.001,
|
||||
"pause seek volume",
|
||||
);
|
||||
await page.screenshot({ path: path.join(out, "video-preview.png") });
|
||||
await page.keyboard.press("Tab");
|
||||
check(
|
||||
await page
|
||||
.getByRole("dialog")
|
||||
.evaluate((e) => e.contains(document.activeElement)),
|
||||
"modal focus stays inside",
|
||||
);
|
||||
await page.getByRole("dialog").locator(".modal-close").focus();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("dialog").waitFor({ state: "hidden" });
|
||||
check((await page.locator("video").count()) === 0, "close unmounts video");
|
||||
check(
|
||||
await page
|
||||
.getByRole("button", { name: "查看任务 #6", exact: true })
|
||||
.evaluate((e) => e === document.activeElement),
|
||||
"modal restores trigger focus",
|
||||
);
|
||||
await page.getByRole("button", { name: "查看任务 #5", exact: true }).click();
|
||||
await page.getByRole("dialog").waitFor();
|
||||
check(
|
||||
(await page.getByRole("dialog").locator("img").count()) === 1,
|
||||
"image preview",
|
||||
);
|
||||
const [download] = await Promise.all([
|
||||
page.waitForEvent("download"),
|
||||
page.getByRole("link", { name: "下载", exact: true }).click(),
|
||||
]);
|
||||
check(!(await download.failure()), "native image download");
|
||||
await download.saveAs(path.join(out, "downloaded-fixture.png"));
|
||||
await page.getByRole("button", { name: "删除", exact: true }).click();
|
||||
check(
|
||||
(await page.locator("tbody tr").count()) === 5,
|
||||
"delete removes row immediately",
|
||||
);
|
||||
await page.getByRole("button", { name: "撤销", exact: true }).click();
|
||||
check((await page.locator("tbody tr").count()) === 6, "undo restores row");
|
||||
check(
|
||||
!result.mutations.some((m) => m.method === "DELETE"),
|
||||
"undo prevents DELETE",
|
||||
);
|
||||
await page.getByRole("button", { name: "查看任务 #5", exact: true }).click();
|
||||
await page.getByRole("button", { name: "删除", exact: true }).click();
|
||||
await page.waitForTimeout(5300);
|
||||
check(
|
||||
result.mutations.some((m) => m.method === "DELETE"),
|
||||
"delete commits after undo window",
|
||||
);
|
||||
await page
|
||||
.locator("tbody tr")
|
||||
.filter({ hasText: "参考生视频 #21" })
|
||||
.getByRole("button", { name: "重试", exact: true })
|
||||
.click();
|
||||
await page.waitForTimeout(150);
|
||||
check(
|
||||
jobs.find((j) => j.id === 4).status === "pending",
|
||||
"retry uses real API contract",
|
||||
);
|
||||
await page
|
||||
.locator("tbody tr")
|
||||
.filter({ hasText: "Qwen 局部重绘" })
|
||||
.getByRole("button", { name: "取消", exact: true })
|
||||
.click();
|
||||
await page.waitForTimeout(150);
|
||||
check(
|
||||
jobs.find((j) => j.id === 3).error === "cancelled",
|
||||
"cancel uses real API contract",
|
||||
);
|
||||
await page.getByRole("button", { name: "查看任务 #1", exact: true }).click();
|
||||
await page.getByRole("button", { name: "创作台", exact: true }).click();
|
||||
check(
|
||||
(await page.locator("tbody tr").count()) === 2,
|
||||
"source filter retained in details",
|
||||
);
|
||||
await page.getByRole("button", { name: "全部来源", exact: true }).click();
|
||||
const testJob = {
|
||||
...structuredClone(fixture.jobs[4]),
|
||||
id: 8,
|
||||
origin: "workflow_test",
|
||||
payload: { source: "workflow_test", title: "HEL769 workflow test" },
|
||||
output_paths: ["HEL769-fixture-4.png"],
|
||||
};
|
||||
jobs.push(testJob);
|
||||
await page.goto(base + "/tasks");
|
||||
await page.getByRole("button", { name: "查看任务 #8", exact: true }).click();
|
||||
await page.getByRole("button", { name: "工作流试跑", exact: true }).click();
|
||||
check(
|
||||
(await page.locator("tbody tr").count()) === 1,
|
||||
"workflow test source isolated",
|
||||
);
|
||||
await page.getByRole("button", { name: "全部来源", exact: true }).click();
|
||||
// Pending/running without a numeric report must remain unknown.
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator("tbody tr").first().waitFor();
|
||||
check(
|
||||
(await page.locator(".task-progress").count()) === 0,
|
||||
"no fabricated percentages after reload",
|
||||
);
|
||||
jobs = [];
|
||||
await page.goto(base + "/tasks");
|
||||
await page.waitForTimeout(400);
|
||||
check((await page.locator("tbody tr").count()) === 0, "true empty data");
|
||||
await page.screenshot({ path: path.join(out, "true-empty.png") });
|
||||
apiError = true;
|
||||
await page.goto(base + "/tasks");
|
||||
await page
|
||||
.getByRole("alert")
|
||||
.filter({ hasText: "任务加载失败" })
|
||||
.waitFor({ timeout: 15000 });
|
||||
check(true, "API failure shown honestly");
|
||||
apiError = false;
|
||||
jobs = structuredClone(fixture.jobs);
|
||||
await page.getByRole("button", { name: "重试", exact: true }).click();
|
||||
await page.locator("tbody tr").first().waitFor();
|
||||
check(true, "load retry restores tasks");
|
||||
for (const route of [
|
||||
"workflows",
|
||||
"connections",
|
||||
"library",
|
||||
"settings",
|
||||
"create?kind=image",
|
||||
"create?kind=video",
|
||||
]) {
|
||||
await page.goto(base + "/" + route);
|
||||
await page.waitForTimeout(400);
|
||||
await page.screenshot({
|
||||
path: path.join(out, "regression-" + route.replace(/\W/g, "-") + ".png"),
|
||||
});
|
||||
check(
|
||||
(await page.locator(".task-table").count()) === 0,
|
||||
`${route}: task table styles scoped`,
|
||||
);
|
||||
if (route.startsWith("create?")) {
|
||||
const textarea = page.locator(".studio-form textarea").first();
|
||||
await textarea.fill("HEL769 isolated creative draft");
|
||||
check(
|
||||
(await textarea.inputValue()) === "HEL769 isolated creative draft",
|
||||
`${route}: prompt remains editable`,
|
||||
);
|
||||
await page.reload();
|
||||
await page.locator(".studio-form textarea").first().waitFor();
|
||||
check(
|
||||
(await page.locator(".studio-form textarea").first().inputValue()) ===
|
||||
"HEL769 isolated creative draft",
|
||||
`${route}: draft survives reload`,
|
||||
);
|
||||
}
|
||||
if (route === "workflows")
|
||||
check(
|
||||
(await page
|
||||
.locator(".mg-side")
|
||||
.evaluate((e) => e.getBoundingClientRect().width)) === 220,
|
||||
"workflow sidebar retains 220px",
|
||||
);
|
||||
}
|
||||
for (const route of [
|
||||
"/",
|
||||
"/workbench",
|
||||
"/agents",
|
||||
"/canvas",
|
||||
"/build-scene",
|
||||
"/models",
|
||||
"/model-connections",
|
||||
"/image",
|
||||
"/video",
|
||||
]) {
|
||||
await page.goto(base + route);
|
||||
await page.locator(".refract-shell > .sidebar").waitFor({ timeout: 15000 });
|
||||
await page.waitForTimeout(350);
|
||||
check(
|
||||
(await page.locator(".refract-shell > .sidebar").count()) === 1,
|
||||
`${route}: shared rail reachable`,
|
||||
);
|
||||
if (route === "/models")
|
||||
check(
|
||||
page.url().includes("/connections?tab=llm"),
|
||||
"legacy models redirect",
|
||||
);
|
||||
if (route === "/model-connections")
|
||||
check(page.url().includes("/connections"), "connections alias redirect");
|
||||
}
|
||||
await page.goto(base + "/create?kind=image");
|
||||
await page.locator(".studio-form textarea").first().waitFor();
|
||||
check(
|
||||
(await page.locator(".studio-form input[type=file]").count()) === 0,
|
||||
"t2i without image input keeps no padding slot",
|
||||
);
|
||||
await page.keyboard.press("Control+k");
|
||||
await page.getByRole("dialog").waitFor();
|
||||
check(true, "Ctrl+K opens global search");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("dialog").waitFor({ state: "hidden" });
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator(".task-table tbody tr").first().waitFor();
|
||||
await ref.setViewportSize({ width: 1440, height: 900 });
|
||||
for (const theme of ["night", "day", "grade", "bluehour"]) {
|
||||
await page.evaluate((theme) => {
|
||||
localStorage.setItem("aigc-theme", theme);
|
||||
window.dispatchEvent(
|
||||
new StorageEvent("storage", { key: "aigc-theme", newValue: theme }),
|
||||
);
|
||||
}, theme);
|
||||
await ref.evaluate((theme) => {
|
||||
go("tasks");
|
||||
setTheme(theme);
|
||||
}, theme);
|
||||
await page.waitForTimeout(650);
|
||||
await page
|
||||
.locator('.refract-shell > .sidebar a[href="/workflows"]')
|
||||
.hover();
|
||||
await ref.locator('.rail [data-go="workflows"]').hover();
|
||||
await page.waitForTimeout(250);
|
||||
result.checks.push({
|
||||
name: `${theme}: rail hover`,
|
||||
pass: true,
|
||||
actual: await measure(page, {
|
||||
hover: '.refract-shell > .sidebar a[href="/workflows"]',
|
||||
}),
|
||||
sample: await measure(ref, { hover: '.rail [data-go="workflows"]' }),
|
||||
});
|
||||
const hover = result.checks.at(-1);
|
||||
for (const prop of ["color", "background", "radius"])
|
||||
check(
|
||||
hover.actual.hover[prop] === hover.sample.hover[prop],
|
||||
`${theme}: hover ${prop} matches sample`,
|
||||
);
|
||||
await page.screenshot({
|
||||
path: path.join(out, `hover-${theme}-actual.png`),
|
||||
});
|
||||
await ref.screenshot({ path: path.join(out, `hover-${theme}-sample.png`) });
|
||||
}
|
||||
await page.locator('.sidebar-bottom button[title="主题"]').click();
|
||||
await page.getByRole("dialog").waitFor();
|
||||
const firstChoice = page.getByRole("dialog").locator(".choice").first();
|
||||
await firstChoice.focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await page.keyboard.press("Enter");
|
||||
check(
|
||||
(await page.evaluate(() => document.documentElement.dataset.theme)) ===
|
||||
"day",
|
||||
"theme keyboard selection",
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("dialog").waitFor({ state: "hidden" });
|
||||
check(
|
||||
await page
|
||||
.locator('.sidebar-bottom button[title="主题"]')
|
||||
.evaluate((e) => e === document.activeElement),
|
||||
"theme dialog restores focus",
|
||||
);
|
||||
await page.locator('button[title="展开导航"]').click();
|
||||
check(
|
||||
(await page.locator(".refract-shell.expanded").count()) === 1,
|
||||
"existing navigation expansion retained",
|
||||
);
|
||||
await page.locator('button[title="收起导航"]').click();
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator('.sidebar-bottom button[title="主题"]').click();
|
||||
await page.getByRole("dialog").waitFor();
|
||||
await page.getByRole("dialog").getByRole("switch").click();
|
||||
await page.getByRole("dialog").locator(".choice").nth(3).click();
|
||||
await page.waitForFunction(
|
||||
() => document.documentElement.dataset.theme === "bluehour",
|
||||
);
|
||||
await page.waitForTimeout(50);
|
||||
result.themeTransition = await page.evaluate(() => ({
|
||||
theme: document.documentElement.dataset.theme,
|
||||
animations: document.getAnimations().map((a) => ({
|
||||
name: a.animationName,
|
||||
duration: a.effect?.getTiming().duration,
|
||||
})),
|
||||
reduced: document.documentElement.dataset.reduce,
|
||||
}));
|
||||
check(
|
||||
result.themeTransition.theme === "bluehour",
|
||||
"full-motion theme switch applies",
|
||||
);
|
||||
await page.waitForTimeout(650);
|
||||
check(
|
||||
(await page.locator(".queue-ring").count()) === 1,
|
||||
"real running jobs restore original queue ring in full motion",
|
||||
);
|
||||
await page.getByRole("dialog").getByRole("switch").click();
|
||||
check(
|
||||
(await page.locator(".queue-ring").count()) === 0,
|
||||
"reduced motion removes queue ring",
|
||||
);
|
||||
await page.keyboard.press("Escape");
|
||||
if (process.env.HEL769_SKIP_VISUAL) {
|
||||
await page.goto(base + "/settings");
|
||||
for (const [index, id] of ["night", "day", "grade", "bluehour"].entries()) {
|
||||
const tile = page.locator(".choices.tiles .choice").nth(index);
|
||||
await tile.click();
|
||||
check(await tile.getAttribute("aria-pressed") === "true", `${id}: settings selection`);
|
||||
check(await page.evaluate(() => localStorage.getItem("aigc-theme")) === id, `${id}: saved theme`);
|
||||
await page.reload();
|
||||
await page.locator(".choices.tiles").waitFor();
|
||||
check(await page.locator(".choices.tiles .choice").nth(index).getAttribute("aria-pressed") === "true", `${id}: selected theme survives reload`);
|
||||
}
|
||||
for (const [width,height] of [[1440,900],[1366,768],[1280,720]]) {
|
||||
await page.setViewportSize({width,height});
|
||||
for (const theme of ["night", "day", "grade", "bluehour"]) {
|
||||
await page.evaluate(theme => {localStorage.setItem("aigc-theme", theme);window.dispatchEvent(new StorageEvent("storage", {key:"aigc-theme",newValue:theme}));}, theme);
|
||||
await page.goto(base + "/workflows");
|
||||
await page.locator(".mg-layout").waitFor();
|
||||
check(await page.locator(".mg-layout").evaluate(e => getComputedStyle(e).gridTemplateColumns.split(" ").length === 3), `${width}/${theme}: workflow three columns`);
|
||||
await page.goto(base + "/tasks");
|
||||
await page.locator(".task-table tbody tr").first().waitFor();
|
||||
check(await page.locator(".task-table th").count() === 8, `${width}/${theme}: tasks eight columns`);
|
||||
check(await page.locator(".task-table").evaluate(e => e.getBoundingClientRect().width > innerWidth - 150), `${width}/${theme}: task table uses full content width`);
|
||||
}
|
||||
}
|
||||
}
|
||||
check(result.errors.length === 0, "no browser page errors");
|
||||
const recordings = [await page.video().path(), await ref.video().path()];
|
||||
await context.close();
|
||||
result.recordings = recordings.map((p) => path.relative(out, p));
|
||||
} finally {
|
||||
await fs.writeFile(
|
||||
path.join(
|
||||
out,
|
||||
process.env.HEL769_SKIP_VISUAL
|
||||
? "interaction-results.json"
|
||||
: "results.json",
|
||||
),
|
||||
JSON.stringify(result, null, 2),
|
||||
);
|
||||
await browser.close();
|
||||
await new Promise((r) => server.close(r));
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Foreground isolated evidence run. No user data or external generation services."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import imageio_ffmpeg
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT.parent / "hel769-evidence"
|
||||
OUT.mkdir(exist_ok=True)
|
||||
|
||||
# This database exists only for the duration of this foreground verification.
|
||||
with tempfile.TemporaryDirectory(prefix="hel769-isolated-", dir=OUT) as data:
|
||||
db = sqlite3.connect(Path(data) / "fixture.sqlite")
|
||||
db.execute("create table fixture_jobs (id integer primary key, purpose text, body text)")
|
||||
names = [
|
||||
"镜头 07 · 首尾帧", "分镜草图 8/12", "Qwen 局部重绘 #62",
|
||||
"参考生视频 #21", "Krea2 文生图 #55", "镜头 06 · 首尾帧",
|
||||
]
|
||||
workflow_names = [
|
||||
"H3 首尾帧生视频", "Krea2 · 4 宫格故事板", "Qwen 2.1 · 局部重绘",
|
||||
"H3 参考生视频", "Krea2 · 文生图", "H3 首尾帧生视频",
|
||||
]
|
||||
workflow_rows = []
|
||||
for i in range(6):
|
||||
kind = "video" if i in (0, 3, 5) else "image"
|
||||
job = {
|
||||
"id": i + 1,
|
||||
"project_id": 1 if i in (0, 1, 5) else 0,
|
||||
"scene_id": 1 if i in (0, 1, 5) else None,
|
||||
"clip_id": None,
|
||||
"kind": kind,
|
||||
"workflow_id": i + 1,
|
||||
"status": ["running", "running", "pending", "failed", "done", "done"][i],
|
||||
"payload": {
|
||||
"title": names[i],
|
||||
"source": "workbench" if i in (0, 1, 5) else "studio-" + kind,
|
||||
"endpoint": {"id": "hel769-fake", "name": "5090D"},
|
||||
},
|
||||
"output_paths": (
|
||||
["HEL769-fixture-4.png" if i == 4 else "HEL769-fixture-video.mp4"]
|
||||
if i > 3 else []
|
||||
),
|
||||
"error": "OOM" if i == 3 else None,
|
||||
"created_at": f"2026-10-21T13:0{i}:00Z",
|
||||
"started_at": None,
|
||||
"completed_at": None,
|
||||
"retry_count": 0,
|
||||
"phase": "comfy_running" if i < 2 else None,
|
||||
}
|
||||
db.execute(
|
||||
"insert into fixture_jobs values (?,?,?)",
|
||||
(i + 1, "HEL-751 isolated sample correspondence; never production",
|
||||
json.dumps(job, ensure_ascii=False)),
|
||||
)
|
||||
workflow_rows.append({
|
||||
"id": i + 1, "name": workflow_names[i], "kind": kind,
|
||||
"media_io": {"in": [], "out": [kind]}, "tags": [],
|
||||
"favorite": False, "category": None, "model_family": None,
|
||||
"usage": "text2video" if kind == "video" else "text2image",
|
||||
"is_enabled": True, "needs_mapping": False,
|
||||
"input_schema": [{
|
||||
"nodeId": "1", "label": "HEL769 fixture prompt",
|
||||
"role": "prompt", "kind": "textarea", "defaultValue": "", "required": True,
|
||||
}],
|
||||
"output_schema": [{"nodeId": "2", "label": "Output", "kind": kind}],
|
||||
"endpoint_id": "hel769-fake",
|
||||
})
|
||||
db.commit()
|
||||
jobs = [json.loads(row[0]) for row in db.execute("select body from fixture_jobs order by id")]
|
||||
db.close()
|
||||
(Path(data) / "fixtures.json").write_text(
|
||||
json.dumps({"jobs": jobs, "workflows": workflow_rows}, ensure_ascii=False),
|
||||
encoding="utf-8",
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
imageio_ffmpeg.get_ffmpeg_exe(), "-y", "-f", "lavfi", "-i",
|
||||
"color=c=navy:s=320x180:r=24", "-f", "lavfi", "-i",
|
||||
"sine=frequency=440:sample_rate=44100", "-t", "2", "-c:v",
|
||||
"libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", str(Path(data) / "video.mp4"),
|
||||
],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True,
|
||||
)
|
||||
env = os.environ | {"HEL769_OUT": str(OUT), "HEL769_DATA": data}
|
||||
subprocess.run(["node", "scripts/verify-hel769.mjs"], cwd=ROOT, env=env, check=True)
|
||||
|
||||
print("Isolated database and media removed; all run-owned servers closed.")
|
||||
|
||||
# Compose unchanged captures into review artifacts; never alter the original HTML.
|
||||
if not os.environ.get("HEL769_SKIP_VISUAL"):
|
||||
evidence = json.loads((OUT / "results.json").read_text())
|
||||
lines = [
|
||||
"| Theme / viewport | Element | Sample x,y,w,h | Actual x,y,w,h | Delta x,y,w,h |",
|
||||
"|---|---|---|---|---|",
|
||||
]
|
||||
for measurement in evidence["measurements"]:
|
||||
name = f"{measurement['route']}-{measurement['theme']}-{measurement['width']}"
|
||||
sample = Image.open(OUT / f"{name}-sample.png").convert("RGB")
|
||||
actual = Image.open(OUT / f"{name}-actual.png").convert("RGB")
|
||||
pair = Image.new("RGB", (sample.width * 2, sample.height + 28), "#151515")
|
||||
ImageDraw.Draw(pair).text((12, 8), "Confirmed sample (left) / Isolated implementation (right)", fill="white")
|
||||
pair.paste(sample, (0, 28))
|
||||
pair.paste(actual, (sample.width, 28))
|
||||
pair.save(OUT / f"{name}-pair.png")
|
||||
for key, expected in measurement["sample"].items():
|
||||
observed = measurement["actual"][key]
|
||||
if not expected or not observed:
|
||||
continue
|
||||
coordinates = ("x", "y", "width", "height")
|
||||
values = lambda row: ", ".join(f"{row[c]:.3f}" for c in coordinates)
|
||||
delta = {c: observed[c] - expected[c] for c in coordinates}
|
||||
lines.append(
|
||||
f"| {measurement['route']} {measurement['theme']} {measurement['width']}×{measurement['height']} "
|
||||
f"| {key} | {values(expected)} | {values(observed)} | {values(delta)} |"
|
||||
)
|
||||
if key in ("themeName", "themeTone"):
|
||||
lines.append(f"| typography | {key} | {expected['font']} / {expected['line']} | {observed['font']} / {observed['line']} | font-size / line-height |")
|
||||
(OUT / "dimensions.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
import hashlib
|
||||
for f in sorted(OUT.glob("*-internal-sample.png")):
|
||||
actual = Image.open(str(f).replace("-sample.png", "-actual.png")).convert("RGB")
|
||||
sample = Image.open(f).convert("RGB")
|
||||
pair = Image.new("RGB", (sample.width, sample.height * 2 + 48), "#151515")
|
||||
draw = ImageDraw.Draw(pair)
|
||||
draw.text((8, 5), "Confirmed sample", fill="white")
|
||||
pair.paste(sample, (0, 24))
|
||||
draw.text((8, sample.height + 29), "Isolated implementation", fill="white")
|
||||
pair.paste(actual, (0, sample.height + 48))
|
||||
pair.resize((pair.width * 3, pair.height * 3), Image.Resampling.NEAREST).save(str(f).replace("-sample.png", "-pair-3x.png"))
|
||||
files = sorted(OUT.glob("*.png"))
|
||||
manifest = [{"file": f.name, "bytes": f.stat().st_size, "sha256": hashlib.sha256(f.read_bytes()).hexdigest()} for f in files]
|
||||
(OUT / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
@@ -0,0 +1,239 @@
|
||||
/** HEL-771 targeted verification; measurement helper adapted from HEL-770 review.
|
||||
* Serves the frozen build locally, fakes the API (no backend, no user data),
|
||||
* renders app settings theme tiles and the original sample side by side,
|
||||
* and records geometry, computed styles and screenshots for offline comparison.
|
||||
*/
|
||||
import fs from "node:fs/promises";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
|
||||
const ROOT = process.cwd();
|
||||
const BUILD = path.join(ROOT, "calliope-web/build");
|
||||
const SAMPLE = path.join(ROOT, "../materials/夜片场-多主题交互样本.html");
|
||||
const OUT = process.env.HEL771_OUT || path.join(ROOT, "../evidence/tiles");
|
||||
await fs.mkdir(OUT, { recursive: true });
|
||||
|
||||
const THEMES = ["night", "day", "grade", "bluehour"];
|
||||
const VIEWPORTS = [1280, 1366, 1440];
|
||||
|
||||
const apiLog = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
try {
|
||||
const p = decodeURIComponent(new URL(req.url, "http://local").pathname);
|
||||
if (p.startsWith("/api/")) {
|
||||
apiLog.push(`${req.method} ${p}`);
|
||||
let body = [];
|
||||
if (p === "/api/settings")
|
||||
body = {
|
||||
queue_concurrency: 2,
|
||||
queue_poll_timeout_sec: 1800,
|
||||
comfyui_base_url: "http://127.0.0.1:8188",
|
||||
projects_root: "D:\\AIGC\\projects",
|
||||
dry_run: false,
|
||||
};
|
||||
else if (
|
||||
p === "/api/projects" ||
|
||||
p === "/api/workflows" ||
|
||||
p === "/api/library/media" ||
|
||||
p === "/api/agent/sessions" ||
|
||||
p === "/api/agent/agents" ||
|
||||
p === "/api/canvas" ||
|
||||
p.startsWith("/api/tasks") ||
|
||||
p.startsWith("/api/models")
|
||||
)
|
||||
body = [];
|
||||
else if (p === "/api/jobs/queue-status") body = { paused: false };
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify(body));
|
||||
return;
|
||||
}
|
||||
if (p.startsWith("/sample")) {
|
||||
const bytes = await fs.readFile(SAMPLE);
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(bytes);
|
||||
return;
|
||||
}
|
||||
let f = path.join(BUILD, p);
|
||||
if (!path.extname(f)) f = path.join(BUILD, "index.html");
|
||||
const bytes = await fs.readFile(f);
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
f.endsWith(".js")
|
||||
? "text/javascript"
|
||||
: f.endsWith(".css")
|
||||
? "text/css"
|
||||
: f.endsWith(".html")
|
||||
? "text/html"
|
||||
: "application/octet-stream",
|
||||
);
|
||||
res.end(bytes);
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
await new Promise((r) => (server.listing = server.listen(0, "127.0.0.1", r)));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
console.log("serving at", base);
|
||||
|
||||
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
|
||||
|
||||
async function freshContext(width) {
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width, height: width === 1440 ? 900 : width === 1366 ? 768 : 720 },
|
||||
timezoneId: "Asia/Shanghai",
|
||||
deviceScaleFactor: 1,
|
||||
});
|
||||
await ctx.addInitScript(() => {
|
||||
localStorage.setItem("aigc-lang", "zh");
|
||||
localStorage.setItem("aigc-reduce-motion", "1");
|
||||
window.__sse = [];
|
||||
window.EventSource = class {
|
||||
constructor() {
|
||||
window.__sse.push(this);
|
||||
setTimeout(() => this.onopen?.(), 0);
|
||||
}
|
||||
addEventListener(t, f) {
|
||||
(this.handlers ??= {})[t] = f;
|
||||
}
|
||||
close() {}
|
||||
};
|
||||
});
|
||||
await ctx.route("**/*", async (route) => {
|
||||
const u = new URL(route.request().url());
|
||||
if (["data:", "blob:", "file:"].includes(u.protocol)) return route.continue();
|
||||
if (u.origin !== base) return route.abort();
|
||||
route.continue();
|
||||
});
|
||||
return ctx;
|
||||
}
|
||||
|
||||
/** Shared DOM measurement: given a card element handle's root, measure all internals. */
|
||||
const MEASURE = (cardSel) => {
|
||||
const card = document.querySelector(cardSel);
|
||||
if (!card) return null;
|
||||
const num = (v) => parseFloat(v) || 0;
|
||||
const r = (el) => {
|
||||
const b = el.getBoundingClientRect();
|
||||
return { x: +b.x.toFixed(3), y: +b.y.toFixed(3), w: +b.width.toFixed(3), h: +b.height.toFixed(3) };
|
||||
};
|
||||
const st = (el) => {
|
||||
const s = getComputedStyle(el);
|
||||
return {
|
||||
rect: r(el),
|
||||
background: s.backgroundColor,
|
||||
backgroundImage: s.backgroundImage,
|
||||
borderTopWidth: s.borderTopWidth,
|
||||
borderRightWidth: s.borderRightWidth,
|
||||
borderBottomWidth: s.borderBottomWidth,
|
||||
borderLeftWidth: s.borderLeftWidth,
|
||||
borderTopColor: s.borderTopColor,
|
||||
borderRightColor: s.borderRightColor,
|
||||
borderBottomColor: s.borderBottomColor,
|
||||
borderLeftColor: s.borderLeftColor,
|
||||
borderTopLeftRadius: s.borderTopLeftRadius,
|
||||
borderTopRightRadius: s.borderTopRightRadius,
|
||||
borderBottomLeftRadius: s.borderBottomLeftRadius,
|
||||
borderBottomRightRadius: s.borderBottomRightRadius,
|
||||
boxShadow: s.boxShadow,
|
||||
paddingTop: s.paddingTop,
|
||||
paddingRight: s.paddingRight,
|
||||
paddingBottom: s.paddingBottom,
|
||||
paddingLeft: s.paddingLeft,
|
||||
opacity: s.opacity,
|
||||
color: s.color,
|
||||
overflow: s.overflow,
|
||||
position: s.position,
|
||||
};
|
||||
};
|
||||
const cardS = st(card);
|
||||
const tag = card.querySelector(".theme-default, .tag");
|
||||
const prev = card.querySelector(".preview") || card.querySelector(".tprev");
|
||||
const rail = prev?.querySelector(".rail") || prev?.querySelector(".r");
|
||||
const list = prev?.querySelector(".list") || prev?.querySelector(".l");
|
||||
const items = list ? [...list.querySelectorAll("i")] : [];
|
||||
const stage = prev?.querySelector(".stage") || prev?.querySelector(".m");
|
||||
const art = stage?.querySelector("i") || stage?.querySelector(".art");
|
||||
const dock = stage?.querySelector("b") || stage?.querySelector(".dk");
|
||||
const badge = dock?.querySelector("em") || dock?.querySelector("span");
|
||||
const textLine = prev?.querySelector(".preview-text") || prev?.querySelector(".tx");
|
||||
const strong = card.querySelector(".copy strong") || card.querySelector("b");
|
||||
const small = card.querySelector(".copy small") || card.querySelector("small");
|
||||
const dot = rail ? getComputedStyle(rail, "::before") : null;
|
||||
return {
|
||||
card: cardS,
|
||||
defaultTag: tag ? st(tag) : null,
|
||||
cardClass: card.className,
|
||||
ariaChecked: card.getAttribute("aria-checked") ?? card.getAttribute("aria-pressed"),
|
||||
dataTheme: prev?.getAttribute("data-theme"),
|
||||
preview: prev ? st(prev) : null,
|
||||
rail: rail ? st(rail) : null,
|
||||
railDot: dot
|
||||
? { w: dot.width, h: dot.height, bg: dot.backgroundColor, mt: dot.marginTop, mr: dot.marginRight, ml: dot.marginLeft, mb: dot.marginBottom, radius: dot.borderRadius }
|
||||
: null,
|
||||
list: list ? st(list) : null,
|
||||
listItemCount: items.length,
|
||||
listItems: items.map((i) => st(i)),
|
||||
stage: stage ? st(stage) : null,
|
||||
art: art ? st(art) : null,
|
||||
dock: dock ? st(dock) : null,
|
||||
badge: badge ? st(badge) : null,
|
||||
textLine: textLine ? st(textLine) : null,
|
||||
copyStrong: strong
|
||||
? { text: strong.textContent.trim().replace(/\s+/g, " "), fontSize: getComputedStyle(strong).fontSize, lineHeight: getComputedStyle(strong).lineHeight, fontWeight: getComputedStyle(strong).fontWeight }
|
||||
: null,
|
||||
copySmall: small
|
||||
? { text: small.textContent.trim(), fontSize: getComputedStyle(small).fontSize, lineHeight: getComputedStyle(small).lineHeight, color: getComputedStyle(small).color, fontFamily: getComputedStyle(small).fontFamily.slice(0, 40) }
|
||||
: null,
|
||||
};
|
||||
};
|
||||
|
||||
const results = { groups: [], errors: [], apiCalls: [] };
|
||||
try {
|
||||
for (const width of VIEWPORTS) {
|
||||
const ctx = await freshContext(width);
|
||||
const app = await ctx.newPage(), ref = await ctx.newPage();
|
||||
for (const p of [app, ref]) p.on("pageerror", e => results.errors.push(e.message));
|
||||
await app.goto(`${base}/settings`);
|
||||
await app.locator(".choices.tiles").waitFor();
|
||||
await ref.goto(`${base}/sample`);
|
||||
await ref.evaluate(() => { go("settings"); document.documentElement.classList.add("capture", "reduce"); });
|
||||
for (const theme of THEMES) {
|
||||
await app.evaluate(t => { localStorage.setItem("aigc-theme", t); window.dispatchEvent(new StorageEvent("storage", {key:"aigc-theme", newValue:t})); }, theme);
|
||||
await ref.evaluate(t => setTheme(t), theme);
|
||||
await app.mouse.move(1200, 600); await ref.mouse.move(1200, 600);
|
||||
await app.waitForTimeout(350);
|
||||
const key = `${theme}-${width}`;
|
||||
await app.screenshot({path:path.join(OUT, `${key}-full-app.png`)});
|
||||
await ref.screenshot({path:path.join(OUT, `${key}-full-sample.png`)});
|
||||
for (let i=0;i<4;i++) {
|
||||
const a = `.choices.tiles .choice:nth-child(${i+1})`, b = `#themeTiles .ttile:nth-child(${i+1})`;
|
||||
for (const state of ["normal", "selected", "hover"]) {
|
||||
// Hold page theme fixed to test every card/state. Class changes are fixture-only;
|
||||
// natural click/selection/persistence are exercised by verify-hel769.py separately.
|
||||
await app.locator(a).evaluate((e,on)=>e.classList.toggle("selected",on), state === "selected");
|
||||
await ref.locator(b).evaluate((e,on)=>e.classList.toggle("on",on), state === "selected");
|
||||
await app.mouse.move(1200,600); await ref.mouse.move(1200,600);
|
||||
if (state === "hover") { await app.locator(a).hover(); await ref.locator(b).hover(); }
|
||||
await app.waitForTimeout(300);
|
||||
const name = `${key}-card${i}-${state}`;
|
||||
results.groups.push({name, theme, width, card:i, state, app:await app.evaluate(MEASURE,a), sample:await ref.evaluate(MEASURE,b)});
|
||||
await app.locator(a).screenshot({path:path.join(OUT,`${name}-app.png`)});
|
||||
await ref.locator(b).screenshot({path:path.join(OUT,`${name}-sample.png`)});
|
||||
}
|
||||
await app.locator(a).evaluate((e,on)=>e.classList.toggle("selected",on), THEMES[i]===theme);
|
||||
await ref.locator(b).evaluate((e,on)=>e.classList.toggle("on",on), THEMES[i]===theme);
|
||||
}
|
||||
}
|
||||
await ctx.close();
|
||||
}
|
||||
} finally {
|
||||
results.apiCalls = [...new Set(apiLog)];
|
||||
await fs.writeFile(path.join(OUT,"measurements.json"), JSON.stringify(results,null,2));
|
||||
await browser.close();
|
||||
await new Promise(r=>server.close(r));
|
||||
}
|
||||
if(results.errors.length || results.groups.length !== 144) throw Error("Incomplete matrix or page errors");
|
||||
console.log(`Collected ${results.groups.length} card/state pairs; zero page errors; browser and server closed.`);
|
||||
Reference in New Issue
Block a user