diff --git a/calliope-backend/contracts.json b/calliope-backend/contracts.json index d845e119..945b8511 100644 --- a/calliope-backend/contracts.json +++ b/calliope-backend/contracts.json @@ -156,7 +156,8 @@ "job.started", "shot.capture.saved", "shot.updated", - "story.ready" + "story.ready", + "workbench.stage.updated" ], "prompt_profiles": [ "minimax_h3_ref", diff --git a/calliope-backend/src/calliope/agent/deliverables.py b/calliope-backend/src/calliope/agent/deliverables.py new file mode 100644 index 00000000..6be088d1 --- /dev/null +++ b/calliope-backend/src/calliope/agent/deliverables.py @@ -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() diff --git a/calliope-backend/src/calliope/agent/harness/runner.py b/calliope-backend/src/calliope/agent/harness/runner.py index e4e86580..feded966 100644 --- a/calliope-backend/src/calliope/agent/harness/runner.py +++ b/calliope-backend/src/calliope/agent/harness/runner.py @@ -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 diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 29e38e0a..24e8955f 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -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'") diff --git a/calliope-backend/src/calliope/main.py b/calliope-backend/src/calliope/main.py index 7303f656..c3ad1351 100644 --- a/calliope-backend/src/calliope/main.py +++ b/calliope-backend/src/calliope/main.py @@ -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"]) diff --git a/calliope-backend/src/calliope/routers/results.py b/calliope-backend/src/calliope/routers/results.py new file mode 100644 index 00000000..d9c8b9b6 --- /dev/null +++ b/calliope-backend/src/calliope/routers/results.py @@ -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 diff --git a/calliope-backend/src/calliope/routers/workbench.py b/calliope-backend/src/calliope/routers/workbench.py index 5c0b19b2..5996faa2 100644 --- a/calliope-backend/src/calliope/routers/workbench.py +++ b/calliope-backend/src/calliope/routers/workbench.py @@ -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 [] diff --git a/calliope-backend/tests/test_results.py b/calliope-backend/tests/test_results.py new file mode 100644 index 00000000..cc476210 --- /dev/null +++ b/calliope-backend/tests/test_results.py @@ -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() diff --git a/calliope-web/scripts/check-skill-frontmatter.mjs b/calliope-web/scripts/check-skill-frontmatter.mjs index 597d6f77..72278a0a 100644 --- a/calliope-web/scripts/check-skill-frontmatter.mjs +++ b/calliope-web/scripts/check-skill-frontmatter.mjs @@ -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( diff --git a/calliope-web/src/lib/api.ts b/calliope-web/src/lib/api.ts index 96f8257c..e1d957d6 100644 --- a/calliope-web/src/lib/api.ts +++ b/calliope-web/src/lib/api.ts @@ -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( + `/api/results/deliverables${sessionId == null ? "" : `?session_id=${sessionId}`}`, + ), + patch: ( + id: number, + payload: { + revision: number; + content: string; + project_id: number | null; + stage_key: WorkbenchStageKey; + }, + ) => + api(`/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; diff --git a/calliope-web/src/lib/components/agent/AgentChat.svelte b/calliope-web/src/lib/components/agent/AgentChat.svelte index 58a2ccc8..120e2c7f 100644 --- a/calliope-web/src/lib/components/agent/AgentChat.svelte +++ b/calliope-web/src/lib/components/agent/AgentChat.svelte @@ -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 | null; result?: unknown; phase: 'running' | 'done' | 'error' }[]; @@ -31,6 +32,7 @@ } let { + studio = false, messages, liveTools, streaming, @@ -46,6 +48,21 @@ let listEl = $state(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 @@
+ {#if studio} + {#if loading}

{t('agentChat.loading')}

{/if} + {#each studioGroups as group (group[0].id)} +
+
{#if group[0].role==='user'}我{:else}{/if}
+
+ {#each group as m (m.id)} + {#if m.role==='tool'} + + {#each artifactJobs(m) as job(job.id)}{/each} + {:else} + {#if m.reasoning}{/if} +
{#if m.status==='steering'}{t('agentChat.steering')}{/if}{#each m.attachments??[] as a (a.path)}{a.name}{/each}{#each bubbleParts(m.content,(m.mentions??[]) as WorkflowMention[]) as part,i (`${i}-${part.type}`)}{#if part.type==='chip'}{part.text}{:else}{part.text}{/if}{/each}
+ {/if} + {/each} +
+
+ {/each} + {#if lastQuestion && !running}

{lastQuestion.question}

{#each lastQuestion.options as opt(opt)}{/each}
{/if} + {#if running && (liveTools.length || streamingReasoning || streaming)} +
+ {#each liveTools as tool,i(i)}{/each} + {#if streamingReasoning}{/if} + {#if streaming}
{streaming}
{/if} +
+ {/if} + {#if !loading&&!messages.length&&!running}

{t('agentChat.emptyHint')}

{/if} + {:else} + {#if loading}

{t('agentChat.loading')}

@@ -329,9 +375,20 @@
{/if} + {/if} diff --git a/calliope-web/src/lib/components/agent/workspace.css b/calliope-web/src/lib/components/agent/workspace.css new file mode 100644 index 00000000..f6dcbd10 --- /dev/null +++ b/calliope-web/src/lib/components/agent/workspace.css @@ -0,0 +1,1002 @@ +/* Approved HTML source, agent home/task sections 06/07/15. + Geometry and effects are copied from the sample; only selectors are namespaced. + Theme-specific values belong to static/themes.css. */ +:where(.b4, .b4-header) :where(h1, h2, h3, p) { + margin: 0; + padding: 0; +} +:where(.b4, .b4-header) :where(button, input, textarea, select) { + font: inherit; + color: inherit; +} +:where(.b4, .b4-header) button { + background: none; + border: 0; + padding: 0; + cursor: pointer; + letter-spacing: inherit; +} +.b4-header { + position: relative; + z-index: 3; + box-sizing: border-box; + display: flex; + align-items: center; + gap: 12px; + height: var(--head); + padding: 0 16px; + border-bottom: 1px solid var(--line); + background: var(--agent-header-bg); + backdrop-filter: blur(10px); + flex: none; + color: var(--tx-1); + font-size: var(--agent-header-font); + letter-spacing: var(--agent-header-spacing); +} +.b4-header .b4-subtitle { + font-size: 12px; + color: var(--tx-3); +} +.b4-crumb { + display: flex; + align-items: center; + gap: 6px; + color: var(--tx-3); + font-size: var(--agent-crumb-font); +} +.b4-crumb b { + font-size: var(--agent-crumb-title-font); + font-weight: var(--agent-crumb-title-weight); + color: var(--tx-1); +} +.b4-grow { + flex: 1; + min-width: 0; +} +.b4-chip { + height: 26px; + padding: 0 10px; + border-radius: var(--agent-chip-radius); + display: inline-flex; + align-items: center; + gap: 5px; + font-size: 12px; + color: var(--tx-2); + background: var(--bg-2); + border: 1px solid var(--line); + white-space: nowrap; +} +.b4 { + flex-direction: var(--agent-page-direction); + position: relative; + display: flex; + flex: 1; + min-height: 0; + height: 100%; + overflow: hidden; + --scene: var(--sc-agent); + line-height: 1.55; + color: var(--tx-1); +} +.b4, +.b4 * { + box-sizing: border-box; +} +.b4 .b4-row { + display: flex; + align-items: center; + gap: 8px; +} +.b4 .dim, +.b4 .muted { + color: var(--tx-2); +} +.b4 .b4-seg { + display: flex; + padding: 3px; + border-radius: var(--agent-radius-9); + background: var(--agent-seg-bg); + border: 1px solid var(--line); + gap: 2px; + overflow: auto; +} +.b4 .b4-seg button { + flex: 1; + height: 28px; + border-radius: var(--agent-radius-7); + color: var(--tx-2); + font-size: 12.5px; + white-space: nowrap; +} +.b4 .b4-seg button.on { + background: var(--agent-seg-selected-bg); + color: var(--tx-1); + box-shadow: var(--agent-seg-shadow); +} +.b4 .eyebrow { + display: inline-flex; + align-items: center; + gap: 6px; + height: 22px; + padding: 0 9px; + border-radius: var(--agent-chip-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); +} + +.b4 .sec-h { + display: flex; + align-items: center; + gap: 10px; + margin: 4px 0 10px; +} +.b4 .big-input .b4-row { + flex-wrap: wrap; +} +.b4 .sec-h h2 { + font-size: 15px; + font-weight: 600; +} +.b4 .sec-h .dim { + font-size: 12px; +} +.b4 .b4-empty { + font-size: 12px; + color: var(--tx-3); + padding: 12px; + line-height: 1.7; +} +.b4 .hero-copy { + position: relative; + min-width: 0; +} +.b4 .hero-copy h2 { + margin-top: 10px; +} +.b4 .hero-copy > p { + margin-top: 8px; + max-width: 560px; + font-size: 13px; + line-height: 1.55; +} +.b4 .steps { + margin-top: 12px; +} +.b4 .titem { + width: 100%; + text-align: left; +} +.b4 .titem b { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.b4 .dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--agent-task-dot, var(--scene)); +} +.b4 .panel h3 .dim { + font-size: 11.5px; + font-weight: 400; +} +.b4 .panel > p { + font-size: 11.5px; +} +.b4 .outcard { + text-align: left; + cursor: pointer; +} +.b4 .outcard .t { + display: grid; + place-items: center; + color: var(--scene); + background: var(--well); +} +.b4 .art-meta { + font-size: var(--agent-art-meta-font); +} +.b4 .art-tabs { + flex: none; +} +.b4 .shot .th :is(img, video) { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: contain; +} +.b4 .shot-copy { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} +.b4 .shot-copy textarea { + width: 100%; + min-height: 0; + field-sizing: content; + margin: -1px -3px; + resize: none; + border: 0; + background: none; + font-size: 12px; + line-height: 1.55; + padding: 1px 3px; +} +.b4 .shot-copy input { + width: var(--agent-duration-width); + field-sizing: content; + min-width: 1ch; + font-size: 11px; + font-family: var(--agent-duration-font); + border: 0; + padding: 0; + background: var(--agent-duration-bg); + appearance: textfield; +} +.b4 .shot-copy .a-tag { + gap: var(--agent-duration-gap); +} +.b4 .shot-copy input::-webkit-inner-spin-button, +.b4 .shot-copy input::-webkit-outer-spin-button { + appearance: none; + margin: 0; +} +.b4 .shot .th { + display: grid; + place-items: center; + background: var(--well); + font-size: 10px; + color: var(--tx-3); +} +.b4-compare { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; +} +.b4-compare pre { + white-space: pre-wrap; + word-break: break-word; + font-size: 12px; + max-height: 60vh; + overflow: auto; +} +.b4 .draft-editor { + flex: 1; + min-height: 180px; + width: 100%; + resize: vertical; + padding: 10px; + border: 1px solid var(--line); + border-radius: var(--agent-radius-8); + background: var(--well); + font-size: 12px; + line-height: 1.8; + color: var(--tx-1); +} +.b4 .art-f .a-btn { + flex: 1; + justify-content: center; +} +.b4 .art-f .primary { + flex: 1.4; +} +.b4 :is(.big-input, .art-f) select { + field-sizing: content; + max-width: var(--agent-input-select-max); + width: auto; + font-size: 12px; + font-weight: var(--agent-select-weight, 600); + border: 0; + background: none; + appearance: none; + padding: 0; +} +.b4 select { + background: var(--bg-2); + border: 1px solid var(--line); + border-radius: var(--agent-chip-radius); + height: 26px; + padding: 0 8px; + color: var(--tx-1); + font-size: 11.5px; + min-width: 0; + max-width: 130px; +} +.b4 .b4-error { + position: absolute; + z-index: 5; + bottom: 120px; + left: 280px; + right: 20px; + padding: 12px; + background: var(--bg-3); + border: 1px solid var(--err); + border-radius: var(--r-sm); + font-size: 12px; +} + +.b4.task-view .aurora { + opacity: var(--agent-task-aurora-opacity); +} +.b4 { + .aurora { + position: absolute; + inset: 0; + pointer-events: none; + overflow: hidden; + z-index: 0; + } + .aurora i { + position: absolute; + border-radius: 50%; + filter: blur(70px); + opacity: var(--aur-op); + animation: drift 18s var(--ease-io) infinite alternate; + } + .aurora i:nth-child(1) { + width: 520px; + height: 420px; + left: 8%; + top: -120px; + background: var(--aur-1); + } + .aurora i:nth-child(2) { + width: 420px; + height: 380px; + right: 4%; + top: 40px; + background: var(--aur-2); + animation-delay: -6s; + opacity: calc(var(--aur-op) * 0.55); + } + .aurora i:nth-child(3) { + width: 460px; + height: 360px; + left: 38%; + top: 260px; + background: var(--aur-3); + animation-delay: -12s; + opacity: calc(var(--aur-op) * 0.36); + } + + .particles { + position: absolute; + inset: 0; + pointer-events: none; + z-index: 0; + } + .agent-grid { + position: relative; + z-index: 1; + display: grid; + grid-template-columns: 260px minmax(0, 1fr); + min-height: 0; + flex: 1; + } + .tasklist { + border-right: 1px solid var(--line); + background: color-mix(in srgb, var(--bg-1) 72%, transparent); + backdrop-filter: blur(8px); + display: flex; + flex-direction: column; + min-height: 0; + } + .tl-h { + padding: 12px; + display: flex; + flex-direction: column; + gap: 8px; + border-bottom: 1px solid var(--line); + } + .tl-b { + flex: 1; + overflow: auto; + padding: 6px 8px; + } + .titem { + padding: 9px 10px; + border-radius: var(--agent-radius-10); + cursor: pointer; + display: flex; + flex-direction: column; + gap: 4px; + border: 1px solid transparent; + margin: 2px 0; + } + .titem:hover { + background: rgb(var(--ink) / 0.03); + } + .titem.on { + background: color-mix(in srgb, var(--sc-agent) 10%, transparent); + border-color: color-mix(in srgb, var(--sc-agent) 30%, transparent); + } + .titem b { + font-size: 12.5px; + font-weight: 500; + } + .titem .meta { + display: flex; + align-items: center; + gap: 6px; + font-size: 11px; + color: var(--tx-3); + } + .agent-home { + overflow: auto; + padding: 22px 26px 30px; + display: flex; + flex-direction: column; + gap: 18px; + } + .ahero { + flex-shrink: var(--agent-hero-shrink); + min-width: 0; + position: relative; + border-radius: var(--agent-radius-22); + overflow: hidden; + border: 1px solid var(--agent-hero-border); + background: var(--agent-hero); + padding: 26px 28px; + display: grid; + grid-template-columns: minmax(0, 1fr) 330px; + gap: 24px; + } + .ahero::before { + content: ""; + position: absolute; + inset: 0; + background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='32' height='32'%3E%3Cpath d='M32 0H0v32' fill='none' stroke='white' stroke-opacity='.04'/%3E%3C/svg%3E"); + -webkit-mask: linear-gradient(90deg, #000, transparent 80%); + mask: linear-gradient(90deg, #000, transparent 80%); + } + .ahero h2 { + font-size: 30px; + font-weight: 700; + line-height: 1.2; + background: var(--agent-title); + -webkit-background-clip: text; + background-clip: text; + color: transparent; + } + .big-input { + margin-top: 14px; + border-radius: var(--agent-radius-16); + background: var(--agent-input-bg); + border: 1px solid var(--agent-input-border); + padding: 12px 14px 10px; + transition: + border-color var(--t-slow), + box-shadow var(--t-slow); + } + .big-input:focus-within { + border-color: var(--agent-input-focus-border); + box-shadow: + 0 0 0 3px color-mix(in srgb, var(--gold) 10%, transparent), + 0 0 40px color-mix(in srgb, var(--sc-agent) 20%, transparent); + } + .big-input textarea { + width: 100%; + height: 58px; + background: none; + border: 0; + outline: 0; + resize: none; + font-size: 14px; + line-height: 1.6; + } + .big-input .row { + flex-wrap: wrap; + } + .steps { + display: flex; + gap: 8px; + flex-wrap: wrap; + } + .steps span { + display: inline-flex; + align-items: center; + gap: 6px; + height: 26px; + padding: 0 10px 0 4px; + border-radius: var(--r-pill); + background: rgb(var(--ink) / 0.05); + border: 1px solid var(--line-2); + font-size: 11.5px; + color: var(--tx-2); + } + .steps span i { + width: 18px; + height: 18px; + border-radius: 50%; + display: grid; + place-items: center; + font: 700 10px var(--mono); + font-style: normal; + background: var(--scene); + color: var(--on-scene); + } + .orb { + position: relative; + display: grid; + place-items: center; + } + .orb .core { + width: 180px; + height: 180px; + border-radius: 50%; + background: var(--orb-core); + box-shadow: var(--agent-orb-shadow); + animation: breath 4.5s var(--ease-io) infinite; + } + .orb .ring { + position: absolute; + width: 250px; + height: 250px; + border-radius: 50%; + border: 1px solid rgb(var(--ink) / 0.12); + animation: spin 24s linear infinite; + } + .orb .ring::before { + content: ""; + position: absolute; + top: -4px; + left: 50%; + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--gold); + box-shadow: var(--agent-ring-shadow); + } + .orb .ring.r2 { + width: 300px; + height: 300px; + animation-duration: 40s; + animation-direction: reverse; + border-style: dashed; + border-color: rgb(var(--ink) / 0.07); + } + + .roster { + display: grid; + grid-template-columns: repeat(5, 1fr); + gap: 12px; + } + .acard { + --c: var(--sc-agent); + position: relative; + border-radius: var(--agent-radius-16); + overflow: hidden; + border: 1px solid var(--line-2); + background: var(--bg-2); + cursor: pointer; + min-height: 176px; + display: flex; + flex-direction: column; + justify-content: flex-end; + transition: + transform var(--t-slow) var(--ease-out), + border-color var(--t-base), + box-shadow var(--t-slow); + } + .acard:hover { + transform: translateY(-4px); + border-color: color-mix(in srgb, var(--c) 60%, transparent); + box-shadow: 0 18px 40px color-mix(in srgb, var(--c) 22%, transparent); + } + .acard .bg { + position: absolute; + inset: 0; + background-size: cover; + background-position: center; + opacity: 0.55; + transition: + transform 0.8s var(--ease-out), + opacity var(--t-slow); + } + .acard:hover .bg { + transform: scale(1.06); + opacity: 0.75; + } + .acard .sh { + position: absolute; + inset: 0; + background: linear-gradient( + 180deg, + transparent 15%, + color-mix(in srgb, var(--bg-2) 95%, transparent) 75% + ); + } + .acard .num { + position: absolute; + right: 12px; + top: 6px; + font: 800 36px/1 var(--agent-number-font); + color: transparent; + -webkit-text-stroke: 1px rgb(var(--ink) / 0.22); + } + .acard .ic { + position: absolute; + left: 12px; + top: 12px; + width: 32px; + height: 32px; + border-radius: var(--agent-radius-9); + display: grid; + place-items: center; + background: color-mix(in srgb, var(--bg-1) 72%, transparent); + border: 1px solid color-mix(in srgb, var(--c) 50%, transparent); + color: var(--c); + } + .acard .tx { + text-align: left; + position: relative; + padding: 12px; + display: flex; + flex-direction: column; + gap: 4px; + } + .acard .tx b { + font-size: 14px; + } + .acard .tx p { + font-size: 11.5px; + color: var(--tx-2); + line-height: 1.5; + } + .acard .tx .b4-row { + margin-top: 4px; + } + .acard .tx .b4-row > .dim { + font-size: 11px; + } + .mini-row { + display: grid; + grid-template-columns: 1.2fr 1fr; + gap: 12px; + } + .panel { + border-radius: var(--agent-radius-16); + border: 1px solid var(--line-2); + background: color-mix(in srgb, var(--bg-2) 80%, transparent); + padding: 14px 16px; + display: flex; + flex-direction: column; + gap: 10px; + } + .panel h3 { + font-size: 13.5px; + font-weight: 600; + display: flex; + align-items: center; + gap: 8px; + } + .skills { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + .skill { + height: 28px; + padding: 0 10px; + border-radius: var(--agent-radius-8); + border: 1px solid var(--line-2); + background: rgb(var(--ink) / 0.03); + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--tx-2); + } + .skill i { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--sc-agent); + } + .outrow { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 8px; + } + .outcard { + border-radius: var(--agent-radius-10); + border: 1px solid var(--line); + background: var(--bg-2); + overflow: hidden; + } + .outcard .t { + height: 64px; + background-size: cover; + background-position: center; + } + .outcard .d { + padding: 7px 9px; + font-size: 11.5px; + display: flex; + flex-direction: column; + gap: 2px; + } + + /* agent task (session) */ + .atask { + min-width: 0; + position: relative; + z-index: 1; + display: grid; + grid-template-columns: 260px minmax(0, 1fr) 420px; + flex: 1; + min-height: 0; + } + .convo { + display: flex; + flex-direction: column; + min-height: 0; + min-width: 0; + border-right: 1px solid var(--line); + } + .convo-b { + flex: 1; + overflow: auto; + padding: 18px 22px; + display: flex; + flex-direction: column; + gap: 14px; + } + .msg { + display: flex; + gap: 10px; + max-width: 760px; + } + .msg.me { + align-self: flex-end; + flex-direction: row-reverse; + } + .msg .av { + 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); + } + .msg.me .av { + background: var(--bg-3); + color: var(--tx-2); + } + .bub { + padding: 10px 13px; + border-radius: var(--agent-radius-12); + background: var(--bg-2); + border: 1px solid var(--line); + font-size: 13px; + line-height: 1.65; + } + .msg.me .bub { + background: color-mix(in srgb, var(--gold) 10%, transparent); + border-color: color-mix(in srgb, var(--gold) 25%, transparent); + } + .plan { + border-radius: var(--agent-radius-12); + border: 1px solid color-mix(in srgb, var(--sc-agent) 30%, transparent); + background: linear-gradient( + 135deg, + color-mix(in srgb, var(--sc-agent) 8%, transparent), + color-mix(in srgb, var(--bg-2) 90%, transparent) + ); + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 8px; + } + .pstep { + display: grid; + grid-template-columns: 22px 1fr auto; + gap: 10px; + align-items: center; + font-size: 12.5px; + } + .pstep .s { + width: 22px; + height: 22px; + border-radius: 50%; + display: grid; + place-items: center; + border: 1px solid var(--line-3); + font: 600 10px var(--mono); + color: var(--tx-3); + } + .pstep.done .s { + background: var(--ok); + border-color: var(--ok); + color: var(--on-ok); + } + .pstep.run .s { + border-color: var(--sc-agent); + color: var(--sc-agent); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--sc-agent) 20%, transparent); + animation: breath 2s infinite; + } + .pstep.done b { + color: var(--tx-2); + font-weight: 400; + } + .tool { + border-radius: var(--agent-radius-10); + border: 1px solid var(--line); + background: var(--bg-1); + font-size: 12px; + } + .tool summary { + list-style: none; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + cursor: pointer; + color: var(--tx-2); + } + .tool summary::-webkit-details-marker { + display: none; + } + .tool summary code { + font-family: var(--mono); + color: var(--sc-image); + font-size: 11.5px; + } + .tool pre { + margin: 0 12px 10px; + padding: 8px 10px; + border-radius: var(--agent-radius-8); + background: var(--well); + font: 11px/1.6 var(--mono); + color: var(--tx-2); + white-space: pre-wrap; + } + .thinking { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: var(--tx-3); + } + .thinking i { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--sc-agent); + animation: blink 1.2s infinite; + } + .thinking i:nth-child(2) { + animation-delay: 0.2s; + } + .thinking i:nth-child(3) { + animation-delay: 0.4s; + } + + .convo-in { + flex: none; + margin: 0 18px 14px; + border-radius: var(--agent-radius-14); + background: var(--bg-2); + border: 1px solid var(--line-2); + padding: 10px 12px; + display: flex; + flex-direction: column; + gap: 8px; + } + .convo-in textarea { + background: none; + border: 0; + outline: 0; + resize: none; + height: 44px; + font-size: 13px; + } + .artifact { + display: flex; + flex-direction: column; + min-height: 0; + background: color-mix(in srgb, var(--bg-1) 80%, transparent); + } + .art-h { + padding: 12px 14px; + border-bottom: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 8px; + } + .art-b { + flex: 1; + overflow: auto; + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 10px; + } + .shot { + display: grid; + grid-template-columns: 86px 1fr; + gap: 10px; + padding: 8px; + border-radius: var(--agent-shot-radius); + border: 1px solid var(--line); + background: var(--bg-2); + } + .shot .th { + aspect-ratio: 16/9; + border-radius: var(--agent-radius-6); + background-size: cover; + background-position: center; + position: relative; + } + .shot .th span { + z-index: var(--agent-media-label-layer); + position: absolute; + left: 3px; + top: 3px; + font: 700 9.5px var(--mono); + background: rgba(0, 0, 0, 0.6); + padding: 1px 4px; + border-radius: 3px; + } + .shot [contenteditable] { + outline: 0; + border-radius: 4px; + padding: 1px 3px; + margin: -1px -3px; + font-size: 12px; + line-height: 1.55; + color: var(--tx-1); + } + .shot [contenteditable]:hover { + background: rgb(var(--ink) / 0.04); + } + .shot [contenteditable]:focus { + background: color-mix(in srgb, var(--gold) 8%, transparent); + box-shadow: 0 0 0 1px color-mix(in srgb, var(--gold) 35%, transparent); + } + .art-f { + font-size: var(--agent-footer-font); + border-top: 1px solid var(--line); + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 8px; + } +} + +:root[data-reduce="1"] .b4 .fx-only { + display: none; +} +@media (prefers-reduced-motion: reduce) { + .b4 .fx-only { + display: none; + } +} + +@keyframes drift { + to { + transform: translate(60px, 40px) scale(1.12); + } +} +@keyframes breath { + 50% { + transform: scale(1.05); + box-shadow: 0 0 120px color-mix(in srgb, var(--sc-agent) 75%, transparent); + } +} +@keyframes blink { + 50% { + opacity: 0.2; + transform: translateY(-2px); + } +} diff --git a/calliope-web/src/lib/components/desk/StudioDesk.svelte b/calliope-web/src/lib/components/desk/StudioDesk.svelte index 287b91b5..61e0436b 100644 --- a/calliope-web/src/lib/components/desk/StudioDesk.svelte +++ b/calliope-web/src/lib/components/desk/StudioDesk.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(null); + let storeJobId = $state(null); async function attachToProject(job: Job) { + if (!workbenchCtxOf(job)) { storeJobId = job.id; return; } if (attachBusyId != null) return; attachBusyId = job.id; try { @@ -1236,7 +1239,6 @@ inactive={false} canSendToSlot={!!imageSlotTarget || !!imageList} canAttach={!!selectedJob && - !!workbenchCtxOf(selectedJob) && selectedJob.status === 'done'} attachBusy={attachBusyId === selectedJob?.id} onAttach={() => selectedJob && attachToProject(selectedJob)} @@ -1854,3 +1856,5 @@ color: var(--text-3); } + +storeJobId=null} /> diff --git a/calliope-web/src/lib/components/generate/StoreResultModal.svelte b/calliope-web/src/lib/components/generate/StoreResultModal.svelte new file mode 100644 index 00000000..b8183452 --- /dev/null +++ b/calliope-web/src/lib/components/generate/StoreResultModal.svelte @@ -0,0 +1,65 @@ + + + +

选择项目和阶段,结果将在该阶段等待确认。

+ + + {#if error}

{error}

{/if} + {#snippet footer()}{/snippet} +
diff --git a/calliope-web/src/lib/components/generate/TakeCard.svelte b/calliope-web/src/lib/components/generate/TakeCard.svelte index e2bdd58d..633c183a 100644 --- a/calliope-web/src/lib/components/generate/TakeCard.svelte +++ b/calliope-web/src/lib/components/generate/TakeCard.svelte @@ -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); diff --git a/calliope-web/src/lib/components/ui/icons.ts b/calliope-web/src/lib/components/ui/icons.ts index bfe63f28..0f4c24f6 100644 --- a/calliope-web/src/lib/components/ui/icons.ts +++ b/calliope-web/src/lib/components/ui/icons.ts @@ -4,6 +4,9 @@ * Each entry is SVG inner content rendered by Icon.svelte via {@html}. */ export const icons = { + "agent-cpu": + '', + "agent-send": '', // Approved B3 sample geometry; retain existing tool icon contracts. "project-check": '', "project-grid": diff --git a/calliope-web/src/lib/components/workbench/IncomingResults.svelte b/calliope-web/src/lib/components/workbench/IncomingResults.svelte new file mode 100644 index 00000000..c77e69b0 --- /dev/null +++ b/calliope-web/src/lib/components/workbench/IncomingResults.svelte @@ -0,0 +1,23 @@ + + +{#each results as result (result.source_key)} +
+ {result.title} · 待整理成果 + {#if result.text}

{result.text}

{/if} + {#each result.paths ?? [] as path (path)}查看{result.kind === "video" ? "视频" : "图片"}产物{/each} + {#if result.session_id}回智能体编辑{/if} +
+{/each} diff --git a/calliope-web/src/lib/components/workbench/ProjectWorkbench.svelte b/calliope-web/src/lib/components/workbench/ProjectWorkbench.svelte index 7ee520dd..7e8973c9 100644 --- a/calliope-web/src/lib/components/workbench/ProjectWorkbench.svelte +++ b/calliope-web/src/lib/components/workbench/ProjectWorkbench.svelte @@ -1,5 +1,6 @@ -{#snippet skillRow(skill: SkillAdminEntry, detail: string)} -
-
- - - {typeLabel(skill.type)} - {detail} - -
-
- - - $toggleSkillMutation.mutate({ dir: skill.dir, next })} - /> -
-
-{/snippet} - -{#if legacyRedirect === 'pending'} -
{t('agents.opening')}
-{:else if legacyRedirect === 'failed'} - +{#if page.url.searchParams.has("legacy") || page.url.searchParams.has("task") || page.url.searchParams.has("project")} + {:else} - -
- -
- -
- -
- {#if messages.length}{/if} -
-
0 || running} - > - {#if $agentsQuery.isLoading}

- 正在载入智能体… -

{:else if $agentsQuery.isError}{:else if activeAgent} - {#if !messages.length && !running}
-
- ● AI {activeAgent.name} · 创作助手 -
-

{theme.title}

-

- {activeAgent.tagline} · 选择技能与工具,与智能体一起打磨创作。 -

-
- -
-
{/if} - {#if messages.length || running}
-
-
-
- AI {activeAgent.name} -

{$sessionQuery.data?.title ?? '这次创作'}

-
- {running ? '● 正在创作' : '等待你的下一步'}{#if sessionProject}回到项目 ↗{/if} -
- {#if $sessionQuery.data?.plan}{/if} -
- (draft = p)} - onAnswer={handleAnswer} - /> -
-
- -
{/if} -
- -
- {draft.length} / 20000 -
- {#if attachments.length}
- {#each attachments as a (a.path)}
- {#if a.kind === 'image'}{a.name}{/if}{a.name} -
{/each} -
{/if} -
- -
- Ctrl + Enter 发送 · Enter 换行{#if running}{:else}{/if} -
-
- -
- {/if} -
-
-
-
- {#snippet footer()}
- 选定画风会加入这次任务要求 -
{/snippet} -
- {#each agentStyles as style, i (style.name)}{/each} -
- {#snippet footer()}
- 由智能体按技能指导完成任务 -
{/snippet} - - {#each applicableSkills.filter((s) => (skillLabel(s.dir) + s.description) - .toLowerCase() - .includes(skillSearch.toLowerCase())) as skill (skill.dir)}{/each}{#if !applicableSkills.length}

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

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

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

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

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

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

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

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

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

- {#if resultError}{/if}
- - $clearMutation.mutate()} - oncancel={() => (clearOpen = false)} - /> - - - deleteSkillTarget && $deleteSkillMutation.mutate(deleteSkillTarget.dir)} - oncancel={() => (deleteSkillTarget = null)} - /> + {/if} - - diff --git a/calliope-web/src/routes/app.css b/calliope-web/src/routes/app.css index 64ec6213..d7c4055c 100644 --- a/calliope-web/src/routes/app.css +++ b/calliope-web/src/routes/app.css @@ -135,6 +135,11 @@ code, ); 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); diff --git a/calliope-web/static/themes.css b/calliope-web/static/themes.css index c5239c77..ca214f5b 100644 --- a/calliope-web/static/themes.css +++ b/calliope-web/static/themes.css @@ -1,6 +1,54 @@ /* HEL-726 approved themes. Loaded before the app for first-paint safety. */ :root, [data-theme="night"] { + --agent-shot-radius: 10px; + --agent-media-label-layer: 1; + --agent-bubble-radius: 12px; + --agent-tool-radius: 10px; + --agent-chip-radius: var(--r-pill); + --agent-orb-shadow: 0 0 80px + color-mix(in srgb, var(--sc-agent) 60%, transparent); + --agent-ring-shadow: 0 0 12px var(--gold); + --agent-hero-border: color-mix(in srgb, var(--sc-agent) 28%, transparent); + --agent-input-bg: color-mix(in srgb, var(--bg-0) 60%, transparent); + --agent-input-border: rgb(var(--ink) / 0.12); + --agent-input-focus-border: color-mix(in srgb, var(--gold) 60%, transparent); + --agent-seg-bg: var(--well); + --agent-seg-selected-bg: var(--bg-3); + --agent-seg-shadow: var(--sh-1); + /* Match the sample's local fallback glyphs even while webfonts are loaded. */ + --agent-number-font: "Cascadia Mono", Consolas, monospace; + --agent-hero-shrink: 0; + --agent-input-select-max: none; + --agent-task-running: var(--sc-agent); + --agent-task-returned: var(--ok); + --agent-task-confirm: var(--gold); + --agent-task-idle: var(--tx-3); + --agent-page-direction: column; + --agent-header-font: 13px; + --agent-header-spacing: 0px; + --agent-header-bg: var(--glass); + --agent-crumb-font: 12px; + --agent-crumb-title-font: 14px; + --agent-crumb-title-weight: 600; + --agent-message-flex: 1; + --agent-task-aurora-opacity: 0.6; + --agent-duration-width: auto; + --agent-duration-gap: 0px; + --agent-footer-font: 11.5px; + --agent-art-meta-font: 11px; + --agent-duration-bg: transparent; + --agent-duration-font: var(--mono); + --agent-radius-22: 22px; + --agent-radius-16: 16px; + --agent-radius-14: 14px; + --agent-radius-12: 12px; + --agent-radius-10: 10px; + --agent-radius-9: 9px; + --agent-radius-8: 8px; + --agent-radius-7: 7px; + --agent-radius-6: 6px; + color-scheme: dark; /* surfaces: ink black with a faint blue cast, never pure #000 */ --bg-0: #07080c; @@ -798,3 +846,157 @@ html.theme-anim *::after { :root:has(.project-workspace) { --toast-bottom: calc(var(--project-footer-height) + 24px); } + +/* B4 grade geometry from the approved multi-theme sample. */ +:root[data-theme="grade"] { + --agent-radius-22: 4px; + --agent-radius-16: 4px; + --agent-radius-14: 4px; + --agent-radius-12: 4px; + --agent-radius-10: 4px; + --agent-radius-9: 4px; + --agent-radius-8: 4px; + --agent-radius-7: 4px; + --agent-radius-6: 4px; +} + +:where(.b4, .b4-header) { + --button-height: 32px; + --button-padding: 12px; + --button-radius: var(--project-button-radius); + --button-font-size: 12.5px; + --button-weight: 500; + --button-sm-height: 26px; + --button-sm-padding: 9px; + --button-sm-font-size: 12px; + --button-sm-radius: var(--project-button-sm-radius); + --button-secondary-bg: var(--bg-3); + --button-secondary-border: var(--line-2); + --button-secondary-padding: 12px; + --button-secondary-radius: var(--project-button-radius); + --button-primary-height: 32px; + --button-primary-padding: 12px; + --button-primary-radius: var(--project-button-radius); + --button-primary-weight: 700; + --button-primary-border-width: 0px; + --button-primary-disabled-opacity: 1; + --button-primary-disabled-filter: var(--project-button-disabled-filter); + --button-primary-disabled-bg: var(--project-button-disabled-bg); + --button-primary-disabled-color: var(--project-button-disabled-color); +} + +.b4 { + --chat-padding: 0px; + --composer-top-padding: 0px; + --composer-top-border: 0px; + --composer-box-align: stretch; + --composer-box-direction: column; + --composer-box-bg: transparent; + --composer-box-border: 0px; + --composer-box-padding: 0px; + --composer-editor-height: 44px; + --composer-send-height: 26px; + --composer-send-bg: var(--grad-gold); + --composer-actions-gap: 8px; +} + +.b4 .composer { + --button-primary-height: var(--button-sm-height); + --button-primary-padding: var(--button-sm-padding); + --button-primary-radius: var(--button-sm-radius); +} + +[data-theme="day"] { + --agent-orb-shadow: 0 18px 50px rgba(109, 69, 208, 0.28); + --agent-ring-shadow: none; + --agent-hero-border: rgba(109, 69, 208, 0.22); + --agent-input-bg: rgba(255, 255, 255, 0.75); + --agent-input-border: rgba(38, 30, 18, 0.14); + --agent-input-focus-border: rgba(38, 30, 18, 0.14); + --agent-seg-bg: var(--bg-0); + --agent-seg-selected-bg: #fff; + --agent-seg-shadow: + 0 1px 2px rgba(60, 44, 20, 0.14), 0 0 0 1px rgba(38, 30, 18, 0.06); +} +[data-theme="grade"] { + --agent-header-spacing: 0.2px; + --agent-chip-radius: 3px; + --agent-orb-shadow: 0 0 40px rgba(165, 152, 216, 0.25); + --agent-ring-shadow: none; +} + +.b4 .shot { + --button-sm-height: 22px; +} + +[data-theme="grade"] { + --agent-shot-radius: 4px; + --agent-bubble-radius: 4px; + --agent-tool-radius: 4px; +} +[data-theme="bluehour"] { + --agent-header-bg: color-mix(in srgb, #0f1838 55%, transparent); + --agent-shot-radius: 14px; + --agent-bubble-radius: 14px; + --agent-tool-radius: 14px; +} +.b4 { + --tool-card-radius: var(--agent-tool-radius); + --tool-card-bg: var(--bg-1); + --tool-head-padding: 8px 12px; + --tool-name-font: 11.5px; + --tool-font: 12px; + --tool-head-font: 12px; + --tool-head-color: var(--tx-2); + --tool-border: var(--line); + --tool-name-flex: 0 0 auto; + --tool-name-color: var(--sc-image); + --tool-ok-color: var(--ok); + --tool-error-color: var(--err); +} + +:where(.b4, .b4-header) { + --tag-height: 18px; + --tag-padding: 6px; + --tag-border-width: 1px; + --tag-border: var(--line); + --tag-radius: 4px; + --tag-background: rgb(var(--ink) / 0.05); + --tag-color: var(--tx-2); + --tag-font-size: 11px; +} +.b4 .roster .acard { + --tag-color: var(--c); + --tag-border: color-mix(in srgb, var(--c) 35%, transparent); +} +:where(.b4, .b4-header) .a-tag.sc { + --tag-color: var(--agent-status-color, var(--sc-agent)); + --tag-background: var(--agent-status-background, rgb(var(--ink) / 0.05)); + --tag-border: color-mix(in srgb, var(--sc-agent) 40%, transparent); +} + +.b4 .studio-msg.me { + --agent-message-flex: initial; +} + +.b4-header { + --agent-status-color: color-mix(in srgb, var(--sc-agent) 80%, var(--hi)); + --agent-status-background: color-mix( + in srgb, + var(--sc-agent) 10%, + transparent + ); +} + +.b4 .tool-card.done { + --tag-border: color-mix(in srgb, var(--ok) 30%, transparent); + --tag-background: color-mix(in srgb, var(--ok) 7%, transparent); +} +.b4 .tool-card.error { + --tag-border: color-mix(in srgb, var(--err) 30%, transparent); + --tag-background: color-mix(in srgb, var(--err) 7%, transparent); +} + +.b4 .art-f .stage-select { + --agent-select-weight: 400; +} diff --git a/docs/changelogs/2026-10-22-hel732-agent-results.md b/docs/changelogs/2026-10-22-hel732-agent-results.md new file mode 100644 index 00000000..604466a0 --- /dev/null +++ b/docs/changelogs/2026-10-22-hel732-agent-results.md @@ -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,未将其宣称为本轮独立复审。原迁移回退限制仍有效。四主题/全页面最终目检和独立审核交总管安排;本批完成施工待审核,整套样本未宣称完成,无部署、合并、线上数据/配置/密钥或真实生成操作。 diff --git a/docs/changelogs/2026-10-22-hel787-agent-visual-fixes.md b/docs/changelogs/2026-10-22-hel787-agent-visual-fixes.md new file mode 100644 index 00000000..3de7da21 --- /dev/null +++ b/docs/changelogs/2026-10-22-hel787-agent-visual-fixes.md @@ -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 回收,交付前再次核验端口与子进程。 diff --git a/docs/changelogs/2026-10-22-hel791-agent-same-state.md b/docs/changelogs/2026-10-22-hel791-agent-same-state.md new file mode 100644 index 00000000..5da67d2b --- /dev/null +++ b/docs/changelogs/2026-10-22-hel791-agent-same-state.md @@ -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。最终整页是否达到样本门禁由总管接续目检与总工独立复审决定。 diff --git a/e2e/fake_agent_b4.py b/e2e/fake_agent_b4.py new file mode 100644 index 00000000..3b8d1412 --- /dev/null +++ b/e2e/fake_agent_b4.py @@ -0,0 +1,30 @@ +"""Loopback-only OpenAI-compatible model: actual tools execute inside the isolated app.""" +import json +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path + +OUT=Path('e2e/shots/hel732');OUT.mkdir(parents=True,exist_ok=True) +class Handler(BaseHTTPRequestHandler): + def log_message(self,*args): pass + def do_POST(self): + payload=json.loads(self.rfile.read(int(self.headers.get('Content-Length','0')))) + with (OUT/'model-requests.jsonl').open('a') as f: f.write(json.dumps(payload,ensure_ascii=False)+'\n') + msgs=payload.get('messages',[]) + last_user=max((i for i,m in enumerate(msgs) if m.get('role')=='user'),default=-1) + has_tool=any(m.get('role')=='tool' for m in msgs[last_user+1:]) + text='第一场,清晨的海岸,女孩将纸船放入海水,等待父亲归来。第二场,纸船带回一片树叶,她望向海平面,知道旅程才刚刚开始。' + if 'B4_STORYBOARD' in json.dumps(msgs,ensure_ascii=False): + text='以下是可编辑分镜成果:\n```json\n'+json.dumps({'shots':[{'id':f'b4-shot-{i}','description':f'隔离验证镜头 {i},女孩沿海岸走向灯塔。','duration_sec':4} for i in range(1,4)]},ensure_ascii=False)+'\n```' + if msgs and str(msgs[0].get('content','')).startswith('You are the planner'): + text=json.dumps({'mode':'single','tasks':[],'note':'隔离模型单任务'}) + delta={'content':text} + if payload.get('tools') and not has_tool: + delta={'tool_calls':[{'index':0,'id':'b4-workspace','type':'function','function':{'name':'get_workspace','arguments':'{"sections":["scenes"]}'}}]} + if payload.get('stream'): + self.send_response(200);self.send_header('Content-Type','text/event-stream');self.end_headers() + self.wfile.write(('data: '+json.dumps({'id':'b4-fake','choices':[{'index':0,'delta':delta,'finish_reason':None}]},ensure_ascii=False)+'\n\n').encode()) + self.wfile.write(b'data: [DONE]\n\n');self.wfile.flush() + else: + data=json.dumps({'choices':[{'index':0,'message':{'role':'assistant',**delta},'finish_reason':'stop'}]},ensure_ascii=False).encode() + self.send_response(200);self.send_header('Content-Type','application/json');self.end_headers();self.wfile.write(data) +ThreadingHTTPServer(('127.0.0.1',18189),Handler).serve_forever() diff --git a/e2e/hel732-conflict.cjs b/e2e/hel732-conflict.cjs new file mode 100644 index 00000000..0b95f776 --- /dev/null +++ b/e2e/hel732-conflict.cjs @@ -0,0 +1,12 @@ +// Review-only proposal: temporary browser style; never change product/sample code. +const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright'); +const fs=require('node:fs');const out='e2e/shots/hel732'; +(async()=>{const b=await chromium.launch({args:['--no-sandbox']});const rows=[]; +try {for(const [width,height] of [[1366,768],[1280,720]]){ + const p=await b.newPage({viewport:{width,height}});await p.goto('http://127.0.0.1:5173/agents');await p.locator('.roster .acard').first().waitFor(); + const measure=()=>p.evaluate(()=>{const hero=document.querySelector('.ahero').getBoundingClientRect(),button=document.querySelector('.big-input .primary').getBoundingClientRect();return {heroHeight:hero.height,heroBottom:hero.bottom,buttonTop:button.top,buttonBottom:button.bottom,clipped:button.bottom>hero.bottom,viewport:innerHeight}}); + const before=await measure();await p.screenshot({path:`${out}/conflict-${width}-actual.png`,animations:'disabled'}); + await p.locator('.ahero').evaluate(e=>e.style.flexShrink='0');const proposal=await measure();await p.screenshot({path:`${out}/proposal-${width}-browser-only.png`,animations:'disabled'}); + rows.push({width,height,before,proposal,temporaryRule:'.ahero {flex-shrink:0}',productCodeChanged:false});await p.close(); + }fs.writeFileSync(out+'/conflict.json',JSON.stringify(rows,null,2));console.log('RECORDED visual blocker and browser-only proposal',rows); +}finally{await b.close()}})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/e2e/hel732-layout.cjs b/e2e/hel732-layout.cjs new file mode 100644 index 00000000..226c824d --- /dev/null +++ b/e2e/hel732-layout.cjs @@ -0,0 +1,42 @@ +// Real controls, normal pointer input and isolated application/model chain at every viewport/theme. +const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright'); +const fs=require('node:fs'),assert=require('node:assert/strict'); +const out='e2e/shots/hel732',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247'; +(async()=>{ + const browser=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']}); + const rows=[],errors=[],checks=[]; + const board=JSON.parse(fs.readFileSync(out+'/fixture-state.json')).board; + const measure=async(page,selector)=>page.locator(selector).first().evaluate(e=>{const r=e.getBoundingClientRect();return {selector:e.getAttribute('aria-label')||e.className,x:r.x,y:r.y,width:r.width,height:r.height,right:r.right,bottom:r.bottom,visible:r.x>=0&&r.y>=0&&r.right<=innerWidth&&r.bottom<=innerHeight,hit:e.contains(document.elementFromPoint(r.x+r.width/2,r.y+r.height/2))}}); + try{ + for(const [width,height]of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){ + const context=await browser.newContext({viewport:{width,height}}),p=await context.newPage(); + p.on('pageerror',e=>errors.push(e.message)); + await p.goto(WEB+'/agents');await p.locator('.roster .acard').first().waitFor(); + await p.evaluate(theme=>{document.documentElement.dataset.theme=theme;localStorage.setItem('aigc-theme',theme)},theme); + const home={hero:await measure(p,'.ahero'),input:await measure(p,'[aria-label="任务想法"]'),start:await measure(p,'.big-input .primary')}; + assert(home.input.visible&&home.input.hit&&home.start.visible&&home.start.hit,JSON.stringify(home)); + assert(home.start.bottom<=home.hero.bottom); + assert(await p.locator('.agent-home').evaluate(e=>e.scrollWidth<=e.clientWidth)); + await p.getByLabel('任务想法').fill(`小窗口真实启动 ${theme} ${width},请调用工具读取工作区并写一段海岸故事。`); + await p.getByLabel('任务想法').click();assert(await p.getByLabel('任务想法').evaluate(e=>e===document.activeElement)); + await p.screenshot({path:`${out}/layout-input-${theme}-${width}.png`,animations:'disabled'}); + await p.locator('.mini-row').scrollIntoViewIfNeeded(); + await p.waitForFunction(()=>{const r=document.querySelector('.mini-row').getBoundingClientRect();return r.bottom<=innerHeight+1&&r.top>=0}); + await p.screenshot({path:`${out}/layout-scrolled-${theme}-${width}.png`,animations:'disabled'}); + await p.getByRole('button',{name:'开始任务',exact:true}).click(); + await p.waitForURL(/session=\d+/);const session=Number(new URL(p.url()).searchParams.get('session')); + await p.waitForFunction(async({API,session})=>(await(await fetch(API+'/api/results/deliverables?session_id='+session)).json()).length>0,{API,session}); + checks.push(`输入、焦点、自然滚动和正常点击启动真实会话 ${theme} ${width}`); + await p.goto(WEB+'/agents?session='+board);await p.locator('.shot-copy textarea').first().waitFor(); + const controls={};for(const selector of ['.art-f','[aria-label="成果项目"]','[aria-label="成果阶段"]','.art-f .secondary','.art-f .primary']){ + controls[selector]=await measure(p,selector);assert(controls[selector].visible&&controls[selector].hit,JSON.stringify(controls[selector])); + } + for(const label of ['成果项目','成果阶段']){await p.getByLabel(label).focus();assert(await p.getByLabel(label).evaluate(e=>e===document.activeElement));} + for(const selector of ['.art-f .secondary','.art-f .primary']){await p.locator(selector).focus();assert(await p.locator(selector).evaluate(e=>e===document.activeElement));} + assert(await p.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)); + await p.screenshot({path:`${out}/layout-footer-${theme}-${width}.png`,animations:'disabled'}); + rows.push({theme,width,height,home,controls});await context.close(); + } + assert.deepEqual(errors,[]);fs.writeFileSync(out+'/layout-checks.json',JSON.stringify({rows,checks,errors},null,2));console.log('PASS 12 theme/viewport input/start/scroll/real selector/focus/overflow checks'); + }finally{await browser.close()} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/e2e/hel732-migration.py b/e2e/hel732-migration.py new file mode 100644 index 00000000..21811b37 --- /dev/null +++ b/e2e/hel732-migration.py @@ -0,0 +1,97 @@ +"""Executable isolated backup / migration / old-code read / exact restore exercise. +No service, user database or production configuration is opened. +""" +from __future__ import annotations + +import asyncio +import hashlib +import json +import os +from pathlib import Path +import sqlite3 +import subprocess +import tarfile + +BASE='8d7e58645c9e63bb9b9e6a4ae8dfb031bf5960fb' +ROOT=Path(__file__).resolve().parents[1] +OUT=ROOT/'e2e/shots/hel732/migration' +OUT.mkdir(parents=True,exist_ok=True) +OLD=OUT/'old-code';OLD.mkdir(exist_ok=True) +archive=subprocess.run(['git','archive',BASE,'calliope-backend/src'],cwd=ROOT,check=True,stdout=subprocess.PIPE).stdout +(OUT/'old-code.tar').write_bytes(archive) +with tarfile.open(OUT/'old-code.tar') as tf:tf.extractall(OLD,filter='data') +DB=OUT/'isolated.db' +if DB.exists():DB.rename(OUT/f'previous-{__import__("time").time_ns()}.db') +checks=[] +def old_run(mode): + code='''import asyncio,json,sys +from pathlib import Path +from calliope import config +from calliope.db import migrate_db,get_db +config.settings.data_dir=Path(sys.argv[1]).parent +config.settings.db_name=Path(sys.argv[1]).name +config.settings.assets_dir=Path(sys.argv[1]).parent/'assets' +config.settings.dry_run=True +config.Settings.save_config_file=lambda self:None +if sys.argv[2]=='create': + asyncio.run(migrate_db(config.settings.db_path)) + c=get_db(config.settings.db_path) + p=c.execute("INSERT INTO projects(title,status) VALUES ('B3 isolated legacy','draft')").lastrowid + c.execute("INSERT INTO agent_sessions(project_id,title,status) VALUES (?,'Legacy session','idle')",(p,)) + c.execute("INSERT INTO agent_messages(session_id,role,content) VALUES (1,'user','Existing legacy message')") + c.execute("INSERT INTO jobs(project_id,kind,status,payload_json,output_paths_json) VALUES (1,'image','done',?,'[]')",(json.dumps({'legacy':True}),)) + content=json.dumps({'text':'Legacy confirmed story text, sufficiently long to preserve the old confirmation behavior.'}) + c.execute("INSERT INTO project_stages(project_id,stage_key,status,content_json,confirmed_content_json) VALUES (?,'script','confirmed',?,?)",(p,content,content)) + c.commit();c.close() +else: + from calliope.main import create_app + from fastapi.testclient import TestClient + with TestClient(create_app()) as client: + s=client.get('/api/agent/sessions/1');assert s.status_code==200,s.text + assert any(m['content']=='Existing legacy message' for m in s.json()['messages']) + jobs=client.get('/api/jobs?project_id=1');assert jobs.status_code==200,jobs.text + assert jobs.json()[0]['status']=='done' and jobs.json()[0]['payload']['legacy'] is True + w=client.get('/api/workbench/projects/1');assert w.status_code==200,w.text + stage=w.json()['stages'][0];assert stage['status']=='confirmed' + assert stage['content']==stage['confirmed_content'] + print(json.dumps({'session':s.json()['title'],'stage':stage['status'],'message_count':len(s.json()['messages'])})) +''' + env=os.environ.copy();env['PYTHONPATH']=str(OLD/'calliope-backend/src') + result=subprocess.run([__import__('sys').executable,'-c',code,str(DB),mode],cwd=OUT,env=env,text=True,capture_output=True,check=True) + (OUT/f'old-{mode}.log').write_text(result.stdout+result.stderr) + checks.append('old code '+mode+' succeeded') +old_run('create') +def backup(src,dst): + a=sqlite3.connect(src);b=sqlite3.connect(dst);a.backup(b);b.close();a.close() +backup(DB,OUT/'pre-b4-backup.db') +def dump(path): + c=sqlite3.connect(path);rows={name:c.execute(f'SELECT * FROM {name}').fetchall() for name in ['projects','agent_sessions','agent_messages','project_stages','jobs']};c.close();return rows +before=dump(DB) +from calliope.db import migrate_db,get_db +asyncio.run(migrate_db(DB));asyncio.run(migrate_db(DB)) +c=get_db(DB) +for table,rows in before.items(): + current=c.execute(f'SELECT * FROM {table}').fetchall() + # New columns are appended; every pre-existing field is equal. + assert [tuple(r)[:len(rows[0])] for r in current]==rows +assert c.execute('PRAGMA integrity_check').fetchone()[0]=='ok' +assert c.execute('PRAGMA foreign_key_check').fetchall()==[] +cols=[r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')] +assert cols.count('task_summary')==1 and cols.count('task_status')==1 +c.close();checks+=['migrate twice; no duplicate columns/tables','all original rows/fields preserved','integrity_check and foreign_key_check passed'] +old_run('read') +# New-only payload survives an old-code read and startup. +c=get_db(DB) +c.execute("INSERT INTO agent_deliverables(session_id,source_message_id,project_id,stage_key,title,content) VALUES (1,1,1,'script','B4 isolated','New isolated deliverable')") +c.commit();c.close() +backup(DB,OUT/'post-b4-export.db') +# Exact rollback to an offline copy of the old backup; never overwrite a live DB. +backup(OUT/'pre-b4-backup.db',OUT/'restored.db') +assert dump(OUT/'restored.db')==before +c=sqlite3.connect(OUT/'restored.db') +assert 'task_summary' not in [r[1] for r in c.execute('PRAGMA table_info(agent_sessions)')] +assert c.execute("SELECT COUNT(*) FROM sqlite_master WHERE name='agent_deliverables'").fetchone()[0]==0 +c.close();checks.append('exact pre-migration backup restored: old rows and old schema equal') +manifest={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in OUT.glob('*.db')} +(OUT/'report.json').write_text(json.dumps({'base':BASE,'checks':checks,'sha256':manifest},indent=2)) +print(json.dumps({'checks':checks,'sha256':manifest},indent=2)) diff --git a/e2e/hel732-visual.cjs b/e2e/hel732-visual.cjs new file mode 100644 index 00000000..4126c5ce --- /dev/null +++ b/e2e/hel732-visual.cjs @@ -0,0 +1,68 @@ +// Same-page/state comparison: normalize reference CONTENT only, retain its original CSS/layout. +const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright'); +const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict'); +const out='e2e/shots/hel732',WEB='http://127.0.0.1:5173',API='http://127.0.0.1:8247'; +const api=async p=>(await fetch(API+p)).json(); +const style=loc=>loc.evaluate(e=>{const s=getComputedStyle(e),r=e.getBoundingClientRect();return Object.fromEntries(['fontSize','fontWeight','letterSpacing','lineHeight','padding','gap','borderRadius','borderTopWidth','borderTopColor','backgroundColor','backgroundImage','color','boxShadow','filter','gridTemplateColumns'].map(k=>[k,s[k]]).concat([['x',r.x],['y',r.y],['width',r.width],['height',r.height]]))}); +(async()=>{ + const state=JSON.parse(fs.readFileSync(out+'/fixture-state.json')); + const registry=await api('/api/agent/agents'),skills=await api('/api/agent/skills?all=true'),results=await api('/api/results/deliverables'); + const session=await api('/api/agent/sessions/'+state.board),shots=JSON.parse(state.br.content).shots; + const sessions=(await Promise.all([api('/api/agent/sessions'),...registry.map(a=>api('/api/agent/sessions?agent_key='+a.key))])).flat().sort((a,b)=>b.updated_at.localeCompare(a.updated_at)); + const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']}); + const server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../evidence/reference/夜片场-多主题交互样本.html'))});await new Promise(r=>server.listen(0,'127.0.0.1',r)); + const rows=[],originalRows=[],operations=[]; + try{ + for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){ + const c=await b.newContext({viewport:{width,height}}),a=await c.newPage(),s=await c.newPage(); + await a.goto(WEB+'/agents');await a.locator('.roster .acard').first().waitFor();await a.evaluate(t=>{document.documentElement.dataset.theme=t;localStorage.setItem('aigc-theme',t);document.documentElement.dataset.reduce='0'},theme); + await s.goto('http://127.0.0.1:'+server.address().port);await s.evaluate(({theme,registry,skills,results,sessions,board})=>{ + go('agents');document.documentElement.dataset.theme=theme;document.querySelectorAll('#p-agents .seg button').forEach((e,i)=>e.classList.toggle('on',i===1)); + const clear=e=>{while(e.firstChild)e.removeChild(e.firstChild)}; + for(const id of ['taskList','taskList2']){const list=document.getElementById(id);clear(list);for(const task of sessions){const item=document.createElement('div');item.className='titem'+(id==='taskList2'&&task.id===board?' on':'');const title=document.createElement('b');title.className='ellipsis';title.textContent=task.title;const meta=document.createElement('div');meta.className='meta';const dot=document.createElement('span');dot.className='dot';dot.style.background='var(--sc-agent)';const grow=document.createElement('span');grow.className='grow';meta.append(dot,({returned:'已带回项目',awaiting_confirm:'待你确认',ready:'未开始'}[task.task_status]||task.task_status||'未开始'),grow,task.project?.title||'沙盒');item.append(title,meta);list.append(item);}} + const chips=document.querySelector('#p-agents .big-input .row').querySelectorAll('.chip');chips[0].querySelector('b').textContent='沙盒';chips[1].querySelector('b').textContent='reference-test';chips[2].querySelector('b').textContent='不指定'; + + document.querySelectorAll('#roster .acard').forEach((e,i)=>{e.querySelector('.bg').style.backgroundImage='none';e.querySelector('.tag').textContent=registry[i].skill_count+' 个技能';e.querySelector('.dim').textContent='reference-test';}); + const skillBox=document.querySelector('#p-agents .skills');clear(skillBox);for(const skill of skills.filter(x=>x.is_enabled)){const el=document.createElement('span');el.className='skill';el.append(document.createElement('i'),skill.name);skillBox.append(el);}const learn=document.createElement('span');learn.className='skill dim';learn.textContent='+ 学习新技能';skillBox.append(learn); + document.querySelector('#p-agents .mini-row .panel:last-child .tag').textContent=String(skills.length); + const outs=document.querySelector('#agentOuts');clear(outs);for(const r of results.slice(0,4)){const card=document.createElement('div');card.className='outcard';const thumb=document.createElement('div');thumb.className='t';const data=document.createElement('div');data.className='d';const title=document.createElement('b');title.textContent=r.title;const sub=document.createElement('span');sub.className='dim';sub.textContent=({script:'剧本创作',storyboard:'分镜设计'}[r.stage_key]||r.stage_key)+' · 草稿 v'+r.revision;data.append(title,sub);card.append(thumb,data);outs.append(card);} + const input=document.querySelector('#p-agents .big-input textarea');input.placeholder='描述你的创作想法、目标与要求…';document.querySelector('#p-agents .big-input .primary').disabled=true; + },{theme,registry,skills,results,sessions,board:state.board}); + await s.screenshot({path:`${out}/home-${theme}-${width}-original-content.png`,animations:'disabled'}); + for(const selector of ['.ahero','.big-input','.big-input .primary'])originalRows.push({theme,width,height,selector,style:await style(s.locator(selector).first())}); + await s.locator('.ahero').evaluate(e=>e.style.flexShrink='0'); + await a.screenshot({path:`${out}/home-${theme}-${width}-actual.png`,animations:'disabled'});await s.screenshot({path:`${out}/home-${theme}-${width}-approved-content.png`,animations:'disabled'}); + for(const [name,actual,ref] of [['hero','.ahero','.ahero'],['title','.ahero h2','.ahero h2'],['assistant','.roster .acard','.roster .acard'],['input','.big-input','.big-input'],['tasklist','.tasklist','.tasklist'],['primary','.big-input .primary','.big-input .primary']])rows.push({theme,width,height,page:'home',name,actual:await style(a.locator(actual).first()),sample:await style(s.locator(ref).first())}); + await a.goto(WEB+'/agents?session='+state.board);await a.locator('.shot-copy textarea').first().waitFor();const thumbnails=await a.locator('.shot .th').evaluateAll(es=>es.map(e=>e.querySelector('img')?.src||''));await s.evaluate(({shots,session,thumbnails})=>{ + go('agent-task'); + // Align real message/event state using the sample's own message/tool templates, never application DOM/CSS. + const page=document.querySelector('#p-agent-task'),body=page.querySelector('.convo-b'); + const userTemplate=body.querySelector('.msg.me').cloneNode(true),avatar=body.querySelector('.msg:not(.me) .av').cloneNode(true),toolTemplate=body.querySelector('details.tool').cloneNode(true); + body.replaceChildren(); + for(const m of session.messages){ + if((m.role==='user'||m.role==='assistant')&&m.content){const row=userTemplate.cloneNode(true);row.classList.toggle('me',m.role==='user');if(m.role==='assistant')row.querySelector('.av').replaceWith(avatar.cloneNode(true));row.querySelector('.bub').textContent=m.content;body.append(row);} + else if(m.role==='tool'){const tool=toolTemplate.cloneNode(true);tool.querySelector('code').textContent=m.tool_name;tool.querySelector('.dim')?.remove();tool.querySelector('.tag').textContent='完成';tool.querySelector('pre').textContent=JSON.stringify(m.tool_result,null,2);body.append(tool);} + } + page.querySelector('.ph .chip b').textContent='reference-test';page.querySelectorAll('.ph .chip')[1]?.remove(); + page.querySelector('.art-h .row>b').textContent='分镜设计 · 草稿';page.querySelector('.art-h .seg').querySelectorAll('button')[2].textContent='原文'; + page.querySelector('.art-f .chip b').textContent=session.project?.title||'沙盒'; + page.querySelector('.convo-in textarea').placeholder='向智能体提问,或用 @ 提及技能…';page.querySelector('.convo-in .ghost')?.remove();page.querySelector('.convo-in .primary').disabled=true; + document.querySelector('#p-agent-task .crumb b').textContent=session.title;document.querySelector('#p-agent-task .ph>.tag').textContent='已带回项目';document.querySelector('#p-agent-task .art-h .row>.dim').textContent=shots.length+' 镜 · '+shots.reduce((sum,s)=>sum+(Number(s.duration_sec)||0),0)+'s'; + const list=document.querySelector('#shotList');const originals=Array.from(list.children);list.replaceChildren();for(const [i,shot]of shots.entries()){const el=originals[i].cloneNode(true);el.querySelector('.th').style.backgroundImage=thumbnails[i]?`url("${thumbnails[i]}")`:'none';el.querySelector('[contenteditable]').textContent=shot.description;el.querySelector('.tag.mono').textContent=shot.duration_sec+'s';list.append(el);} + },{shots,session,thumbnails}); + await a.screenshot({path:`${out}/task-${theme}-${width}-actual.png`,animations:'disabled'});await s.screenshot({path:`${out}/task-${theme}-${width}-reference-content.png`,animations:'disabled'}); + for(const [name,actual,ref] of [['columns','.atask','.atask'],['artifact','.artifact','.artifact'],['header','.art-h','.art-h'],['footer','.art-f','.art-f'],['shot','.shot','.shot'],['save','.art-f .secondary','.art-f .btn:not(.primary)'],['primary','.art-f .primary','.art-f .primary']])rows.push({theme,width,height,page:'task',name,actual:await style(a.locator(actual).first()),sample:await style(s.locator(ref).first())}); + if(width===1440&&theme==='night'){ + await a.getByLabel('镜头 b4-shot-1 描述').fill('主题切换保持未保存编辑');await a.evaluate(async()=>{const {setTheme}=await import('/src/lib/theme.ts');setTheme('day')});await a.waitForFunction(()=>document.documentElement.dataset.theme==='day');assert.equal(await a.getByLabel('镜头 b4-shot-1 描述').inputValue(),'主题切换保持未保存编辑');operations.push('切换主题保持未保存成果文本');await a.screenshot({path:out+'/operation-theme-edit-preserved.png'}); + await a.getByRole('button',{name:'原文',exact:true}).click();await a.waitForFunction(()=>document.querySelector('[aria-label=成果草稿]')?.value.includes('主题切换保持未保存编辑'));assert((await a.getByLabel('成果草稿').inputValue()).includes('主题切换保持未保存编辑'));operations.push('逐镜编辑与原文视图同步');await a.screenshot({path:out+'/operation-raw-edit.png'}); + await a.reload();await a.locator('.shot-copy textarea').first().waitFor();await a.getByRole('button',{name:'对比上一版',exact:true}).click();await a.getByRole('dialog').waitFor();await a.screenshot({path:out+'/operation-version-comparison.png'});await a.keyboard.press('Escape'); + const tool=a.locator('.tool-card .head').first();await tool.click();await a.locator('.tool-card .body').first().waitFor();operations.push('工具详情真实参数与返回值可展开');await a.screenshot({path:out+'/operation-tool-expanded.png'}); + await a.evaluate(()=>document.documentElement.dataset.reduce='1');assert.equal(await a.locator('.b4 .aurora').evaluate(e=>getComputedStyle(e).display),'none');operations.push('减少动效隐藏本页装饰光晕与粒子'); + } + await c.close(); + } + fs.writeFileSync(out+'/original-style-values.json',JSON.stringify(originalRows,null,2)); + fs.writeFileSync(out+'/style-values.json',JSON.stringify(rows,null,2)); + const compareKeys=['x','y','width','height','padding','borderRadius','fontSize','fontWeight','letterSpacing','filter','backgroundColor','backgroundImage','boxShadow','gridTemplateColumns'];const differences=rows.flatMap(r=>compareKeys.filter(k=>r.actual[k]!==r.sample[k]).map(k=>({theme:r.theme,width:r.width,page:r.page,name:r.name,property:k,actual:r.actual[k],sample:r.sample[k]})));fs.writeFileSync(out+'/measured-differences.json',JSON.stringify(differences,null,2));assert.deepEqual(differences,[],'Measured sample differences must be corrected');fs.writeFileSync(out+'/operations.json',JSON.stringify(operations,null,2));console.log('PASS normalized visual pairs: 24; measured selector pairs:',rows.length,'operations:',operations.length); + }finally{await b.close();await new Promise(r=>server.close(r));} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/e2e/hel732.cjs b/e2e/hel732.cjs new file mode 100644 index 00000000..a677f233 --- /dev/null +++ b/e2e/hel732.cjs @@ -0,0 +1,82 @@ +const {chromium}=require(process.env.PLAYWRIGHT_MODULE_PATH||'playwright'); +const fs=require('node:fs'),http=require('node:http'),assert=require('node:assert/strict'); +const API='http://127.0.0.1:8247',WEB='http://127.0.0.1:5173',out='e2e/shots/hel732'; +fs.mkdirSync(out,{recursive:true});const checks=[],errors=[]; +const ok=(n,v)=>{assert(v,n);checks.push(n);console.log('PASS',n)}; +async function api(p,b,method){const r=await fetch(API+p,{method:method||(b?'POST':'GET'),headers:{'Content-Type':'application/json'},body:b?JSON.stringify(b):undefined});if(!r.ok)throw Error(p+' '+await r.text());return r.json()} +async function wait(fn){for(let i=0;i<120;i++){const r=await fn();if(r)return r;await new Promise(r=>setTimeout(r,150))}throw Error('condition timeout')} +(async()=>{ + const b=await chromium.launch({args:['--no-sandbox','--disable-dev-shm-usage']}); + const c=await b.newContext({viewport:{width:1440,height:900}});await c.tracing.start({screenshots:true,snapshots:true,sources:true});const p=await c.newPage();p.setDefaultTimeout(15000);p.on('pageerror',e=>errors.push(e.message)); + const sample=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html;charset=utf-8');res.end(fs.readFileSync('../evidence/reference/夜片场-多主题交互样本.html'))});await new Promise(r=>sample.listen(0,'127.0.0.1',r)); + try{ + const project=await api('/api/projects',{title:'B4 隔离项目',idea:'海岸与纸船'}),other=await api('/api/projects',{title:'B4 另一个项目'}); + await p.goto(WEB+'/agents');await p.locator('.roster .acard').first().waitFor(); + ok('首页五个真实阶段助手',await p.locator('.roster .acard').count()===5); + ok('无成果显示真实空态',(await p.locator('.outrow').innerText()).includes('暂无成果')); + await p.getByLabel('绑定项目',{exact:true}).selectOption(String(project.id)); + await p.getByLabel('任务技能').selectOption({index:1}); + await p.getByLabel('任务想法').fill('请调用工具查看项目,然后写一个海岸纸船的完整故事。'); + await p.getByRole('button',{name:'开始任务',exact:true}).click(); + const sid=await wait(async()=>Number(new URL(p.url()).searchParams.get('session'))||null); + const r=await wait(async()=>(await api('/api/results/deliverables?session_id='+sid))[0]); + ok('真实会话链路产生持久化成果',r.content.length>30); + const s=await api('/api/agent/sessions/'+sid);ok('任务摘要与状态持久化',s.task_summary.includes('海岸')&&s.task_status==='awaiting_confirm'); + ok('假模型通过应用实际调用工具',s.messages.some(m=>m.role==='tool'&&m.tool_name==='get_workspace')); + ok('技能选择传入真实会话',s.messages.some(m=>m.role==='user'&&m.mentions?.some(x=>x.type==='skill'))); + await p.getByLabel('成果草稿').waitFor();const edited=r.content+'【浏览器编辑并保存】';await p.getByLabel('成果草稿').fill(edited);await p.getByRole('button',{name:'保存草稿',exact:true}).click(); + await wait(async()=>(await api('/api/results/deliverables?session_id='+sid))[0].revision===2); + await p.reload();await p.getByLabel('成果草稿').waitFor();ok('编辑保存刷新恢复',await p.getByLabel('成果草稿').inputValue()===edited); + await p.getByRole('button',{name:'带回项目待确认',exact:true}).click();await p.locator('[data-testid=incoming-result]').waitFor(); + const wb=await api('/api/workbench/projects/'+project.id),stage=wb.stages.find(x=>x.stage_key==='script'); + ok('带回指定项目阶段且仅待确认',stage.status==='awaiting_confirm'&&stage.content.text===edited&&stage.confirmed_content===null); + ok('其他项目未出现成果',!JSON.stringify(await api('/api/workbench/projects/'+other.id)).includes('浏览器编辑')); + await p.locator('[data-testid=stage-confirm-btn]').click();await wait(async()=>(await api('/api/workbench/projects/'+project.id)).stages[0].status==='confirmed');ok('真实项目页显式确认',true); + const nr=(await api('/api/results/deliverables?session_id='+sid))[0];const body={deliverable_id:nr.id,revision:nr.revision,project_id:project.id,stage_key:'script'}; + ok('重复提交幂等',(await api('/api/results/store',body)).already_attached===true); + const bad=await fetch(API+'/api/results/store',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...body,project_id:other.id})});ok('跨项目误存被拒绝',bad.status===409); + // Actual structured reply and a single image job; no GPU/paid model. + const board=await api('/api/agent/sessions',{project_id:project.id,agent_key:'storyboard',title:'B4 分镜隔离任务'}); + await api('/api/agent/sessions/'+board.id+'/messages',{content:'B4_STORYBOARD 请读取工作区并给出三个镜头。'}); + const br=await wait(async()=>(await api('/api/results/deliverables?session_id='+board.id))[0]); + const parsed=JSON.parse(br.content.split('```json')[1].split('```')[0]); + const saved=await api('/api/results/deliverables/'+br.id,{revision:br.revision,content:JSON.stringify(parsed,null,2),project_id:project.id,stage_key:'storyboard'},'PATCH'); + await api('/api/results/store',{project_id:project.id,stage_key:'storyboard',deliverable_id:saved.id,revision:saved.revision}); + await p.goto(WEB+'/agents?session='+board.id);await p.getByRole('button',{name:'重画',exact:true}).first().waitFor(); + await p.getByLabel('镜头 b4-shot-1 描述').fill('逐镜编辑后的真实描述');await p.getByLabel('镜头 b4-shot-1 时长').fill('6');await p.getByRole('button',{name:'保存草稿',exact:true}).click(); + await wait(async()=>(await api('/api/results/deliverables?session_id='+board.id))[0].revision===3); + await p.getByRole('button',{name:'对比上一版',exact:true}).click();await p.getByRole('dialog').waitFor();ok('成果对比读取真实上一保存版本',(await p.getByRole('dialog').innerText()).includes('隔离验证镜头 1'));await p.getByRole('dialog').getByRole('button',{name:'关闭对话框',exact:true}).click(); + await p.reload();await p.getByLabel('镜头 b4-shot-1 描述').waitFor();ok('逐镜文字与时长保存刷新恢复',(await p.getByLabel('镜头 b4-shot-1 描述').inputValue())==='逐镜编辑后的真实描述'&&(await p.getByLabel('镜头 b4-shot-1 时长').inputValue())==='6'); + + const before=(await api('/api/jobs?project_id='+project.id)).length; + await p.getByRole('button',{name:'重画',exact:true}).nth(1).click(); + const jobs=await wait(async()=>{const rows=await api('/api/jobs?project_id='+project.id);return rows.length>before?rows:null}); + ok('单镜重画仅新增一个任务',jobs.length===before+1); + ok('单镜重画保留指定镜头',jobs[0].payload.target_id==='b4-shot-2'); + // Independent take → chooser → specific stage draft, original flow-back stays separately covered by B3. + fs.writeFileSync('e2e/fake_mode.json',JSON.stringify({mode:'ok',delay_sec:0,videos:false,unique_filename:true})); + const f=JSON.parse(fs.readFileSync('e2e/shots/reference/fixtures.json')); + await p.goto(WEB+'/create?kind=image&wf='+f.dual);await p.locator('#desk-prompt').waitFor();await p.locator('#desk-prompt').fill('B4 isolated independent image'); + const maxJob=Math.max(0,...(await api('/api/playground/jobs')).map(x=>x.id));await p.locator('.gen').click(); + const job=await wait(async()=>(await api('/api/playground/jobs')).find(j=>j.id>maxJob&&j.status==='done')); + await p.getByRole('button',{name:'存入项目',exact:true}).click();await p.getByLabel('存入项目',{exact:true}).selectOption(String(other.id));await p.getByLabel('存入阶段').selectOption('assets'); + await p.getByRole('button',{name:'存入待确认草稿'}).click(); + const mediaStage=await wait(async()=>(await api('/api/workbench/projects/'+other.id)).stages.find(s=>s.stage_key==='assets'&&s.incoming_results?.length)); + ok('独立生成经通用选择器存入指定阶段',mediaStage.incoming_results[0].paths[0]===job.output_paths[0]&&mediaStage.status==='awaiting_confirm'); + await p.goto(WEB+'/agents?legacy=1');await p.locator('.agent-rail').waitFor();ok('原会话及技能管理仍可达',true); + fs.writeFileSync(out+'/fixture-state.json',JSON.stringify({project,other,sid,board:board.id,br:(await api('/api/results/deliverables?session_id='+board.id))[0]},null,2)); + const sp=await c.newPage();const measures=[]; + for(const [width,height] of [[1440,900],[1366,768],[1280,720]])for(const theme of ['night','day','grade','bluehour']){ + await p.setViewportSize({width,height});await sp.setViewportSize({width,height}); + await p.goto(WEB+'/agents');await p.evaluate(t=>{document.documentElement.dataset.theme=t;localStorage.setItem('aigc-theme',t);document.documentElement.dataset.reduce='0'},theme);await p.locator('.roster .acard').first().waitFor(); + await sp.goto('http://127.0.0.1:'+sample.address().port);await sp.evaluate(t=>{go('agents');document.documentElement.dataset.theme=t;document.documentElement.dataset.reduce='0'},theme); + await p.screenshot({animations:"disabled",path:`${out}/home-${theme}-${width}-actual.png`});await sp.screenshot({animations:"disabled",path:`${out}/home-${theme}-${width}-sample.png`}); + measures.push({width,height,theme,page:'home',actual:await p.locator('.ahero').evaluate(e=>({width:e.offsetWidth,padding:getComputedStyle(e).padding,title:getComputedStyle(e.querySelector('h2')).fontSize,weight:getComputedStyle(e.querySelector('h2')).fontWeight})),sample:await sp.locator('.ahero').evaluate(e=>({width:e.offsetWidth,padding:getComputedStyle(e).padding,title:getComputedStyle(e.querySelector('h2')).fontSize,weight:getComputedStyle(e.querySelector('h2')).fontWeight}))}); + await p.goto(WEB+'/agents?session='+board.id);await p.locator('.shot-copy textarea').first().waitFor();await sp.evaluate(()=>go('agent-task')); + await p.screenshot({animations:"disabled",path:`${out}/task-${theme}-${width}-actual.png`});await sp.screenshot({animations:"disabled",path:`${out}/task-${theme}-${width}-sample.png`}); + ok(`任务页成果底栏可见 ${theme} ${width}`,await p.locator('.art-f').evaluate(e=>{const r=e.getBoundingClientRect();return r.bottom<=innerHeight&&r.top>=0})); + measures.push({width,height,theme,page:'task',actual:await p.locator('.atask').evaluate(e=>({columns:getComputedStyle(e).gridTemplateColumns,height:e.offsetHeight})),sample:await sp.locator('.atask').evaluate(e=>({columns:getComputedStyle(e).gridTemplateColumns,height:e.offsetHeight}))}); + } + fs.writeFileSync(out+'/measurements.json',JSON.stringify(measures,null,2));ok('浏览器无运行时错误',errors.length===0); + }finally{fs.writeFileSync(out+'/checks.json',JSON.stringify({checks,errors},null,2));await c.tracing.stop({path:out+'/trace.zip'});await b.close();await new Promise(r=>sample.close(r));} +})().catch(e=>{console.error(e);process.exit(1)}); diff --git a/e2e/run-hel732.py b/e2e/run-hel732.py new file mode 100644 index 00000000..7eb10a4c --- /dev/null +++ b/e2e/run-hel732.py @@ -0,0 +1,52 @@ +"""Run the isolated regression stack in the foreground and always stop children.""" +import os, signal, socket, subprocess, time, urllib.request +from pathlib import Path +root=Path(__file__).resolve().parents[1] +os.chdir(root) +py=os.environ.get('HEL732_PYTHON', 'python3') +logs=root/'e2e/shots/hel732'; logs.mkdir(parents=True,exist_ok=True) +env=os.environ.copy() +env['PYTHONPATH']=str(root/'calliope-backend/src') +for port in [8247,5173,18188,18189]: + with socket.socket() as probe: + assert probe.connect_ex(('127.0.0.1',port)) != 0, f'Test port {port} is already in use' +# Every run gets fresh disposable state; retain prior evidence instead of deleting it. +reference=root/'e2e/shots/reference' +reuse_fixture=os.environ.get('HEL732_REUSE_FIXTURE')=='1' +if reference.exists() and not reuse_fixture:reference.rename(reference.with_name('reference.previous-'+str(time.time_ns()))) +mode_path=root/'e2e/fake_mode.json' +saved_mode=mode_path.read_bytes() if mode_path.exists() else None +processes=[]; handles=[] +try: + for name,cmd in [('api',[py,'e2e/reference/server.py']),('comfy',[py,'e2e/fake_comfy.py']),('llm',[py,'e2e/fake_agent_b4.py']),('web',['npm','--prefix',os.environ.get('HEL732_WEB_DIR',os.environ.get('HEL729_WEB_DIR','calliope-web')),'run','dev'])]: + h=open(logs/(name+'.log'),'w');handles.append(h);processes.append(subprocess.Popen(cmd,stdout=h,stderr=subprocess.STDOUT,env=env,start_new_session=True)) + for url in ['http://127.0.0.1:8247/api/health','http://127.0.0.1:5173']: + for i in range(100): + try: + urllib.request.urlopen(url,timeout=2); break + except Exception: + if any(p.poll() is not None for p in processes): raise RuntimeError('A test service failed') + if i==99:raise + time.sleep(.2) + if not reuse_fixture: + for cmd in [[py,'e2e/seed.py'],[py,'e2e/reference/seed.py']]:subprocess.run(cmd,env=env,check=True) + failures=[] + scripts=os.environ.get('HEL732_TESTS',os.environ.get('HEL729_TESTS','e2e/hel732.cjs')).split(',') + for script in scripts: + print('RUN',script,flush=True) + result=subprocess.run(['node',script],env=env) + if result.returncode:failures.append(script) + print('FAILED SCRIPTS',failures,flush=True) + if failures:raise SystemExit(1) + +finally: + for p in processes: + if p.poll() is None:os.killpg(p.pid,signal.SIGTERM) + for p in processes: + try:p.wait(timeout=10) + except subprocess.TimeoutExpired:os.killpg(p.pid,signal.SIGKILL);p.wait() + print("STOPPED TEST CHILDREN", [{"pid":p.pid,"exit":p.returncode} for p in processes],flush=True) + for h in handles:h.close() + + if saved_mode is not None:mode_path.write_bytes(saved_mode) + elif mode_path.exists():mode_path.unlink()