diff --git a/autobot-backend/api/agent_org.py b/autobot-backend/api/agent_org.py index 52844aba97..0e76f8f845 100644 --- a/autobot-backend/api/agent_org.py +++ b/autobot-backend/api/agent_org.py @@ -36,6 +36,7 @@ from autobot_shared.error_boundaries import ErrorCategory, with_error_handling from autobot_shared.logging_manager import get_logger from llc.services.agent_hire_service import HireApprovalRequiredError +from services.agent_activity_feed import get_agent_feeds, with_feed from services.agent_org_service import AgentOrgService from services.delegation_service import DelegationService from user_management.services import TenantContext @@ -86,8 +87,6 @@ def _fallback_agents_from_registry() -> List[Dict[str, Any]]: "status": profile.availability_status, # #17514: the registry counts no tasks, so its success_rate is a starting # default until tasks run; activity fields are not reported (None). - "recentTasks": [], - "activityTimeline": [], } ) return agents @@ -150,7 +149,9 @@ async def get_agents_status( # The in-memory registry holds platform agents only (no company), which every # signed-in caller may see (#19246), so this fallback needs no tenant filter. logger.debug("PG unavailable — returning in-memory agents for /agents/status (#10511)") - agents = _fallback_agents_from_registry() + fallback = _fallback_agents_from_registry() + feeds = await get_agent_feeds([a["id"] for a in fallback]) # #21270: same feed as the PG path + agents = [with_feed(a, feeds[a["id"]]) for a in fallback] items = [AgentStatusItem(**a) for a in agents] return AgentStatusListResponse(agents=items, total=len(items)) diff --git a/autobot-backend/api/heartbeat.py b/autobot-backend/api/heartbeat.py index 254f588a96..7845972692 100644 --- a/autobot-backend/api/heartbeat.py +++ b/autobot-backend/api/heartbeat.py @@ -17,7 +17,12 @@ from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.orm import selectinload -from api.schemas_system import ( +from api.heartbeat_responses import ( + _run_to_response, + _state_to_response, + _wakeup_to_response, +) +from api.schemas_heartbeat import ( AgentErrorRequest, AgentPauseRequest, AgentRecoverRequest, @@ -25,10 +30,11 @@ AgentTerminateRequest, HeartbeatConfigRequest, HeartbeatConfigResponse, +) +from api.schemas_system import ( HeartbeatRunResponse, HeartbeatTriggerResponse, HeartbeatWakeupQueuedResponse, - RunEventResponse, WakeupRequestCreate, WakeupRequestResponse, ) @@ -38,15 +44,18 @@ from autobot_shared.auth.permissions import is_admin_role from autobot_shared.error_boundaries import ErrorCategory, with_error_handling from autobot_shared.logging_manager import get_logger +from autobot_shared.principal import resolve_principal_id from autobot_shared.time_utils import now_utc +from llc.services.member_standing import display_name_of from models.heartbeat import ( AgentRuntimeState, AgentWakeupRequest, HeartbeatRun, - HeartbeatRunEvent, HeartbeatStatus, WakeupTrigger, ) +from services.audit.audit import record_committed +from services.audit.taxonomy import AuditAction, AuditCategory, AuditEvent, action_name from services.heartbeat_scheduler import HeartbeatScheduler, _get_or_create_state logger = get_logger(__name__) @@ -85,7 +94,7 @@ async def get_heartbeat_config( """Return heartbeat config and runtime state for an agent (#1407).""" state = await _get_or_create_state(session, agent_id) await session.commit() - return _state_to_response(state) + return await _state_response(session, state) @router.put("/{agent_id}/config", response_model=HeartbeatConfigResponse) @@ -120,7 +129,7 @@ async def update_config( await scheduler.disable_agent(agent_id) elif body.heartbeat_enabled and was_enabled: await scheduler.enable_agent(agent_id, body.heartbeat_interval_seconds) - return _state_to_response(state) + return await _state_response(session, state) @router.patch("/{agent_id}/session", response_model=HeartbeatConfigResponse) @@ -145,7 +154,7 @@ async def update_session( state.extra = body["extra"] await session.commit() await session.refresh(state) - return _state_to_response(state) + return await _state_response(session, state) @router.get("/{agent_id}/runs", response_model=List[HeartbeatRunResponse]) @@ -262,6 +271,33 @@ async def trigger_manual( return {"agent_id": agent_id, "status": "triggered"} +def _actor_id(user: Any) -> str: + """The verified caller's principal id, from the auth dependency only (#21136).""" + claims = user if isinstance(user, dict) else vars(user) + return resolve_principal_id(claims) or str(claims.get("username") or "unknown") + + +async def _audit_control(actor: str, action: AuditAction, agent_id: str, reason: str | None = None) -> None: + """Durably record who paused, resumed or terminated an agent BEFORE the change (#21136, #20557). + + Resume clears the row, so this event is the only record of the resumer: it is the awaited, + bounded ``record_committed`` write, not the fire-and-forget bus. As on the secrets routes + (``api/secrets_audit.py``), a write that fails (returns False) raises 503 and nothing is changed. + """ + recorded = await record_committed( + AuditEvent( + category=AuditCategory.SECURITY, + action=action_name(action), + actor_id=actor, + resource_type="agent_heartbeat", + resource_id=agent_id, + metadata={"reason": reason} if reason else None, + ) + ) + if not recorded: + raise HTTPException(status_code=503, detail="Audit trail unavailable; nothing was changed") + + @router.post("/{agent_id}/pause", response_model=HeartbeatConfigResponse) @with_error_handling( category=ErrorCategory.SERVER_ERROR, @@ -284,16 +320,19 @@ async def pause_agent( if state.status == HeartbeatStatus.TERMINATED.value: raise HTTPException(status_code=409, detail="Agent is terminated; cannot pause") if state.status == HeartbeatStatus.PAUSED.value: - return _state_to_response(state) + return await _state_response(session, state) + # The verified caller is the only actor; body.paused_by is never trusted (#21136). + actor = _actor_id(_user) + await _audit_control(actor, AuditAction.AGENT_PAUSE, agent_id, body.reason) state.status = HeartbeatStatus.PAUSED.value state.paused_reason = body.reason state.paused_at = now_utc() - state.paused_by = body.paused_by or "user" + state.paused_by = actor await session.commit() await session.refresh(state) await scheduler.disable_agent(agent_id) logger.info("Agent %s paused by %s: %s", agent_id, state.paused_by, state.paused_reason) - return _state_to_response(state) + return await _state_response(session, state) async def _request_skill_approval_for_resume(agent_id: str, paused_by: str, requested_by: str) -> str: @@ -315,6 +354,37 @@ async def _request_skill_approval_for_resume(agent_id: str, paused_by: str, requ return result.approval_id or "" +def _require_resumable(state: AgentRuntimeState) -> None: + """Raise 409 unless the agent is PAUSED.""" + if state.status == HeartbeatStatus.TERMINATED.value: + raise HTTPException(status_code=409, detail="Agent is terminated; cannot resume") + if state.status != HeartbeatStatus.PAUSED.value: + raise HTTPException(status_code=409, detail=f"Agent is not paused (status={state.status})") + + +async def _queue_system_pause_resume(agent_id: str, paused_by: str, user: Any) -> Any: + """A 202 response when a non-admin resumes a system-paused agent (GH#8734), else None. + + ``user`` is a dict with ``role`` and ``username`` keys, or an object with those attributes. + """ + from fastapi.responses import JSONResponse + + if not paused_by.startswith("system:"): + return None + claims = user if isinstance(user, dict) else vars(user) + if is_admin_role(claims.get("role", "")): + return None + approval_id = await _request_skill_approval_for_resume(agent_id, paused_by, claims.get("username", "")) + return JSONResponse( + status_code=202, + content={ + "approval_id": approval_id, + "status": "pending", + "message": f"Agent was paused by {paused_by}; resume request queued for admin approval", + }, + ) + + @router.post("/{agent_id}/resume", response_model=HeartbeatConfigResponse) @with_error_handling( category=ErrorCategory.SERVER_ERROR, @@ -337,29 +407,14 @@ async def resume_agent( User-paused agents can be resumed by any authenticated user. DISABLED and TERMINATED agents are not affected — use PUT /config instead. """ - from fastapi.responses import JSONResponse - state = await _get_or_create_state(session, agent_id) - if state.status == HeartbeatStatus.TERMINATED.value: - raise HTTPException(status_code=409, detail="Agent is terminated; cannot resume") - if state.status != HeartbeatStatus.PAUSED.value: - raise HTTPException(status_code=409, detail=f"Agent is not paused (status={state.status})") - # System-enforced pauses use the SkillApproval governance workflow (GH#8734). - # _user is always a Dict with keys "role" (str) and "username" (str). - paused_by = state.paused_by or "" - if paused_by.startswith("system:"): - username = _user.get("username", "") if isinstance(_user, dict) else getattr(_user, "username", "") - user_role = _user.get("role", "") if isinstance(_user, dict) else getattr(_user, "role", "") - if not is_admin_role(user_role): - approval_id = await _request_skill_approval_for_resume(agent_id, paused_by, username) - return JSONResponse( - status_code=202, - content={ - "approval_id": approval_id, - "status": "pending", - "message": (f"Agent was paused by {paused_by}; resume request queued for admin approval"), - }, - ) + _require_resumable(state) + queued = await _queue_system_pause_resume(agent_id, state.paused_by or "", _user) + if queued is not None: + return queued + # No resumer column on the row (would need a migration); this event names the caller. + resumer = _actor_id(_user) + await _audit_control(resumer, AuditAction.AGENT_RESUME, agent_id) state.status = HeartbeatStatus.ACTIVE.value state.paused_reason = None state.paused_at = None @@ -367,8 +422,8 @@ async def resume_agent( await session.commit() await session.refresh(state) await scheduler.enable_agent(agent_id, state.heartbeat_interval_seconds) - logger.info("Agent %s resumed", agent_id) - return _state_to_response(state) + logger.info("Agent %s resumed by %s", agent_id, resumer) + return await _state_response(session, state) @router.post("/{agent_id}/terminate", response_model=HeartbeatConfigResponse) @@ -391,19 +446,18 @@ async def terminate_agent( """ state = await _get_or_create_state(session, agent_id) if state.status == HeartbeatStatus.TERMINATED.value: - return _state_to_response(state) + return await _state_response(session, state) + actor = _actor_id(_user) + await _audit_control(actor, AuditAction.AGENT_TERMINATE, agent_id, body.reason) state.status = HeartbeatStatus.TERMINATED.value state.paused_reason = body.reason state.paused_at = now_utc() - # _user is always a Dict; "id" key does not exist — use "username" (P1) - state.paused_by = ( - _user.get("username", "unknown") if isinstance(_user, dict) else getattr(_user, "username", "unknown") - ) + state.paused_by = actor await session.commit() await session.refresh(state) await scheduler.disable_agent(agent_id) logger.info("Agent %s terminated: %s", agent_id, body.reason) - return _state_to_response(state) + return await _state_response(session, state) @router.post("/{agent_id}/error", response_model=HeartbeatConfigResponse) @@ -429,7 +483,7 @@ async def set_agent_error( if state.status == HeartbeatStatus.TERMINATED.value: raise HTTPException(status_code=409, detail="Agent is terminated; cannot set error state") if state.status == HeartbeatStatus.ERROR.value: - return _state_to_response(state) + return await _state_response(session, state) state.status = HeartbeatStatus.ERROR.value state.error_detail = body.error_detail state.error_at = now_utc() @@ -438,7 +492,7 @@ async def set_agent_error( await session.refresh(state) await scheduler.disable_agent(agent_id) logger.info("Agent %s entered error state: code=%s detail=%s", agent_id, state.error_code, state.error_detail) - return _state_to_response(state) + return await _state_response(session, state) @router.post("/{agent_id}/recover", response_model=HeartbeatConfigResponse) @@ -470,73 +524,22 @@ async def recover_agent( await session.refresh(state) await scheduler.enable_agent(agent_id, state.heartbeat_interval_seconds) logger.info("Agent %s recovered from error state", agent_id) - return _state_to_response(state) - - -def _state_to_response(state: AgentRuntimeState) -> HeartbeatConfigResponse: - """Convert AgentRuntimeState ORM row to Pydantic response (#1407, GH#6476, MVA-1411).""" - return HeartbeatConfigResponse( - agent_id=state.agent_id, - heartbeat_enabled=state.heartbeat_enabled, - status=state.status, - paused_reason=state.paused_reason, - paused_at=(state.paused_at.isoformat() if state.paused_at else None), - paused_by=state.paused_by, - error_detail=state.error_detail, - error_at=(state.error_at.isoformat() if state.error_at else None), - error_code=state.error_code, - heartbeat_interval_seconds=state.heartbeat_interval_seconds, - max_run_duration_seconds=state.max_run_duration_seconds, - current_task_id=state.current_task_id, - last_heartbeat_at=(state.last_heartbeat_at.isoformat() if state.last_heartbeat_at else None), - session_params=state.session_params, - extra=state.extra, - created_at=(state.created_at.isoformat() if state.created_at else None), - updated_at=(state.updated_at.isoformat() if state.updated_at else None), - ) + return await _state_response(session, state) -def _run_to_response(run: HeartbeatRun) -> HeartbeatRunResponse: - """Convert HeartbeatRun ORM row to Pydantic response (#1407).""" - return HeartbeatRunResponse( - id=str(run.id), - agent_id=run.agent_id, - status=run.status, - trigger=run.trigger, - wakeup_context=run.wakeup_context, - started_at=(run.started_at.isoformat() if run.started_at else None), - finished_at=(run.finished_at.isoformat() if run.finished_at else None), - tokens_used=run.tokens_used, - cost_usd=run.cost_usd, - model=run.model, - provider=run.provider, - error_message=run.error_message, - created_at=(run.created_at.isoformat() if run.created_at else None), - events=[_event_to_response(e) for e in (run.events or [])], - ) - +async def _paused_by_name(session: AsyncSession, paused_by: str | None) -> str | None: + """The display name of the user whose principal id is ``paused_by``, or None (#21136). -def _event_to_response(event: HeartbeatRunEvent) -> RunEventResponse: - """Convert HeartbeatRunEvent ORM row to Pydantic response (#1407).""" - return RunEventResponse( - id=str(event.id), - event_type=event.event_type, - message=event.message, - payload=event.payload, - occurred_at=event.occurred_at, - ) + None for no actor, a ``system:*`` actor, a legacy free-text actor, or an unknown user; the + client then shows the system label or the raw value. + """ + try: + user_id = uuid.UUID(paused_by or "") + except ValueError: + return None + return await display_name_of(session, user_id) -def _wakeup_to_response(req: AgentWakeupRequest) -> WakeupRequestResponse: - """Convert AgentWakeupRequest ORM row to Pydantic response (#1407).""" - return WakeupRequestResponse( - id=str(req.id), - agent_id=req.agent_id, - priority=req.priority, - context=req.context, - reason=req.reason, - consumed=req.consumed_at is not None, - consumed_at=(req.consumed_at.isoformat() if req.consumed_at else None), - created_at=(req.created_at.isoformat() if req.created_at else None), - merged_count=req.merged_count if req.merged_count is not None else 0, - ) +async def _state_response(session: AsyncSession, state: AgentRuntimeState) -> HeartbeatConfigResponse: + """The response for ``state`` with the actor's display name resolved from the user record (#21136).""" + return _state_to_response(state, await _paused_by_name(session, state.paused_by)) diff --git a/autobot-backend/api/heartbeat_actor_21136_test.py b/autobot-backend/api/heartbeat_actor_21136_test.py new file mode 100644 index 0000000000..cededbb25e --- /dev/null +++ b/autobot-backend/api/heartbeat_actor_21136_test.py @@ -0,0 +1,132 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Pause, resume and terminate record the verified principal id (#21136).""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import HTTPException + +from api import heartbeat +from api.schemas_heartbeat import AgentPauseRequest, AgentResumeRequest, AgentTerminateRequest +from models.heartbeat import HeartbeatStatus +from services.audit.taxonomy import AuditAction, action_name + +CALLER = {"id": "principal-7", "username": "alice", "role": "admin"} + + +def _state(status, paused_by=None): + return SimpleNamespace( + status=status.value, + paused_by=paused_by, + paused_reason=None, + paused_at=None, + heartbeat_interval_seconds=60, + ) + + +@pytest.fixture +def harness(monkeypatch): + audits = [] + + async def _record(event): + audits.append({"user_id": event.actor_id, "action": event.action, "resource_id": event.resource_id}) + return True + + monkeypatch.setattr(heartbeat, "record_committed", _record) + monkeypatch.setattr(heartbeat, "_state_to_response", lambda state, *a: state) + session = MagicMock(commit=AsyncMock(), refresh=AsyncMock()) + monkeypatch.setattr(heartbeat, "_paused_by_name", AsyncMock(return_value=None)) + scheduler = MagicMock(disable_agent=AsyncMock(), enable_agent=AsyncMock()) + + def install(state): + monkeypatch.setattr(heartbeat, "_get_or_create_state", AsyncMock(return_value=state)) + + return audits, session, scheduler, install + + +@pytest.mark.asyncio +async def test_pause_records_principal_and_ignores_forged_body_actor(harness): + audits, session, scheduler, install = harness + state = _state(HeartbeatStatus.ACTIVE) + install(state) + body = AgentPauseRequest(reason="r", paused_by="system:forged") + await heartbeat.pause_agent("a1", body, session, scheduler, CALLER) + assert state.paused_by == "principal-7" + assert audits[0]["user_id"] == "principal-7" + assert audits[0]["action"] == action_name(AuditAction.AGENT_PAUSE) + assert audits[0]["resource_id"] == "a1" + + +@pytest.mark.asyncio +async def test_resume_emits_audit_event_naming_caller(harness): + audits, session, scheduler, install = harness + install(_state(HeartbeatStatus.PAUSED, paused_by="principal-1")) + await heartbeat.resume_agent("a1", AgentResumeRequest(), session, scheduler, CALLER) + assert audits[0]["user_id"] == "principal-7" + assert audits[0]["action"] == action_name(AuditAction.AGENT_RESUME) + + +@pytest.mark.asyncio +async def test_terminate_stores_principal_id_not_username(harness): + audits, session, scheduler, install = harness + state = _state(HeartbeatStatus.ACTIVE) + install(state) + await heartbeat.terminate_agent("a1", AgentTerminateRequest(reason="r"), session, scheduler, CALLER) + assert state.paused_by == "principal-7" + assert audits[0]["action"] == action_name(AuditAction.AGENT_TERMINATE) + + +def test_actor_falls_back_to_username_without_principal_claim(): + assert heartbeat._actor_id({"username": "svc"}) == "svc" + + +@pytest.mark.asyncio +async def test_event_is_written_before_the_commit(harness): + audits, session, scheduler, install = harness + install(_state(HeartbeatStatus.ACTIVE)) + session.commit.side_effect = lambda: audits.append("commit") + await heartbeat.pause_agent("a1", AgentPauseRequest(reason="r"), session, scheduler, CALLER) + assert audits[0]["action"] == action_name(AuditAction.AGENT_PAUSE) + assert audits[1] == "commit" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("route", ["pause", "resume", "terminate"]) +async def test_failed_audit_write_is_503_and_changes_nothing(harness, monkeypatch, route): + audits, session, scheduler, install = harness + monkeypatch.setattr(heartbeat, "record_committed", AsyncMock(return_value=False)) + paused = HeartbeatStatus.PAUSED if route == "resume" else HeartbeatStatus.ACTIVE + state = _state(paused, paused_by="principal-1") + before = dict(vars(state)) + install(state) + bodies = {"pause": AgentPauseRequest(), "resume": AgentResumeRequest(), "terminate": AgentTerminateRequest()} + handler = getattr(heartbeat, f"{route}_agent") + with pytest.raises(HTTPException) as exc: + await handler("a1", bodies[route], session, scheduler, CALLER) + assert exc.value.status_code == 503 + assert exc.value.detail == "Audit trail unavailable; nothing was changed" + assert vars(state) == before + session.commit.assert_not_called() + scheduler.disable_agent.assert_not_called() + scheduler.enable_agent.assert_not_called() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("actor", [None, "system:budget", "alice-legacy"]) +async def test_paused_by_name_is_none_without_a_user_id(actor): + session = MagicMock(execute=AsyncMock()) + assert await heartbeat._paused_by_name(session, actor) is None + session.execute.assert_not_called() + + +@pytest.mark.asyncio +async def test_paused_by_name_resolves_through_the_shared_helper(monkeypatch): + helper = AsyncMock(return_value="Alice A") + monkeypatch.setattr(heartbeat, "display_name_of", helper) + uid = "11111111-1111-1111-1111-111111111111" + assert await heartbeat._paused_by_name(MagicMock(), uid) == "Alice A" + helper.assert_awaited_once() diff --git a/autobot-backend/api/heartbeat_responses.py b/autobot-backend/api/heartbeat_responses.py new file mode 100644 index 0000000000..bac27d0108 --- /dev/null +++ b/autobot-backend/api/heartbeat_responses.py @@ -0,0 +1,88 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""ORM-row to response-model converters for the heartbeat API (#1407, GH#6476).""" + +from api.schemas_heartbeat import HeartbeatConfigResponse +from api.schemas_system import ( + HeartbeatRunResponse, + RunEventResponse, + WakeupRequestResponse, +) +from models.heartbeat import ( + AgentRuntimeState, + AgentWakeupRequest, + HeartbeatRun, + HeartbeatRunEvent, +) + + +def _state_to_response(state: AgentRuntimeState, paused_by_name: str | None = None) -> HeartbeatConfigResponse: + """Convert AgentRuntimeState ORM row to Pydantic response (#1407, GH#6476, MVA-1411).""" + return HeartbeatConfigResponse( + agent_id=state.agent_id, + heartbeat_enabled=state.heartbeat_enabled, + status=state.status, + paused_reason=state.paused_reason, + paused_at=(state.paused_at.isoformat() if state.paused_at else None), + paused_by=state.paused_by, + paused_by_name=paused_by_name, + error_detail=state.error_detail, + error_at=(state.error_at.isoformat() if state.error_at else None), + error_code=state.error_code, + heartbeat_interval_seconds=state.heartbeat_interval_seconds, + max_run_duration_seconds=state.max_run_duration_seconds, + current_task_id=state.current_task_id, + last_heartbeat_at=(state.last_heartbeat_at.isoformat() if state.last_heartbeat_at else None), + session_params=state.session_params, + extra=state.extra, + created_at=(state.created_at.isoformat() if state.created_at else None), + updated_at=(state.updated_at.isoformat() if state.updated_at else None), + ) + + +def _run_to_response(run: HeartbeatRun) -> HeartbeatRunResponse: + """Convert HeartbeatRun ORM row to Pydantic response (#1407).""" + return HeartbeatRunResponse( + id=str(run.id), + agent_id=run.agent_id, + status=run.status, + trigger=run.trigger, + wakeup_context=run.wakeup_context, + started_at=(run.started_at.isoformat() if run.started_at else None), + finished_at=(run.finished_at.isoformat() if run.finished_at else None), + tokens_used=run.tokens_used, + cost_usd=run.cost_usd, + model=run.model, + provider=run.provider, + error_message=run.error_message, + created_at=(run.created_at.isoformat() if run.created_at else None), + events=[_event_to_response(e) for e in (run.events or [])], + ) + + +def _event_to_response(event: HeartbeatRunEvent) -> RunEventResponse: + """Convert HeartbeatRunEvent ORM row to Pydantic response (#1407).""" + return RunEventResponse( + id=str(event.id), + event_type=event.event_type, + message=event.message, + payload=event.payload, + occurred_at=event.occurred_at, + ) + + +def _wakeup_to_response(req: AgentWakeupRequest) -> WakeupRequestResponse: + """Convert AgentWakeupRequest ORM row to Pydantic response (#1407).""" + return WakeupRequestResponse( + id=str(req.id), + agent_id=req.agent_id, + priority=req.priority, + context=req.context, + reason=req.reason, + consumed=req.consumed_at is not None, + consumed_at=(req.consumed_at.isoformat() if req.consumed_at else None), + created_at=(req.created_at.isoformat() if req.created_at else None), + merged_count=req.merged_count if req.merged_count is not None else 0, + ) diff --git a/autobot-backend/api/schemas_agent.py b/autobot-backend/api/schemas_agent.py index 60fd86b2b0..e8a2a72a24 100644 --- a/autobot-backend/api/schemas_agent.py +++ b/autobot-backend/api/schemas_agent.py @@ -1101,8 +1101,7 @@ class ChainOfCommandResponse(BaseModel): class AgentStatusItem(BaseModel): - """One agent for the Home dashboard "Agent Activity Monitor" (#10502, frontend ``Agent``). - A field the server cannot measure is None, never 0: the widget shows "not reported" (#17514).""" + """Home dashboard "Agent Activity Monitor" agent (#10502); an unmeasured field is None, never 0 (#17514, #21270).""" id: str name: str @@ -1114,8 +1113,9 @@ class AgentStatusItem(BaseModel): tasksCompleted: int | None = None uptime: int | None = None successRate: int | None = None - recentTasks: List[Dict[str, Any]] = Field(default_factory=list) - activityTimeline: List[Dict[str, Any]] = Field(default_factory=list) + recentTasks: List[Dict[str, Any]] | None = None + activityTimeline: List[Dict[str, Any]] | None = None + activityWindowStart: int | None = None # UTC ms of the timeline axis start (6 one-hour columns) class AgentStatusListResponse(BaseModel): diff --git a/autobot-backend/api/schemas_heartbeat.py b/autobot-backend/api/schemas_heartbeat.py new file mode 100644 index 0000000000..9a43a13382 --- /dev/null +++ b/autobot-backend/api/schemas_heartbeat.py @@ -0,0 +1,70 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Request and response models for the heartbeat config and agent-control routes (GH#6476, MVA-1411).""" + +from typing import Any, Dict + +from pydantic import BaseModel, Field + + +class HeartbeatConfigRequest(BaseModel): + """Request body to configure heartbeat for an agent.""" + + heartbeat_enabled: bool = False + heartbeat_interval_seconds: int = Field(default=300, ge=10) + max_run_duration_seconds: int = Field(default=600, ge=10) + + +class HeartbeatConfigResponse(BaseModel): + """Response for agent heartbeat config / runtime state (GH#6476).""" + + agent_id: str + heartbeat_enabled: bool + status: str + paused_reason: str | None = None + paused_at: str | None = None + paused_by: str | None = None + paused_by_name: str | None = Field( + default=None, description="Display name of the user in paused_by; null for system actors or unknown users." + ) + error_detail: str | None = None + error_at: str | None = None + error_code: str | None = None + heartbeat_interval_seconds: int + max_run_duration_seconds: int + current_task_id: str | None + last_heartbeat_at: str | None + session_params: Dict[str, Any] | None + extra: Dict[str, Any] | None + created_at: str | None + updated_at: str | None + + +class AgentPauseRequest(BaseModel): + """Request body for POST /heartbeat/{agent_id}/pause (GH#6476).""" + + reason: str | None = None + paused_by: str | None = Field(default=None, description="Ignored; the actor is the verified caller.") + + +class AgentResumeRequest(BaseModel): + """Request body for POST /heartbeat/{agent_id}/resume (GH#6476).""" + + +class AgentTerminateRequest(BaseModel): + """Request body for POST /heartbeat/{agent_id}/terminate (GH#6476).""" + + reason: str | None = None + + +class AgentErrorRequest(BaseModel): + """Request body for POST /heartbeat/{agent_id}/error (MVA-1411).""" + + error_detail: str | None = None + error_code: str | None = None + + +class AgentRecoverRequest(BaseModel): + """Request body for POST /heartbeat/{agent_id}/recover (MVA-1411).""" diff --git a/autobot-backend/api/schemas_system.py b/autobot-backend/api/schemas_system.py index f9757cc923..8c27c3ce60 100644 --- a/autobot-backend/api/schemas_system.py +++ b/autobot-backend/api/schemas_system.py @@ -2380,64 +2380,6 @@ class TerminalHostSelectionResponse(BaseModel): connection_info: Dict | None = Field(None, description="Connection details (host, port, username)") -class HeartbeatConfigRequest(BaseModel): - """Request body to configure heartbeat for an agent.""" - - heartbeat_enabled: bool = False - heartbeat_interval_seconds: int = Field(default=300, ge=10) - max_run_duration_seconds: int = Field(default=600, ge=10) - - -class HeartbeatConfigResponse(BaseModel): - """Response for agent heartbeat config / runtime state (GH#6476).""" - - agent_id: str - heartbeat_enabled: bool - status: str - paused_reason: str | None = None - paused_at: str | None = None - paused_by: str | None = None - error_detail: str | None = None - error_at: str | None = None - error_code: str | None = None - heartbeat_interval_seconds: int - max_run_duration_seconds: int - current_task_id: str | None - last_heartbeat_at: str | None - session_params: Dict[str, Any] | None - extra: Dict[str, Any] | None - created_at: str | None - updated_at: str | None - - -class AgentPauseRequest(BaseModel): - """Request body for POST /heartbeat/{agent_id}/pause (GH#6476).""" - - reason: str | None = None - paused_by: str | None = None - - -class AgentResumeRequest(BaseModel): - """Request body for POST /heartbeat/{agent_id}/resume (GH#6476).""" - - -class AgentTerminateRequest(BaseModel): - """Request body for POST /heartbeat/{agent_id}/terminate (GH#6476).""" - - reason: str | None = None - - -class AgentErrorRequest(BaseModel): - """Request body for POST /heartbeat/{agent_id}/error (MVA-1411).""" - - error_detail: str | None = None - error_code: str | None = None - - -class AgentRecoverRequest(BaseModel): - """Request body for POST /heartbeat/{agent_id}/recover (MVA-1411).""" - - class WakeupRequestCreate(BaseModel): """Request body to queue a wakeup for an agent.""" diff --git a/autobot-backend/llc/services/member_standing.py b/autobot-backend/llc/services/member_standing.py index 00639029ce..390b05dfe5 100644 --- a/autobot-backend/llc/services/member_standing.py +++ b/autobot-backend/llc/services/member_standing.py @@ -62,6 +62,15 @@ async def member_people( ) +async def display_name_of(session: AsyncSession, user_id: uuid.UUID) -> Optional[str]: + """The display name of one user (``display_name``, else ``username``), or ``None`` for no such user (#21136). + + The single-user form of :func:`member_people`, so a route that names one actor does not copy the lookup. + """ + names, _active = await member_people(session, [user_id]) + return names.get(user_id) + + async def viewer_standing( session: AsyncSession, company_id: uuid.UUID, viewer_id: Optional[uuid.UUID], *, platform_admin: bool ) -> Dict[str, Any]: diff --git a/autobot-backend/llc/tests/test_display_name_of_21136.py b/autobot-backend/llc/tests/test_display_name_of_21136.py new file mode 100644 index 0000000000..38ef31beb6 --- /dev/null +++ b/autobot-backend/llc/tests/test_display_name_of_21136.py @@ -0,0 +1,28 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""`display_name_of` is the single-user form of `member_people` (#21136).""" + +import uuid +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from llc.services import member_standing + + +@pytest.mark.asyncio +async def test_returns_the_resolved_name(monkeypatch): + uid = uuid.uuid4() + people = AsyncMock(return_value=({uid: "Alice A"}, {uid: True})) + monkeypatch.setattr(member_standing, "member_people", people) + assert await member_standing.display_name_of(MagicMock(), uid) == "Alice A" + people.assert_awaited_once() + assert people.await_args.args[1] == [uid] + + +@pytest.mark.asyncio +async def test_unknown_user_is_none(monkeypatch): + monkeypatch.setattr(member_standing, "member_people", AsyncMock(return_value=({}, {}))) + assert await member_standing.display_name_of(MagicMock(), uuid.uuid4()) is None diff --git a/autobot-backend/services/agent_activity_feed.py b/autobot-backend/services/agent_activity_feed.py new file mode 100644 index 0000000000..890e064207 --- /dev/null +++ b/autobot-backend/services/agent_activity_feed.py @@ -0,0 +1,156 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Per-agent recent-task and timeline feeds for the Agent Activity widget (#21270). + +One implementation over the analytics history store (the same records +``GET /api/analytics/agents/tasks/recent`` reads). A feed is ``None`` when the store could +not be read ("not reported", #17514) and a real list, possibly empty, when it was. +""" + +import math +from datetime import datetime, timedelta +from typing import Any, Dict, List + +from autobot_shared.env_utils import env_int_clamped +from autobot_shared.logging_manager import get_logger +from autobot_shared.status_enums import TaskStatus +from autobot_shared.time_utils import now_utc, parse_utc_iso +from services.agent_analytics import get_agent_analytics + +logger = get_logger(__name__) + +# Env-backed caps: records read per agent, and agents read per status call. +FEED_LIMIT = env_int_clamped("AUTOBOT_AGENT_FEED_RECORDS", 20, min_v=1, max_v=200) +FEED_MAX_AGENTS = env_int_clamped("AUTOBOT_AGENT_FEED_MAX_AGENTS", 200, min_v=1, max_v=5000) +# The widget's timeline axis: the last six clock hours, ending at the next hour boundary. +TIMELINE_HOURS = 6 +_WIDGET_STATUS = { + TaskStatus.COMPLETED.value: "completed", + TaskStatus.FAILED.value: "failed", + TaskStatus.TIMEOUT.value: "failed", + TaskStatus.CANCELLED.value: "cancelled", +} +_BAR_TYPE = {"completed": "working", "failed": "error", "cancelled": "idle"} + +Feed = Dict[str, Any] # recentTasks, activityTimeline: lists; windowStart: UTC ms of the axis start + + +def _window(now: datetime) -> tuple[datetime, float]: + """(start, span in seconds) of the timeline axis for ``now``.""" + end = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + return end - timedelta(hours=TIMELINE_HOURS), TIMELINE_HOURS * 3600.0 + + +def _recent_task(record: Dict[str, Any], status: str, finished: datetime) -> Dict[str, Any]: + return { + "id": record["task_id"], + "name": record.get("task_name") or record["task_id"], + "status": status, + "completedAt": int(finished.timestamp() * 1000), + } + + +def _duration_ms(record: Dict[str, Any]) -> float: + """The stored duration in ms: finite and >= 0; ValueError for NaN / Infinity. + + The writer subtracts two wall-clock timestamps (``AgentAnalytics.complete_task``) and does not clamp, so a + clock step can store a small negative for a real task: it is shown as zero-length, not dropped. + ``json.loads`` accepts ``NaN`` / ``Infinity`` / ``1e999``, which are no duration (and invalid JSON in + the response), so they are malformed. A missing or null value counts as 0. + """ + value = float(record.get("duration_ms") or 0) + if not math.isfinite(value): + raise ValueError("duration_ms is not finite") + return max(value, 0.0) + + +def _timeline_bar(record: Dict[str, Any], status: str, finished: datetime, win: tuple) -> Dict[str, Any] | None: + """A bar for a finished task that overlaps the axis, clipped to it; None when outside.""" + start, span = win + duration_ms = _duration_ms(record) + began = finished - timedelta(milliseconds=duration_ms) + left = max((began - start).total_seconds(), 0.0) + right = min((finished - start).total_seconds(), span) + if right <= 0 or left >= span: + return None + return { + "task": record.get("task_name") or record["task_id"], + "type": _BAR_TYPE[status], + "startPercent": round(left / span * 100, 2), + "widthPercent": round((right - left) / span * 100, 2), + "duration": int(duration_ms), + } + + +def _record_entries(record: Dict[str, Any], win: tuple) -> tuple | None: + """(task, bar-or-None) for a finished record; None for a running one. Raises on a bad record.""" + status = _WIDGET_STATUS.get(str(record.get("status"))) + finished = parse_utc_iso(record["completed_at"]) if record.get("completed_at") else None + if status is None or finished is None: + return None # still running: not a finished task + return _recent_task(record, status, finished), _timeline_bar(record, status, finished, win) + + +def _collect(records: List[Dict[str, Any]], win: tuple) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]], int]: + """(recent tasks, timeline bars, number of malformed records skipped).""" + tasks: List[Dict[str, Any]] = [] + bars: List[Dict[str, Any]] = [] + skipped = 0 + for record in records: + try: + entry = _record_entries(record, win) + except (KeyError, TypeError, ValueError, AttributeError, OverflowError) as exc: + skipped += 1 + logger.debug("Skipping malformed task record in agent feed: %s", type(exc).__name__) + continue + if entry is not None: + tasks.append(entry[0]) + bars.extend([entry[1]] if entry[1] is not None else []) + return tasks, bars, skipped + + +def build_feed(records: List[Dict[str, Any]], now: datetime | None = None, agent_id: str = "") -> Feed: + """Turn analytics task records into the widget's feed; a bad record is skipped, counted in one warning.""" + win = _window(now or now_utc()) + tasks, bars, skipped = _collect(records, win) + if skipped: + logger.warning("Skipped %d malformed task record(s) in the agent feed for %r", skipped, agent_id) + return { + "recentTasks": tasks, + "activityTimeline": bars, + "windowStart": int(win[0].timestamp() * 1000), + } + + +async def get_agent_feeds(agent_ids: List[str]) -> Dict[str, Feed | None]: + """agent_id -> feed (or None when the store is unreadable), in one pipelined read. + + Only the first ``FEED_MAX_AGENTS`` agents are read; the rest report None (not measured). + """ + read = list(agent_ids)[:FEED_MAX_AGENTS] + try: + histories = await get_agent_analytics().read_agent_histories(read, FEED_LIMIT) + except Exception as exc: + logger.warning("Agent activity feeds unreadable, reporting none: %s", exc) + histories = None + feeds = {a: None for a in agent_ids} + if histories is not None: + feeds.update({a: build_feed(records, agent_id=a) for a, records in histories.items()}) + return feeds + + +async def get_agent_feed(agent_id: str) -> Feed | None: + """One agent's feed, or ``None`` when the history store cannot be read (not "no tasks").""" + return (await get_agent_feeds([agent_id]))[agent_id] + + +def with_feed(item: Dict[str, Any], feed: Feed | None) -> Dict[str, Any]: + """``item`` carrying the feed's two lists, or None for both when unmeasured.""" + return { + **item, + "recentTasks": None if feed is None else feed["recentTasks"], + "activityTimeline": None if feed is None else feed["activityTimeline"], + "activityWindowStart": None if feed is None else feed["windowStart"], + } diff --git a/autobot-backend/services/agent_analytics.py b/autobot-backend/services/agent_analytics.py index 4f85b9bc60..aa53fc9075 100644 --- a/autobot-backend/services/agent_analytics.py +++ b/autobot-backend/services/agent_analytics.py @@ -30,6 +30,7 @@ from autobot_shared.status_enums import TaskStatus from autobot_shared.time_utils import now_utc, parse_utc_iso, utc_timestamp from constants.ttl_constants import TTL_1_HOUR, TTL_30_DAYS +from services.agent_metrics_model import AgentMetrics logger = get_logger(__name__) @@ -103,83 +104,6 @@ def from_dict(cls, data: Dict[str, Any]) -> "AgentTaskRecord": ) -@dataclass -class AgentMetrics: - """Aggregated metrics for an agent""" - - agent_id: str - agent_type: str - total_tasks: int = 0 - completed_tasks: int = 0 - failed_tasks: int = 0 - cancelled_tasks: int = 0 - timeout_tasks: int = 0 - avg_duration_ms: float = 0 - min_duration_ms: float = 0 - max_duration_ms: float = 0 - total_tokens_used: int = 0 - error_rate: float = 0 - success_rate: float = 0 - last_activity: str | None = None - - def to_dict(self) -> Dict[str, Any]: - """Convert to dictionary""" - return { - "agent_id": self.agent_id, - "agent_type": self.agent_type, - "total_tasks": self.total_tasks, - "completed_tasks": self.completed_tasks, - "failed_tasks": self.failed_tasks, - "cancelled_tasks": self.cancelled_tasks, - "timeout_tasks": self.timeout_tasks, - "avg_duration_ms": round(self.avg_duration_ms, 2), - "min_duration_ms": round(self.min_duration_ms, 2), - "max_duration_ms": round(self.max_duration_ms, 2), - "total_tokens_used": self.total_tokens_used, - "error_rate": round(self.error_rate, 2), - "success_rate": round(self.success_rate, 2), - "last_activity": self.last_activity, - } - - # === Issue #372: Feature Envy Reduction Methods === - - def get_prometheus_labels(self) -> str: - """Get Prometheus label string for this agent (Issue #372 - reduces feature envy).""" - return f'agent_id="{self.agent_id}",agent_type="{self.agent_type}"' - - def to_prometheus_tasks_line(self) -> str: - """Generate Prometheus line for total tasks (Issue #372 - reduces feature envy).""" - return f"autobot_agent_tasks_total{{{self.get_prometheus_labels()}}} {self.total_tasks}" - - def to_prometheus_success_rate_line(self) -> str: - """Generate Prometheus line for success rate (Issue #372 - reduces feature envy).""" - return f"autobot_agent_success_rate{{{self.get_prometheus_labels()}}} {self.success_rate}" - - def to_prometheus_error_rate_line(self) -> str: - """Generate Prometheus line for error rate (Issue #372 - reduces feature envy).""" - return f"autobot_agent_error_rate{{{self.get_prometheus_labels()}}} {self.error_rate}" - - def to_prometheus_duration_line(self) -> str: - """Generate Prometheus line for avg duration (Issue #372 - reduces feature envy).""" - return f"autobot_agent_avg_duration_ms{{{self.get_prometheus_labels()}}} {self.avg_duration_ms}" - - def to_csv_row(self) -> List[Any]: - """Generate CSV row for export (Issue #372 - reduces feature envy).""" - return [ - self.agent_id, - self.agent_type, - self.total_tasks, - self.completed_tasks, - self.failed_tasks, - self.timeout_tasks, - self.success_rate, - self.error_rate, - self.avg_duration_ms, - self.total_tokens_used, - self.last_activity or "", - ] - - class AgentAnalytics(AsyncRedisClientMixin): """ Tracks and analyzes agent performance across the system. @@ -493,24 +417,47 @@ async def get_all_agents_metrics(self) -> List[AgentMetrics]: logger.error("Failed to get all agents metrics: %s", e) return [] - async def get_agent_history(self, agent_id: str, limit: int = 100) -> List[Dict[str, Any]]: - """Get task history for an agent""" - try: - redis = await self.get_redis() - if redis is None: - logger.error( - "Redis unavailable: agent history for %s degraded to empty (not genuinely no data)", - agent_id, - ) - return [] - agent_key = f"{self.AGENT_HISTORY_KEY}:{agent_id}" - records = await redis.lrange(agent_key, 0, limit - 1) + async def read_agent_histories( + self, agent_ids: List[str], limit: int = 100 + ) -> Dict[str, List[Dict[str, Any]]] | None: + """Strict history read: agent_id -> records in ONE pipelined round trip. - return [json.loads(r) for r in records] + ``None`` only when the store cannot be read; an unparsable record is logged and skipped. + """ + redis = await self.get_redis() + if redis is None or not agent_ids: + return None if redis is None else {} + pipe = redis.pipeline() + for agent_id in agent_ids: + pipe.lrange(f"{self.AGENT_HISTORY_KEY}:{agent_id}", 0, limit - 1) + return {a: self._parse_history(a, raw) for a, raw in zip(agent_ids, await pipe.execute())} + + @staticmethod + def _parse_history(agent_id: str, raw: List[Any]) -> List[Dict[str, Any]]: + records = [] + for item in raw: + try: + records.append(json.loads(item)) + except (TypeError, ValueError) as exc: + logger.warning("Skipping unparsable history record for %s: %s", agent_id, exc) + return records + + async def read_agent_history(self, agent_id: str, limit: int = 100) -> List[Dict[str, Any]] | None: + """Strict single-agent history: ``None`` when the store cannot be read.""" + histories = await self.read_agent_histories([agent_id], limit) + return None if histories is None else histories[agent_id] + async def get_agent_history(self, agent_id: str, limit: int = 100) -> List[Dict[str, Any]]: + """Get task history for an agent (``[]`` when the store cannot be read).""" + try: + records = await self.read_agent_history(agent_id, limit) except Exception as e: logger.error("Failed to get agent history: %s", e) return [] + if records is None: + logger.error("Redis unavailable: agent history for %s degraded to empty", agent_id) + return [] + return records async def get_recent_tasks(self, limit: int = 100) -> List[Dict[str, Any]]: """Get recent tasks across all agents""" diff --git a/autobot-backend/services/agent_metrics_model.py b/autobot-backend/services/agent_metrics_model.py new file mode 100644 index 0000000000..01216fdad4 --- /dev/null +++ b/autobot-backend/services/agent_metrics_model.py @@ -0,0 +1,85 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Aggregated per-agent metrics model, split out of ``agent_analytics`` (#21270).""" + +from dataclasses import dataclass +from typing import Any, Dict, List + + +@dataclass +class AgentMetrics: + """Aggregated metrics for an agent""" + + agent_id: str + agent_type: str + total_tasks: int = 0 + completed_tasks: int = 0 + failed_tasks: int = 0 + cancelled_tasks: int = 0 + timeout_tasks: int = 0 + avg_duration_ms: float = 0 + min_duration_ms: float = 0 + max_duration_ms: float = 0 + total_tokens_used: int = 0 + error_rate: float = 0 + success_rate: float = 0 + last_activity: str | None = None + + def to_dict(self) -> Dict[str, Any]: + """Convert to dictionary""" + return { + "agent_id": self.agent_id, + "agent_type": self.agent_type, + "total_tasks": self.total_tasks, + "completed_tasks": self.completed_tasks, + "failed_tasks": self.failed_tasks, + "cancelled_tasks": self.cancelled_tasks, + "timeout_tasks": self.timeout_tasks, + "avg_duration_ms": round(self.avg_duration_ms, 2), + "min_duration_ms": round(self.min_duration_ms, 2), + "max_duration_ms": round(self.max_duration_ms, 2), + "total_tokens_used": self.total_tokens_used, + "error_rate": round(self.error_rate, 2), + "success_rate": round(self.success_rate, 2), + "last_activity": self.last_activity, + } + + # === Issue #372: Feature Envy Reduction Methods === + + def get_prometheus_labels(self) -> str: + """Get Prometheus label string for this agent (Issue #372 - reduces feature envy).""" + return f'agent_id="{self.agent_id}",agent_type="{self.agent_type}"' + + def to_prometheus_tasks_line(self) -> str: + """Generate Prometheus line for total tasks (Issue #372 - reduces feature envy).""" + return f"autobot_agent_tasks_total{{{self.get_prometheus_labels()}}} {self.total_tasks}" + + def to_prometheus_success_rate_line(self) -> str: + """Generate Prometheus line for success rate (Issue #372 - reduces feature envy).""" + return f"autobot_agent_success_rate{{{self.get_prometheus_labels()}}} {self.success_rate}" + + def to_prometheus_error_rate_line(self) -> str: + """Generate Prometheus line for error rate (Issue #372 - reduces feature envy).""" + return f"autobot_agent_error_rate{{{self.get_prometheus_labels()}}} {self.error_rate}" + + def to_prometheus_duration_line(self) -> str: + """Generate Prometheus line for avg duration (Issue #372 - reduces feature envy).""" + return f"autobot_agent_avg_duration_ms{{{self.get_prometheus_labels()}}} {self.avg_duration_ms}" + + def to_csv_row(self) -> List[Any]: + """Generate CSV row for export (Issue #372 - reduces feature envy).""" + return [ + self.agent_id, + self.agent_type, + self.total_tasks, + self.completed_tasks, + self.failed_tasks, + self.timeout_tasks, + self.success_rate, + self.error_rate, + self.avg_duration_ms, + self.total_tokens_used, + self.last_activity or "", + ] diff --git a/autobot-backend/services/agent_org_service.py b/autobot-backend/services/agent_org_service.py index 8c7f911cd8..6cca3fa463 100644 --- a/autobot-backend/services/agent_org_service.py +++ b/autobot-backend/services/agent_org_service.py @@ -17,6 +17,7 @@ from autobot_shared.logging_manager import get_logger from models.agent_org import AgentOrgNode, OrgRole +from services.agent_activity_feed import get_agent_feeds, with_feed logger = get_logger(__name__) @@ -144,17 +145,20 @@ async def get_agent_statuses(self, *, can_see: Callable[[Any], bool]) -> List[Di names = await self._company_names({n.company_id for n in nodes if n.company_id}) # #17514: the registry measures no activity, so those fields are None ("not reported"), # never a 0 that reads as observed. The company tells two same-role agents apart. + # #21270: the task feeds come from the analytics history, None when it is unreadable. + feeds = await get_agent_feeds([n.agent_id for n in nodes]) return [ - { - "id": node.agent_id, - "name": node.name, - "type": _ROLE_TO_ACTIVITY_TYPE.get(node.org_role, "worker"), - "status": self._status_for_node(node), - "companyId": str(node.company_id) if node.company_id else None, - "companyName": names.get(node.company_id), - "recentTasks": [], - "activityTimeline": [], - } + with_feed( + { + "id": node.agent_id, + "name": node.name, + "type": _ROLE_TO_ACTIVITY_TYPE.get(node.org_role, "worker"), + "status": self._status_for_node(node), + "companyId": str(node.company_id) if node.company_id else None, + "companyName": names.get(node.company_id), + }, + feeds[node.agent_id], + ) for node in nodes ] diff --git a/autobot-backend/services/audit/taxonomy.py b/autobot-backend/services/audit/taxonomy.py index b2868f59e9..8a42bcbe77 100644 --- a/autobot-backend/services/audit/taxonomy.py +++ b/autobot-backend/services/audit/taxonomy.py @@ -149,6 +149,10 @@ class AuditAction(str, Enum): CONVERSATION_FILE_CLEANUP_RESET = "conversation_file.cleanup_reset" BUDGET_CHAT_REFUSED = "budget.chat_refused" # #20589 chat over a budget LLC_PROJECT_BACKFILL = "llc.project_backfill" # #18978: an approved project backfill assigned projects + # #21136: heartbeat control routes record the verified principal who paused, resumed or terminated an agent. + AGENT_PAUSE = "agent.pause" + AGENT_RESUME = "agent.resume" + AGENT_TERMINATE = "agent.terminate" # #16333: the internal service key was admitted on a route that names its caller (service_opt_in). SERVICE_KEY_ADMITTED = "auth.service_key_admitted" # pragma: allowlist secret -- an action name, not a key # #20750: re-aligning the backend's AUTOBOT_INTERNAL_API_KEY to the SLM's, one record per step. diff --git a/autobot-backend/tests/api/test_agent_status_17514.py b/autobot-backend/tests/api/test_agent_status_17514.py index 7d97b07f83..d738a86be5 100644 --- a/autobot-backend/tests/api/test_agent_status_17514.py +++ b/autobot-backend/tests/api/test_agent_status_17514.py @@ -75,11 +75,23 @@ async def factory() -> AsyncIterator[async_sessionmaker[AsyncSession]]: await engine.dispose() +@pytest.fixture(autouse=True) +def _no_redis_feeds(monkeypatch): # noqa: ANN001, ANN202 + """Keep these tests off the analytics Redis (#21270): feeds are unreadable (None) unless a test says otherwise.""" + from services import agent_org_service + + async def unreadable(ids): # noqa: ANN001, ANN202 + return {i: None for i in ids} + + monkeypatch.setattr(agent_org_service, "get_agent_feeds", unreadable) + + ADMIN = AgentVisibility(is_platform_admin=True) MEMBER_OF_ACME = AgentVisibility(is_platform_admin=False, company_ids=frozenset({ACME})) -async def _status(factory, visibility: AgentVisibility = ADMIN) -> list[dict]: # noqa: ANN001 +async def _status(factory, visibility: AgentVisibility = ADMIN, *, postgres: bool = True) -> list[dict]: # noqa: ANN001 + """GET /agents/status; ``postgres=False`` hands the route no session, so it takes the registry fallback.""" app = FastAPI() app.include_router(router, prefix="/agents") @@ -88,7 +100,7 @@ async def _session(): # noqa: ANN202 yield session app.dependency_overrides[get_db_session] = _session - app.dependency_overrides[get_optional_db_session] = _session + app.dependency_overrides[get_optional_db_session] = _session if postgres else (lambda: None) app.dependency_overrides[get_agent_visibility] = lambda: visibility app.dependency_overrides[get_current_user] = lambda: {"user_id": str(uuid.uuid4())} async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client: @@ -104,6 +116,9 @@ async def test_unmeasured_activity_is_not_reported_as_zero(factory): # noqa: AN assert agent["successRate"] is None assert by_id["ceo-acme"]["status"] is None # not "idle": nobody measured it assert by_id["paused"]["status"] == "paused" # the one state the registry does know + for agent in by_id.values(): # the store is unreadable here, so the feeds are not reported either + assert agent["recentTasks"] is None and agent["activityTimeline"] is None + assert agent["activityWindowStart"] is None @pytest.mark.asyncio @@ -136,3 +151,68 @@ async def test_a_soft_deleted_company_is_not_named(factory): # noqa: ANN001 by_id = {a["id"]: a for a in await _status(factory)} assert by_id["ceo-globex"]["companyName"] is None assert by_id["ceo-acme"]["companyName"] == "Acme" # contrast: a live company is still named + + +@pytest.mark.asyncio +async def test_unreadable_feeds_are_none_on_the_wire_and_measured_empty_is_a_list(factory, monkeypatch): # noqa: ANN001 + """#21270: the status response carries None for an unmeasured feed and [] only for a measured one.""" + from services import agent_org_service + + async def feeds(ids): # noqa: ANN001, ANN202 + return { + i: ({"recentTasks": [], "activityTimeline": [], "windowStart": 1} if i == "paused" else None) for i in ids + } + + monkeypatch.setattr(agent_org_service, "get_agent_feeds", feeds) + by_id = {a["id"]: a for a in await _status(factory)} + assert by_id["ceo-acme"]["recentTasks"] is None and by_id["ceo-acme"]["activityTimeline"] is None + assert by_id["paused"]["recentTasks"] == [] and by_id["paused"]["activityTimeline"] == [] + + +def _patch_fallback_feeds(monkeypatch, feed_for): # noqa: ANN001, ANN202 + """Patch the helper where the route looks it up; returns the list of id-lists the route asked for.""" + from api import agent_org + + asked: list[list[str]] = [] + + async def feeds(ids): # noqa: ANN001, ANN202 + asked.append(list(ids)) + return {i: feed_for(i) for i in ids} + + monkeypatch.setattr(agent_org, "get_agent_feeds", feeds) + return asked + + +@pytest.mark.asyncio +async def test_fallback_route_reports_an_unreadable_store_as_none(factory, monkeypatch): # noqa: ANN001 + asked = _patch_fallback_feeds(monkeypatch, lambda i: None) + agents = await _status(factory, postgres=False) + assert agents and asked == [[a["id"] for a in agents]] # the route fed its own registry agents to the helper + for agent in agents: + assert agent["recentTasks"] is None and agent["activityTimeline"] is None + assert agent["activityWindowStart"] is None + + +@pytest.mark.asyncio +async def test_fallback_route_reports_a_measured_empty_history_as_empty_lists(factory, monkeypatch): # noqa: ANN001 + _patch_fallback_feeds(monkeypatch, lambda i: {"recentTasks": [], "activityTimeline": [], "windowStart": 1234}) + agents = await _status(factory, postgres=False) + assert agents + for agent in agents: + assert agent["recentTasks"] == [] and agent["activityTimeline"] == [] + assert agent["activityWindowStart"] == 1234 + + +@pytest.mark.asyncio +async def test_fallback_route_carries_the_helpers_items_per_agent(factory, monkeypatch): # noqa: ANN001 + def feed(agent_id: str) -> dict: + task = {"id": f"t-{agent_id}", "name": "Deploy", "status": "completed", "completedAt": 5} + bar = {"task": "Deploy", "type": "working", "startPercent": 1.0, "widthPercent": 2.0, "duration": 3} + return {"recentTasks": [task], "activityTimeline": [bar], "windowStart": 99} + + _patch_fallback_feeds(monkeypatch, feed) + agents = await _status(factory, postgres=False) + assert agents + for agent in agents: + assert [t["id"] for t in agent["recentTasks"]] == [f"t-{agent['id']}"] + assert agent["activityTimeline"][0]["task"] == "Deploy" and agent["activityWindowStart"] == 99 diff --git a/autobot-backend/tests/api/test_heartbeat_pause_route_actor_21136.py b/autobot-backend/tests/api/test_heartbeat_pause_route_actor_21136.py new file mode 100644 index 0000000000..8cd4cfe6a4 --- /dev/null +++ b/autobot-backend/tests/api/test_heartbeat_pause_route_actor_21136.py @@ -0,0 +1,128 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Pause, resume and terminate take the actor from the authenticated caller, never the body (#21136).""" + +from datetime import datetime, timezone +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from api import heartbeat +from api.schemas_heartbeat import HeartbeatConfigResponse +from models.heartbeat import HeartbeatStatus + +_BASE = "/api/heartbeat/a1" +_CALLER = {"id": "principal-7", "username": "alice", "role": "admin"} +_STAMP = datetime(2026, 1, 2, 3, 4, 5, tzinfo=timezone.utc) + + +def _state() -> SimpleNamespace: + """Every attribute ``_state_to_response`` reads, typed as the ORM row types them.""" + return SimpleNamespace( + agent_id="a1", + heartbeat_enabled=True, + status=HeartbeatStatus.ACTIVE.value, + paused_reason=None, + paused_at=None, + paused_by=None, + error_detail=None, + error_at=None, + error_code=None, + heartbeat_interval_seconds=60, + max_run_duration_seconds=3600, + current_task_id=None, + last_heartbeat_at=_STAMP, + session_params={}, + extra=None, + created_at=_STAMP, + updated_at=_STAMP, + ) + + +@pytest.fixture +def harness(real_auth_middleware, monkeypatch): + """The real router and the real auth dependency; only the stores are faked.""" + identity = SimpleNamespace(user=_CALLER) + + async def _no_token(_request): + return None + + middleware = SimpleNamespace( + get_user_from_request=lambda _request: identity.user, + _extract_user_from_run_jwt=_no_token, + _extract_user_from_device_jwt=_no_token, + ) + monkeypatch.setattr(real_auth_middleware, "get_auth_middleware", lambda: middleware) + + audits: list = [] + + async def _record(event): + audits.append(event.actor_id) + return True + + state = _state() + session = MagicMock(commit=AsyncMock(), refresh=AsyncMock()) + scheduler = MagicMock(disable_agent=AsyncMock(), enable_agent=AsyncMock()) + get_state = AsyncMock(return_value=state) + names = AsyncMock(return_value=None) + monkeypatch.setattr(heartbeat, "record_committed", _record) + monkeypatch.setattr(heartbeat, "_get_or_create_state", get_state) + monkeypatch.setattr(heartbeat, "_paused_by_name", names) + app = FastAPI() + app.include_router(heartbeat.router, prefix="/api/heartbeat") + app.dependency_overrides[heartbeat.get_current_user] = real_auth_middleware.get_current_user + app.dependency_overrides[heartbeat.get_db_session] = lambda: session + app.dependency_overrides[heartbeat._get_scheduler] = lambda: scheduler + return SimpleNamespace( + client=TestClient(app), + identity=identity, + state=state, + audits=audits, + session=session, + scheduler=scheduler, + get_state=get_state, + names=names, + ) + + +def test_pause_ignores_forged_body_actor(harness) -> None: + response = harness.client.post(f"{_BASE}/pause", json={"reason": "r", "paused_by": "system:forged"}) + + assert response.status_code == 200 + # Fails if the route used the body: the state write would carry "system:forged". + assert harness.state.paused_by == "principal-7" + # Fails if the audit named the body's value. + assert harness.audits == ["principal-7"] + body = HeartbeatConfigResponse.model_validate(response.json()) + assert (body.agent_id, body.status, body.paused_reason) == ("a1", HeartbeatStatus.PAUSED.value, "r") + assert body.paused_by == "principal-7" + assert body.paused_at is not None + harness.names.assert_awaited_once_with(harness.session, "principal-7") + harness.scheduler.disable_agent.assert_awaited_once_with("a1") + + +_ROUTES = [ + pytest.param("pause", {"reason": "r", "paused_by": "system:forged"}, id="pause"), + pytest.param("resume", {}, id="resume"), + pytest.param("terminate", {"reason": "r"}, id="terminate"), +] + + +@pytest.mark.parametrize(("action", "payload"), _ROUTES) +def test_an_anonymous_caller_is_refused_and_nothing_is_written(harness, action: str, payload: dict) -> None: + harness.identity.user = None + + response = harness.client.post(f"{_BASE}/{action}", json=payload) + + assert response.status_code == 401 + assert harness.audits == [] + harness.get_state.assert_not_awaited() + harness.session.commit.assert_not_awaited() + harness.scheduler.disable_agent.assert_not_awaited() + harness.scheduler.enable_agent.assert_not_awaited() + assert (harness.state.status, harness.state.paused_by) == (HeartbeatStatus.ACTIVE.value, None) diff --git a/autobot-backend/tests/unit/test_agent_activity_feed_21270.py b/autobot-backend/tests/unit/test_agent_activity_feed_21270.py new file mode 100644 index 0000000000..3647a3fe4e --- /dev/null +++ b/autobot-backend/tests/unit/test_agent_activity_feed_21270.py @@ -0,0 +1,232 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""Agent task feeds are measured or None, never a placeholder [] (#21270).""" + +import json +from datetime import datetime, timezone +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from services import agent_activity_feed as feed_mod +from services.agent_analytics import AgentAnalytics + +NOW = datetime(2026, 11, 9, 12, 30, tzinfo=timezone.utc) # axis: 07:00 -> 13:00 + + +@pytest.fixture(autouse=True) +def fixed_clock(monkeypatch): + """Every test sees the same "now": get_agent_feeds builds feeds with the module's now_utc.""" + monkeypatch.setattr(feed_mod, "now_utc", lambda: NOW) + + +def _record(task_id, status, completed_at, duration_ms=60_000): + return { + "task_id": task_id, + "task_name": f"name-{task_id}", + "status": status, + "completed_at": completed_at, + "duration_ms": duration_ms, + } + + +def _redis(*lists, error=None): + """A Redis double whose pipeline returns one raw list per queued lrange.""" + pipe = MagicMock() + pipe.execute = AsyncMock(side_effect=error, return_value=list(lists)) + redis = MagicMock() + redis.pipeline = MagicMock(return_value=pipe) + redis.pipe = pipe + return redis + + +def _use(monkeypatch, redis): + analytics = AgentAnalytics() + analytics.get_redis = AsyncMock(return_value=redis) + monkeypatch.setattr(feed_mod, "get_agent_analytics", lambda: analytics) + return analytics + + +@pytest.mark.asyncio +async def test_unreadable_store_is_none_not_empty(monkeypatch): + _use(monkeypatch, None) + assert await feed_mod.get_agent_feed("a") is None + + +@pytest.mark.asyncio +async def test_redis_error_is_none_not_empty(monkeypatch): + _use(monkeypatch, _redis(error=ConnectionError("down"))) + assert await feed_mod.get_agent_feed("a") is None + + +@pytest.mark.asyncio +async def test_measured_empty_history_is_empty_lists(monkeypatch): + redis = _redis([]) + _use(monkeypatch, redis) + got = await feed_mod.get_agent_feed("a") + assert got["recentTasks"] == [] and got["activityTimeline"] == [] + redis.pipe.lrange.assert_called_once_with("agent_analytics:history:a", 0, feed_mod.FEED_LIMIT - 1) + + +@pytest.mark.asyncio +async def test_history_records_feed_both_lists(monkeypatch): + raw = [json.dumps(_record("t1", "completed", "2026-11-09T12:00:00+00:00"))] + _use(monkeypatch, _redis(raw)) + got = await feed_mod.get_agent_feed("a") + assert [t["id"] for t in got["recentTasks"]] == ["t1"] + assert len(got["activityTimeline"]) == 1 + + +@pytest.mark.asyncio +async def test_many_agents_are_one_pipelined_round_trip(monkeypatch): + redis = _redis([], []) + _use(monkeypatch, redis) + got = await feed_mod.get_agent_feeds(["a", "b"]) + assert set(got) == {"a", "b"} and all(v is not None for v in got.values()) + assert redis.pipe.execute.await_count == 1 and redis.pipe.lrange.call_count == 2 + + +@pytest.mark.asyncio +async def test_agents_beyond_the_cap_report_none(monkeypatch): + monkeypatch.setattr(feed_mod, "FEED_MAX_AGENTS", 1) + redis = _redis([]) + _use(monkeypatch, redis) + got = await feed_mod.get_agent_feeds(["a", "b"]) + assert got["a"] is not None and got["b"] is None + assert redis.pipe.lrange.call_count == 1 + + +@pytest.mark.asyncio +async def test_bad_records_are_skipped_not_fatal(monkeypatch): + good = json.dumps(_record("ok", "completed", "2026-11-09T12:00:00+00:00")) + no_id = json.dumps({"status": "completed", "completed_at": "2026-11-09T12:00:00+00:00"}) + bad_time = json.dumps(_record("bt", "completed", "not-a-time")) + _use(monkeypatch, _redis([good, "{not json", no_id, bad_time, good])) + got = await feed_mod.get_agent_feed("a") + assert got is not None + assert [t["id"] for t in got["recentTasks"]] == ["ok", "ok"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "duration_ms, completed_at", + [ + (1e20, "2026-11-09T12:00:00+00:00"), # pre-fix: OverflowError from timedelta, escaped the guard + (1e999, "2026-11-09T12:00:00+00:00"), # JSON Infinity: pre-fix OverflowError, escaped + (float("-inf"), "2026-11-09T12:00:00+00:00"), # pre-fix OverflowError, escaped + (float("nan"), "2026-11-09T12:00:00+00:00"), # pre-fix ValueError, skipped (kept as a regression pin) + ("abc", "2026-11-09T12:00:00+00:00"), # float() ValueError + ([1], "2026-11-09T12:00:00+00:00"), # float() TypeError + (60_000, "0001-01-01T00:00:00+00:00"), # pre-fix: finished - duration underflows year 1: OverflowError + ], +) +async def test_overflowing_or_non_finite_records_are_skipped_not_fatal(monkeypatch, duration_ms, completed_at): + good = json.dumps(_record("ok", "completed", "2026-11-09T12:00:00+00:00")) + bad = json.dumps(_record("bad", "completed", completed_at, duration_ms)) # allow_nan writes NaN/Infinity + _use(monkeypatch, _redis([good, bad, good])) + got = await feed_mod.get_agent_feed("a") + assert got is not None + assert [t["id"] for t in got["recentTasks"]] == ["ok", "ok"] + assert len(got["activityTimeline"]) == 2 + json.dumps(got, allow_nan=False) # the response stays valid JSON + + +_MISSING = object() + + +@pytest.mark.parametrize( + "duration_ms, expected", + [ + (_MISSING, 0), # key absent + (None, 0), + (0, 0), + ("1500", 1500), # numeric string: float() accepts it + (True, 1), # bool is an int: 1 ms + (-5, 0), # the writer subtracts wall clocks without clamping: a real task, shown zero-length + (-0.4, 0), + ], +) +def test_lenient_durations_keep_the_task_with_a_non_negative_bar(duration_ms, expected): + record = _record("t", "completed", "2026-11-09T12:00:00+00:00", duration_ms) + if duration_ms is _MISSING: + del record["duration_ms"] + got = feed_mod.build_feed([record], NOW) + assert [t["id"] for t in got["recentTasks"]] == ["t"] + (bar,) = got["activityTimeline"] + assert bar["duration"] == expected and bar["widthPercent"] >= 0 + json.dumps(got, allow_nan=False) + + +def test_non_dict_records_are_skipped_not_fatal(): + good = _record("ok", "completed", "2026-11-09T12:00:00+00:00") + got = feed_mod.build_feed([good, [1, 2], "text", None, 7, good], NOW) + assert [t["id"] for t in got["recentTasks"]] == ["ok", "ok"] + + +def test_skips_are_one_counted_warning_without_record_content(caplog): + caplog.set_level("DEBUG", logger=feed_mod.logger.name) + task_name = "PRIVATE-TASK-NAME" + bad = [{"task_id": task_name, "status": "completed", "completed_at": "nope"} for _ in range(3)] + feed_mod.build_feed(bad, NOW, agent_id="agent-x") + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 1 and "3" in warnings[0].getMessage() and "agent-x" in warnings[0].getMessage() + assert task_name not in caplog.text + + +@pytest.mark.asyncio +async def test_one_bad_record_does_not_break_other_agents(monkeypatch): + good = json.dumps(_record("ok", "completed", "2026-11-09T12:00:00+00:00")) + bad = json.dumps(_record("bad", "completed", "2026-11-09T12:00:00+00:00", 1e20)) + _use(monkeypatch, _redis([bad], [good])) + got = await feed_mod.get_agent_feeds(["a", "b"]) + assert got["a"]["recentTasks"] == [] and [t["id"] for t in got["b"]["recentTasks"]] == ["ok"] + + +@pytest.mark.asyncio +async def test_get_agent_history_keeps_empty_on_failure(monkeypatch): + analytics = _use(monkeypatch, None) + assert await analytics.get_agent_history("a") == [] + assert await analytics.read_agent_history("a") is None + + +def test_feed_carries_the_axis_start_utc_ms(): + got = feed_mod.build_feed([], NOW) + assert got["windowStart"] == int(datetime(2026, 11, 9, 7, tzinfo=timezone.utc).timestamp() * 1000) + + +def test_build_feed_maps_status_and_skips_unfinished(): + records = [ + _record("ok", "completed", "2026-11-09T12:00:00+00:00"), + _record("bad", "timeout", "2026-11-09T11:00:00+00:00"), + _record("run", "running", None), + ] + got = feed_mod.build_feed(records, NOW) + assert [(t["id"], t["status"]) for t in got["recentTasks"]] == [("ok", "completed"), ("bad", "failed")] + done = datetime(2026, 11, 9, 12, tzinfo=timezone.utc) + assert got["recentTasks"][0]["completedAt"] == int(done.timestamp() * 1000) + assert [b["type"] for b in got["activityTimeline"]] == ["working", "error"] + + +def test_timeline_bar_is_positioned_on_the_six_hour_axis(): + # finished 12:00, ran 60 min -> 11:00..12:00 on a 07:00..13:00 axis + got = feed_mod.build_feed([_record("t", "completed", "2026-11-09T12:00:00+00:00", 3_600_000)], NOW) + bar = got["activityTimeline"][0] + assert bar["startPercent"] == pytest.approx(66.67, abs=0.01) + assert bar["widthPercent"] == pytest.approx(16.67, abs=0.01) + assert bar["duration"] == 3_600_000 + + +def test_task_outside_the_axis_stays_in_recent_tasks_only(): + got = feed_mod.build_feed([_record("old", "completed", "2026-11-08T12:00:00+00:00")], NOW) + assert len(got["recentTasks"]) == 1 + assert got["activityTimeline"] == [] + + +def test_with_feed_none_sets_both_to_none(): + item = feed_mod.with_feed({"id": "a"}, None) + assert item["recentTasks"] is None and item["activityTimeline"] is None + measured = feed_mod.with_feed({"id": "a"}, {"recentTasks": [], "activityTimeline": [], "windowStart": 5}) + assert measured["recentTasks"] == [] and measured["activityTimeline"] == [] + assert measured["activityWindowStart"] == 5 and item["activityWindowStart"] is None diff --git a/autobot-backend/tests/unit/test_agents_status_pg_optional.py b/autobot-backend/tests/unit/test_agents_status_pg_optional.py index 0f3c599fa8..e39abcac66 100644 --- a/autobot-backend/tests/unit/test_agents_status_pg_optional.py +++ b/autobot-backend/tests/unit/test_agents_status_pg_optional.py @@ -102,45 +102,31 @@ def test_fallback_returns_list(self): assert len(agents) >= 4, "Expected at least 4 default agents" def test_fallback_shapes(self): - """Every in-memory agent maps to an AgentStatusItem-compatible dict.""" - from orchestration.agent_registry import AgentCapabilityRegistry + """The real fallback builder's items, fed through the real ``with_feed``, are status-shaped. - _ORCH_TYPE_MAP = { - "research": "analyzer", - "librarian": "analyzer", - "system_commands": "executor", - "orchestrator": "orchestrator", - } + Runs the module's own ``_fallback_agents_from_registry`` (not a local dict), so a change + to the fields it builds fails here. The route-level wiring to the feed helper is + asserted in ``tests/api/test_agent_status_17514.py`` (#21270). + """ + from services.agent_activity_feed import with_feed - registry = AgentCapabilityRegistry(initialize_defaults=True) + fallback_fn = self._import_func("_fallback_agents_from_registry") + agents = fallback_fn() + assert agents, "the default registry must yield agents" required_keys = { "id", "name", "type", "status", - "currentTask", - "tasksCompleted", - "uptime", - "successRate", "recentTasks", "activityTimeline", + "activityWindowStart", } - - for profile in registry.get_all().values(): - item = { - "id": profile.agent_id, - "name": profile.agent_id.replace("_", " ").title(), - "type": _ORCH_TYPE_MAP.get(profile.agent_type, "worker"), - "status": profile.availability_status, - "currentTask": None, - "tasksCompleted": 0, - "uptime": 0, - "successRate": int(profile.success_rate * 100), - "recentTasks": [], - "activityTimeline": [], - } - assert required_keys == set(item.keys()), f"Missing keys for {profile.agent_id}" - assert isinstance(item["successRate"], int) + for agent in agents: + item = with_feed(agent, None) + assert required_keys == set(item.keys()), f"Wrong keys for {agent['id']}" + assert item["recentTasks"] is None and item["activityTimeline"] is None + assert item["activityWindowStart"] is None assert item["type"] in {"analyzer", "executor", "orchestrator", "worker"} def test_orch_type_map_covers_defaults(self): diff --git a/autobot-frontend/src/components/agents/HeartbeatPanel.vue b/autobot-frontend/src/components/agents/HeartbeatPanel.vue index 22b68083b8..6488cc488c 100644 --- a/autobot-frontend/src/components/agents/HeartbeatPanel.vue +++ b/autobot-frontend/src/components/agents/HeartbeatPanel.vue @@ -30,7 +30,7 @@