Skip to content

The platform for continuously improving AI agents.

18.6 KB
Raw Blame
from unittest.mock import patch

import pytest
from django.db import connections
from fakes.responses_api import ResponsesAPI, response
from mcp_fixtures import call_tool, mcp_context
from rest_framework.test import APIClient

from overbae.models import Cell, Dataset
from overbae.services.datasets import land
from overbae.services.datasets.lifecycle import DatasetError
from overbae.services.workshop_agent import agent, conversation, lifecycle, model_stream
from overbae.services.workshop_agent.contracts import ControlMessage, SendMessage, StartTask

pytestmark = [pytest.mark.django_db, pytest.mark.covers("work-once")]


@pytest.fixture(autouse=True)
def wakes():
    with patch("overbae.tasks.research.dispatch_wakes.delay"):
        yield


def task_fixture():
    grant = mcp_context(["read", "write"])
    dataset = Dataset.objects.create(project=grant.project, name="Conversation")
    task = lifecycle.start(
        grant, StartTask(dataset=dataset.pk, objective="Inspect the data", request_key="initial")
    )
    return grant, task


def transcript(turn=0, **fields):
    """A task's saved state at ``turn``, as its loop holds it."""
    return {
        "turn": turn,
        "items": [{"role": "user", "content": "Inspect values"}],
        "publications": [],
        "events": [],
        "accepted": [],
        **fields,
    }


def test_followup_is_idempotent_delivered_once_and_keeps_cell_context():
    grant, task = task_fixture()
    cell = Cell.objects.create(
        dataset=task.dataset, position=0, title="Source", state="ok", rows=3, fingerprint="a" * 64
    )
    body = dict(
        dataset=str(task.dataset_id),
        text="Why are these values missing?",
        cell=str(cell.pk),
        request_key="followup",
    )
    first = call_tool("send_workshop_message", body, grant)
    assert not first.isError, first
    assert conversation.send(grant, SendMessage(**body)).pk == task.pk
    incoming = conversation.inbox(task)
    assert len(incoming) == 1 and incoming[0]["cells"][0]["id"] == str(cell.pk)
    with pytest.raises(DatasetError, match="conflicts"):
        conversation.send(grant, SendMessage(**{**body, "text": "Change the data"}))
    conversation.accept(task, incoming[0]["id"])
    replay = conversation.page(grant.project, task.dataset_id)
    assert replay["events"][-1]["message"]["status"] == "completed"
    assert conversation.page(grant.project, task.dataset_id, replay["cursor"])["events"] == []


@pytest.mark.covers("tenancy")
def test_history_and_followup_cannot_cross_projects():
    grant, task = task_fixture()
    other = mcp_context(["read", "write"])
    client = APIClient()
    client.force_authenticate(other.user, other.token)
    assert (
        client.get(
            "/api/workshop-tasks/history/",
            {"project": str(other.project.pk), "dataset": str(task.dataset_id)},
        ).status_code
        == 404
    )
    response = client.post(
        "/api/workshop-tasks/messages/",
        {
            "project": str(other.project.pk),
            "dataset": str(task.dataset_id),
            "text": "Show data",
            "request_key": "foreign",
        },
        format="json",
    )
    assert response.status_code == 400
    assert conversation.page(other.project, task.dataset_id)["events"] == []


def test_followup_at_completion_is_not_lost_and_the_next_request_is_a_new_task():
    grant, task = task_fixture()
    conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="Explain the result", request_key="late")
    )
    state = transcript(1)
    # The reply does not answer a message it never read: the task goes on.
    assert agent.settle(task, state, "completed", "The values were inspected.") is None
    task.refresh_from_db()
    assert task.state == "queued"
    for message in conversation.inbox(task):
        state["accepted"].append(message["id"])
        conversation.accept(task, message["id"])
    assert agent.settle(task, state, "completed", "The values were inspected.")["state"] == (
        "completed"
    )
    task.refresh_from_db()
    continuation = conversation.send(
        grant,
        SendMessage(dataset=task.dataset_id, text="What about duplicates?", request_key="next"),
    )
    assert continuation.pk != task.pk
    assert any(
        message["text"] == "Explain the result" for message in conversation.history(continuation)
    )


def test_cancellation_marks_unread_followups_undelivered_and_excludes_them_from_new_tasks():
    grant, task = task_fixture()
    conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="Remove duplicates", request_key="unread")
    )
    lifecycle.control(grant.project, task.pk, "cancel")
    agent.settle(task, transcript(), "cancelled", "", final=True)
    messages = conversation.page(grant.project, task.dataset_id)["events"]
    assert messages[-1]["message"]["status"] == "cancelled"
    continuation = conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="Inspect only", request_key="next")
    )
    assert not any(
        message["text"] == "Remove duplicates" for message in conversation.history(continuation)
    )


@pytest.mark.parametrize("command,outcome", [("cancel", "cancelled"), ("pause", "paused")])
def test_control_after_model_response_wins_over_completion(command, outcome):
    grant, task = task_fixture()
    lifecycle.control(grant.project, task.pk, command)
    result = agent.settle(task, transcript(1), "completed", "Inspected the data.")
    task.refresh_from_db()
    assert result["state"] == task.state == outcome
    assert task.preparation.state == outcome


def test_queued_edits_are_idempotent_and_delivery_freezes_the_last_revision():
    grant, task = task_fixture()
    conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="Keep 10 rows", request_key="queued")
    )
    payload = ControlMessage(
        task=task.pk,
        message="user:queued",
        command="edit",
        text="Keep all rows",
        revision=0,
        request_key="edit",
    )
    edited = conversation.control_message(grant, payload)
    assert edited["revision"] == 1
    assert conversation.control_message(grant, payload) == edited
    with pytest.raises(DatasetError, match="changed"):
        conversation.control_message(grant, payload.model_copy(update={"request_key": "stale"}))
    lifecycle.control(grant.project, task.pk, "pause")
    assert conversation.claim_inbox(task) == []
    lifecycle.control(grant.project, task.pk, "resume")
    delivered = conversation.claim_inbox(task)
    assert [item["text"] for item in delivered] == ["Keep all rows"]
    with pytest.raises(DatasetError, match="no longer"):
        conversation.control_message(
            grant, payload.model_copy(update={"revision": 1, "request_key": "late"})
        )
    assert conversation.claim_inbox(task) == delivered
    conversation.accept(task, delivered[0]["id"])
    assert (
        conversation.page(grant.project, task.dataset_id)["events"][-1]["message"]["text"]
        == "Keep all rows"
    )


@pytest.mark.covers("tenancy")
def test_queued_removal_is_project_scoped_and_never_reaches_the_agent():
    grant, task = task_fixture()
    conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="Remove rows", request_key="queued")
    )
    body = dict(
        task=str(task.pk), message="user:queued", command="remove", revision=0, request_key="remove"
    )
    assert call_tool("control_workshop_message", body, mcp_context(["read", "write"])).isError
    assert not call_tool("control_workshop_message", body, grant).isError
    assert not call_tool("control_workshop_message", body, grant).isError
    assert conversation.claim_inbox(task) == []


@pytest.mark.django_db(transaction=True)
def test_stop_during_silent_provider_stream_retains_interruption_without_replaying(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")

    def cancel(socket, request):
        try:
            lifecycle.control(grant.project, task.pk, "cancel")
        finally:
            connections.close_all()

    with (
        ResponsesAPI(cancel) as api,
        model_stream.ModelStream(url=api.url, api_key="test") as model,
    ):
        with pytest.raises(agent.StoppedError):
            agent.reason(task, transcript(), model)
        with pytest.raises(DatasetError, match="not running"):
            agent.reason(task, transcript(), model)
        assert len(api.requests) == 1
    assert (
        conversation.page(grant.project, task.dataset_id)["events"][-1]["message"]["status"]
        == "interrupted"
    )
    with pytest.raises(DatasetError, match="cancellation"):
        lifecycle.control(grant.project, task.pk, "resume")


def test_provider_stream_retains_public_text_and_complete_tool_call_without_private_reasoning(
    monkeypatch,
):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    answer = response()
    with (
        ResponsesAPI(answer) as api,
        model_stream.ModelStream(url=api.url, api_key="test") as model,
    ):
        result = agent.reason(task, transcript(), model)
        assert result["status"] == 200, result
        assert result["body"]["output"][-1]["arguments"] == '{"code": "print(3)"}'
        assert agent.reason(task, transcript(), model) == result
        assert len(api.requests) == 1
    events = conversation.page(grant.project, task.dataset_id)["events"]
    assert events[-1]["message"]["text"] == "Inspecting the values."
    assert "Private provider reasoning" not in str(events)
    preparing = [event for event in events if event["message"].get("tool") == "python"]
    assert preparing and preparing[0]["id"] < events[-1]["id"]
    assert preparing[-1]["message"]["status"] == "preparing"
    assert preparing[-1]["message"]["code"] == "print(3)"
    assert {event["message"]["id"] for event in preparing} == {"action:0"}


def test_provider_reasoning_summary_is_shown_as_thinking_and_kept_out_of_later_tasks(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    thoughts = ["**Checking values**\n\nAge has blanks.", "**Choosing a check**\n\nCount them."]
    with (
        ResponsesAPI(response(summary=thoughts)) as api,
        model_stream.ModelStream(url=api.url, api_key="test") as model,
    ):
        assert agent.reason(task, transcript(), model)["status"] == 200
        assert api.requests[0]["reasoning"]["summary"] == "auto"
    events = conversation.page(grant.project, task.dataset_id)["events"]
    thinking = [event for event in events if event["message"]["role"] == "thinking"]
    assert thinking[-1]["message"]["text"] == "\n\n".join(thoughts)
    assert thinking[-1]["message"]["status"] == "completed"
    answer = next(event for event in events if event["message"]["id"] == "model:0")
    assert thinking[0]["id"] < answer["id"]
    assert "opaque-reasoning" not in str(events)
    agent.settle(task, transcript(1), "completed", "The values were inspected.")
    task.refresh_from_db()
    continuation = conversation.send(
        grant, SendMessage(dataset=task.dataset_id, text="What about duplicates?", request_key="n")
    )
    assert continuation.pk != task.pk
    assert "Checking values" not in str(conversation.history(continuation))


def lose_stream(socket, request):
    socket({"type": "response.created", "response": {"id": "resp_lost"}})
    raise ConnectionResetError("stream lost")


def test_lost_provider_stream_is_sent_again_and_leaves_usage_unknown(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    answer = response()
    with (
        ResponsesAPI(lose_stream, answer) as api,
        model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
    ):
        result = agent.reason(task, transcript(), model)
        assert result["status"] == 200 and result["body"] == answer, result
        assert len(api.requests) == 2 and api.requests[0] == api.requests[1]
    events = conversation.page(grant.project, task.dataset_id)["events"]
    assert events[-1]["message"] == {
        "id": "model:0",
        "role": "assistant",
        "text": "Inspecting the values.",
        "status": "completed",
    }
    # The lost attempt may have been billed: the task's usage is no longer a measured fact.
    assert lifecycle.describe(task)["used_tokens"] is None


def test_request_the_provider_refuses_for_now_is_sent_again_with_usage_known(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    answer = response()
    with (
        ResponsesAPI(503, 429, answer) as api,
        model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
    ):
        assert agent.reason(task, transcript(), model)["body"] == answer
        assert len(api.requests) == 3
    task.refresh_from_db()
    assert lifecycle.describe(task)["used_tokens"] == answer["usage"]["total_tokens"]


def test_unanswered_request_ends_unknown_after_bounded_attempts(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    with (
        ResponsesAPI(*[lose_stream] * model_stream.ATTEMPTS, response()) as api,
        model_stream.ModelStream(url=api.url, api_key="test", waits=(0,)) as model,
    ):
        assert agent.reason(task, transcript(), model) == {"unknown": True}
        assert agent.reason(task, transcript(), model)["unknown"]
        assert len(api.requests) == model_stream.ATTEMPTS
    assert (
        conversation.page(grant.project, task.dataset_id)["events"][-1]["message"]["status"]
        == "interrupted"
    )


def test_request_left_in_flight_by_a_failed_worker_is_sent_again(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    answer = response()

    def malformed(socket, request):
        socket({"type": "response.output_item.added"})
        raise ConnectionResetError("stream lost")

    with (
        ResponsesAPI(malformed, answer) as api,
        model_stream.ModelStream(url=api.url, api_key="test") as model,
    ):
        # The worker fails while its request is with the provider.
        with pytest.raises(KeyError):
            agent.reason(task, transcript(), model)
        lifecycle.control(grant.project, task.pk, "pause")
        lifecycle.control(grant.project, task.pk, "resume")
        assert agent.reason(task, transcript(), model)["body"] == answer
        assert len(api.requests) == 2
    assert lifecycle.describe(task)["used_tokens"] is None


def test_a_replacement_worker_sends_the_full_context_it_retained(monkeypatch):
    grant, task = task_fixture()
    monkeypatch.setenv("WORKSHOP_AGENT_MODEL", "test")
    answers = [response() for _ in range(4)]
    items = [{"role": "user", "content": "Inspect values"}]
    with ResponsesAPI(*answers) as api:
        with model_stream.ModelStream(url=api.url, api_key="test") as model:
            for turn in range(3):
                result = agent.reason(task, transcript(turn, items=list(items)), model)
                assert result["body"] == answers[turn]
                items.extend(answers[turn]["output"])
                items.append(
                    {
                        "type": "function_call_output",
                        "call_id": answers[turn]["output"][-1]["call_id"],
                        "output": "3",
                    }
                )
            assert len(api.requests[1]["input"]) > 1
            assert all("previous_response_id" not in r for r in api.requests)
        # A replacement worker sends complete context, including provider-only fields.
        for item in items:
            item.pop("phase", None)
            for content in item.get("content", []) if isinstance(item.get("content"), list) else []:
                content.pop("logprobs", None)
        with model_stream.ModelStream(url=api.url, api_key="test") as model:
            agent.reason(task, transcript(3, items=list(items)), model)
            assert "previous_response_id" not in api.requests[3]
            assert api.requests[3]["input"][2]["phase"] == "commentary"
            assert api.requests[3]["input"][2]["content"][0]["logprobs"] == []
            assert api.requests[3]["input"][1]["encrypted_content"] == "opaque-reasoning"
        assert all(r["service_tier"] == "default" and r["store"] is False for r in api.requests)


def test_a_version_attached_to_a_message_is_frozen_and_listed_once_for_the_sandbox():
    grant, task = task_fixture()
    land.land_rows(task.dataset, [{"value": 7}])
    task.dataset.refresh_from_db()
    selected = task.dataset.active_cell
    for key in ("inspect", "again"):
        conversation.send(
            grant,
            SendMessage(
                dataset=task.dataset_id, cell=selected.pk, text="Inspect this cell", request_key=key
            ),
        )
    selected.refresh_from_db()
    assert selected.used_at is not None
    [attached] = conversation.chat_cells(task)
    assert attached["path"] == f"/workspace/inputs/chat-cells/{selected.pk}.parquet"
    assert attached["fingerprint"] == selected.fingerprint


def test_queue_order_survives_replay_and_claim_prevents_late_reordering():
    grant, task = task_fixture()
    for key in ("first", "second", "third"):
        conversation.send(grant, SendMessage(dataset=task.dataset_id, text=key, request_key=key))
    move = ControlMessage(
        task=task.pk,
        message="user:third",
        command="move",
        position=0,
        revision=0,
        request_key="move-third",
    )
    conversation.control_message(grant, move)
    conversation.control_message(grant, move)
    assert [item["text"] for item in conversation.inbox(task)] == ["third", "first", "second"]
    claimed = conversation.claim_inbox(task)
    assert [item["text"] for item in claimed] == ["third", "first", "second"]
    with pytest.raises(DatasetError, match="no longer"):
        conversation.control_message(
            grant, move.model_copy(update={"revision": 1, "request_key": "late-move"})
        )


def test_cancel_between_model_completion_and_execution_settles_preparing_tools():
    grant, task = task_fixture()
    conversation.emit(
        task,
        "draft",
        {
            "id": "action:0",
            "role": "activity",
            "status": "preparing",
            "tool": "python",
            "text": "Inspect values",
            "code": "print(3)",
        },
    )
    cursor = conversation.page(grant.project, task.dataset_id)["cursor"]
    conversation.settle(task, "cancelled", [])
    events = conversation.page(grant.project, task.dataset_id, after=cursor)["events"]
    assert events[-1]["message"]["id"] == "action:0"
    assert events[-1]["message"]["status"] == "interrupted"
    conversation.settle(task, "cancelled", [])
    assert conversation.page(grant.project, task.dataset_id, after=cursor)["events"] == events