Compare commits

...
Author SHA1 Message Date
leeferandmultica-agent 37bd8d85b8 test: map canvas viewport and minimap state in comparisons
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 18:54:50 +08:00
leeferandmultica-agent 32d0297564 fix: resolve canvas viewfinder color in its scene
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 18:49:45 +08:00
leeferandmultica-agent f300927546 feat: apply approved four-theme canvas design (HEL-818)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 18:46:06 +08:00
leeferandmultica-agent fe4759b788 feat: implement approved restrained motion and state audit (HEL-813)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 18:00:46 +08:00
leeferandmultica-agent e2f139806f fix(i18n): translate Build Scene suggestion labels (HEL-810)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 15:23:58 +08:00
leeferandmultica-agent b6ded3942b fix(workflows): derive honest media metadata for single imports (HEL-809)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 15:08:19 +08:00
leeferandmultica-agent cb410fbdea test: package HEL-806 evidence and verify genuine empty state
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 13:36:32 +08:00
leeferandmultica-agent 6d6552e011 fix: complete HEL-806 audit evidence and shared visual corrections
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 13:28:29 +08:00
leeferandmultica-agent 1f6c2d2a6b HEL-733: align approved motion and audit remaining sample gaps
Co-authored-by: multica-agent <github@multica.ai>
2026-10-23 12:43:05 +08:00
leefer 2952af42b6 Merge pull request 'HEL-732: 智能体成果、项目草稿与样本视觉修复' (#11) from feat/hel-732-agent-results into leefer/hel-731-studio-project
HEL-804: merge reviewed B4 agent results (HEL-732/785/786/788/791/792 chain; user approved 6 sample deviations on HEL-801)
2026-10-23 11:50:01 +08:00
leeferandmultica-agent ea3a1c6f06 fix(agent): retain daylight input focus border from sample
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 20:22:02 +08:00
leeferandmultica-agent e2b69aff16 fix(agent): preserve home title and media label visibility
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 20:18:37 +08:00
leeferandmultica-agent cb35d9819a fix(agent): align header, tool cards and real message presentation
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 20:10:45 +08:00
leeferandmultica-agent afbf50447a fix(agent): match studio controls, thumbnail ratio and sample digits
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 18:53:44 +08:00
leeferandmultica-agent ab48895b99 fix: regenerate SSE contract vocabulary (HEL-785)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 17:44:09 +08:00
leeferandmultica-agent dca216e2c7 test: align agent comparison content with real task events (HEL-732)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 16:09:33 +08:00
leeferandmultica-agent 37cb6ec209 fix: keep agent task input reachable at small viewports (HEL-732)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 16:03:08 +08:00
leeferandmultica-agent 31e5906462 feat: persist agent deliverables and explicit project draft handoff (HEL-732)
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 12:55:57 +08:00
leeferandmultica-agent 8d7e58645c fix: align B3 small button radii and primary disabled states
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 11:00:53 +08:00
leeferandmultica-agent 930cca653f HEL-774: record supplemental check exit and support a focused cleanup recheck
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 09:43:39 +08:00
leeferandmultica-agent 15ff2a3cac HEL-774: keep project feedback clear of fixed save and confirm actions
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 09:41:42 +08:00
leeferandmultica-agent 3dfed6780c HEL-774: wait for navigation, pending saves and theme transitions in focused checks
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 09:35:41 +08:00
leeferandmultica-agent f2ca010fcd HEL-774: restore studio and project secondary button sample tokens
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 09:32:52 +08:00
leeferandmultica-agent 30851d57f1 HEL-731: align studio and five-stage project with approved sample
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 08:34:59 +08:00
leeferandmultica-agent a1c01f1e90 docs(HEL-771): record raw pixel results and verification boundary
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 07:45:14 +08:00
leeferandmultica-agent fb6139d45c test(HEL-771): wait for sample border transition before capture
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 07:43:33 +08:00
leeferandmultica-agent af0417e874 fix(HEL-771): align theme tile hover tone and badge spacing
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 07:42:46 +08:00
leeferandmultica-agent b2bcbc10df fix(HEL-769): restore theme tile preview details from sample
Co-authored-by: multica-agent <github@multica.ai>
2026-10-22 07:07:44 +08:00
142 changed files with 16069 additions and 8284 deletions
+2 -1
View File
@@ -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
@@ -124,6 +124,19 @@ def note_description(ui_workflow: dict[str, Any], limit: int = 160) -> str | Non
return None
def media_io_from_schema(
inputs: list[dict[str, Any]], outputs: list[dict[str, Any]]
) -> dict[str, list[str]]:
"""Media declared by the final input schema and real graph outputs."""
media_kinds = ("image", "image_list", "video", "video_list", "audio", "audio_list")
return {
"in": sorted(
{e["kind"].replace("_list", "") for e in inputs if e.get("kind") in media_kinds}
),
"out": sorted({e["kind"] for e in outputs if e.get("kind") in ("image", "video", "audio")}),
}
def suggested_metadata(
converted: dict[str, Any],
source_path: str | None = None,
@@ -131,21 +144,10 @@ def suggested_metadata(
) -> dict[str, Any]:
"""The import suggestion bundle for one converted workflow."""
judgment = classify_usage(converted)
media_kinds = ("image", "image_list", "video", "video_list", "audio", "audio_list")
media_in = sorted(
{
entry["kind"].replace("_list", "")
for entry in parse_dynamic_inputs(converted)
if entry.get("kind") in media_kinds
}
)
media_out = sorted(
{
str(entry.get("kind"))
for entry in parse_dynamic_outputs(converted)
if entry.get("kind") in ("image", "video", "audio")
}
media_io = media_io_from_schema(
parse_dynamic_inputs(converted), parse_dynamic_outputs(converted)
)
media_in, media_out = media_io["in"], media_io["out"]
category, category_label = category_from_source_path(source_path)
return {
"kind": "video" if "video" in media_out and "image" not in media_out else "image",
+37
View File
@@ -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'")
+8 -2
View File
@@ -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 []
@@ -7,7 +7,7 @@ from fastapi import APIRouter, HTTPException
from calliope.comfyui.endpoints import client_for, endpoint_snapshot
from calliope.comfyui.lint import blocking_problem, workflow_warnings
from calliope.comfyui.metadata import suggested_metadata
from calliope.comfyui.metadata import media_io_from_schema, suggested_metadata
from calliope.comfyui.output_map import (
auto_output_map,
load_output_map,
@@ -76,7 +76,9 @@ def _serialize_workflow(row: Any) -> dict[str, Any]:
mapping_problem(data["workflow_json"], raw_map, data.get("output_map_source")) is not None
)
# HEL-681: structured library metadata (raw JSON columns → values).
data["media_io"] = _load_json_col(data.get("media_io"), {"in": [], "out": []})
data["media_io"] = _resolved_media_io(
data.get("media_io"), data["input_schema"], data["output_schema"]
)
data["tags"] = _load_json_col(data.get("tags"), [])
data["favorite"] = bool(data.get("favorite"))
return data
@@ -90,6 +92,20 @@ def _load_json_col(raw: Any, default: Any) -> Any:
return value if value is not None else default
def _resolved_media_io(
raw: Any, inputs: list[dict[str, Any]], outputs: list[dict[str, Any]]
) -> dict[str, list[str]]:
"""Fill missing declarations only; an explicit empty list is meaningful."""
stored = _load_json_col(raw, {})
derived = media_io_from_schema(inputs, outputs)
if not isinstance(stored, dict):
return derived
return {
key: stored[key] if isinstance(stored.get(key), list) else derived[key]
for key in ("in", "out")
}
async def _connection_check(
endpoint_id: str | None, workflow_json: dict[str, Any], refresh: bool = False
) -> dict[str, Any]:
@@ -197,13 +213,15 @@ async def reanalyze_workflow(workflow_id: int) -> dict[str, Any]:
output_map, output_map_source = None, None
else:
output_map, output_map_source = json.dumps(auto_output_map(workflow)), "auto"
media_io = _resolved_media_io(data["media_io"], schema, outputs)
media_io["in"] = media_io_from_schema(schema, outputs)["in"]
is_enabled = data["is_enabled"]
if output_map_source is None or usage is None:
is_enabled = 0
conn.execute(
"UPDATE workflows SET input_schema = ?, output_schema = ?,"
" usage = ?, usage_source = ?, output_map = ?, output_map_source = ?,"
" is_enabled = ? WHERE id = ?",
" is_enabled = ?, media_io = ? WHERE id = ?",
(
json.dumps(schema),
json.dumps(outputs),
@@ -212,6 +230,7 @@ async def reanalyze_workflow(workflow_id: int) -> dict[str, Any]:
output_map,
output_map_source,
is_enabled,
json.dumps(media_io),
workflow_id,
),
)
@@ -247,7 +266,8 @@ async def list_workflows(view: str | None = None) -> list[dict[str, Any]]:
try:
if view == "meta":
# HEL-681: metadata-only list for 150+ scale browsing — no
# workflow_json, no per-row re-parse. `needs_mapping` here is the
# workflow_json in the response. Only legacy/missing media
# declarations need graph parsing. `needs_mapping` here is the
# cheap pending check (usage/output_map not yet settled); rows
# that never generated keep showing as pending exactly like the
# full view reports them.
@@ -260,11 +280,27 @@ async def list_workflows(view: str | None = None) -> list[dict[str, Any]]:
data = row_to_dict(row)
data["is_enabled"] = bool(data.get("is_enabled"))
data["favorite"] = bool(data.get("favorite"))
data["media_io"] = _load_json_col(data.get("media_io"), {"in": [], "out": []})
media = _load_json_col(data.get("media_io"), {})
if isinstance(media, dict) and all(
isinstance(media.get(key), list) for key in ("in", "out")
):
data["media_io"] = {key: media[key] for key in ("in", "out")}
else:
legacy = conn.execute(
"SELECT workflow_json, input_schema FROM workflows WHERE id = ?",
(data["id"],),
).fetchone()
graph = json.loads(legacy["workflow_json"])
schema = effective_input_schema(
_load_json_col(legacy["input_schema"], []), graph
)
data["media_io"] = _resolved_media_io(
data.get("media_io"), schema, parse_dynamic_outputs(graph)
)
data["tags"] = _load_json_col(data.get("tags"), [])
data["needs_mapping"] = data.get("usage") is None or data.get(
"output_map_source"
) is None
data["needs_mapping"] = (
data.get("usage") is None or data.get("output_map_source") is None
)
out.append(data)
return out
rows = conn.execute("SELECT * FROM workflows ORDER BY id DESC").fetchall()
@@ -369,6 +405,9 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
output_map = json.dumps(auto_map) if auto_map else None
output_map_source = "auto" if auto_map else None
mapping_ok = not needs_user_output_map(payload.workflow_json) or bool(payload.output_map)
schema = _stored_schema(payload.input_schema, payload.workflow_json)
outputs = parse_dynamic_outputs(payload.workflow_json)
media_io = media_io_from_schema(json.loads(schema), outputs)
conn = get_db(settings.db_path)
try:
# Byte-identical re-imports are the main way the library fills up with
@@ -395,15 +434,15 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
INSERT INTO workflows (name, kind, workflow_json, input_schema,
output_schema, description, prompt_profile,
endpoint_id, is_enabled, usage, usage_source,
output_map, output_map_source)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
output_map, output_map_source, media_io)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
payload.name,
kind,
json.dumps(payload.workflow_json),
_stored_schema(payload.input_schema, payload.workflow_json),
json.dumps(parse_dynamic_outputs(payload.workflow_json)),
schema,
json.dumps(outputs),
payload.description,
profile,
payload.endpoint_id,
@@ -412,6 +451,7 @@ async def create_workflow(payload: WorkflowCreate) -> dict[str, Any]:
usage_source,
output_map,
output_map_source,
json.dumps(media_io),
),
)
conn.commit()
@@ -474,7 +514,20 @@ async def update_workflow(workflow_id: int, payload: WorkflowUpdate) -> dict[str
if "input_schema" in data and data["input_schema"] is not None:
if not all(isinstance(e, dict) for e in data["input_schema"]):
raise HTTPException(status_code=422, detail="input_schema 必须是参数对象数组")
media = _resolved_media_io(
existing["media_io"], [], parse_dynamic_outputs(workflow_json)
)
schema = effective_input_schema(data["input_schema"], workflow_json)
media["in"] = media_io_from_schema(schema, [])["in"]
data["media_io"] = json.dumps(media)
data["input_schema"] = json.dumps(data["input_schema"])
elif existing["media_io"] is None:
schema = effective_input_schema(
_load_json_col(existing["input_schema"], []), workflow_json
)
data["media_io"] = json.dumps(
media_io_from_schema(schema, parse_dynamic_outputs(workflow_json))
)
# endpoint_id: explicit null clears the binding; other Nones are skips
# (an output_map reset keeps its explicit NULLs).
explicit_null = {"endpoint_id", "output_map", "output_map_source"} & {
@@ -792,6 +845,8 @@ def _insert_converted(
"existing_id": existing["id"],
}
is_enabled = 1 if (usage and mapping_ok) else 0
schema = _stored_schema(item.input_schema, converted)
outputs = parse_dynamic_outputs(converted)
cur = conn.execute(
"""
INSERT INTO workflows (name, kind, workflow_json, input_schema, output_schema,
@@ -805,10 +860,8 @@ def _insert_converted(
report["name"],
kind,
workflow_text,
json.dumps(
item.input_schema if item.input_schema else parse_dynamic_inputs(converted)
),
json.dumps(parse_dynamic_outputs(converted)),
schema,
json.dumps(outputs),
item.description if item.description is not None else suggested["description"],
profile,
is_enabled,
@@ -818,7 +871,7 @@ def _insert_converted(
output_map_source,
suggested["category"],
suggested["model_family"],
json.dumps({"in": suggested["media_in"], "out": suggested["media_out"]}),
json.dumps(media_io_from_schema(json.loads(schema), outputs)),
json.dumps(item.tags or []),
item.source_path,
),
+183
View File
@@ -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()
@@ -339,7 +339,7 @@ def test_meta_view_has_metadata_but_no_full_json(client):
def test_legacy_list_shape_and_old_records_unchanged(client):
"""Old imports (API format via POST /api/workflows) keep working; the
legacy list still carries workflow_json and the new columns default."""
legacy list still carries workflow_json and truthful media declarations."""
created = client.post(
"/api/workflows",
json={"name": "旧导入", "workflow_json": _api_workflow()},
@@ -352,7 +352,7 @@ def test_legacy_list_shape_and_old_records_unchanged(client):
assert "usage" in row and "output_map" in row
assert row["favorite"] is False
assert row["tags"] == []
assert row["media_io"] == {"in": [], "out": []}
assert row["media_io"] == {"in": ["image"], "out": ["video"]}
meta = client.get("/api/workflows", params={"view": "meta"}).json()
assert meta[0]["needs_mapping"] is False or meta[0]["needs_mapping"] is True
assert meta[0]["source"] is None
@@ -0,0 +1,205 @@
"""HEL-809: import declarations, persistence and both library views agree."""
from __future__ import annotations
import json
import pytest
from calliope.config import settings
from calliope.db import get_db
from tests.test_workflow_import_batch import _ui_graph
def graph(*classes):
nodes = {str(i): {"class_type": cls, "inputs": {}} for i, cls in enumerate(classes, 1)}
nodes["90"] = {
"class_type": "PrimitiveStringMultiline",
"inputs": {"value": "HEL809 isolated prompt"},
"_meta": {"title": "Prompt (Input:prompt)"},
}
for i in range(1, len(classes) + 1):
role = "mask" if classes[i - 1] == "LoadImageMask" else "image"
nodes[str(i)]["_meta"] = {"title": f"Reference (Input:{role})"}
return nodes
def create(client, workflow, schema=None):
analyzed = client.post("/api/workflows/analyze", json={"workflow_json": workflow})
assert analyzed.status_code == 200
response = client.post(
"/api/workflows",
json={
"name": "HEL809 input contract",
"workflow_json": workflow,
"input_schema": analyzed.json()["inputs"] if schema is None else schema,
},
)
assert response.status_code == 200, response.text
return response.json()
def assert_views(client, wid, expected):
detail = client.get(f"/api/workflows/{wid}").json()
assert detail["media_io"] == expected
for query in ("", "?view=meta"):
rows = client.get("/api/workflows" + query).json()
row = next(r for r in rows if r["id"] == wid)
assert row["media_io"] == expected
# This is the library's exact media predicate, fed by the meta API.
for media in ("image", "video", "audio"):
hits = [
r["id"]
for r in rows
if media in r["media_io"]["in"] or media in r["media_io"]["out"]
]
assert (wid in hits) == (media in expected["in"] or media in expected["out"])
if query:
assert not {"workflow_json", "input_schema", "output_schema"} & row.keys()
def stored_media(wid):
with get_db(settings.db_path) as conn:
return json.loads(
conn.execute("SELECT media_io FROM workflows WHERE id = ?", (wid,)).fetchone()[
"media_io"
]
)
@pytest.mark.parametrize(
"classes", [("LoadImage",), ("LoadImageMask",), ("LoadImage", "LoadImageMask"), ()]
)
def test_analyze_create_persists_media_and_agrees_with_library(client, classes):
row = create(client, graph(*classes))
expected = {"in": ["image"] if classes else [], "out": []}
if "LoadImageMask" in classes:
assert any(e["role"] == "mask" and e["kind"] == "image" for e in row["input_schema"])
assert stored_media(row["id"]) == expected
assert row["model_family"] is None # never infer a model or output from kind
assert_views(client, row["id"], expected)
def test_create_uses_confirmed_schema_not_original_graph(client):
row = create(client, graph(), [{"nodeId": "90", "kind": "audio_list", "manual": True}])
assert stored_media(row["id"]) == {"in": ["audio"], "out": []}
assert_views(client, row["id"], {"in": ["audio"], "out": []})
def test_update_changes_inputs_preserving_explicit_outputs_and_other_metadata(client):
row = create(client, graph("LoadImage"))
with get_db(settings.db_path) as conn:
conn.execute(
"UPDATE workflows SET media_io = ?, model_family = ?, tags = ? WHERE id = ?",
(json.dumps({"in": ["image"], "out": []}), "existing", '["tag"]', row["id"]),
)
for kind, expected in (("audio_list", ["audio"]), ("text", []), ("video_list", ["video"])):
response = client.patch(
f"/api/workflows/{row['id']}",
json={
"input_schema": [{"nodeId": "90", "kind": kind, "manual": True}],
},
)
assert response.status_code == 200, response.text
assert response.json()["model_family"] == "existing"
assert response.json()["tags"] == ["tag"]
assert stored_media(row["id"]) == {"in": expected, "out": []}
assert_views(client, row["id"], {"in": expected, "out": []})
@pytest.mark.parametrize(
"raw, expected",
[
(None, {"in": ["image"], "out": ["image"]}),
('{"in": [], "out": []}', {"in": [], "out": []}),
('{"out": []}', {"in": ["image"], "out": []}),
('{"in": []}', {"in": [], "out": ["image"]}),
],
)
def test_legacy_null_and_missing_keys_are_distinct_from_empty_lists(client, raw, expected):
workflow = graph("LoadImageMask")
workflow["99"] = {"class_type": "SaveImage", "inputs": {"images": ["1", 0]}}
row = create(client, workflow)
with get_db(settings.db_path) as conn:
conn.execute("UPDATE workflows SET media_io = ? WHERE id = ?", (raw, row["id"]))
assert_views(client, row["id"], expected)
with get_db(settings.db_path) as conn:
assert (
conn.execute("SELECT media_io FROM workflows WHERE id = ?", (row["id"],)).fetchone()[
"media_io"
]
== raw
) # read only fallback
if raw is None:
response = client.patch(f"/api/workflows/{row['id']}", json={"favorite": True})
assert response.status_code == 200
assert stored_media(row["id"]) == expected
def test_legacy_prompt_only_has_no_invented_media(client):
row = create(client, graph())
with get_db(settings.db_path) as conn:
conn.execute("UPDATE workflows SET media_io = NULL WHERE id = ?", (row["id"],))
assert_views(client, row["id"], {"in": [], "out": []})
def test_batch_import_metadata_survives_unrelated_update(client):
response = client.post(
"/api/workflows/import-batch",
json={
"files": [
{
"source_path": "3-图像生成/Qwen-Image-2.1/demo.json",
"workflow_json": _ui_graph(),
"tags": ["existing batch"],
}
]
},
)
assert response.status_code == 200, response.text
wid = response.json()["imported_ids"][0]
before = client.get(f"/api/workflows/{wid}").json()
response = client.patch(f"/api/workflows/{wid}", json={"favorite": True})
after = response.json()
for key in ("media_io", "source", "source_path", "category", "model_family", "tags"):
assert before[key] == after[key]
assert_views(client, wid, {"in": [], "out": ["image"]})
def test_reanalyze_refreshes_inputs_and_preserves_empty_output_declaration(client):
row = create(client, graph("LoadImageMask"))
client.patch(
f"/api/workflows/{row['id']}",
json={
"input_schema": [{"nodeId": "90", "kind": "text"}],
},
)
# Legacy auto schema: read/reanalyze must rederive it before media classification.
with get_db(settings.db_path) as conn:
conn.execute(
"UPDATE workflows SET input_schema = ? WHERE id = ?",
('[{"nodeId": "90", "kind": "text", "auto": true}]', row["id"]),
)
response = client.post(f"/api/workflows/{row['id']}/reanalyze")
assert response.status_code == 200
expected = {"in": ["image"], "out": []}
assert stored_media(row["id"]) == expected
assert_views(client, row["id"], expected)
def test_batch_import_uses_final_confirmed_input_schema(client):
response = client.post(
"/api/workflows/import-batch",
json={
"files": [
{
"workflow_json": _ui_graph(),
"input_schema": [{"nodeId": "2", "kind": "image_list", "manual": True}],
}
]
},
)
assert response.status_code == 200, response.text
wid = response.json()["imported_ids"][0]
assert stored_media(wid) == {"in": ["image"], "out": ["image"]}
assert_views(client, wid, {"in": ["image"], "out": ["image"]})
@@ -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(
+18 -1
View File
@@ -4,12 +4,29 @@
<meta charset="utf-8" />
<script>
(function () {
var saved;
var saved, motion, legacy;
try {
saved = localStorage.getItem("aigc-theme");
motion = localStorage.getItem("aigc-motion");
legacy = localStorage.getItem("aigc-reduce-motion");
} catch (_) {}
document.documentElement.dataset.theme =
/^(night|day|grade|bluehour)$/.test(saved || "") ? saved : "night";
var preference =
motion === null || motion === undefined
? legacy === "1" || legacy === "true"
? "off"
: "full"
: /^(full|calm|off)$/.test(motion)
? motion
: "full";
var mode = matchMedia("(prefers-reduced-motion: reduce)").matches
? "off"
: preference;
document.documentElement.dataset.motion = mode;
document.documentElement.dataset.reduce = mode === "off" ? "1" : "0";
document.documentElement.classList.toggle("calm", mode === "calm");
document.documentElement.classList.toggle("reduce", mode === "off");
})();
</script>
<link rel="stylesheet" href="%sveltekit.assets%/themes.css" />
@@ -0,0 +1,18 @@
import type { Action } from "svelte/action";
/** HEL-716: interacting with an arriving result skips its development effect. */
export const finishAnimations: Action<HTMLElement> = (node) => {
const finish = () => {
for (const animation of node.getAnimations({ subtree: true })) {
if (animation.playState === "running") animation.finish();
}
};
node.addEventListener("pointerdown", finish);
node.addEventListener("keydown", finish);
return {
destroy() {
node.removeEventListener("pointerdown", finish);
node.removeEventListener("keydown", finish);
},
};
};
@@ -8,6 +8,7 @@ export const spotlight: Action<HTMLElement> = (node) => {
event.pointerType === "touch"
)
return;
if (document.documentElement.dataset.motion === "calm") return;
const rect = node.getBoundingClientRect();
node.style.setProperty("--pointer-x", `${event.clientX - rect.left}px`);
node.style.setProperty("--pointer-y", `${event.clientY - rect.top}px`);
+59
View File
@@ -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;
+51 -138
View File
@@ -1,11 +1,15 @@
<script lang="ts">
import { type Node, type NodeProps } from '@xyflow/svelte';
import { untrack } from 'svelte';
import { reduceMotion } from '$lib/reduceMotion.svelte';
import { finishAnimations } from '$lib/actions/finishAnimations';
import SafeMedia from '$lib/components/SafeMedia.svelte';
import { assetUrl } from '$lib/api';
import { t } from '$lib/i18n.svelte';
interface ArtifactNodeData extends Record<string, unknown> {
canvasNodeId: number;
jobId: number | null;
title: string;
/** Generated media file (image or video) — absolute path served via /assets. */
artifactPath: string | null;
@@ -17,39 +21,66 @@
type ArtifactNode = Node<ArtifactNodeData, 'image' | 'video'>;
let { data }: NodeProps<ArtifactNode> = $props();
let { data, selected }: NodeProps<ArtifactNode> = $props();
const mediaSrc = $derived(data.artifactPath ? assetUrl(data.artifactPath) : null);
const mediaSrc = $derived(
data.artifactPath ? assetUrl(data.artifactPath) : null,
);
// '#t=0.1' fragment paints the first frame (same trick as ClipMonitor).
const videoSrc = $derived(
data.kind === 'video' && mediaSrc ? mediaSrc + '#t=0.1' : null,
);
const running = $derived(data.status === 'running' || data.status === 'pending');
const running = $derived(
data.status === 'running' || data.status === 'pending',
);
let arriving = $state(false);
let previous: { id: number | null; status: string } | null = null;
$effect(() => {
void reduceMotion.mode;
void reduceMotion.loopRevision;
arriving = false;
});
$effect(() => {
const id = data.jobId,
status = data.status;
if (!id || previous?.id !== id || status !== 'done') arriving = false;
else if (previous.status === 'pending' || previous.status === 'running')
arriving = !untrack(() => reduceMotion.mode === 'off');
previous = { id, status };
});
$effect(() => {
if (!arriving) return;
const skip = () => (arriving = false);
window.addEventListener('pointerdown', skip, true);
return () => window.removeEventListener('pointerdown', skip, true);
});
function openPreview() {
if (!mediaSrc) return;
data.onOpenMedia?.(data.kind);
}
</script>
<div class="artifact-node" class:running>
<div
class="canvas-card artifact-node a-viewfinder"
class:a-in-frame={selected}
data-kind={data.kind}
>
<header>
<span class="type-chip">{data.kind}</span>
<span class="title" title={data.title}>{data.title}</span>
{#if running}
<span class="status running-badge">{t('canvas.running')}</span>
{:else if data.status === 'failed'}
<span class="status failed-badge">{t('canvas.failed')}</span>
{:else if videoSrc}
<span class="play-badge" aria-hidden="true">▶</span>
{/if}
</header>
<div class="media">
<div
class="media"
use:finishAnimations
onanimationend={() => (arriving = false)}
>
{#if videoSrc}
<button
type="button"
class="media-btn"
class:a-result-develop={arriving}
onclick={openPreview}
title={t('canvas.openPreview')}
>
@@ -65,6 +96,7 @@
<button
type="button"
class="media-btn"
class:a-result-develop={arriving}
onclick={openPreview}
title={t('canvas.openPreview')}
>
@@ -81,131 +113,12 @@
{:else}
<span class="placeholder">{t('canvas.noMedia')}</span>
{/if}
<span class="out-kind">{data.kind}</span>
</div>
<span class="out-kind">{data.kind}</span>
<footer>
{#if running}<span class="status running-badge">{t('canvas.running')}</span
>{:else if data.status === 'failed'}<span class="status failed-badge"
>{t('canvas.failed')}</span
>{/if}<span class="node-id">#{data.canvasNodeId}</span>
</footer>
</div>
<style>
.artifact-node {
width: 220px;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: 12px;
overflow: hidden;
position: relative;
}
.artifact-node.running {
border-color: var(--run);
box-shadow: 0 0 18px var(--run-soft);
}
:global(.svelte-flow__node.selected) .artifact-node {
border-color: var(--accent);
box-shadow:
0 0 0 1px var(--accent),
0 0 30px var(--accent-glow);
}
header {
display: flex;
align-items: center;
gap: 7px;
padding: 8px 10px;
}
.type-chip {
font-size: 9px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-2);
background: var(--bg-4);
border: 1px solid var(--line-2);
border-radius: 999px;
padding: 2px 6px;
flex-shrink: 0;
}
.title {
flex: 1;
min-width: 0;
font-size: 12px;
font-weight: 500;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.status {
font-size: 9.5px;
padding: 2px 6px;
border-radius: 999px;
flex-shrink: 0;
}
.running-badge {
color: var(--run);
background: var(--run-soft);
}
.failed-badge {
color: var(--err);
background: var(--err-soft);
}
.play-badge {
font-size: 9px;
color: var(--text-primary);
background: color-mix(in srgb, var(--accent) 22%, transparent);
border-radius: 50%;
width: 18px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
.media {
height: 124px;
background: var(--bg-elevated);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
/* SafeMedia renders the <img> inside a child component, so the scoped
* `.media-el` below never lands on it — the :global() reach is what
* makes it fill the frame (same pattern as EntityNode). Without it the
* image renders at natural size and only a slice is visible. */
.media :global(.media-el),
.media-el {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.media-btn {
appearance: none;
border: none;
background: transparent;
padding: 0;
width: 100%;
height: 100%;
cursor: pointer;
display: block;
}
.placeholder {
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
}
/* Identical to EntityNode's kind badge: transparent-black pill, muted
* white text — one style across project and non-project cards. */
.out-kind {
position: absolute;
right: 16px;
bottom: 10px;
font-size: 8.5px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: lowercase;
color: var(--on-media);
pointer-events: none;
background: var(--media-scrim);
padding: 1px 5px;
border-radius: 999px;
}
</style>
+32 -98
View File
@@ -32,13 +32,15 @@
}
}
let { data }: NodeProps<EntityNode> = $props();
let { data, selected }: NodeProps<EntityNode> = $props();
const posterSrc = $derived(assetUrl(data.imagePath));
// '#t=0.1' media fragment: with preload="metadata" browsers paint nothing
// until playback, so the thumbnail sat black. The fragment seeks+paints
// the first frame without playing (same trick as ClipMonitor).
const videoSrc = $derived(data.videoPath ? assetUrl(data.videoPath) + '#t=0.1' : null);
const videoSrc = $derived(
data.videoPath ? assetUrl(data.videoPath) + '#t=0.1' : null,
);
function activate() {
// One rule for every card (artifact and entity alike): click opens the
@@ -52,7 +54,9 @@
</script>
<div
class="entity-node"
class="canvas-card entity-node a-viewfinder"
class:a-in-frame={selected}
data-kind={data.entityType}
role="button"
tabindex="0"
onclick={activate}
@@ -61,7 +65,9 @@
}}
>
<header>
<Icon name={iconFor(data.entityType)} size={14} />
<span class="kind-icon"
><Icon name={iconFor(data.entityType)} size={14} /></span
>
<span class="title" title={data.title}>{data.title}</span>
{#if videoSrc}
<span class="play-badge" aria-hidden="true">
@@ -73,7 +79,13 @@
{#if videoSrc && posterSrc}
<!-- Idle video card: show the poster (cheap static file, never a
mounted <video>). Click opens the modal player. -->
<SafeMedia class="media-el" src={posterSrc} alt={data.title} kind="image" controls={false} />
<SafeMedia
class="media-el"
src={posterSrc}
alt={data.title}
kind="image"
controls={false}
/>
{:else if videoSrc}
<!-- No poster available: #t=0.1 first-frame thumbnail. -->
<video
@@ -84,101 +96,23 @@
preload="metadata"
></video>
{:else if posterSrc}
<SafeMedia class="media-el" src={posterSrc} alt={data.title} kind="image" controls={false} />
<SafeMedia
class="media-el"
src={posterSrc}
alt={data.title}
kind="image"
controls={false}
/>
{:else}
<span class="placeholder">{data.entityType}</span>
{/if}
{#if videoSrc}<span class="out-kind">video</span>{:else if posterSrc}<span
class="out-kind">image</span
>{/if}
</div>
{#if videoSrc}
<span class="out-kind">video</span>
{:else if posterSrc}
<span class="out-kind">image</span>
{/if}
<footer>
<span>{data.entityType}</span><span class="node-id"
>#{data.canvasNodeId}</span
>
</footer>
</div>
<style>
.entity-node {
width: 240px;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: 14px;
overflow: visible;
cursor: pointer;
transition: border-color 0.15s;
}
.entity-node:hover {
border-color: var(--line-2);
}
/* Svelte Flow marks the selected node wrapper with .selected */
:global(.svelte-flow__node.selected) .entity-node {
border-color: var(--accent);
box-shadow:
0 0 0 1px var(--accent),
0 0 40px var(--accent-glow);
}
header {
display: flex;
align-items: center;
gap: 8px;
padding: 9px 12px;
color: var(--text-secondary);
}
.title {
flex: 1;
min-width: 0;
font-size: 12.5px;
font-weight: 500;
color: var(--text-primary);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.play-badge {
display: inline-flex;
align-items: center;
justify-content: center;
width: 18px;
height: 18px;
border-radius: 50%;
background: color-mix(in srgb, var(--accent) 22%, transparent);
color: var(--text-primary);
flex-shrink: 0;
}
.media {
height: 132px;
background: var(--bg-elevated);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
border-radius: 0 0 14px 14px;
}
.media :global(.media-el),
.media-el {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.placeholder {
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-muted);
}
.out-kind {
position: absolute;
right: 16px;
bottom: 10px;
font-size: 8.5px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: lowercase;
color: var(--on-media);
pointer-events: none;
background: var(--media-scrim);
padding: 1px 5px;
border-radius: 999px;
}
</style>
+227
View File
@@ -0,0 +1,227 @@
/* Scope border-box to the canvas; shared legacy chat uses content-box elsewhere. */
.canvas-root,
.canvas-root *,
.canvas-root *::before,
.canvas-root *::after {
box-sizing: border-box;
}
/* Canvas surfaces consume the approved shared theme and motion tokens. */
.canvas-root .svelte-flow {
--xy-background-color-default: var(--board-bg);
--xy-background-pattern-color-default: var(--board-dot);
--xy-controls-button-background-color-default: transparent;
--xy-controls-button-background-color-hover-default: rgb(var(--ink) / 0.06);
--xy-controls-button-color-default: var(--tx-2);
--xy-controls-button-color-hover-default: var(--tx-1);
--xy-controls-button-border-color-default: transparent;
}
.canvas-root .svelte-flow__panel {
margin: 14px;
}
.canvas-root .svelte-flow__controls,
.canvas-root .svelte-flow__minimap {
padding: 4px;
border: 1px solid var(--line-2);
border-radius: var(--r-md);
background: var(--glass);
backdrop-filter: blur(14px);
box-shadow: var(--sh-1);
overflow: hidden;
}
.canvas-root .svelte-flow__controls {
gap: 2px;
height: 160px;
}
.canvas-root .svelte-flow__controls-button {
width: 30px;
height: 30px;
padding: 7px;
border-radius: 7px;
}
.canvas-root .svelte-flow__minimap {
padding: 10px;
}
.canvas-root .svelte-flow__minimap svg {
display: block;
background: rgb(var(--ink) / 0.04);
border-radius: 5px;
}
.canvas-root .svelte-flow__minimap-mask {
fill: rgb(var(--ink) / 0.04);
stroke: color-mix(in srgb, var(--gold) 80%, var(--hi));
}
.canvas-card {
position: relative;
width: 240px;
border-radius: var(--r-lg);
background: var(--bg-2);
border: 1px solid var(--line-2);
box-shadow: var(--sh-1);
cursor: grab;
transition:
box-shadow var(--t-base),
border-color var(--t-base);
--scene: var(--sc-image);
}
.canvas-card.artifact-node {
width: 220px;
border-radius: var(--r-md);
}
.canvas-card:hover {
box-shadow: var(--sh-2);
border-color: var(--line-3);
}
.canvas-card.a-in-frame,
.canvas-root .svelte-flow__node:focus-visible .canvas-card {
border-color: color-mix(in srgb, var(--scene) 45%, transparent);
}
.canvas-card:focus-visible {
outline: none;
}
.canvas-card:focus-visible::after,
.canvas-root .svelte-flow__node:focus-visible .canvas-card::after {
opacity: 1;
inset: var(--viewfinder-selected-inset);
}
.canvas-card header {
display: flex;
align-items: center;
gap: 7px;
padding: 9px 10px 8px;
}
.canvas-card .title {
flex: 1;
min-width: 0;
font-size: 12.5px;
font-weight: 600;
color: var(--tx-1);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.canvas-card .kind-icon {
width: 22px;
height: 22px;
display: grid;
place-items: center;
flex-shrink: 0;
border-radius: 6px;
color: var(--kind-color);
background: color-mix(in srgb, var(--kind-color) 12%, transparent);
}
.canvas-card[data-kind="character"] {
--kind-color: var(--sc-agent);
}
.canvas-card[data-kind="location"],
.canvas-card[data-kind="scene"],
.canvas-card[data-kind="video"] {
--kind-color: var(--sc-video);
}
.canvas-card[data-kind="item"] {
--kind-color: var(--sc-project);
}
.canvas-card[data-kind="image"] {
--kind-color: var(--sc-image);
}
.canvas-card .play-badge {
display: grid;
place-items: center;
flex-shrink: 0;
width: 22px;
height: 22px;
border-radius: 50%;
background: rgb(var(--ink) / 0.06);
color: var(--tx-2);
}
.canvas-card .media {
position: relative;
height: 132px;
margin: 0 8px 8px;
border-radius: calc(var(--r-md) - 2px);
background: var(--desk-media-bg);
box-shadow: var(--media-shadow);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.canvas-card.artifact-node .media {
height: 124px;
}
.canvas-card .media-el {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.canvas-card .media-btn {
appearance: none;
border: 0;
background: transparent;
padding: 0;
width: 100%;
height: 100%;
cursor: pointer;
display: block;
}
.canvas-card .placeholder {
font-size: 10px;
letter-spacing: 0.08em;
color: var(--tx-3);
}
.canvas-card .out-kind {
position: absolute;
right: 6px;
bottom: 6px;
height: 18px;
display: inline-flex;
align-items: center;
padding: 0 6px;
border-radius: 4px;
font-size: 10.5px;
color: var(--on-media);
background: var(--media-scrim);
border: 1px solid var(--line-2);
pointer-events: none;
}
.canvas-card footer {
display: flex;
align-items: center;
gap: 6px;
padding: 0 10px 9px;
font-size: 11px;
color: var(--tx-3);
}
.canvas-card footer .node-id {
margin-left: auto;
font-family: var(--mono);
}
.canvas-card .type-chip {
font-size: 10.5px;
padding: 2px 6px;
border-radius: 4px;
color: var(--kind-color);
background: color-mix(in srgb, var(--kind-color) 12%, transparent);
height: 18px;
display: inline-flex;
align-items: center;
}
.canvas-card .status {
display: inline-flex;
align-items: center;
gap: 4px;
font-size: 10.5px;
}
.canvas-card .running-badge {
color: var(--info);
}
.canvas-card .running-badge::before {
content: "";
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--info);
}
.canvas-card .failed-badge {
color: var(--err);
}
@@ -8,18 +8,11 @@
type Toast,
} from '$lib/toast';
import Icon from '$lib/components/ui/Icon.svelte';
import type { IconName } from '$lib/components/ui/icons';
import { t } from '$lib/i18n.svelte';
let items = $state<Toast[]>([]);
onMount(() => subscribeToasts((next) => (items = next)));
const kindIcon: Record<Toast['kind'], IconName> = {
success: 'check',
error: 'alert',
info: 'info',
};
</script>
{#if items.length}
@@ -27,6 +20,7 @@
{#each items as toast (toast.id)}
<div
class="toast {toast.kind}"
class:leaving={toast.leaving}
role="status"
onmouseenter={() => pauseToast(toast.id)}
onmouseleave={() => resumeToast(toast.id)}
@@ -35,15 +29,18 @@
>
<span class="badge" aria-hidden="true">
<span class="dot"></span>
<Icon name={kindIcon[toast.kind]} size={15} />
</span>
<span class="msg">{toast.message}</span>
{#if toast.action}
<button type="button" class="action" onclick={() => (toast.action?.run(), dismissToast(toast.id))}>
{toast.action.label}
</button>
{/if}
<button
<span class="msg">{toast.message}</span>
{#if toast.action}
<button
type="button"
class="action"
onclick={() => (toast.action?.run(), dismissToast(toast.id))}
>
{toast.action.label}
</button>
{/if}
<button
type="button"
class="dismiss"
aria-label={t('toast.dismiss')}
@@ -57,35 +54,45 @@
{/if}
<style>
/* §四.5 Toast:右下角堆叠,220ms 上移入场;成功绿点 / 失败红点。 */
/* Shared host; visual values come from the approved sample tokens. */
.toast-host {
position: fixed;
right: 24px;
bottom: 24px;
right: var(--toast-right);
bottom: var(--toast-bottom);
/* Above every overlay, incl. the 10000 lightbox, so feedback stays visible. */
z-index: 10001;
display: flex;
flex-direction: column;
gap: 8px;
max-width: min(400px, calc(100vw - 32px));
max-width: min(var(--toast-max-width), calc(100vw - 32px));
pointer-events: none;
}
.toast {
box-sizing: border-box;
font-size: var(--toast-font);
line-height: var(--toast-line-height);
pointer-events: auto;
display: flex;
align-items: flex-start;
gap: 10px;
padding: 12px 14px;
border-radius: var(--r-lg);
background: var(--float-bg);
box-shadow: var(--shadow-float);
animation: toast-in var(--d-enter) var(--ease-out);
min-width: var(--toast-min-width);
max-width: var(--toast-max-width);
padding: var(--toast-padding);
border-radius: var(--toast-radius);
background: var(--toast-bg);
border: 1px solid var(--toast-border);
box-shadow: var(--toast-shadow);
animation: toast-in var(--toast-enter) var(--toast-ease);
transition: opacity var(--toast-exit);
}
.toast.leaving {
opacity: 0;
}
.badge {
display: inline-flex;
align-items: center;
gap: 6px;
margin-top: 1px;
margin-top: var(--toast-dot-top);
flex-shrink: 0;
}
.dot {
@@ -93,6 +100,7 @@
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 8px currentColor;
}
.toast.success .badge {
color: var(--ok);
@@ -105,10 +113,10 @@
}
.msg {
flex: 1;
font-size: var(--fs-body);
line-height: 1.4;
font-size: var(--toast-font);
line-height: var(--toast-line-height);
color: var(--text-primary);
font-weight: 500;
font-weight: 400;
}
/* §四.5: Toast 动作(如撤销)为金色文字 */
.action {
@@ -158,7 +166,8 @@
@keyframes toast-in {
from {
opacity: 0;
transform: translateY(8px);
transform: translateY(var(--toast-enter-y))
scale(var(--toast-enter-scale));
}
to {
opacity: 1;
@@ -643,9 +643,9 @@
height: 7px;
border-radius: 50%;
background: var(--run);
animation: wft-breathe 1.6s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-workflowtestdialog-wft-breathe) 1.6s ease-in-out infinite;
}
@keyframes wft-breathe {
@keyframes -global-motion-workflowtestdialog-wft-breathe {
0%,
100% {
opacity: 1;
@@ -192,9 +192,9 @@
flex-shrink: 0;
border-radius: 9999px;
background: var(--warning);
animation: pulse 1.2s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-agentartifactcard-pulse) 1.2s ease-in-out infinite;
}
@keyframes pulse {
@keyframes -global-motion-agentartifactcard-pulse {
0%,
100% {
opacity: 0.4;
@@ -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;
@@ -431,38 +488,38 @@
display: inline-flex;
align-items: center;
gap: 6px;
font-size: var(--fs-mini);
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
font-size: var(--chat-tag-size, var(--fs-mini));
font-weight: var(--chat-tag-weight, 700);
letter-spacing: var(--chat-tag-spacing, 0.06em);
text-transform: var(--chat-tag-transform, uppercase);
color: var(--agent, var(--text-2));
margin-bottom: 4px;
padding-left: 2px;
}
.agent-dot {
width: 8px;
height: 8px;
width: var(--chat-dot-size, 8px);
height: var(--chat-dot-size, 8px);
border-radius: 999px;
flex-shrink: 0;
box-shadow: 0 0 0 2px color-mix(in srgb, var(--agent, var(--text-2)) 25%, transparent);
box-shadow: var(--chat-identity-shadow, 0 0 0 2px color-mix(in srgb, var(--agent, var(--text-2)) 25%, transparent));
}
.reasoning-wrap {
margin-bottom: 4px;
max-width: 86%;
}
.bubble {
max-width: 86%;
border-radius: var(--r-lg);
padding: 10px 14px;
font-size: 13.5px;
max-width: var(--chat-bubble-width, 86%);
border-radius: var(--chat-bubble-radius, var(--r-lg));
padding: var(--chat-bubble-padding, 10px 14px);
font-size: var(--chat-bubble-font, 13.5px);
line-height: 1.6;
white-space: pre-wrap;
word-break: break-word;
}
/* 对话气泡按规范 §3.2/§3.6:用户 --bg-3,Agent --bg-2 + --line 描边。 */
.user-bubble {
background: var(--bg-3);
border: 1px solid var(--line);
background: var(--chat-user-bg, var(--bg-3));
border: 1px solid var(--chat-user-border, var(--line));
color: var(--text);
}
.user-bubble.steering {
@@ -517,7 +574,7 @@
.assistant-bubble {
background: var(--bg-2);
border: 1px solid var(--line);
border-left: 3px solid var(--agent, var(--text-2));
border-left: var(--chat-agent-border-width, 3px) solid var(--chat-agent-border, var(--agent, var(--text-2)));
color: var(--text);
}
.question-card {
@@ -607,10 +664,10 @@
height: 14px;
margin-left: 2px;
background: var(--run);
animation: blink 1s step-end infinite;
animation: var(--decorative-loop-name, motion-agentchat-blink) 1s step-end infinite;
vertical-align: text-bottom;
}
@keyframes blink {
@keyframes -global-motion-agentchat-blink {
50% {
opacity: 0;
}
@@ -624,13 +681,14 @@
}
/* 进行中指示 = 信号青(§1.3),不占金色。 */
.pulse {
opacity: var(--thinking-opacity, 1);
width: 8px;
height: 8px;
border-radius: 999px;
background: var(--run);
animation: pulse 1.1s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-agentchat-pulse) 1.1s ease-in-out infinite;
}
@keyframes pulse {
@keyframes -global-motion-agentchat-pulse {
0%,
100% {
opacity: 0.35;
@@ -20,6 +20,8 @@
import { t } from '$lib/i18n.svelte';
interface Props {
studio?: boolean;
primaryAction?: boolean;
running: boolean;
onSend: (payload: AgentComposerPayload) => void;
onCancel: () => void;
@@ -34,6 +36,8 @@ interface Props {
}
let {
studio = false,
primaryAction = false,
running,
onSend,
onCancel,
@@ -549,6 +553,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 +564,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" : primaryAction ? "a-btn 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 +624,8 @@ let {
gap: 8px;
width: 100%;
min-width: 0;
padding-top: 10px;
border-top: 1px solid var(--border);
padding: var(--composer-padding, var(--composer-top-padding, 10px) 0 0);
border-top: var(--composer-top-border, 1px) solid var(--border);
}
.composer.drag-over .box {
border-color: var(--accent);
@@ -686,18 +693,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 +749,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 +785,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;
@@ -84,9 +84,9 @@
color: var(--text-muted);
}
.icon-wrap.spinning {
animation: spin 1.5s linear infinite;
animation: var(--decorative-loop-name, motion-agentplanpanel-spin) 1.5s linear infinite;
}
@keyframes spin {
@keyframes -global-motion-agentplanpanel-spin {
to {
transform: rotate(360deg);
}
@@ -155,9 +155,9 @@
width: 10px;
height: 10px;
border-radius: 9999px;
animation: pulse 1.1s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-agentplanpanel-pulse) 1.1s ease-in-out infinite;
}
@keyframes pulse {
@keyframes -global-motion-agentplanpanel-pulse {
0%,
100% {
opacity: 0.35;
@@ -201,8 +201,8 @@
.sidebar {
width: 240px;
flex-shrink: 0;
border-right: 1px solid var(--border);
background: var(--bg-surface);
border-right: 1px solid var(--line);
background: var(--bg-1);
display: flex;
flex-direction: column;
gap: 4px;
@@ -243,8 +243,8 @@
justify-content: center;
width: 32px;
height: 32px;
border: 1px dashed var(--border);
border-radius: var(--radius-sm);
border: 0;
border-radius: var(--r-sm);
background: transparent;
color: var(--text-secondary);
cursor: pointer;
@@ -267,32 +267,34 @@
min-height: 0;
}
.rail-dot {
width: 10px;
height: 10px;
border-radius: 50%;
border: 1px solid var(--border);
background: var(--bg-elevated);
width: 32px;
height: 32px;
display: grid;
place-items: center;
border: 0;
border-radius: var(--r-sm);
background: transparent;
cursor: pointer;
padding: 0;
}
.rail-dot::after {
content: '';
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--tx-3);
}
.rail-dot:hover {
border-color: var(--accent);
background: rgb(var(--ink) / 0.05);
}
.rail-dot.active {
background: var(--accent);
border-color: var(--accent);
background: color-mix(in srgb, var(--sc-agent) 12%, transparent);
}
.rail-dot.run {
animation: rail-pulse 1.4s ease-in-out infinite;
.rail-dot.active::after {
background: var(--sc-agent);
}
@keyframes rail-pulse {
0%,
100% {
box-shadow: 0 0 0 0 var(--accent-glow);
}
50% {
box-shadow: 0 0 0 5px transparent;
}
.rail-dot.run::after {
background: var(--ok);
}
.new-chat {
display: flex;
@@ -399,9 +401,10 @@
.dot.run {
background: var(--warning);
opacity: 1;
animation: pulse 1.1s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-agentsessionsidebar-pulse)
1.1s ease-in-out infinite;
}
@keyframes pulse {
@keyframes -global-motion-agentsessionsidebar-pulse {
0%,
100% {
opacity: 0.35;
@@ -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;
@@ -97,9 +106,9 @@
}
.dot.running {
background: var(--warning);
animation: pulse 1.1s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-agenttoolcard-pulse) 1.1s ease-in-out infinite;
}
@keyframes pulse {
@keyframes -global-motion-agenttoolcard-pulse {
0%,
100% {
opacity: 0.35;
@@ -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;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -76,9 +76,9 @@
color: var(--text-muted);
}
.icon-wrap.spinning {
animation: spin 1.5s linear infinite;
animation: var(--decorative-loop-name, motion-reasoningpanel-spin) 1.5s linear infinite;
}
@keyframes spin {
@keyframes -global-motion-reasoningpanel-spin {
to {
transform: rotate(360deg);
}
@@ -118,10 +118,10 @@
height: 12px;
margin-left: 1px;
background: var(--accent);
animation: blink 1s step-end infinite;
animation: var(--decorative-loop-name, motion-reasoningpanel-blink) 1s step-end infinite;
vertical-align: text-bottom;
}
@keyframes blink {
@keyframes -global-motion-reasoningpanel-blink {
50% {
opacity: 0;
}
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { finishAnimations } from '$lib/actions/finishAnimations';
import { reduceMotion } from '$lib/reduceMotion.svelte';
import { untrack, type Snippet } from 'svelte';
import Modal from '$lib/components/ui/Modal.svelte';
import ImageLightbox from '$lib/components/ImageLightbox.svelte';
@@ -102,6 +104,35 @@
outIndex = 0;
});
// Only a live transition to a completed result develops. Opening old history
// or changing the theme never replays an arrival effect.
let arriving = $state(false);
let previous: { id: number; status: string } | null = null;
$effect(() => {
// A live preference/system change finishes an in-flight reveal.
void reduceMotion.mode;
void reduceMotion.loopRevision;
arriving = false;
});
$effect(() => {
const id = job?.id,
status = job?.status;
if (!id || previous?.id !== id || status !== 'done') {
arriving = false;
} else if (previous.status === 'running' || previous.status === 'pending') {
arriving = !untrack(() => reduceMotion.mode === 'off');
}
// Repeated done snapshots must not erase the effect before the first paint.
previous = id && status ? { id, status } : null;
});
$effect(() => {
if (!arriving) return;
const skip = () => (arriving = false);
// v3: any explicit pointer action may skip an arrival, including actions
// outside the media surface. The listener exists only during this reveal.
window.addEventListener('pointerdown', skip, true);
return () => window.removeEventListener('pointerdown', skip, true);
});
const st = $derived(job ? jobStatusInfo(job) : null);
// §3.4 红/琥珀界线: amber only when the task SUCCEEDED but its files
// cannot be fetched — the failed case stays red.
@@ -208,9 +239,12 @@
{#if output && video}
<!-- svelte-ignore a11y_media_has_caption -->
<div
class="print a-photo"
style:width={fitted > 0 ? `${naturalWidth * fitted}px` : '100%'}
style:height={fitted > 0 ? `${naturalHeight * fitted}px` : '100%'}
class="print a-photo a-viewfinder a-in-frame"
class:a-result-develop={arriving}
use:finishAnimations
onanimationend={() => (arriving = false)}
style:width={fitted > 0 ? `${Math.floor(naturalWidth * fitted)}px` : '100%'}
style:height={fitted > 0 ? `${Math.floor(naturalHeight * fitted)}px` : '100%'}
>
{#if st.tone === 'ok' && !fileGone}<span class="a-fix"
>{t('jobst.done')}</span
@@ -248,9 +282,12 @@
</div>
{:else if output}
<div
class="print a-photo"
style:width={fitted > 0 ? `${naturalWidth * fitted}px` : '100%'}
style:height={fitted > 0 ? `${naturalHeight * fitted}px` : '100%'}
class="print a-photo a-viewfinder a-in-frame"
class:a-result-develop={arriving}
use:finishAnimations
onanimationend={() => (arriving = false)}
style:width={fitted > 0 ? `${Math.floor(naturalWidth * fitted)}px` : '100%'}
style:height={fitted > 0 ? `${Math.floor(naturalHeight * fitted)}px` : '100%'}
>
{#if st.tone === 'ok' && !fileGone}<span class="a-fix"
>{t('jobst.done')}</span
@@ -275,6 +312,24 @@
style:left={`${compareAt}%`}
></div>{/if}
</div>
{:else if job.status === 'running' || job.status === 'pending'}
<div class="generation-card" aria-label={st.label}>
<div class="generation-grain" aria-hidden="true"></div>
{#if job.status === 'running'}<div
class="a-scan-beam"
aria-hidden="true"
></div>{/if}
<div class="generation-info">
<b>{st.label}</b>
{#if progress > 0}<div
class="a-progress"
style:--p={progress / 100}
>
<i></i>
</div>{/if}
<span>{st.detail}</span>
</div>
</div>
{:else if fileGone}
<div class="stage-empty gone">
<span>{t('desk.missingTitle')}</span>
@@ -535,7 +590,7 @@
.artboard {
position: relative;
display: grid;
grid-template-rows: 0 minmax(0, 1fr) 40px;
grid-template-rows: 0 minmax(0, 1fr) var(--desk-action-height);
height: 100%;
min-height: 0;
border: 0;
@@ -644,6 +699,7 @@
min-height: 0;
}
.print {
overflow: hidden;
position: relative;
display: grid;
grid-template: minmax(0, 1fr) / minmax(0, 1fr);
@@ -653,14 +709,15 @@
min-width: 0;
border: 0;
padding: 0;
background: none;
box-shadow: none;
background: var(--desk-media-bg);
box-shadow: var(--media-shadow);
border-radius: var(--desk-media-radius);
}
.big-play {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
translate: var(--desk-player-offset) var(--desk-player-offset);
width: 64px;
height: 64px;
border-radius: 50%;
@@ -684,6 +741,37 @@
.print :global(.a-fix) {
display: none;
}
.generation-card {
width: var(--generation-width);
aspect-ratio: var(--ar, 1);
max-height: var(--generation-max-height);
border-radius: var(--generation-radius);
position: relative;
overflow: hidden;
background: var(--gen-bg);
border: 1px solid var(--line-2);
}
.generation-grain {
position: absolute;
inset: 0;
opacity: var(--generation-grain-opacity);
background-image: repeating-radial-gradient(
circle at 17% 32%,
var(--grain) 0 1px,
transparent 1px 3px
);
}
.generation-info {
position: absolute;
left: 0;
right: 0;
bottom: 0;
padding: var(--generation-info-padding);
background: var(--generation-info-bg);
display: flex;
flex-direction: column;
gap: var(--generation-info-gap);
}
.stage-empty {
display: flex;
flex-direction: column;
@@ -26,13 +26,14 @@
{#each sorted as job (job.id)}
{@const status = jobStatusInfo(job)}
<button
class="history-take"
class="history-take a-viewfinder"
class:a-in-frame={selectedId === job.id}
class:selected={selectedId === job.id}
onclick={() => onSelect(job)}
aria-label={'查看历史 #' + job.id + ' · ' + status.label}
aria-pressed={selectedId === job.id}
>
<div class="thumb">
<div class="thumb" class:placeholder={!job.output_paths[0] || status.tone !== 'ok'}>
{#if job.output_paths[0] && status.tone === 'ok'}
{#if isVideoOutput(job, job.output_paths[0])}<span
class="video-mark">▷</span
@@ -96,52 +97,63 @@
flex: 1;
min-height: 0;
overflow: auto;
padding: 8px 6px;
padding: var(--desk-history-padding);
display: flex;
flex-direction: column;
gap: var(--desk-history-gap);
align-items: center;
}
.history-take {
display: block;
position: relative;
width: 100%;
padding: 3px;
margin-bottom: 8px;
border: 1px solid transparent;
border-radius: var(--r-sm);
}
.history-take.selected {
border-color: var(--scene);
background: color-mix(in srgb, var(--scene) 10%, transparent);
padding: 0;
border: 1px solid var(--line);
border-radius: var(--desk-media-radius);
background: var(--desk-media-bg);
flex: none;
}
.history-take.selected { border-color: transparent; }
.thumb {
position: relative;
aspect-ratio: 1;
display: grid;
place-items: center;
background: var(--bg-0);
border-radius: var(--r-xs);
background: var(--desk-media-bg);
border-radius: inherit;
overflow: hidden;
font-size: 10px;
}
img,
video {
.thumb.placeholder { aspect-ratio: 1; display: grid; place-items: center; }
img, video {
width: 100%;
height: 100%;
height: auto;
display: block;
object-fit: contain;
position: absolute;
inset: 0;
}
.video-mark {
position: absolute;
bottom: 3px;
right: 3px;
width: 16px;
height: 16px;
border-radius: 4px;
display: grid;
place-items: center;
z-index: 1;
color: var(--on-media);
font-size: 24px;
text-shadow: 0 1px 6px var(--media-scrim);
font-size: 10px;
background: var(--desk-history-label-bg);
}
.failed {
color: var(--err);
}
small {
font-family: var(--mono);
font-size: 10px;
color: var(--tx-3);
position: absolute;
left: 3px;
top: 3px;
font: 600 9.5px var(--mono);
padding: 1px 4px;
border-radius: 3px;
background: var(--desk-history-label-bg);
color: var(--desk-history-label-color);
}
p {
text-align: center;
@@ -10,7 +10,7 @@
import { SvelteMap, SvelteSet, SvelteURL } from 'svelte/reactivity';
import { page } from '$app/state';
import { goto } from '$app/navigation';
import '$lib/components/ui/Icon.svelte';
import Icon from '$lib/components/ui/Icon.svelte';
import Modal from '$lib/components/ui/Modal.svelte';
import AppShell from '$lib/components/shell/AppShell.svelte';
import Composer from '$lib/components/generate/Composer.svelte';
@@ -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 {
@@ -1149,7 +1152,7 @@
/>
{/snippet}
<AppShell active={kind} title="创作台" workspace>
<AppShell active={kind} title="创作台" workspace hideHeader>
<div
class="reference-desk"
class:focused={focusMode}
@@ -1218,7 +1221,7 @@
>
</div>{/if}
<div class="studio-layout">
<section class="viewer" aria-label="查看生成结果">
<section class="viewer" aria-label="查看生成结果" style:background="var(--desk-stage-background)">
<div class="preview-area">
{#if selectedJob}<Artboard
main
@@ -1236,7 +1239,6 @@
inactive={false}
canSendToSlot={!!imageSlotTarget || !!imageList}
canAttach={!!selectedJob &&
!!workbenchCtxOf(selectedJob) &&
selectedJob.status === 'done'}
attachBusy={attachBusyId === selectedJob?.id}
onAttach={() => selectedJob && attachToProject(selectedJob)}
@@ -1250,22 +1252,9 @@
onSendToSlot={sendToSlot}
onDelete={requestDelete}
/>{:else}<div class="desk-welcome">
<span class="eyebrow">● AI 创作引擎</span>
<h1>让灵感,成为作品</h1>
<div class="desk-emblem">{kind === 'image' ? '◈' : '▷'}</div>
<div class="workflow-description">
<strong
>{currentWorkflow?.name ??
currentMeta?.name ??
'选择工作流,开始创作'}</strong
>
<p>
{currentWorkflow?.description ??
currentMeta?.description ??
'选择左侧工作流,填写下方提示词与参数。'}
</p>
<small>生成结果在这里显示,视频由你手动播放。</small>
</div>
<div class="desk-emblem"><Icon name={kind === 'image' ? 'image' : 'film'} size={22} /></div>
<div class="empty-title">作品会在这里完整显示</div>
<div class="empty-hint">选工作流 → 填素材与提示词 → 开始生成</div>
</div>{/if}
</div>
</section>
@@ -1618,7 +1607,7 @@
.studio-layout {
display: grid;
grid-template-rows: minmax(0, 1fr) auto;
gap: 12px;
gap: var(--desk-layout-gap);
flex: 1;
min-height: 0;
min-width: 0;
@@ -1630,49 +1619,38 @@
min-width: 0;
overflow: hidden;
}
.viewer {
padding: var(--desk-stage-padding);
box-sizing: border-box;
}
.studio-form {
min-height: 0;
min-width: 0;
}
.desk-welcome {
box-sizing: border-box;
padding-bottom: var(--desk-action-height);
display: flex;
height: 100%;
align-items: center;
justify-content: center;
text-align: center;
flex-direction: column;
gap: 12px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--bg-1);
}
.desk-welcome h1 {
font-size: 24px;
font-weight: 550;
margin: 0;
gap: var(--desk-empty-gap);
color: var(--tx-3);
}
.desk-emblem {
color: var(--accent);
font-size: 56px;
line-height: 1.2;
}
.eyebrow {
color: var(--accent);
font-size: 10px;
}
.workflow-description {
max-width: 400px;
padding: 0 20px;
}
.workflow-description strong {
font-size: 13px;
color: var(--text-2);
}
.workflow-description p,
.workflow-description small {
font-size: 11px;
color: var(--text-3);
box-sizing: border-box;
width: var(--desk-empty-ring);
height: var(--desk-empty-ring);
border-radius: 50%;
border: 1px dashed var(--line-3);
display: grid;
place-items: center;
color: color-mix(in srgb, var(--scene) 70%, var(--hi));
}
.empty-title { font-size: var(--desk-empty-title-size); color: var(--tx-2); }
.empty-hint { font-size: var(--desk-empty-hint-size); }
.history-full {
height: min(680px, 68vh);
}
@@ -1722,12 +1700,6 @@
.picker-empty {
color: var(--text-3);
}
@media (max-height: 740px) {
.studio-layout {
grid-template-rows: minmax(0, 1fr) auto;
gap: 10px;
}
}
@media (max-width: 1100px) {
.refract-studio {
padding-left: 12px;
@@ -1854,3 +1826,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}
@@ -145,7 +145,7 @@
@keyframes appear {
from {
opacity: 0;
transform: translateY(4px) scale(0.98);
transform: translateY(var(--parameter-pop-enter-y)) scale(var(--pop-enter-scale));
}
to {
opacity: 1;
@@ -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);
@@ -606,9 +606,9 @@
position: absolute;
inset: 0;
background: linear-gradient(100deg, transparent 30%, var(--run-soft) 50%, transparent 70%);
animation: take-sheen 1.4s linear infinite;
animation: var(--decorative-loop-name, motion-takecard-take-sheen) 1.4s linear infinite;
}
@keyframes take-sheen {
@keyframes -global-motion-takecard-take-sheen {
from {
transform: translateX(-100%);
}
File diff suppressed because it is too large Load Diff
@@ -40,7 +40,7 @@
--button-font-size: var(--manage-control-size);
--button-radius: var(--manage-control-radius);
--button-secondary-bg: var(--bg-3);
animation: management-enter var(--t-slow) var(--ease-out);
animation: management-enter var(--page-enter-duration) var(--ease-out);
--button-sm-height: var(--manage-button-height);
--button-sm-padding: var(--manage-button-padding);
--button-sm-radius: var(--manage-button-radius);
@@ -717,7 +717,7 @@ textarea.f-input {
@keyframes management-enter {
from {
opacity: 0;
transform: translateY(6px);
transform: translateY(var(--page-enter-y));
}
to {
opacity: 1;
@@ -6,10 +6,10 @@
import { page } from "$app/state";
import LanguageSwitcher from "$lib/components/LanguageSwitcher.svelte";
import Icon from "$lib/components/ui/Icon.svelte";
import Switch from "$lib/components/ui/Switch.svelte";
import MotionChoices from "./MotionChoices.svelte";
import { settings, jobsApi, comfy } from "$lib/api";
import { t } from "$lib/i18n.svelte";
import { reduceMotion, setReduceMotion } from "$lib/reduceMotion.svelte";
import { reduceMotion } from "$lib/reduceMotion.svelte";
import CommandPalette from "./CommandPalette.svelte";
import ProjectScope from "./ProjectScope.svelte";
import QueueTray from "./QueueTray.svelte";
@@ -17,12 +17,15 @@
import { storageGet, storageSet } from "$lib/storage";
import Modal from "$lib/components/ui/Modal.svelte";
import ThemeChoices from "./ThemeChoices.svelte";
import { themeStorageUnavailable } from "$lib/theme";
/** Desktop studio shell: six named sections, project scope, search,
* real queue and connection status. Individual tools keep their routes. */
interface Props {
workspace?: boolean;
pageHeader?: import("svelte").Snippet;
/** The workspace supplies its own full-height header (creative desk). */
hideHeader?: boolean;
pageHeader?: import("svelte").Snippet<[{ openSearch: () => void }]>;
active: NavId;
title: string;
subtitle?: string;
@@ -37,6 +40,7 @@
children,
pageHeader,
workspace = false,
hideHeader = false,
}: Props = $props();
let paletteOpen = $state(false);
@@ -226,7 +230,7 @@
aria-label="查看生成任务"
>
<Icon name="nav-queue" />
{#if genJobs.some((j) => j.status === "running") && !reduceMotion.manual && !reduceMotion.system}<span
{#if genJobs.some((j) => j.status === "running") && reduceMotion.mode !== "off"}<span
class="queue-ring"
aria-hidden="true"
></span>{/if}
@@ -282,7 +286,9 @@
class="app-body"
style:background={pageHeader ? "var(--manage-page-background)" : undefined}
>
{#if pageHeader}{@render pageHeader()}{:else}
{#if pageHeader}{@render pageHeader({
openSearch: openPalette,
})}{:else if !hideHeader}
<header class="topbar">
<div class="breadcrumb">
{currentNav?.label ?? title}<span>/</span><span class="page-name"
@@ -318,14 +324,7 @@
><Icon name="search" size={16} /><span>搜索</span><kbd>Ctrl K</kbd
></button
>
<label class="motion"
><Switch
checked={reduceMotion.system || reduceMotion.manual}
disabled={reduceMotion.system}
label={t("shell.reduceMotion")}
onchange={setReduceMotion}
/><span>减少动效</span></label
>
<MotionChoices />
<LanguageSwitcher /><QueueTray jobs={genJobs} />
</header>
{/if}
@@ -333,16 +332,12 @@
</div>
</div>
<CommandPalette bind:open={paletteOpen} />
<Modal bind:open={themeOpen} title="外观主题">
<Modal bind:open={themeOpen} title="界面主题" rail>
{#snippet headerActions()}<span class="theme-subtitle">同一布局与功能,只换灯光</span>{/snippet}
<ThemeChoices compact />
<label class="theme-motion"
><Switch
checked={reduceMotion.system || reduceMotion.manual}
disabled={reduceMotion.system}
label={t("shell.reduceMotion")}
onchange={setReduceMotion}
/><span>减少动效</span></label
>
{#snippet footer()}
<div class="theme-motion"><span class="theme-foot-note" role="status"><Icon name={$themeStorageUnavailable ? "close" : "check"} size={18} />{$themeStorageUnavailable ? "浏览器禁止本地存储:本次有效,其他操作不受影响" : "已记住,下次打开沿用 · 正在编辑的内容不受影响"}</span><MotionChoices /></div>
{/snippet}
</Modal>
<style>
@@ -358,15 +353,21 @@
);
box-shadow: 0 0 0 1px var(--line-3);
}
.theme-subtitle { font-size: var(--theme-pop-note-size); color: var(--tx-3); }
.theme-foot-note { display: flex; align-items: center; gap: var(--theme-pop-footer-gap); }
.theme-motion {
flex-wrap: wrap;
--button-sm-height: var(--theme-pop-button-height);
--button-sm-padding: var(--theme-pop-button-padding);
--button-sm-font-size: var(--theme-pop-button-size);
--button-sm-radius: var(--theme-pop-button-radius);
display: flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
font-size: 12px;
color: var(--tx-2);
justify-content: space-between;
width: 100%;
gap: var(--theme-pop-footer-gap);
font-size: var(--theme-pop-note-size);
color: var(--tx-3);
}
.nav-item[aria-current="page"] :global(svg) {
color: var(--nav-c, var(--gold));
@@ -385,7 +386,7 @@
grid-template-columns: var(--rail-expanded-width) minmax(0, 1fr);
}
.sidebar {
background: var(--bg-1);
background: var(--rail-background);
border-right: 1px solid var(--line);
--icon-stroke: var(--manage-icon-stroke);
padding: var(--rail-padding);
@@ -529,9 +530,9 @@
border-radius: var(--rail-queue-ring-radius);
border: var(--rail-queue-ring-border) solid transparent;
border-top-color: var(--sc-video);
animation: rail-spin var(--rail-queue-ring-duration) linear infinite;
animation: var(--queue-loop, rail-spin) var(--rail-queue-ring-duration) linear infinite;
}
@keyframes rail-spin {
@keyframes -global-rail-spin {
to {
transform: rotate(360deg);
}
@@ -560,6 +561,7 @@
text-decoration: none;
}
.app-body {
animation: a-page-enter var(--page-enter-duration) var(--ease-out);
display: flex;
flex-direction: column;
min-height: 0;
@@ -610,13 +612,6 @@
color: var(--tx-3);
margin-left: 8px;
}
.motion {
display: flex;
align-items: center;
gap: 6px;
font-size: 10px;
color: var(--text-3);
}
.body {
flex: 1;
min-height: 0;
@@ -0,0 +1,14 @@
<script lang="ts">
import { MOTION_MODES, reduceMotion, setMotionMode } from "$lib/reduceMotion.svelte";
import "$lib/components/manage/management.css";
</script>
<div class="mg-options" role="group" aria-label="动效强度">
{#each MOTION_MODES as mode (mode.id)}
<button class="mg-option" class:on={reduceMotion.mode === mode.id}
aria-pressed={reduceMotion.mode === mode.id} disabled={reduceMotion.system}
onclick={() => setMotionMode(mode.id)}>{mode.label}</button>
{/each}
{#if reduceMotion.system}<span role="status">关闭 · 跟随系统</span>{/if}
{#if reduceMotion.storageUnavailable}<span role="status">浏览器禁止本地存储:本次有效,其他操作不受影响</span>{/if}
</div>
@@ -1,4 +1,5 @@
<script lang="ts">
import Icon from "$lib/components/ui/Icon.svelte";
import { THEMES, theme, setTheme, themeStorageUnavailable } from "$lib/theme";
let {
compact = false,
@@ -48,27 +49,31 @@
>
<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 + " · " + item.tone}</small>{#if !tiles}<span
>{item.description}</span
>{/if}</span
>
<span class="check" class:tile-check={tiles} aria-hidden="true"
>{$theme === item.id ? "✓" : ""}</span
>{#if $theme === item.id}<Icon name="check" size={14} />{/if}</span
>
</button>
{/each}
</div>
{#if $themeStorageUnavailable}<p class="notice" role="status">
{#if $themeStorageUnavailable && !compact}<p class="notice" role="status">
浏览器禁止本地存储:本次有效,其他操作不受影响
</p>{/if}
@@ -80,14 +85,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 +104,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;
}
@@ -103,6 +117,26 @@
flex-direction: column;
}
.choices.compact {
--choice-box-sizing: border-box;
--choice-description-size: var(--theme-pop-note-size);
--choice-description-line: var(--theme-choice-description-line);
--choice-gap: var(--theme-choice-gap);
--choice-radius: var(--theme-choice-radius);
--choice-border: transparent;
--choice-hover-background: rgb(var(--ink) / .04);
--choice-hover-border: var(--line-2);
--choice-selected: color-mix(in srgb, var(--gold) 55%, transparent);
--choice-selected-bg: color-mix(in srgb, var(--gold) 8%, transparent);
--choice-tone-font: var(--theme-choice-english-font);
--choice-preview-radius: var(--theme-choice-preview-radius);
--choice-preview-art: var(--theme-preview-art);
--choice-art-shadow: 0 0 0 1px var(--line-2);
--choice-art-border: 0;
--choice-dock-radius: 3px;
--choice-dock-width: 100%;
--choice-dock-border: 1px solid var(--line-2);
--choice-dock-background: var(--bg-3);
gap: var(--theme-choice-list-gap);
grid-template-columns: 1fr;
}
.choice {
@@ -112,7 +146,7 @@
grid-template-columns: minmax(0, 1fr) var(--choice-check-width, 18px);
gap: var(--choice-gap, 8px);
padding: 8px;
border: 1px solid var(--line-2);
border: 1px solid var(--choice-border, var(--line-2));
border-radius: var(--choice-radius, var(--r-md));
background: var(--bg-2);
color: var(--tx-1);
@@ -120,18 +154,20 @@
cursor: pointer;
}
.choice:hover {
border-color: var(--line-3);
background: var(--bg-3);
border-color: var(--choice-hover-border, var(--line-3));
background: var(--choice-hover-background, var(--bg-3));
}
.choice.selected {
border-color: var(--choice-selected, var(--gold));
box-shadow: var(--choice-shadow, none);
background: var(--choice-selected-bg, var(--bg-2));
}
.choice:focus-visible {
outline: 2px solid var(--info);
outline-offset: 2px;
}
.compact .choice {
font: var(--theme-choice-font);
grid-template-columns: 76px minmax(0, 1fr) 18px;
align-items: center;
}
@@ -139,7 +175,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 +216,7 @@
background: var(--sc-image);
}
.stage {
position: relative;
padding: 5px 6px;
display: flex;
flex-direction: column;
@@ -188,13 +226,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 +246,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;
@@ -222,7 +273,8 @@
}
.copy > span {
width: 100%;
font-size: 11px;
font-size: var(--choice-description-size, 11px);
line-height: var(--choice-description-line, inherit);
color: var(--tx-2);
}
.check {
@@ -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')}
@@ -162,7 +162,7 @@
border-radius: var(--r-lg) 0 0 var(--r-lg);
box-shadow: var(--shadow-float);
outline: none;
animation: drawer-slide var(--d-drawer) var(--ease-drawer) both;
animation: var(--drawer-animation, drawer-slide) var(--d-drawer) var(--ease-drawer) both;
}
.drawer-header {
display: flex;
@@ -229,7 +229,11 @@
opacity: 1;
}
}
@keyframes drawer-slide {
@keyframes -global-drawer-calm {
from { opacity: 0; transform: translateY(var(--pop-enter-y)) scale(var(--pop-enter-scale)); }
to { opacity: 1; transform: none; }
}
@keyframes -global-drawer-slide {
from {
transform: translateX(100%);
}
+41 -13
View File
@@ -14,6 +14,8 @@
children: Snippet;
/** Open above a dock, retaining the shared dialog focus and keyboard behavior. */
anchor?: HTMLElement | null;
/** HEL-726 theme picker uses the same dialog behavior beside the rail. */
rail?: boolean;
headerActions?: Snippet;
}
@@ -26,6 +28,7 @@
footer,
children,
anchor = null,
rail = false,
headerActions,
}: Props = $props();
@@ -129,6 +132,24 @@
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="modal-backdrop"
style:--modal-overlay={rail ? 'transparent' : undefined}
style:--modal-box-sizing={rail ? 'border-box' : undefined}
style:--modal-width={rail ? 'var(--theme-pop-width)' : undefined}
style:--modal-position={rail ? 'fixed' : undefined}
style:--modal-left={rail ? 'var(--theme-pop-left)' : undefined}
style:--modal-bottom={rail ? 'var(--theme-pop-bottom)' : undefined}
style:--modal-border={rail ? '1px solid var(--line-2)' : undefined}
style:--modal-bg={rail ? 'var(--bg-2)' : undefined}
style:--modal-shadow={rail ? 'var(--theme-pop-shadow)' : undefined}
style:--modal-origin={rail ? 'bottom left' : undefined}
style:--modal-header-padding={rail ? 'var(--theme-pop-header-padding)' : undefined}
style:--modal-title-size={rail ? 'var(--theme-pop-title-size)' : undefined}
style:--modal-title-weight={rail ? '700' : undefined}
style:--modal-header-gap={rail ? 'var(--theme-pop-header-gap)' : undefined}
style:--modal-close-size={rail ? 'var(--theme-pop-button-height)' : undefined}
style:--modal-body-padding={rail ? 'var(--theme-pop-body-padding)' : undefined}
style:--modal-footer-padding={rail ? 'var(--theme-pop-footer-padding)' : undefined}
style:--modal-footer-border={rail ? '1px solid var(--line)' : undefined}
class:anchored={!!anchor}
onclick={handleBackdropClick}
>
@@ -186,17 +207,23 @@
align-items: center;
justify-content: center;
padding: 24px;
background: var(--overlay);
background: var(--modal-overlay, var(--overlay));
animation: modal-fade var(--d-state) ease-out;
}
.modal-panel {
width: min(520px, 100%);
width: var(--modal-width, min(520px, 100%));
box-sizing: var(--modal-box-sizing, content-box);
position: var(--modal-position, static);
left: var(--modal-left, auto);
bottom: var(--modal-bottom, auto);
border: var(--modal-border, 0);
transform-origin: var(--modal-origin, center);
max-height: calc(100vh - 96px);
display: flex;
flex-direction: column;
background: var(--float-bg);
background: var(--modal-bg, var(--float-bg));
border-radius: var(--r-lg);
box-shadow: var(--shadow-float);
box-shadow: var(--modal-shadow, var(--shadow-float));
outline: none;
animation: modal-rise var(--d-pop) var(--ease-out);
}
@@ -242,22 +269,22 @@
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 18px 20px 0;
gap: var(--modal-header-gap, 12px);
padding: var(--modal-header-padding, 18px 20px 0);
}
.modal-title {
margin: 0;
font-family: var(--font-display);
font-size: var(--fs-title);
font-weight: 600;
font-size: var(--modal-title-size, var(--fs-title));
font-weight: var(--modal-title-weight, 600);
color: var(--text-primary);
}
.modal-close {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
width: var(--modal-close-size, 28px);
height: var(--modal-close-size, 28px);
margin-left: auto;
border: none;
border-radius: var(--radius-sm);
@@ -279,7 +306,7 @@
outline-offset: 2px;
}
.modal-body {
padding: 16px 20px 20px;
padding: var(--modal-body-padding, 16px 20px 20px);
overflow-y: auto;
font-size: 14px;
line-height: 1.5;
@@ -289,7 +316,8 @@
display: flex;
justify-content: flex-end;
gap: 8px;
padding: 0 20px 20px;
padding: var(--modal-footer-padding, 0 20px 20px);
border-top: var(--modal-footer-border, 0);
}
@keyframes modal-fade {
from {
@@ -302,7 +330,7 @@
@keyframes modal-rise {
from {
opacity: 0;
transform: translateY(8px);
transform: translateY(var(--pop-enter-y)) scale(var(--pop-enter-scale));
}
to {
opacity: 1;
@@ -113,9 +113,9 @@
);
box-shadow: none;
transition: none;
animation: progress-slide 1.2s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-progressbar-progress-slide) 1.2s ease-in-out infinite;
}
@keyframes progress-slide {
@keyframes -global-motion-progressbar-progress-slide {
0% {
left: -40%;
}
@@ -23,12 +23,12 @@
.skeleton {
background: var(--bg-3);
border-radius: var(--r-sm);
animation: skeleton-breath 1.4s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-skeleton-skeleton-breath) 1.4s ease-in-out infinite;
}
.skeleton.circle {
border-radius: 50%;
}
@keyframes skeleton-breath {
@keyframes -global-motion-skeleton-skeleton-breath {
50% {
opacity: 0.5;
}
@@ -20,7 +20,7 @@
border-style: solid;
border-color: var(--spinner-track, var(--bg-elevated));
border-top-color: var(--spinner-arc, var(--accent));
animation: spin 0.7s linear infinite;
animation: var(--decorative-loop-name, motion-spinner-spin) 0.7s linear infinite;
}
.spinner-sm {
width: 14px;
@@ -48,7 +48,7 @@
white-space: nowrap;
border: 0;
}
@keyframes spin {
@keyframes -global-motion-spinner-spin {
to {
transform: rotate(360deg);
}
@@ -76,9 +76,9 @@
background: var(--bg-4);
}
.dot.pulsing {
animation: chip-pulse 1.4s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-statuschip-chip-pulse) 1.4s ease-in-out infinite;
}
@keyframes chip-pulse {
@keyframes -global-motion-statuschip-chip-pulse {
0%,
100% {
opacity: 1;
@@ -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":
@@ -77,6 +105,7 @@ export const icons = {
'<rect x="6" y="4" width="4" height="16" rx="1"/><rect x="14" y="4" width="4" height="16" rx="1"/>',
stop: '<rect x="5" y="5" width="14" height="14" rx="2"/>',
// Status
motion: '<path d="M3 12h4l3-8 4 16 3-8h4"/>',
check: '<path d="M20 6 9 17l-5-5"/>',
star: '<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/>',
alert:
@@ -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}
@@ -84,9 +84,9 @@
height: 6px;
border-radius: 50%;
background: var(--run);
animation: wb-chip-breath 2s cubic-bezier(0.16, 1, 0.3, 1) infinite;
animation: var(--decorative-loop-name, motion-jobchip-wb-chip-breath) 2s cubic-bezier(0.16, 1, 0.3, 1) infinite;
}
@keyframes wb-chip-breath {
@keyframes -global-motion-jobchip-wb-chip-breath {
0%,
100% {
opacity: 0.35;
@@ -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,842 @@
.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="running"] {
--project-stage-shadow: var(--running-stage-shadow);
}
.project-workspace [data-state="running"] .avatar,
.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-stage-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);
}
+4
View File
@@ -599,6 +599,10 @@ export const de: Dict = {
// --- Build scene ---
"buildScene.title": "Szene bauen",
"buildScene.builderBadge": "3D-Builder",
"buildScene.suggestionTwoPerson": "Komposition mit zwei Personen",
"buildScene.suggestionHeroPose": "Komposition mit Heldenpose",
"buildScene.suggestionBlockout": "Einfachen Raum anlegen",
"buildScene.suggestionCapture": "Referenzbild aufnehmen",
"buildScene.preparing": "Szene wird vorbereitet…",
"buildScene.stillLoading": "Szene lädt noch…",
"buildScene.expandChat": "Chat ausklappen",
+4
View File
@@ -579,6 +579,10 @@ export const en = {
// --- Build scene ---
"buildScene.title": "Build Scene",
"buildScene.builderBadge": "3D Builder",
"buildScene.suggestionTwoPerson": "Two-person composition",
"buildScene.suggestionHeroPose": "Hero pose composition",
"buildScene.suggestionBlockout": "Block out a simple room",
"buildScene.suggestionCapture": "Capture a reference image",
"buildScene.preparing": "Preparing scene…",
"buildScene.stillLoading": "Scene still loading…",
"buildScene.expandChat": "Expand chat",
+4
View File
@@ -599,6 +599,10 @@ export const es: Dict = {
// --- Build scene ---
"buildScene.title": "Componer escena",
"buildScene.builderBadge": "Editor 3D",
"buildScene.suggestionTwoPerson": "Composición de dos personas",
"buildScene.suggestionHeroPose": "Composición con pose heroica",
"buildScene.suggestionBlockout": "Crear una habitación sencilla",
"buildScene.suggestionCapture": "Capturar una imagen de referencia",
"buildScene.preparing": "Preparando la escena…",
"buildScene.stillLoading": "La escena aún se está cargando…",
"buildScene.expandChat": "Expandir chat",
+4
View File
@@ -603,6 +603,10 @@ export const fr: Dict = {
// --- Build scene ---
"buildScene.title": "Composer la scène",
"buildScene.builderBadge": "Éditeur 3D",
"buildScene.suggestionTwoPerson": "Composition à deux personnages",
"buildScene.suggestionHeroPose": "Composition en pose héroïque",
"buildScene.suggestionBlockout": "Créer une pièce simple",
"buildScene.suggestionCapture": "Capturer une image de référence",
"buildScene.preparing": "Préparation de la scène…",
"buildScene.stillLoading": "Scène en cours de chargement…",
"buildScene.expandChat": "Développer la discussion",
+4
View File
@@ -592,6 +592,10 @@ export const ja: Dict = {
// --- Build scene ---
"buildScene.title": "シーン構築",
"buildScene.builderBadge": "3D ビルダー",
"buildScene.suggestionTwoPerson": "二人の会話の構図",
"buildScene.suggestionHeroPose": "ヒーローポーズの構図",
"buildScene.suggestionBlockout": "シンプルな部屋を作成",
"buildScene.suggestionCapture": "参考画像をキャプチャ",
"buildScene.preparing": "シーンを準備中…",
"buildScene.stillLoading": "シーンをまだ読み込み中…",
"buildScene.expandChat": "チャットを展開",
+4
View File
@@ -582,6 +582,10 @@ export const ko: Dict = {
// --- Build scene ---
"buildScene.title": "장면 구성",
"buildScene.builderBadge": "3D 빌더",
"buildScene.suggestionTwoPerson": "두 사람 대화 구도",
"buildScene.suggestionHeroPose": "영웅 자세 구도",
"buildScene.suggestionBlockout": "간단한 방 만들기",
"buildScene.suggestionCapture": "참조 이미지 캡처",
"buildScene.preparing": "장면 준비 중…",
"buildScene.stillLoading": "장면을 아직 불러오는 중…",
"buildScene.expandChat": "채팅 펼치기",
+4
View File
@@ -566,6 +566,10 @@ export const zh: Dict = {
// --- Build scene ---
"buildScene.title": "搭建场景",
"buildScene.builderBadge": "3D 搭建器",
"buildScene.suggestionTwoPerson": "双人对话构图",
"buildScene.suggestionHeroPose": "英雄姿态构图",
"buildScene.suggestionBlockout": "搭建简单房间",
"buildScene.suggestionCapture": "截取参考画面",
"buildScene.preparing": "正在准备场景……",
"buildScene.stillLoading": "场景仍在加载……",
"buildScene.expandChat": "展开对话",
+85 -22
View File
@@ -1,33 +1,90 @@
import { storageGet, storageSet } from "./storage";
import { storageGet, storageTrySet } from "./storage";
/**
* 减少动态效果 (HEL-649 §五). The OS setting always wins (app.css also reacts
* to `prefers-reduced-motion` directly, so it cannot be switched off here);
* otherwise the top-bar switch decides. The effective value is mirrored to
* `<html data-reduce="1">`, which is what every reduced-motion rule keys on.
*/
const STORAGE_KEY = "aigc-reduce-motion";
export type MotionMode = "full" | "calm" | "off";
export const MOTION_MODES = [
{ id: "full", label: "完整" },
{ id: "calm", label: "克制" },
{ id: "off", label: "关闭" },
] as const;
const STORAGE_KEY = "aigc-motion";
const QUERY = "(prefers-reduced-motion: reduce)";
export const reduceMotion = $state({ system: false, manual: false });
export const reduceMotion = $state({
system: false,
manual: false,
preference: "full" as MotionMode,
mode: "full" as MotionMode,
loopRevision: 0,
storageUnavailable: false,
});
let stop: (() => void) | null = null;
const isMode = (value: string | null): value is MotionMode =>
value === "full" || value === "calm" || value === "off";
function apply() {
document.documentElement.dataset.reduce =
reduceMotion.system || reduceMotion.manual ? "1" : "0";
function apply(initial = false) {
const root = document.documentElement;
const mode = reduceMotion.system ? "off" : reduceMotion.preference;
if (!initial && mode !== reduceMotion.mode) {
// Returning to full must wait for the next page/task trigger. New nodes
// have no marker; mounted loops stay at their static initial appearance.
root
.querySelectorAll(
".aurora i, .orb .core, .orb .ring, .thinking i, .pstep.run .s, .queue-ring, .a-scan-beam, .a-tile-ring > i",
)
.forEach((node) => node.setAttribute("data-motion-held", ""));
for (const animation of document.getAnimations()) {
if (animation.effect?.getTiming().iterations === Infinity) {
const target = (animation.effect as KeyframeEffect).target;
if (target instanceof Element)
target.setAttribute("data-motion-held", "");
} else {
try {
animation.finish();
} catch {
animation.cancel();
}
}
}
reduceMotion.loopRevision++;
}
reduceMotion.mode = mode;
reduceMotion.manual = reduceMotion.preference === "off";
root.dataset.motion = mode;
root.dataset.reduce = mode === "off" ? "1" : "0";
root.classList.toggle("calm", mode === "calm");
root.classList.toggle("reduce", mode === "off");
if (!initial && mode === "full") {
// Loops suppressed by calm/off have no Animation until the tokens change.
// Hold those too, in the same task and before the next paint.
for (const animation of document.getAnimations()) {
if (animation.effect?.getTiming().iterations !== Infinity) continue;
const target = (animation.effect as KeyframeEffect).target;
if (target instanceof Element)
target.setAttribute("data-motion-held", "");
animation.cancel();
}
}
if (!initial) window.dispatchEvent(new Event("aigc-motion-change"));
}
/** Call once on the client (root layout). Returns the teardown. */
/** Root-layout lifecycle; OS override never overwrites the saved preference. */
export function initReduceMotion(): () => void {
if (typeof window === "undefined") return () => {};
stop?.();
const mq = window.matchMedia(QUERY);
const saved = storageGet(STORAGE_KEY);
const legacy = storageGet("aigc-reduce-motion");
reduceMotion.preference =
saved === null
? legacy === "1" || legacy === "true"
? "off"
: "full"
: isMode(saved)
? saved
: "full";
reduceMotion.system = mq.matches;
reduceMotion.manual = storageGet(STORAGE_KEY) === "1";
apply();
const onChange = (e: MediaQueryListEvent) => {
reduceMotion.system = e.matches;
apply(true);
const onChange = (event: MediaQueryListEvent) => {
reduceMotion.system = event.matches;
apply();
};
mq.addEventListener("change", onChange);
@@ -38,8 +95,14 @@ export function initReduceMotion(): () => void {
};
}
export function setReduceMotion(on: boolean) {
reduceMotion.manual = on;
storageSet(STORAGE_KEY, on ? "1" : "0");
export function setMotionMode(mode: MotionMode) {
if (reduceMotion.system || !isMode(mode)) return;
reduceMotion.preference = mode;
reduceMotion.storageUnavailable = !storageTrySet(STORAGE_KEY, mode);
apply();
}
/** Compatibility for existing boolean controls. */
export function setReduceMotion(on: boolean) {
setMotionMode(on ? "off" : "full");
}
@@ -200,9 +200,9 @@
border-color: var(--accent);
}
.rail-dot.run {
animation: rail-pulse 1.4s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-shotsessionrail-rail-pulse) 1.4s ease-in-out infinite;
}
@keyframes rail-pulse {
@keyframes -global-motion-shotsessionrail-rail-pulse {
0%,
100% {
box-shadow: 0 0 0 0 var(--accent-glow);
@@ -266,9 +266,9 @@
}
.dot.run {
background: var(--run);
animation: dot-pulse 1.4s ease-in-out infinite;
animation: var(--decorative-loop-name, motion-shotsessionrail-dot-pulse) 1.4s ease-in-out infinite;
}
@keyframes dot-pulse {
@keyframes -global-motion-shotsessionrail-dot-pulse {
0%,
100% {
opacity: 1;
@@ -42,6 +42,7 @@ let orbit: OrbitControls;
let gizmo: TransformControls;
let gizmoHelper: THREE.Object3D;
let raf = 0;
let cleanupVisibility: (() => void) | null = null;
let resizeObserver: ResizeObserver;
let cleanupPointerUp: (() => void) | null = null;
@@ -473,6 +474,7 @@ let exporting = false;
// ── loop ────────────────────────────────────────────────────────
function tick() {
if (document.hidden) { raf = 0; return; }
raf = requestAnimationFrame(tick);
if (exporting) return; // export drives the scene on its own fixed clock
const now = performance.now() / 1000;
@@ -635,10 +637,18 @@ let exporting = false;
});
resizeObserver.observe(container);
raf = requestAnimationFrame(tick);
const visibility = () => {
cancelAnimationFrame(raf);
raf = 0;
if (!document.hidden) tick();
};
document.addEventListener('visibilitychange', visibility);
cleanupVisibility = () => document.removeEventListener('visibilitychange', visibility);
visibility();
});
onDestroy(() => {
cleanupVisibility?.();
cancelAnimationFrame(raf);
resizeObserver?.disconnect();
cleanupPointerUp?.();
+10 -1
View File
@@ -29,10 +29,19 @@ export function storageGet(key: string): string | null {
}
export function storageSet(key: string, value: string): void {
storageTrySet(key, value);
}
/** Also reports failure when a preference UI needs to explain persistence. */
export function storageTrySet(key: string, value: string): boolean {
try {
webStorage()?.setItem(key, value);
const storage = webStorage();
if (!storage) return false;
storage.setItem(key, value);
return true;
} catch {
// Private mode / quota exceeded — persistence is best-effort.
return false;
}
}
+23 -6
View File
@@ -7,25 +7,32 @@ export const THEMES = [
id: "night",
name: "夜片场",
english: "Nocturne",
description: "墨黑与钨丝金 · 沉浸式创作",
tone: "深色 · 默认",
description:
"墨黑棚里一盏钨丝灯:作品最亮,金色只给“去做”。夜间与沉浸创作。",
},
{
id: "day",
name: "日光棚",
english: "Daylight",
description: "暖白纸面 · 白天办公与长时间审稿",
tone: "浅色",
description:
"开窗的白天摄影棚:暖白纸面、墨色文字、琥珀主键。白天办公与长时间审稿。",
},
{
id: "grade",
name: "调色间",
english: "Grading",
description: "中性深灰 · 判断作品色彩",
tone: "中性深灰",
description:
"调色室的中性灰:不给作品染色,场景色降饱和、主键为白。判断色彩、久盯不累。",
},
{
id: "bluehour",
name: "蓝调时刻",
english: "Blue Hour",
description: "靛蓝与珊瑚 · 提案与灵感发散",
tone: "深蓝",
description: "日落后的靛蓝天色配珊瑚主光,氛围最浓。提案、展示与灵感发散。",
},
] as const;
export type ThemeId = (typeof THEMES)[number]["id"];
@@ -69,7 +76,7 @@ export function setTheme(id: ThemeId, event?: MouseEvent) {
apply();
return;
}
if (document.startViewTransition) {
if (document.startViewTransition && root.dataset.motion !== "calm") {
if (event && event.detail !== 0) {
root.style.setProperty("--theme-x", event.clientX + "px");
root.style.setProperty("--theme-y", event.clientY + "px");
@@ -101,6 +108,16 @@ export function initTheme() {
document.documentElement.dataset.theme = id;
theme.set(id);
};
const finishMotion = () => {
transition?.skipTransition();
clearTimeout(fallbackTimer);
document.documentElement.classList.remove("theme-anim");
};
window.addEventListener("aigc-motion-change", finishMotion);
window.addEventListener("storage", sync);
return () => window.removeEventListener("storage", sync);
return () => {
finishMotion();
window.removeEventListener("aigc-motion-change", finishMotion);
window.removeEventListener("storage", sync);
};
}
+21 -4
View File
@@ -13,11 +13,13 @@ export type Toast = {
/** Auto-dismiss delay in ms. 0 = sticky until dismissed. */
duration: number;
action?: ToastAction;
leaving?: boolean;
};
type Listener = (toasts: Toast[]) => void;
const DEFAULT_DURATION = 3200;
const EXIT_DURATION = 300;
let seq = 0;
let toasts: Toast[] = [];
@@ -27,6 +29,7 @@ type TimerState = {
remaining: number;
startedAt: number;
handle: ReturnType<typeof setTimeout>;
paused?: boolean;
};
const timers = new Map<number, TimerState>();
@@ -56,7 +59,18 @@ function schedule(id: number, delay: number) {
timers.set(id, {
remaining: delay,
startedAt: Date.now(),
handle: setTimeout(() => dismissToast(id), delay),
handle: setTimeout(() => expireToast(id), delay),
});
}
function expireToast(id: number) {
timers.delete(id);
toasts = toasts.map((t) => (t.id === id ? { ...t, leaving: true } : t));
emit();
timers.set(id, {
remaining: 0,
startedAt: Date.now(),
handle: setTimeout(() => dismissToast(id), EXIT_DURATION),
});
}
@@ -76,24 +90,27 @@ export function showToast(
/** Pause auto-dismiss (e.g. while the pointer or focus is on the toast). */
export function pauseToast(id: number) {
const timer = timers.get(id);
if (!timer) return;
if (!timer || timer.paused || toasts.find((t) => t.id === id)?.leaving)
return;
clearTimeout(timer.handle);
timer.remaining = Math.max(
0,
timer.remaining - (Date.now() - timer.startedAt),
);
timer.startedAt = Date.now();
timer.paused = true;
}
/** Resume auto-dismiss after a pause. */
export function resumeToast(id: number) {
const timer = timers.get(id);
if (!timer) return;
if (!timer?.paused) return;
clearTimeout(timer.handle);
const delay = Math.max(0, timer.remaining);
timer.remaining = delay;
timer.startedAt = Date.now();
timer.handle = setTimeout(() => dismissToast(id), delay);
timer.paused = false;
timer.handle = setTimeout(() => expireToast(id), delay);
}
export const toast = {
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+207 -42
View File
@@ -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,9 @@ code,
width: 100%;
}
.a-btn.primary {
border-color: transparent;
position: relative;
overflow: hidden;
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 +125,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 +162,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 +179,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 +189,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 +275,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 +305,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>.
@@ -553,7 +583,7 @@ button.a-tile:disabled {
background: conic-gradient(var(--accent) 0.3turn, var(--line-2) 0);
-webkit-mask: radial-gradient(circle, transparent 9.5px, #000 10.5px);
mask: radial-gradient(circle, transparent 9.5px, #000 10.5px);
animation: a-tile-spin 900ms linear infinite;
animation: var(--tile-loop, a-tile-spin) 900ms linear infinite;
}
@keyframes a-tile-spin {
to {
@@ -908,27 +938,6 @@ button.a-tile:disabled {
border-radius: var(--r-sm);
}
/* Reduced-motion baseline for components that still carry their own
durations. Components that need a styled static fallback (Skeleton,
ProgressBar indeterminate, StatusChip pulse) also handle this in their
scoped styles. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
:root[data-reduce="1"] *,
:root[data-reduce="1"] *::before,
:root[data-reduce="1"] *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
/* Refract shared behavior: desktop composition, paper surfaces, direct feedback. */
[hidden] {
display: none !important;
@@ -1008,13 +1017,23 @@ select:focus-visible {
border-radius: inherit;
pointer-events: none;
opacity: 0;
background-image: var(--lattice);
z-index: -1;
background-image:
radial-gradient(
var(--lattice-light-radius) circle at
var(--lattice-x, var(--pointer-x, 50%))
var(--lattice-y, var(--pointer-y, 50%)),
color-mix(in srgb, var(--scene) var(--lattice-scene), transparent),
transparent 70%
),
var(--lattice);
mask-image: radial-gradient(
70px circle at var(--pointer-x, -100px) var(--pointer-y, -100px),
#000,
transparent
var(--lattice-mask-radius) circle at var(--lattice-x, var(--pointer-x, 50%))
var(--lattice-y, var(--pointer-y, 50%)),
#000 0,
transparent var(--lattice-mask-end)
);
transition: opacity 180ms ease;
transition: opacity var(--lattice-duration) var(--ease-out);
}
@media (hover: hover) and (pointer: fine) {
.reference-option:hover::after {
@@ -1044,3 +1063,149 @@ select:focus-visible {
color: color-mix(in srgb, var(--sc-agent) 70%, var(--hi));
border-color: color-mix(in srgb, var(--sc-agent) 35%, transparent);
}
/* HEL-716 / HEL-726 effects: one shared source, theme values in themes.css. */
@keyframes a-page-enter {
from {
opacity: 0;
transform: translateY(var(--page-enter-y));
}
to {
opacity: 1;
transform: none;
}
}
.a-btn.primary::after {
display: var(--effect-display);
content: "";
position: absolute;
top: 0;
bottom: 0;
width: var(--primary-sweep-width);
left: var(--primary-sweep-from);
background: var(--primary-sweep);
transform: skewX(var(--primary-sweep-skew));
transition: left 0s;
pointer-events: none;
}
.a-btn.primary:hover:not(:disabled):not([aria-disabled="true"])::after {
left: var(--primary-sweep-to);
transition: left var(--t-reveal) var(--ease-out);
}
.a-result-develop > img,
.a-result-develop > video {
animation: var(--result-develop) var(--t-reveal) var(--ease-out);
}
@keyframes a-develop-calm {
from {
filter: var(--result-calm-filter);
opacity: var(--result-calm-opacity);
}
to {
filter: none;
opacity: 1;
}
}
/* Finishing a one-shot or changing mode must not restart a mounted loop. */
[data-motion-held] {
animation: none !important;
}
@keyframes a-develop {
0% {
filter: blur(18px) brightness(1.8) saturate(0);
opacity: 0.2;
transform: scale(1.015);
}
60% {
filter: blur(2px) brightness(1.1) saturate(0.8);
opacity: 1;
}
100% {
filter: none;
transform: none;
}
}
@keyframes a-develop-day {
0% {
filter: blur(16px) brightness(1.35) sepia(0.6) saturate(0.2);
opacity: 0.15;
transform: scale(1.015);
}
60% {
filter: blur(2px) sepia(0.12);
opacity: 1;
}
100% {
filter: none;
transform: none;
}
}
@keyframes a-develop-grade {
0% {
filter: blur(10px) saturate(0);
opacity: 0.25;
}
100% {
filter: none;
opacity: 1;
}
}
.a-scan-beam {
display: var(--effect-display);
position: absolute;
top: 0;
bottom: 0;
width: var(--scan-width);
left: calc(0% - var(--scan-width));
background: var(--beam);
animation: a-scan var(--scan-duration) var(--ease-io) infinite;
pointer-events: none;
}
@keyframes a-scan {
to {
left: 100%;
}
}
:root[data-reduce="1"] .a-scan-beam,
:root[data-reduce="1"] .a-btn.primary::after {
display: none;
}
@media (prefers-reduced-motion: reduce) {
.a-scan-beam,
.a-btn.primary::after {
display: none;
}
}
.a-viewfinder::after {
content: "";
position: absolute;
inset: var(--viewfinder-inset);
border-radius: inherit;
pointer-events: none;
opacity: 0;
transition:
opacity var(--t-base),
inset var(--viewfinder-position-duration, var(--t-slow)) var(--ease-out);
background:
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) top
left/var(--viewfinder-length) var(--viewfinder-stroke) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) top
left/var(--viewfinder-stroke) var(--viewfinder-length) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) top
right/var(--viewfinder-length) var(--viewfinder-stroke) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) top
right/var(--viewfinder-stroke) var(--viewfinder-length) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) bottom
left/var(--viewfinder-length) var(--viewfinder-stroke) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) bottom
left/var(--viewfinder-stroke) var(--viewfinder-length) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) bottom
right/var(--viewfinder-length) var(--viewfinder-stroke) no-repeat,
linear-gradient(var(--viewfinder-color), var(--viewfinder-color)) bottom
right/var(--viewfinder-stroke) var(--viewfinder-length) no-repeat;
}
.a-viewfinder.a-in-frame::after {
opacity: 1;
inset: var(--viewfinder-selected-inset);
}
@@ -1,4 +1,5 @@
<script lang="ts">
import { storageGet, storageSet, storageRemove } from '$lib/storage';
import { onMount } from 'svelte';
import { toStore } from 'svelte/store';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
@@ -47,18 +48,18 @@
let chatCollapsed = $state(false);
$effect(() => {
railCollapsed = localStorage.getItem(RAIL_KEY) === '1';
chatCollapsed = localStorage.getItem(CHAT_KEY) === '1';
railCollapsed = storageGet(RAIL_KEY) === '1';
chatCollapsed = storageGet(CHAT_KEY) === '1';
});
function toggleRail() {
railCollapsed = !railCollapsed;
localStorage.setItem(RAIL_KEY, railCollapsed ? '1' : '0');
storageSet(RAIL_KEY, railCollapsed ? '1' : '0');
}
function toggleChat() {
chatCollapsed = !chatCollapsed;
localStorage.setItem(CHAT_KEY, chatCollapsed ? '1' : '0');
storageSet(CHAT_KEY, chatCollapsed ? '1' : '0');
}
function isSceneSession(s: AgentSession): boolean {
@@ -77,7 +78,7 @@
if (shotStore.compositionId != null) await shotStore.flushSave();
sessionId = id;
compositionReady = false;
if (persist) localStorage.setItem(ACTIVE_SESSION_KEY, String(id));
if (persist) storageSet(ACTIVE_SESSION_KEY, String(id));
const comp = await shotStore.loadComposition(id);
if (comp && comp.title === 'Untitled composition') {
const title = `Scene · ${id}`;
@@ -106,7 +107,7 @@
// (AI Canvas) excludes them, so the two surfaces never leak
// into each other.
const sessions = await agentApi.listSceneSessions();
const stored = Number(localStorage.getItem(ACTIVE_SESSION_KEY) ?? '');
const stored = Number(storageGet(ACTIVE_SESSION_KEY) ?? '');
const sceneSessions = sessions.filter(isSceneSession);
const initial = sceneSessions.find((s) => s.id === stored) ?? sceneSessions[0] ?? null;
if (initial) {
@@ -143,8 +144,8 @@
const mine = comps.find((c) => c.agent_session_id === id);
if (mine) await shotApi.deleteComposition(mine.id);
await agentApi.deleteSession(id);
if (Number(localStorage.getItem(ACTIVE_SESSION_KEY)) === id) {
localStorage.removeItem(ACTIVE_SESSION_KEY);
if (Number(storageGet(ACTIVE_SESSION_KEY)) === id) {
storageRemove(ACTIVE_SESSION_KEY);
}
const sessions = await agentApi.listSceneSessions();
const next = sessions.find(isSceneSession);
+2 -1
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { storageGet } from '$lib/storage';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { agentApi, canvasApi } from '$lib/api';
@@ -10,7 +11,7 @@
onMount(async () => {
try {
const sessions = await agentApi.listSessions();
const stored = Number(localStorage.getItem('calliope.agents.activeSession'));
const stored = Number(storageGet('calliope.agents.activeSession'));
const found =
sessions.find((s) => s.id === stored) ?? sessions[0] ?? (await agentApi.createSession({}));
const graph = found.project_id
+349 -198
View File
@@ -1,10 +1,14 @@
<script lang="ts">
import { resolve } from '$app/paths';
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { toStore } from 'svelte/store';
import { createMutation, createQuery, useQueryClient } from '@tanstack/svelte-query';
import {
createMutation,
createQuery,
useQueryClient,
} from '@tanstack/svelte-query';
import {
SvelteFlow,
Controls,
@@ -16,6 +20,7 @@
type Viewport,
} from '@xyflow/svelte';
import '@xyflow/svelte/dist/style.css';
import '$lib/canvas/canvas.css';
import AppShell from '$lib/components/shell/AppShell.svelte';
import AgentChat from '$lib/components/agent/AgentChat.svelte';
import AgentComposer from '$lib/components/agent/AgentComposer.svelte';
@@ -44,7 +49,11 @@
type Location,
type Scene,
} from '$lib/api';
import type { AgentComposerPayload, SkillOption, WorkflowOption } from '$lib/agentComposer';
import type {
AgentComposerPayload,
SkillOption,
WorkflowOption,
} from '$lib/agentComposer';
import { connectEvents } from '$lib/events';
import { toast } from '$lib/toast';
@@ -145,7 +154,11 @@
caption: string;
} | null>(null);
function openMediaPreview(kind: 'image' | 'video', path: string | null, caption: string) {
function openMediaPreview(
kind: 'image' | 'video',
path: string | null,
caption: string,
) {
const src = assetUrl(path);
if (!src) return;
preview = { src, kind, caption };
@@ -184,10 +197,13 @@
// eslint-disable-next-line svelte/prefer-svelte-reactivity -- Effect-local job lookup is built and synchronously consumed into nodes, then discarded; graph/jobs already drive the effect.
const nodeRunning = new Map<number, boolean>();
for (const n of graph.nodes) {
const tracked = n.job_id != null ? jobs.find((j) => j.id === n.job_id) : undefined;
const tracked =
n.job_id != null ? jobs.find((j) => j.id === n.job_id) : undefined;
nodeRunning.set(
n.id,
tracked ? tracked.status === 'running' || tracked.status === 'pending' : false,
tracked
? tracked.status === 'running' || tracked.status === 'pending'
: false,
);
}
nodes = graph.nodes
@@ -204,7 +220,10 @@
title: n.title ?? 'Artifact',
artifactPath: n.artifact_path,
kind: n.type,
status: nodeRunning.get(n.id) ? 'running' : n.status,
status: nodeRunning.get(n.id)
? 'running'
: (jobs.find((j) => j.id === n.job_id)?.status ?? n.status),
jobId: n.job_id,
onOpenMedia: (kind: 'image' | 'video') =>
openMediaPreview(kind, n.artifact_path, n.title ?? 'Artifact'),
},
@@ -216,14 +235,23 @@
position: { x: n.x, y: n.y },
data: {
canvasNodeId: n.id,
entityType: n.entity_type as 'character' | 'location' | 'item' | 'scene',
entityType: n.entity_type as
'character' | 'location' | 'item' | 'scene',
title: n.title ?? 'Untitled',
imagePath: media.imagePath,
videoPath: media.videoPath,
onOpenMedia: (kind: 'image' | 'video') =>
kind === 'video'
? openMediaPreview('video', media.videoPath, n.title ?? 'Untitled')
: openMediaPreview('image', media.imagePath, n.title ?? 'Untitled'),
? openMediaPreview(
'video',
media.videoPath,
n.title ?? 'Untitled',
)
: openMediaPreview(
'image',
media.imagePath,
n.title ?? 'Untitled',
),
},
};
});
@@ -238,7 +266,9 @@
y: node.position.y,
});
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.savePosFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.savePosFailed'),
);
}
}
@@ -258,7 +288,11 @@
// Group drags: targetNode is null, `nodes` is the whole selection.
// Single drags: nodes[0] is the dragged node. Persist EVERYTHING —
// persisting only the last node dropped the rest of a group's moves.
const moved = e.nodes?.length ? e.nodes : e.targetNode ? [e.targetNode] : [];
const moved = e.nodes?.length
? e.nodes
: e.targetNode
? [e.targetNode]
: [];
if (moved.length > 0) void persistNodePositions(moved);
// A refetch landed during the drag: rebuild now that positions are
// settled (and re-ordered by the just-saved values on the next fetch).
@@ -277,7 +311,11 @@
return typeof id === 'number' ? id : null;
}
async function onBeforeDeleteCanvas({ nodes }: { nodes: Node[] }): Promise<boolean> {
async function onBeforeDeleteCanvas({
nodes,
}: {
nodes: Node[];
}): Promise<boolean> {
const blocked = nodes.filter(
(n) =>
n.type === 'entity' ||
@@ -292,11 +330,15 @@
}
async function onDeleteCanvas({ nodes }: { nodes: Node[] }) {
const ids = nodes.map(nodeServerId).filter((id): id is number => id != null);
const ids = nodes
.map(nodeServerId)
.filter((id): id is number => id != null);
if (ids.length === 0) return;
let fileDeletedCount = 0;
let keptCount = 0;
const results = await Promise.allSettled(ids.map((id) => canvasApi.deleteNode(canvasId, id)));
const results = await Promise.allSettled(
ids.map((id) => canvasApi.deleteNode(canvasId, id)),
);
for (const r of results) {
if (r.status === 'fulfilled') {
if (r.value.file_deleted) fileDeletedCount++;
@@ -310,7 +352,9 @@
return;
}
if (fileDeletedCount > 0 && keptCount > 0) {
toast.success(t('canvas.deletedMixed', { files: fileDeletedCount, kept: keptCount }));
toast.success(
t('canvas.deletedMixed', { files: fileDeletedCount, kept: keptCount }),
);
} else if (fileDeletedCount > 0) {
toast.success(t('canvas.deletedWithFile', { count: fileDeletedCount }));
} else {
@@ -365,7 +409,9 @@
// localStorage first (synchronous, survives navigation + reloads
// even if the request never lands), backend per canvas second.
storageSet(viewportLocalStorageKey(canvasId), json);
void canvasApi.patchCanvas(canvasId, { viewport_json: json }).catch(() => undefined);
void canvasApi
.patchCanvas(canvasId, { viewport_json: json })
.catch(() => undefined);
}, 500);
}
@@ -433,7 +479,9 @@
const activeSession = $derived(
activeId != null ? (sessions.find((s) => s.id === activeId) ?? null) : null,
);
const running = $derived(Boolean(activeSession?.running || activeSession?.status === 'running'));
const running = $derived(
Boolean(activeSession?.running || activeSession?.status === 'running'),
);
const sessionQuery = createQuery(
toStore(() => ({
@@ -448,7 +496,8 @@
const jobsQuery = createQuery(
toStore(() => ({
queryKey: ['agent-project-jobs', projectId ?? 'sandbox'],
queryFn: () => (projectId != null ? jobsApi.list(projectId) : playgroundApi.jobs()),
queryFn: () =>
projectId != null ? jobsApi.list(projectId) : playgroundApi.jobs(),
enabled: activeId != null,
})),
);
@@ -491,10 +540,16 @@
// gone session just 404s in the session query, which is recoverable.
activeId = pid;
// Deep-link handoff (/agents?project=&task=) pre-fills the composer once.
const prefill = sessionStorage.getItem('calliope.canvas.composerPrefill');
if (prefill) {
sessionStorage.removeItem('calliope.canvas.composerPrefill');
setComposerDraft(prefill);
try {
const prefill = sessionStorage.getItem(
'calliope.canvas.composerPrefill',
);
if (prefill) {
sessionStorage.removeItem('calliope.canvas.composerPrefill');
setComposerDraft(prefill);
}
} catch {
// A blocked handoff cache must not interrupt opening the real session.
}
replaceUrlParam('session');
return;
@@ -546,7 +601,9 @@
: await canvasApi.ensureForSession(s.id);
goto(resolve(`/canvas/${graph.canvas.id}?session=${s.id}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.openThatFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.openThatFailed'),
);
}
}
@@ -582,7 +639,9 @@
const graph = await canvasApi.ensureForSession(s.id);
goto(resolve(`/canvas/${graph.canvas.id}?session=${s.id}`));
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.sessionCreateFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.sessionCreateFailed'),
);
}
}
@@ -599,7 +658,9 @@
goto(resolve(`/canvas/${graph.canvas.id}?session=${s.id}`));
}
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.sessionCreateFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.sessionCreateFailed'),
);
}
}
@@ -611,7 +672,9 @@
await client.invalidateQueries({ queryKey: ['agent-sessions'] });
toast.success(t('canvas.sessionDeleted'));
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.sessionDeleteFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.sessionDeleteFailed'),
);
}
}
@@ -633,12 +696,15 @@
goto(resolve(`/canvas/${graph.canvas.id}?session=${sid}`));
toast.success(t('canvas.chatUnlinked'));
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.unlinkFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.unlinkFailed'),
);
}
}
const sendMutation = createMutation({
mutationFn: (payload: AgentComposerPayload) => agentApi.postMessage(activeId!, payload),
mutationFn: (payload: AgentComposerPayload) =>
agentApi.postMessage(activeId!, payload),
onMutate: () => {
if (activeId != null) {
const s = sessions.find((x) => x.id === activeId);
@@ -649,9 +715,10 @@
thinkingAgent = null;
liveTools = [];
livePlan = null;
client.setQueryData<AgentSession & { messages: AgentMessage[]; plan?: AgentPlan | null }>(
['agent-session', activeId],
(old) => (old ? { ...old, plan: null } : old),
client.setQueryData<
AgentSession & { messages: AgentMessage[]; plan?: AgentPlan | null }
>(['agent-session', activeId], (old) =>
old ? { ...old, plan: null } : old,
);
}
}
@@ -676,7 +743,9 @@
await client.invalidateQueries({ queryKey: ['agent-session', activeId] });
toast.info(t('canvas.runCancelled'));
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.cancelFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.cancelFailed'),
);
}
}
@@ -693,13 +762,19 @@
activeId = s.id;
$sendMutation.mutate(payload);
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.sessionCreateFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.sessionCreateFailed'),
);
}
}
/** Question-card click: the option text is the reply, stamped with the
* question seq so the backend records a structured approval. */
function handleQuestionAnswer(option: string, _scope: string, questionSeq: number) {
function handleQuestionAnswer(
option: string,
_scope: string,
questionSeq: number,
) {
if (running || activeId == null) return;
handleSend({
content: option,
@@ -800,7 +875,9 @@
...liveTools[real],
result: ev.data?.result,
phase:
(ev.data?.result as { ok?: boolean } | undefined)?.ok === false ? 'error' : 'done',
(ev.data?.result as { ok?: boolean } | undefined)?.ok === false
? 'error'
: 'done',
};
}
}
@@ -819,7 +896,9 @@
livePlan = livePlan
? {
...livePlan,
tasks: livePlan.tasks.map((t, i) => (i === index ? { ...t, status } : t)),
tasks: livePlan.tasks.map((t, i) =>
i === index ? { ...t, status } : t,
),
}
: livePlan;
}
@@ -851,7 +930,9 @@
// ---- artifacts from job events -------------------------------------------
async function materializeJobArtifact(data: Record<string, unknown> | undefined) {
async function materializeJobArtifact(
data: Record<string, unknown> | undefined,
) {
const jobId = Number(data?.job_id ?? NaN);
if (!Number.isFinite(jobId)) return;
// Scope: project canvases take their own project's jobs; sandbox
@@ -958,7 +1039,7 @@
// Stored in px; capped against the live window so a resized window can
// never restore an oversize panel (max 30% of window width).
let chatWidth = $state(300);
let chatWidth = $state(320);
let dragging = $state(false);
function clampChatWidth(px: number): number {
@@ -968,9 +1049,15 @@
$effect(() => {
const raw = Number(storageGet(CHAT_W_KEY));
if (Number.isFinite(raw) && raw > 0) chatWidth = clampChatWidth(raw);
chatWidth = clampChatWidth(
Number.isFinite(raw) && raw > 0
? raw
: window.innerWidth <= 1280
? 300
: 320,
);
// Keep the panel within the cap when the window shrinks.
const onResize = () => (chatWidth = clampChatWidth(chatWidth));
const onResize = () => (chatWidth = clampChatWidth(storageGet(CHAT_W_KEY) ? chatWidth : window.innerWidth <= 1280 ? 300 : 320));
window.addEventListener('resize', onResize);
return () => window.removeEventListener('resize', onResize);
});
@@ -1003,6 +1090,8 @@
let titleDraft = $state('');
let titleEditing = $state(false);
let savedFlash = $state(false);
let savedTimer: ReturnType<typeof setTimeout> | undefined;
onDestroy(() => clearTimeout(savedTimer));
$effect(() => {
if (!titleEditing) titleDraft = canvas?.title ?? '';
@@ -1016,20 +1105,25 @@
await canvasApi.patchCanvas(canvasId, { title: next });
await client.invalidateQueries({ queryKey: ['canvas', canvasId] });
savedFlash = true;
setTimeout(() => (savedFlash = false), 1400);
clearTimeout(savedTimer);
savedTimer = setTimeout(() => (savedFlash = false), 2400);
} catch (err) {
toast.error(err instanceof Error ? err.message : t('canvas.renameFailed'));
toast.error(
err instanceof Error ? err.message : t('canvas.renameFailed'),
);
}
}
const SUGGESTIONS: { label: string; prompt: string }[] = [
{
label: t('canvas.suggestFilm'),
prompt: 'Create a new film project and guide me through drafting the story.',
prompt:
'Create a new film project and guide me through drafting the story.',
},
{
label: t('canvas.suggestStory'),
prompt: 'Draft a storyline — beats, characters, environments, and misc. items.',
prompt:
'Draft a storyline — beats, characters, environments, and misc. items.',
},
];
</script>
@@ -1076,14 +1170,19 @@
title={t('canvas.rename')}
>
{canvas.title}
<span class="rename-icon"><Icon name="edit" size={14} /></span>
</button>
{/if}
{#if savedFlash}
<span class="saved">saved</span>
{/if}
<span class="title-separator"></span>
{#if canvas.project}
<a class="project-chip" href={resolve(`/workbench/${canvas.project.id}`)}>
<Icon name="folder" size={12} />
<a
class="project-chip"
href={resolve(`/workbench/${canvas.project.id}`)}
>
<Icon name="folder" size={14} />
{canvas.project.title}
</a>
<button
@@ -1100,12 +1199,12 @@
title: canvas.project.title,
})}
>
<Icon name="link-off" size={12} />
<Icon name="link-off" size={14} />
{t('canvas.unlinkButton')}
</button>
{:else}
<span class="sandbox-chip">
<Icon name="sparkle" size={12} />
<Icon name="sparkle" size={14} />
Sandbox
</span>
{/if}
@@ -1115,7 +1214,7 @@
bind:nodes
bind:viewport
{nodeTypes}
colorMode="light"
colorMode="system"
minZoom={0.05}
maxZoom={4}
{initialViewport}
@@ -1131,9 +1230,24 @@
onmoveend={(_event, vp) => scheduleViewportSave(vp)}
oninit={assertViewportOnInit}
>
<Background variant={BackgroundVariant.Dots} gap={26} size={1} />
<Controls />
<MiniMap />
<Background
variant={BackgroundVariant.Dots}
gap={26 / viewport.zoom}
size={2 / viewport.zoom}
patternColor="var(--board-dot)"
/>
<Controls
><span class="zoom-value">{Math.round(viewport.zoom * 100)}%</span
></Controls
>
<MiniMap
width={150}
height={88}
nodeColor={(node) => node.type === 'video' ? 'color-mix(in srgb, var(--sc-video) 60%, var(--tx-3))' : 'color-mix(in srgb, var(--sc-image) 55%, var(--tx-3))'}
maskColor="rgb(var(--ink) / 0.04)"
maskStrokeColor="var(--gold)"
maskStrokeWidth={1.5}
/>
<Panel position="bottom-center">
<button
type="button"
@@ -1183,8 +1297,15 @@
<div class="chat-title-block">
{#if activeSession}
<span class="chat-title">{activeSession.title}</span>
<span class="chat-subtitle"
>{activeSession.project_id
? (canvas?.project?.title ?? 'Sandbox')
: 'Sandbox'}</span
>
{:else}
<span class="chat-title muted">{t('canvas.noChatSelected')}</span>
<span class="chat-title muted"
>{t('canvas.noChatSelected')}</span
>
{/if}
</div>
<button
@@ -1213,7 +1334,7 @@
<AgentPlanPanel {plan} />
{/if}
{#key activeId}
<AgentComposer
<AgentComposer primaryAction
{running}
draft={composerDraft}
draftNonce={composerNonce}
@@ -1261,57 +1382,28 @@
flex: 1;
display: flex;
min-height: 0;
position: relative;
background: var(--bg-1);
--scene: var(--sc-image);
}
.flow-panel {
flex: 1;
min-width: 0;
position: relative;
background: var(--board-bg);
}
.load-error {
padding: 24px;
color: var(--text-secondary);
border: 1px solid var(--border);
border-radius: var(--radius-md);
margin: 24px;
color: var(--tx-2);
}
.tidy-btn {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border: 1px solid var(--border);
border-radius: var(--radius-md);
background: var(--bg-surface);
color: var(--text-secondary);
font-size: 12px;
font-weight: 600;
cursor: pointer;
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
}
.tidy-btn:hover:not(:disabled) {
color: var(--text-primary);
border-color: var(--accent);
}
.tidy-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.canvas-empty-hint {
display: flex;
flex-direction: column;
gap: 4px;
max-width: 340px;
padding: 10px 14px;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
font-size: 12px;
color: var(--text-secondary);
}
.canvas-empty-hint strong {
color: var(--text-primary);
font-size: 12.5px;
.titlecard,
.tidy-btn,
.canvas-empty-hint,
.chat-expand {
background: var(--glass);
backdrop-filter: blur(14px);
border: 1px solid var(--line-2);
box-shadow: var(--sh-1);
}
.titlecard {
position: absolute;
@@ -1320,139 +1412,224 @@
z-index: 5;
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-md);
box-shadow: 0 8px 30px rgba(0, 0, 0, 0.35);
gap: 8px;
height: 42px;
max-width: calc(100% - 28px);
padding: 0 8px 0 14px;
border-radius: var(--r-lg);
}
.title-btn {
border: none;
display: flex;
align-items: center;
gap: 7px;
min-width: 0;
border: 0;
background: transparent;
color: var(--text-primary);
color: var(--tx-1);
font-size: 14px;
font-weight: 600;
letter-spacing: 0.2px;
cursor: text;
padding: 2px 4px;
border-radius: var(--radius-sm);
max-width: 280px;
padding: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.title-btn:hover {
background: var(--bg-elevated);
.rename-icon {
color: var(--tx-3);
opacity: 0;
}
.title-btn:hover .rename-icon,
.title-btn:focus-visible .rename-icon {
opacity: 1;
}
.title-input {
border: 1px solid var(--accent);
background: var(--bg-elevated);
color: var(--text-primary);
min-width: 0;
width: 180px;
border: 1px solid var(--gold);
background: var(--well);
color: var(--tx-1);
font-size: 14px;
font-weight: 600;
padding: 2px 6px;
border-radius: var(--radius-sm);
max-width: 280px;
outline: none;
border-radius: var(--r-sm);
}
.title-separator {
flex-shrink: 0;
width: 1px;
height: 18px;
background: var(--line-2);
}
.saved {
font-size: 10.5px;
color: var(--text-muted);
letter-spacing: 0.05em;
font-size: 11px;
color: var(--ok);
}
.project-chip,
.sandbox-chip {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 11.5px;
color: var(--text-secondary);
text-decoration: none;
padding: 3px 8px;
border: 1px solid var(--border);
border-radius: 999px;
height: 28px;
padding: 0 10px;
border-radius: var(--r-pill);
border: 1px solid var(--line-2);
font-size: 12px;
color: var(--tx-2);
white-space: nowrap;
text-decoration: none;
max-width: 40%;
overflow: hidden;
text-overflow: ellipsis;
}
.project-chip {
background: color-mix(in srgb, var(--sc-project) 12%, transparent);
border-color: color-mix(in srgb, var(--sc-project) 38%, transparent);
color: color-mix(in srgb, var(--sc-project) 82%, var(--hi));
}
.project-chip:hover {
border-color: var(--accent);
color: var(--text-primary);
background: color-mix(in srgb, var(--sc-project) 18%, transparent);
}
.unlink-btn {
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 11.5px;
color: var(--text-secondary);
padding: 3px 9px;
border: 1px solid var(--border);
border-radius: 999px;
height: 28px;
padding: 0 9px;
border: 0;
background: transparent;
border-radius: var(--r-sm);
color: var(--tx-3);
font-size: 12px;
cursor: pointer;
white-space: nowrap;
transition:
border-color 0.15s,
color 0.15s;
}
.unlink-btn:hover:not(:disabled) {
border-color: var(--err-line);
color: var(--err);
background: color-mix(in srgb, var(--err) 8%, transparent);
}
.unlink-btn:disabled {
.unlink-btn:disabled,
.tidy-btn:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.tidy-btn {
display: inline-flex;
align-items: center;
gap: 7px;
height: 34px;
padding: 0 16px;
border-radius: var(--r-pill);
color: var(--tx-1);
font-size: 12.5px;
font-weight: 500;
cursor: pointer;
transition:
box-shadow var(--t-base),
border-color var(--t-base);
}
.tidy-btn:hover:not(:disabled) {
border-color: var(--line-3);
box-shadow: var(--sh-2);
}
.canvas-empty-hint {
display: flex;
flex-direction: column;
gap: 3px;
width: 380px;
max-width: 100%;
padding: 14px 18px;
border-radius: var(--r-lg);
text-align: center;
color: var(--tx-2);
font-size: 12px;
line-height: 1.6;
}
.canvas-empty-hint strong {
font-size: 14px;
font-weight: 600;
color: var(--tx-1);
}
/* Empty canvas title and instruction share the top edge: reserve a second row. */
.flow-panel :global(.svelte-flow__panel.top.center) {
margin-top: 70px;
max-width: calc(100% - 28px);
}
.zoom-value {
padding: 3px 0;
margin-top:2px;
border-top:1px solid var(--line);
font: 10px var(--mono);
color: var(--tx-3);
text-align: center;
}
.chat-panel {
flex-shrink: 0;
border-left: 1px solid var(--border);
background: var(--bg-surface);
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
border-left: 1px solid var(--line);
background: var(--bg-1);
--chat-padding: 14px 12px;
--chat-bubble-width:100%; --chat-bubble-font:13px; --chat-bubble-radius:12px;
--chat-bubble-padding:9px 12px; --chat-agent-border-width:1px; --chat-agent-border:var(--line);
--chat-tag-size:11px; --chat-tag-weight:400; --chat-tag-transform:none; --chat-tag-spacing:.4px;
--chat-identity-shadow:none; --chat-dot-size:7px;
--chat-user-bg:color-mix(in srgb,var(--gold) 10%,transparent);
--chat-user-border:color-mix(in srgb,var(--gold) 25%,transparent);
--id-1:var(--tx-1); --id-2:var(--tx-2); --id-3:var(--tx-3); --id-4:var(--tx-2); --id-5:var(--tx-3);
--composer-send-bg: var(--grad-gold);
--composer-box-bg: var(--well);
--composer-padding: 10px 12px 12px;
--composer-send-height: 32px;
}
.chat-splitter {
width: 7px;
flex-shrink: 0;
padding: 0;
border: none;
border: 0;
background: transparent;
cursor: col-resize;
margin-left: -3px;
margin-right: -3px;
margin: 0 -3px;
z-index: 6;
position: relative;
transition: background 0.12s;
}
.chat-splitter:hover,
.chat-splitter.dragging,
.chat-splitter:focus-visible {
background: color-mix(in srgb, var(--accent) 45%, transparent);
background: color-mix(in srgb, var(--gold) 45%, transparent);
outline: none;
}
.chat-splitter.dragging {
/* Svelte Flow's pane captures pointer events while dragging near the
graph edge — suppress text selection app-wide during the drag. */
cursor: col-resize;
}
.chat-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--space-sm);
padding: 10px 14px;
border-bottom: 1px solid var(--border);
gap: 8px;
height: 46px;
padding: 0 12px;
border-bottom: 1px solid var(--line);
flex-shrink: 0;
}
.chat-title-block {
min-width: 0;
display: flex;
align-items: baseline;
gap: 8px;
}
.chat-title {
font-size: 13px;
font-size: 13.5px;
font-weight: 600;
color: var(--text-primary);
color: var(--tx-1);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-subtitle {
font-size: 11px;
color: var(--tx-3);
white-space: nowrap;
}
.chat-title.muted {
color: var(--text-muted);
color: var(--tx-3);
font-weight: 400;
}
.chat-toggle,
@@ -1460,30 +1637,34 @@
display: inline-flex;
align-items: center;
justify-content: center;
border: 1px solid var(--border);
background: var(--bg-surface);
color: var(--text-secondary);
border-radius: var(--radius-sm);
flex-shrink: 0;
color: var(--tx-2);
border-radius: var(--r-md);
cursor: pointer;
}
.chat-toggle {
width: 26px;
height: 26px;
border: 0;
background: transparent;
}
.chat-toggle:hover,
.chat-expand:hover {
color: var(--text-primary);
border-color: var(--accent);
color: var(--tx-1);
}
.chat-expand {
position: absolute;
right: 12px;
top: 12px;
width: 34px;
height: 34px;
position: absolute;
right: 14px;
top: 14px;
z-index: 5;
}
/* ── ≤760px 可用级适配(F 批):解除 100vh 固定布局,画布与对话纵向堆叠。 ── */
@media (max-width: 1280px) {
.titlecard {
height: 38px;
}
}
@media (max-width: 760px) {
.shell {
height: auto;
@@ -1498,7 +1679,7 @@
}
.chat-panel {
width: 100% !important;
border-left: none;
border-left: 0;
border-top: 1px solid var(--line);
min-height: 50vh;
}
@@ -1506,34 +1687,4 @@
display: none;
}
}
.flow-panel {
background: #eae9e3;
border: 1px solid var(--line);
border-radius: 17px;
margin: 20px 0 20px 20px;
overflow: hidden;
}
.workspace {
background: var(--bg);
}
.titlecard {
background: var(--surface);
border-color: var(--line);
box-shadow: 0 4px 12px #292a2d0a;
}
.chat-panel {
margin: 20px;
border: 1px solid var(--line);
border-radius: 14px;
background: var(--surface);
}
:global(.svelte-flow) {
--xy-background-color-default: #eae9e3;
--xy-background-pattern-color-default: #c8c9bc;
--xy-edge-stroke-default: #a7b0e4;
}
.canvas-empty-hint {
color: var(--text-3);
}
</style>
+2 -20
View File
@@ -8,7 +8,7 @@
} from "@tanstack/svelte-query";
import ManagementPage from "$lib/components/manage/ManagementPage.svelte";
import LanguageSwitcher from "$lib/components/LanguageSwitcher.svelte";
import { reduceMotion, setReduceMotion } from "$lib/reduceMotion.svelte";
import MotionChoices from "$lib/components/shell/MotionChoices.svelte";
import ThemeChoices from "$lib/components/shell/ThemeChoices.svelte";
import MemoryPanel from "$lib/components/settings/MemoryPanel.svelte";
import Button from "$lib/components/ui/Button.svelte";
@@ -431,25 +431,7 @@
</section>
<section class="mg-field">
<h3>动效强度</h3>
<div class="mg-options">
<button
class="mg-option"
class:on={!reduceMotion.system && !reduceMotion.manual}
aria-pressed={!reduceMotion.system && !reduceMotion.manual}
disabled={reduceMotion.system}
onclick={() => setReduceMotion(false)}>完整</button
><button
class="mg-option"
disabled
title="当前动效偏好只提供完整和减少动效,克制档尚未实现"
>克制</button
><button
class="mg-option"
class:on={reduceMotion.system || reduceMotion.manual}
aria-pressed={reduceMotion.system || reduceMotion.manual}
onclick={() => setReduceMotion(true)}>关闭(减少动效)</button
>
</div>
<MotionChoices />
<p class="mg-dim">
系统开启“减少动态效果”时自动关闭;主题切换保留当前编辑内容。
</p>
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 600 B

+420 -1
View File
@@ -1,8 +1,58 @@
/* 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: 13px;
--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 */
--board-bg: #0a0c12;
--board-dot: rgb(var(--ink) / 0.11);
--bg-0: #07080c;
--bg-1: #0c0e14;
--bg-2: #12151d;
@@ -44,6 +94,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;
@@ -56,6 +130,28 @@
--desk-dock-focus:
var(--sh-2), 0 0 0 3px color-mix(in srgb, var(--gold) 8%, transparent),
0 0 40px color-mix(in srgb, var(--gold) 8%, transparent);
--theme-pop-button-height: 26px;
--theme-pop-button-padding: 9px;
--theme-pop-button-size: 12px;
--theme-pop-button-radius: 5px;
--theme-pop-width: 380px;
--theme-pop-left: calc(var(--rail) + 8px);
--theme-pop-bottom: 12px;
--theme-pop-shadow: var(--sh-2), 0 24px 60px rgba(0, 0, 0, 0.35);
--theme-pop-header-gap: 8px;
--theme-pop-header-padding: 12px 14px 8px;
--theme-pop-body-padding: 4px 10px 10px;
--theme-pop-footer-padding: 8px 10px 8px 14px;
--theme-pop-title-size: 13.5px;
--theme-pop-note-size: 11.5px;
--theme-pop-footer-gap: 6px;
--theme-choice-font: 400 13px/1.55 var(--font);
--theme-choice-gap: 12px;
--theme-choice-list-gap: 6px;
--theme-choice-radius: 10px;
--theme-choice-preview-radius: 8px;
--theme-choice-english-font: 500 10.5px var(--mono);
--theme-choice-description-line: 1.45;
--theme-reveal-duration: 520ms;
--theme-fallback-duration: 280ms;
--theme-preview-art: linear-gradient(160deg, #2f5d7c, #f2b36b);
@@ -91,6 +187,7 @@
--manage-card-min: 280px;
--manage-card-padding: 14px;
/* Shared sample rail and management typography, not per-theme offsets. */
--rail-background: var(--bg-1);
--rail-padding: 12px 0 10px;
--rail-brand-size: 40px;
--rail-brand-margin: 10px;
@@ -142,6 +239,35 @@
--task-tabs-offset: 12px;
--task-search-width: 240px;
--task-preview-height: 300px;
--viewfinder-length: 12px;
--viewfinder-stroke: 1.5px;
--viewfinder-inset: -1px;
--viewfinder-selected-inset: -3px;
--desk-player-offset: -50%;
--desk-media-bg: #000;
--desk-media-radius: 8px;
--desk-stage-padding: 12px 16px 8px;
--desk-layout-gap: 0px;
--desk-action-height: 40px;
--desk-history-padding: 8px;
--desk-history-gap: 8px;
--desk-history-label-bg: rgba(0, 0, 0, 0.6);
--desk-history-label-color: #ccc;
--desk-empty-ring: 84px;
--desk-empty-gap: 12px;
--desk-empty-title-size: 14px;
--desk-empty-hint-size: 12px;
--desk-stage-background:
radial-gradient(
60% 70% at 50% 45%,
color-mix(in srgb, var(--scene) var(--stage-tint), transparent),
transparent 70%
),
repeating-linear-gradient(0deg, var(--scanline) 0 1px, transparent 1px 3px);
--lattice-light-radius: 160px;
--lattice-mask-end: 75%;
--lattice-mask-radius: 140px;
--lattice-scene: 30%;
--desk-head-height: var(--head);
--desk-head-inset: 16px;
--desk-head-bg: var(--glass);
@@ -205,6 +331,35 @@
--t-base: 200ms;
--t-slow: 320ms;
--t-reveal: 700ms;
--scan-duration: 1.6s;
--lattice-duration: 320ms;
--running-stage-shadow: 0 0 0 3px
color-mix(in srgb, var(--sc-agent) 20%, transparent);
--page-enter-duration: 320ms;
--page-enter-y: 6px;
--effect-display: block;
--loop-play-state: running;
--result-calm-filter: blur(10px);
--result-calm-opacity: 0.4;
--primary-sweep-width: 40%;
--primary-sweep-from: -60%;
--primary-sweep-to: 130%;
--primary-sweep-skew: -20deg;
--primary-sweep: linear-gradient(
100deg,
transparent,
rgba(255, 255, 255, 0.55),
transparent
);
--result-develop: a-develop;
--scan-width: 45%;
--generation-width: min(60%, 520px);
--generation-max-height: 92%;
--generation-radius: 8px;
--generation-grain-opacity: 0.25;
--generation-info-padding: 12px 14px;
--generation-info-gap: 8px;
--generation-info-bg: linear-gradient(transparent, rgba(0, 0, 0, 0.75));
/* layout */
--rail: 68px;
--list: 272px;
@@ -277,8 +432,17 @@
}
[data-theme="day"] {
--result-develop: a-develop-day;
--result-calm-filter: blur(8px) sepia(0.25);
--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;
--board-bg: #e6e0d3;
--board-dot: rgb(var(--ink) / 0.16);
--bg-0: #e9e4da;
--bg-1: #f4f1ea;
--bg-2: #fbf9f5;
@@ -360,12 +524,26 @@
}
[data-theme="grade"] {
--desk-media-radius: 4px;
--result-develop: a-develop-grade;
--result-calm-filter: blur(5px) saturate(0.2);
--result-calm-opacity: 0.5;
--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;
--desk-filter-radius: 3px;
--desk-connection-radius: 3px;
color-scheme: dark;
--board-bg: #1e1e21;
--board-dot: rgb(var(--ink) / 0.12);
--bg-0: #1b1b1c;
--bg-1: #222223;
--bg-2: #29292b;
@@ -460,9 +638,18 @@
}
[data-theme="bluehour"] {
--desk-media-radius: 14px;
--rail-background: linear-gradient(180deg, #101a40, #1a1440);
--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;
--board-bg: #0c1330;
--board-dot: rgb(var(--ink) / 0.13);
--bg-0: #0a1029;
--bg-1: #0f1838;
--bg-2: #162148;
@@ -578,6 +765,11 @@
--hist: 84px;
}
}
@media (max-height: 800px) {
:root {
--desk-stage-padding: 8px 16px 8px;
}
}
@media (max-width: 1280px) {
:root {
--rail: 60px;
@@ -596,6 +788,23 @@
--composer-bg: var(--desk-dock-bg);
--composer-focus: var(--bg-2);
--float-bg: var(--bg-2);
--toast-right: 18px;
--toast-bottom: 18px;
--toast-min-width: 260px;
--toast-max-width: 380px;
--toast-padding: 10px 14px;
--toast-radius: 10px;
--toast-bg: color-mix(in srgb, var(--bg-3) 97%, transparent);
--toast-border: var(--line-2);
--toast-shadow: var(--sh-2);
--toast-font: 12.5px;
--toast-line-height: 1.55;
--toast-enter: 320ms;
--toast-ease: cubic-bezier(0.34, 1.56, 0.64, 1);
--toast-enter-y: 10px;
--toast-enter-scale: 0.96;
--toast-exit: 300ms;
--toast-dot-top: 6px;
--on-media: #fff;
--on-media-line: #ffffff66;
--sel-shadow: 0 0 0 1px var(--gold);
@@ -656,7 +865,10 @@
--ease-drawer: cubic-bezier(0.32, 0.72, 0, 1);
--d-press: 160ms;
--d-state: 160ms;
--d-pop: 180ms;
--d-pop: var(--t-base);
--pop-enter-y: 6px;
--parameter-pop-enter-y: 4px;
--pop-enter-scale: 0.98;
--d-leave: 200ms;
--d-enter: 220ms;
--d-drawer: 250ms;
@@ -750,3 +962,210 @@ html.theme-anim *::after {
animation: none;
}
}
/* Preserve the existing clearance for the fixed project 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"] {
--rail-background: linear-gradient(180deg, #101a40, #1a1440);
--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;
}
/* HEL-813 / approved v3: each behavior has its own value, no duration factor. */
:root.calm {
--page-enter-duration: 200ms;
--page-enter-y: 2px;
--d-pop: 150ms;
--d-drawer: 150ms;
--drawer-animation: drawer-calm;
--pop-enter-y: 2px;
--parameter-pop-enter-y: 2px;
--ease-drawer: var(--ease-out);
--pop-enter-scale: 0.995;
--t-reveal: 350ms;
--result-develop: a-develop-calm;
--effect-display: none;
--queue-loop: none;
--tile-loop: none;
--loop-delay: 0s;
--decorative-loop-name: none;
--loop-play-state: paused;
--thinking-opacity: 0.65;
--thinking-loop: none;
--stage-loop: none;
--toast-enter: 200ms;
--toast-enter-y: 4px;
--toast-enter-scale: 1;
--toast-ease: var(--ease-out);
--lattice-x: 50%;
--lattice-y: 50%;
--viewfinder-inset: var(--viewfinder-selected-inset);
--viewfinder-position-duration: 0ms;
}
:root[data-reduce="1"] {
--stage-loop: none;
--viewfinder-inset: var(--viewfinder-selected-inset);
}
/* Resolve the existing corner token against each canvas card's local scene.
* Other consumers retain the original inherited root value. */
:root,
.canvas-card.a-viewfinder {
--viewfinder-color: color-mix(in srgb, var(--scene) 90%, var(--hi));
}
[data-theme="day"],
[data-theme="day"] .canvas-card.a-viewfinder {
--viewfinder-color: color-mix(in srgb, var(--scene) 85%, black);
}
+216
View File
@@ -0,0 +1,216 @@
> 授权记录:HEL-801 确认线程 `01a167c6-b1dd-7a15-b304-c6d1dbd50dca`,2026-10-23 用户“1-8项按建议”。下文待确认字样保留原始材料,施工按该次批准解释:四主题350ms滤镜推荐方案、关闭档静态阶段微调、首版不自动降级;200ms纯淡入和硬件降级备选未选。
# 夜片场 · 动效三档规范 v3(原始美术师材料存档)
> 美术师出具,补 HEL-733 报告的规范缺口。v1 §6 与 v2 §4 继续有效;本文只定义「克制」档行为和三档优先规则。**凡本文新增、原样本与 v1/v2 中没有依据的规则,一律标【待确认】,经白栖知看样确认后才授权施工。**
## 0. 依据核对(哪些已有依据,哪些是本次新建议)
已有依据,可直接施工,不需再请批:
- 原 HTML 1137 行只有「完整 / 克制 / 关闭(减少动效)」三个选项和一句“系统开启减少动态效果时自动切到关闭”;1532 行 `motionBtn` 与 1605 行系统检测都只切换 `html.reduce`。**原样本没有克制档的任何行为定义。**
- v1 §6(样本「规范 → 06 动效」表)定义了完整档各效果的触发/时长/曲线/可打断,以及“减少动效时”的行为;v2 §4 沿用 v1 并补充主题切换 520/280ms。**v1/v2 同样没有克制档行为表。**
- 关闭档行为已有依据:`html.reduce` 全局 `animation-duration:1ms; animation-iteration-count:1; transition-duration:1ms`,`.fx-only`(队列环、扫描光、极光、粒子、光球、思考点)`display:none`,主题切换立即替换,显影淡入 1ms,蜂窝仅背景变亮,取景框保留角标无位移。
本次新建议(全部【待确认】):克制档每一项行为、三档优先与偏好恢复规则、动态切换规则、低性能降级策略。下列表格中「克制」列即新建议,施工员不得自行乘系数或类推。
## 1. 三档定义与优先级
| 档 | 类名 | 含义 |
|---|---|---|
| 完整 | (默认,无类) | 现有全部动效,v1 §6 + v2 §4 已批准 |
| 克制 | `html.calm` | 【待确认】保留状态反馈与方向感:一次性过渡缩短减幅,装饰性循环改静态标识,真实数值反馈(进度条)不动 |
| 关闭 | `html.reduce` | 既有行为:去掉光束、粒子与位移,只保留颜色和状态变化 |
优先级(【待确认】规则 1–5):
1. **系统优先**:`prefers-reduced-motion: reduce` 生效时强制关闭档,覆盖用户任何选择;界面上三档开关显示「关闭」并标注“跟随系统”。
2. **偏好记忆与恢复**:用户选择存 `localStorage['aigc-motion']`(`full`/`calm`/`off`,非法值回退 `full`)。系统减少动效只覆盖表现、**不改写已存偏好**;用户关闭系统设置后,恢复其先前选择的档位。
3. **动态切换即时停止**:运行中切到克制/关闭,所有循环立即停止(粒子取消 rAF 并清空画布、CSS 循环类移除),进行中的入场/显影/弹层动画跳到终态;切回完整时,循环从下一个触发事件起恢复,不向进行中的画面中途注入循环。
4. **后台与卸载**:标签页隐藏(`visibilitychange`)时粒子 rAF 停止(既有行为,扩展到一切未来 rAF 循环);CSS 循环依赖浏览器自动节流,不另做计时器。`pagehide`/卸载不做除既有偏好持久化外的任何操作。
5. **低性能降级**:首版不做自动降级——三档 + 系统档已覆盖,自动跳档会造成状态不一致。若总工评估后认为需要,备选方案是仅在首次访问、用户从未选择过时,按 `hardwareConcurrency ≤ 4` 或 `deviceMemory ≤ 4` 默认建议克制档并一次性提示,绝不覆盖已有选择。**此备选技术可行性待总工确认后再定。**
## 2. 克制档循环保留总决策【待确认】
| 循环 | 克制档处置 | 理由 |
|---|---|---|
| 扫描光束(生成中) | 停止扫动,保留生成底色 + 进度条 | 进度条是真实数值反馈;光束是装饰 |
| 队列环(侧栏队列点) | 停止旋转,保留静态弧形描边 | 静态弧仍有“进行中”含义 |
| 智能体极光 | 暂停漂移,保留静态氛围色块 | 极光是页面气质底色,静态不丢氛围 |
| 46 粒子(canvas) | 停止 rAF 并清空 | 静态粒子无意义且 canvas 常驻成本高 |
| 光球呼吸 + 双环旋转 | 停止呼吸与旋转,保留静态光球与环 | 光球本体是视觉锚点 |
| 思考点(三点闪烁) | 停止闪烁,保留静态三点 + 文字 | 文字本身已传达状态 |
| 运行阶段呼吸(项目步骤) | 停止呼吸,保留静态高亮描边与底色 | 当前步骤必须可辨识 |
| 视频播放 pan | 不变 | 只在用户手动播放时运行,非装饰循环 |
## 3. 逐类行为表
「完整」列是已批准的既有行为(原样本实测值);「克制」列全部为【待确认】新建议;「关闭」列为既有 `html.reduce` 行为。
### 3.1 扫描光束(生成中)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 任务进入 running | 同左 | 同左 |
| 循环与停止 | 1.6s `ease-io` 无限循环;任务停止/取消即卸载 | 不循环:光束层不渲染,仅生成底色 `--gen-bg` + 颗粒保留 | 光束隐藏(`.fx-only`) |
| 动画属性及幅度 | `left: -45% → 100%`,宽 45% | 无位移动画 | 无 |
| 时长曲线 | 1.6s · `--ease-io` | — | — |
| 可否打断 | 取消即停 | 无循环可打断 | — |
| 终态 | 任务结束卸载生成层 | 同左 | 同左 |
| 配套保留 | — | 进度条 `width .25s linear` 照常(真实数值,三档均不动) | 同左 |
### 3.2 队列环(侧栏队列点)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 队列有进行中任务 | 同左 | 同左 |
| 循环与停止 | `spin` 1.6s linear 无限 | 不旋转,静态显示 1.5px 弧形描边(border-top-color 场景色) | 隐藏(`.fx-only`),仅保留计数数字 |
| 动画属性及幅度 | `rotate 0→360deg` | 无 | 无 |
| 可否打断 | 队列清空即移除 | 同左 | 同左 |
| 终态 | 无进行中任务时移除 | 同左 | 同左 |
### 3.3 智能体极光
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 进入智能体首页/任务页 | 同左 | 进入页面 |
| 循环与停止 | `drift` 18s `ease-io` 无限交替;离开页面即停 | 暂停漂移(`animation-play-state:paused` 于初始帧),保留三色静态色块与 `blur(70px)`、浓度 `--aur-op` 不变 | 隐藏(`.fx-only`) |
| 动画属性及幅度 | `translate(60px,40px) scale(1.12)` | 无位移 | 无 |
| 可否打断 | 离开页面即停 | 同左 | — |
| 终态 | 离页卸载 | 同左 | 同左 |
### 3.4 粒子(46 粒 canvas)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 进入智能体页 `startParticles()` | 不启动 | 不启动 |
| 循环与停止 | rAF 循环;离页/隐藏标签页/减少动效时停止并清空 | 不启动 rAF,canvas 保持空 | 不启动(既有判断) |
| 动画属性及幅度 | 上升 `.15–.5 px/f`、正弦横漂 `.2`、半径 `.4–2`、透明度 `.15–.65` | 无 | 无 |
| 可否打断 | 离页即停 | — | — |
| 终态 | 清空画布 | 始终为空 | 同左 |
### 3.5 光球呼吸与双环
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 进入智能体首页 hero | 同左 | 隐藏 |
| 循环与停止 | 核心 `breath` 4.5s `ease-io` 无限;环 `spin` 24s、外环 40s 反向虚线 | 全部暂停:核心保留 `--orb-core` 渐变与基础光晕(`0 0 80px`),双环静态 | 整体隐藏(`.fx-only`) |
| 动画属性及幅度 | `scale 1→1.05`,光晕 80→120px | 无 | 无 |
| 可否打断 | 离页即停 | — | — |
### 3.6 思考点
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 智能体任务进行中 | 同左 | 隐藏 |
| 循环与停止 | `blink` 1.2s 无限,三点依次延迟 0/.2/.4s | 静态三点(透明度 .65 固定),说明文字照常 | 隐藏(`.fx-only`),文字保留 |
| 动画属性及幅度 | `opacity→.2`、`translateY(-2px)` | 无 | 无 |
### 3.7 运行阶段呼吸(项目步骤 `.pstep.run`)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 项目阶段进入 running | 同左 | 同左 |
| 循环与停止 | `breath` 2s 无限(光晕脉冲) | 不脉冲;保留场景色描边 + 静态 `0 0 0 3px 20%` 光晕 + 场景色图标 | 全局 1ms 规则使脉冲仅一闪;建议克制同款静态样式应用于关闭档以保持可辨识【待确认,属对关闭档的微调建议】 |
| 可否打断 | 阶段结束即换样式 | 同左 | 同左 |
### 3.8 页面进入
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 切换一级页 | 同左 | 同左 |
| 动画属性及幅度 | `opacity 0→1` + `translateY(6px)→0` | `opacity 0→1` + `translateY(2px)→0`(幅度减到 2px,不乘时长系数之外的属性) | 直接出现(1ms) |
| 时长曲线 | 320ms · `--ease-out` | 200ms · `--ease-out` | 1ms |
| 可否打断 | 是(再次切换接管) | 是 | — |
| 终态 | 移除动画、稳定布局 | 同左 | 同左 |
### 3.9 弹层(参数弹层 / 主题弹层 / 灯箱 / 底部 sheet)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 打开弹层 | 同左 | 同左 |
| 动画属性及幅度 | `opacity` + `translateY(6px)` + `scale(.98)` | `opacity` + `translateY(2px)` + `scale(.995)` | 直接出现 |
| 时长曲线 | 200ms · `--ease-out` | 150ms · `--ease-out` | 1ms |
| 可否打断 | Esc / 点外部立即关 | 同左 | 同左 |
| 终态 | 稳定显示,焦点圈定不变 | 同左 | 同左 |
### 3.10 主题切换「开灯」
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 选择新主题 | 同左 | 同左 |
| 形式 | View Transitions 圆形展开;不支持时 280ms 颜色淡入淡出 | 不用圆形展开:统一走 280ms 颜色淡入淡出(`html.theme-anim`,340ms 后移除类) | 立即替换 |
| 时长曲线 | 520ms · `--ease-out`(回退 280ms · `ease-io`) | 280ms · `--ease-io` | 0ms |
| 可否打断 | 是,再次选择接管 | 是 | — |
| 终态 | `data-theme` 已换、内容不动 | 同左 | 同左 |
### 3.11 显影(结果到达)——四主题分别规定,不乘统一系数
触发均为:仅当前同一任务从 pending/running 到 done;历史与主题切换不重播;点击任意处跳过;完成后移除类。三档通用。
| 主题 | 完整(既有,700ms · `--ease-out`) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 夜片场 night | `develop`:blur(18px) brightness(1.8) saturate(0) opacity .2 scale(1.015) → 60% blur(2px) → 清晰 | 保留模糊显影个性但去掉过曝与缩放:blur(10px) opacity .4 → 清晰,350ms · `--ease-out` | 淡入 1ms |
| 蓝调时刻 bluehour | 同 night | 同 night 的克制规则(两主题完整档本就共用 `develop`) | 淡入 1ms |
| 日光棚 day | `developDay`:blur(16px) brightness(1.35) sepia(.6) saturate(.2) → 清晰(相纸显影) | 保留棕褐相纸感、减幅度:blur(8px) sepia(.25) opacity .4 → 清晰,350ms | 淡入 1ms |
| 调色间 grade | `developGrade`:blur(10px) saturate(0) opacity .25 → 清晰 | 保留去饱和个性:blur(5px) saturate(.2) opacity .5 → 清晰,350ms | 淡入 1ms |
备选方案(供用户二选一,默认推荐上行方案):克制档四主题统一改为 200ms 纯淡入,不做滤镜。推荐保留各主题滤镜个性的方案,否则克制档下四主题显影无差别,违背“同一个片场换一种灯光”的主题原则。
### 3.12 主按钮扫光
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 悬停主操作 | 悬停主操作 | — |
| 动画属性及幅度 | 40% 宽高光 `left -60%→130%`、`skewX(-20deg)` | 无扫光;保留既有背景/阴影 hover 变化(`--t-fast/--t-base` 颜色过渡不动) | 无扫光(1ms 等同无) |
| 时长曲线 | 700ms · `--ease-out`,一次 | — | — |
| 可否打断 | 是(移出即复位) | — | — |
| 说明 | disabled/aria-disabled 不扫光,三档通用 | 同左 | 同左 |
### 3.13 蜂窝 / 光栅悬停(`.lg`)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 指针进入列表/卡片 | 同左 | 同左 |
| 行为 | 160px 径向场景色光 + 140px mask 蜂窝纹,跟随指针 `--mx/--my` | 不跟随指针:进入时蜂窝光斑静止于卡片中心渐显,离开渐隐 | 仅背景变亮,无蜂窝纹 |
| 时长曲线 | 320ms 渐显 · `--ease-out` | 320ms 渐显渐隐 · `--ease-out`(不变) | 1ms |
| 可否打断 | 是 | 是 | — |
### 3.14 取景框(`.vf` 角标)
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 选中工作流/作品 | 同左 | 同左 |
| 动画属性及幅度 | 角标透明度 0→1 + inset −1→−3(外扩 2px) | 角标透明度 0→1,无 inset 位移,直接出现在 −3 | 保留角标,无位移(既有表已定) |
| 时长曲线 | 透明度 200ms;位置 320ms · `--ease-out` | 透明度 200ms 不变 | 1ms |
| 可否打断 | 是 | 是 | — |
### 3.15 提示 Toast
| 项 | 完整(既有) | 克制【待确认】 | 关闭(既有) |
|---|---|---|---|
| 触发 | 操作完成 | 同左 | 同左 |
| 动画属性及幅度 | `opacity` + `translateY(10px)` + `scale(.96)`,`--ease-spring` | `opacity` + `translateY(4px)`,去弹性用 `--ease-out` | 淡入(1ms) |
| 时长曲线 | 320ms · spring;3.2s 后消失 | 200ms · `--ease-out`;3.2s 消失不变 | 1ms |
| 可否打断 | 是 | 是 | — |
### 3.16 微交互(三档均保留,非装饰)
悬停/聚焦的颜色、背景、边框过渡(`--t-fast 120ms` / `--t-base 200ms`)、开关弹簧位移、卡片 hover 位移、进度条 width 过渡、选中态颜色变化:**三档全部保留**,属于可用性反馈而非动效装饰;关闭档下由全局 1ms 规则即时完成,不删除属性本身。
## 4. 施工提示(确认后执行)
1. 克制档实现为 `html.calm` 一个类:CSS 侧用 `html.calm` 覆盖各动画属性(停用 animation 或替换关键帧引用),JS 侧三处接入点——`startParticles` 增加 calm 判断、主题切换 `setTheme` 在 calm 时走 `theme-anim` 回退路径、显影按主题选择 `develop*Calm` 关键帧。
2. 全部视觉值继续引用语义 token;克制档不新增颜色变量,只新增(【待确认】命名):`--t-calm:150–350ms` 各值写入上表、`--ease-out` 复用。
3. 存储键 `aigc-motion` 复用既有安全存储封装(存储不可用时当次有效 + 提示,与主题一致);旧版只有 reduce 布尔时的迁移:`reduce=true → off`,无记录 → `full`。【待确认】
4. 三档开关 UI:主题弹层底部「动效开」按钮改为三态分段(完整/克制/关闭),系统减少动效时显示“关闭 · 跟随系统”且禁用切换。【待确认】
5. 不得借通用“减少动效”建议改回已定完整/关闭档行为;emil-skills 等通用参考与已批准样本冲突时,以样本为准。
## 5. 待确认清单(汇总,请白栖知逐条过目)
1. §1 优先级规则 1–5(系统优先、偏好恢复、动态切换、后台卸载、低性能不自动降级 + 备选)。
2. §2 八类循环的克制处置(静态化 or 停止)。
3. §3 各一次性效果的克制幅度/时长(逐项数值,非系数)。
4. §3.11 四主题克制显影:推荐方案(保留个性滤镜 350ms)vs 备选(统一 200ms 淡入)。
5. §3.7 附带建议:关闭档的运行阶段样式与克制档静态样式对齐(属对既有关闭档的唯一微调建议)。
6. §4 存储键命名、迁移规则与三态开关 UI 形态。
@@ -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,47 @@
# HEL-733 · 全站既定动效修复与首轮差异核查
本卡尚未达到整站验收门槛。原样本的“克制”档缺少行为规则,需总管补充规范;不能用禁用该档宣布完成。当前交付是可审核的阶段代码、隔离复测和缺口清单,不合并、不部署,不请求用户整体验收。
基底为已集成B4的 `leefer/hel-731-studio-project@2952af42b6232483640f1f27803980367cd62dd0`,已核实远端与原PR #11合并状态。原HTML SHA256 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`。HEL-801批准的6项差异和hero小窗口例外保留。
## 实现
- `static/themes.css` 为新增/修正的视觉值统一来源;共享效果写在原 `app.css`,既有组件消费token,未引入样式覆盖层或项目依赖。
- `AppShell` / `StudioDesk`:创作台使用自身页头,删除重复的48/44px全局顶栏;保留Ctrl+K、主题与真实队列入口。蓝调rail恢复原渐变;空态恢复样本84px环、标题与提示,舞台使用原场景光晕与扫描底纹,不放演示作品。
- 统一页面320ms进入、蜂窝320ms径向跟随、取景框角标、扫描光1.6s、主按钮700ms扫光。既有减少动效规则归并为单一来源,系统或手动减少动效下关闭位移/循环/装饰。
- `Artboard`:仅当前任务从pending/running到done时进行700ms主题显影;重复done快照不提前清除效果,历史/切主题不重播,点击可结束。生成层绑定真实running/pending状态;不修改任务来源、数值或业务逻辑。修复播放键按压时全局transform覆盖居中导致点击落空的问题,改用独立translate保持中心;视频默认暂停且只由用户操作播放。
- `HistoryRail`:图片/视频按自身比例显示,编号覆盖在媒体上,复用统一取景框,移除强制方形缩略图;缺失/未完成保持明确占位。
- 主题弹层复用`Modal`焦点、关闭和层级机制,原组件参数化定位与尺寸,恢复rail旁8px/底部12px/380px宽、四行预览与原文案。`ThemeChoices`仍复用设置页同一主题注册表,设置tiles形态保留。共用弹层修正为200ms、上移6px+缩放.98。
- 智能体粒子在减少动效、任务页或隐藏标签页停止rAF,退出清理;B4成果底栏的存量11.5px容器字号改为样本13px,真实选择控件保留。
- 画布入口、画布会话预填、搭景与原会话管理在浏览器local/sessionStorage禁止时使用既有安全封装或容错,避免页面抛错;缓存不可用不改变真实数据与会话归属。
## 进度条约4.6px核对
测量对象是第一行running任务的外框`.task-progress`和填充`i`,不是只看填充百分比。1440/1366/1280下原样本与实际x差分别为-4.9375/-4.640625/-4.296875,外框均156×4。
原样本第二行来源为“智能体 · 分镜助手”,隔离真实任务按契约显示“项目 · 雾港来信”,auto表格列宽随文本重新分配。只在参考DOM对应来源文字、不动CSS后,四主题三窗口外框与填充x/y/宽/高差均0。保留真实来源,未添加CSS偏移,不以base同样存在豁免。原HEL-772附件只有base-results,没有head-results;本轮提供当前基底重新实测、输入和DOM,不声称读到了缺失文件。
## 复现与验证边界
先`npm --prefix calliope-web ci`,执行lint/check/test/build。浏览器验证需要运行环境已有的Playwright和Chromium;不加入项目依赖。`e2e/hel733-audit.mjs`读取冻结build、原HTML与明确隔离输入,阻止外部请求和产品写操作;样本从任务附件下载到仓库父目录`materials`。完整输入与产物在本卡证据附件中。
`e2e/run-hel733.py`使用真实隔离后端、假ComfyUI、假智能体模型和冻结build的preview服务。测试与构建顺序执行,避免开发服务器被check/build生成文件热重载而污染交互记录。退出核对daemon PID,关闭所有自建进程并删除隔离数据库;保留截图、结果与录屏。可用`HEL733_TESTS`指定脚本列表。
初审96组覆盖8页×四主题×三窗口;真实隔离数据截图另覆盖12类页面。大部分原样本是演示内容,应用截图是真实隔离API状态/空态,不能把这些自动称为全站同状态像素通过。B4的24组已有内容映射由`hel732-visual.cjs`另行核对。具体数表、命令、结果、录屏和未覆盖项见本卡附件。
## 未完成门槛
1. “克制”需要各类循环、位移/滤镜、时长/曲线、打断及系统优先规则;原HTML1137行只有选项,1532/1605行脚本只支持reduce,v1/v2也未补规则,不自行创作第三套动效。
2. 全站各真实/空态与交互态的完整同状态映射、逐页目检、所有关键数值表尚未全部收齐,初审图不能代替差异清零。
3. HEL-767既有末槽“导航”与原样本“规范”用途不同,需总管核定,不把几何一致视为新增授权。画布/搭景原样本仅组织说明,缺精确画面处不自创。
4. 未验证真实GPU/收费模型质量、线上真实用户数据和独立部署;由总管后续安排总工审核与部署。
回退本轮代码可revert本卡提交,保留2952af4与全部B4修复;零后端/数据库结构改动,无部署/迁移需回退。
## 本轮最终自测结果
- 全仓`npm run lint`、`npm run check`(0 errors / 0 warnings)、`npm test`、`npm run build`通过;保留现有构建chunk/第三方未使用导入提示,无新增检查例外。
- 冻结构建+真实隔离API:新增浏览器187项通过、0 pageerror;涵盖四主题显影/扫描、真实鼠标播放、首尾帧上传与编辑器实例保留、会话草稿、粒子停止、local/sessionStorage禁止。
- B4功能31项通过;同状态24组,156对关键DOM值0差异,另4项交互通过。原验证脚本中开发时动态导入源模块改为点击实际主题入口,现可审核冻结产物。
- 96组逐页初审图、144张真实隔离页面图、12组主题弹层;弹层外框四主题三窗口x/y/宽/高差均0。全动效下12组蜂窝背景/遮罩/透明度/时序/层级均与原件一致。
- 以上不替代未完成门槛;没有把真实数据差异、缺样本或克制禁用归类为整站通过。
@@ -0,0 +1,17 @@
HEL-806 continues draft PR #12 on `agent/agent/8ec6e532b3ac`, from `1f6c2d2a6b8da29ef29a874709d90da138123216`; target remains `leefer/hel-731-studio-project@2952af42b6232483640f1f27803980367cd62dd0`. All B4 and HEL-733 changes are retained. No merge or deployment.
The approved HTML remains read-only, SHA256 `0473d80d22b90194375f3566c1b8ca30dbd7433581b18f60956eabca252242a4`. The architectural boundaries follow HEL-727 and the existing B1–B4 components. No dependency, backend, schema, API, cloud generation integration or production configuration is changed.
- `themes.css`, `ToastHost.svelte`, `toast.ts`: use the sample's 18px placement, surface, border, 10px radius, 12.5px text, dot, 320ms spring entry and 3200ms display followed by 300ms fade. Repeated pause no longer consumes remaining time twice. Existing undo/manual dismissal/sticky feedback and the project's fixed-action clearance remain. Those real controls and clearance are recorded as specific sample conflicts, not silently removed or presented as approved.
- `StudioDesk.svelte`, `Artboard.svelte`: replace the extra 12px gap with the original stage padding (12px 16px 8px, top 8px when height <=800), keep the 40px action row for empty as well as populated states, and clip media to its theme radius (8px night/day, 4px grade, 14px bluehour). Values have one source in tokens; no overlay stylesheet or duplicate component.
- `e2e/hel806.cjs`: real disposable HTTP data, fake ComfyUI/model only, four themes × three viewports. Original reference, runtime content map and actual screenshots are distinct. Reference changes use existing templates/content/state; no reference CSS/layout changes. Missing empty states, non-storyboard stage content, real edit/compare/validation dialogs and organization-only pages are explicitly marked. The sample's static parameter list is not substituted for actual workflow declarations.
- `e2e/hel806-toast.mjs`, `hel806-toast-browser.cjs`: deterministic expiry/pause/sticky/cleanup regression plus full/reduced motion, project footer clearance and real explicit confirmation.
- `scripts/report-hel806.py`: measured values, self-contained themed galleries and parallel images. Screenshot delivery uses lossless WebP; decoded RGB equality is checked against source PNGs. Manifests retain both hashes. Identical bitmap bytes are deduplicated inside self-contained upload parts; media-files.json preserves the logical-name mapping, and every state stays with its three viewport sizes. Screenshot counts and DOM measurements are evidence, never automatic visual approval.
Reproduce from a frozen build: install the repository's existing dependencies, run frontend lint/check/test/build, then set existing `PLAYWRIGHT_MODULE_PATH`, browser library path and `HEL732_PYTHON` for this machine. `HEL733_TESTS=e2e/hel732.cjs,e2e/hel729.cjs,e2e/hel742.cjs,e2e/hel733-live.cjs,e2e/hel732-visual.cjs,e2e/hel806.cjs,e2e/hel806-toast-browser.cjs HEL733_SKIP_SHOTS=1 python3 e2e/run-hel733.py`. The original HTML is downloaded through the CLI to `../materials` and the B4 reference copy to `../evidence/reference`. All required results are collected before exit; the runner closes its exact child processes and removes the disposable database. Run `node e2e/hel806-toast.mjs` separately. The report script reads `../evidence/hel806-final/results.json`.
The attached coverage report owns the per-page findings and exact run results. The six approved business differences, small-window hero exception, text-to-image without image slots, honest unknown connection metrics and manual video playback remain. Restrained motion, final navigation slot purpose and canvas/scene visual samples still await the design decision already routed by the coordinator. No claim that HEL-733 or the whole site is complete; final independent review and deployment belong to the responsible reviewer.
Rollback only these commits, keeping `1f6c2d2` and B4. No database rollback is needed.
Validation completed: full frontend lint/check (0 errors / 0 warnings), guard scripts and production build pass. Relevant backend regressions: 24 pass, one existing Starlette deprecation warning. B1 browser checks: 42; no-image guards: 7; B4 functional: 31; shared motion/storage checks: 43, all pass with no page errors. B4 same-state 24 groups / 156 measured selector pairs have no differences, plus four interactions. The audit delivers 34 states × 12 viewports/themes = 408 groups and 12 dedicated Toast style/clearance checks. Image frame geometry/radius and empty-ring geometry each match the reference in their 12 measured groups; these local findings do not imply whole-page approval.

Some files were not shown because too many files have changed in this diff Show More