Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(canvas): item versions, and documents named on chat replies
trohitgc5eabeba5323
diff --git a/server/nodes/tool/canvas/__init__.py b/server/nodes/tool/canvas/__init__.pyindex 13d9f40b..6ea59474 100644--- a/server/nodes/tool/canvas/__init__.py+++ b/server/nodes/tool/canvas/__init__.py@@ -28,6 +28,7 @@ from pydantic import (model_validator,)+from core.logging import get_loggerfrom services.plugin import (NodeContext,NodeUserError,@@ -46,6 +47,11 @@ from ._store import (truncate_note,)+logger = get_logger(__name__)++#: Languages a note is a document in, not code.+_DOCUMENT_LANGUAGES = frozenset({"markdown", "md"})+# Depth cap for the structural FileRef scan of connected outputs. Node# results are already payload-disciplined; anything nested deeper than this# is not a ref a user meant to display.@@ -87,6 +93,14 @@ class CanvasParams(BaseModel):default="append",description="append adds to the board; replace clears it first.",)+ update_id: Optional[str] = Field(+ default=None,+ max_length=64,+ description=(+ "The id of an item already on the board (from an earlier result's added list) to update instead: "+ "what this call shows (one path, url or content, of the same kind) becomes its next version."+ ),+ )model_config = ConfigDict(extra="ignore")@@ -160,7 +174,8 @@ class CanvasNode(ToolNode):"http(s) URL, or markdown text via content. Use this after producing ""a file or result the user should see — e.g. a screenshot, a chart, ""or a report. mode=replace clears the board first; the default "- "append adds to it."+ "append adds to it. To revise something you showed, pass its id as "+ "update_id: the board keeps its earlier versions.")handles = ({"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},@@ -260,6 +275,20 @@ class CanvasNode(ToolNode):items[0]["title"] = params.titlestore = CanvasStore(get_database())+ if params.update_id:+ if len(items) != 1:+ raise NodeUserError("update_id updates one item: pass one path, url or content.")+ try:+ updated, revision = await store.update(scope, params.update_id, items[0])+ except CanvasStoreError as exc:+ raise NodeUserError(str(exc)) from exc+ await dispatch_canvas_updated(workflow_id=ctx.workflow_id, node_id=ctx.node_id, revision=revision)+ await _show_in_chat(ctx, updated)+ return {+ "message": f"Updated {updated['title'] or 'the item'} to version {updated['version']}.",+ "revision": revision,+ "added": [{"id": updated["id"], "kind": updated["kind"], "title": updated["title"], "version": updated["version"]}],+ }try:added, revision, total = await store.append(scope, items, mode=params.mode@@ -272,6 +301,8 @@ class CanvasNode(ToolNode):node_id=ctx.node_id,revision=revision,)+ for row in added:+ await _show_in_chat(ctx, row)message = f"Displayed {len(added)} item(s); board holds {total}."if params.mode == "replace":@@ -289,6 +320,43 @@ class CanvasNode(ToolNode):}+async def _show_in_chat(ctx: NodeContext, item: Dict[str, Any]) -> None:+ """A note the agent answering the owner writes is an artifact of its+ answer: a card in the reply that opens the board on it (and its+ versions). Best effort: the board has it either way."""+ stream = ctx.raw.get("chat_stream") if isinstance(ctx.raw, dict) else None+ if not isinstance(stream, dict) or item.get("kind") != "note" or not ctx.workflow_id:+ return+ language = str(item.get("language") or "").strip().lower()+ try:+ from services.chat.parts import show_artifact+ from services.plugin.deps import get_database++ await show_artifact(+ get_database(),+ stream,+ artifact={+ "workflow_id": ctx.workflow_id,+ "canvas_node_id": ctx.node_id,+ "item_id": item["id"],+ "version": int(item.get("version") or 1),+ "title": item.get("title") or _note_title(item.get("content") or ""),+ "format": "code" if language and language not in _DOCUMENT_LANGUAGES else "markdown",+ },+ )+ except Exception: # noqa: BLE001 - the board has the note either way+ logger.warning("Could not show a canvas note in the chat", item_id=item.get("id"), exc_info=True)+++def _note_title(content: str) -> str:+ """A note's first line (its heading), as its title."""+ for line in content.splitlines():+ text = line.strip().lstrip("#").strip()+ if text:+ return text[:120]+ return "Note"++def _build_ref(ctx: NodeContext, raw_path: str) -> Dict[str, Any]:"""A workspace path -> a serialized ``FileRef`` (gallery-style).diff --git a/server/nodes/tool/canvas/_handlers.py b/server/nodes/tool/canvas/_handlers.pyindex f5ec3e65..5bc9cd6f 100644--- a/server/nodes/tool/canvas/_handlers.py+++ b/server/nodes/tool/canvas/_handlers.py@@ -136,11 +136,42 @@ async def handle_canvas_clear(return {"success": True, **result}+@ws_response+async def handle_canvas_versions(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """An item's versions, newest first."""+ store, scope = await _resolve_store_and_scope(data, websocket)+ item_id = str(data.get("item_id") or "").strip()+ if not item_id:+ raise NodeUserError("item_id required")+ try:+ result = await store.versions(scope, item_id)+ except CanvasStoreError as exc:+ raise NodeUserError(str(exc)) from exc+ return {"success": True, **result}+++@ws_response+async def handle_canvas_version(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:+ """One version of an item, whole."""+ store, scope = await _resolve_store_and_scope(data, websocket)+ item_id = str(data.get("item_id") or "").strip()+ version = data.get("version")+ if not item_id or not isinstance(version, int) or version < 1:+ raise NodeUserError("item_id and version required")+ try:+ item = await store.version(scope, item_id, version)+ except CanvasStoreError as exc:+ raise NodeUserError(str(exc)) from exc+ return {"success": True, "item": item}++WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]WS_HANDLERS: Dict[str, WSHandler] = {"canvas_list": handle_canvas_list,"canvas_remove": handle_canvas_remove,"canvas_clear": handle_canvas_clear,+ "canvas_versions": handle_canvas_versions,+ "canvas_version": handle_canvas_version,}@@ -149,4 +180,6 @@ __all__ = ["handle_canvas_clear","handle_canvas_list","handle_canvas_remove",+ "handle_canvas_version",+ "handle_canvas_versions",]diff --git a/server/nodes/tool/canvas/_store.py b/server/nodes/tool/canvas/_store.pyindex 4ab653a6..a8303f78 100644--- a/server/nodes/tool/canvas/_store.py+++ b/server/nodes/tool/canvas/_store.py@@ -11,6 +11,12 @@ A board holds *references* (serialized ``FileRef`` dicts, URLs) and smallmarkdown notes — never file bytes. Content bodies for workspace files arefetched by the client over the existing workspace HTTP route; the board rowsstay small so ``canvas_list`` is one cheap fetch.++Items have versions. An item starts at version 1; ``update`` makes what a+later call shows its next version, and ``canvas_item_versions`` keeps every+version (the current one too), at most ``CANVAS_MAX_VERSIONS`` per item,+oldest dropped first. Removing an item, clearing the board or evicting an+item drops its versions with it."""from __future__ import annotations@@ -35,6 +41,8 @@ _KEY_VERSION = "canvas:v1"UNSAVED_WORKFLOW_ID = "unsaved"CANVAS_MAX_ITEMS = 200+#: Versions kept per item (its current one included).+CANVAS_MAX_VERSIONS = 50CANVAS_NOTE_MAX_BYTES = 64 * 1024CANVAS_MAX_PATHS_PER_CALL = 20@@ -109,12 +117,40 @@ class CanvasItemRow(SQLModel, table=True):source: str = Field(default="workflow", max_length=10)position: int = Field(default=0, index=True)created_at: datetime = Field(default_factory=_utcnow)+ #: 1 for a new item; each update adds one.+ version: int = Field(default=1)+ updated_at: Optional[datetime] = Field(default=None)+++class CanvasItemVersion(SQLModel, table=True):+ """One version of an item, as it was shown (the current one too)."""++ __tablename__ = "canvas_item_versions"++ id: str = Field(primary_key=True, max_length=64)+ item_id: str = Field(index=True, max_length=64)+ board_id: str = Field(index=True, max_length=80)+ version: int = Field(default=1)+ kind: str = Field(max_length=10)+ title: Optional[str] = Field(default=None, max_length=300)+ ref: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))+ url: Optional[str] = Field(default=None, max_length=2048)+ content: Optional[str] = Field(default=None, sa_column=Column(Text))+ language: Optional[str] = Field(default=None, max_length=40)+ source: str = Field(default="workflow", max_length=10)+ created_at: datetime = Field(default_factory=_utcnow)class CanvasStoreError(ValueError):"""User-correctable store failure (unknown item id, bad kind)."""+def _iso(moment: Optional[datetime]) -> Optional[str]:+ if moment is None:+ return None+ return (moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)).isoformat()++def _serialize(row: CanvasItemRow) -> Dict[str, Any]:"""Row -> the fixed CanvasItem wire shape (stable key set, null-filled)."""return {@@ -126,10 +162,37 @@ def _serialize(row: CanvasItemRow) -> Dict[str, Any]:"content": row.content,"language": row.language,"source": row.source,- "created_at": row.created_at.isoformat() if row.created_at else None,+ "created_at": _iso(row.created_at),+ "version": int(row.version or 1),+ "updated_at": _iso(row.updated_at),}+def _version_row(row: CanvasItemRow) -> CanvasItemVersion:+ return CanvasItemVersion(+ id=uuid.uuid4().hex,+ item_id=row.id,+ board_id=row.board_id,+ version=int(row.version or 1),+ kind=row.kind,+ title=row.title,+ ref=row.ref,+ url=row.url,+ content=row.content,+ language=row.language,+ source=row.source,+ created_at=row.updated_at or row.created_at or _utcnow(),+ )+++def _version_size(version: CanvasItemVersion) -> int:+ if version.content is not None:+ return len(version.content.encode("utf-8"))+ if isinstance(version.ref, dict) and isinstance(version.ref.get("size_bytes"), int):+ return int(version.ref["size_bytes"])+ return 0++class CanvasStore:"""Append/list/remove/clear over one board, each a single transaction."""@@ -149,16 +212,17 @@ class CanvasStore:if engine in self._initialized_engines:returnasync with engine.begin() as connection:- await connection.run_sync(- lambda sync_connection: CanvasBoard.__table__.create(- sync_connection, checkfirst=True- )- )- await connection.run_sync(- lambda sync_connection: CanvasItemRow.__table__.create(- sync_connection, checkfirst=True+ for table in (CanvasBoard.__table__, CanvasItemRow.__table__, CanvasItemVersion.__table__):+ await connection.run_sync(+ lambda sync_connection, table=table: table.create(sync_connection, checkfirst=True))- )+ # Boards saved before items had versions.+ result = await connection.exec_driver_sql("PRAGMA table_info(canvas_items)")+ columns = {row[1] for row in result.fetchall()}+ if columns and "version" not in columns:+ await connection.exec_driver_sql("ALTER TABLE canvas_items ADD COLUMN version INTEGER NOT NULL DEFAULT 1")+ if columns and "updated_at" not in columns:+ await connection.exec_driver_sql("ALTER TABLE canvas_items ADD COLUMN updated_at DATETIME")self._initialized_engines.add(engine)async def append(@@ -184,6 +248,7 @@ class CanvasStore:CanvasItemRow.board_id == board.id))+ await session.execute(delete(CanvasItemVersion).where(CanvasItemVersion.board_id == board.id))next_position = 0else:result = await session.execute(@@ -212,6 +277,7 @@ class CanvasStore:position=next_position + offset,)session.add(row)+ session.add(_version_row(row))added.append(row)# FIFO eviction: keep the newest CANVAS_MAX_ITEMS by position.@@ -237,6 +303,7 @@ class CanvasStore:CanvasItemRow.id.in_(evicted_ids)))+ await session.execute(delete(CanvasItemVersion).where(CanvasItemVersion.item_id.in_(evicted_ids)))total = CANVAS_MAX_ITEMSboard.revision += 1@@ -277,6 +344,7 @@ class CanvasStore:if row is None:raise CanvasStoreError(f"No canvas item with id '{item_id}'")await session.delete(row)+ await session.execute(delete(CanvasItemVersion).where(CanvasItemVersion.item_id == row.id))board.revision += 1board.updated_at = _utcnow()session.add(board)@@ -292,6 +360,7 @@ class CanvasStore:result = await session.execute(delete(CanvasItemRow).where(CanvasItemRow.board_id == board.id))+ await session.execute(delete(CanvasItemVersion).where(CanvasItemVersion.board_id == board.id))board.revision += 1board.updated_at = _utcnow()session.add(board)@@ -301,6 +370,106 @@ class CanvasStore:"revision": board.revision,}+ async def update(self, scope: CanvasScope, item_id: str, item: Dict[str, Any]) -> tuple[Dict[str, Any], int]:+ """Make ``item`` the next version of the board's item ``item_id``+ (same kind). Returns ``(wire_item, revision)``."""+ await self.ensure_schema()+ if item.get("kind") not in CANVAS_ITEM_KINDS:+ raise CanvasStoreError(f"Unknown canvas item kind: {item.get('kind')!r}")+ async with self.database.get_session() as session:+ board = await self._board(session, scope, create=False)+ row = await self._item(session, board, item_id)+ if row.kind != item["kind"]:+ raise CanvasStoreError(f"Item '{item_id}' is a {row.kind}; update it with a {row.kind} too")+ content = item.get("content")+ if isinstance(content, str):+ content, _ = truncate_note(content)+ row.title = item.get("title") or row.title+ row.ref = item.get("ref")+ row.url = item.get("url")+ row.content = content+ row.language = item.get("language")+ row.source = str(item.get("source") or row.source)+ row.version = int(row.version or 1) + 1+ row.updated_at = _utcnow()+ session.add(row)+ session.add(_version_row(row))+ await session.flush()+ # Keep the newest CANVAS_MAX_VERSIONS.+ old = await session.execute(+ select(CanvasItemVersion.id)+ .where(CanvasItemVersion.item_id == row.id)+ .order_by(CanvasItemVersion.version.desc())+ .offset(CANVAS_MAX_VERSIONS)+ )+ dropped = [value for (value,) in old.all()]+ if dropped:+ await session.execute(delete(CanvasItemVersion).where(CanvasItemVersion.id.in_(dropped)))+ board.revision += 1+ board.updated_at = _utcnow()+ session.add(board)+ await session.commit()+ return _serialize(row), board.revision++ async def versions(self, scope: CanvasScope, item_id: str) -> Dict[str, Any]:+ """An item's versions, newest first: ``{versions: [{version, title,+ created_at, source, size_bytes}], latest}``."""+ await self.ensure_schema()+ async with self.database.get_session() as session:+ board = await self._board(session, scope, create=False)+ row = await self._item(session, board, item_id)+ result = await session.execute(+ select(CanvasItemVersion).where(CanvasItemVersion.item_id == row.id).order_by(CanvasItemVersion.version.desc())+ )+ versions = [+ {+ "version": version.version,+ "title": version.title,+ "created_at": _iso(version.created_at),+ "source": version.source,+ "size_bytes": _version_size(version),+ }+ for version in result.scalars().all()+ ]+ return {"item_id": row.id, "versions": versions, "latest": int(row.version or 1)}++ async def version(self, scope: CanvasScope, item_id: str, version: int) -> Dict[str, Any]:+ """One version of an item, in the CanvasItem wire shape."""+ await self.ensure_schema()+ async with self.database.get_session() as session:+ board = await self._board(session, scope, create=False)+ row = await self._item(session, board, item_id)+ result = await session.execute(+ select(CanvasItemVersion).where(CanvasItemVersion.item_id == row.id, CanvasItemVersion.version == int(version))+ )+ found = result.scalars().first()+ if found is None:+ raise CanvasStoreError(f"Item '{item_id}' has no version {version}")+ return {+ "id": row.id,+ "kind": found.kind,+ "title": found.title,+ "ref": found.ref,+ "url": found.url,+ "content": found.content,+ "language": found.language,+ "source": found.source,+ "created_at": _iso(found.created_at),+ "version": found.version,+ "latest": int(row.version or 1),+ }++ async def _item(self, session: Any, board: Optional[CanvasBoard], item_id: str) -> CanvasItemRow:+ if board is None:+ raise CanvasStoreError("No canvas content for this node")+ result = await session.execute(+ select(CanvasItemRow).where(CanvasItemRow.board_id == board.id, CanvasItemRow.id == str(item_id or "").strip())+ )+ row = result.scalars().first()+ if row is None:+ raise CanvasStoreError(f"No canvas item with id '{item_id}'")+ return row+async def _board(self, session: Any, scope: CanvasScope, *, create: bool) -> Optional[CanvasBoard]:@@ -323,9 +492,11 @@ __all__ = ["CANVAS_ITEM_KINDS","CANVAS_MAX_ITEMS","CANVAS_MAX_PATHS_PER_CALL",+ "CANVAS_MAX_VERSIONS","CANVAS_NOTE_MAX_BYTES","CanvasBoard","CanvasItemRow",+ "CanvasItemVersion","CanvasScope","CanvasStore","CanvasStoreError",diff --git a/server/services/chat/parts.py b/server/services/chat/parts.pyindex 3a2f40cf..04e06bde 100644--- a/server/services/chat/parts.py+++ b/server/services/chat/parts.py@@ -11,12 +11,16 @@ first kind: ``show_ui`` saves the checked spec and publishes it as an emptySources (``services/chat/sources.py``) are the numbered results of a searchthe answering agent ran. Approvals name the drafts it made that wait for theowner (``services/approvals/tool_calls.py``): the card reads them live from-the approvals store, so the part only names them.+the approvals store, so the part only names them. Artifacts name the+documents (Canvas notes) it wrote or revised, at the version it left them+(``show_artifact``, called by the canvas tool): a card that opens the+Canvas on it.When the run ends, ``seal_parts`` copies its parts into the reply message's-``parts`` (``{"ui": [...], "sources": [...], "approvals": [...]}``), creating-an empty reply when the run showed an interface or made a draft but wrote-nothing, so a reload draws what the run showed. Every write here is best effort for the run: a part that cannot be+``parts`` (``{"ui": [...], "sources": [...], "approvals": [...],+"artifacts": [...]}``), creating an empty reply when the run showed an+interface, made a draft or wrote a document but wrote no text, so a reload+draws what the run showed. Every write here is best effort for the run: a part that cannot besaved is logged, and the run goes on."""@@ -38,7 +42,7 @@ logger = get_logger(__name__)#: The ``activity_type`` of a generated UI's events.JSON_RENDER = "json_render"#: The kinds of part a run collects for its reply.-PART_KINDS = ("ui", "sources", "approvals")+PART_KINDS = ("ui", "sources", "approvals", "artifacts")def ui_part_id(run_id: str, tool_call_id: str) -> str:@@ -137,8 +141,24 @@ async def show_approval(database: Any, stream: Mapping[str, Any], *, approval_id)+async def show_artifact(database: Any, stream: Mapping[str, Any], *, artifact: Dict[str, Any]) -> None:+ """Name a document the run wrote on the Canvas (``{workflow_id,+ canvas_node_id, item_id, version, title, format}``) on its reply, and+ show its card live. A newer version of the same item replaces it."""+ item_id = str(artifact.get("item_id") or "")+ if not item_id:+ return+ await record_part(database, stream["run_id"], kind="artifacts", key=f"artifact:{item_id}", payload=dict(artifact))+ _publish(+ stream,+ "activity.snapshot",+ {"message_id": f"artifact_{item_id}", "activity_type": "artifact", "content": dict(artifact), "replace": True},+ f"artifact:{item_id}:{artifact.get('version')}",+ )++#: What names one item of each kind, for merging a run's parts into a reply.-_ITEM_KEYS = {"ui": "part_id", "sources": "n", "approvals": "approval_id"}+_ITEM_KEYS = {"ui": "part_id", "sources": "n", "approvals": "approval_id", "artifacts": "item_id"}def grouped_parts(parts: List[ChatRunPart]) -> Dict[str, List[Dict[str, Any]]]:@@ -157,13 +177,23 @@ def grouped_parts(parts: List[ChatRunPart]) -> Dict[str, List[Dict[str, Any]]]:return dict(grouped)+#: Kinds whose run copy is the newer one: a document's card names the latest+#: version the run wrote, and nothing the owner does changes it.+_RUN_COPY_WINS = frozenset({"artifacts"})++def _merged(kind: str, existing: List[Any], incoming: List[Dict[str, Any]]) -> List[Any]:"""The reply's items of a kind with the run's new ones added. An item thereply already holds stays as it is there: the owner may have changed it- since (an interface's state), and the run's copy is older."""+ since (an interface's state), and the run's copy is older. A document's+ card is the exception: the run's copy names a newer version."""key = _ITEM_KEYS.get(kind)if key is None:return incoming+ if kind in _RUN_COPY_WINS:+ newer = {item.get(key): item for item in incoming}+ kept = [newer.pop(item.get(key), item) if isinstance(item, dict) else item for item in existing]+ return [*kept, *newer.values()]held = {item.get(key) for item in existing if isinstance(item, dict)}return [*existing, *[item for item in incoming if item.get(key) not in held]]@@ -191,7 +221,7 @@ async def seal_parts(database: Any, run: ChatRun) -> bool:else:# Sources show only where a reply cites them: alone they# are no reason to make one.- if not (grouped.get("ui") or grouped.get("approvals")):+ if not (grouped.get("ui") or grouped.get("approvals") or grouped.get("artifacts")):return Falsecurrent = await session.get(ChatRun, run.run_id)stopped = current is not None and current.state in ("stopping", "stopped")@@ -395,6 +425,7 @@ __all__ = ["run_parts","seal_parts","show_approval",+ "show_artifact","show_ui","ui_event_message","ui_part_id",diff --git a/server/tests/nodes/test_canvas_node.py b/server/tests/nodes/test_canvas_node.pyindex 4c19464b..57425582 100644--- a/server/tests/nodes/test_canvas_node.py+++ b/server/tests/nodes/test_canvas_node.py@@ -28,9 +28,12 @@ from nodes.tool.canvas._handlers import (handle_canvas_clear,handle_canvas_list,handle_canvas_remove,+ handle_canvas_version,+ handle_canvas_versions,)from nodes.tool.canvas._store import (CANVAS_NOTE_MAX_BYTES,+ CanvasItemVersion,CanvasScope,CanvasStore,CanvasStoreError,@@ -169,7 +172,118 @@ async def test_item_wire_shape_is_stable(canvas_database):"language","source","created_at",+ "version",+ "updated_at",}+ assert (added[0]["version"], added[0]["updated_at"]) == (1, None)+++# ---------------------------------------------------------------------------+# Versions+# ---------------------------------------------------------------------------+++async def _version_count(database, item_id=None) -> int:+ from sqlalchemy import func, select++ async with database.get_session() as session:+ query = select(func.count()).select_from(CanvasItemVersion)+ if item_id is not None:+ query = query.where(CanvasItemVersion.item_id == item_id)+ return int((await session.execute(query)).scalar() or 0)+++async def test_an_update_is_the_next_version_and_the_earlier_ones_stay(canvas_database):+ store = CanvasStore(canvas_database)+ scope = _scope()+ [first], first_revision, _ = await store.append(scope, [{"kind": "note", "content": "# Plan\none", "title": "Plan"}])+ updated, revision = await store.update(scope, first["id"], {"kind": "note", "content": "# Plan\ntwo", "source": "agent"})+ assert revision == first_revision + 1+ assert (updated["id"], updated["version"], updated["content"], updated["title"]) == (first["id"], 2, "# Plan\ntwo", "Plan")+ assert updated["updated_at"] is not None++ listed = (await store.list(scope))["items"]+ assert [(item["version"], item["content"]) for item in listed] == [(2, "# Plan\ntwo")]+ history = await store.versions(scope, first["id"])+ assert history["latest"] == 2+ assert [(entry["version"], entry["size_bytes"]) for entry in history["versions"]] == [(2, 10), (1, 10)]+ old = await store.version(scope, first["id"], 1)+ assert (old["version"], old["latest"], old["content"]) == (1, 2, "# Plan\none")+ with pytest.raises(CanvasStoreError):+ await store.version(scope, first["id"], 3)+++async def test_an_update_keeps_the_kind_and_needs_the_item(canvas_database):+ store = CanvasStore(canvas_database)+ scope = _scope()+ [note], _, _ = await store.append(scope, [{"kind": "note", "content": "x"}])+ with pytest.raises(CanvasStoreError, match="note"):+ await store.update(scope, note["id"], {"kind": "url", "url": "https://example.com"})+ with pytest.raises(CanvasStoreError):+ await store.update(scope, "missing", {"kind": "note", "content": "y"})+ # Another node's board does not hold it.+ with pytest.raises(CanvasStoreError):+ await store.update(_scope(node_id="other"), note["id"], {"kind": "note", "content": "y"})+++async def test_an_item_keeps_its_newest_versions(canvas_database, monkeypatch):+ monkeypatch.setattr("nodes.tool.canvas._store.CANVAS_MAX_VERSIONS", 3)+ store = CanvasStore(canvas_database)+ scope = _scope()+ [note], _, _ = await store.append(scope, [{"kind": "note", "content": "v1"}])+ for number in range(2, 6):+ await store.update(scope, note["id"], {"kind": "note", "content": f"v{number}"})+ history = await store.versions(scope, note["id"])+ assert [entry["version"] for entry in history["versions"]] == [5, 4, 3]+++async def test_removing_clearing_and_replacing_drop_versions(canvas_database):+ store = CanvasStore(canvas_database)+ scope = _scope()+ [kept, dropped], _, _ = await store.append(scope, [{"kind": "note", "content": "a"}, {"kind": "note", "content": "b"}])+ await store.update(scope, dropped["id"], {"kind": "note", "content": "b2"})+ await store.remove(scope, dropped["id"])+ assert await _version_count(canvas_database, dropped["id"]) == 0+ assert await _version_count(canvas_database, kept["id"]) == 1+ await store.append(scope, [{"kind": "note", "content": "c"}], mode="replace")+ assert await _version_count(canvas_database, kept["id"]) == 0+ await store.clear(scope)+ assert await _version_count(canvas_database) == 0+++async def test_eviction_drops_versions(canvas_database, monkeypatch):+ monkeypatch.setattr("nodes.tool.canvas._store.CANVAS_MAX_ITEMS", 2)+ store = CanvasStore(canvas_database)+ scope = _scope()+ [oldest], _, _ = await store.append(scope, [{"kind": "note", "content": "1"}])+ await store.append(scope, [{"kind": "note", "content": "2"}, {"kind": "note", "content": "3"}])+ assert await _version_count(canvas_database, oldest["id"]) == 0+ assert await _version_count(canvas_database) == 2+++async def test_a_board_saved_before_versions_gets_them(canvas_database):+ store = CanvasStore(canvas_database)+ scope = _scope()+ [note], _, _ = await store.append(scope, [{"kind": "note", "content": "old"}])+ # The table as it was before items had versions.+ async with canvas_database.engine.begin() as connection:+ await connection.exec_driver_sql("ALTER TABLE canvas_items RENAME TO canvas_items_new")+ await connection.exec_driver_sql(+ "CREATE TABLE canvas_items (id VARCHAR(64) PRIMARY KEY, board_id VARCHAR(80), kind VARCHAR(10), "+ "title VARCHAR(300), ref JSON, url VARCHAR(2048), content TEXT, language VARCHAR(40), "+ "source VARCHAR(10), position INTEGER, created_at DATETIME)"+ )+ await connection.exec_driver_sql(+ "INSERT INTO canvas_items SELECT id, board_id, kind, title, ref, url, content, language, source, position, created_at "+ "FROM canvas_items_new"+ )+ await connection.exec_driver_sql("DROP TABLE canvas_items_new")+ CanvasStore._initialized_engines.discard(canvas_database.engine)++ [listed] = (await store.list(scope))["items"]+ assert (listed["id"], listed["version"], listed["updated_at"]) == (note["id"], 1, None)+ updated, _ = await store.update(scope, note["id"], {"kind": "note", "content": "new"})+ assert updated["version"] == 2def test_truncate_note_caps_with_visible_marker():@@ -367,6 +481,66 @@ async def test_display_replace_mode_clears_board(assert "replaced" in result["message"]+async def test_display_update_id_revises_an_item(tmp_path, op_database, captured_events):+ node, ctx = _node(), _ctx(tmp_path)+ first = await node.display(ctx, CanvasParams(content="# Plan\nDraft", title="Plan"))+ item_id = first["added"][0]["id"]+ result = await node.display(ctx, CanvasParams(content="# Plan\nFinal", update_id=item_id))+ assert result["added"] == [{"id": item_id, "kind": "note", "title": "Plan", "version": 2}]+ assert "version 2" in result["message"]+ [item] = (await CanvasStore(op_database).list(CanvasScope(owner_id="owner", workflow_id="wf-op", node_id="canvas-node")))["items"]+ assert (item["version"], item["content"]) == (2, "# Plan\nFinal")+ assert len(captured_events) == 2+++async def test_display_update_id_takes_one_item_of_its_kind(tmp_path, op_database, captured_events):+ node, ctx = _node(), _ctx(tmp_path)+ item_id = (await node.display(ctx, CanvasParams(content="note")))["added"][0]["id"]+ with pytest.raises(NodeUserError, match="one item"):+ await node.display(ctx, CanvasParams(content="x", url="https://example.com", update_id=item_id))+ with pytest.raises(NodeUserError, match="note"):+ await node.display(ctx, CanvasParams(url="https://example.com", update_id=item_id))+ with pytest.raises(NodeUserError):+ await node.display(ctx, CanvasParams(content="x", update_id="missing"))+++def shown_documents(monkeypatch):+ shown = []++ async def _show(database, stream, *, artifact):+ shown.append({"stream": stream, **artifact})++ monkeypatch.setattr("services.chat.parts.show_artifact", _show)+ return shown+++async def test_a_note_the_answering_agent_writes_shows_in_its_reply(tmp_path, op_database, captured_events, shown_documents):+ stream = {"run_id": "r_1", "session_id": "wf-op", "workflow_id": "wf-op"}+ node, ctx = _node(), _ctx(tmp_path, raw={"_tool_config": object(), "chat_stream": stream})+ item_id = (await node.display(ctx, CanvasParams(content="## Weekly report\nAll good.")))["added"][0]["id"]+ await node.display(ctx, CanvasParams(content="## Weekly report\nAll better.", update_id=item_id, language="python"))+ assert shown_documents == [+ {"stream": stream, "workflow_id": "wf-op", "canvas_node_id": "canvas-node", "item_id": item_id, "version": 1, "title": "Weekly report", "format": "markdown"},+ {"stream": stream, "workflow_id": "wf-op", "canvas_node_id": "canvas-node", "item_id": item_id, "version": 2, "title": "Weekly report", "format": "code"},+ ]+++async def test_only_notes_in_a_chat_run_show_in_the_reply(tmp_path, op_database, captured_events, shown_documents):+ (tmp_path / "chart.png").write_bytes(b"\x89PNG fake")+ stream = {"run_id": "r_1", "session_id": "wf-op", "workflow_id": "wf-op"}+ await _node().display(_ctx(tmp_path, raw={"chat_stream": stream}), CanvasParams(paths=["chart.png"], url="https://example.com"))+ await _node().display(_ctx(tmp_path), CanvasParams(content="no run"))+ assert shown_documents == []+++async def test_a_markdown_note_is_a_document_not_code(tmp_path, op_database, captured_events, shown_documents):+ stream = {"run_id": "r_1", "session_id": "wf-op", "workflow_id": "wf-op"}+ ctx = _ctx(tmp_path, raw={"chat_stream": stream})+ await _node().display(ctx, CanvasParams(content="Plain words", language="Markdown"))+ assert [(shown["title"], shown["format"]) for shown in shown_documents] == [("Plain words", "markdown")]++def test_collect_connected_refs_dedupes_and_caps():ref = {"kind": "file", "path": "a/b.png", "filename": "b.png"}payload = {@@ -537,6 +711,26 @@ async def test_handler_round_trip_list_remove_clear(assert final["items"] == []+async def test_handler_reads_versions(canvas_database, handler_env, handler_events):+ handler_env(_graph())+ store = CanvasStore(canvas_database)+ scope = CanvasScope(owner_id="owner", workflow_id="wf-h", node_id="canvas-h")+ [note], _, _ = await store.append(scope, [{"kind": "note", "content": "one"}])+ await store.update(scope, note["id"], {"kind": "note", "content": "two"})+ where = {"workflow_id": "wf-h", "node_id": "canvas-h", "item_id": note["id"]}++ listed = await handle_canvas_versions(where, _FakeSocket())+ assert (listed["success"], listed["latest"], [entry["version"] for entry in listed["versions"]]) == (True, 2, [2, 1])+ first = await handle_canvas_version({**where, "version": 1}, _FakeSocket())+ assert (first["success"], first["item"]["content"], first["item"]["latest"]) == (True, "one", 2)++ assert (await handle_canvas_version({**where, "version": 9}, _FakeSocket()))["success"] is False+ assert (await handle_canvas_version({**where, "version": "1"}, _FakeSocket()))["success"] is False+ assert (await handle_canvas_versions({**where, "item_id": ""}, _FakeSocket()))["success"] is False+ # The same preamble as the other handlers.+ assert (await handle_canvas_versions(where, _FakeSocket(path="/ws/internal")))["success"] is False++# ---------------------------------------------------------------------------# Event + tool-schema contract locks# ---------------------------------------------------------------------------diff --git a/server/tests/services/chat/test_parts.py b/server/tests/services/chat/test_parts.pyindex 3c64c906..616c35d6 100644--- a/server/tests/services/chat/test_parts.py+++ b/server/tests/services/chat/test_parts.py@@ -215,3 +215,51 @@ async def test_the_ui_state_command(chat):assert (await chat.handlers.handle_chat_ui_state({"session_id": "wf", "part_id": "ui_x", "changes": [{"path": "/a", "value": 1}]}, None))["error"] == "not_found"bad = await chat.handlers.handle_chat_ui_state({"session_id": "wf", "part_id": part_id, "changes": "nope"}, None)assert bad["error"] == "invalid_request"+++# ----- documents the run wrote -----+++def document(version=1, item_id="item_1"):+ return {"workflow_id": "wf", "canvas_node_id": "wf:canvas:1", "item_id": item_id, "version": version, "title": "Plan", "format": "markdown"}+++async def test_a_document_the_run_wrote_shows_once_at_its_latest_version(database, hub):+ socket = FakeSocket()+ hub.subscribe(socket, "wf")+ run = await running(database)+ await parts.show_artifact(database, stream_of(run), artifact=document(1))+ await parts.show_artifact(database, stream_of(run), artifact=document(2))+ # One part per document, at the latest version.+ [saved] = await parts.run_parts(database, run.run_id)+ assert (saved.kind, saved.key, saved.payload) == ("artifacts", "artifact:item_1", document(2))+ await asyncio.sleep(0)+ shown = [event["data"] for event in socket.events() if event["type"].endswith("activity.snapshot")]+ assert [(data["activity_type"], data["message_id"], data["content"]["version"]) for data in shown] == [+ ("artifact", "artifact_item_1", 1),+ ("artifact", "artifact_item_1", 2),+ ]+ # A run that wrote nothing but the document gets a reply holding its card.+ finished = await ledger.finish_run(database, run_id=run.run_id, success=True, **CLAIM)+ assert finished.result == {"reply_message_id": run.reply_message_uid}+ [_, reply] = await database.get_chat_messages("wf")+ assert (reply["message"], reply["parts"]["artifacts"]) == ("", [document(2)])+++async def test_a_newer_version_replaces_the_card_on_a_saved_reply(database, hub):+ run = await running(database)+ await parts.show_artifact(database, stream_of(run), artifact=document(1))+ reply = await ledger.post_reply(database, run=run, node_id="n", text="Here is the plan.", execution_id="gen-1")+ assert reply["parts"]["artifacts"] == [document(1)]+ await parts.show_artifact(database, stream_of(run), artifact=document(2))+ await parts.show_artifact(database, stream_of(run), artifact=document(1, item_id="item_2"))+ await ledger.finish_run(database, run_id=run.run_id, success=True, **CLAIM)+ [_, saved] = await database.get_chat_messages("wf")+ # In place, then the new one.+ assert saved["parts"]["artifacts"] == [document(2), document(1, item_id="item_2")]+++async def test_a_document_without_an_item_shows_nothing(database, hub):+ run = await running(database)+ await parts.show_artifact(database, stream_of(run), artifact={**document(), "item_id": ""})+ assert await parts.run_parts(database, run.run_id) == []