Skip to content

Enterprise agent platform for building, deploying, and operating AI teammates.

161 KB
Raw Blame
"""Integration tests for agent management endpoints."""

import asyncio
import base64
import io
import json
import secrets
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, cast

import pytest
from sqlalchemy import event
from sqlalchemy.exc import IntegrityError

from xagent.config import get_uploads_dir
from xagent.core.execution_scope import (
    EXECUTION_SCOPE_AGENT_CONFIG_KEY,
    execution_scope_from_agent_config,
)
from xagent.web import jwt_codec as jwt
from xagent.web.api import agents as agents_api
from xagent.web.api.public_chat_access import (
    create_public_chat_access_token,
    create_public_file_ticket,
)
from xagent.web.api.widget import (
    EMBED_TICKET_TYPE,
    WIDGET_CREDENTIAL_REQUIRED_DETAIL,
    WIDGET_KEY_REQUIRED_DETAIL,
)
from xagent.web.auth_config import JWT_ALGORITHM, JWT_SECRET_KEY
from xagent.web.models.agent import Agent, AgentOrigin, AgentStatus
from xagent.web.models.agent_api_key import AgentApiKey
from xagent.web.models.task import Task, TaskStatus
from xagent.web.models.template_stats import TemplateStats
from xagent.web.models.uploaded_file import UploadedFile
from xagent.web.models.user import User
from xagent.web.models.workforce import Workforce, WorkforceAgent, WorkforceRun
from xagent.web.services import agent_prompt as _agent_prompt_services
from xagent.web.services.agent_management import (
    AgentManagementService,
    AgentWorkforceConflictError,
    AgentWorkforceReference,
    TemplateQuickAccessRaceError,
)
from xagent.web.services.task_runtime import (
    SELECTED_FILE_IDS_AGENT_CONFIG_KEY,
    TASK_RUNTIME_BINDINGS_AGENT_CONFIG_KEY,
    task_extension_bindings_from_agent_config,
)
from xagent.web.services.task_setup_snapshot import RuntimeUserFields
from xagent.web.services.workforce_access import WorkforcePolicy, set_workforce_policy
from xagent.web.services.workforce_lifecycle import discard_draft_workforce

from .conftest import (
    _admin_headers,
    _direct_db_session,
    _install_one_slot_queue_pool,
    _register_second_user,
    _share_guest_id,
    client,
)

pytestmark = pytest.mark.usefixtures("_test_db")


@pytest.fixture(autouse=True)
def _reset_workforce_policy() -> None:
    set_workforce_policy(WorkforcePolicy())
    yield
    set_workforce_policy(WorkforcePolicy())


def test_delete_agent_uses_sync_route_boundary() -> None:
    delete_route = next(
        route
        for route in agents_api.router.routes
        if route.path == "/api/agents/{agent_id}" and "DELETE" in route.methods
    )

    assert not asyncio.iscoroutinefunction(delete_route.endpoint)


def _create_agent(headers: dict[str, str], name: str = "Test Agent") -> int:
    resp = client.post(
        "/api/agents",
        headers=headers,
        json={
            "name": name,
            "description": "test",
            "instructions": "You are a test agent.",
            "execution_mode": "balanced",
        },
    )
    assert resp.status_code == 200, resp.text
    return resp.json()["id"]


def test_create_from_template_releases_request_session_before_async_runtime(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """The legacy wrapper must enter template I/O with no request pool slot held."""

    headers = _admin_headers()
    engine = _install_one_slot_queue_pool(monkeypatch)
    checked_out_during_template_load: list[int] = []

    class TemplateManagerStub:
        async def get_template(self, template_id: str) -> dict[str, Any]:
            checked_out_during_template_load.append(engine.pool.checkedout())
            return {
                "id": template_id,
                "name": "Detached legacy template",
                "descriptions": {"en": "Created through the shared runtime"},
                "agent_config": {
                    "instructions": "Use the worker-owned management runtime.",
                    "execution_mode": "balanced",
                },
            }

    monkeypatch.setattr(
        client.app.state,
        "template_manager",
        TemplateManagerStub(),
        raising=False,
    )

    try:
        response = client.post(
            "/api/agents/from-template",
            headers=headers,
            json={"template_id": "detached-legacy-template"},
        )
        assert response.status_code == 200, response.text
        assert checked_out_during_template_load == [0]
        assert response.json()["name"] == "Detached legacy template"
        assert response.json()["visibility"] == "team"
    finally:
        engine.dispose()


def test_create_from_template_fails_closed_when_request_session_is_not_clean(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """The legacy wrapper must not cross an await with pending request DB state."""

    headers = _admin_headers()
    template_calls: list[str] = []

    class TemplateManagerStub:
        async def get_template(self, template_id: str) -> dict[str, Any]:
            template_calls.append(template_id)
            return {}

    monkeypatch.setattr(
        client.app.state,
        "template_manager",
        TemplateManagerStub(),
        raising=False,
    )
    monkeypatch.setattr(
        agents_api,
        "release_db_connection_if_clean",
        lambda _db: False,
    )

    response = client.post(
        "/api/agents/from-template",
        headers=headers,
        json={"template_id": "must-not-load"},
    )

    assert response.status_code == 500
    assert response.json()["detail"] == (
        "Agent creation requires a clean request database transaction"
    )
    assert template_calls == []


def test_create_from_template_persists_template_id(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """The created (and later listed) agent must carry its source template id."""

    headers = _admin_headers()

    class TemplateManagerStub:
        async def get_template(self, template_id: str) -> dict[str, Any]:
            return {
                "id": template_id,
                "name": "Template-Linked Agent",
                "descriptions": {"en": "Created from a template"},
                "agent_config": {
                    "instructions": "Follow the template.",
                    "execution_mode": "balanced",
                },
            }

    monkeypatch.setattr(
        client.app.state, "template_manager", TemplateManagerStub(), raising=False
    )

    response = client.post(
        "/api/agents/from-template",
        headers=headers,
        json={"template_id": "linked-template-id"},
    )
    assert response.status_code == 200, response.text
    agent_id = response.json()["id"]
    assert response.json()["template_id"] == "linked-template-id"

    list_response = client.get("/api/agents", headers=headers)
    assert list_response.status_code == 200, list_response.text
    listed = next(a for a in list_response.json() if a["id"] == agent_id)
    assert listed["template_id"] == "linked-template-id"

    detail_response = client.get(f"/api/agents/{agent_id}", headers=headers)
    assert detail_response.status_code == 200, detail_response.text
    assert detail_response.json()["template_id"] == "linked-template-id"


def test_create_from_template_duplicate_name_returns_400_with_stable_detail(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Pins the exact 400 detail string POST /api/agents/from-template
    returns on a name collision - a different endpoint's exception handling
    from the plain POST /api/agents duplicate-name test above. See PR review
    finding F2: without this test, a refactor could change this endpoint's
    exception mapping while every other test (DB-pool release, the
    clean-transaction 500 guard, template_id persistence) stayed green.

    Note: template-agent-resolution.ts (the frontend's create-or-reuse
    flow) does not itself branch on this string - it only checks
    response.ok and surfaces the HTTP status. This test's value is the
    stable API contract, not a cross-stack string dependency.
    """

    headers = _admin_headers()

    class TemplateManagerStub:
        async def get_template(self, template_id: str) -> dict[str, Any]:
            return {
                "id": template_id,
                "name": "Duplicate Name Agent",
                "descriptions": {"en": "Created from a template"},
                "agent_config": {
                    "instructions": "Follow the template.",
                    "execution_mode": "balanced",
                },
            }

    monkeypatch.setattr(
        client.app.state, "template_manager", TemplateManagerStub(), raising=False
    )

    first_response = client.post(
        "/api/agents/from-template",
        headers=headers,
        json={"template_id": "dup-name-template"},
    )
    assert first_response.status_code == 200, first_response.text

    second_response = client.post(
        "/api/agents/from-template",
        headers=headers,
        json={"template_id": "dup-name-template-2"},
    )
    assert second_response.status_code == 400
    assert second_response.json()["detail"] == "Agent with this name already exists"


class _ResolveTemplateManagerStub:
    """Minimal template manager for the resolve-flow tests."""

    def __init__(self, name: str = "Resolve Flow Agent") -> None:
        self.name = name

    async def get_template(self, template_id: str) -> dict[str, Any]:
        return {
            "id": template_id,
            "name": self.name,
            "descriptions": {"en": "Created by the resolve flow"},
            "agent_config": {
                "instructions": "Follow the template.",
                "execution_mode": "balanced",
            },
        }


def _install_resolve_template_stub(
    monkeypatch: pytest.MonkeyPatch, name: str = "Resolve Flow Agent"
) -> None:
    monkeypatch.setattr(
        client.app.state,
        "template_manager",
        _ResolveTemplateManagerStub(name),
        raising=False,
    )


class _MalformedCapabilitiesTemplateManagerStub(_ResolveTemplateManagerStub):
    """A template whose authored tool_categories/skills contain a
    non-string element (e.g. an authoring typo) - agent_management.py's
    _spec_from_template must filter these out rather than let them reach
    AgentResponse's strict list[str] fields as an unhandled Pydantic
    ValidationError."""

    async def get_template(self, template_id: str) -> dict[str, Any]:
        template = await super().get_template(template_id)
        template["agent_config"]["tool_categories"] = [123, "web_search", None]
        template["agent_config"]["skills"] = ["real_skill", {"bad": "shape"}]
        return template


def test_resolve_from_template_creates_and_publishes_on_first_use(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    response = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )

    assert response.status_code == 200, response.text
    body = response.json()
    assert body["created"] is True
    assert body["agent"]["template_id"] == "resolve-template"
    assert body["agent"]["status"] == "published"
    assert body["agent"]["name"] == "Resolve Flow Agent"


def test_resolve_from_template_reuses_the_same_agent_on_repeat_calls(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """The whole point of the resolve endpoint (PR review D1): repeat sends
    must converge on one agent per (user, template), enforced server-side
    rather than by client-side reconciliation."""

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    first = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert first.status_code == 200, first.text

    second = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert second.status_code == 200, second.text
    assert second.json()["created"] is False
    assert second.json()["agent"]["id"] == first.json()["agent"]["id"]

    listed = client.get("/api/agents", headers=headers).json()
    matching = [a for a in listed if a.get("template_id") == "resolve-template"]
    assert len(matching) == 1


def test_resolve_from_template_drops_non_string_capability_elements(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """A malformed tool_categories/skills entry in the template's authored
    agent_config must not 500 the resolve endpoint - it must be filtered
    out, the same way get_agent_capability_lists filters it for the
    marketplace list/detail endpoints."""
    headers = _admin_headers()
    monkeypatch.setattr(
        client.app.state,
        "template_manager",
        _MalformedCapabilitiesTemplateManagerStub(),
        raising=False,
    )

    response = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "malformed-capabilities-template"},
    )

    assert response.status_code == 200, response.text
    body = response.json()["agent"]
    assert body["tool_categories"] == ["web_search"]
    assert body["skills"] == ["real_skill"]


def test_resolve_from_template_increments_used_count_only_on_the_fresh_mint(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Hire is the primary adoption path for every currently-featured
    template, and the Featured section's hero ranking sorts by used_count -
    a resolve call that mints a fresh agent must record a use, exactly once,
    not on every repeat/idempotent call."""
    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    def used_count() -> int:
        db = _direct_db_session()
        try:
            stats = (
                db.query(TemplateStats)
                .filter(TemplateStats.template_id == "resolve-template")
                .first()
            )
            return stats.used_count if stats else 0
        finally:
            db.close()

    first = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert first.status_code == 200, first.text
    assert first.json()["created"] is True
    assert used_count() == 1

    second = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert second.status_code == 200, second.text
    assert second.json()["created"] is False
    assert used_count() == 1


def test_resolve_from_template_does_not_adopt_a_workforce_builder_draft(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding B4: the plain POST
    /from-template (workforce-builder UI, one-off named creates) writes
    template_id but not the quick-access origin marker. The resolve flow's
    reuse query must not adopt (and publish) that unrelated draft - it has
    to mint its own separate quick-access agent instead."""
    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    created = client.post(
        "/api/agents/from-template",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert created.status_code == 200, created.text
    assert created.json()["status"] == "draft"

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 200, resolved.text
    assert resolved.json()["created"] is True
    assert resolved.json()["agent"]["id"] != created.json()["id"]
    assert resolved.json()["agent"]["status"] == "published"

    # The workforce-builder draft is untouched - still its own draft.
    workforce_draft = client.get(f"/api/agents/{created.json()['id']}", headers=headers)
    assert workforce_draft.status_code == 200, workforce_draft.text
    assert workforce_draft.json()["status"] == "draft"


def test_resolve_from_template_does_not_republish_a_deliberate_unpublish(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding B3: status/published_at alone
    can't distinguish "never published yet" from "the user explicitly
    unpublished it" - both are status=draft, published_at=None. Resolve must
    not silently flip a deliberate unpublish back to published on a later,
    unrelated call."""
    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    first = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert first.status_code == 200, first.text
    assert first.json()["agent"]["status"] == "published"
    agent_id = first.json()["agent"]["id"]

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text
    assert unpublished.json()["agent"]["status"] == "draft"

    second = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert second.status_code == 200, second.text
    assert second.json()["created"] is False
    assert second.json()["agent"]["id"] == agent_id
    assert second.json()["agent"]["status"] == "draft"


def test_resolve_from_template_never_touches_another_users_agent(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding F1: resolving a template must
    only ever consider the caller's own agents - another user's draft from
    the same template stays untouched (not reused, not published)."""

    _install_resolve_template_stub(monkeypatch)

    # Bootstrap the admin (first user) before the public register endpoint
    # will accept a second account.
    headers = _admin_headers()

    other_headers = _register_second_user(username="resolveother")
    other_draft = client.post(
        "/api/agents/from-template",
        headers=other_headers,
        json={"template_id": "resolve-template"},
    )
    assert other_draft.status_code == 200, other_draft.text
    other_agent_id = other_draft.json()["id"]
    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 200, resolved.text
    assert resolved.json()["created"] is True
    assert resolved.json()["agent"]["id"] != other_agent_id
    assert resolved.json()["agent"]["status"] == "published"

    other_view = client.get(f"/api/agents/{other_agent_id}", headers=other_headers)
    assert other_view.status_code == 200, other_view.text
    assert other_view.json()["status"] == "draft"


def test_resolve_from_template_disambiguates_a_colliding_default_name(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """An unrelated agent already holding the template's default name must
    not fail the resolve - the server picks a free name itself instead of
    surfacing the duplicate-name 400 the plain create path returns."""

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)
    _create_agent(headers, name="Resolve Flow Agent")

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 200, resolved.text
    body = resolved.json()
    assert body["created"] is True
    assert body["agent"]["name"] != "Resolve Flow Agent"
    assert body["agent"]["name"].startswith("Resolve Flow Agent")
    assert body["agent"]["status"] == "published"


def test_resolve_from_template_converges_when_a_racing_insert_wins_the_same_name(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding F3: if a concurrent request
    creates this template's agent between our select and our insert, the
    retry loop must re-select and reuse that row instead of erroring or
    minting a duplicate. Here the racing insert collides on name too, which
    is caught by the (user_id, name) unique index alone - see the sibling
    test below for the interleaving where names do *not* collide (B1/B2)."""

    from xagent.web.services import agent_management as management_module
    from xagent.web.services.agent_store import AgentStore

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    real_resolve_name = management_module.resolve_unique_agent_name
    racing_agent_id: dict[str, int] = {}

    def race_then_delegate(db: Any, *, user_id: int, name: str) -> str:
        # Simulate a concurrent request winning the race: insert this
        # template's agent (as the same user) after resolve's select missed
        # but before its own insert, then hand back the template's default
        # name so the insert collides on the unique index.
        if not racing_agent_id:
            store = AgentStore(db)
            racing = store.create_agent(
                user_id=user_id,
                name=name,
                description="raced in first",
                instructions="Follow the template.",
                execution_mode="balanced",
                template_id="resolve-template",
                origin=AgentOrigin.TEMPLATE_QUICK_ACCESS.value,
            )
            db.commit()
            racing_agent_id["id"] = int(racing.id)
            return name
        return real_resolve_name(db, user_id=user_id, name=name)

    monkeypatch.setattr(
        management_module, "resolve_unique_agent_name", race_then_delegate
    )

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 200, resolved.text
    assert resolved.json()["created"] is False
    assert resolved.json()["agent"]["id"] == racing_agent_id["id"]


def test_resolve_from_template_converges_when_a_racing_insert_wins_a_different_name(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding B2: the realistic interleaving
    is a racing insert that takes its *own* disambiguated name - no
    (user_id, name) collision at all - which the plain name-collision retry
    from the sibling test above can't catch (it never fires, so the old
    code's retry loop never re-selected, and two rows ended up sharing one
    template_id with different names, both reporting created=True).
    Convergence here depends entirely on
    AGENT_TEMPLATE_QUICK_ACCESS_UNIQUE_INDEX - the (user_id, template_id)
    partial unique index scoped to the quick-access origin (B1/D2/D3)."""

    from xagent.web.services import agent_management as management_module
    from xagent.web.services.agent_store import AgentStore

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    real_resolve_name = management_module.resolve_unique_agent_name
    racing_agent_id: dict[str, int] = {}

    def race_then_delegate(db: Any, *, user_id: int, name: str) -> str:
        # Simulate a concurrent request winning the race between our SELECT
        # and our INSERT - but, unlike the sibling test above, under a
        # disambiguated name that never collides with our own. Only the
        # first call (the "our own" resolve's own resolve_unique_agent_name
        # lookup) triggers the race; the racing insert's own internal
        # resolve_unique_agent_name call must not recurse into this hook.
        if not racing_agent_id:
            store = AgentStore(db)
            racing = store.create_agent(
                user_id=user_id,
                name="Totally Unrelated Name",
                description="raced in first, under a name that never collides",
                instructions="Follow the template.",
                execution_mode="balanced",
                template_id="resolve-template",
                origin=AgentOrigin.TEMPLATE_QUICK_ACCESS.value,
                status=AgentStatus.PUBLISHED,
            )
            db.commit()
            racing_agent_id["id"] = int(racing.id)
            # Our own insert proceeds under its natural, undisambiguated
            # name - no name collision occurs at all.
            return name
        return real_resolve_name(db, user_id=user_id, name=name)

    monkeypatch.setattr(
        management_module, "resolve_unique_agent_name", race_then_delegate
    )

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 200, resolved.text
    assert resolved.json()["created"] is False
    assert resolved.json()["agent"]["id"] == racing_agent_id["id"]
    assert resolved.json()["agent"]["name"] == "Totally Unrelated Name"


def test_resolve_from_template_reports_409_when_retries_are_exhausted_by_race(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """When every TEMPLATE_RESOLVE_RACE_RETRIES attempt loses the
    (user_id, template_id) quick-access race, the error must say so
    honestly - not the name-collision 400, since no name collision is
    involved at all in this failure mode."""
    from xagent.web.services import agent_management as management_module

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    def always_races(*args: Any, **kwargs: Any) -> Any:
        raise TemplateQuickAccessRaceError("resolve-template")

    monkeypatch.setattr(
        management_module.AgentManagementService,
        "create_agent_with_optional_key",
        always_races,
    )

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 409, resolved.text
    assert "name" not in resolved.json()["detail"].lower()


def test_resolve_from_template_reports_409_when_a_race_hit_precedes_final_name_collision(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding m6: retry exhaustion must
    report the quick-access race (409) whenever *any* attempt hit it, even
    if the *last* attempt's collision happened to be a plain name collision
    instead. Before this fix, only the last error's type was tracked, so
    this exact interleaving (race, then name-collision, then name-collision)
    surfaced a misleading 400 "Agent with this name already exists" - which
    is wrong, since the caller never even chose a colliding name."""
    from xagent.web.services import agent_management as management_module

    headers = _admin_headers()
    _install_resolve_template_stub(monkeypatch)

    attempts = {"n": 0}

    def race_then_name_collisions(*args: Any, **kwargs: Any) -> Any:
        attempts["n"] += 1
        if attempts["n"] == 1:
            raise TemplateQuickAccessRaceError("resolve-template")
        raise management_module.DuplicateAgentNameError("Resolve Flow Agent")

    monkeypatch.setattr(
        management_module.AgentManagementService,
        "create_agent_with_optional_key",
        race_then_name_collisions,
    )

    resolved = client.post(
        "/api/agents/from-template/resolve",
        headers=headers,
        json={"template_id": "resolve-template"},
    )
    assert resolved.status_code == 409, resolved.text
    assert "name" not in resolved.json()["detail"].lower()


def test_manually_created_agent_has_no_template_id() -> None:
    headers = _admin_headers()
    agent_id = _create_agent(headers, name="Hand-built agent")

    response = client.get(f"/api/agents/{agent_id}", headers=headers)
    assert response.status_code == 200, response.text
    assert response.json()["template_id"] is None


def test_duplicate_agent_name_returns_400_with_stable_detail() -> None:
    """Pins the exact 400 detail string POST /api/agents returns on a name
    collision, so a refactor of this endpoint's exception mapping doesn't
    silently change the API contract."""

    headers = _admin_headers()
    _create_agent(headers, name="Duplicate Name Agent")

    response = client.post(
        "/api/agents",
        headers=headers,
        json={
            "name": "Duplicate Name Agent",
            "description": "test",
            "instructions": "You are a test agent.",
            "execution_mode": "balanced",
        },
    )
    assert response.status_code == 400
    assert response.json()["detail"] == "Agent with this name already exists"


def test_db_constraint_catches_name_race_the_app_precheck_missed(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Simulates two concurrent requests both passing the app-level
    pre-check before either commits: the DB partial unique index must still
    reject the second insert with a clean DuplicateAgentNameError (400), not
    a raw IntegrityError (500).
    """
    from xagent.web.services.agent_store import AgentStore

    headers = _admin_headers()
    monkeypatch.setattr(AgentStore, "agent_name_exists", lambda self, *a, **k: False)

    first = client.post(
        "/api/agents",
        headers=headers,
        json={
            "name": "Raced Agent Name",
            "description": "test",
            "instructions": "You are a test agent.",
            "execution_mode": "balanced",
        },
    )
    assert first.status_code == 200, first.text

    second = client.post(
        "/api/agents",
        headers=headers,
        json={
            "name": "Raced Agent Name",
            "description": "test",
            "instructions": "You are a test agent.",
            "execution_mode": "balanced",
        },
    )
    assert second.status_code == 400, second.text
    assert second.json()["detail"] == "Agent with this name already exists"


def test_update_agent_translates_a_raced_rename_collision_to_400(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """Regression test for PR review finding R1-1: update_agent's
    agent_name_exists precheck is a fast path, not the source of truth,
    exactly like create_agent's - so a rename that races past it must still
    surface the DB's uq_agents_user_id_name_active violation as a clean 400,
    not an uncaught IntegrityError leaking as a 500 (update_agent had no
    equivalent to create_agent's `except IntegrityError` handler)."""
    from xagent.web.services.agent_store import AgentStore

    headers = _admin_headers()
    _create_agent(headers, name="Rename Race Target")
    renamed_id = _create_agent(headers, name="Rename Race Source")

    monkeypatch.setattr(AgentStore, "agent_name_exists", lambda self, *a, **k: False)

    response = client.put(
        f"/api/agents/{renamed_id}",
        headers=headers,
        json={"name": "Rename Race Target"},
    )
    assert response.status_code == 400, response.text
    assert response.json()["detail"] == "Agent with this name already exists"


def _create_agent_row(
    *,
    user_id: int,
    name: str,
    status: AgentStatus = AgentStatus.DRAFT,
    origin: str = AgentOrigin.USER.value,
    widget_enabled: bool = True,
    allowed_domains: list[str] | None = None,
    share_enabled: bool = False,
    share_token: str | None = None,
    widget_key: str | None = None,
    generate_widget_key: bool = True,
    suggested_prompts: list[str] | None = None,
) -> int:
    db = _direct_db_session()
    try:
        if widget_key is None and widget_enabled and generate_widget_key:
            widget_key = f"wk-{secrets.token_urlsafe(24)}"
        agent = Agent(
            user_id=user_id,
            name=name,
            description=f"{name} description",
            instructions=f"{name} instructions",
            execution_mode="balanced",
            origin=origin,
            status=status,
            widget_enabled=widget_enabled,
            allowed_domains=allowed_domains or [],
            share_enabled=share_enabled,
            share_token=share_token,
            widget_key=widget_key,
            suggested_prompts=suggested_prompts or [],
        )
        db.add(agent)
        db.commit()
        db.refresh(agent)
        return int(agent.id)
    finally:
        db.close()


def _widget_key_for(agent_id: int) -> str:
    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).first()
        assert agent is not None and agent.widget_key
        return str(agent.widget_key)
    finally:
        db.close()


def _set_agent_status(agent_id: int, status: AgentStatus) -> None:
    """Write a status straight to the row.

    Only needed for ``ARCHIVED``: no web API route assigns it, so the
    ``!= PUBLISHED`` shape of the widget gates cannot be exercised through the
    real ``/unpublish`` endpoint, which hardcodes ``DRAFT``.
    """
    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        agent.status = status
        db.commit()
    finally:
        db.close()


def _user_id(username: str) -> int:
    db = _direct_db_session()
    try:
        user = db.query(User).filter(User.username == username).first()
        assert user is not None
        return int(user.id)
    finally:
        db.close()


def _authenticate_share_guest(
    share_token: str,
) -> dict[str, str]:
    response = client.post(
        "/api/share/auth",
        json={"share_token": share_token},
    )
    assert response.status_code == 200, response.text
    access_token = response.json()["access_token"]
    return {"Authorization": f"Bearer {access_token}"}


def _authenticate_widget_guest(
    *,
    agent_id: int,
    guest_id: str = "guest-1",
    origin: str = "https://example.com",
) -> dict[str, str]:
    # Authenticate via the direct-visit widget-key flow, which needs no
    # embedding origin. The origin arg is accepted for call-site compatibility
    # but no longer gates auth.
    del origin
    response = client.post(
        "/api/widget/auth",
        json={"widget_key": _widget_key_for(agent_id), "guest_id": guest_id},
    )
    assert response.status_code == 200, response.text
    access_token = response.json()["access_token"]
    return {"Authorization": f"Bearer {access_token}"}


def _create_public_task_file(
    *,
    owner_id: int,
    agent_id: int,
    guest_id: str,
    filename: str = "shared-note.txt",
    content: bytes = b"hello from public task",
) -> str:
    uploads_root = get_uploads_dir() / f"user_{owner_id}"
    uploads_root.mkdir(parents=True, exist_ok=True)
    file_path = uploads_root / filename
    file_path.write_bytes(content)

    db = _direct_db_session()
    try:
        task = Task(
            user_id=owner_id,
            title="Public task",
            description="Public task",
            status=TaskStatus.PENDING,
            agent_id=agent_id,
            channel_id=None,
            channel_name="Shared Agent",
            agent_config={
                "auth_mode": "share",
                "share_agent_id": agent_id,
                # Per-guest isolation (#973): the task must carry the accessing
                # guest's id or get_task_for_share_context rejects it.
                "guest_id": guest_id,
            },
        )
        db.add(task)
        db.commit()
        db.refresh(task)

        uploaded_file = UploadedFile(
            user_id=owner_id,
            task_id=int(task.id),
            filename=filename,
            storage_path=str(file_path),
            mime_type="text/plain",
            file_size=len(content),
        )
        db.add(uploaded_file)
        db.commit()
        db.refresh(uploaded_file)
        return str(uploaded_file.file_id)
    finally:
        db.close()


class _VisibleAgentPolicy(WorkforcePolicy):
    def __init__(self, visible_agent_ids: set[int]) -> None:
        self.visible_agent_ids = visible_agent_ids

    def get_visible_agent_ids(
        self,
        db: Any,
        user: User,
        purpose: str,
    ) -> set[int]:
        del db, user, purpose
        return self.visible_agent_ids


def test_list_agents_includes_owned_agents_and_policy_visible_agents() -> None:
    _admin_headers()
    bob_headers = _register_second_user()
    admin_id = _user_id("admin")
    bob_id = _user_id("bob")

    bob_draft_id = _create_agent_row(user_id=bob_id, name="Bob Draft")
    bob_published_id = _create_agent_row(
        user_id=bob_id,
        name="Bob Published",
        status=AgentStatus.PUBLISHED,
    )
    shared_published_id = _create_agent_row(
        user_id=admin_id,
        name="Shared Published",
        status=AgentStatus.PUBLISHED,
    )
    shared_draft_id = _create_agent_row(
        user_id=admin_id,
        name="Shared Draft",
        status=AgentStatus.DRAFT,
    )
    set_workforce_policy(_VisibleAgentPolicy({shared_published_id, shared_draft_id}))

    response = client.get("/api/agents", headers=bob_headers)
    assert response.status_code == 200, response.text
    items_by_id = {item["id"]: item for item in response.json()}

    assert {
        bob_draft_id,
        bob_published_id,
        shared_published_id,
        shared_draft_id,
    }.issubset(items_by_id)

    assert items_by_id[bob_draft_id]["access"] == "owner"
    assert items_by_id[bob_draft_id]["readonly"] is False
    assert items_by_id[bob_draft_id]["can_edit"] is True
    assert items_by_id[bob_draft_id]["can_publish"] is True
    assert items_by_id[bob_draft_id]["can_delete"] is True

    assert items_by_id[shared_published_id]["access"] == "policy"
    assert items_by_id[shared_published_id]["readonly"] is True
    assert items_by_id[shared_published_id]["can_edit"] is False
    assert items_by_id[shared_published_id]["can_publish"] is False
    assert items_by_id[shared_published_id]["can_delete"] is False
    assert items_by_id[shared_draft_id]["access"] == "policy"
    assert items_by_id[shared_draft_id]["status"] == "draft"
    assert items_by_id[shared_draft_id]["readonly"] is True


def test_list_agents_search_preserves_access_scope() -> None:
    _admin_headers()
    headers = _register_second_user()
    bob_id = _user_id("bob")
    admin_id = _user_id("admin")
    owned_id = _create_agent_row(user_id=bob_id, name="Needle owned")
    shared_id = _create_agent_row(user_id=admin_id, name="Needle shared")
    _create_agent_row(user_id=admin_id, name="Needle private")
    _create_agent_row(user_id=bob_id, name="Unrelated")
    description_id = _create_agent_row(user_id=bob_id, name="Description match")
    db = _direct_db_session()
    try:
        db.get(Agent, description_id).description = "Handles needle requests"
        db.commit()
    finally:
        db.close()
    set_workforce_policy(_VisibleAgentPolicy({shared_id}))

    response = client.get(
        "/api/agents", params={"search": "  NEEDLE  "}, headers=headers
    )
    assert response.status_code == 200, response.text
    assert {item["id"] for item in response.json()} == {
        owned_id,
        shared_id,
        description_id,
    }
    empty = client.get("/api/agents", params={"search": "%"}, headers=headers)
    assert empty.status_code == 200
    assert empty.json() == []


def test_list_agents_paginated_admin_defaults_to_mine_and_pages_other_users(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    headers = _admin_headers()
    _register_second_user()
    admin_id = _user_id("admin")
    bob_id = _user_id("bob")

    mine_id = _create_agent_row(user_id=admin_id, name="Mine")
    newest_other_id = _create_agent_row(
        user_id=bob_id,
        name="Zulu other",
        status=AgentStatus.PUBLISHED,
    )
    older_other_id = _create_agent_row(user_id=bob_id, name="Alpha other")

    def fail_full_list(*_args: Any, **_kwargs: Any) -> None:
        raise AssertionError("paginated requests must not load the full Agent list")

    monkeypatch.setattr(
        agents_api,
        "list_accessible_agents",
        fail_full_list,
    )

    mine = client.get(
        "/api/agents",
        params={"page": 1, "size": 1},
        headers=headers,
    )
    assert mine.status_code == 200, mine.text
    mine_page = mine.json()
    assert mine_page["ownership"] == "mine"
    assert mine_page["can_view_others"] is True
    assert mine_page["visible_total"] == 3
    assert mine_page["total"] == 1
    assert [item["id"] for item in mine_page["items"]] == [mine_id]
    assert mine_page["status_counts"] == {"all": 1, "enabled": 0, "drafts": 1}

    others = client.get(
        "/api/agents",
        params={
            "page": 1,
            "size": 1,
            "ownership": "others",
            "sort": "name",
        },
        headers=headers,
    )
    assert others.status_code == 200, others.text
    other_page = others.json()
    assert other_page["ownership"] == "others"
    assert other_page["total"] == 2
    assert other_page["pages"] == 2
    assert [item["id"] for item in other_page["items"]] == [older_other_id]

    enabled = client.get(
        "/api/agents",
        params={
            "page": 1,
            "size": 12,
            "ownership": "others",
            "status": "enabled",
        },
        headers=headers,
    )
    assert enabled.status_code == 200, enabled.text
    assert [item["id"] for item in enabled.json()["items"]] == [newest_other_id]


def test_list_agents_paginated_literal_search_and_non_admin_others_guard() -> None:
    _admin_headers()
    headers = _register_second_user()
    bob_id = _user_id("bob")
    _create_agent_row(user_id=bob_id, name="100% literal")
    _create_agent_row(user_id=bob_id, name="100 wildcard")

    response = client.get(
        "/api/agents",
        params={"page": 1, "search": "%"},
        headers=headers,
    )
    assert response.status_code == 200, response.text
    assert [item["name"] for item in response.json()["items"]] == ["100% literal"]
    assert response.json()["can_view_others"] is False

    forbidden = client.get(
        "/api/agents",
        params={"page": 1, "ownership": "others"},
        headers=headers,
    )
    assert forbidden.status_code == 403


def test_list_agents_paginated_non_admin_preserves_access_scope() -> None:
    _admin_headers()
    headers = _register_second_user()
    admin_id = _user_id("admin")
    bob_id = _user_id("bob")

    owned_id = _create_agent_row(user_id=bob_id, name="Owned")
    shared_id = _create_agent_row(user_id=admin_id, name="Policy visible")
    _create_agent_row(user_id=admin_id, name="Private")
    admins_only_id = _create_agent_row(user_id=admin_id, name="Admins only")
    db = _direct_db_session()
    try:
        admins_only = db.get(Agent, admins_only_id)
        assert admins_only is not None
        admins_only.visibility = "admins"
        db.commit()
    finally:
        db.close()
    set_workforce_policy(_VisibleAgentPolicy({shared_id, admins_only_id}))

    response = client.get(
        "/api/agents",
        params={"page": 1, "size": 12},
        headers=headers,
    )
    assert response.status_code == 200, response.text
    page = response.json()
    assert page["visible_total"] == 2
    assert page["total"] == 2
    assert page["ownership"] == "all"
    assert {item["id"] for item in page["items"]} == {owned_id, shared_id}
    items_by_id = {item["id"]: item for item in page["items"]}
    assert items_by_id[owned_id]["access"] == "owner"
    assert items_by_id[shared_id]["access"] == "policy"


def test_list_agents_paginated_team_admin_can_switch_to_other_creators(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    from xagent.web.services import agent_team_scope as scope_module
    from xagent.web.services.agent_team_scope import AgentTeamScope

    _admin_headers()
    headers = _register_second_user()
    admin_id = _user_id("admin")
    bob_id = _user_id("bob")
    team_id = 77
    mine_id = _create_agent_row(user_id=bob_id, name="Team admin's agent")
    other_id = _create_agent_row(user_id=admin_id, name="Team member's agent")
    db = _direct_db_session()
    try:
        db.query(Agent).filter(Agent.id.in_([mine_id, other_id])).update(
            {Agent.team_id: team_id}, synchronize_session=False
        )
        db.commit()
    finally:
        db.close()

    monkeypatch.setattr(
        scope_module,
        "_agent_team_scope_hook",
        lambda _db, user_id: (
            AgentTeamScope(team_id=team_id, is_team_admin=True)
            if user_id == bob_id
            else None
        ),
    )

    mine = client.get(
        "/api/agents",
        params={"page": 1, "ownership": "auto"},
        headers=headers,
    )
    assert mine.status_code == 200, mine.text
    assert mine.json()["can_view_others"] is True
    assert [item["id"] for item in mine.json()["items"]] == [mine_id]

    others = client.get(
        "/api/agents",
        params={"page": 1, "ownership": "others"},
        headers=headers,
    )
    assert others.status_code == 200, others.text
    assert [item["id"] for item in others.json()["items"]] == [other_id]


def test_list_agents_response_carries_suggested_prompts_through_owner_and_policy_rows() -> (
    None
):
    # tests/web/test_agent_visibility.py only exercises
    # AgentStore.agent_to_list_item_dict directly - this drives the real
    # GET /api/agents route so a future regression in AgentListItem's
    # response-model validation or the permission-merge step in
    # _serialize_agent_list_item would actually be caught here, not just
    # at the store layer the /task "My Team" picker's auto-fill depends on.
    _admin_headers()
    bob_headers = _register_second_user()
    admin_id = _user_id("admin")
    bob_id = _user_id("bob")

    bob_with_prompts_id = _create_agent_row(
        user_id=bob_id,
        name="Bob With Prompts",
        status=AgentStatus.PUBLISHED,
        suggested_prompts=["Draft a status update"],
    )
    bob_without_prompts_id = _create_agent_row(
        user_id=bob_id,
        name="Bob Without Prompts",
        status=AgentStatus.PUBLISHED,
    )
    shared_with_prompts_id = _create_agent_row(
        user_id=admin_id,
        name="Shared With Prompts",
        status=AgentStatus.PUBLISHED,
        suggested_prompts=["Summarize today's meetings"],
    )
    set_workforce_policy(_VisibleAgentPolicy({shared_with_prompts_id}))

    response = client.get("/api/agents", headers=bob_headers)
    assert response.status_code == 200, response.text
    items_by_id = {item["id"]: item for item in response.json()}

    assert items_by_id[bob_with_prompts_id]["suggested_prompts"] == [
        "Draft a status update"
    ]
    assert items_by_id[bob_without_prompts_id]["suggested_prompts"] == []
    assert items_by_id[shared_with_prompts_id]["suggested_prompts"] == [
        "Summarize today's meetings"
    ]


def test_agent_lists_keep_reusable_managers_and_hide_generated_managers() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    reusable_manager_id = _create_agent_row(
        user_id=owner_id,
        name="Reusable Manager",
        status=AgentStatus.PUBLISHED,
    )
    generated_manager_id = _create_agent_row(
        user_id=owner_id,
        name="Generated Manager",
        status=AgentStatus.PUBLISHED,
        origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
    )
    worker_id = _create_agent_row(
        user_id=owner_id,
        name="Reusable Worker",
        status=AgentStatus.PUBLISHED,
    )

    db = _direct_db_session()
    try:
        workforce = Workforce(
            owner_user_id=owner_id,
            scope_type="user",
            scope_id=str(owner_id),
            name="Reusable Manager Workforce",
            manager_agent_id=reusable_manager_id,
            status="draft",
        )
        db.add(workforce)
        db.commit()
    finally:
        db.close()

    response = client.get("/api/agents", headers=headers)
    assert response.status_code == 200, response.text
    agent_ids = {item["id"] for item in response.json()}
    assert reusable_manager_id in agent_ids
    assert generated_manager_id not in agent_ids
    assert worker_id in agent_ids

    options_response = client.get("/api/workforces/agent-options", headers=headers)
    assert options_response.status_code == 200, options_response.text
    option_ids = {item["id"] for item in options_response.json()}
    assert reusable_manager_id in option_ids
    assert generated_manager_id not in option_ids
    assert worker_id in option_ids


def test_agent_name_conflicts_ignore_generated_workforce_managers() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    generated_name = "Generated Manager Name"
    generated_manager_id = _create_agent_row(
        user_id=owner_id,
        name=generated_name,
        status=AgentStatus.PUBLISHED,
        origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
    )

    create_response = client.post(
        "/api/agents",
        headers=headers,
        json={
            "name": generated_name,
            "description": "Reusable agent",
            "instructions": "You are reusable.",
            "execution_mode": "balanced",
        },
    )

    assert create_response.status_code == 200, create_response.text
    created_agent_id = create_response.json()["id"]
    assert created_agent_id != generated_manager_id

    update_target_id = _create_agent_row(user_id=owner_id, name="Update Target")
    hidden_update_name = "Hidden Update Manager Name"
    _create_agent_row(
        user_id=owner_id,
        name=hidden_update_name,
        status=AgentStatus.PUBLISHED,
        origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
    )

    update_response = client.put(
        f"/api/agents/{update_target_id}",
        headers=headers,
        json={"name": hidden_update_name},
    )

    assert update_response.status_code == 200, update_response.text
    assert update_response.json()["name"] == hidden_update_name


def test_generated_workforce_manager_agents_cannot_authenticate_widget() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    generated_manager_id = _create_agent_row(
        user_id=owner_id,
        name="Generated Widget Manager",
        status=AgentStatus.PUBLISHED,
        origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
        widget_enabled=True,
        allowed_domains=["*"],
    )

    response = client.post(
        "/api/widget/auth",
        json={
            "widget_key": _widget_key_for(generated_manager_id),
            "guest_id": "guest-1",
        },
    )

    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid widget key"


def test_embed_ticket_origin_matches_allowed_domains_case_insensitively() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Case Insensitive Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["Example.com"],
    )

    response = _issue_embed_ticket(agent_id, "https://EXAMPLE.com")

    assert response.status_code == 200, response.text


def _issue_embed_ticket(
    agent_id: int, origin: str, widget_key: str | None = None
) -> Any:
    return client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": widget_key or _widget_key_for(agent_id)},
        headers={"origin": origin},
    )


def test_widget_embed_ticket_flow_validates_embedding_origin() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Embed Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    # widget.js requests the ticket from the top-level embedding page, so
    # the browser-enforced Origin header carries the real embedding site.
    ticket_response = _issue_embed_ticket(agent_id, "https://trusted-site.com")
    assert ticket_response.status_code == 200, ticket_response.text
    ticket = ticket_response.json()["ticket"]

    # The backend signs the validated embedding origin into the ticket, not
    # a caller-supplied value.
    ticket_claims = jwt.decode(ticket, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    assert ticket_claims["type"] == EMBED_TICKET_TYPE
    assert ticket_claims["embed_origin"] == "trusted-site.com"

    # The auth fetch runs inside the iframe: its Origin is the xagent host,
    # which is NOT in allowed_domains — the ticket alone must carry trust.
    auth_response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
        headers={"origin": "https://xagent-host.example"},
    )
    assert auth_response.status_code == 200, auth_response.text


def test_widget_embed_ticket_rejected_for_disallowed_origin() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Embed Ticket Rejection Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = _issue_embed_ticket(agent_id, "https://evil-attacker.com")

    assert response.status_code == 403
    assert response.json()["detail"] == "Domain not allowed: evil-attacker.com"


def test_widget_embed_ticket_rejects_malformed_persisted_agent_allowlist(
    caplog: pytest.LogCaptureFixture,
) -> None:
    caplog.set_level("WARNING", logger="xagent.web.services.widget_domains")
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Malformed Allowlist Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        cast(Any, agent).allowed_domains = {
            "do-not-log-this-policy-value.example": True
        }
        db.commit()
    finally:
        db.close()

    response = _issue_embed_ticket(agent_id, "https://trusted-site.com")

    assert response.status_code == 403
    assert response.json()["detail"] == "Domain not allowed: trusted-site.com"
    assert (
        "Rejected malformed widget allowed-domains policy: "
        f"owner_type=agent owner_id={agent_id} reason=not_list"
    ) in caplog.text
    assert "do-not-log-this-policy-value.example" not in caplog.text


def test_embed_ticket_requires_valid_widget_key_despite_spoofed_origin() -> None:
    """#742 (embed-ticket path): a forged allowlisted Origin is worthless
    without the unguessable per-agent widget key."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Key Gated Embed Ticket Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    ok = _issue_embed_ticket(agent_id, "https://trusted-site.com")
    assert ok.status_code == 200, ok.text
    assert ok.json()["agent_id"] == agent_id

    forged = client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": "wk-not-the-real-key"},
        headers={"origin": "https://trusted-site.com"},
    )
    assert forged.status_code == 403
    assert forged.json()["detail"] == "Invalid widget key"


def test_embed_ticket_rejects_numeric_agent_id_without_key() -> None:
    """The enumerable numeric agent_id can no longer obtain a ticket, and a
    key-less (legacy) request gets an actionable 403 rather than a bare 422."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Agent Id Only Embed Ticket Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = client.post(
        "/api/widget/embed-ticket",
        json={"agent_id": agent_id},
        headers={"origin": "https://trusted-site.com"},
    )
    assert response.status_code == 403
    assert response.json()["detail"] == WIDGET_KEY_REQUIRED_DETAIL


def test_embed_ticket_rejects_stale_key_after_rotation() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Rotated Key Embed Ticket Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    old_key = _widget_key_for(agent_id)

    rotate = client.post(f"/api/agents/{agent_id}/widget-key/rotate", headers=headers)
    assert rotate.status_code == 200, rotate.text
    new_key = rotate.json()["widget_key"]
    assert new_key != old_key

    stale = client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": old_key},
        headers={"origin": "https://trusted-site.com"},
    )
    assert stale.status_code == 403
    assert stale.json()["detail"] == "Invalid widget key"

    fresh = _issue_embed_ticket(
        agent_id, "https://trusted-site.com", widget_key=new_key
    )
    assert fresh.status_code == 200, fresh.text


def test_embed_ticket_rejects_disabled_widget_like_an_unknown_key() -> None:
    """Disabled-widget and unknown-key both return the same 403 so callers
    cannot tell agents apart."""
    _admin_headers()
    owner_id = _user_id("admin")
    _create_agent_row(
        user_id=owner_id,
        name="Disabled Widget Embed Ticket Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=False,
        allowed_domains=["trusted-site.com"],
        widget_key="wk-disabled-agent-key",
        generate_widget_key=False,
    )

    response = client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": "wk-disabled-agent-key"},
        headers={"origin": "https://trusted-site.com"},
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid widget key"


def test_widget_auth_rejects_spoofed_origin_without_credential() -> None:
    """#742 reproduction: a spoofed allowlisted Origin header plus an
    enumerable agent_id, with no ticket and no widget key, authenticates
    nothing now that the bare-header fallback is removed."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Spoofed Origin Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1"},
        headers={"origin": "https://trusted-site.com"},
    )

    assert response.status_code == 403
    assert response.json()["detail"] == WIDGET_CREDENTIAL_REQUIRED_DETAIL


def test_widget_auth_ignores_client_supplied_embed_origin() -> None:
    """A client self-reporting an allowed origin in the body (the pre-ticket
    design's flaw) still gets nothing without a verifiable credential."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Self Reported Origin Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = client.post(
        "/api/widget/auth",
        json={
            "agent_id": agent_id,
            "guest_id": "guest-1",
            "embed_origin": "https://trusted-site.com",
        },
        headers={"origin": "https://evil-attacker.com"},
    )

    assert response.status_code == 403
    assert response.json()["detail"] == WIDGET_CREDENTIAL_REQUIRED_DETAIL


def test_widget_auth_with_no_origin_and_no_credential_is_rejected() -> None:
    """The absent-Origin row from #742's table: still 403 with no credential."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="No Origin Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1"},
    )

    assert response.status_code == 403


def test_widget_auth_direct_visit_with_widget_key_succeeds() -> None:
    """Direct (non-embedded) visits authenticate with the widget key alone;
    no origin allowlist applies because a direct visit is not embedded."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Direct Visit Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    widget_key = _widget_key_for(agent_id)

    response = client.post(
        "/api/widget/auth",
        json={"widget_key": widget_key, "guest_id": "guest-1"},
    )
    assert response.status_code == 200, response.text
    assert response.json()["agent_id"] == agent_id

    stale = client.post(
        "/api/widget/auth",
        json={"widget_key": "wk-not-a-real-key", "guest_id": "guest-1"},
    )
    assert stale.status_code == 403
    assert stale.json()["detail"] == "Invalid widget key"


def test_widget_auth_rejects_tampered_or_mismatched_ticket() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Tampered Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    other_agent_id = _create_agent_row(
        user_id=owner_id,
        name="Other Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    # Garbage ticket: fails signature verification.
    response = client.post(
        "/api/widget/auth",
        json={
            "agent_id": agent_id,
            "guest_id": "guest-1",
            "embed_ticket": "not-a-real-ticket",
        },
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid or expired embed ticket"

    # A ticket authenticates only as the agent it was issued for; a spoofed
    # agent_id in the body cannot redirect it to another agent.
    other_ticket = _issue_embed_ticket(
        other_agent_id, "https://trusted-site.com"
    ).json()["ticket"]
    response = client.post(
        "/api/widget/auth",
        json={
            "agent_id": agent_id,
            "guest_id": "guest-1",
            "embed_ticket": other_ticket,
        },
    )
    assert response.status_code == 200, response.text
    assert response.json()["agent_id"] == other_agent_id


def test_widget_auth_rejects_expired_embed_ticket() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Expired Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    expired_ticket = jwt.encode(
        {
            "type": EMBED_TICKET_TYPE,
            "agent_id": agent_id,
            "embed_origin": "trusted-site.com",
            "exp": datetime.now(timezone.utc) - timedelta(seconds=1),
        },
        JWT_SECRET_KEY,
        algorithm=JWT_ALGORITHM,
    )

    response = client.post(
        "/api/widget/auth",
        json={
            "agent_id": agent_id,
            "guest_id": "guest-1",
            "embed_ticket": expired_ticket,
        },
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid or expired embed ticket"


def test_widget_auth_rejects_valid_signed_token_of_wrong_type() -> None:
    """All token classes share one signing key, so the type claim is the only
    thing separating them. A validly-signed guest access token with the right
    agent_id must not be replayable as an embed ticket."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Wrong Type Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    wrong_type_ticket = jwt.encode(
        {
            "type": "widget",
            "agent_id": agent_id,
            "embed_origin": "trusted-site.com",
            "exp": datetime.now(timezone.utc) + timedelta(minutes=5),
        },
        JWT_SECRET_KEY,
        algorithm=JWT_ALGORITHM,
    )

    response = client.post(
        "/api/widget/auth",
        json={
            "agent_id": agent_id,
            "guest_id": "guest-1",
            "embed_ticket": wrong_type_ticket,
        },
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid or expired embed ticket"


def test_widget_auth_rechecks_ticket_origin_against_current_allowlist() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Shrinking Allowlist Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    ticket = _issue_embed_ticket(agent_id, "https://trusted-site.com").json()["ticket"]

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).first()
        assert agent is not None
        agent.allowed_domains = ["another-site.com"]
        db.commit()
    finally:
        db.close()

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Domain not allowed: trusted-site.com"


def test_widget_auth_rejects_ticket_when_agent_allowlist_becomes_malformed(
    caplog: pytest.LogCaptureFixture,
) -> None:
    caplog.set_level("WARNING", logger="xagent.web.services.widget_domains")
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Malformed Live Allowlist Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    ticket = _issue_embed_ticket(agent_id, "https://trusted-site.com").json()["ticket"]

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        cast(Any, agent).allowed_domains = [
            "do-not-log-this-policy-value.example",
            None,
        ]
        db.commit()
    finally:
        db.close()

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
    )

    assert response.status_code == 403
    assert response.json()["detail"] == "Domain not allowed: trusted-site.com"
    assert (
        "Rejected malformed widget allowed-domains policy: "
        f"owner_type=agent owner_id={agent_id} reason=non_string_entry"
    ) in caplog.text
    assert "do-not-log-this-policy-value.example" not in caplog.text


def test_widget_embed_ticket_matches_domain_regardless_of_scheme() -> None:
    """allowed_domains matches on host[:port] only; the scheme is not part
    of the comparison, so an http origin matches an entry with no scheme."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Scheme Agnostic Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    response = _issue_embed_ticket(agent_id, "http://trusted-site.com")

    assert response.status_code == 200, response.text


def test_widget_embed_ticket_wildcard_allows_any_origin() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Wildcard Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["*"],
    )

    response = _issue_embed_ticket(agent_id, "https://anything-goes.example")

    assert response.status_code == 200, response.text


def test_widget_embed_ticket_matches_subdomain_of_allowed_entry() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Subdomain Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )

    allowed = _issue_embed_ticket(agent_id, "https://app.trusted-site.com")
    assert allowed.status_code == 200, allowed.text

    # A domain that merely ends with the allowed string but is not a subdomain
    # (no dot boundary) must not match.
    spoofed = _issue_embed_ticket(agent_id, "https://eviltrusted-site.com")
    assert spoofed.status_code == 403
    assert spoofed.json()["detail"] == "Domain not allowed: eviltrusted-site.com"


def test_embed_ticket_endpoint_rejects_unknown_key() -> None:
    _admin_headers()
    response = client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": "wk-does-not-exist"},
        headers={"origin": "https://trusted-site.com"},
    )
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid widget key"


def test_embed_ticket_endpoint_rejects_generated_manager_agent() -> None:
    """A workforce-manager agent's key is treated the same as an unknown key."""
    _admin_headers()
    owner_id = _user_id("admin")
    manager_id = _create_agent_row(
        user_id=owner_id,
        name="Generated Manager Ticket Agent",
        status=AgentStatus.PUBLISHED,
        origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
        widget_enabled=True,
        allowed_domains=["*"],
    )
    response = _issue_embed_ticket(manager_id, "https://trusted-site.com")
    assert response.status_code == 403
    assert response.json()["detail"] == "Invalid widget key"


def test_widget_public_tokens_cannot_create_tasks_for_other_agents() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    allowed_agent_id = _create_agent_row(
        user_id=owner_id,
        name="Allowed Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["example.com"],
    )
    other_agent_id = _create_agent_row(
        user_id=owner_id,
        name="Other Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["example.com"],
    )

    guest_headers = _authenticate_widget_guest(agent_id=allowed_agent_id)

    create_task_response = client.post(
        "/api/widget/chat/task/create",
        json={
            "title": "cross agent",
            "description": "cross agent",
            "agent_id": other_agent_id,
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 403, create_task_response.text
    assert create_task_response.json()["detail"] == "Widget access is unavailable"


def test_widget_task_create_persists_connector_runtime_selection_snapshot() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Widget Snapshot Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["example.com"],
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    create_task_response = client.post(
        "/api/widget/chat/task/create",
        json={
            "title": "hello from widget",
            "description": "hello from widget",
            "agent_id": agent_id,
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 200, create_task_response.text

    db = _direct_db_session()
    try:
        task = (
            db.query(Task)
            .filter(Task.id == create_task_response.json()["task_id"])
            .one()
        )
        assert task.connector_runtime_selected_refs == []
        assert task.agent_config.get("__xagent_file_operation_access_version") == 1
    finally:
        db.close()


def test_widget_task_create_drops_forged_runtime_extension_bindings() -> None:
    """Widget guests are explicitly denied ``runtime_extensions`` (400), yet the
    client ``agent_config`` copy would still let a guest write the server-owned
    per-task binding record directly. Task deletion dispatches provider cleanup
    by that record, so a forged entry naming a broken provider can wedge the
    owner's task."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Widget Binding Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["example.com"],
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    create_task_response = client.post(
        "/api/widget/chat/task/create",
        json={
            "title": "forged binding",
            "description": "forged binding",
            "agent_id": agent_id,
            "agent_config": {
                TASK_RUNTIME_BINDINGS_AGENT_CONFIG_KEY: ["victim_ext"],
                "keep_me": "client value",
            },
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 200, create_task_response.text

    db = _direct_db_session()
    try:
        task = (
            db.query(Task)
            .filter(Task.id == create_task_response.json()["task_id"])
            .one()
        )
        assert task_extension_bindings_from_agent_config(task.agent_config) == ()
        # Only the reserved key goes; ordinary client config and the
        # server-owned keys layered on top both survive.
        assert task.agent_config.get("keep_me") == "client value"
        assert task.agent_config.get("auth_mode") == "widget"
        assert task.agent_config.get("guest_id") == "guest-1"
    finally:
        db.close()


def test_widget_task_create_drops_forged_execution_scope() -> None:
    """A widget guest cannot pre-seed the scope snapshot that governs where a
    task's bytes land -- sandbox mount, storage prefix, workspace directory,
    memory dimensions -- or the bound file list, by naming either in the
    request body's ``agent_config``.
    """
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Widget Scope Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["example.com"],
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    create_task_response = client.post(
        "/api/widget/chat/task/create",
        json={
            "title": "forged scope",
            "description": "forged scope",
            "agent_id": agent_id,
            "agent_config": {
                EXECUTION_SCOPE_AGENT_CONFIG_KEY: {
                    "sandbox_key_suffix": "victim",
                    "workspace_segments": ["victim"],
                    "memory_dimensions": {"tenant": "victim"},
                },
                SELECTED_FILE_IDS_AGENT_CONFIG_KEY: ["victim-file-id"],
                "keep_me": "client value",
            },
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 200, create_task_response.text

    db = _direct_db_session()
    try:
        task = (
            db.query(Task)
            .filter(Task.id == create_task_response.json()["task_id"])
            .one()
        )
        assert EXECUTION_SCOPE_AGENT_CONFIG_KEY not in task.agent_config
        assert execution_scope_from_agent_config(task.agent_config) is None
        assert SELECTED_FILE_IDS_AGENT_CONFIG_KEY not in task.agent_config
        assert task.agent_config.get("keep_me") == "client value"
        assert task.agent_config.get("auth_mode") == "widget"
        assert task.agent_config.get("guest_id") == "guest-1"
    finally:
        db.close()


def _create_widget_task(guest_headers: dict[str, str], agent_id: int) -> Any:
    return client.post(
        "/api/widget/chat/task/create",
        json={
            "title": "hello",
            "description": "hello",
            "agent_id": agent_id,
        },
        headers=guest_headers,
    )


def test_disabled_widget_invalidates_existing_guest_tokens() -> None:
    """Disabling an agent's widget must invalidate already-issued guest JWTs
    on their next request (mirrors the workforce/share widget path)."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Disable Invalidate Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    # Sanity: the guest token works while the widget is enabled.
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    disabled = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"widget_enabled": False},
    )
    assert disabled.status_code == 200, disabled.text

    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def test_rotated_widget_key_invalidates_existing_guest_tokens() -> None:
    """Rotating an agent's widget key must invalidate already-issued guest
    JWTs on their next request."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Rotate Invalidate Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    rotate = client.post(f"/api/agents/{agent_id}/widget-key/rotate", headers=headers)
    assert rotate.status_code == 200, rotate.text

    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def test_unpublishing_agent_invalidates_existing_widget_guest_tokens() -> None:
    """Unpublishing an agent must invalidate already-issued guest JWTs on their
    next request — the third revocation lever alongside disable and rotate.

    ``unpublish_agent`` only flips ``status``; it leaves ``widget_enabled`` and
    ``widget_key`` intact on purpose, so that re-publishing restores the same
    embed snippet. That makes the per-request check in
    ``ensure_widget_agent_available`` the thing that has to enforce this (#1055).
    """
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Unpublish Invalidate Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    # Sanity: the guest token works while the agent is published.
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text

    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def test_republishing_agent_restores_widget_access_for_existing_tokens() -> None:
    """Unpublish is a reversible lever: re-publishing revives the same guest
    token, because the widget key it pins was never rotated. Locks in why the
    status check lives in the availability helper rather than in
    ``unpublish_agent`` clearing ``widget_enabled`` (#1055)."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Republish Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)
    key_before = _widget_key_for(agent_id)

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text
    assert _create_widget_task(guest_headers, agent_id).status_code == 403

    republished = client.post(f"/api/agents/{agent_id}/publish", headers=headers)
    assert republished.status_code == 200, republished.text

    assert _widget_key_for(agent_id) == key_before
    assert _create_widget_task(guest_headers, agent_id).status_code == 200


def test_widget_auth_rejects_unpublished_agent_key() -> None:
    """An unpublished agent's widget key must stop minting guest tokens at all,
    rather than handing out a token that dies on its first real request. Mirrors
    the workforce branch, which resolves keys only for ``status == 'active'``."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Unpublish Auth Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    widget_key = _widget_key_for(agent_id)

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text

    response = client.post(
        "/api/widget/auth",
        json={"widget_key": widget_key, "guest_id": "guest-1"},
    )
    assert response.status_code == 403, response.text
    # Same detail as an unknown key: publication state must not be probeable.
    assert response.json()["detail"] == "Invalid widget key"


@pytest.mark.parametrize("status", [AgentStatus.DRAFT, AgentStatus.ARCHIVED])
def test_widget_auth_rejects_agent_that_is_not_published(status: AgentStatus) -> None:
    """Agents are created ``widget_enabled=True`` with a key already minted, so
    a never-published draft carries a live widget credential. External access
    requires publication, so that key must not authenticate either (#1055).

    Parametrized over both non-published states to pin the gate as
    ``!= PUBLISHED`` rather than ``== DRAFT``; ``ARCHIVED`` is not reachable
    through the web API today, so nothing else would catch a narrowing."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name=f"Unpublished Widget Agent ({status.value})",
        status=status,
        widget_enabled=True,
    )

    response = client.post(
        "/api/widget/auth",
        json={"widget_key": _widget_key_for(agent_id), "guest_id": "guest-1"},
    )
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Invalid widget key"


def test_embed_ticket_rejects_unpublished_agent_like_an_unknown_key() -> None:
    """The embedding page cannot obtain a fresh ticket for an unpublished agent;
    unpublished and unknown-key collapse to the same 403."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Unpublish Embed Ticket Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    widget_key = _widget_key_for(agent_id)
    assert _issue_embed_ticket(agent_id, "https://trusted-site.com").status_code == 200

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text

    response = client.post(
        "/api/widget/embed-ticket",
        json={"widget_key": widget_key},
        headers={"origin": "https://trusted-site.com"},
    )
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Invalid widget key"


def test_embed_ticket_stops_authenticating_once_agent_is_unpublished() -> None:
    """A ticket minted while the agent was published must not survive an
    unpublish inside its 60s TTL: redemption re-derives the agent from live
    state, mirroring ``_workforce_owner_from_ticket``'s ``active`` check.

    The denial reuses the disabled-widget detail so a caller holding a valid
    ticket cannot tell the two revocation levers apart."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Unpublish Ticket Redemption Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    ticket_response = _issue_embed_ticket(agent_id, "https://trusted-site.com")
    assert ticket_response.status_code == 200, ticket_response.text
    ticket = ticket_response.json()["ticket"]

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
        headers={"origin": "https://xagent-host.example"},
    )
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is disabled for this agent"


def test_widget_guest_token_rejected_when_agent_is_archived() -> None:
    """``ensure_widget_agent_available`` gates on ``!= PUBLISHED``, not
    ``== DRAFT``.

    ``test_unpublishing_agent_invalidates_existing_widget_guest_tokens`` covers
    the DRAFT half, but only through the real ``/unpublish`` endpoint, which
    hardcodes ``AgentStatus.DRAFT`` and can never produce ``ARCHIVED`` — so a
    narrowed gate would still pass it. Hence the direct status write."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Archived Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    _set_agent_status(agent_id, AgentStatus.ARCHIVED)

    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def test_embed_ticket_rejects_widget_enabled_agent_with_no_widget_key() -> None:
    """``_get_live_widget_agent`` also requires a live ``widget_key``, matching
    its three sibling gates.

    Nothing produces ``widget_enabled=True, widget_key=None`` today — creation
    always mints a key, the update path re-mints one if the flag is toggled on
    without it, and rotation never nulls it — but no schema constraint forbids
    the row either. Written directly so the check is pinned: such an agent must
    fail here rather than redeem the ticket into a guest token that 403s on its
    first real request."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Keyless Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    ticket_response = _issue_embed_ticket(agent_id, "https://trusted-site.com")
    assert ticket_response.status_code == 200, ticket_response.text
    ticket = ticket_response.json()["ticket"]

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        agent.widget_key = None
        db.commit()
    finally:
        db.close()

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
        headers={"origin": "https://xagent-host.example"},
    )
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is disabled for this agent"


def test_embed_ticket_stops_authenticating_once_agent_is_archived() -> None:
    """``_get_live_widget_agent`` gates on ``!= PUBLISHED``, not ``== DRAFT``.

    Same reasoning as ``test_widget_guest_token_rejected_when_agent_is_archived``
    one gate over: the sibling unpublish test can only reach DRAFT."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Archived Ticket Redemption Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
        allowed_domains=["trusted-site.com"],
    )
    ticket_response = _issue_embed_ticket(agent_id, "https://trusted-site.com")
    assert ticket_response.status_code == 200, ticket_response.text
    ticket = ticket_response.json()["ticket"]

    _set_agent_status(agent_id, AgentStatus.ARCHIVED)

    response = client.post(
        "/api/widget/auth",
        json={"agent_id": agent_id, "guest_id": "guest-1", "embed_ticket": ticket},
        headers={"origin": "https://xagent-host.example"},
    )
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is disabled for this agent"


def test_unpublishing_agent_revokes_widget_guest_access_to_task_files() -> None:
    """The publication gate reaches further than the chat/WS routes: the public
    file endpoints resolve a guest token through ``get_public_chat_user``
    (``_validate_public_task_file_access``), which calls the same
    ``ensure_widget_agent_available``. So unpublishing also cuts a widget guest
    off from its own task's attachments — part of the shipped blast radius of
    #1055, and the only widget/guest file-access assertion in the suite."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Unpublish Widget File Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)

    created = _create_widget_task(guest_headers, agent_id)
    assert created.status_code == 200, created.text
    task_id = created.json()["task_id"]

    uploaded = client.post(
        "/api/widget/files/upload",
        headers=guest_headers,
        data={"task_type": "task", "task_id": str(task_id)},
        files={"file": ("widget-note.txt", io.BytesIO(b"hello"), "text/plain")},
    )
    assert uploaded.status_code == 200, uploaded.text
    file_id = uploaded.json()["file_id"]

    allowed = client.get(f"/api/files/public/download/{file_id}", headers=guest_headers)
    assert allowed.status_code == 200, allowed.text
    assert allowed.content == b"hello"

    unpublished = client.post(f"/api/agents/{agent_id}/unpublish", headers=headers)
    assert unpublished.status_code == 200, unpublished.text

    denied = client.get(f"/api/files/public/download/{file_id}", headers=guest_headers)
    assert denied.status_code == 403, denied.text
    assert denied.json()["detail"] == "Widget is unavailable"


def test_widget_guest_token_rejected_when_agent_becomes_generated_manager() -> None:
    """``ensure_widget_agent_available`` must reject a live guest token once the
    backing agent is a workforce-generated manager, tripping the check at the
    task-create site (not just at ``/api/widget/auth``)."""
    _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Becomes Manager Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    # Flip the agent into a generated manager after the token was issued.
    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        agent.origin = AgentOrigin.WORKFORCE_GENERATED_MANAGER.value
        db.commit()
    finally:
        db.close()

    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def _mint_legacy_widget_guest_token(
    *,
    user_id: int,
    agent_id: int,
    guest_id: str = "guest-legacy",
) -> dict[str, str]:
    """Mint a widget guest JWT the way it was minted before the ``widget_key``
    claim shipped (issue #988): no key embedded. Exercises the backward-compat
    branch in ``ensure_widget_agent_available``."""
    db = _direct_db_session()
    try:
        user = db.query(User).filter(User.id == user_id).one()
        username = str(user.username)
    finally:
        db.close()
    token = create_public_chat_access_token(
        {
            "sub": username,
            "user_id": user_id,
            "channel_id": None,
            "guest_id": guest_id,
            "auth_mode": "widget",
            "widget_agent_id": agent_id,
        }
    )
    return {"Authorization": f"Bearer {token}"}


def test_legacy_guest_token_without_widget_key_stays_gated_on_widget_enabled() -> None:
    """Guest tokens minted before the ``widget_key`` claim shipped carry no key:
    they still work while the widget is enabled, survive key rotation (no key to
    compare), but are revoked when the widget is disabled. Locks in the
    transitional contract documented on ``ensure_widget_agent_available``."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Legacy Token Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _mint_legacy_widget_guest_token(user_id=owner_id, agent_id=agent_id)

    # (a) A keyless legacy token works while the widget is enabled.
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    # (c) Rotating the key does not revoke a keyless token: there is no key
    # claim to compare, so it stays gated on widget_enabled only.
    rotate = client.post(f"/api/agents/{agent_id}/widget-key/rotate", headers=headers)
    assert rotate.status_code == 200, rotate.text
    assert _create_widget_task(guest_headers, agent_id).status_code == 200

    # (b) Disabling the widget still revokes it.
    disabled = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"widget_enabled": False},
    )
    assert disabled.status_code == 200, disabled.text
    response = _create_widget_task(guest_headers, agent_id)
    assert response.status_code == 403, response.text
    assert response.json()["detail"] == "Widget is unavailable"


def test_share_link_requires_published_agent() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    draft_agent_id = _create_agent_row(
        user_id=owner_id,
        name="Draft Share Agent",
        status=AgentStatus.DRAFT,
    )

    response = client.post(f"/api/agents/{draft_agent_id}/share-link", headers=headers)

    assert response.status_code == 400
    assert response.json()["detail"] == "Only published agents can be shared"


def test_generic_agent_responses_do_not_expose_share_token() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    share_token = "hidden-from-generic-agent-response"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Hidden Share Token Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )

    detail_response = client.get(f"/api/agents/{agent_id}", headers=headers)
    assert detail_response.status_code == 200, detail_response.text
    assert "share_token" not in detail_response.json()

    list_response = client.get("/api/agents", headers=headers)
    assert list_response.status_code == 200, list_response.text
    list_item = next(item for item in list_response.json() if item["id"] == agent_id)
    assert "share_token" not in list_item

    share_link_response = client.get(
        f"/api/agents/{agent_id}/share-link", headers=headers
    )
    assert share_link_response.status_code == 200, share_link_response.text
    assert share_link_response.json()["share_token"] == share_token


def test_share_link_can_be_enabled_rotated_and_disabled() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Published Share Agent",
        status=AgentStatus.PUBLISHED,
    )

    enable_response = client.post(f"/api/agents/{agent_id}/share-link", headers=headers)
    assert enable_response.status_code == 200, enable_response.text
    enabled_agent = enable_response.json()
    assert enabled_agent["agent_id"] == agent_id
    assert enabled_agent["share_enabled"] is True
    assert isinstance(enabled_agent["share_token"], str)
    first_token = enabled_agent["share_token"]

    rotate_response = client.post(
        f"/api/agents/{agent_id}/share-link/rotate", headers=headers
    )
    assert rotate_response.status_code == 200, rotate_response.text
    rotated_agent = rotate_response.json()
    assert rotated_agent["share_enabled"] is True
    assert isinstance(rotated_agent["share_token"], str)
    assert rotated_agent["share_token"] != first_token

    disable_response = client.delete(
        f"/api/agents/{agent_id}/share-link", headers=headers
    )
    assert disable_response.status_code == 200, disable_response.text
    disabled_agent = disable_response.json()
    assert disabled_agent["share_enabled"] is False
    assert disabled_agent["share_token"] is None


def test_created_agents_get_a_widget_key() -> None:
    headers = _admin_headers()
    agent_id = _create_agent(headers, name="Widget Key Agent")

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).first()
        assert agent is not None
        assert isinstance(agent.widget_key, str) and len(agent.widget_key) >= 32
    finally:
        db.close()


def test_generic_agent_responses_do_not_expose_widget_key() -> None:
    headers = _admin_headers()
    agent_id = _create_agent(headers, name="Hidden Widget Key Agent")

    detail_response = client.get(f"/api/agents/{agent_id}", headers=headers)
    assert detail_response.status_code == 200, detail_response.text
    assert "widget_key" not in detail_response.json()

    list_response = client.get("/api/agents", headers=headers)
    assert list_response.status_code == 200, list_response.text
    list_item = next(item for item in list_response.json() if item["id"] == agent_id)
    assert "widget_key" not in list_item


def test_widget_key_endpoint_is_owner_only_and_heals_missing_keys() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    # Row created directly, predating the widget_key column (no key).
    agent_id = _create_agent_row(user_id=owner_id, name="Legacy Widget Agent")

    response = client.get(f"/api/agents/{agent_id}/widget-key", headers=headers)
    assert response.status_code == 200, response.text
    payload = response.json()
    assert payload["agent_id"] == agent_id
    assert isinstance(payload["widget_key"], str) and len(payload["widget_key"]) >= 32

    # Stable across reads once generated.
    second = client.get(f"/api/agents/{agent_id}/widget-key", headers=headers)
    assert second.json()["widget_key"] == payload["widget_key"]

    other_headers = _register_second_user()
    for method, url in (
        ("get", f"/api/agents/{agent_id}/widget-key"),
        ("post", f"/api/agents/{agent_id}/widget-key/rotate"),
    ):
        other_response = getattr(client, method)(url, headers=other_headers)
        assert other_response.status_code == 404


def test_widget_key_can_be_rotated() -> None:
    headers = _admin_headers()
    agent_id = _create_agent(headers, name="Rotating Widget Agent")

    first = client.get(f"/api/agents/{agent_id}/widget-key", headers=headers)
    assert first.status_code == 200, first.text
    first_key = first.json()["widget_key"]

    rotate = client.post(f"/api/agents/{agent_id}/widget-key/rotate", headers=headers)
    assert rotate.status_code == 200, rotate.text
    rotated_key = rotate.json()["widget_key"]
    assert isinstance(rotated_key, str) and rotated_key != first_key

    after = client.get(f"/api/agents/{agent_id}/widget-key", headers=headers)
    assert after.json()["widget_key"] == rotated_key


def test_enabling_widget_generates_missing_key() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Disabled Widget Agent",
        widget_enabled=False,
    )

    response = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"widget_enabled": True},
    )
    assert response.status_code == 200, response.text

    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).first()
        assert agent is not None
        assert isinstance(agent.widget_key, str) and len(agent.widget_key) >= 32
    finally:
        db.close()


@pytest.mark.parametrize(
    "blank_domain",
    ["", "   ", "\u001c"],
    ids=["empty", "spaces", "unicode-control-separator"],
)
def test_agent_update_rejects_blank_widget_allowed_domain(
    blank_domain: str,
) -> None:
    headers = _admin_headers()
    agent_id = _create_agent(headers, name="Validated Widget Domain Agent")
    configured = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"allowed_domains": ["existing.example"]},
    )
    assert configured.status_code == 200, configured.text

    response = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"allowed_domains": [blank_domain]},
    )

    assert response.status_code == 422, response.text
    db = _direct_db_session()
    try:
        agent = db.query(Agent).filter(Agent.id == agent_id).one()
        assert agent.allowed_domains == ["existing.example"]
    finally:
        db.close()


def test_share_link_authenticates_public_chat_for_published_agent() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    share_token = "public-share-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Public Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )

    response = client.post(
        "/api/share/auth",
        json={"share_token": share_token},
    )

    assert response.status_code == 200, response.text
    payload = response.json()
    assert payload["agent_id"] == agent_id
    assert payload["agent_name"] == "Public Share Agent"
    assert isinstance(payload["access_token"], str)


def test_disabled_share_link_invalidates_existing_public_tokens() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    share_token = "revoked-share-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Revoked Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )

    guest_headers = _authenticate_share_guest(share_token)

    disable_response = client.delete(
        f"/api/agents/{agent_id}/share-link", headers=headers
    )
    assert disable_response.status_code == 200, disable_response.text

    create_task_response = client.post(
        "/api/share/chat/task/create",
        json={
            "title": "hello",
            "description": "hello",
            "agent_id": agent_id,
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 403, create_task_response.text
    assert create_task_response.json()["detail"] == "Share link is unavailable"

    upload_response = client.post(
        "/api/share/files/upload",
        headers=guest_headers,
        data={"task_type": "task"},
        files={"file": ("note.txt", io.BytesIO(b"hello"), "text/plain")},
    )
    assert upload_response.status_code == 403, upload_response.text
    assert upload_response.json()["detail"] == "Share link is unavailable"


def test_rotated_share_link_invalidates_existing_public_tokens() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    original_share_token = "rotating-share-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Rotating Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=original_share_token,
    )

    guest_headers = _authenticate_share_guest(original_share_token)

    rotate_response = client.post(
        f"/api/agents/{agent_id}/share-link/rotate", headers=headers
    )
    assert rotate_response.status_code == 200, rotate_response.text
    rotated_share_token = rotate_response.json()["share_token"]
    assert isinstance(rotated_share_token, str)
    assert rotated_share_token != original_share_token

    create_task_response = client.post(
        "/api/share/chat/task/create",
        json={
            "title": "hello after rotate",
            "description": "hello after rotate",
            "agent_id": agent_id,
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 403, create_task_response.text
    assert create_task_response.json()["detail"] == "Share link is unavailable"

    refreshed_guest_headers = _authenticate_share_guest(rotated_share_token)
    refreshed_create_task_response = client.post(
        "/api/share/chat/task/create",
        json={
            "title": "hello with new token",
            "description": "hello with new token",
            "agent_id": agent_id,
        },
        headers=refreshed_guest_headers,
    )
    assert refreshed_create_task_response.status_code == 200, (
        refreshed_create_task_response.text
    )
    db = _direct_db_session()
    try:
        task = (
            db.query(Task)
            .filter(Task.id == refreshed_create_task_response.json()["task_id"])
            .one()
        )
        assert task.connector_runtime_selected_refs == []
    finally:
        db.close()


def test_reenabled_share_link_invalidates_existing_public_tokens() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    original_share_token = "reenable-share-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Re-enabled Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=original_share_token,
    )

    guest_headers = _authenticate_share_guest(original_share_token)

    disable_response = client.delete(
        f"/api/agents/{agent_id}/share-link", headers=headers
    )
    assert disable_response.status_code == 200, disable_response.text

    enable_response = client.post(f"/api/agents/{agent_id}/share-link", headers=headers)
    assert enable_response.status_code == 200, enable_response.text
    new_share_token = enable_response.json()["share_token"]
    assert isinstance(new_share_token, str)
    assert new_share_token != original_share_token

    create_task_response = client.post(
        "/api/share/chat/task/create",
        json={
            "title": "hello after re-enable",
            "description": "hello after re-enable",
            "agent_id": agent_id,
        },
        headers=guest_headers,
    )
    assert create_task_response.status_code == 403, create_task_response.text
    assert create_task_response.json()["detail"] == "Share link is unavailable"

    refreshed_guest_headers = _authenticate_share_guest(new_share_token)
    refreshed_create_task_response = client.post(
        "/api/share/chat/task/create",
        json={
            "title": "hello after reauth",
            "description": "hello after reauth",
            "agent_id": agent_id,
        },
        headers=refreshed_guest_headers,
    )
    assert refreshed_create_task_response.status_code == 200, (
        refreshed_create_task_response.text
    )


def test_share_upload_requires_task_id() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    share_token = "upload-needs-task-token"
    _create_agent_row(
        user_id=owner_id,
        name="Upload Requires Task Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )

    guest_headers = _authenticate_share_guest(share_token)

    upload_response = client.post(
        "/api/share/files/upload",
        headers=guest_headers,
        data={"task_type": "task"},
        files={"file": ("note.txt", io.BytesIO(b"hello"), "text/plain")},
    )
    assert upload_response.status_code == 400, upload_response.text
    assert upload_response.json()["detail"] == "task_id is required"


def test_share_public_file_preview_requires_valid_share_token() -> None:
    headers = _admin_headers()
    owner_id = _user_id("admin")
    share_token = "share-preview-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Preview Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )
    guest_headers = _authenticate_share_guest(share_token)
    access_token = guest_headers["Authorization"].replace("Bearer ", "", 1)
    file_id = _create_public_task_file(
        owner_id=owner_id,
        agent_id=agent_id,
        guest_id=_share_guest_id(access_token),
    )

    preview_without_token = client.get(f"/api/files/public/preview/{file_id}")
    assert preview_without_token.status_code == 403, preview_without_token.text

    # The retired query-string carrier no longer grants access (CASA 6.5.1):
    # the guest token must never be required in, or accepted from, a URL.
    preview_with_query_token = client.get(
        f"/api/files/public/preview/{file_id}",
        params={"token": access_token},
    )
    assert preview_with_query_token.status_code == 403, preview_with_query_token.text

    preview_with_token = client.get(
        f"/api/files/public/preview/{file_id}", headers=guest_headers
    )
    assert preview_with_token.status_code == 200, preview_with_token.text
    assert preview_with_token.content == b"hello from public task"

    disable_response = client.delete(
        f"/api/agents/{agent_id}/share-link", headers=headers
    )
    assert disable_response.status_code == 200, disable_response.text

    preview_after_disable = client.get(
        f"/api/files/public/preview/{file_id}", headers=guest_headers
    )
    assert preview_after_disable.status_code == 403, preview_after_disable.text
    assert preview_after_disable.json()["detail"] == "Share link is unavailable"


def test_share_public_file_download_requires_valid_share_token() -> None:
    _admin_headers()
    owner_id = _user_id("admin")
    share_token = "share-download-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Download Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )
    guest_headers = _authenticate_share_guest(share_token)
    access_token = guest_headers["Authorization"].replace("Bearer ", "", 1)
    file_id = _create_public_task_file(
        owner_id=owner_id,
        agent_id=agent_id,
        guest_id=_share_guest_id(access_token),
        filename="download-note.txt",
    )

    download_with_token = client.get(
        f"/api/files/public/download/{file_id}", headers=guest_headers
    )
    assert download_with_token.status_code == 200, download_with_token.text
    assert download_with_token.content == b"hello from public task"

    download_without_token = client.get(f"/api/files/public/download/{file_id}")
    assert download_without_token.status_code == 403, download_without_token.text

    download_with_query_token = client.get(
        f"/api/files/public/download/{file_id}", params={"token": access_token}
    )
    assert download_with_query_token.status_code == 403, download_with_query_token.text


def _mint_public_file_ticket(file_id: str, guest_headers: dict[str, str]) -> Any:
    return client.post(f"/api/files/public/tickets/{file_id}", headers=guest_headers)


def test_share_public_file_ticket_is_file_bound_and_revocable() -> None:
    """Browser-loaded URLs (media, HTML preview assets) cannot send headers, so
    the guest exchanges its header token for a short-lived ticket bound to one
    file. The ticket must not leak the guest token or the share secret, must
    only open its own file, and must die with the share link."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    share_token = "share-ticket-secret-token"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Ticket Share Agent",
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )
    guest_headers = _authenticate_share_guest(share_token)
    access_token = guest_headers["Authorization"].replace("Bearer ", "", 1)
    guest_id = _share_guest_id(access_token)
    file_id = _create_public_task_file(
        owner_id=owner_id, agent_id=agent_id, guest_id=guest_id
    )
    other_file_id = _create_public_task_file(
        owner_id=owner_id,
        agent_id=agent_id,
        guest_id=guest_id,
        filename="other-note.txt",
        content=b"other file",
    )

    assert client.post(f"/api/files/public/tickets/{file_id}").status_code == 401
    garbage = _mint_public_file_ticket(file_id, {"Authorization": "Bearer garbage"})
    assert garbage.status_code == 401, garbage.text

    minted = _mint_public_file_ticket(file_id, guest_headers)
    assert minted.status_code == 200, minted.text
    body = minted.json()
    # Only the ticket and its lifetime; the client builds its own URL.
    assert set(body) == {"ticket", "expires_in"}
    ticket = body["ticket"]
    assert 0 < body["expires_in"] <= 3600
    assert access_token not in ticket
    preview_url = f"/api/files/public/preview/{file_id}?ticket={ticket}"
    # Signed, not encrypted: the share secret itself must not ride in the URL.
    claims = jwt.decode(ticket, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    assert share_token not in json.dumps(claims)
    assert claims["type"] == "public_file_ticket"
    assert claims["file_id"] == file_id

    preview = client.get(preview_url)
    assert preview.status_code == 200, preview.text
    assert preview.content == b"hello from public task"
    download = client.get(
        f"/api/files/public/download/{file_id}", params={"ticket": ticket}
    )
    assert download.status_code == 200, download.text

    # Bound to one file: replaying it against another is refused.
    replayed = client.get(
        f"/api/files/public/preview/{other_file_id}", params={"ticket": ticket}
    )
    assert replayed.status_code == 401, replayed.text
    # A present ticket is judged alone, never rescued by a valid header.
    bad_ticket = client.get(
        f"/api/files/public/preview/{file_id}",
        params={"ticket": "not-a-ticket"},
        headers=guest_headers,
    )
    assert bad_ticket.status_code == 401, bad_ticket.text

    disabled = client.delete(f"/api/agents/{agent_id}/share-link", headers=headers)
    assert disabled.status_code == 200, disabled.text
    revoked = client.get(preview_url)
    assert revoked.status_code == 403, revoked.text
    assert revoked.json()["detail"] == "Share link is unavailable"


def test_widget_public_file_ticket_dies_with_widget_key_rotation() -> None:
    """The ticket carries only a digest of the widget key; redemption restores
    the live key, so rotating it revokes outstanding tickets like guest tokens."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Ticket Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    widget_key = _widget_key_for(agent_id)
    guest_headers = _authenticate_widget_guest(agent_id=agent_id)
    created = _create_widget_task(guest_headers, agent_id)
    assert created.status_code == 200, created.text
    uploaded = client.post(
        "/api/widget/files/upload",
        headers=guest_headers,
        data={"task_type": "task", "task_id": str(created.json()["task_id"])},
        files={"file": ("widget-ticket.txt", io.BytesIO(b"widget"), "text/plain")},
    )
    assert uploaded.status_code == 200, uploaded.text
    file_id = uploaded.json()["file_id"]

    minted = _mint_public_file_ticket(file_id, guest_headers)
    assert minted.status_code == 200, minted.text
    ticket = minted.json()["ticket"]
    claims = jwt.decode(ticket, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    assert widget_key not in json.dumps(claims)

    assert (
        client.get(
            f"/api/files/public/preview/{file_id}", params={"ticket": ticket}
        ).status_code
        == 200
    )

    rotated = client.post(f"/api/agents/{agent_id}/widget-key/rotate", headers=headers)
    assert rotated.status_code == 200, rotated.text
    revoked = client.get(
        f"/api/files/public/preview/{file_id}", params={"ticket": ticket}
    )
    assert revoked.status_code == 403, revoked.text
    assert revoked.json()["detail"] == "Widget is unavailable"


def _unverified_jwt_payload(token: str) -> dict[str, Any]:
    """Read a JWT payload the way any ticket holder can: base64, no key."""
    segment = token.split(".")[1]
    raw = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))
    return cast(dict[str, Any], json.loads(raw))


def _string_values(value: object) -> list[str]:
    if isinstance(value, str):
        return [value]
    if isinstance(value, dict):
        return [s for item in value.values() for s in _string_values(item)]
    if isinstance(value, list):
        return [s for item in value for s in _string_values(item)]
    return []


def test_widget_file_ticket_reveals_no_guest_identity_for_widget_auth() -> None:
    """A widget file ticket travels in a URL and is only signed, so anything in
    it is readable. ``/api/widget/auth`` signs any caller-supplied guest id
    with the public widget key, so a readable guest id would let a ticket
    holder mint a fresh 30-day token for that guest. The ticket must carry only
    a keyed binding of the guest id, and nothing in it may obtain the guest."""
    _admin_headers()  # ensures the admin owner exists
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Ticket Identity Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    widget_key = _widget_key_for(agent_id)
    victim_guest_id = f"victim-{secrets.token_hex(6)}"
    guest_headers = _authenticate_widget_guest(
        agent_id=agent_id, guest_id=victim_guest_id
    )
    created = _create_widget_task(guest_headers, agent_id)
    assert created.status_code == 200, created.text
    uploaded = client.post(
        "/api/widget/files/upload",
        headers=guest_headers,
        data={"task_type": "task", "task_id": str(created.json()["task_id"])},
        files={"file": ("identity.txt", io.BytesIO(b"victim"), "text/plain")},
    )
    assert uploaded.status_code == 200, uploaded.text
    file_id = uploaded.json()["file_id"]
    minted = _mint_public_file_ticket(file_id, guest_headers)
    assert minted.status_code == 200, minted.text
    ticket = minted.json()["ticket"]

    payload = _unverified_jwt_payload(ticket)
    assert "guest_id" not in payload
    assert "guest_id" not in payload["guest"]
    assert "sub" not in payload["guest"]
    assert victim_guest_id not in json.dumps(payload)
    assert victim_guest_id not in ticket
    assert widget_key not in json.dumps(payload)
    assert set(payload["guest"]) <= {
        "type",
        "auth_mode",
        "user_id",
        "channel_id",
        "widget_agent_id",
        "deployment_secret_sha256",
        "guest_binding",
    }

    preview_url = f"/api/files/public/preview/{file_id}"

    def file_opens_for(guest_id: str) -> bool:
        # The supported direct-visit path with the public widget key.
        auth = client.post(
            "/api/widget/auth",
            json={"widget_key": widget_key, "guest_id": guest_id},
        )
        if auth.status_code == 422:  # too long to be any guest id
            return False
        assert auth.status_code == 200, auth.text
        token = auth.json()["access_token"]
        response = client.get(preview_url, headers={"Authorization": f"Bearer {token}"})
        return response.status_code == 200

    # Control: the attack works if the real guest id is known.
    assert file_opens_for(victim_guest_id)
    # No value a ticket holder can read becomes that guest.
    candidates = set(_string_values(payload)) | {ticket}
    for candidate in candidates:
        assert not file_opens_for(candidate), candidate

    # The ticket itself still redeems for its file.
    redeemed = client.get(preview_url, params={"ticket": ticket})
    assert redeemed.status_code == 200, redeemed.text
    assert redeemed.content == b"victim"


def test_public_file_ticket_redeems_only_for_its_guests_task() -> None:
    """Redemption restores the guest from the file's own task, so a ticket
    whose binding names another guest is refused even for a file id it is
    signed for."""
    *_, access_token, file_id = _share_ticket_fixture("Ticket Binding Agent")
    guest = jwt.decode(access_token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    good = create_public_file_ticket(guest, file_id=file_id, ttl_seconds=60)
    url = f"/api/files/public/preview/{file_id}"
    assert client.get(url, params={"ticket": good}).status_code == 200

    forged_guest = {**guest, "guest_id": "someone-else"}
    other = create_public_file_ticket(forged_guest, file_id=file_id, ttl_seconds=60)
    refused = client.get(url, params={"ticket": other})
    assert refused.status_code == 401, refused.text
    unbound_guest = {k: v for k, v in guest.items() if k != "guest_id"}
    unbound = create_public_file_ticket(unbound_guest, file_id=file_id, ttl_seconds=60)
    refused = client.get(url, params={"ticket": unbound})
    assert refused.status_code == 401, refused.text


def _share_ticket_fixture(
    name: str,
) -> tuple[int, int, str, dict[str, str], str, str]:
    """A published share agent, one guest, and one file on that guest's task.

    Returns ``(owner_id, agent_id, share_token, guest_headers, access_token,
    file_id)``.
    """
    _admin_headers()  # ensures the admin owner exists
    owner_id = _user_id("admin")
    share_token = f"share-{secrets.token_urlsafe(12)}"
    agent_id = _create_agent_row(
        user_id=owner_id,
        name=name,
        status=AgentStatus.PUBLISHED,
        share_enabled=True,
        share_token=share_token,
    )
    guest_headers = _authenticate_share_guest(share_token)
    access_token = guest_headers["Authorization"].replace("Bearer ", "", 1)
    file_id = _create_public_task_file(
        owner_id=owner_id,
        agent_id=agent_id,
        guest_id=_share_guest_id(access_token),
        filename=f"{secrets.token_hex(4)}-note.txt",
    )
    return owner_id, agent_id, share_token, guest_headers, access_token, file_id


def test_public_file_ticket_expiry_matches_expires_in() -> None:
    _, _, _, guest_headers, _, file_id = _share_ticket_fixture("Ticket Exp Agent")
    before = datetime.now(timezone.utc).timestamp()
    minted = _mint_public_file_ticket(file_id, guest_headers)
    assert minted.status_code == 200, minted.text
    body = minted.json()
    claims = jwt.decode(body["ticket"], JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    # exp tracks expires_in, so the client's refresh margin is meaningful.
    assert abs(claims["exp"] - (before + body["expires_in"])) <= 5

    guest = jwt.decode(
        guest_headers["Authorization"].replace("Bearer ", "", 1),
        JWT_SECRET_KEY,
        algorithms=[JWT_ALGORITHM],
    )
    expired = create_public_file_ticket(guest, file_id=file_id, ttl_seconds=-1)
    response = client.get(
        f"/api/files/public/preview/{file_id}", params={"ticket": expired}
    )
    assert response.status_code == 401, response.text


def test_public_file_ticket_mint_denied_for_another_guests_file() -> None:
    _, _, share_token, _, _, file_id = _share_ticket_fixture("Ticket Cross Agent")
    # Same share link, a different guest: isolated from the first guest's task.
    intruder = _authenticate_share_guest(share_token)
    denied = _mint_public_file_ticket(file_id, intruder)
    assert denied.status_code == 403, denied.text
    assert "ticket" not in denied.json()


def test_public_file_ticket_audiences_do_not_mix() -> None:
    """A widget guest's ticket never opens a share task's file (and vice versa),
    even when signed by this server and bound to the right file id."""
    owner_id, _, _, share_headers, share_access, share_file = _share_ticket_fixture(
        "Ticket Audience Share Agent"
    )
    widget_agent_id = _create_agent_row(
        user_id=owner_id,
        name="Ticket Audience Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    widget_headers = _authenticate_widget_guest(agent_id=widget_agent_id)
    created = _create_widget_task(widget_headers, widget_agent_id)
    assert created.status_code == 200, created.text
    uploaded = client.post(
        "/api/widget/files/upload",
        headers=widget_headers,
        data={"task_type": "task", "task_id": str(created.json()["task_id"])},
        files={"file": ("audience.txt", io.BytesIO(b"widget"), "text/plain")},
    )
    assert uploaded.status_code == 200, uploaded.text
    widget_file = uploaded.json()["file_id"]

    # Minting across audiences is refused outright.
    assert _mint_public_file_ticket(share_file, widget_headers).status_code == 401
    assert _mint_public_file_ticket(widget_file, share_headers).status_code == 401

    def claims_of(headers: dict[str, str]) -> dict[str, Any]:
        token = headers["Authorization"].replace("Bearer ", "", 1)
        return cast(
            dict[str, Any],
            jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM]),
        )

    # A server-signed ticket carrying the other audience's guest is refused too.
    widget_ticket = create_public_file_ticket(
        claims_of(widget_headers), file_id=share_file, ttl_seconds=60
    )
    share_ticket = create_public_file_ticket(
        claims_of(share_headers), file_id=widget_file, ttl_seconds=60
    )
    assert share_access not in share_ticket
    for file_id, ticket in ((share_file, widget_ticket), (widget_file, share_ticket)):
        response = client.get(
            f"/api/files/public/preview/{file_id}", params={"ticket": ticket}
        )
        assert response.status_code == 401, response.text


def test_public_file_routes_reject_credentials_in_the_wrong_carrier() -> None:
    _, _, _, guest_headers, access_token, file_id = _share_ticket_fixture(
        "Ticket Carrier Agent"
    )
    ticket = _mint_public_file_ticket(file_id, guest_headers).json()["ticket"]
    preview_url = f"/api/files/public/preview/{file_id}"

    # A file ticket is not a guest login.
    as_bearer = client.get(preview_url, headers={"Authorization": f"Bearer {ticket}"})
    assert as_bearer.status_code == 401, as_bearer.text
    as_mint_bearer = _mint_public_file_ticket(
        file_id, {"Authorization": f"Bearer {ticket}"}
    )
    assert as_mint_bearer.status_code == 401, as_mint_bearer.text
    # The long-lived guest token is not a ticket.
    as_ticket = client.get(preview_url, params={"ticket": access_token})
    assert as_ticket.status_code == 401, as_ticket.text
    # A signed-in user's private stream ticket does not open public routes.
    stream = client.get(
        f"/api/files/stream-tickets/{file_id}", headers=_admin_headers()
    )
    assert stream.status_code == 200, stream.text
    stream_ticket = stream.json()["path"].split("ticket=", 1)[1]
    for route in ("preview", "download"):
        response = client.get(
            f"/api/files/public/{route}/{file_id}", params={"ticket": stream_ticket}
        )
        assert response.status_code == 401, response.text


def test_public_file_ticket_redeems_relative_preview_assets() -> None:
    owner_id, agent_id, _, guest_headers, access_token, page_id = _share_ticket_fixture(
        "Ticket Asset Agent"
    )
    page_id = _create_public_task_file(
        owner_id=owner_id,
        agent_id=agent_id,
        guest_id=_share_guest_id(access_token),
        filename="ticket-page.html",
        content=b"<img src='ticket-asset.png'>",
    )
    (get_uploads_dir() / f"user_{owner_id}" / "ticket-asset.png").write_bytes(
        b"asset-bytes"
    )
    ticket = _mint_public_file_ticket(page_id, guest_headers).json()["ticket"]
    url = f"/api/files/public/preview/{page_id}"

    asset = client.get(
        url, params={"relative_path": "ticket-asset.png", "ticket": ticket}
    )
    assert asset.status_code == 200, asset.text
    assert asset.content == b"asset-bytes"
    anonymous = client.get(url, params={"relative_path": "ticket-asset.png"})
    assert anonymous.status_code == 403, anonymous.text


def test_public_file_ticket_without_secret_digest_stays_gated_on_live_widget() -> None:
    """Legacy guest tokens carry no widget key, so their tickets carry no digest;
    redemption still re-derives access from the live widget state."""
    headers = _admin_headers()
    owner_id = _user_id("admin")
    agent_id = _create_agent_row(
        user_id=owner_id,
        name="Ticket Legacy Widget Agent",
        status=AgentStatus.PUBLISHED,
        widget_enabled=True,
    )
    guest_headers = _mint_legacy_widget_guest_token(user_id=owner_id, agent_id=agent_id)
    created = _create_widget_task(guest_headers, agent_id)
    assert created.status_code == 200, created.text
    uploaded = client.post(
        "/api/widget/files/upload",
        headers=guest_headers,
        data={"task_type": "task", "task_id": str(created.json()["task_id"])},
        files={"file": ("legacy.txt", io.BytesIO(b"legacy"), "text/plain")},
    )
    assert uploaded.status_code == 200, uploaded.text
    file_id = uploaded.json()["file_id"]

    ticket = _mint_public_file_ticket(file_id, guest_headers).json()["ticket"]
    claims = jwt.decode(ticket, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
    assert "deployment_secret_sha256" not in claims["guest"]
    url = f"/api/files/public/preview/{file_id}"
    assert client.get(url, params={"ticket": ticket}).status_code == 200

    disabled = client.put(
        f"/api/agents/{agent_id}", headers=headers, json={"widget_enabled": False}
    )
    assert disabled.status_code == 200, disabled.text
    revoked = client.get(url, params={"ticket": ticket})
    assert revoked.status_code == 403, revoked.text
    assert revoked.json()["detail"] == "Widget is unavailable"


def _logo_data_url(payload: bytes = b"fake-logo-bytes") -> str:
    return "data:image/png;base64," + base64.b64encode(payload).decode()


@pytest.fixture
def logo_uploads_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
    """Isolate agent logo reads/writes to a temp dir instead of the real uploads root."""
    monkeypatch.setattr(agents_api, "get_uploads_dir", lambda: tmp_path)
    return tmp_path


def test_logo_reupload_gets_a_fresh_url_and_removes_the_old_file(
    logo_uploads_dir: Path,
) -> None:
    """A re-uploaded logo must change logo_url (#975): the old fix saved every
    logo under the same deterministic filename, so browsers kept serving the
    stale cached image after an update even though the file on disk changed."""
    headers = _admin_headers()
    agent_id = _create_agent(headers)

    first = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"logo_base64": _logo_data_url(b"first")},
    )
    assert first.status_code == 200, first.text
    first_logo_url = first.json()["logo_url"]
    assert first_logo_url
    first_path = logo_uploads_dir / first_logo_url.removeprefix("/uploads/")
    assert first_path.is_file()

    second = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"logo_base64": _logo_data_url(b"second")},
    )
    assert second.status_code == 200, second.text
    second_logo_url = second.json()["logo_url"]

    assert second_logo_url and second_logo_url != first_logo_url
    assert not first_path.exists(), "old logo file should be cleaned up"
    assert (logo_uploads_dir / second_logo_url.removeprefix("/uploads/")).is_file()


def test_clearing_logo_with_empty_string_nulls_url_and_deletes_file(
    logo_uploads_dir: Path,
) -> None:
    """logo_base64="" (vs. omitted, meaning "no change") must clear an
    existing logo end-to-end (#976)."""
    headers = _admin_headers()
    agent_id = _create_agent(headers)

    uploaded = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"logo_base64": _logo_data_url()},
    )
    assert uploaded.status_code == 200, uploaded.text
    logo_url = uploaded.json()["logo_url"]
    logo_path = logo_uploads_dir / logo_url.removeprefix("/uploads/")
    assert logo_path.is_file()

    cleared = client.put(
        f"/api/agents/{agent_id}",
        headers=headers,
        json={"logo_base64": ""},
    )
    assert cleared.status_code == 200, cleared.text
    assert cleared.json()["logo_url"] is None
    assert not logo_path.exists()


def test_delete_logo_removes_a_file_inside_the_uploads_root(
    logo_uploads_dir: Path,
) -> None:
    logo_dir = logo_uploads_dir / "agent_logos"
    logo_dir.mkdir(parents=True)
    logo_file = logo_dir / "agent_1_abcd1234.png"
    logo_file.write_bytes(b"fake")

    agents_api._delete_logo("/uploads/agent_logos/agent_1_abcd1234.png")

    assert not logo_file.exists()


def test_delete_logo_refuses_a_path_traversal_attempt(
    logo_uploads_dir: Path,
) -> None:
    """A logo_url escaping the uploads root (e.g. via "..") must be refused
    rather than deleting whatever it resolves to outside that root."""
    outside_file = logo_uploads_dir.parent / "outside-secret.txt"
    outside_file.write_text("do not delete me")

    try:
        agents_api._delete_logo("/uploads/../" + outside_file.name)
        assert outside_file.exists()
    finally:
        outside_file.unlink(missing_ok=True)


class TestDeleteAgent:
    """DELETE /api/agents/{agent_id} - remove an agent."""

    def test_rejects_visible_manager_and_worker_references(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        headers = _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(
            user_id=owner_id,
            name="Referenced Agent",
            status=AgentStatus.PUBLISHED,
        )
        alternate_manager_id = _create_agent_row(
            user_id=owner_id,
            name="Alternate Manager",
            status=AgentStatus.PUBLISHED,
        )

        db = _direct_db_session()
        try:
            manager_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Manager Reference",
                manager_agent_id=target_id,
                status="draft",
            )
            worker_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Worker Reference",
                manager_agent_id=alternate_manager_id,
                status="draft",
            )
            archived_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Archived Reference",
                manager_agent_id=target_id,
                status="archived",
            )
            db.add_all([manager_workforce, worker_workforce, archived_workforce])
            db.flush()
            db.add(
                WorkforceAgent(
                    workforce_id=worker_workforce.id,
                    agent_id=target_id,
                    assignment_instructions="Handle delegated work.",
                    source_type="existing",
                    enabled=True,
                    sort_order=0,
                )
            )
            db.add(
                WorkforceRun(
                    workforce_id=worker_workforce.id,
                    user_id=owner_id,
                    status="completed",
                    snapshot={"version": 1},
                )
            )
            db.commit()
            manager_workforce_id = int(manager_workforce.id)
            worker_workforce_id = int(worker_workforce.id)
            archived_workforce_id = int(archived_workforce.id)
        finally:
            db.close()

        logo_calls: list[str] = []
        cache_calls: list[tuple[object, ...]] = []
        monkeypatch.setattr("xagent.web.api.agents._delete_logo", logo_calls.append)
        monkeypatch.setattr(
            "xagent.web.services.agent_management.invalidate_agent_cache",
            lambda *args: cache_calls.append(args),
        )
        monkeypatch.setattr(
            "xagent.web.services.agent_store.invalidate_agent_cache",
            lambda *args: cache_calls.append(args),
        )

        response = client.delete(f"/api/agents/{target_id}", headers=headers)

        assert response.status_code == 409, response.text
        assert response.json() == {
            "detail": {
                "code": "agent_in_use_by_workforce",
                "message": "Agent is used by one or more workforces.",
                "references": [
                    {
                        "workforce_id": manager_workforce_id,
                        "name": "Manager Reference",
                        "status": "draft",
                        "roles": ["manager"],
                        "can_edit": True,
                        "can_discard": True,
                    },
                    {
                        "workforce_id": worker_workforce_id,
                        "name": "Worker Reference",
                        "status": "draft",
                        "roles": ["worker"],
                        "can_edit": True,
                        "can_discard": False,
                    },
                    {
                        "workforce_id": archived_workforce_id,
                        "name": "Archived Reference",
                        "status": "archived",
                        "roles": ["manager"],
                        "can_edit": False,
                        "can_discard": False,
                    },
                ],
                "has_hidden_references": False,
            }
        }
        assert logo_calls == []
        assert cache_calls == []

        db = _direct_db_session()
        try:
            assert db.get(Agent, target_id) is not None
            assert (
                db.query(WorkforceAgent)
                .filter(
                    WorkforceAgent.workforce_id == worker_workforce_id,
                    WorkforceAgent.agent_id == target_id,
                )
                .one_or_none()
                is not None
            )
        finally:
            db.close()

    def test_hidden_only_reference_returns_sanitized_conflict(self) -> None:
        _admin_headers()
        bob_headers = _register_second_user("bob", "bobpass1")
        admin_id = _user_id("admin")
        bob_id = _user_id("bob")
        target_id = _create_agent_row(
            user_id=bob_id,
            name="Bob Referenced Agent",
            status=AgentStatus.PUBLISHED,
        )

        db = _direct_db_session()
        try:
            hidden_workforce = Workforce(
                owner_user_id=admin_id,
                scope_type="user",
                scope_id=str(admin_id),
                name="Hidden Workforce Name",
                manager_agent_id=target_id,
                status="draft",
            )
            db.add(hidden_workforce)
            db.commit()
            hidden_workforce_id = int(hidden_workforce.id)
        finally:
            db.close()

        response = client.delete(f"/api/agents/{target_id}", headers=bob_headers)

        assert response.status_code == 409, response.text
        assert response.json() == {
            "detail": {
                "code": "agent_in_use_by_workforce",
                "message": "Agent is used by one or more workforces.",
                "references": [],
                "has_hidden_references": True,
            }
        }
        assert "Hidden Workforce Name" not in response.text
        assert str(hidden_workforce_id) not in response.text

        db = _direct_db_session()
        try:
            assert db.get(Agent, target_id) is not None
        finally:
            db.close()

    def test_empty_workforce_reference_state_has_no_conflict(self) -> None:
        _admin_headers()
        owner_id = _user_id("admin")

        db = _direct_db_session()
        try:
            actor = db.query(User).filter(User.id == owner_id).one()

            conflict = AgentManagementService(db)._workforce_conflict(
                actor=actor,
                agent_id=999_999,
            )

            assert conflict is None
        finally:
            db.close()

    def test_reference_snapshot_classifies_policy_visibility_in_one_statement(
        self,
    ) -> None:
        _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Snapshot Target")

        db = _direct_db_session()
        try:
            actor = db.query(User).filter(User.id == owner_id).one()
            visible_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Policy Visible",
                manager_agent_id=target_id,
                status="draft",
            )
            hidden_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Policy Hidden",
                manager_agent_id=target_id,
                status="draft",
            )
            db.add_all([visible_workforce, hidden_workforce])
            db.commit()
            visible_workforce_id = int(visible_workforce.id)
            hidden_workforce_id = int(hidden_workforce.id)

            class NameVisibilityPolicy(WorkforcePolicy):
                filter_calls = 0

                def filter_visible_workforces(
                    self,
                    db: Any,
                    user: User,
                    query: Any,
                ) -> Any:
                    del db, user
                    self.filter_calls += 1
                    return query.filter(Workforce.name == "Policy Visible")

            policy = NameVisibilityPolicy()
            set_workforce_policy(policy)
            statements: list[str] = []
            engine = db.get_bind()

            def record_statement(
                _connection: Any,
                _cursor: Any,
                statement: str,
                _parameters: Any,
                _context: Any,
                _executemany: bool,
            ) -> None:
                statements.append(statement)

            event.listen(engine, "before_cursor_execute", record_statement)
            try:
                snapshot = AgentManagementService(db)._workforce_reference_snapshot(
                    actor=actor,
                    agent_id=target_id,
                )
            finally:
                event.remove(engine, "before_cursor_execute", record_statement)

            snapshot_by_id = {
                reference.workforce_id: reference for reference in snapshot
            }
            assert policy.filter_calls == 1
            assert len(statements) == 1
            assert snapshot_by_id[visible_workforce_id].is_visible is True
            assert snapshot_by_id[hidden_workforce_id].is_visible is False
        finally:
            db.close()

    def test_workforce_conflict_requires_blocker_evidence(self) -> None:
        with pytest.raises(ValueError, match="blocker evidence"):
            AgentWorkforceConflictError((), has_hidden_references=False)

    def test_visible_workforce_conflict_requires_at_least_one_role(self) -> None:
        with pytest.raises(ValueError, match="at least one role"):
            AgentWorkforceConflictError(
                (
                    AgentWorkforceReference(
                        workforce_id=7,
                        name="Invalid reference",
                        status="draft",
                        roles=(),
                        can_edit=True,
                        can_discard=False,
                    ),
                ),
                has_hidden_references=False,
            )

    def test_reference_marks_draft_undiscardable_when_generated_manager_is_shared(
        self,
    ) -> None:
        headers = _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(
            user_id=owner_id,
            name="Referenced Worker",
            status=AgentStatus.PUBLISHED,
        )
        generated_manager_id = _create_agent_row(
            user_id=owner_id,
            name="Shared Generated Manager",
            status=AgentStatus.PUBLISHED,
            origin=AgentOrigin.WORKFORCE_GENERATED_MANAGER.value,
        )

        db = _direct_db_session()
        try:
            referenced_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Referenced Draft",
                manager_agent_id=generated_manager_id,
                status="draft",
            )
            other_workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Other Manager Reference",
                manager_agent_id=generated_manager_id,
                status="draft",
            )
            db.add_all([referenced_workforce, other_workforce])
            db.flush()
            db.add(
                WorkforceAgent(
                    workforce_id=int(referenced_workforce.id),
                    agent_id=target_id,
                    assignment_instructions="Handle delegated work.",
                    source_type="existing",
                    enabled=True,
                    sort_order=0,
                )
            )
            db.commit()
            referenced_workforce_id = int(referenced_workforce.id)
        finally:
            db.close()

        response = client.delete(f"/api/agents/{target_id}", headers=headers)

        assert response.status_code == 409, response.text
        references = response.json()["detail"]["references"]
        assert references == [
            {
                "workforce_id": referenced_workforce_id,
                "name": "Referenced Draft",
                "status": "draft",
                "roles": ["worker"],
                "can_edit": True,
                "can_discard": False,
            }
        ]

    def test_disappearing_worker_reference_is_gone_before_conflict_classification(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        headers = _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Racing Worker")
        manager_id = _create_agent_row(user_id=owner_id, name="Race Manager")

        setup_db = _direct_db_session()
        try:
            workforce = Workforce(
                owner_user_id=owner_id,
                scope_type="user",
                scope_id=str(owner_id),
                name="Disappearing Worker Reference",
                manager_agent_id=manager_id,
                status="draft",
            )
            setup_db.add(workforce)
            setup_db.flush()
            setup_db.add(
                WorkforceAgent(
                    workforce_id=int(workforce.id),
                    agent_id=target_id,
                    assignment_instructions="Race with Agent deletion.",
                    source_type="existing",
                    enabled=True,
                    sort_order=0,
                )
            )
            setup_db.commit()
            workforce_id = int(workforce.id)
        finally:
            setup_db.close()

        original_snapshot = AgentManagementService._workforce_reference_snapshot

        def snapshot_then_discard(
            service: AgentManagementService,
            *,
            actor: User,
            agent_id: int,
        ):
            snapshot = original_snapshot(service, actor=actor, agent_id=agent_id)
            discard_db = _direct_db_session()
            try:
                discard_actor = discard_db.query(User).filter(User.id == owner_id).one()
                discard_draft_workforce(
                    discard_db,
                    discard_actor,
                    discard_db.get(Workforce, workforce_id),
                )
            finally:
                discard_db.close()
            return snapshot

        monkeypatch.setattr(
            AgentManagementService,
            "_workforce_reference_snapshot",
            snapshot_then_discard,
        )

        response = client.delete(f"/api/agents/{target_id}", headers=headers)

        assert response.status_code == 200, response.text
        assert response.json() == {"message": "Agent deleted successfully"}

        verify_db = _direct_db_session()
        try:
            assert verify_db.get(Workforce, workforce_id) is None
            assert verify_db.get(Agent, target_id) is None
        finally:
            verify_db.close()

    def test_maps_commit_time_fk_race_after_rollback(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Racing Agent")

        db = _direct_db_session()
        try:
            actor = db.query(User).filter(User.id == owner_id).one()
            service = AgentManagementService(db)
            conflicts = iter(
                [
                    None,
                    AgentWorkforceConflictError(
                        (),
                        has_hidden_references=True,
                    ),
                ]
            )
            monkeypatch.setattr(
                service,
                "_workforce_conflict",
                lambda **_kwargs: next(conflicts),
            )
            monkeypatch.setattr(
                db,
                "commit",
                lambda: (_ for _ in ()).throw(
                    IntegrityError(
                        "DELETE FROM agents WHERE id = ?",
                        {"id": target_id},
                        RuntimeError("raw fk constraint details"),
                    )
                ),
            )

            with pytest.raises(AgentWorkforceConflictError) as exc_info:
                service.delete_agent(actor=actor, agent_id=target_id)

            assert "raw fk constraint details" not in str(exc_info.value)
            assert db.get(Agent, target_id) is not None
        finally:
            db.close()

    def test_unrelated_integrity_error_is_not_mapped_to_workforce_conflict(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Unrelated Error Agent")

        db = _direct_db_session()
        try:
            actor = db.query(User).filter(User.id == owner_id).one()
            service = AgentManagementService(db)
            monkeypatch.setattr(
                service,
                "_workforce_conflict",
                lambda **_kwargs: None,
            )
            raw_error = IntegrityError(
                "DELETE FROM agents WHERE id = ?",
                {"id": target_id},
                RuntimeError("unrelated integrity failure"),
            )
            monkeypatch.setattr(
                db,
                "commit",
                lambda: (_ for _ in ()).throw(raw_error),
            )

            with pytest.raises(IntegrityError) as exc_info:
                service.delete_agent(actor=actor, agent_id=target_id)

            assert exc_info.value is raw_error
            assert db.get(Agent, target_id) is not None
        finally:
            db.close()

    def test_unexpected_delete_failure_returns_structured_sanitized_error(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        headers = _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Failing Agent")

        def fail_delete(
            _service: AgentManagementService,
            *,
            actor: User,
            agent_id: int,
        ) -> None:
            del actor, agent_id
            raise RuntimeError("sensitive database detail")

        monkeypatch.setattr(AgentManagementService, "delete_agent", fail_delete)

        response = client.delete(f"/api/agents/{target_id}", headers=headers)

        assert response.status_code == 500, response.text
        assert response.json() == {
            "detail": {
                "code": "agent_delete_failed",
                "message": "Failed to delete agent",
            }
        }
        assert "sensitive database detail" not in response.text

    def test_logo_and_cache_cleanup_observe_committed_delete(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        headers = _admin_headers()
        owner_id = _user_id("admin")
        target_id = _create_agent_row(user_id=owner_id, name="Cleanup Agent")
        logo_url = f"/uploads/agent_logos/agent_{target_id}.png"

        db = _direct_db_session()
        try:
            agent = db.get(Agent, target_id)
            assert agent is not None
            agent.logo_url = logo_url
            db.commit()
        finally:
            db.close()

        cleanup_events: list[str] = []

        def assert_committed(event: str) -> None:
            check_db = _direct_db_session()
            try:
                assert check_db.get(Agent, target_id) is None
            finally:
                check_db.close()
            cleanup_events.append(event)

        monkeypatch.setattr(
            "xagent.web.api.agents._delete_logo",
            lambda value: (
                assert_committed("logo")
                if value == logo_url
                else pytest.fail("unexpected logo URL")
            ),
        )
        monkeypatch.setattr(
            "xagent.web.services.agent_management.invalidate_agent_cache",
            lambda *_args: assert_committed("cache"),
        )
        monkeypatch.setattr(
            "xagent.web.services.agent_store.invalidate_agent_cache",
            lambda *_args: assert_committed("cache"),
        )

        response = client.delete(f"/api/agents/{target_id}", headers=headers)

        assert response.status_code == 200, response.text
        assert sorted(cleanup_events) == ["cache", "logo"]

    def test_with_tasks_keeps_tasks_and_nulls_agent_id(self):
        headers = _admin_headers()
        agent_id = _create_agent(headers)
        client.post(f"/api/agents/{agent_id}/api-key", headers=headers)

        db = _direct_db_session()
        try:
            admin_user = db.query(User).filter(User.username == "admin").first()
            assert admin_user is not None
            task = Task(
                user_id=admin_user.id,
                title="task tied to agent",
                description="task tied to agent",
                status=TaskStatus.PENDING,
                agent_id=agent_id,
            )
            db.add(task)
            db.commit()
            db.refresh(task)
            task_id = task.id
        finally:
            db.close()

        delete_resp = client.delete(f"/api/agents/{agent_id}", headers=headers)
        assert delete_resp.status_code == 200, delete_resp.text

        db = _direct_db_session()
        try:
            task = db.query(Task).filter(Task.id == task_id).first()
            assert task is not None
            assert task.agent_id is None
            assert (
                db.query(AgentApiKey).filter(AgentApiKey.agent_id == agent_id).all()
                == []
            )
        finally:
            db.close()


def test_admin_can_read_other_users_agent_detail():
    """管理员只读查看普通用户的 agent 详情。"""
    admin = _admin_headers()
    bob = _register_second_user("bob", "bobpass1")

    created = client.post(
        "/api/agents",
        headers=bob,
        json={
            "name": "Bob Agent",
            "instructions": "hi",
            "tool_categories": ["mcp:foo"],
        },
    )
    assert created.status_code == 200, created.text
    agent_id = created.json()["id"]

    resp = client.get(f"/api/agents/{agent_id}", headers=admin)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert "mcp:foo" in body["tool_categories"]
    # Admin sees it read-only: writes stay owner-only, so the builder must lock
    # instead of letting a save fail with "Agent not found".
    assert body["readonly"] is True
    assert body["can_edit"] is False

    # The owner still gets an editable detail.
    owner_resp = client.get(f"/api/agents/{agent_id}", headers=bob)
    assert owner_resp.status_code == 200, owner_resp.text
    assert owner_resp.json()["readonly"] is False
    assert owner_resp.json()["can_edit"] is True


def test_non_admin_cannot_read_other_users_agent_detail():
    """普通用户读别人 agent 仍 404,不泄露存在性。"""
    _admin_headers()
    bob = _register_second_user("bob", "bobpass1")
    carol = _register_second_user("carol", "carolpass1")

    created = client.post(
        "/api/agents", headers=bob, json={"name": "Bob Agent", "instructions": "hi"}
    )
    agent_id = created.json()["id"]

    resp = client.get(f"/api/agents/{agent_id}", headers=carol)
    assert resp.status_code == 404


def test_policy_shared_non_admin_reads_agent_detail_read_only():
    """非管理员通过 policy 只读共享,可读详情且被锁为只读(不再 404)。"""
    _admin_headers()
    _register_second_user("bob", "bobpass1")
    bob_id = _user_id("bob")

    agent_id = _create_agent_row(user_id=bob_id, name="Bob Shared")
    # carol 不拥有该 agent,但 policy 把它列进了 carol 的可见列表。
    carol = _register_second_user("carol", "carolpass1")
    set_workforce_policy(_VisibleAgentPolicy({agent_id}))

    resp = client.get(f"/api/agents/{agent_id}", headers=carol)
    assert resp.status_code == 200, resp.text
    body = resp.json()
    assert body["readonly"] is True
    assert body["can_edit"] is False


def _set_preferences(user_id: int, preferences: dict[str, Any]) -> None:
    db = _direct_db_session()
    try:
        user = db.get(User, user_id)
        assert user is not None
        user.preferences = preferences
        db.commit()
    finally:
        db.close()


class TestApplyUserVoice:
    """Unit tests for apply_user_voice - the onboarding Launch-step voice
    preference's system-prompt injection, alongside enhance_system_prompt_with_kb."""

    def test_no_voice_returns_prompt_unchanged(self):
        assert (
            _agent_prompt_services.apply_user_voice("Be helpful.", None)
            == "Be helpful."
        )

    def test_unrecognized_voice_value_returns_prompt_unchanged(self):
        assert (
            _agent_prompt_services.apply_user_voice("Be helpful.", "sarcastic")
            == "Be helpful."
        )

    def test_list_voice_value_does_not_raise_and_returns_prompt_unchanged(self):
        # The JSON `preferences` column has no nested-type constraint, so a
        # corrupted/hand-edited row could hold a list here. A list is truthy
        # but unhashable - `dict.get` on it would raise TypeError instead of
        # degrading to plain output.
        assert (
            _agent_prompt_services.apply_user_voice("Be helpful.", ["concise"])
            == "Be helpful."
        )

    def test_dict_voice_value_does_not_raise_and_returns_prompt_unchanged(self):
        assert (
            _agent_prompt_services.apply_user_voice("Be helpful.", {"voice": "concise"})
            == "Be helpful."
        )

    def test_known_voice_appends_output_voice_section(self):
        result = _agent_prompt_services.apply_user_voice("Be helpful.", "concise")

        assert result.startswith("Be helpful.\n\n## OUTPUT VOICE\n")
        assert "As short as possible" in result

    def test_none_system_prompt_with_voice_omits_leading_blank_lines(self):
        result = _agent_prompt_services.apply_user_voice(None, "warm")

        assert result.startswith("## OUTPUT VOICE\n")

    def test_every_valid_voice_has_a_matching_instruction(self):
        # Guards the module-level consistency assertion in agents.py itself
        # (VALID_USER_VOICES vs _VOICE_INSTRUCTIONS) with an explicit test,
        # so a future divergence fails a test, not just an import-time assert.
        assert set(agents_api._VOICE_INSTRUCTIONS) == agents_api.VALID_USER_VOICES


class TestVoiceFromRuntimeUser:
    """Unit tests for voice_from_runtime_user - extracts the voice
    preference without issuing a new query, from whichever runtime-user
    shape a caller already has in hand (see apply_user_voice's docstring
    for why a fresh query is deliberately avoided here)."""

    def test_none_runtime_user_returns_none(self):
        assert _agent_prompt_services.voice_from_runtime_user(None) is None

    def test_runtime_user_fields_with_voice_set(self):
        runtime_user = RuntimeUserFields(id=1, is_admin=False, voice="friendly")
        assert (
            _agent_prompt_services.voice_from_runtime_user(runtime_user) == "friendly"
        )

    def test_runtime_user_fields_with_no_voice(self):
        runtime_user = RuntimeUserFields(id=1, is_admin=False)
        assert _agent_prompt_services.voice_from_runtime_user(runtime_user) is None

    def test_full_user_orm_row_reads_from_preferences(self):
        _admin_headers()
        user_id = _user_id("admin")
        _set_preferences(user_id, {"voice": "playful"})

        db = _direct_db_session()
        try:
            user = db.get(User, user_id)
            assert _agent_prompt_services.voice_from_runtime_user(user) == "playful"
        finally:
            db.close()

    def test_full_user_orm_row_with_no_preferences(self):
        _admin_headers()
        user_id = _user_id("admin")
        _set_preferences(user_id, {})

        db = _direct_db_session()
        try:
            user = db.get(User, user_id)
            assert _agent_prompt_services.voice_from_runtime_user(user) is None
        finally:
            db.close()

    def test_unexpected_shape_does_not_raise(self):
        # A caller passing something that's neither RuntimeUserFields nor a
        # real User row (e.g. a mismatched test double) must degrade to "no
        # voice" rather than crash agent construction over a cosmetic
        # preference - see test_agent_manager_reconstruction.py's
        # test_admin_task_uses_task_owner_workspace_dirs, which broke this
        # way when apply_user_voice used to query on its own.
        class _NotAUser:
            pass

        assert _agent_prompt_services.voice_from_runtime_user(_NotAUser()) is None