Skip to content

Self-improving AI Employees for everyone

4.1 KB
Raw Blame
"""Helpers for the chat run tests."""

from __future__ import annotations

from types import SimpleNamespace
from typing import Any, Dict, List, Optional

from starlette.websockets import WebSocketState

from models.database import WorkflowControlExecution


class FakeSocket:
    """A status socket: records what the hub writes to it."""

    def __init__(self, *, path: str = "/ws/status", user_id: Optional[str] = None) -> None:
        self.scope = {"path": path}
        self.state = SimpleNamespace(user_id=user_id)
        self.client_state = WebSocketState.CONNECTED
        self.application_state = WebSocketState.CONNECTED
        self.sent: List[str] = []

    async def send_text(self, text: str) -> None:
        self.sent.append(text)

    def events(self) -> List[Dict[str, Any]]:
        import json

        return [json.loads(text)["data"] for text in self.sent]


async def saved_workflow(database, workflow_id: str) -> None:
    """The saved workflow a chat session names (chat refuses a session that
    names none). An empty graph, saved only if missing."""
    if await database.get_workflow(workflow_id) is None:
        await database.save_workflow(workflow_id, workflow_id, f"{workflow_id}_1", {"nodes": [], "edges": []})


async def add_control(
    database,
    workflow_id: str,
    status: str,
    *,
    generation: int = 1,
    nodes: Optional[List[Dict[str, Any]]] = None,
):
    """A control generation of a saved workflow, its graph holding ``nodes``."""
    await saved_workflow(database, workflow_id)
    async with database.get_session() as session:
        session.add(
            WorkflowControlExecution(
                id=f"{workflow_id}-{generation}",
                workflow_id=workflow_id,
                generation=generation,
                execution_id=f"gen-{generation}",
                root_execution_id=f"gen-{generation}",
                graph_hash="0" * 64,
                graph_snapshot={"nodes": list(nodes or []), "edges": []},
                status=status,
                idempotency_key=f"k-{generation}",
            )
        )
        await session.commit()


def chat_trigger(workflow_id: str, **data: Any) -> Dict[str, Any]:
    return {"id": f"{workflow_id}:chatTrigger:1", "type": "chatTrigger", "data": {"label": "Chat", **data}}


async def talking(database, workflow_id: str = "wf", status: str = "running", generation: int = 1) -> None:
    """A deployed workflow whose chat trigger answers its own session."""
    await add_control(database, workflow_id, status, generation=generation, nodes=[chat_trigger(workflow_id)])


async def held_call(database, approval_id: str, run_id: str, *, runtime: str = "turn") -> None:
    """A call the run's agent made, held for the owner: one its turn waits
    on (``turn``, RFC-0007), or a draft."""
    from models.approvals import ApprovalRequest

    async with database.get_session() as session:
        session.add(
            ApprovalRequest(
                id=approval_id,
                idempotency_key=f"k-{approval_id}",
                owner_id="owner",
                workflow_id="wf",
                node_id="wf:whatsappSend:1",
                kind="tool_call",
                channel="WhatsApp",
                action="WhatsApp message",
                recipient="447700900123",
                runtime=runtime,
                run_id=run_id,
                draft_text="On my way",
            )
        )
        await session.commit()


def chat_updates(frames) -> List[Dict[str, Any]]:
    return [frame["data"]["data"] for frame in frames if frame["type"] == "chat.updated"]


def updates_at_dispatch(chat, monkeypatch) -> List[int]:
    """How many ``chat.updated`` frames had gone out as each message was
    dispatched (the ``chat`` fixture's dispatch still records it)."""
    seen: List[int] = []
    dispatch = chat.handlers.dispatch_chat_message_received

    async def recording(event_data, **kwargs):
        seen.append(len(chat_updates(chat.frames)))
        await dispatch(event_data, **kwargs)

    monkeypatch.setattr(chat.handlers, "dispatch_chat_message_received", recording)
    return seen