From 082e767c8e69c73184ec15da1daa7ba3367821ee Mon Sep 17 00:00:00 2001 From: Benjiyaya Date: Tue, 1 Sep 2026 02:10:08 +0800 Subject: [PATCH] feat(canvas): CRUD router with entity auto-seed, tombstones, position persistence --- calliope-backend/src/calliope/db.py | 1 + calliope-backend/src/calliope/main.py | 2 + .../src/calliope/routers/canvas.py | 361 ++++++++++++++++++ calliope-backend/tests/test_canvas_db.py | 4 +- calliope-backend/tests/test_canvas_router.py | 191 +++++++++ 5 files changed, 557 insertions(+), 2 deletions(-) create mode 100644 calliope-backend/src/calliope/routers/canvas.py create mode 100644 calliope-backend/tests/test_canvas_router.py diff --git a/calliope-backend/src/calliope/db.py b/calliope-backend/src/calliope/db.py index 7789f5b4..f5eac5ec 100644 --- a/calliope-backend/src/calliope/db.py +++ b/calliope-backend/src/calliope/db.py @@ -180,6 +180,7 @@ CREATE TABLE IF NOT EXISTS canvas_node ( input_values_json TEXT NOT NULL DEFAULT '{}', entity_type TEXT NULL, entity_id INTEGER NULL, + deleted INTEGER NOT NULL DEFAULT 0, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); diff --git a/calliope-backend/src/calliope/main.py b/calliope-backend/src/calliope/main.py index d568197e..849648e3 100644 --- a/calliope-backend/src/calliope/main.py +++ b/calliope-backend/src/calliope/main.py @@ -18,6 +18,7 @@ from calliope.queue.worker import queue_worker from calliope.routers import ( agent, assets, + canvas, events, jobs, playground, @@ -128,6 +129,7 @@ def create_app(static_dir: Path | None = None) -> FastAPI: app.include_router(workflows.router, prefix="/api/workflows", tags=["workflows"]) app.include_router(jobs.router, prefix="/api/jobs", tags=["jobs"]) app.include_router(playground.router, prefix="/api/playground", tags=["playground"]) + app.include_router(canvas.router, prefix="/api/canvas", tags=["canvas"]) app.include_router(agent.router, prefix="/api/agent", tags=["agent"]) app.include_router(events.router, prefix="/api/events", tags=["events"]) diff --git a/calliope-backend/src/calliope/routers/canvas.py b/calliope-backend/src/calliope/routers/canvas.py new file mode 100644 index 00000000..6eae94ba --- /dev/null +++ b/calliope-backend/src/calliope/routers/canvas.py @@ -0,0 +1,361 @@ +"""Canvas v2.1 — project/sandbox graph storage (Phase 1: entities only). + +Scope model (addendum §1): one durable canvas per project (the story bible, +shared across its sessions); one sandbox canvas per unlinked agent session. +Entity auto-seed is idempotent on (entity_type, entity_id) and never +resurrects nodes the user deleted. +""" +from __future__ import annotations + +import json +from datetime import datetime, timezone +from typing import Any + +from fastapi import APIRouter, HTTPException +from pydantic import BaseModel, field_validator + +from calliope.config import settings +from calliope.db import get_db, row_to_dict +from calliope.events.bus import event_bus + +router = APIRouter() + +ENTITY_COLUMNS = { + "character": 80, + "location": 420, + "item": 760, + "scene": 1100, +} + +_ENTITY_QUERIES = [ + ( + "character", + "SELECT id, name AS label FROM characters WHERE project_id = ? ORDER BY id", + ), + ( + "location", + "SELECT id, name AS label FROM locations WHERE project_id = ? ORDER BY id", + ), + ( + "item", + "SELECT id, name AS label FROM items WHERE project_id = ? ORDER BY id", + ), + ( + "scene", + "SELECT id, heading AS label FROM scenes WHERE project_id = ? ORDER BY order_index, id", + ), +] + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +class CanvasCreate(BaseModel): + project_id: int | None = None + agent_session_id: int | None = None + title: str = "Untitled Canvas" + + @field_validator("title") + @classmethod + def _bound_title(cls, v: str) -> str: + if len(v) > 300: + raise ValueError("Title too long (max 300 characters)") + return v + + +class CanvasPatch(BaseModel): + title: str | None = None + viewport_json: str | None = None + + @field_validator("title") + @classmethod + def _bound_title(cls, v: str | None) -> str | None: + if v is not None and len(v) > 300: + raise ValueError("Title too long (max 300 characters)") + return v + + +class NodePatch(BaseModel): + x: float | None = None + y: float | None = None + title: str | None = None + + +def _canvas_out(conn, row) -> dict[str, Any]: + out = row_to_dict(row) + if out.get("project_id"): + proj = conn.execute( + "SELECT id, title FROM projects WHERE id = ?", (out["project_id"],) + ).fetchone() + out["project"] = {"id": proj["id"], "title": proj["title"]} if proj else None + else: + out["project"] = None + return out + + +def _load_graph(conn, canvas_id: int) -> dict[str, Any]: + row = conn.execute("SELECT * FROM canvas WHERE id = ?", (canvas_id,)).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Canvas not found") + nodes = [ + row_to_dict(r) + for r in conn.execute( + "SELECT * FROM canvas_node WHERE canvas_id = ? AND deleted = 0 ORDER BY id", + (canvas_id,), + ).fetchall() + ] + return {"canvas": _canvas_out(conn, row), "nodes": nodes} + + +def seed_entities(conn, canvas_id: int, project_id: int) -> int: + """Insert entity nodes for characters/locations/items/scenes not yet on + the canvas. Idempotent on (entity_type, entity_id). Returns insert count.""" + existing = { + (r["entity_type"], r["entity_id"]) + for r in conn.execute( + "SELECT entity_type, entity_id FROM canvas_node WHERE canvas_id = ?", + (canvas_id,), + ).fetchall() + } + # Tombstoned entity nodes (user deleted the card) must not resurrect. + existing |= { + (r["entity_type"], r["entity_id"]) + for r in conn.execute( + """ + SELECT entity_type, entity_id FROM canvas_node + WHERE canvas_id = ? AND deleted = 1 + """, + (canvas_id,), + ).fetchall() + } + inserted = 0 + for entity_type, query in _ENTITY_QUERIES: + rows = conn.execute(query, (project_id,)).fetchall() + y = 80 + for r in rows: + key = (entity_type, r["id"]) + if key in existing: + continue + conn.execute( + """ + INSERT INTO canvas_node + (canvas_id, type, title, x, y, entity_type, entity_id, + created_at, updated_at) + VALUES (?, 'entity', ?, ?, ?, ?, ?, ?, ?) + """, + ( + canvas_id, + r["label"], + ENTITY_COLUMNS[entity_type], + y, + entity_type, + r["id"], + _now(), + _now(), + ), + ) + existing.add(key) + inserted += 1 + y += 120 + return inserted + + +@router.get("") +async def list_canvas() -> list[dict[str, Any]]: + conn = get_db(settings.db_path) + try: + rows = conn.execute( + """ + SELECT id, title, project_id, agent_session_id, updated_at + FROM canvas ORDER BY updated_at DESC + """ + ).fetchall() + return [row_to_dict(r) for r in rows] + finally: + conn.close() + + +@router.post("") +async def create_canvas(payload: CanvasCreate) -> dict[str, Any]: + if (payload.project_id is None) == (payload.agent_session_id is None): + raise HTTPException( + status_code=422, detail="Exactly one of project_id or agent_session_id is required" + ) + conn = get_db(settings.db_path) + try: + canvas_id: int + if payload.project_id is not None: + pid = payload.project_id + if not conn.execute("SELECT id FROM projects WHERE id = ?", (pid,)).fetchone(): + raise HTTPException(status_code=404, detail="Project not found") + row = conn.execute( + "SELECT id FROM canvas WHERE project_id = ? ORDER BY id LIMIT 1", (pid,) + ).fetchone() + if row: + canvas_id = int(row["id"]) + else: + cur = conn.execute( + """ + INSERT INTO canvas (project_id, title, created_at, updated_at) + VALUES (?, ?, ?, ?) + """, + (pid, payload.title, _now(), _now()), + ) + canvas_id = int(cur.lastrowid) + seed_entities(conn, canvas_id, pid) + else: + sid = payload.agent_session_id + session = conn.execute( + "SELECT id, project_id FROM agent_sessions WHERE id = ?", (sid,) + ).fetchone() + if not session: + raise HTTPException(status_code=404, detail="Session not found") + if session["project_id"] is not None: + raise HTTPException( + status_code=422, + detail="Session is project-linked; create the project canvas instead", + ) + row = conn.execute( + "SELECT id FROM canvas WHERE agent_session_id = ? ORDER BY id LIMIT 1", (sid,) + ).fetchone() + if row: + canvas_id = int(row["id"]) + else: + cur = conn.execute( + """ + INSERT INTO canvas (agent_session_id, title, created_at, updated_at) + VALUES (?, ?, ?, ?) + """, + (sid, payload.title, _now(), _now()), + ) + canvas_id = int(cur.lastrowid) + + conn.commit() + graph = _load_graph(conn, canvas_id) + finally: + conn.close() + await event_bus.publish( + "canvas.updated", + {"canvas_id": canvas_id, "reason": "created"}, + ) + return graph + + +@router.get("/{canvas_id}") +async def get_canvas(canvas_id: int) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + return _load_graph(conn, canvas_id) + finally: + conn.close() + + +@router.patch("/{canvas_id}") +async def patch_canvas(canvas_id: int, payload: CanvasPatch) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + if not conn.execute("SELECT id FROM canvas WHERE id = ?", (canvas_id,)).fetchone(): + raise HTTPException(status_code=404, detail="Canvas not found") + if payload.title is not None: + conn.execute( + "UPDATE canvas SET title = ?, updated_at = ? WHERE id = ?", + (payload.title, _now(), canvas_id), + ) + if payload.viewport_json is not None: + try: + json.loads(payload.viewport_json) + except json.JSONDecodeError as exc: + raise HTTPException( + status_code=422, detail="viewport_json must be valid JSON" + ) from exc + conn.execute( + "UPDATE canvas SET viewport_json = ?, updated_at = ? WHERE id = ?", + (payload.viewport_json, _now(), canvas_id), + ) + conn.commit() + row = conn.execute("SELECT * FROM canvas WHERE id = ?", (canvas_id,)).fetchone() + out = _canvas_out(conn, row) + finally: + conn.close() + await event_bus.publish( + "canvas.updated", + {"canvas_id": canvas_id, "reason": "patched"}, + ) + return out + + +@router.delete("/{canvas_id}") +async def delete_canvas(canvas_id: int) -> dict[str, bool]: + conn = get_db(settings.db_path) + try: + if not conn.execute("SELECT id FROM canvas WHERE id = ?", (canvas_id,)).fetchone(): + raise HTTPException(status_code=404, detail="Canvas not found") + conn.execute("DELETE FROM canvas WHERE id = ?", (canvas_id,)) + conn.commit() + finally: + conn.close() + await event_bus.publish( + "canvas.updated", + {"canvas_id": canvas_id, "reason": "deleted"}, + ) + return {"ok": True} + + +@router.patch("/{canvas_id}/nodes/{node_id}") +async def patch_node(canvas_id: int, node_id: int, payload: NodePatch) -> dict[str, Any]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id FROM canvas_node WHERE id = ? AND canvas_id = ?", + (node_id, canvas_id), + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Node not found") + if payload.x is not None: + conn.execute( + "UPDATE canvas_node SET x = ?, updated_at = ? WHERE id = ?", + (payload.x, _now(), node_id), + ) + if payload.y is not None: + conn.execute( + "UPDATE canvas_node SET y = ?, updated_at = ? WHERE id = ?", + (payload.y, _now(), node_id), + ) + if payload.title is not None: + conn.execute( + "UPDATE canvas_node SET title = ?, updated_at = ? WHERE id = ?", + (payload.title, _now(), node_id), + ) + conn.commit() + out = row_to_dict( + conn.execute("SELECT * FROM canvas_node WHERE id = ?", (node_id,)).fetchone() + ) + finally: + conn.close() + return out + + +@router.delete("/{canvas_id}/nodes/{node_id}") +async def delete_node(canvas_id: int, node_id: int) -> dict[str, bool]: + conn = get_db(settings.db_path) + try: + row = conn.execute( + "SELECT id, entity_type, entity_id FROM canvas_node WHERE id = ? AND canvas_id = ?", + (node_id, canvas_id), + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Node not found") + if row["entity_type"] is not None and row["entity_id"] is not None: + # Entity nodes tombstone — hard delete would let auto-seed resurrect + # the card the user deliberately removed. + conn.execute( + "UPDATE canvas_node SET deleted = 1, updated_at = ? WHERE id = ?", + (_now(), node_id), + ) + else: + conn.execute("DELETE FROM canvas_node WHERE id = ?", (node_id,)) + conn.commit() + finally: + conn.close() + return {"ok": True} diff --git a/calliope-backend/tests/test_canvas_db.py b/calliope-backend/tests/test_canvas_db.py index f2ea9239..696e5e42 100644 --- a/calliope-backend/tests/test_canvas_db.py +++ b/calliope-backend/tests/test_canvas_db.py @@ -38,7 +38,7 @@ def test_project_delete_cascades_canvas(client): pid = client.post("/api/projects", json={"title": "C1", "idea": "x"}).json()["id"] r = client.post("/api/canvas", json={"project_id": pid, "title": "Bible"}) assert r.status_code == 200 - canvas_id = r.json()["id"] + canvas_id = r.json()["canvas"]["id"] client.delete(f"/api/projects/{pid}") @@ -50,7 +50,7 @@ def test_session_delete_cascades_sandbox_canvas(client): sid = client.post("/api/agent/sessions", json={}).json()["id"] r = client.post("/api/canvas", json={"agent_session_id": sid}) assert r.status_code == 200 - canvas_id = r.json()["id"] + canvas_id = r.json()["canvas"]["id"] client.delete(f"/api/agent/sessions/{sid}") diff --git a/calliope-backend/tests/test_canvas_router.py b/calliope-backend/tests/test_canvas_router.py new file mode 100644 index 00000000..14dcb3c9 --- /dev/null +++ b/calliope-backend/tests/test_canvas_router.py @@ -0,0 +1,191 @@ +"""Canvas v2.1 Phase 1 — CRUD router, get-or-create scoping, entity auto-seed.""" +from __future__ import annotations + +import json as _json + +import calliope.config as config_module +from calliope.db import get_db + + +def _seed_story_entities(client, project_id: int) -> None: + """Insert entity rows directly (no LLM) — deterministic test fixtures.""" + conn = get_db(config_module.settings.db_path) + try: + conn.execute( + "INSERT INTO characters (project_id, name, appearance) VALUES (?, ?, ?)", + (project_id, "Kira", "tall fighter"), + ) + conn.execute( + "INSERT INTO characters (project_id, name, appearance) VALUES (?, ?, ?)", + (project_id, "Yun", "rival"), + ) + conn.execute( + "INSERT INTO locations (project_id, name, description) VALUES (?, ?, ?)", + (project_id, "Rooftop", "night rooftop"), + ) + conn.execute( + "INSERT INTO items (project_id, name, description) VALUES (?, ?, ?)", + (project_id, "Locket", "silver locket"), + ) + conn.execute( + "INSERT INTO scenes (project_id, order_index, heading, action) VALUES (?, ?, ?, ?)", + (project_id, 1, "Round 1", "feint low, switch high"), + ) + conn.commit() + finally: + conn.close() + + +def test_get_or_create_project_canvas(client): + pid = client.post("/api/projects", json={"title": "Alpha", "idea": "x"}).json()["id"] + r1 = client.post("/api/canvas", json={"project_id": pid, "title": "Alpha Bible"}) + assert r1.status_code == 200 + r2 = client.post("/api/canvas", json={"project_id": pid}) + assert r2.status_code == 200 + assert r1.json()["canvas"]["id"] == r2.json()["canvas"]["id"], "must be get-or-create" + assert r2.json()["canvas"]["title"] == "Alpha Bible", "existing title preserved" + + +def test_sandbox_canvas_requires_session_and_scopes(client): + sid = client.post("/api/agent/sessions", json={}).json()["id"] + r = client.post("/api/canvas", json={"agent_session_id": sid}) + assert r.status_code == 200 + c = r.json()["canvas"] + assert c["project_id"] is None + assert c["agent_session_id"] == sid + + +def test_create_rejects_both_and_neither_scope(client): + pid = client.post("/api/projects", json={"title": "Beta", "idea": "x"}).json()["id"] + sid = client.post("/api/agent/sessions", json={}).json()["id"] + assert client.post("/api/canvas", json={}).status_code == 422 + assert ( + client.post("/api/canvas", json={"project_id": pid, "agent_session_id": sid}).status_code + == 422 + ) + + +def test_linked_session_cannot_make_sandbox_canvas(client): + pid = client.post("/api/projects", json={"title": "Linked", "idea": "x"}).json()["id"] + sid = client.post("/api/agent/sessions", json={"project_id": pid}).json()["id"] + r = client.post("/api/canvas", json={"agent_session_id": sid}) + assert r.status_code == 422 + + +def test_auto_seed_and_position_persistence(client): + pid = client.post("/api/projects", json={"title": "Gamma", "idea": "x"}).json()["id"] + _seed_story_entities(client, pid) + r = client.post("/api/canvas", json={"project_id": pid}) + assert r.status_code == 200, r.text + graph = r.json() + nodes = graph["nodes"] + assert len(nodes) == 5, "2 chars + 1 loc + 1 item + 1 scene" + kinds = {n["entity_type"] for n in nodes} + assert kinds == {"character", "location", "item", "scene"} + assert all(n["type"] == "entity" for n in nodes) + + seen: set[tuple[str, int]] = set() + for n in nodes: + key = (n["entity_type"], n["entity_id"]) + assert key not in seen, "duplicate entity node" + seen.add(key) + + chars = [n for n in nodes if n["entity_type"] == "character"] + locs = [n for n in nodes if n["entity_type"] == "location"] + assert chars[0]["x"] < locs[0]["x"], "characters left of locations" + + node_id = nodes[0]["id"] + r = client.patch( + f"/api/canvas/{graph['canvas']['id']}/nodes/{node_id}", json={"x": 555.5, "y": 77} + ) + assert r.status_code == 200 + assert abs(r.json()["x"] - 555.5) < 1e-9 + fetched = client.get(f"/api/canvas/{graph['canvas']['id']}").json() + match = [n for n in fetched["nodes"] if n["id"] == node_id][0] + assert match["x"] == 555.5 + + +def test_reopen_seeds_only_new_entities(client): + pid = client.post("/api/projects", json={"title": "Delta", "idea": "x"}).json()["id"] + _seed_story_entities(client, pid) + graph = client.post("/api/canvas", json={"project_id": pid}).json() + canvas_id = graph["canvas"]["id"] + before = {(n["entity_type"], n["entity_id"]) for n in graph["nodes"]} + assert len(before) == 5 + + conn = get_db(config_module.settings.db_path) + try: + cur = conn.execute( + "INSERT INTO characters (project_id, name, appearance) VALUES (?, ?, ?)", + (pid, "Late Addition", "short"), + ) + late_id = cur.lastrowid + conn.commit() + finally: + conn.close() + + graph2 = client.post("/api/canvas", json={"project_id": pid}).json() + assert graph2["canvas"]["id"] == canvas_id + after = {(n["entity_type"], n["entity_id"]) for n in graph2["nodes"]} + assert ("character", late_id) in after, "new entity must gain a node on reopen" + assert before <= after + assert len(after) == 6 + + +def test_deleted_entity_node_not_reseeded(client): + """Removing a node is a user choice — reopen must not resurrect it.""" + pid = client.post("/api/projects", json={"title": "Epsilon", "idea": "x"}).json()["id"] + _seed_story_entities(client, pid) + graph = client.post("/api/canvas", json={"project_id": pid}).json() + canvas_id = graph["canvas"]["id"] + victim = [n for n in graph["nodes"] if n["entity_type"] == "item"][0] + assert client.delete(f"/api/canvas/{canvas_id}/nodes/{victim['id']}").status_code == 200 + + graph2 = client.post("/api/canvas", json={"project_id": pid}).json() + keys = {(n["entity_type"], n["entity_id"]) for n in graph2["nodes"]} + assert ("item", victim["entity_id"]) not in keys + + +def test_viewport_and_title_patch(client): + sid = client.post("/api/agent/sessions", json={}).json()["id"] + cid = client.post("/api/canvas", json={"agent_session_id": sid}).json()["canvas"]["id"] + r = client.patch( + f"/api/canvas/{cid}", + json={"title": "Scratch", "viewport_json": '{"x":12,"y":-4,"zoom":0.8}'}, + ) + assert r.status_code == 200 + assert r.json()["title"] == "Scratch" + fetched = client.get(f"/api/canvas/{cid}").json()["canvas"] + assert fetched["viewport_json"] == '{"x":12,"y":-4,"zoom":0.8}' + + +def test_viewport_must_be_json(client): + sid = client.post("/api/agent/sessions", json={}).json()["id"] + cid = client.post("/api/canvas", json={"agent_session_id": sid}).json()["canvas"]["id"] + r = client.patch(f"/api/canvas/{cid}", json={"viewport_json": "not json{"}) + assert r.status_code == 422 + + +def test_delete_canvas(client): + sid = client.post("/api/agent/sessions", json={}).json()["id"] + cid = client.post("/api/canvas", json={"agent_session_id": sid}).json()["canvas"]["id"] + assert client.delete(f"/api/canvas/{cid}").status_code == 200 + assert client.get(f"/api/canvas/{cid}").status_code == 404 + + +def test_canvas_updated_events_published(client, monkeypatch): + """Graph mutations publish canvas.updated so open canvases refetch.""" + events: list[tuple[str, dict]] = [] + + async def fake_publish(event_type: str, data: dict) -> None: + events.append((event_type, data)) + + import calliope.events.bus as bus_mod + + monkeypatch.setattr(bus_mod.event_bus, "publish", fake_publish) + + pid = client.post("/api/projects", json={"title": "Ev", "idea": "x"}).json()["id"] + r = client.post("/api/canvas", json={"project_id": pid}) + assert r.status_code == 200 + updates = [d for (t, d) in events if t == "canvas.updated"] + assert updates and updates[-1]["canvas_id"] == r.json()["canvas"]["id"]