AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
feat(platform): morning briefing, needs-attention unification, briefing-first home (#13800)
Ubbeb454075a1377
diff --git a/autogpt_platform/backend/backend/api/features/briefings/__init__.py b/autogpt_platform/backend/backend/api/features/briefings/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/api/features/briefings/routes.py b/autogpt_platform/backend/backend/api/features/briefings/routes.pynew file mode 100644index 0000000000..e2e4634da0--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/briefings/routes.py@@ -0,0 +1,75 @@+import logging+from datetime import date, datetime, timedelta, timezone++import autogpt_libs.auth as autogpt_auth_lib+from fastapi import APIRouter, Security+from pydantic import BaseModel, ValidationError++from backend.copilot.briefing.models import BriefingContent+from backend.data import briefing as briefing_db++logger = logging.getLogger(__name__)++router = APIRouter(+ prefix="/briefings",+ tags=["briefings"],+ dependencies=[Security(autogpt_auth_lib.requires_user)],+)+++class BriefingResponse(BaseModel):+ id: str+ briefing_date: date+ created_at: datetime+ delivered_at: datetime | None+ content: BriefingContent+++# How stale a briefing may be and still be shown as "your briefing". Beyond+# this the home card would present weeks-old runs — with deep links into+# executions long since reviewed or deleted — under a year-less "August 7"+# label. Yesterday is included so an early-morning visit still has one.+_MAX_BRIEFING_AGE_DAYS = 1++[email protected]("/latest", summary="Get Latest Briefing")+async def get_latest_briefing(+ user_id: str = Security(autogpt_auth_lib.get_user_id),+) -> BriefingResponse | None:+ """Return the user's current briefing, or None if there isn't a fresh one.++ Only briefings covering today or yesterday qualify; anything older is+ history, not "this morning".++ Stored content that fails to validate against the current BriefingContent+ shape (e.g. written by an older/newer version of the composer) is skipped+ rather than 500ing the request — and rather than hiding every older+ briefing behind one unreadable row on the newest date.+ """+ oldest_allowed = datetime.now(timezone.utc).date() - timedelta(+ days=_MAX_BRIEFING_AGE_DAYS+ )+ for record in await briefing_db.get_latest_briefings(user_id):+ if record.briefing_date < oldest_allowed:+ break++ try:+ content = BriefingContent.model_validate(record.content)+ except ValidationError:+ logger.warning(+ "Briefing %s for user %s failed to validate against "+ "BriefingContent; falling back to the previous briefing",+ record.id,+ user_id,+ )+ continue++ return BriefingResponse(+ id=record.id,+ briefing_date=record.briefing_date,+ created_at=record.created_at,+ delivered_at=record.delivered_at,+ content=content,+ )++ return Nonediff --git a/autogpt_platform/backend/backend/api/features/briefings/routes_test.py b/autogpt_platform/backend/backend/api/features/briefings/routes_test.pynew file mode 100644index 0000000000..ce17ed3b74--- /dev/null+++ b/autogpt_platform/backend/backend/api/features/briefings/routes_test.py@@ -0,0 +1,230 @@+"""Tests for the briefings API routes.++Pattern mirrors backend/api/features/executions/review/review_routes_test.py:+the full app from backend.api.rest_api, the session-scoped `server` fixture+(real Prisma DB), and `mock_jwt_user` for auth overrides. Unlike the review+tests, these seed real rows via backend.data.briefing.create_briefing rather+than mocking the data layer, since the behavior under test includes how the+route handles content that fails to validate against BriefingContent.+"""++import datetime+from collections.abc import AsyncGenerator++import httpx+import pytest+import pytest_asyncio+from prisma.models import UserBriefing++from backend.api.rest_api import app+from backend.data import briefing as briefing_db++from .routes import router+++@pytest_asyncio.fixture(loop_scope="session")+async def client(server, mock_jwt_user) -> AsyncGenerator[httpx.AsyncClient, None]:+ """Create async HTTP client with auth overrides"""+ from autogpt_libs.auth.jwt_utils import get_jwt_payload++ app.dependency_overrides[get_jwt_payload] = mock_jwt_user["get_jwt_payload"]++ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://test",+ ) as http_client:+ yield http_client++ app.dependency_overrides.pop(get_jwt_payload, None)+++async def _delete_briefings(user_id: str) -> None:+ """Delete the user's briefings, retrying once on a stale event loop.++ Fire-and-forget background tasks in earlier tests can leave the Prisma+ pool holding a connection bound to a since-closed function-scoped loop;+ the first session-loop call after that raises ``RuntimeError: Event loop+ is closed`` and the pool re-establishes itself on the retry. Same+ workaround as ``backend/conftest.py::_create_user_with_loop_retry``.+ """+ try:+ await UserBriefing.prisma().delete_many(where={"userId": user_id})+ except RuntimeError as e:+ if "Event loop is closed" not in str(e):+ raise+ await UserBriefing.prisma().delete_many(where={"userId": user_id})+++@pytest_asyncio.fixture(loop_scope="session", autouse=True)+async def _clean_briefings(server, test_user_id: str):+ """Ensure no leftover briefings for the shared test user before/after each test.++ loop_scope must match the session-scoped Prisma client — a+ function-scoped loop here hits "Event loop is closed" on the first+ delete_many once another test has already bound the client's HTTP+ session to a since-closed loop."""+ await _delete_briefings(test_user_id)+ yield+ await _delete_briefings(test_user_id)+++def _today() -> datetime.date:+ """UTC today — the route's own reference point for the recency bound."""+ return datetime.datetime.now(datetime.timezone.utc).date()+++def _days_ago(days: int) -> datetime.date:+ return _today() - datetime.timedelta(days=days)+++def _valid_content() -> dict:+ return {+ "generated_at": "2026-08-07T09:00:00+00:00",+ "timezone": "UTC",+ "zero_expert_fallback": False,+ "run_items": [+ {+ "expert_id": "expert-1",+ "expert_name": "Maria",+ "expert_avatar_url": None,+ "agent_name": "SEO Blog Writer",+ "graph_id": "graph-1",+ "execution_id": "exec-1",+ "library_agent_id": "library-agent-1",+ "status": "COMPLETED",+ "summary": "Published 3 posts",+ "link": "/library/agents/library-agent-1",+ }+ ],+ "decision_items": [+ {+ "node_exec_id": "node-exec-1",+ "graph_exec_id": "exec-1",+ "title": "Approve email send",+ "expert_id": "expert-1",+ "expert_name": "Maria",+ "expert_avatar_url": None,+ "link": "/review/exec-1",+ }+ ],+ }++[email protected](loop_scope="session")+async def test_get_latest_briefing_returns_null_when_none_exists(+ client: httpx.AsyncClient,+) -> None:+ """No briefing rows for the user -> 200 with a null body."""+ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ assert response.json() is None++[email protected](loop_scope="session")+async def test_get_latest_briefing_returns_typed_content(+ client: httpx.AsyncClient,+ setup_test_user: str,+) -> None:+ """A seeded briefing comes back as typed content matching what was stored."""+ content = _valid_content()+ today = _today()+ record = await briefing_db.create_briefing(setup_test_user, today, content)++ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ data = response.json()+ assert data["id"] == record.id+ assert data["briefing_date"] == today.isoformat()+ assert data["delivered_at"] is None+ assert data["content"]["timezone"] == "UTC"+ assert data["content"]["zero_expert_fallback"] is False+ assert data["content"]["run_items"][0]["expert_name"] == "Maria"+ assert data["content"]["decision_items"][0]["title"] == "Approve email send"++[email protected](loop_scope="session")+async def test_get_latest_briefing_returns_only_the_latest_by_date(+ client: httpx.AsyncClient,+ setup_test_user: str,+) -> None:+ """When multiple briefings exist, the one with the latest briefing_date wins."""+ await briefing_db.create_briefing(setup_test_user, _days_ago(1), _valid_content())+ latest = await briefing_db.create_briefing(+ setup_test_user, _today(), _valid_content()+ )++ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ data = response.json()+ assert data["id"] == latest.id+ assert data["briefing_date"] == _today().isoformat()++[email protected](loop_scope="session")+async def test_get_latest_briefing_returns_null_on_invalid_stored_content(+ client: httpx.AsyncClient,+ setup_test_user: str,+) -> None:+ """Content that no longer validates against BriefingContent is treated as+ if there were no briefing, rather than 500ing the request."""+ await briefing_db.create_briefing(+ setup_test_user, _today(), {"unexpected": "shape"}+ )++ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ assert response.json() is None++[email protected](loop_scope="session")+async def test_get_latest_briefing_falls_back_to_the_newest_readable_briefing(+ client: httpx.AsyncClient,+ setup_test_user: str,+) -> None:+ """One unreadable row on the newest date must not hide older briefings."""+ readable = await briefing_db.create_briefing(+ setup_test_user, _days_ago(1), _valid_content()+ )+ await briefing_db.create_briefing(+ setup_test_user, _today(), {"unexpected": "shape"}+ )++ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ data = response.json()+ assert data["id"] == readable.id+ assert data["briefing_date"] == _days_ago(1).isoformat()++[email protected](loop_scope="session")+async def test_get_latest_briefing_ignores_stale_briefings(+ client: httpx.AsyncClient,+ setup_test_user: str,+) -> None:+ """A briefing older than yesterday is history, not "this morning" — the+ home card must not present weeks-old runs under a year-less date label."""+ await briefing_db.create_briefing(setup_test_user, _days_ago(21), _valid_content())++ response = await client.get("/api/briefings/latest")++ assert response.status_code == 200+ assert response.json() is None+++def test_get_latest_briefing_requires_auth() -> None:+ """GET /briefings/latest should return 401 when no valid JWT is provided."""+ import fastapi+ import fastapi.testclient++ unauthenticated_app = fastapi.FastAPI()+ unauthenticated_app.include_router(router)+ unauthenticated_client = fastapi.testclient.TestClient(unauthenticated_app)++ response = unauthenticated_client.get("/briefings/latest")++ assert response.status_code == 401diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 81a38dbe1e..26cd9c7606 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -114,6 +114,7 @@ from backend.data.credit import UsageTransactionMetadata, get_user_credit_modelfrom backend.data.redis_client import get_redis_asyncfrom backend.data.understanding import get_business_understandingfrom backend.data.workspace import build_files_block, resolve_workspace_files+from backend.util.background import spawn_background_taskfrom backend.util.exceptions import InsufficientBalanceError, NotFoundErrorfrom backend.util.settings import Settings@@ -1170,9 +1171,22 @@ async def stream_chat_post(request: Request body with message, is_user_message, and optional context.user_id: Authenticated user ID."""- import asyncioimport time+ # Fire-and-forget; per-user Redis dedup inside the helper provides+ # cross-process / cross-restart idempotency. Same pattern as+ # graphiti/ingest.py's ensure_dream_system_scheduled registration.+ from backend.copilot.briefing.scheduling import ensure_morning_briefing_scheduled++ # Spawned through the shared helper: the loop only holds a weak+ # reference, so an unretained task can be GC'd mid-flight — leaving the+ # Redis marker unwritten and making every subsequent turn redo the whole+ # registration.+ spawn_background_task(+ ensure_morning_briefing_scheduled(user_id),+ name=f"morning-briefing-register-{user_id[:12]}",+ )+stream_start_time = time.perf_counter()# Wall-clock arrival time, propagated to the executor so the turn-start# drain can order pending messages relative to this request (pendingdiff --git a/autogpt_platform/backend/backend/api/features/executions/review/model.py b/autogpt_platform/backend/backend/api/features/executions/review/model.pyindex bad8b8d304..a86324d6ec 100644--- a/autogpt_platform/backend/backend/api/features/executions/review/model.py+++ b/autogpt_platform/backend/backend/api/features/executions/review/model.py@@ -55,6 +55,18 @@ class PendingHumanReviewModel(BaseModel):review_message: str | None = Field(description="Optional message from the reviewer", default=None)+ expert_id: str | None = Field(+ default=None, description="Expert attributed to the requesting run"+ )+ expert_name: str | None = Field(default=None)+ expert_avatar_url: str | None = Field(default=None)+ agent_name: str | None = Field(+ default=None, description="Display name of the agent that requested the review"+ )+ library_agent_id: str | None = Field(default=None, description="For run deep links")+ session_id: str | None = Field(+ default=None, description="Chat session id for copilot run_block reviews"+ )was_edited: bool | None = Field(description="Whether the data was modified during review", default=None)diff --git a/autogpt_platform/backend/backend/api/features/library/db.py b/autogpt_platform/backend/backend/api/features/library/db.pyindex 7f1b59121d..9f59ca008e 100644--- a/autogpt_platform/backend/backend/api/features/library/db.py+++ b/autogpt_platform/backend/backend/api/features/library/db.py@@ -480,6 +480,38 @@ async def get_library_agent_id_by_graph_id(user_id: str, graph_id: str) -> str |return agent.id if agent else None+async def get_library_agent_refs_by_graph_ids(+ user_id: str, graph_ids: list[str]+) -> list[library_model.LibraryAgentRef]:+ """Resolve display name + id for the given graphs in one query.++ Batched counterpart to :func:`get_library_agent_id_by_graph_id`, for+ callers (e.g. the morning briefing) that need to label a known handful+ of runs and would otherwise page through the whole library.++ ``@@unique([userId, agentGraphId, agentGraphVersion])`` allows several+ rows per graph, so exactly one ref per graph is returned — the newest+ version — instead of whichever row the DB happened to return last.+ """+ if not graph_ids:+ return []+ agents = await prisma.models.LibraryAgent.prisma().find_many(+ where={+ "userId": user_id,+ "agentGraphId": {"in": graph_ids},+ "isDeleted": False,+ },+ order=[{"agentGraphVersion": "asc"}],+ )+ newest_by_graph = {+ agent.agentGraphId: library_model.LibraryAgentRef(+ id=agent.id, graph_id=agent.agentGraphId, name=agent.name or ""+ )+ for agent in agents+ }+ return list(newest_by_graph.values())++async def get_library_agent_by_graph_id(user_id: str,graph_id: str,diff --git a/autogpt_platform/backend/backend/api/features/library/model.py b/autogpt_platform/backend/backend/api/features/library/model.pyindex a395af142d..6a7c8e91a6 100644--- a/autogpt_platform/backend/backend/api/features/library/model.py+++ b/autogpt_platform/backend/backend/api/features/library/model.py@@ -132,6 +132,19 @@ class MarketplaceListing(pydantic.BaseModel):creator: MarketplaceListingCreator+class LibraryAgentRef(pydantic.BaseModel):+ """Just enough of a library agent to label and deep-link a run.++ Deliberately cheap: no relation includes, no schedule info, unlike+ :class:`LibraryAgent`. Used where a caller only needs to turn a set of+ graph ids into display names and links.+ """++ id: str+ graph_id: str+ name: str++class RecentExecution(pydantic.BaseModel):"""Summary of a recent execution for quality assessment.diff --git a/autogpt_platform/backend/backend/api/rest_api.py b/autogpt_platform/backend/backend/api/rest_api.pyindex 97e1f4f4f7..9167d35075 100644--- a/autogpt_platform/backend/backend/api/rest_api.py+++ b/autogpt_platform/backend/backend/api/rest_api.py@@ -26,6 +26,7 @@ import backend.api.features.admin.platform_cost_routesimport backend.api.features.admin.rate_limit_admin_routesimport backend.api.features.admin.store_admin_routesimport backend.api.features.auth_email.routes as auth_email_routes+import backend.api.features.briefings.routesimport backend.api.features.builderimport backend.api.features.builder.routesimport backend.api.features.chat.routes as chat_routes@@ -422,6 +423,10 @@ app.include_router(tags=["v2", "executions", "review"],prefix="/api/review",)+app.include_router(+ backend.api.features.briefings.routes.router,+ prefix="/api",+)app.include_router(backend.api.features.library.routes.router, tags=["v2"], prefix="/api/library")diff --git a/autogpt_platform/backend/backend/copilot/briefing/__init__.py b/autogpt_platform/backend/backend/copilot/briefing/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.pynew file mode 100644index 0000000000..82a1a3490f--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py@@ -0,0 +1,374 @@+import asyncio+import logging+import re+import uuid+from datetime import datetime, timedelta+from datetime import timezone as dt_timezone+from typing import NamedTuple, TypedDict+from urllib.parse import quote+from zoneinfo import ZoneInfo++from pydantic import ValidationError++from backend.api.features.executions.review.model import PendingHumanReviewModel+from backend.api.features.experts.models import Expert+from backend.copilot.constants import COPILOT_SESSION_PREFIX+from backend.data.db_accessors import (+ execution_db,+ experts_db,+ library_db,+ review_db,+ user_db,+)+from backend.data.execution import ExecutionStatus, GraphExecutionMeta+from backend.util.clients import get_database_manager_async_client+from backend.util.feature_flag import Flag, is_feature_enabled+from backend.util.timezone_utils import get_user_timezone_or_utc++from .models import BriefingContent, BriefingDecisionItem, BriefingRunItem++logger = logging.getLogger(__name__)++_BRIEFED_STATUSES = [ExecutionStatus.COMPLETED, ExecutionStatus.FAILED]+# Derived so the query filter and the in-Python filter can't drift apart.+_TERMINAL_STATUSES = {str(s) for s in _BRIEFED_STATUSES}+_MAX_RUN_ITEMS = 10+_MAX_DECISION_ITEMS = 10+# Headroom over _MAX_RUN_ITEMS: the fetched window is filtered again in+# Python (expert-owned runs only), so fetching exactly 10 could yield zero+# briefable runs for a user who also runs plain agents.+_EXECUTION_FETCH_LIMIT = 50+# Ceiling on both the decisions considered and the reported decision_total.+_PENDING_REVIEW_PAGE_SIZE = 100+# Shared fallback for a run whose agent couldn't be resolved in the library.+_DEFAULT_AGENT_NAME = "Agent"+_LIBRARY_LINK = "/library"+++class BriefingResult(TypedDict, total=False):+ """Outcome of one :func:`generate_and_deliver_briefing` call.++ ``status`` is always present; the rest depend on it — ``reason`` on a+ skip, ``briefing_id``/``session_id`` on a delivery.+ """++ status: str+ reason: str+ briefing_id: str+ session_id: str | None+++class AgentInfo(NamedTuple):+ name: str+ library_agent_id: str | None+++def _run_link(info: AgentInfo | None, execution_id: str) -> str | None:+ """Deep link that opens a specific run on the library agent page.++ ``activeTab``/``activeItem`` are the params that page actually parses+ (see ``NewAgentLibraryView``); ids are percent-encoded so a link target+ can never carry markdown or URL metacharacters.++ Same route contract as the frontend's ``getReviewLink``+ (``frontend/src/lib/review-links.ts``) — change both together.+ """+ if info and info.library_agent_id:+ return (+ f"/library/agents/{quote(info.library_agent_id)}"+ f"?activeTab=runs&activeItem={quote(execution_id)}"+ )+ return None+++def _activity_summary(stats: GraphExecutionMeta.Stats | dict | None) -> str | None:+ """Pull the AI-generated activity summary off an execution's stats.++ ``GraphExecutionMeta.stats`` is a ``Stats`` pydantic model in+ production; tests stub it with a plain dict. Handle both.+ """+ if isinstance(stats, dict):+ return stats.get("activity_status")+ return getattr(stats, "activity_status", None)+++def compose_briefing(+ *,+ experts: list[Expert],+ executions: list[GraphExecutionMeta],+ reviews: list[PendingHumanReviewModel],+ agent_info_by_graph_id: dict[str, AgentInfo],+ generated_at: datetime,+ tz_name: str,+) -> BriefingContent | None:+ experts_by_id = {e.id: e for e in experts}+ zero_expert_fallback = not experts++ # ExecutionStatus (backend.data.execution.ExecutionStatus) is a+ # prisma StrEnum, so str(e.status) already yields the plain value+ # (e.g. "COMPLETED") regardless of whether e.status is a real enum+ # member or a bare string (as in tests).+ terminal = [e for e in executions if str(e.status) in _TERMINAL_STATUSES]+ if not zero_expert_fallback:+ terminal = [e for e in terminal if e.expert_id]+ # FAILED first: the key is False (0) for failures, True (1) otherwise.+ terminal.sort(key=lambda e: str(e.status) != "FAILED")++ run_items = []+ for execution in terminal[:_MAX_RUN_ITEMS]:+ info = agent_info_by_graph_id.get(execution.graph_id)+ expert = experts_by_id.get(execution.expert_id) if execution.expert_id else None+ run_items.append(+ BriefingRunItem(+ expert_id=expert.id if expert else None,+ expert_name=expert.name if expert else None,+ expert_avatar_url=expert.avatar_url if expert else None,+ agent_name=info.name if info else _DEFAULT_AGENT_NAME,+ graph_id=execution.graph_id,+ execution_id=execution.id,+ library_agent_id=info.library_agent_id if info else None,+ status=str(execution.status),+ summary=_activity_summary(execution.stats),+ link=_run_link(info, execution.id),+ )+ )++ expert_id_by_exec = {e.id: e.expert_id for e in executions}+ decision_items = []+ # Capped like run_items: an uncapped list turns a user with 100 waiting+ # reviews into a 100-line assistant message that also rides along in+ # every later LLM turn of that session. The renderer points the overflow+ # at the needs-attention list.+ for review in reviews[:_MAX_DECISION_ITEMS]:+ if review.graph_exec_id.startswith(COPILOT_SESSION_PREFIX):+ session_id = review.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)+ link = f"/copilot?sessionId={quote(session_id)}"+ else:+ info = agent_info_by_graph_id.get(review.graph_id)+ link = _run_link(info, review.graph_exec_id) or _LIBRARY_LINK+ # _enrich_pending_reviews already resolved expert attribution on the+ # review model (including copilot-session reviews and executions older+ # than the 24h window); the local lookup only backfills gaps.+ fallback = experts_by_id.get(+ review.expert_id or expert_id_by_exec.get(review.graph_exec_id) or ""+ )+ decision_items.append(+ BriefingDecisionItem(+ node_exec_id=review.node_exec_id,+ graph_exec_id=review.graph_exec_id,+ title=review.instructions or "Review needed",+ expert_id=review.expert_id or (fallback.id if fallback else None),+ expert_name=review.expert_name or (fallback.name if fallback else None),+ expert_avatar_url=review.expert_avatar_url+ or (fallback.avatar_url if fallback else None),+ link=link,+ )+ )++ if not run_items and not decision_items:+ return None+ return BriefingContent(+ generated_at=generated_at,+ timezone=tz_name,+ zero_expert_fallback=zero_expert_fallback,+ run_items=run_items,+ decision_items=decision_items,+ decision_total=len(reviews),+ )+++# Agent names, AI-generated summaries and review instructions can all+# originate from a third-party/marketplace agent. Escaping the markdown+# metacharacters that carry structure stops that text from breaking out of+# the link syntax it is interpolated into and spoofing the label or target+# rendered in the user's thread.+_MARKDOWN_META_RE = re.compile(r"([\\`*_\[\]()<>])")+++def _md(text: str) -> str:+ """Escape untrusted text for inline interpolation into markdown."""+ collapsed = " ".join(text.split())+ return _MARKDOWN_META_RE.sub(r"\\\1", collapsed)+++def _md_link(label: str, target: str | None) -> str:+ """Render ``label`` as a markdown link, or as plain text if it can't be.++ Composed targets are relative, percent-encoded paths. Enforcing that in+ code — rather than by convention — keeps an absolute or ``javascript:``+ target from ever reaching the user's thread as a clickable link.+ """+ if not target or not target.startswith("/") or target.startswith("//"):+ return label+ return f"[{label}]({target})"+++def render_briefing_markdown(content: BriefingContent) -> str:+ lines = ["## ☀️ Your morning briefing", ""]+ if content.run_items:+ lines.append("**What ran**")+ for item in content.run_items:+ who = f"{_md(item.expert_name)}: " if item.expert_name else ""+ outcome = "completed" if item.status == "COMPLETED" else "failed"+ name = _md_link(_md(item.agent_name), item.link)+ lines.append(f"- {who}{name} — {outcome}")+ lines.append("")+ found = [item for item in content.run_items if item.summary]+ if found:+ lines.append("**What was found**")+ lines.extend(+ f"- **{_md(item.agent_name)}**: {_md(item.summary or '')}" for item in found+ )+ lines.append("")+ if content.decision_items:+ total = max(content.decision_total, len(content.decision_items))+ lines.append(f"**Needs your decision ({total})**")+ lines.extend(+ f"- {_md_link(_md(d.title), d.link)}" for d in content.decision_items+ )+ remaining = total - len(content.decision_items)+ if remaining > 0:+ lines.append(f"- …and {remaining} more on your home page")+ return "\n".join(lines).strip()+++# Fixed namespace so the same (user, local calendar date) always derives the+# same message id — retries and double-fires of the scheduler job dedupe via+# append_plain_session_message's message_id uniqueness check.+_BRIEFING_NAMESPACE = uuid.UUID("7f1c2d3e-9a4b-4c5d-8e6f-0a1b2c3d4e5f")+++def _merge_agent_info(agent_info: dict[str, AgentInfo], experts: list[Expert]) -> None:+ for expert in experts:+ for wf in expert.workflows:+ if not wf.graph_id:+ continue+ existing = agent_info.get(wf.graph_id)+ agent_info[wf.graph_id] = AgentInfo(+ wf.name or (existing.name if existing else _DEFAULT_AGENT_NAME),+ wf.library_agent_id+ or (existing.library_agent_id if existing else None),+ )+++def _stored_briefing_content(content: dict) -> BriefingContent | None:+ """Re-validate a stored briefing for redelivery.++ ``None`` means the stored shape is unreadable (written by a different+ composer version) — the caller recomposes instead of failing the run.+ """+ try:+ return BriefingContent.model_validate(content)+ except ValidationError:+ logger.warning(+ "Stored briefing content failed validation; recomposing instead",+ exc_info=True,+ )+ return None+++async def _compose_fresh_briefing(+ user_id: str, now_local: datetime, tz_name: str+) -> BriefingContent | None:+ window_start = (now_local - timedelta(hours=24)).astimezone(dt_timezone.utc)+ # The three reads are independent; run them concurrently so the briefing+ # costs one round-trip's latency rather than three. The library lookup+ # can't join them — it needs the graph ids the executions resolve to.+ experts, executions, reviews = await asyncio.gather(+ experts_db().list_experts(user_id),+ # Filter and bound in the query: a user running minute-crons can+ # accumulate thousands of executions a day, and every one of them+ # would otherwise be serialized over the DatabaseManager RPC just to+ # render at most _MAX_RUN_ITEMS bullets.+ execution_db().get_graph_executions(+ user_id=user_id,+ created_time_gte=window_start,+ statuses=_BRIEFED_STATUSES,+ limit=_EXECUTION_FETCH_LIMIT,+ ),+ # One page, deliberately wider than _MAX_DECISION_ITEMS: the extra+ # rows aren't rendered, they're what makes decision_total (and the+ # "…and N more" line) a real number rather than the render cap.+ # A user past _PENDING_REVIEW_PAGE_SIZE waiting decisions therefore+ # sees the total reported at that ceiling.+ review_db().get_pending_reviews_for_user(user_id, 1, _PENDING_REVIEW_PAGE_SIZE),+ )+ # Resolve only the graphs actually referenced, rather than paging the+ # library: paging it would drop the very agent being briefed for a user+ # with >100 agents, leaving an unlinkable "Agent" row.+ graph_ids = list({e.graph_id for e in executions} | {r.graph_id for r in reviews})+ refs = await library_db().get_library_agent_refs_by_graph_ids(user_id, graph_ids)+ agent_info: dict[str, AgentInfo] = {+ ref.graph_id: AgentInfo(ref.name or _DEFAULT_AGENT_NAME, ref.id) for ref in refs+ }+ _merge_agent_info(agent_info, experts)++ return compose_briefing(+ experts=experts,+ executions=executions,+ reviews=reviews,+ agent_info_by_graph_id=agent_info,+ generated_at=now_local,+ tz_name=tz_name,+ )+++async def generate_and_deliver_briefing(user_id: str) -> BriefingResult:+ if not await is_feature_enabled(Flag.HIRE_EXPERTS, user_id, default=False):+ return {"status": "skipped", "reason": "flag_disabled"}++ user = await user_db().get_user_by_id(user_id)+ tz_name = get_user_timezone_or_utc(user.timezone)+ now_local = datetime.now(ZoneInfo(tz_name))+ briefing_date = now_local.date()++ client = get_database_manager_async_client()+ record = await client.get_briefing_for_date(user_id, briefing_date)+ if record and record.delivered_at:+ return {"status": "skipped", "reason": "already_delivered"}++ # An undelivered record means a prior run stored the briefing but the+ # session post failed — redeliver the stored content so the record and+ # the posted message can't diverge.+ stored = _stored_briefing_content(record.content) if record else None+ if record is not None and stored is not None:+ content = stored+ else:+ content = await _compose_fresh_briefing(user_id, now_local, tz_name)+ if content is None:+ if record is not None:+ # An unreadable row whose recompose now yields nothing would+ # otherwise be re-gathered and re-composed on every future+ # run. Stamp it so this user's cron stops reprocessing it.+ await client.mark_briefing_delivered(user_id, record.id)+ return {"status": "skipped", "reason": "nothing_to_say"}+ if record is None:+ record = await client.create_briefing(+ user_id, briefing_date, content.model_dump(mode="json")+ )+ else:+ # Recompose path: write the fresh content back, or the home card+ # (which re-validates) would keep skipping this row and show an+ # older briefing than the one posted into the thread.+ await client.update_briefing_content(+ user_id, record.id, content.model_dump(mode="json")+ )++ message_id = str(+ uuid.uuid5(+ _BRIEFING_NAMESPACE,+ f"morning-briefing:{user_id}:{briefing_date.isoformat()}",+ )+ )+ session_id = await client.append_plain_session_message(+ user_id=user_id,+ content=render_briefing_markdown(content),+ message_id=message_id,+ metadata={"kind": "morning_briefing", "briefing_id": record.id},+ )+ await client.mark_briefing_delivered(user_id, record.id)+ return {+ "status": "delivered",+ "briefing_id": record.id,+ "session_id": session_id,+ }diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py b/autogpt_platform/backend/backend/copilot/briefing/generate_test.pynew file mode 100644index 0000000000..718c39f5c7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py@@ -0,0 +1,842 @@+from datetime import datetime, timezone++import pytest++from backend.copilot.briefing.generate import (+ AgentInfo,+ compose_briefing,+ render_briefing_markdown,+)++NOW = datetime(2026, 8, 7, 9, 0, tzinfo=timezone.utc)+++def make_expert(id="exp-1", name="Ana", avatar="https://a/x.png", workflows=None):+ # Build a minimal backend.api.features.experts.models.Expert+ from backend.api.features.experts.models import Expert++ return Expert(+ id=id,+ name=name,+ avatar_url=avatar,+ role="Researcher",+ tagline=None,+ bio=None,+ skills=[],+ identity="",+ voice_preferences="",+ boundaries="",+ protected_soul_rules=[],+ is_template=False,+ source_template_id=None,+ is_archived=False,+ workflows=workflows or [],+ )+++def make_exec(+ id="run-1",+ graph_id="g-1",+ expert_id="exp-1",+ status="COMPLETED",+ summary="Found 3 leads",+):+ from unittest.mock import MagicMock++ m = MagicMock()+ m.id, m.graph_id, m.expert_id = id, graph_id, expert_id+ m.status = status+ m.stats = {"activity_status": summary} if summary else {}+ return m+++def make_review(+ node_exec_id="ne-1",+ graph_exec_id="run-1",+ graph_id="g-1",+ instructions="Approve outreach email",+ expert_id=None,+ expert_name=None,+ expert_avatar_url=None,+):+ from unittest.mock import MagicMock++ r = MagicMock()+ r.node_exec_id, r.graph_exec_id, r.instructions = (+ node_exec_id,+ graph_exec_id,+ instructions,+ )+ r.graph_id = graph_id+ # Explicit None defaults matter: MagicMock auto-attributes are truthy and+ # would short-circuit compose_briefing's enriched-attribution preference.+ r.expert_id = expert_id+ r.expert_name = expert_name+ r.expert_avatar_url = expert_avatar_url+ return r+++def test_nothing_to_say_returns_none():+ assert (+ compose_briefing(+ experts=[make_expert()],+ executions=[],+ reviews=[],+ agent_info_by_graph_id={},+ generated_at=NOW,+ tz_name="UTC",+ )+ is None+ )+++def test_expert_runs_and_decisions():+ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[make_review()],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None+ assert content.zero_expert_fallback is False+ item = content.run_items[0]+ assert (item.expert_name, item.agent_name, item.summary) == (+ "Ana",+ "Lead Finder",+ "Found 3 leads",+ )+ assert item.link == "/library/agents/lib-1?activeTab=runs&activeItem=run-1"+ decision = content.decision_items[0]+ assert decision.title == "Approve outreach email"+ assert decision.expert_name == "Ana" # attributed via the run's expert_id+ assert decision.link == "/library/agents/lib-1?activeTab=runs&activeItem=run-1"+++def test_zero_experts_falls_back_to_plain_activity():+ content = compose_briefing(+ experts=[],+ executions=[make_exec(expert_id=None)],+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("My Agent", "lib-9")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content.zero_expert_fallback is True+ assert content.run_items[0].expert_id is None+++def test_copilot_review_links_to_session():+ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[make_review(graph_exec_id="copilot-session-abc123")],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content.decision_items[0].link == "/copilot?sessionId=abc123"+++def test_decision_prefers_enriched_expert_attribution():+ """A review raised inside an expert's copilot session carries attribution+ resolved by _enrich_pending_reviews; compose must not discard it."""+ content = compose_briefing(+ experts=[make_expert()], # exp-1 "Ana" — not the enriched expert+ executions=[],+ reviews=[+ make_review(+ graph_exec_id="copilot-session-abc123",+ expert_id="exp-2",+ expert_name="Bob",+ expert_avatar_url="https://a/b.png",+ )+ ],+ agent_info_by_graph_id={},+ generated_at=NOW,+ tz_name="UTC",+ )+ decision = content.decision_items[0]+ assert (decision.expert_id, decision.expert_name) == ("exp-2", "Bob")+ assert decision.expert_avatar_url == "https://a/b.png"+++def test_decision_backfills_display_fields_from_expert_id():+ """Enriched expert_id without name/avatar falls back to the local expert+ lookup for the display fields."""+ content = compose_briefing(+ experts=[make_expert()],+ executions=[],+ reviews=[make_review(expert_id="exp-1")],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ decision = content.decision_items[0]+ assert (decision.expert_id, decision.expert_name) == ("exp-1", "Ana")+++def test_failed_runs_sort_before_completed():+ content = compose_briefing(+ experts=[make_expert()],+ executions=[+ make_exec(id="run-1", status="COMPLETED"),+ make_exec(id="run-2", status="FAILED"),+ ],+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None+ assert [i.status for i in content.run_items] == ["FAILED", "COMPLETED"]+++def test_run_items_capped_at_ten():+ executions = [make_exec(id=f"run-{i}", status="COMPLETED") for i in range(12)]+ content = compose_briefing(+ experts=[make_expert()],+ executions=executions,+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None+ assert len(content.run_items) == 10+++def test_review_without_agent_info_falls_back_to_library_link():+ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[make_review(graph_id="g-unknown")],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None+ assert content.decision_items[0].link == "/library"+++def test_markdown_has_three_sections_and_links():+ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[make_review()],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ md = render_briefing_markdown(content)+ assert "What ran" in md and "What was found" in md and "Needs your decision" in md+ assert "(/library/agents/lib-1?activeTab=runs&activeItem=run-1)" in md+++async def test_generate_skips_when_flag_off(monkeypatch):+ from backend.copilot.briefing import generate++ async def flag_off(*a, **kw):+ return False++ monkeypatch.setattr(generate, "is_feature_enabled", flag_off)+ result = await generate.generate_and_deliver_briefing("user-1")+ assert result == {"status": "skipped", "reason": "flag_disabled"}+++async def test_generate_skips_when_already_delivered(monkeypatch):+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))+ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )+ delivered_record = MagicMock(delivered_at=datetime(2026, 8, 7, 9, 5))+ client = MagicMock(get_briefing_for_date=AsyncMock(return_value=delivered_record))+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ result = await generate.generate_and_deliver_briefing("user-1")+ assert result == {"status": "skipped", "reason": "already_delivered"}+++async def test_generate_delivers_and_composes_briefing(monkeypatch):+ import uuid+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ fixed_now = datetime(2026, 8, 7, 9, 0, tzinfo=timezone.utc)+ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = fixed_now+ monkeypatch.setattr(generate, "datetime", fake_datetime)++ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))++ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )++ briefing_record = MagicMock(id="briefing-1")+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=None),+ create_briefing=AsyncMock(return_value=briefing_record),+ append_plain_session_message=AsyncMock(return_value="session-1"),+ mark_briefing_delivered=AsyncMock(),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ expert = make_expert()+ execution = make_exec()+ review = make_review()+ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[expert])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=AsyncMock(return_value=[execution])),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(+ get_pending_reviews_for_user=AsyncMock(return_value=[review])+ ),+ )+ library_agent = MagicMock(graph_id="g-1", id="lib-1")+ library_agent.name = "Lead Finder"+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(+ get_library_agent_refs_by_graph_ids=AsyncMock(return_value=[library_agent])+ ),+ )++ result = await generate.generate_and_deliver_briefing("user-1")++ assert result == {+ "status": "delivered",+ "briefing_id": "briefing-1",+ "session_id": "session-1",+ }++ expected_content = compose_briefing(+ experts=[expert],+ executions=[execution],+ reviews=[review],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=fixed_now,+ tz_name="UTC",+ )+ assert expected_content is not None++ create_call = client.create_briefing.await_args+ assert create_call.args == (+ "user-1",+ fixed_now.date(),+ expected_content.model_dump(mode="json"),+ )++ expected_message_id = str(+ uuid.uuid5(+ generate._BRIEFING_NAMESPACE,+ f"morning-briefing:user-1:{fixed_now.date().isoformat()}",+ )+ )+ append_call = client.append_plain_session_message.await_args+ assert append_call.kwargs == {+ "user_id": "user-1",+ "content": render_briefing_markdown(expected_content),+ "message_id": expected_message_id,+ "metadata": {"kind": "morning_briefing", "briefing_id": "briefing-1"},+ }+ client.mark_briefing_delivered.assert_awaited_once_with("user-1", "briefing-1")+++def _patch_generate_env(monkeypatch, generate, client):+ """Shared plumbing for the delivery-retry tests: fixed clock, flag on,+ UTC user, and the given database-manager client."""+ from unittest.mock import AsyncMock, MagicMock++ fixed_now = datetime(2026, 8, 7, 9, 0, tzinfo=timezone.utc)+ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = fixed_now+ monkeypatch.setattr(generate, "datetime", fake_datetime)+ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))+ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)+++async def test_generate_retries_undelivered_briefing_without_recomposing(monkeypatch):+ """A stored-but-undelivered record (prior session post failed) is+ redelivered from its stored content — no data gathering, no recompose,+ no duplicate create."""+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ stored = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert stored is not None+ record = MagicMock(+ id="briefing-1", delivered_at=None, content=stored.model_dump(mode="json")+ )+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=record),+ create_briefing=AsyncMock(),+ append_plain_session_message=AsyncMock(return_value="session-1"),+ mark_briefing_delivered=AsyncMock(),+ )+ _patch_generate_env(monkeypatch, generate, client)+ gather_mock = MagicMock(list_experts=AsyncMock(return_value=[]))+ monkeypatch.setattr(generate, "experts_db", lambda: gather_mock)++ result = await generate.generate_and_deliver_briefing("user-1")++ assert result == {+ "status": "delivered",+ "briefing_id": "briefing-1",+ "session_id": "session-1",+ }+ client.create_briefing.assert_not_awaited()+ gather_mock.list_experts.assert_not_awaited()+ append_call = client.append_plain_session_message.await_args+ assert append_call.kwargs["content"] == render_briefing_markdown(stored)+ client.mark_briefing_delivered.assert_awaited_once_with("user-1", "briefing-1")+++async def test_generate_failed_post_leaves_briefing_retryable(monkeypatch):+ """When the session post raises, the record must stay undelivered so the+ next run retries instead of skipping with already_delivered."""+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=None),+ create_briefing=AsyncMock(return_value=MagicMock(id="briefing-1")),+ append_plain_session_message=AsyncMock(+ side_effect=RuntimeError("session post failed")+ ),+ mark_briefing_delivered=AsyncMock(),+ )+ _patch_generate_env(monkeypatch, generate, client)+ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[make_expert()])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=AsyncMock(return_value=[make_exec()])),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(get_pending_reviews_for_user=AsyncMock(return_value=[])),+ )+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(+ get_library_agent_refs_by_graph_ids=AsyncMock(return_value=[])+ ),+ )++ with pytest.raises(RuntimeError, match="session post failed"):+ await generate.generate_and_deliver_briefing("user-1")++ client.mark_briefing_delivered.assert_not_awaited()+++async def test_generate_keeps_library_link_when_workflow_has_no_library_agent_id(+ monkeypatch,+):+ from unittest.mock import AsyncMock, MagicMock++ from backend.api.features.experts.models import ExpertWorkflowRef+ from backend.copilot.briefing import generate++ fixed_now = datetime(2026, 8, 7, 9, 0, tzinfo=timezone.utc)+ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = fixed_now+ monkeypatch.setattr(generate, "datetime", fake_datetime)++ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))++ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )++ briefing_record = MagicMock(id="briefing-1")+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=None),+ create_briefing=AsyncMock(return_value=briefing_record),+ append_plain_session_message=AsyncMock(return_value="session-1"),+ mark_briefing_delivered=AsyncMock(),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ # The workflow shares "g-1" with the library agent below but carries no+ # library_agent_id of its own — the merge must not clobber the+ # library-derived id with None.+ workflow = ExpertWorkflowRef(+ id="wf-1",+ store_listing_version_id=None,+ library_agent_id=None,+ graph_id="g-1",+ name="Lead Finder Workflow",+ description=None,+ )+ expert = make_expert(workflows=[workflow])+ execution = make_exec()+ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[expert])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=AsyncMock(return_value=[execution])),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(get_pending_reviews_for_user=AsyncMock(return_value=[])),+ )+ library_agent = MagicMock(graph_id="g-1", id="lib-1")+ library_agent.name = "Lead Finder"+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(+ get_library_agent_refs_by_graph_ids=AsyncMock(return_value=[library_agent])+ ),+ )++ result = await generate.generate_and_deliver_briefing("user-1")+ assert result["status"] == "delivered"++ content_dict = client.create_briefing.await_args.args[2]+ run_item = content_dict["run_items"][0]+ assert run_item["library_agent_id"] == "lib-1"+ assert run_item["link"] == "/library/agents/lib-1?activeTab=runs&activeItem=run-1"+ assert run_item["agent_name"] == "Lead Finder Workflow"+++def test_summary_reads_stats_model_not_just_dict():+ """Production hands compose_briefing a ``GraphExecutionMeta.Stats`` model,+ while the other tests stub ``stats`` as a plain dict — pin the model branch+ so the attribute read can't silently regress to dict-only."""+ from backend.data.execution import GraphExecutionMeta++ execution = make_exec(summary=None)+ execution.stats = GraphExecutionMeta.Stats(activity_status="Filed 2 tickets")++ content = compose_briefing(+ experts=[make_expert()],+ executions=[execution],+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )++ assert content is not None+ assert content.run_items[0].summary == "Filed 2 tickets"+++def test_markdown_escapes_untrusted_text_in_link_labels():+ """Agent names and review instructions can come from a marketplace agent;+ they must not be able to break out of the markdown link they sit in."""+ review = make_review(instructions="Approve [Trusted](https://evil.example) now")++ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec(summary="Found [a](https://evil.example)")],+ reviews=[review],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead [Finder]", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None++ markdown = render_briefing_markdown(content)++ assert "[Trusted](https://evil.example)" not in markdown+ assert "Approve \\[Trusted\\]\\(https://evil.example\\) now" in markdown+ assert (+ "[Lead \\[Finder\\]](/library/agents/lib-1?activeTab=runs&activeItem=run-1)"+ in markdown+ )+++def test_decision_items_are_capped_and_the_overflow_is_summarized():+ """100 pending reviews must not become a 100-line assistant message —+ that message also rides along in every later LLM turn of the session."""+ reviews = [+ make_review(node_exec_id=f"ne-{i}", graph_exec_id=f"run-{i}") for i in range(25)+ ]++ content = compose_briefing(+ experts=[make_expert()],+ executions=[],+ reviews=reviews,+ agent_info_by_graph_id={},+ generated_at=NOW,+ tz_name="UTC",+ )++ assert content is not None+ assert len(content.decision_items) == 10+ assert content.decision_total == 25++ markdown = render_briefing_markdown(content)+ assert "**Needs your decision (25)**" in markdown+ assert "…and 15 more on your home page" in markdown+++def test_markdown_renders_non_relative_link_targets_as_plain_text():+ """Targets are server-composed relative paths; anything else must not+ become a clickable link in the user's thread."""+ content = compose_briefing(+ experts=[make_expert()],+ executions=[make_exec()],+ reviews=[],+ agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},+ generated_at=NOW,+ tz_name="UTC",+ )+ assert content is not None+ content.run_items[0].link = "javascript:alert(1)"++ markdown = render_briefing_markdown(content)++ assert "javascript:alert(1)" not in markdown+ assert "Lead Finder" in markdown+++async def test_generate_writes_recomposed_content_back_to_an_unreadable_row(+ monkeypatch,+):+ """The stored row and the posted message must not diverge: a row whose+ content no longer validates is rewritten, not just re-posted."""+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = NOW+ monkeypatch.setattr(generate, "datetime", fake_datetime)+ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))++ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )++ stale_record = MagicMock(id="briefing-1", delivered_at=None)+ stale_record.content = {"unexpected": "shape"}+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=stale_record),+ create_briefing=AsyncMock(),+ update_briefing_content=AsyncMock(),+ append_plain_session_message=AsyncMock(return_value="session-1"),+ mark_briefing_delivered=AsyncMock(),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[make_expert()])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=AsyncMock(return_value=[make_exec()])),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(get_pending_reviews_for_user=AsyncMock(return_value=[])),+ )+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(+ get_library_agent_refs_by_graph_ids=AsyncMock(return_value=[])+ ),+ )++ result = await generate.generate_and_deliver_briefing("user-1")++ assert result["status"] == "delivered"+ client.create_briefing.assert_not_awaited()+ update_call = client.update_briefing_content.await_args+ assert update_call.args[:2] == ("user-1", "briefing-1")+ assert update_call.args[2]["run_items"][0]["agent_name"] == "Agent"+++async def test_generate_stops_reprocessing_an_unreadable_row_with_nothing_to_say(+ monkeypatch,+):+ """Otherwise every future run re-gathers and re-composes the same row."""+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate++ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = NOW+ monkeypatch.setattr(generate, "datetime", fake_datetime)+ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))++ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )++ stale_record = MagicMock(id="briefing-1", delivered_at=None)+ stale_record.content = {"unexpected": "shape"}+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=stale_record),+ append_plain_session_message=AsyncMock(),+ mark_briefing_delivered=AsyncMock(),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[make_expert()])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=AsyncMock(return_value=[])),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(get_pending_reviews_for_user=AsyncMock(return_value=[])),+ )+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(+ get_library_agent_refs_by_graph_ids=AsyncMock(return_value=[])+ ),+ )++ result = await generate.generate_and_deliver_briefing("user-1")++ assert result == {"status": "skipped", "reason": "nothing_to_say"}+ client.mark_briefing_delivered.assert_awaited_once_with("user-1", "briefing-1")+ client.append_plain_session_message.assert_not_awaited()+++async def test_generate_bounds_the_execution_query(monkeypatch):+ """The 24h read is filtered and limited in the query — a user running+ minute-crons would otherwise ship thousands of rows over the RPC."""+ from unittest.mock import AsyncMock, MagicMock++ from backend.copilot.briefing import generate+ from backend.data.execution import ExecutionStatus++ fake_datetime = MagicMock(wraps=datetime)+ fake_datetime.now.return_value = NOW+ monkeypatch.setattr(generate, "datetime", fake_datetime)+ monkeypatch.setattr(generate, "is_feature_enabled", AsyncMock(return_value=True))++ user = MagicMock()+ user.timezone = "UTC"+ monkeypatch.setattr(+ generate,+ "user_db",+ lambda: MagicMock(get_user_by_id=AsyncMock(return_value=user)),+ )+ client = MagicMock(+ get_briefing_for_date=AsyncMock(return_value=None),+ create_briefing=AsyncMock(return_value=MagicMock(id="briefing-1")),+ append_plain_session_message=AsyncMock(return_value="session-1"),+ mark_briefing_delivered=AsyncMock(),+ )+ monkeypatch.setattr(generate, "get_database_manager_async_client", lambda: client)++ get_graph_executions = AsyncMock(return_value=[make_exec()])+ monkeypatch.setattr(+ generate,+ "experts_db",+ lambda: MagicMock(list_experts=AsyncMock(return_value=[make_expert()])),+ )+ monkeypatch.setattr(+ generate,+ "execution_db",+ lambda: MagicMock(get_graph_executions=get_graph_executions),+ )+ monkeypatch.setattr(+ generate,+ "review_db",+ lambda: MagicMock(get_pending_reviews_for_user=AsyncMock(return_value=[])),+ )+ refs_lookup = AsyncMock(return_value=[])+ monkeypatch.setattr(+ generate,+ "library_db",+ lambda: MagicMock(get_library_agent_refs_by_graph_ids=refs_lookup),+ )++ await generate.generate_and_deliver_briefing("user-1")++ kwargs = get_graph_executions.await_args.kwargs+ assert kwargs["statuses"] == [ExecutionStatus.COMPLETED, ExecutionStatus.FAILED]+ assert kwargs["limit"] == generate._EXECUTION_FETCH_LIMIT+ # Only the graphs actually referenced are resolved — no whole-library page.+ assert refs_lookup.await_args.args == ("user-1", ["g-1"])diff --git a/autogpt_platform/backend/backend/copilot/briefing/models.py b/autogpt_platform/backend/backend/copilot/briefing/models.pynew file mode 100644index 0000000000..6d9b13b1a7--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/briefing/models.py@@ -0,0 +1,39 @@+from datetime import datetime++from pydantic import BaseModel+++class BriefingRunItem(BaseModel):+ expert_id: str | None+ expert_name: str | None+ expert_avatar_url: str | None+ agent_name: str+ graph_id: str+ execution_id: str+ library_agent_id: str | None+ status: str+ summary: str | None+ link: str | None+++class BriefingDecisionItem(BaseModel):+ node_exec_id: str+ graph_exec_id: str+ title: str+ expert_id: str | None+ expert_name: str | None+ expert_avatar_url: str | None+ link: str+++class BriefingContent(BaseModel):+ generated_at: datetime+ timezone: str+ zero_expert_fallback: bool+ run_items: list[BriefingRunItem]+ decision_items: list[BriefingDecisionItem]+ # How many decisions were pending in total, before the list above was+ # capped. Defaults to 0 so briefings stored before this field existed+ # still validate; the renderer treats "<= len(decision_items)" as+ # "nothing was truncated".+ decision_total: int = 0diff --git a/autogpt_platform/backend/backend/copilot/briefing/scheduling.py b/autogpt_platform/backend/backend/copilot/briefing/scheduling.pynew file mode 100644index 0000000000..1793035b72--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/briefing/scheduling.py@@ -0,0 +1,219 @@+"""Lazy auto-registration of the per-user morning-briefing schedule.++Single-job counterpart to ``backend/copilot/dream/scheduling.py``. That+module's registry-of-crons shape earns its weight over two-plus jobs; the+briefing system has exactly one (``morning_briefing_{user_id}``, daily+user-local), so this module inlines the same registration logic without+the registry indirection.++**Timezone drift handling.** APScheduler binds the cron trigger to the+timezone at job-creation time — a later ``User.timezone`` change silently+leaves the cron firing at the old local time. Two mechanisms cover that:+``update_user_timezone`` clears the Redis marker so the very next call+re-registers, and the marker's TTL bounds how long a drift arriving by any+other route can persist. The scheduler side compares the stored trigger+timezone and only rewrites the job when it actually differs — re-adding an+existing cron would reset a pending ``next_run_time`` and drop that day's+briefing.++**Hot-path cost.** This helper runs on every chat turn. The LaunchDarkly+gate runs first (in-process cached), then the Redis marker short-circuits+the rest. Only the first call after the marker expires pays for the+timezone lookup (a DB read) and the scheduler RPC.++Failures are logged at WARN and swallowed — ``ensure_morning_briefing_scheduled``+is fired via ``asyncio.create_task`` from the hot chat-stream request path+and must never raise.+"""++from __future__ import annotations++import logging++from backend.data.db_accessors import user_db+from backend.data.model import USER_TIMEZONE_NOT_SET+from backend.data.redis_client import get_redis_async+from backend.util.feature_flag import Flag, is_feature_enabled++logger = logging.getLogger(__name__)++# How long a registration marker suppresses re-checking. Mirrors+# ``dream/scheduling.py``: a timezone change goes through+# ``update_user_timezone``, which clears the marker outright, so the TTL only+# has to bound out-of-band drift (an externally deleted cron, a tz written+# straight to the DB) rather than carry drift detection on its own.+REGISTRATION_TTL_SECONDS = 7 * 24 * 3600++BRIEFING_REGISTRATION_PREFIX = "morning_briefing_registered"+++async def _resolve_user_timezone(user_id: str) -> str | None:+ """Look up the user's IANA timezone from Postgres.++ Returns ``"UTC"`` only when the answer is authoritative (user missing+ or timezone genuinely unset) and ``None`` when the lookup itself+ failed — a transient DB blip is "unknown", not "UTC", and must never+ silently re-register the user's local-time cron onto UTC.++ Routes through the ``user_db()`` accessor, NOT ``User.prisma()``: this+ runs in the scheduler process, which never connects a local Prisma+ client. A direct Prisma call raises ``ClientNotConnectedError`` on+ every invocation there. The accessor falls back to the+ DatabaseManager RPC in Prisma-less processes (same pattern as+ ``dream/scheduling.py``).+ """+ try:+ try:+ user = await user_db().get_user_by_id(user_id)+ except ValueError:+ # Authoritative: the user row doesn't exist.+ return "UTC"+ tz = (user.timezone or "").strip()+ if not tz or tz == USER_TIMEZONE_NOT_SET:+ return "UTC"+ return tz+ except Exception:+ logger.warning(+ "Could not resolve timezone for user %s; leaving existing "+ "morning-briefing schedule untouched this cycle",+ user_id[:12],+ exc_info=True,+ )+ return None+++async def _read_registration_marker(user_id: str) -> str | None:+ """Read the freshness marker for this user's briefing cron.++ The key is written with ``REGISTRATION_TTL_SECONDS``, so its mere+ presence means "registered recently enough, don't re-check". Its value+ is the timezone the cron was last registered with, kept for debugging+ and log context; drift itself is decided scheduler-side, by comparing+ the live job's trigger timezone (see+ ``Scheduler.add_morning_briefing_schedule``).++ Returns:+ * The stored timezone string when the key exists.+ * ``None`` when the key is missing OR Redis is unavailable. The+ caller treats both as "needs registration" — the scheduler no-ops+ when the existing job already matches, so a redundant call is cheap+ and, crucially, can't reset a pending ``next_run_time``.+ """+ try:+ redis = await get_redis_async()+ key = f"{BRIEFING_REGISTRATION_PREFIX}:{user_id}"+ stored = await redis.get(key)+ if stored is None:+ return None+ if isinstance(stored, bytes):+ return stored.decode("utf-8", errors="replace")+ return str(stored)+ except Exception:+ logger.debug(+ "Redis read failed for %s:%s; treating as not-registered",+ BRIEFING_REGISTRATION_PREFIX,+ user_id[:12],+ exc_info=True,+ )+ return None+++async def _write_registration_marker(user_id: str, current_tz: str) -> None:+ """Persist the freshness marker, valued with the timezone just used.++ Best-effort — a Redis write failure means the next call will see the+ key as missing and force a redundant re-register, which the scheduler+ turns into a no-op when nothing changed.+ """+ try:+ redis = await get_redis_async()+ key = f"{BRIEFING_REGISTRATION_PREFIX}:{user_id}"+ await redis.set(key, current_tz, ex=REGISTRATION_TTL_SECONDS)+ except Exception:+ logger.debug(+ "Redis write failed for %s:%s; lazy path will re-detect later",+ BRIEFING_REGISTRATION_PREFIX,+ user_id[:12],+ exc_info=True,+ )+++async def clear_briefing_registration_marker(user_id: str) -> None:+ """Delete the Redis registration marker for the briefing cron.++ Called from ``update_user_timezone`` so a profile change immediately+ re-opens lazy registration instead of leaving the marker to block it+ for the remainder of its TTL. Single-key DEL so it routes on+ Redis Cluster.++ Best-effort — on Redis failure the marker simply expires via TTL.+ """+ try:+ redis = await get_redis_async()+ await redis.delete(f"{BRIEFING_REGISTRATION_PREFIX}:{user_id}")+ except Exception:+ logger.warning(+ "Redis delete failed for %s:%s; marker will expire via TTL",+ BRIEFING_REGISTRATION_PREFIX,+ user_id[:12],+ exc_info=True,+ )+++async def ensure_morning_briefing_scheduled(user_id: str) -> None:+ """Idempotently register the morning-briefing cron for a user.++ Fire-and-forget callable from two trigger points:++ * **Lazy path** — ``stream_chat_post`` fires this after resolving the+ authenticated user on every turn. The Redis marker short-circuits+ the common case, so only the first turn after the marker expires+ re-resolves the timezone and re-registers.+ * **Eager path** — ``update_user_timezone`` clears the marker first+ (see :func:`clear_briefing_registration_marker`) then calls this,+ so a profile change re-registers within a single call instead of+ waiting for the dedup key's TTL to expire.++ Never raises — swallows and logs every failure so a bad call can+ never break the caller's hot path.+ """+ try:+ if not user_id:+ return+ if not await is_feature_enabled(Flag.HIRE_EXPERTS, user_id, default=False):+ return++ # Marker next: one Redis GET is the rest of the cost of the common+ # case. Resolving the timezone is a DB read, and this runs on+ # every chat turn, so it must stay behind this gate.+ if await _read_registration_marker(user_id) is not None:+ return++ tz = await _resolve_user_timezone(user_id)+ if tz is None:+ # Lookup failed — "unknown" is not "UTC". Re-registering would+ # silently rebind the user's local-time cron to UTC; leave the+ # existing cron and stored tz untouched until a later call+ # resolves the real timezone.+ return++ # Lazy client handle, mirroring dream/scheduling.py: a flag-off+ # user never even constructs the scheduler client, and the lazy+ # import avoids a circular import during process bootstrap.+ from backend.util.clients import get_scheduler_client++ await get_scheduler_client().add_morning_briefing_schedule(+ user_id=user_id, user_timezone=tz+ )+ await _write_registration_marker(user_id, tz)+ logger.info(+ "Morning briefing: registered cron for user %s (tz=%s)",+ user_id[:12],+ tz,+ )+ except Exception:+ logger.warning(+ "Morning briefing: failed to register cron for user %s",+ user_id[:12],+ exc_info=True,+ )diff --git a/autogpt_platform/backend/backend/copilot/briefing/scheduling_test.py b/autogpt_platform/backend/backend/copilot/briefing/scheduling_test.pynew file mode 100644index 0000000000..a783905eea--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/briefing/scheduling_test.py@@ -0,0 +1,290 @@+"""Morning-briefing auto-registration tests.++Single-job counterpart to ``backend/copilot/dream/scheduling_test.py``.+Contracts pinned here:++ 1. Empty ``user_id`` → no-op, no flag check, no RPC.+ 2. Flag off → no-op, no timezone lookup, no RPC.+ 3. Timezone lookup failure is "unknown", not "UTC" — skip the cycle+ rather than risk re-registering onto UTC.+ 4. First call (no marker) registers the cron and writes the marker.+ 5. Marker present → no-op: no timezone lookup (a DB read on the hot+ chat path) and no RPC.+ 6. Cleared marker (the ``update_user_timezone`` path) → re-registers+ with the current timezone and rewrites the marker.+ 7. ``ensure_morning_briefing_scheduled`` never raises — it's fired+ via ``asyncio.create_task`` from a hot request path.+ 8. ``_resolve_user_timezone`` behaviors copied from the dream module:+ missing user is authoritative UTC, DB failure is None (unknown),+ unset timezone falls back to UTC.+ 9. ``clear_briefing_registration_marker`` deletes the single key and+ swallows Redis failures.+"""++from __future__ import annotations++import logging+from unittest.mock import AsyncMock, MagicMock, patch++import pytest++from . import scheduling+from .scheduling import (+ BRIEFING_REGISTRATION_PREFIX,+ REGISTRATION_TTL_SECONDS,+ clear_briefing_registration_marker,+ ensure_morning_briefing_scheduled,+)++# Paths used by the helper — patched at the module level since the helper+# does lazy imports of the scheduler client + Redis client to avoid+# bootstrap circular imports (same pattern as backend/copilot/dream).+_PATH_FLAG = "backend.copilot.briefing.scheduling.is_feature_enabled"+_PATH_TZ = "backend.copilot.briefing.scheduling._resolve_user_timezone"+_PATH_READ_TZ = "backend.copilot.briefing.scheduling._read_registration_marker"+_PATH_WRITE_TZ = "backend.copilot.briefing.scheduling._write_registration_marker"+_PATH_CLIENT = "backend.util.clients.get_scheduler_client"+++def _mock_scheduler_client(*, fail: bool = False) -> MagicMock:+ client = MagicMock()+ if fail:+ client.add_morning_briefing_schedule = AsyncMock(+ side_effect=RuntimeError("scheduler down")+ )+ else:+ client.add_morning_briefing_schedule = AsyncMock(+ return_value={+ "id": "morning_briefing_abc",+ "user_id": "abc",+ "next_run_time": None,+ }+ )+ return client+++# ---------------------------------------------------------------------------+# Empty / null user_id+# ---------------------------------------------------------------------------+++async def test_empty_user_id_no_op():+ flag_mock = AsyncMock(return_value=True)+ with patch(_PATH_FLAG, new=flag_mock):+ await ensure_morning_briefing_scheduled("")++ flag_mock.assert_not_called()+++# ---------------------------------------------------------------------------+# Flag gate+# ---------------------------------------------------------------------------+++async def test_flag_off_no_op():+ client = _mock_scheduler_client()+ tz_mock = AsyncMock(return_value="UTC")+ with patch(_PATH_FLAG, new=AsyncMock(return_value=False)), patch(+ _PATH_TZ, new=tz_mock+ ), patch(_PATH_CLIENT, return_value=client):+ await ensure_morning_briefing_scheduled("abc")++ tz_mock.assert_not_called()+ client.add_morning_briefing_schedule.assert_not_called()+++# ---------------------------------------------------------------------------+# Timezone lookup failure — "unknown" must not become "UTC"+# ---------------------------------------------------------------------------+++async def test_timezone_lookup_failure_skips_registration():+ client = _mock_scheduler_client()+ write_spy = AsyncMock()+ with patch(_PATH_FLAG, new=AsyncMock(return_value=True)), patch(+ _PATH_TZ, new=AsyncMock(return_value=None)+ ), patch(_PATH_READ_TZ, new=AsyncMock(return_value=None)), patch(+ _PATH_WRITE_TZ, new=write_spy+ ), patch(+ _PATH_CLIENT, return_value=client+ ):+ await ensure_morning_briefing_scheduled("abc")++ client.add_morning_briefing_schedule.assert_not_called()+ write_spy.assert_not_called()+++# ---------------------------------------------------------------------------+# First registration+# ---------------------------------------------------------------------------+++async def test_first_call_registers_and_writes_marker():+ client = _mock_scheduler_client()+ write_spy = AsyncMock()+ with patch(_PATH_FLAG, new=AsyncMock(return_value=True)), patch(+ _PATH_TZ, new=AsyncMock(return_value="America/New_York")+ ), patch(_PATH_READ_TZ, new=AsyncMock(return_value=None)), patch(+ _PATH_WRITE_TZ, new=write_spy+ ), patch(+ _PATH_CLIENT, return_value=client+ ):+ await ensure_morning_briefing_scheduled("abc")++ client.add_morning_briefing_schedule.assert_awaited_once_with(+ user_id="abc", user_timezone="America/New_York"+ )+ write_spy.assert_awaited_once_with("abc", "America/New_York")+++# ---------------------------------------------------------------------------+# Marker present — no-op, and crucially no DB read on the hot chat path+# ---------------------------------------------------------------------------+++async def test_existing_marker_skips_timezone_lookup_and_registration():+ client = _mock_scheduler_client()+ tz_mock = AsyncMock(return_value="America/New_York")+ with patch(_PATH_FLAG, new=AsyncMock(return_value=True)), patch(+ _PATH_TZ, new=tz_mock+ ), patch(_PATH_READ_TZ, new=AsyncMock(return_value="America/New_York")), patch(+ _PATH_CLIENT, return_value=client+ ):+ await ensure_morning_briefing_scheduled("abc")++ tz_mock.assert_not_called()+ client.add_morning_briefing_schedule.assert_not_called()+++# ---------------------------------------------------------------------------+# Cleared marker (timezone change) — re-registers on the current timezone+# ---------------------------------------------------------------------------+++async def test_cleared_marker_reregisters_on_current_timezone():+ client = _mock_scheduler_client()+ write_spy = AsyncMock()+ with patch(_PATH_FLAG, new=AsyncMock(return_value=True)), patch(+ _PATH_TZ, new=AsyncMock(return_value="Europe/Paris")+ ), patch(_PATH_READ_TZ, new=AsyncMock(return_value=None)), patch(+ _PATH_WRITE_TZ, new=write_spy+ ), patch(+ _PATH_CLIENT, return_value=client+ ):+ await ensure_morning_briefing_scheduled("abc")++ client.add_morning_briefing_schedule.assert_awaited_once_with(+ user_id="abc", user_timezone="Europe/Paris"+ )+ write_spy.assert_awaited_once_with("abc", "Europe/Paris")+++# ---------------------------------------------------------------------------+# Never raises — fired via asyncio.create_task from a hot request path+# ---------------------------------------------------------------------------+++async def test_scheduler_rpc_failure_is_swallowed_and_logged(caplog):+ client = _mock_scheduler_client(fail=True)+ with patch(_PATH_FLAG, new=AsyncMock(return_value=True)), patch(+ _PATH_TZ, new=AsyncMock(return_value="UTC")+ ), patch(_PATH_READ_TZ, new=AsyncMock(return_value=None)), patch(+ _PATH_WRITE_TZ, new=AsyncMock()+ ), patch(+ _PATH_CLIENT, return_value=client+ ), caplog.at_level(+ logging.WARNING, logger=scheduling.logger.name+ ):+ await ensure_morning_briefing_scheduled("abc") # must not raise++ assert any(r.levelno == logging.WARNING for r in caplog.records)+++async def test_unexpected_flag_check_error_is_swallowed():+ with patch(+ _PATH_FLAG, new=AsyncMock(side_effect=ConnectionError("LD unreachable"))+ ):+ await ensure_morning_briefing_scheduled("abc") # must not raise+++# ---------------------------------------------------------------------------+# _resolve_user_timezone — copied logic, behaviors pinned+# ---------------------------------------------------------------------------+++async def test_resolve_user_timezone_missing_user_is_authoritative_utc():+ accessor = MagicMock()+ accessor.get_user_by_id = AsyncMock(side_effect=ValueError("User not found"))+ with patch("backend.copilot.briefing.scheduling.user_db", return_value=accessor):+ assert await scheduling._resolve_user_timezone("abc") == "UTC"+++async def test_resolve_user_timezone_returns_none_when_db_lookup_fails():+ accessor = MagicMock()+ accessor.get_user_by_id = AsyncMock(side_effect=ConnectionError("db down"))+ with patch("backend.copilot.briefing.scheduling.user_db", return_value=accessor):+ assert await scheduling._resolve_user_timezone("abc") is None+++async def test_resolve_user_timezone_unset_value_falls_back_to_utc():+ from backend.data.model import USER_TIMEZONE_NOT_SET++ accessor = MagicMock()+ accessor.get_user_by_id = AsyncMock(+ return_value=MagicMock(timezone=USER_TIMEZONE_NOT_SET)+ )+ with patch("backend.copilot.briefing.scheduling.user_db", return_value=accessor):+ assert await scheduling._resolve_user_timezone("abc") == "UTC"+++# ---------------------------------------------------------------------------+# clear_briefing_registration_marker+# ---------------------------------------------------------------------------+++async def test_clear_marker_deletes_the_registration_key():+ redis = AsyncMock()+ with patch(+ "backend.copilot.briefing.scheduling.get_redis_async",+ new=AsyncMock(return_value=redis),+ ):+ await clear_briefing_registration_marker("abc")+ redis.delete.assert_awaited_once_with(f"{BRIEFING_REGISTRATION_PREFIX}:abc")+++async def test_clear_marker_swallows_redis_failure(caplog):+ with patch(+ "backend.copilot.briefing.scheduling.get_redis_async",+ new=AsyncMock(side_effect=ConnectionError("redis down")),+ ), caplog.at_level(logging.WARNING, logger=scheduling.logger.name):+ await clear_briefing_registration_marker("abc") # must not raise++ warnings = [r for r in caplog.records if r.levelno == logging.WARNING]+ assert any("marker will expire via TTL" in r.getMessage() for r in warnings)+ assert any(r.exc_info is not None for r in warnings)+++# ---------------------------------------------------------------------------+# Module constants+# ---------------------------------------------------------------------------+++def test_registration_ttl_bounds_the_recheck_window():+ assert REGISTRATION_TTL_SECONDS == 7 * 24 * 3600+++# Suppress "imported but unused" — ``scheduling`` is the module under test.+_ = schedulingdiff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.pyindex 6aab982f08..34863affb4 100644--- a/autogpt_platform/backend/backend/copilot/db.py+++ b/autogpt_platform/backend/backend/copilot/db.py@@ -1100,3 +1100,66 @@ async def append_expert_run_message(message_id=message_id,)return session_id+++async def append_plain_session_message(+ user_id: str,+ content: str,+ message_id: str,+ metadata: dict[str, Any] | None = None,+) -> str | None:+ """Post an assistant message into the user's latest non-expert (plain+ Autopilot) session, creating one when none exists — this is the user's+ "primary thread", e.g. where a morning briefing lands.++ Deduplicates on *message_id* (deterministic per event at the caller), so+ retries and double-fires never produce duplicate posts.+ Returns the session id the message landed in, or None when deduped.+ """+ existing = await PrismaChatMessage.prisma().find_unique(where={"id": message_id})+ if existing is not None:+ return None++ # Dream-pass sessions are also ``expertId IS NULL`` but are hidden from+ # every listing surface (see :data:`_EXCLUDE_DREAM_SESSIONS_SQL`), so+ # posting into one would drop the message somewhere the user can never+ # open. Same exclusion as the listing queries.+ sessions = await db.query_raw_with_schema(+ 'SELECT * FROM {schema_prefix}"ChatSession" WHERE "userId" = $1 '+ f'AND "expertId" IS NULL AND {_EXCLUDE_DREAM_SESSIONS_SQL} '+ 'ORDER BY "updatedAt" DESC LIMIT 1',+ user_id,+ model=PrismaChatSession,+ )+ if sessions:+ session_id = sessions[0].id+ else:+ created = await create_chat_session(+ session_id=str(uuid.uuid4()), user_id=user_id+ )+ session_id = created.session_id++ async def write_with_fresh_sequence() -> None:+ await add_chat_message(+ session_id=session_id,+ role="assistant",+ sequence=await get_next_sequence(session_id),+ content=content,+ message_id=message_id,+ metadata=metadata,+ )++ # Same Redis NX lock as append_expert_run_message: the sequence read ++ # insert must not interleave with a concurrent turn writer picking the+ # same sequence and PK-colliding on (sessionId, sequence).+ async with _get_session_lock(session_id):+ try:+ await write_with_fresh_sequence()+ except UniqueViolationError as e:+ if is_duplicate_chat_message_id_error(e):+ return None+ # Reachable only in lock-degraded mode (Redis down yields the+ # lock without acquiring); one retry with a fresh sequence is+ # enough at this write volume.+ await write_with_fresh_sequence()+ return session_iddiff --git a/autogpt_platform/backend/backend/copilot/plain_session_post_test.py b/autogpt_platform/backend/backend/copilot/plain_session_post_test.pynew file mode 100644index 0000000000..11d8ccc7f5--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/plain_session_post_test.py@@ -0,0 +1,181 @@+"""Integration tests for append_plain_session_message."""++import logging+from uuid import uuid4++import pytest+from prisma.errors import UniqueViolationError+from prisma.models import ChatMessage, Expert, User++from backend.copilot import db as copilot_db+from backend.copilot.model import ChatSessionMetadata+from backend.util.test import SpinTestServer++logger = logging.getLogger(__name__)+++async def _create_user(user_id: str) -> None:+ try:+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"plain-session-{user_id}@example.com",+ "name": "Plain Session Test",+ }+ )+ except UniqueViolationError:+ pass+++async def _cleanup(user_id: str) -> None:+ try:+ # ChatSession -> User, ChatMessage -> ChatSession, and Expert.ownerUserId+ # -> User are all onDelete: Cascade, so deleting the user sweeps+ # everything created for it, including any expert + expert-scoped+ # session set up for the discrimination check below.+ await User.prisma().delete_many(where={"id": user_id})+ except Exception as exc:+ logger.warning("cleanup for %s failed: %s", user_id, exc)++[email protected](loop_scope="session")+async def test_append_plain_session_message_creates_session_and_dedupes(+ server: SpinTestServer,+):+ user_id = f"plain-session-{uuid4()}"+ await _create_user(user_id)+ try:+ message_id = str(uuid4())++ session_id = await copilot_db.append_plain_session_message(+ user_id=user_id,+ content="## Briefing",+ message_id=message_id,+ metadata={"kind": "morning_briefing"},+ )+ assert session_id is not None++ # Same message id -> dedup, no second message.+ assert (+ await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing", message_id=message_id+ )+ is None+ )++ # Reuses the latest plain session instead of creating another.+ second = await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing 2", message_id=str(uuid4())+ )+ assert second == session_id++ # An expert-scoped session that is the MOST RECENTLY updated session+ # for this user must still be skipped -- the {"expertId": None}+ # filter has to actively discriminate, not just "reuse whatever's+ # newest." Without the filter this would wrongly post into the+ # expert's thread.+ expert = await Expert.prisma().create(+ data={+ "ownerUserId": user_id,+ "name": "Test Expert",+ "role": "assistant",+ "identity": "test",+ }+ )+ expert_session = await copilot_db.create_chat_session(+ session_id=str(uuid4()), user_id=user_id, expert_id=expert.id+ )+ assert expert_session.session_id != session_id++ third = await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing 3", message_id=str(uuid4())+ )+ assert third == session_id+ assert third != expert_session.session_id++ expert_messages = await ChatMessage.prisma().find_many(+ where={"sessionId": expert_session.session_id}+ )+ assert expert_messages == []+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_append_plain_session_message_retries_on_sequence_collision(+ server: SpinTestServer, mocker+):+ """Lock-degraded path: a sequence PK collision (not a duplicate message+ id) must be retried once with a fresh sequence rather than propagating."""+ user_id = f"plain-session-retry-{uuid4()}"+ await _create_user(user_id)+ try:+ real_add_chat_message = copilot_db.add_chat_message+ calls = {"n": 0}++ async def collide_once(*args, **kwargs):+ calls["n"] += 1+ if calls["n"] == 1:+ # A (sessionId, sequence) collision, NOT a duplicate+ # ChatMessage id — the branch under test.+ raise UniqueViolationError(+ {+ "user_facing_error": {+ "message": "Unique constraint failed on the "+ "fields: (`sessionId`,`sequence`)"+ }+ }+ )+ return await real_add_chat_message(*args, **kwargs)++ mocker.patch.object(copilot_db, "add_chat_message", side_effect=collide_once)++ message_id = str(uuid4())+ session_id = await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing", message_id=message_id+ )++ assert calls["n"] == 2 # first write collided, retry succeeded+ assert session_id is not None+ stored = await ChatMessage.prisma().find_unique(where={"id": message_id})+ assert stored is not None+ assert stored.sessionId == session_id+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_append_plain_session_message_skips_dream_sessions(+ server: SpinTestServer,+):+ """Dream sessions are also ``expertId IS NULL`` but are hidden from every+ listing surface, so a briefing posted into one is invisible forever — and+ still gets stamped delivered."""+ user_id = f"plain-session-dream-{uuid4()}"+ await _create_user(user_id)+ try:+ plain = await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing", message_id=str(uuid4())+ )+ assert plain is not None++ # Created after the plain session, so it is the most recently updated+ # expertId-IS-NULL session for this user.+ dream_session = await copilot_db.create_chat_session(+ session_id=str(uuid4()),+ user_id=user_id,+ metadata=ChatSessionMetadata(kind="dream"),+ )+ assert dream_session.session_id != plain++ landed = await copilot_db.append_plain_session_message(+ user_id=user_id, content="## Briefing 2", message_id=str(uuid4())+ )++ assert landed == plain+ dream_messages = await ChatMessage.prisma().find_many(+ where={"sessionId": dream_session.session_id}+ )+ assert dream_messages == []+ finally:+ await _cleanup(user_id)diff --git a/autogpt_platform/backend/backend/data/briefing.py b/autogpt_platform/backend/backend/data/briefing.pynew file mode 100644index 0000000000..0e4e6e3647--- /dev/null+++ b/autogpt_platform/backend/backend/data/briefing.py@@ -0,0 +1,112 @@+from datetime import date, datetime, time, timezone+from typing import Any++import prisma.errors+import prisma.models+from pydantic import BaseModel++from backend.util.json import SafeJson++# Serialized BriefingContent (see backend/copilot/briefing/models.py). Left+# untyped at this layer so a shape written by another composer version still+# round-trips; callers re-validate against the model.+BriefingContentJson = dict[str, Any]++# Upper bound on how far back get_latest_briefings looks for a readable+# briefing when the newest rows fail validation.+_LATEST_BRIEFING_SCAN_LIMIT = 5+++class BriefingRecord(BaseModel):+ id: str+ user_id: str+ briefing_date: date+ content: BriefingContentJson+ created_at: datetime+ delivered_at: datetime | None = None++ @classmethod+ def from_db(cls, row: prisma.models.UserBriefing) -> "BriefingRecord":+ return cls(+ id=row.id,+ user_id=row.userId,+ briefing_date=row.briefingDate.date(),+ content=dict(row.content) if row.content else {},+ created_at=row.createdAt,+ delivered_at=row.deliveredAt,+ )+++def _as_db_date(briefing_date: date) -> datetime:+ return datetime.combine(briefing_date, time.min, tzinfo=timezone.utc)+++async def create_briefing(+ user_id: str, briefing_date: date, content: BriefingContentJson+) -> BriefingRecord:+ try:+ row = await prisma.models.UserBriefing.prisma().create(+ data={+ "userId": user_id,+ "briefingDate": _as_db_date(briefing_date),+ "content": SafeJson(content),+ }+ )+ except prisma.errors.UniqueViolationError:+ existing = await prisma.models.UserBriefing.prisma().find_first(+ where={"userId": user_id, "briefingDate": _as_db_date(briefing_date)}+ )+ if existing is None:+ raise+ return BriefingRecord.from_db(existing)+ return BriefingRecord.from_db(row)+++async def get_briefing_for_date(+ user_id: str, briefing_date: date+) -> BriefingRecord | None:+ row = await prisma.models.UserBriefing.prisma().find_first(+ where={"userId": user_id, "briefingDate": _as_db_date(briefing_date)}+ )+ return BriefingRecord.from_db(row) if row else None+++async def update_briefing_content(+ user_id: str, briefing_id: str, content: BriefingContentJson+) -> None:+ """Overwrite a stored briefing's content.++ Used when a stored row can't be re-validated against the current+ ``BriefingContent`` shape: the generator recomposes and writes the fresh+ content back, so the stored row and the message it posts stay in sync.+ """+ await prisma.models.UserBriefing.prisma().update_many(+ where={"id": briefing_id, "userId": user_id},+ data={"content": SafeJson(content)},+ )+++async def mark_briefing_delivered(user_id: str, briefing_id: str) -> None:+ await prisma.models.UserBriefing.prisma().update_many(+ where={"id": briefing_id, "userId": user_id},+ data={"deliveredAt": datetime.now(timezone.utc)},+ )+++async def get_latest_briefings(+ user_id: str, limit: int = _LATEST_BRIEFING_SCAN_LIMIT+) -> list[BriefingRecord]:+ """Return the user's most recent briefings, newest covered date first.++ More than one is returned so a caller that re-validates stored content+ can fall back to the newest *readable* briefing instead of showing+ nothing when a single corrupt row happens to sit on the newest date.++ Ordered by briefingDate, not createdAt: a backfill or retry can write an+ earlier date's briefing after a later date's already exists, and the+ "latest" briefing means the latest date it covers, not insertion order.+ """+ rows = await prisma.models.UserBriefing.prisma().find_many(+ where={"userId": user_id}, order={"briefingDate": "desc"}, take=limit+ )+ return [BriefingRecord.from_db(row) for row in rows]diff --git a/autogpt_platform/backend/backend/data/briefing_test.py b/autogpt_platform/backend/backend/data/briefing_test.pynew file mode 100644index 0000000000..77dd2936c8--- /dev/null+++ b/autogpt_platform/backend/backend/data/briefing_test.py@@ -0,0 +1,138 @@+"""Integration tests for the briefing data layer."""++import logging+from datetime import date, timedelta+from uuid import uuid4++import pytest+from prisma.errors import UniqueViolationError+from prisma.models import User, UserBriefing++from backend.data import briefing+from backend.util.test import SpinTestServer++logger = logging.getLogger(__name__)+++async def _create_user(user_id: str) -> None:+ try:+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"briefing-{user_id}@example.com",+ "name": "Briefing Test",+ }+ )+ except UniqueViolationError:+ pass+++async def _cleanup(user_id: str) -> None:+ try:+ await UserBriefing.prisma().delete_many(where={"userId": user_id})+ await User.prisma().delete_many(where={"id": user_id})+ except Exception as exc:+ logger.warning("cleanup for %s failed: %s", user_id, exc)++[email protected](loop_scope="session")+async def test_create_and_get_briefing(server: SpinTestServer):+ user_id = f"briefing-{uuid4()}"+ await _create_user(user_id)+ try:+ content = {"run_items": [], "decision_items": [{"title": "Approve email"}]}++ record = await briefing.create_briefing(user_id, date(2026, 8, 7), content)+ assert record.user_id == user_id+ assert record.content["decision_items"][0]["title"] == "Approve email"++ again = await briefing.create_briefing(+ user_id, date(2026, 8, 7), {"other": True}+ )+ assert again.id == record.id # idempotent per (user, date)++ assert (+ await briefing.get_briefing_for_date(user_id, date(2026, 8, 7))+ ).id == record.id+ assert (await briefing.get_briefing_for_date(user_id, date(2026, 8, 8))) is None+ assert (await briefing.get_latest_briefings(user_id))[0].id == record.id+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_get_latest_briefings_order_by_briefing_date_not_created_at(+ server: SpinTestServer,+):+ """A backfill/retry can write an earlier date's briefing after a later+ date's already exists; "latest" must mean the latest date covered, not+ insertion order."""+ user_id = f"briefing-order-{uuid4()}"+ await _create_user(user_id)+ try:+ later = await briefing.create_briefing(+ user_id, date(2026, 8, 10), {"which": "later-date"}+ )+ earlier = await briefing.create_briefing(+ user_id, date(2026, 8, 5), {"which": "earlier-date-inserted-second"}+ )+ # Force the out-of-order insertion the test depends on: createdAt has+ # millisecond precision, so back-to-back inserts can tie and make an+ # `earlier.created_at > later.created_at` assertion flaky.+ await UserBriefing.prisma().update(+ where={"id": earlier.id},+ data={"createdAt": later.created_at + timedelta(seconds=1)},+ )++ latest = await briefing.get_latest_briefings(user_id)+ assert [record.id for record in latest] == [later.id, earlier.id]+ assert latest[0].briefing_date == date(2026, 8, 10)+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_update_briefing_content_is_user_scoped(server: SpinTestServer):+ user_id = f"briefing-update-{uuid4()}"+ await _create_user(user_id)+ try:+ record = await briefing.create_briefing(+ user_id, date(2026, 8, 7), {"which": "original"}+ )++ await briefing.update_briefing_content(+ f"not-{user_id}", record.id, {"which": "foreign-overwrite"}+ )+ untouched = await briefing.get_briefing_for_date(user_id, date(2026, 8, 7))+ assert untouched is not None+ assert untouched.content == {"which": "original"}++ await briefing.update_briefing_content(+ user_id, record.id, {"which": "recomposed"}+ )+ updated = await briefing.get_briefing_for_date(user_id, date(2026, 8, 7))+ assert updated is not None+ assert updated.content == {"which": "recomposed"}+ finally:+ await _cleanup(user_id)++[email protected](loop_scope="session")+async def test_mark_briefing_delivered_is_user_scoped(server: SpinTestServer):+ user_id = f"briefing-delivered-{uuid4()}"+ await _create_user(user_id)+ try:+ record = await briefing.create_briefing(user_id, date(2026, 8, 7), {"k": "v"})+ assert record.delivered_at is None++ await briefing.mark_briefing_delivered(f"not-{user_id}", record.id)+ undelivered = await briefing.get_briefing_for_date(user_id, date(2026, 8, 7))+ assert undelivered is not None+ assert undelivered.delivered_at is None # foreign user can't mark it++ await briefing.mark_briefing_delivered(user_id, record.id)+ delivered = await briefing.get_briefing_for_date(user_id, date(2026, 8, 7))+ assert delivered is not None+ assert delivered.delivered_at is not None+ finally:+ await _cleanup(user_id)diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 3c1377f81c..8ab53b2e66 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -17,6 +17,7 @@ from backend.api.features.library.db import (get_library_agent,get_library_agent_by_graph_id,get_library_agent_id_by_graph_id,+ get_library_agent_refs_by_graph_ids,get_preset,get_root_agent_summaries,list_folders,@@ -60,6 +61,13 @@ from backend.data.block import (get_blocks_needing_optimization,update_block_optimized_description,)+from backend.data.briefing import (+ create_briefing,+ get_briefing_for_date,+ get_latest_briefings,+ mark_briefing_delivered,+ update_briefing_content,+)from backend.data.credit import (UsageTransactionMetadata,get_user_credit_model,@@ -103,6 +111,7 @@ from backend.data.human_review import (delete_review_by_node_exec_id,get_or_create_human_review,get_pending_reviews_for_execution,+ get_pending_reviews_for_user,get_reviews_by_node_exec_ids,has_pending_reviews_for_graph_exec,update_review_processed_status,@@ -329,6 +338,7 @@ class DatabaseManager(AppService):delete_review_by_node_exec_id = _(delete_review_by_node_exec_id)get_or_create_human_review = _(get_or_create_human_review)get_pending_reviews_for_execution = _(get_pending_reviews_for_execution)+ get_pending_reviews_for_user = _(get_pending_reviews_for_user)get_reviews_by_node_exec_ids = _(get_reviews_by_node_exec_ids)has_pending_reviews_for_graph_exec = _(has_pending_reviews_for_graph_exec)update_review_processed_status = _(update_review_processed_status)@@ -350,6 +360,7 @@ class DatabaseManager(AppService):list_library_agents = _(list_library_agents)add_store_agent_to_library = _(add_store_agent_to_library)get_library_agent_id_by_graph_id = _(get_library_agent_id_by_graph_id)+ get_library_agent_refs_by_graph_ids = _(get_library_agent_refs_by_graph_ids)create_graph_in_library = _(create_graph_in_library)create_library_agent = _(create_library_agent)get_library_agent = _(get_library_agent)@@ -517,7 +528,16 @@ class DatabaseManager(AppService):update_chat_session_status = _(chat_db.update_chat_session_status)get_chat_session_status = _(chat_db.get_chat_session_status)get_latest_user_message_in_session = _(chat_db.get_latest_user_message_in_session)- add_chat_message = _(chat_db.add_chat_message)++ # ============ Morning Briefing ============ #+ # Exposed so the Prisma-less scheduler process can compose, store and+ # post a briefing via db_accessors / the DatabaseManager RPC.+ append_plain_session_message = _(chat_db.append_plain_session_message)+ create_briefing = _(create_briefing)+ get_briefing_for_date = _(get_briefing_for_date)+ get_latest_briefings = _(get_latest_briefings)+ mark_briefing_delivered = _(mark_briefing_delivered)+ update_briefing_content = _(update_briefing_content)class DatabaseManagerClient(AppServiceClient):@@ -570,6 +590,15 @@ class DatabaseManagerClient(AppServiceClient):append_expert_run_message = _(d.append_expert_run_message)get_library_agent_id_by_graph_id = _(d.get_library_agent_id_by_graph_id)+ # Morning briefing (scheduler cron; runs Prisma-less)+ append_plain_session_message = _(d.append_plain_session_message)+ create_briefing = _(d.create_briefing)+ get_briefing_for_date = _(d.get_briefing_for_date)+ get_latest_briefings = _(d.get_latest_briefings)+ mark_briefing_delivered = _(d.mark_briefing_delivered)+ update_briefing_content = _(d.update_briefing_content)+ get_library_agent_refs_by_graph_ids = _(d.get_library_agent_refs_by_graph_ids)+# Storeget_store_agents = _(d.get_store_agents)get_store_agent_details = _(d.get_store_agent_details)@@ -631,6 +660,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):delete_review_by_node_exec_id = d.delete_review_by_node_exec_idget_or_create_human_review = d.get_or_create_human_reviewget_pending_reviews_for_execution = d.get_pending_reviews_for_execution+ get_pending_reviews_for_user = d.get_pending_reviews_for_userget_reviews_by_node_exec_ids = d.get_reviews_by_node_exec_idsupdate_review_processed_status = d.update_review_processed_status@@ -653,8 +683,17 @@ class DatabaseManagerAsyncClient(AppServiceClient):d.get_user_notification_oldest_message_in_batch)+ # ============ Morning Briefing ============ #+ append_plain_session_message = d.append_plain_session_message+ create_briefing = d.create_briefing+ get_briefing_for_date = d.get_briefing_for_date+ get_latest_briefings = d.get_latest_briefings+ mark_briefing_delivered = d.mark_briefing_delivered+ update_briefing_content = d.update_briefing_content+# ============ Library ============ #list_library_agents = d.list_library_agents+ get_library_agent_refs_by_graph_ids = d.get_library_agent_refs_by_graph_idsadd_store_agent_to_library = d.add_store_agent_to_librarycreate_graph_in_library = d.create_graph_in_librarycreate_library_agent = d.create_library_agentdiff --git a/autogpt_platform/backend/backend/data/human_review.py b/autogpt_platform/backend/backend/data/human_review.pyindex c2ac3d102b..bf697d2a5c 100644--- a/autogpt_platform/backend/backend/data/human_review.py+++ b/autogpt_platform/backend/backend/data/human_review.py@@ -9,7 +9,13 @@ from datetime import datetime, timezonefrom typing import TYPE_CHECKING, Optionalfrom prisma.enums import ReviewStatus-from prisma.models import AgentNodeExecution, PendingHumanReview+from prisma.models import (+ AgentGraphExecution,+ AgentNodeExecution,+ ChatSession,+ LibraryAgent,+ PendingHumanReview,+)from prisma.types import PendingHumanReviewUpdateInputfrom pydantic import BaseModel@@ -18,6 +24,7 @@ from backend.api.features.executions.review.model import (SafeJsonData,)from backend.copilot.constants import (+ COPILOT_SESSION_PREFIX,is_copilot_synthetic_id,parse_node_id_from_exec_id,)@@ -371,12 +378,9 @@ async def get_pending_reviews_for_user(page_size: Number of reviews per pageReturns:- List of pending review models with node_id included+ List of pending review models, enriched with node_id and (where+ resolvable) expert/agent attribution."""- # Local import to avoid event loop conflicts in tests- from backend.data.execution import get_node_execution-- # Calculate offset for paginationoffset = (page - 1) * page_sizereviews = await PendingHumanReview.prisma().find_many(@@ -386,13 +390,138 @@ async def get_pending_reviews_for_user(take=page_size,)- # Fetch node_id for each review from NodeExecution- result = []- for review in reviews:- node_id = await _resolve_node_id(review.nodeExecId, get_node_execution)- result.append(PendingHumanReviewModel.from_db(review, node_id=node_id))+ models = [PendingHumanReviewModel.from_db(review, node_id="") for review in reviews]+ return await _enrich_pending_reviews(user_id, models)- return result++async def _enrich_pending_reviews(+ user_id: str, reviews: list[PendingHumanReviewModel]+) -> list[PendingHumanReviewModel]:+ """Batch-resolve node_id and attach expert/agent attribution.++ Resolves, in a fixed number of batched, ``userId``-scoped queries+ rather than one round-trip per row:+ - ``node_id``, from the node executions+ - expert attribution (from the graph execution, or from the chat+ session for CoPilot run_block reviews)+ - the requesting agent's display name and library agent id+ - the chat session id, for CoPilot run_block reviews++ Mutates and returns the given models in place.+ """+ real_exec_ids = [+ r.graph_exec_id for r in reviews if not is_copilot_synthetic_id(r.graph_exec_id)+ ]+ session_ids = [+ r.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)+ for r in reviews+ if r.graph_exec_id.startswith(COPILOT_SESSION_PREFIX)+ ]+ real_node_exec_ids = [+ r.node_exec_id for r in reviews if not is_copilot_synthetic_id(r.node_exec_id)+ ]++ # These three reads don't depend on each other; the library lookup below+ # does (it needs the graph ids the executions resolve to). Running them+ # concurrently costs this endpoint two round-trips instead of four —+ # it backs the home needs-attention list, refetched on every focus.+ node_execs, executions, sessions = await asyncio.gather(+ _node_executions_for(user_id, real_node_exec_ids),+ _graph_executions_for(user_id, real_exec_ids),+ _chat_sessions_for(user_id, session_ids),+ )+ node_id_by_exec = {ne.id: ne.agentNodeId for ne in node_execs}+ exec_by_id = {e.id: e for e in executions}+ session_by_id = {s.id: s for s in sessions}++ graph_ids = list({e.agentGraphId for e in executions})+ lib_agents = (+ await LibraryAgent.prisma().find_many(+ # Soft-deleted rows are excluded like every other library+ # lookup: linking to one produces a 404 instead of falling+ # through to the /library fallback the deep link has for+ # exactly this case.+ where={+ "userId": user_id,+ "agentGraphId": {"in": graph_ids},+ "isDeleted": False,+ },+ # @@unique([userId, agentGraphId, agentGraphVersion]) allows+ # several rows per graph; ordering makes "newest version wins"+ # deterministic rather than whichever row came back last.+ order=[{"agentGraphVersion": "asc"}],+ )+ if graph_ids+ else []+ )+ lib_by_graph = {a.agentGraphId: a for a in lib_agents}++ for r in reviews:+ if is_copilot_synthetic_id(r.node_exec_id):+ r.node_id = parse_node_id_from_exec_id(r.node_exec_id)+ else:+ r.node_id = node_id_by_exec.get(r.node_exec_id, r.node_exec_id)++ execution = exec_by_id.get(r.graph_exec_id)+ if execution:+ r.expert_id = execution.expertId+ if execution.Expert:+ r.expert_name = execution.Expert.name+ r.expert_avatar_url = execution.Expert.avatarUrl++ lib_agent = lib_by_graph.get(execution.agentGraphId)+ if lib_agent:+ r.library_agent_id = lib_agent.id+ r.agent_name = (lib_agent.name if lib_agent else None) or (+ execution.AgentGraph.name if execution.AgentGraph else None+ )+ elif r.graph_exec_id.startswith(COPILOT_SESSION_PREFIX):+ session_id = r.graph_exec_id.removeprefix(COPILOT_SESSION_PREFIX)+ r.session_id = session_id+ session = session_by_id.get(session_id)+ if session:+ r.expert_id = session.expertId+ if session.Expert:+ r.expert_name = session.Expert.name+ r.expert_avatar_url = session.Expert.avatarUrl++ return reviews+++async def _node_executions_for(+ user_id: str, node_exec_ids: list[str]+) -> list[AgentNodeExecution]:+ if not node_exec_ids:+ return []+ return await AgentNodeExecution.prisma().find_many(+ where={+ "id": {"in": node_exec_ids},+ # Callers pass ids from user-filtered PendingHumanReview rows,+ # but scope here too so this helper can never leak another+ # user's node executions if a future caller slips.+ "GraphExecution": {"is": {"userId": user_id}},+ }+ )+++async def _graph_executions_for(+ user_id: str, graph_exec_ids: list[str]+) -> list[AgentGraphExecution]:+ if not graph_exec_ids:+ return []+ return await AgentGraphExecution.prisma().find_many(+ where={"id": {"in": graph_exec_ids}, "userId": user_id},+ include={"Expert": True, "AgentGraph": True},+ )+++async def _chat_sessions_for(user_id: str, session_ids: list[str]) -> list[ChatSession]:+ if not session_ids:+ return []+ return await ChatSession.prisma().find_many(+ where={"id": {"in": session_ids}, "userId": user_id},+ include={"Expert": True},+ )async def get_pending_reviews_for_execution(diff --git a/autogpt_platform/backend/backend/data/human_review_enrichment_test.py b/autogpt_platform/backend/backend/data/human_review_enrichment_test.pynew file mode 100644index 0000000000..8e376353e3--- /dev/null+++ b/autogpt_platform/backend/backend/data/human_review_enrichment_test.py@@ -0,0 +1,281 @@+"""Integration tests for pending-review batching + expert attribution.++Covers get_pending_reviews_for_user's enrichment: expert attribution from+the graph execution (or, for CoPilot run_block reviews, from the chat+session), the requesting agent's display name, and the library agent id+used for run deep links.+"""++import logging+from uuid import uuid4++import pytest+from prisma.enums import ReviewStatus+from prisma.errors import UniqueViolationError+from prisma.models import (+ AgentBlock,+ AgentGraph,+ AgentGraphExecution,+ AgentNode,+ AgentNodeExecution,+ ChatSession,+ Expert,+ LibraryAgent,+ PendingHumanReview,+ User,+)++from backend.copilot.constants import COPILOT_NODE_PREFIX, COPILOT_SESSION_PREFIX+from backend.copilot.db import create_chat_session+from backend.data.human_review import get_pending_reviews_for_user+from backend.util.json import SafeJson+from backend.util.test import SpinTestServer++logger = logging.getLogger(__name__)++pytestmark = pytest.mark.asyncio(loop_scope="session")+++async def _create_user(user_id: str) -> None:+ try:+ await User.prisma().create(+ data={+ "id": user_id,+ "email": f"review-enrich-{user_id}@example.com",+ "name": "Review Enrichment Test",+ }+ )+ except UniqueViolationError:+ pass+++async def _create_graph(graph_id: str, user_id: str, name: str) -> None:+ await AgentGraph.prisma().create(+ data={+ "id": graph_id,+ "version": 1,+ "name": name,+ "description": "test",+ "userId": user_id,+ "isActive": True,+ }+ )+++async def _cleanup(user_id: str, graph_ids: list[str], session_ids: list[str]) -> None:+ try:+ await PendingHumanReview.prisma().delete_many(where={"userId": user_id})+ await AgentGraphExecution.prisma().delete_many(where={"userId": user_id})+ if session_ids:+ await ChatSession.prisma().delete_many(where={"id": {"in": session_ids}})+ await LibraryAgent.prisma().delete_many(where={"userId": user_id})+ for graph_id in graph_ids:+ await AgentGraph.prisma().delete_many(where={"id": graph_id})+ await Expert.prisma().delete_many(where={"ownerUserId": user_id})+ await User.prisma().delete_many(where={"id": user_id})+ except Exception as exc:+ logger.warning("cleanup for %s failed: %s", user_id, exc)+++async def test_pending_reviews_are_enriched(server: SpinTestServer):+ user_id = f"review-enrich-{uuid4()}"+ graph_id = str(uuid4())+ real_exec_id = str(uuid4())+ graph_ids = [graph_id]+ session_ids: list[str] = []++ await _create_user(user_id)+ try:+ await _create_graph(graph_id, user_id, "Lead Finder")++ ana = await Expert.prisma().create(+ data={+ "ownerUserId": user_id,+ "name": "Ana",+ "avatarUrl": "https://example.com/ana.png",+ "role": "Researcher",+ "identity": "You are Ana, a research expert.",+ }+ )++ lib_agent = await LibraryAgent.prisma().create(+ data={+ "userId": user_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": 1,+ "name": "Lead Finder",+ "isCreatedByUser": True,+ }+ )++ await AgentGraphExecution.prisma().create(+ data={+ "id": real_exec_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": 1,+ "userId": user_id,+ "expertId": ana.id,+ }+ )++ session = await create_chat_session(+ f"sess-{uuid4().hex[:8]}", user_id, expert_id=ana.id+ )+ session_ids.append(session.session_id)+ copilot_exec_id = f"{COPILOT_SESSION_PREFIX}{session.session_id}"++ await PendingHumanReview.prisma().create(+ data={+ "nodeExecId": f"node-exec-{uuid4()}",+ "userId": user_id,+ "graphExecId": real_exec_id,+ "graphId": graph_id,+ "graphVersion": 1,+ "payload": SafeJson({"foo": "bar"}),+ "editable": True,+ "status": ReviewStatus.WAITING,+ }+ )+ await PendingHumanReview.prisma().create(+ data={+ "nodeExecId": f"{COPILOT_NODE_PREFIX}some-block:{uuid4().hex[:8]}",+ "userId": user_id,+ "graphExecId": copilot_exec_id,+ "graphId": copilot_exec_id,+ "graphVersion": 1,+ "payload": SafeJson({"foo": "bar"}),+ "editable": True,+ "status": ReviewStatus.WAITING,+ }+ )++ reviews = await get_pending_reviews_for_user(user_id, 1, 25)+ by_exec = {r.graph_exec_id: r for r in reviews}++ real = by_exec[real_exec_id]+ assert real.expert_id == ana.id+ assert real.expert_name == "Ana"+ assert real.expert_avatar_url == "https://example.com/ana.png"+ assert real.agent_name == "Lead Finder"+ assert real.library_agent_id == lib_agent.id+ assert real.session_id is None++ copilot = by_exec[copilot_exec_id]+ assert copilot.session_id == session.session_id+ assert copilot.expert_id == ana.id+ assert copilot.expert_name == "Ana"+ finally:+ await _cleanup(user_id, graph_ids, session_ids)+++async def test_plain_run_review_has_null_expert(server: SpinTestServer):+ user_id = f"review-enrich-plain-{uuid4()}"+ graph_id = str(uuid4())+ plain_exec_id = str(uuid4())+ graph_ids = [graph_id]++ await _create_user(user_id)+ try:+ await _create_graph(graph_id, user_id, "Plain Agent")++ await LibraryAgent.prisma().create(+ data={+ "userId": user_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": 1,+ "name": "Plain Agent",+ "isCreatedByUser": True,+ }+ )++ await AgentGraphExecution.prisma().create(+ data={+ "id": plain_exec_id,+ "agentGraphId": graph_id,+ "agentGraphVersion": 1,+ "userId": user_id,+ }+ )++ await PendingHumanReview.prisma().create(+ data={+ "nodeExecId": f"node-exec-{uuid4()}",+ "userId": user_id,+ "graphExecId": plain_exec_id,+ "graphId": graph_id,+ "graphVersion": 1,+ "payload": SafeJson({"foo": "bar"}),+ "editable": True,+ "status": ReviewStatus.WAITING,+ }+ )++ reviews = await get_pending_reviews_for_user(user_id, 1, 25)+ plain = next(r for r in reviews if r.graph_exec_id == plain_exec_id)+ assert plain.expert_id is None+ assert plain.agent_name is not None+ finally:+ await _cleanup(user_id, graph_ids, [])+++async def test_enrichment_never_resolves_foreign_node_executions(+ server: SpinTestServer,+):+ """A review pointing at a node execution owned by another user must not+ resolve that user's node id — the lookup is user-scoped, so node_id+ falls back to the raw exec id."""+ user_id = f"review-enrich-scope-{uuid4()}"+ other_user_id = f"review-enrich-scope-other-{uuid4()}"+ other_graph_id = str(uuid4())+ other_exec_id = str(uuid4())++ await _create_user(user_id)+ await _create_user(other_user_id)+ try:+ await _create_graph(other_graph_id, other_user_id, "Their Agent")++ block = await AgentBlock.prisma().find_first()+ assert block is not None, "test DB should have seeded blocks"+ node = await AgentNode.prisma().create(+ data={+ "agentBlockId": block.id,+ "agentGraphId": other_graph_id,+ "agentGraphVersion": 1,+ }+ )+ await AgentGraphExecution.prisma().create(+ data={+ "id": other_exec_id,+ "agentGraphId": other_graph_id,+ "agentGraphVersion": 1,+ "userId": other_user_id,+ }+ )+ foreign_node_exec = await AgentNodeExecution.prisma().create(+ data={+ "agentGraphExecutionId": other_exec_id,+ "agentNodeId": node.id,+ }+ )++ await PendingHumanReview.prisma().create(+ data={+ "nodeExecId": foreign_node_exec.id,+ "userId": user_id,+ "graphExecId": other_exec_id,+ "graphId": other_graph_id,+ "graphVersion": 1,+ "payload": SafeJson({"foo": "bar"}),+ "editable": True,+ "status": ReviewStatus.WAITING,+ }+ )++ reviews = await get_pending_reviews_for_user(user_id, 1, 25)+ crossed = next(r for r in reviews if r.node_exec_id == foreign_node_exec.id)+ assert crossed.node_id == foreign_node_exec.id # fallback, not node.id+ assert crossed.expert_id is None+ assert crossed.agent_name is None+ finally:+ await _cleanup(user_id, [], [])+ await _cleanup(other_user_id, [other_graph_id], [])diff --git a/autogpt_platform/backend/backend/data/human_review_test.py b/autogpt_platform/backend/backend/data/human_review_test.pyindex baa5c0c0c4..60f97bce3b 100644--- a/autogpt_platform/backend/backend/data/human_review_test.py+++ b/autogpt_platform/backend/backend/data/human_review_test.py@@ -131,13 +131,23 @@ async def test_get_pending_reviews_for_user(mock_find_many = mocker.patch("backend.data.human_review.PendingHumanReview.prisma")mock_find_many.return_value.find_many = AsyncMock(return_value=[sample_db_review])- # Mock get_node_execution to return node with node_id (async function)+ # Mock the batched node_id resolution (AgentNodeExecution.prisma().find_many)mock_node_exec = Mock()- mock_node_exec.node_id = "test_node_def_789"- mocker.patch(- "backend.data.execution.get_node_execution",- new=AsyncMock(return_value=mock_node_exec),+ mock_node_exec.id = "test_node_123"+ mock_node_exec.agentNodeId = "test_node_def_789"+ mock_node_exec_prisma = mocker.patch(+ "backend.data.human_review.AgentNodeExecution.prisma"+ )+ mock_node_exec_prisma.return_value.find_many = AsyncMock(+ return_value=[mock_node_exec]+ )++ # Mock the batched graph-execution lookup empty, so the enrichment step's+ # dependent LibraryAgent/ChatSession queries are skipped entirely.+ mock_graph_exec_prisma = mocker.patch(+ "backend.data.human_review.AgentGraphExecution.prisma")+ mock_graph_exec_prisma.return_value.find_many = AsyncMock(return_value=[])result = await get_pending_reviews_for_user("test_user", page=2, page_size=10)diff --git a/autogpt_platform/backend/backend/data/user.py b/autogpt_platform/backend/backend/data/user.pyindex f4ab41c8b8..7975b5255d 100644--- a/autogpt_platform/backend/backend/data/user.py+++ b/autogpt_platform/backend/backend/data/user.py@@ -827,6 +827,37 @@ async def update_user_timezone(user_id: str, timezone: str) -> User:exc_info=True,)+ # Same rationale for the morning-briefing cron: clear the stored+ # marker first, since its mere presence short-circuits the helper,+ # then re-ensure so the profile change takes effect immediately+ # instead of waiting out the marker's TTL. Fire-and-forget like the dream task+ # above so the profile update doesn't block on Redis/scheduler+ # I/O, and guard the import so a failure here can't surface as a+ # false "failed to update timezone" after the row committed.+ try:+ from backend.copilot.briefing.scheduling import (+ clear_briefing_registration_marker,+ ensure_morning_briefing_scheduled,+ )++ async def _reregister_briefing() -> None:+ await clear_briefing_registration_marker(user_id)+ await ensure_morning_briefing_scheduled(user_id)++ task = asyncio.create_task(+ _reregister_briefing(),+ name=f"briefing-tz-reregister-{user_id[:12]}",+ )+ _background_tasks.add(task)+ task.add_done_callback(_on_background_task_done)+ except Exception:+ logger.warning(+ "Failed to spawn morning-briefing re-register after timezone "+ "update for user %s — lazy drift detection will catch it",+ user_id[:12],+ exc_info=True,+ )+return User.from_db(user)except Exception as e:raise DatabaseError(f"Failed to update timezone for user {user_id}: {e}") from ediff --git a/autogpt_platform/backend/backend/data/user_test.py b/autogpt_platform/backend/backend/data/user_test.pyindex 3873eea25b..89112cfe47 100644--- a/autogpt_platform/backend/backend/data/user_test.py+++ b/autogpt_platform/backend/backend/data/user_test.py@@ -84,6 +84,7 @@ class TestUpdateUserTimezone:time. A profile-page timezone change MUST eagerly re-registerthe dream-system crons so they fire at the right local timewithout waiting for the 7-day Redis dedup-key TTL to expire."""+ from backend.copilot.briefing import scheduling as briefing_schedulingfrom backend.copilot.dream import scheduling as dream_schedulingprisma_user = MagicMock(id="user-tz", email="[email protected]")@@ -102,6 +103,19 @@ class TestUpdateUserTimezone:patch.object(dream_scheduling, "ensure_dream_system_scheduled", new=fake_ensure),+ # This test isolates the dream-system re-registration contract;+ # the sibling morning-briefing re-registration (also wired here)+ # is covered separately by scheduling_test.py.+ patch.object(+ briefing_scheduling,+ "clear_briefing_registration_marker",+ new=AsyncMock(),+ ),+ patch.object(+ briefing_scheduling,+ "ensure_morning_briefing_scheduled",+ new=AsyncMock(),+ ),):mock_prisma_user.prisma.return_value.update = AsyncMock(return_value=prisma_user@@ -120,6 +134,7 @@ class TestUpdateUserTimezone:exception never observed. The spawn must keep a strong ref in``_background_tasks`` until done and log failures via thedone-callback instead of dropping them."""+ from backend.copilot.briefing import scheduling as briefing_schedulingfrom backend.copilot.dream import scheduling as dream_schedulingprisma_user = MagicMock(id="user-tz", email="[email protected]")@@ -136,6 +151,21 @@ class TestUpdateUserTimezone:patch.object(dream_scheduling, "ensure_dream_system_scheduled", new=failing_ensure),+ # Isolate the dream-system task-retention contract under test+ # from the sibling morning-briefing re-registration (also wired+ # here) — real Redis/flag I/O in that path would otherwise give+ # the event loop extra turns and let the dream task above+ # complete (and get discarded) before the assertion below runs.+ patch.object(+ briefing_scheduling,+ "clear_briefing_registration_marker",+ new=AsyncMock(),+ ),+ patch.object(+ briefing_scheduling,+ "ensure_morning_briefing_scheduled",+ new=AsyncMock(),+ ),patch.object(user_module.logger, "warning") as warn_mock,):mock_prisma_user.prisma.return_value.update = AsyncMock(@@ -159,6 +189,60 @@ class TestUpdateUserTimezone:warn_mock.assert_called_once()assert isinstance(warn_mock.call_args.kwargs["exc_info"], RuntimeError)+ @pytest.mark.asyncio+ async def test_briefing_re_register_runs_in_background_clear_first(self):+ """The briefing re-register must not block the profile update+ (it's a spawned task, like the dream sibling) and must clear the+ stored marker before re-ensuring, or the drift check would read+ the just-superseded timezone and skip the re-register."""+ from backend.copilot.briefing import scheduling as briefing_scheduling+ from backend.copilot.dream import scheduling as dream_scheduling++ prisma_user = MagicMock(id="user-tz", email="[email protected]")+ calls: list[str] = []++ async def fake_clear(user_id: str):+ calls.append("clear")++ async def fake_ensure(user_id: str):+ calls.append("ensure")++ with (+ patch.object(user_module, "PrismaUser") as mock_prisma_user,+ patch.object(user_module.User, "from_db", return_value=MagicMock()),+ patch.object(user_module.get_user_by_id, "cache_delete"),+ patch.object(user_module.get_user_by_email, "cache_delete"),+ patch.object(user_module.get_or_create_user, "cache_clear"),+ patch.object(+ dream_scheduling, "ensure_dream_system_scheduled", new=AsyncMock()+ ),+ patch.object(+ briefing_scheduling,+ "clear_briefing_registration_marker",+ new=fake_clear,+ ),+ patch.object(+ briefing_scheduling,+ "ensure_morning_briefing_scheduled",+ new=fake_ensure,+ ),+ ):+ mock_prisma_user.prisma.return_value.update = AsyncMock(+ return_value=prisma_user+ )+ await update_user_timezone("user-tz", "Europe/Paris")+ assert calls == [] # nothing ran inline — it's a background task++ spawned = [+ t+ for t in user_module._background_tasks+ if t.get_name() == "briefing-tz-reregister-user-tz"+ ]+ assert spawned, "briefing re-register task must be spawned + retained"+ await asyncio.gather(*spawned)++ assert calls == ["clear", "ensure"]+class TestTableBackedCredentials:"""get/set_user_credentials — the IntegrationCredential-backed seam thediff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 41942fbf39..690b8593fd 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -1,4 +1,5 @@import asyncio+import hashlibimport loggingimport osimport re@@ -556,6 +557,48 @@ def execute_community_rebuild(user_id: str):)+def _morning_briefing_crontab(user_id: str) -> str:+ """Daily 09:00-local cron, with the minute spread across the hour.++ A fixed ``0 9 * * *`` fires every user in a timezone at the same instant;+ deriving the minute from the user id spreads that batch over the hour.+ Hashed with sha256 rather than ``hash()`` because the latter is salted+ per process, which would move a user's slot on every restart.+ """+ minute = int(hashlib.sha256(user_id.encode("utf-8")).hexdigest(), 16) % 60+ return f"{minute} 9 * * *"+++def _job_timezone_name(job: JobObj) -> str | None:+ """IANA name of a cron job's trigger timezone, if it has one."""+ if isinstance(job.trigger, CronTrigger):+ return str(job.trigger.timezone)+ return None+++def execute_morning_briefing(user_id: str) -> None:+ """Per-user morning briefing cron body.++ Sync wrapper around the async ``generate_and_deliver_briefing`` so it+ can run on the APScheduler thread pool. Unlike+ ``execute_community_rebuild``, the coroutine does not guarantee it+ swallows every failure internally (DB / LLM calls can raise), so this+ wrapper must catch failures itself — an exception escaping a job body+ is fatal to that run, and one user's briefing must never affect+ scheduler health.+ """+ from backend.copilot.briefing.generate import generate_and_deliver_briefing++ try:+ result = run_async(+ generate_and_deliver_briefing(user_id),+ timeout=SCHEDULER_OPERATION_TIMEOUT_SECONDS,+ )+ logger.info("Morning briefing for user %s: %s", user_id[:12], result)+ except Exception as e:+ logger.error("Morning briefing failed for user %s: %s", user_id[:12], e)++def execute_nightly_batch_sync(user_id: str):"""Per-user nightly batch-family fan-out cron body.@@ -2093,6 +2136,73 @@ class Scheduler(AppService):timeout=SCHEDULER_DREAM_OPERATION_TIMEOUT_SECONDS,)+ # --- Morning briefing ---+ #+ # Daily per-user cron at user-local 09:00. The job body's flag gate and+ # idempotency (per local calendar date) live inside+ # ``generate_and_deliver_briefing`` itself, so — unlike community+ # rebuild — there's no registration-time flag check here.++ @expose+ def add_morning_briefing_schedule(+ self,+ user_id: str,+ user_timezone: str = "UTC",+ ) -> dict:+ """Register a daily morning briefing for one user.++ Re-registration with an unchanged timezone is a no-op rather than a+ ``replace_existing`` write: APScheduler recomputes ``next_run_time``+ on the replace path, so replacing a job whose 09:00 fire is already+ overdue (e.g. after a scheduler restart) would push it to tomorrow+ and lose that day's briefing entirely.+ """+ if not user_timezone:+ user_timezone = "UTC"++ job_id = f"morning_briefing_{user_id}"+ existing = self.scheduler.get_job(job_id, jobstore=Jobstores.EXECUTION.value)+ if existing is not None and _job_timezone_name(existing) == user_timezone:+ return {+ "id": existing.id,+ "user_id": user_id,+ "user_timezone": user_timezone,+ "next_run_time": (+ existing.next_run_time.isoformat()+ if existing.next_run_time+ else None+ ),+ "skipped": True,+ "reason": "already_registered",+ }++ job = self.scheduler.add_job(+ execute_morning_briefing,+ kwargs={"user_id": user_id},+ trigger=CronTrigger.from_crontab(+ _morning_briefing_crontab(user_id), timezone=user_timezone+ ),+ id=job_id,+ name=f"Morning briefing for {user_id[:12]}",+ jobstore=Jobstores.EXECUTION.value,+ replace_existing=True,+ max_instances=1,+ )+ logger.info(+ "Registered morning briefing job %s for user %s in tz %s",+ job.id,+ user_id[:12],+ user_timezone,+ )+ return {+ "id": job.id,+ "user_id": user_id,+ "user_timezone": user_timezone,+ "next_run_time": (+ job.next_run_time.isoformat() if job.next_run_time else None+ ),+ }+# --- Dream nightly batch (P-0.2 + P-0.4 consolidated) ---## ONE per-user cron at user-local 03:00 fans out all batch-family@@ -2311,6 +2421,10 @@ class SchedulerClient(AppServiceClient):Scheduler.execute_community_rebuild_pass)+ add_morning_briefing_schedule = endpoint_to_async(+ Scheduler.add_morning_briefing_schedule+ )+add_nightly_batch_schedule = endpoint_to_async(Scheduler.add_nightly_batch_schedule)delete_nightly_batch_schedule = endpoint_to_async(Scheduler.delete_nightly_batch_schedulediff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.pyindex 3f57ece2b7..b9073ad52f 100644--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py@@ -5,6 +5,7 @@ the copilot-turn scheduling feature so they're exercised by the regularbackend test job (and counted by codecov), not just the integration suite."""+import loggingfrom datetime import datetime, timedelta, timezonefrom unittest.mock import AsyncMock, MagicMock, patch@@ -683,3 +684,111 @@ class TestScheduleOrgVisibility:]result = self._run(infos, user_id="me")assert [r.schedule_id for r in result] == ["mine"]+++# ---------------------------------------------------------------------------+# add_morning_briefing_schedule / execute_morning_briefing+# ---------------------------------------------------------------------------+++class TestMorningBriefingSchedule:+ """Registration kwargs and the job body's failure containment."""++ def _register(self, existing=None, **kwargs) -> MagicMock:+ sched = Scheduler.__new__(Scheduler)+ sched.scheduler = MagicMock()+ sched.scheduler.get_job.return_value = existing+ sched.scheduler.add_job.return_value = MagicMock(+ id="morning_briefing_user-1", next_run_time=None+ )+ Scheduler.add_morning_briefing_schedule(sched, **kwargs)+ return sched.scheduler.add_job++ def test_registers_daily_9am_cron_in_the_users_timezone(self):+ add_job = self._register(user_id="user-1", user_timezone="America/New_York")++ add_job.assert_called_once()+ call_kwargs = add_job.call_args.kwargs+ assert call_kwargs["id"] == "morning_briefing_user-1"+ assert call_kwargs["kwargs"] == {"user_id": "user-1"}+ assert call_kwargs["replace_existing"] is True+ assert call_kwargs["max_instances"] == 1++ trigger = call_kwargs["trigger"]+ assert str(trigger.timezone) == "America/New_York"+ # CronTrigger stringifies its fields; pin the 09:00 daily contract.+ # The minute is spread per user, so only the hour is fixed.+ assert "hour='9'" in str(trigger)++ def test_empty_timezone_falls_back_to_utc(self):+ add_job = self._register(user_id="user-1", user_timezone="")++ assert str(add_job.call_args.kwargs["trigger"].timezone) == "UTC"++ def test_reregistering_the_same_timezone_leaves_the_job_alone(self):+ """APScheduler recomputes next_run_time on the replace path, so+ re-adding an unchanged job would push an already-overdue 09:00 fire to+ tomorrow and silently lose that day's briefing."""+ existing = MagicMock(+ id="morning_briefing_user-1",+ next_run_time=datetime(2026, 8, 7, 13, 0, tzinfo=timezone.utc),+ trigger=CronTrigger.from_crontab("7 9 * * *", timezone="America/New_York"),+ )++ add_job = self._register(+ existing=existing, user_id="user-1", user_timezone="America/New_York"+ )++ add_job.assert_not_called()++ def test_a_changed_timezone_still_rewrites_the_job(self):+ existing = MagicMock(+ id="morning_briefing_user-1",+ next_run_time=None,+ trigger=CronTrigger.from_crontab("7 9 * * *", timezone="America/New_York"),+ )++ add_job = self._register(+ existing=existing, user_id="user-1", user_timezone="Europe/Madrid"+ )++ add_job.assert_called_once()+ assert str(add_job.call_args.kwargs["trigger"].timezone) == "Europe/Madrid"++ def test_the_fire_minute_is_stable_per_user_and_spread_across_users(self):+ """A fixed "0 9 * * *" fires every user in a timezone at once; the+ minute must vary by user but never move between restarts."""+ from backend.executor.scheduler import _morning_briefing_crontab++ assert _morning_briefing_crontab("user-1") == _morning_briefing_crontab(+ "user-1"+ )+ minutes = {+ _morning_briefing_crontab(f"user-{i}").split(" ")[0] for i in range(50)+ }+ assert len(minutes) > 10+ assert all(0 <= int(m) < 60 for m in minutes)++ def test_job_body_swallows_and_logs_generation_failures(self, caplog):+ """The cron body exists to keep one user's failure off the scheduler."""+ from backend.executor.scheduler import execute_morning_briefing++ with (+ # MagicMock, not AsyncMock: run_async is stubbed out, so an+ # unawaited coroutine here would only raise a RuntimeWarning.+ patch(+ "backend.copilot.briefing.generate.generate_and_deliver_briefing",+ new=MagicMock(),+ ),+ patch(+ f"{_SCHEDULER_PATH}.run_async",+ side_effect=RuntimeError("briefing boom"),+ ),+ caplog.at_level(logging.ERROR),+ ):+ execute_morning_briefing("user-1") # must not raise++ assert any(+ r.levelno == logging.ERROR and "Morning briefing failed" in r.getMessage()+ for r in caplog.records+ )diff --git a/autogpt_platform/backend/backend/util/background.py b/autogpt_platform/backend/backend/util/background.pynew file mode 100644index 0000000000..27b927bf1f--- /dev/null+++ b/autogpt_platform/backend/backend/util/background.py@@ -0,0 +1,33 @@+"""Fire-and-forget task spawning that survives garbage collection."""++import asyncio+import logging+from typing import Coroutine++logger = logging.getLogger(__name__)++# asyncio only keeps weak references to running tasks, so a task nobody holds+# can be collected mid-flight. This module-level set is the strong reference;+# the done-callback drops it again.+_background_tasks: set[asyncio.Task] = set()+++def _on_done(task: asyncio.Task) -> None:+ _background_tasks.discard(task)+ if task.cancelled():+ return+ exc = task.exception()+ if exc is not None:+ logger.warning("Background task %s failed", task.get_name(), exc_info=exc)+++def spawn_background_task(coro: Coroutine, *, name: str) -> asyncio.Task:+ """Run ``coro`` detached from the caller, keeping a strong ref to it.++ Detached tasks have no awaiter, so their exceptions would otherwise go+ unobserved; failures are logged rather than lost.+ """+ task = asyncio.create_task(coro, name=name)+ _background_tasks.add(task)+ task.add_done_callback(_on_done)+ return taskdiff --git a/autogpt_platform/backend/backend/util/background_test.py b/autogpt_platform/backend/backend/util/background_test.pynew file mode 100644index 0000000000..d5c87dc2cb--- /dev/null+++ b/autogpt_platform/backend/backend/util/background_test.py@@ -0,0 +1,68 @@+import asyncio+import logging++import pytest++from backend.util.background import _background_tasks, spawn_background_task+++async def test_spawn_background_task_holds_a_strong_reference_until_done():+ """asyncio only weak-refs running tasks, so the module set is what keeps a+ detached task from being collected mid-flight."""+ started = asyncio.Event()+ release = asyncio.Event()++ async def work() -> None:+ started.set()+ await release.wait()++ task = spawn_background_task(work(), name="held-task")+ await started.wait()+ assert task in _background_tasks++ release.set()+ await task+ assert task not in _background_tasks+++async def test_spawn_background_task_logs_failures_instead_of_swallowing_them(+ caplog: pytest.LogCaptureFixture,+):+ """A detached task has no awaiter, so a raised exception would otherwise go+ unobserved."""++ async def boom() -> None:+ raise ValueError("kaboom")++ with caplog.at_level(logging.WARNING, logger="backend.util.background"):+ task = spawn_background_task(boom(), name="failing-task")+ with pytest.raises(ValueError):+ await task+ # The done-callback runs on the next loop iteration.+ await asyncio.sleep(0)++ assert task not in _background_tasks+ assert any(+ "failing-task" in record.getMessage() and record.exc_info+ for record in caplog.records+ )+++async def test_spawn_background_task_does_not_log_cancellation():+ started = asyncio.Event()++ async def work() -> None:+ started.set()+ await asyncio.sleep(60)++ task = spawn_background_task(work(), name="cancelled-task")+ await started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ await asyncio.sleep(0)++ assert task not in _background_tasksdiff --git a/autogpt_platform/backend/backend/util/feature_flag.py b/autogpt_platform/backend/backend/util/feature_flag.pyindex 7bcb52d18a..5309b3a04b 100644--- a/autogpt_platform/backend/backend/util/feature_flag.py+++ b/autogpt_platform/backend/backend/util/feature_flag.py@@ -92,6 +92,14 @@ class Flag(str, Enum):# only.DREAM_PASS_ENABLED = "dream-pass-enabled"+ # Mirror of the frontend `hire-experts` flag (same LaunchDarkly key,+ # so both sides evaluate one cohort switch). Gates the experts+ # surface, including the scheduled morning-briefing job end-to-end:+ # schedule registration, generation, and delivery. Deliberately no+ # independent briefing kill switch — briefings ship to exactly the+ # experts cohort.+ HIRE_EXPERTS = "hire-experts"+# Per-feature gate for the web-fact-check tool (P0.5). The tool# can only DEMOTE memories on contradiction; new web-derived# facts ride the ratification loop as tentative. Off on thediff --git a/autogpt_platform/backend/migrations/20260807120631_add_user_briefing/migration.sql b/autogpt_platform/backend/migrations/20260807120631_add_user_briefing/migration.sqlnew file mode 100644index 0000000000..f6f2861efa--- /dev/null+++ b/autogpt_platform/backend/migrations/20260807120631_add_user_briefing/migration.sql@@ -0,0 +1,16 @@+-- CreateTable+CREATE TABLE "UserBriefing" (+ "id" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "userId" TEXT NOT NULL,+ "briefingDate" DATE NOT NULL,+ "content" JSONB NOT NULL,++ CONSTRAINT "UserBriefing_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "UserBriefing_userId_briefingDate_key" ON "UserBriefing"("userId", "briefingDate");++-- AddForeignKey+ALTER TABLE "UserBriefing" ADD CONSTRAINT "UserBriefing_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/autogpt_platform/backend/migrations/20260807215500_add_user_briefing_delivered_at/migration.sql b/autogpt_platform/backend/migrations/20260807215500_add_user_briefing_delivered_at/migration.sqlnew file mode 100644index 0000000000..68a5b0ba2f--- /dev/null+++ b/autogpt_platform/backend/migrations/20260807215500_add_user_briefing_delivered_at/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "UserBriefing" ADD COLUMN "deliveredAt" TIMESTAMP(3);diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex f02380aace..f3f422d11a 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -136,6 +136,7 @@ model User {CreditTransactions CreditTransaction[]UserBalance UserBalance?ChatSessions ChatSession[]+ UserBriefings UserBriefing[]AgentPresets AgentPreset[]LibraryAgents LibraryAgent[]LibraryFolders LibraryFolder[]@@ -288,6 +289,29 @@ model OnboardingBrainDump {@@index([userId])}+model UserBriefing {+ id String @id @default(uuid())+ createdAt DateTime @default(now())++ userId String+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)++ // Local calendar date the briefing covers, in the user's timezone at generation time.+ briefingDate DateTime @db.Date++ // Serialized BriefingContent (see backend/copilot/briefing/models.py).+ content Json++ // Set only after the briefing was posted into the user's copilot thread.+ // Null means the session post failed (or hasn't happened yet) — the next+ // generation run for the same date retries delivery instead of skipping.+ deliveredAt DateTime?++ // Every read is by user + date (latest-first or exact date), so the unique+ // index above serves them all — no secondary index to pay for on write.+ @@unique([userId, briefingDate])+}+//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// USER WORKSPACE TABLES /////////////////diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/CopilotHome.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/CopilotHome.tsxnew file mode 100644index 0000000000..03d378bf3e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/CopilotHome.tsx@@ -0,0 +1,52 @@+"use client";++import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { NeedsAttentionList } from "@/components/organisms/NeedsAttentionList/NeedsAttentionList";+import type { ReactNode } from "react";+import { BriefingCard } from "./components/BriefingCard/BriefingCard";+import { TeamStrip } from "./components/TeamStrip/TeamStrip";+import { useCopilotHome } from "./useCopilotHome";++interface Props {+ fallback: ReactNode;+}++// The briefing-first block of the copilot home. Mounted *inside*+// EmptySession rather than beside it, so the experts cohort keeps the+// onboarding surface (welcome dialog, greeting flow, suggestion themes) and+// the composer's recipient picker, which live there.+export function CopilotHome({ fallback }: Props) {+ const {+ briefing,+ isLoadingBriefing,+ isBriefingError,+ refetchBriefing,+ hasBriefing,+ } = useCopilotHome();++ return (+ <>+ {/* Briefing card slot — falls back to whatever the caller renders in+ its place only when a successful fetch says there is no briefing+ yet; a failed fetch shows the error card so it can't masquerade as+ "no briefing". Nothing renders until load settles so the fallback+ doesn't flash for users who do have a briefing. */}+ {isLoadingBriefing ? null : isBriefingError ? (+ <ErrorCard+ context="briefing"+ httpError={{ message: "Failed to load your briefing" }}+ onRetry={() => refetchBriefing()}+ className="mb-5"+ />+ ) : hasBriefing && briefing ? (+ <BriefingCard briefing={briefing} />+ ) : (+ fallback+ )}++ <NeedsAttentionList />++ <TeamStrip />+ </>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/flag-off.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/flag-off.test.tsxnew file mode 100644index 0000000000..f33348e3b6--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/flag-off.test.tsx@@ -0,0 +1,134 @@+import { expect, test, vi } from "vitest";+import { render, screen } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import {+ getGetV2ListLibraryAgentsMockHandler,+ getGetV2ListLibraryAgentsResponseMock,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import { getGetBriefingsGetLatestBriefingMockHandler200 } from "@/app/api/__generated__/endpoints/briefings/briefings.msw";+import { getGetV2GetPendingReviewsMockHandler200 } from "@/app/api/__generated__/endpoints/executions/executions.msw";+import { EmptySession } from "../../EmptySession/EmptySession";++// The mirror of main.test.tsx: everything the briefing home adds rides the+// experts flag, so with it off the pre-existing pulse strip must be what+// renders and none of the new surfaces may mount.+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {+ const actual =+ await importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) => flag === actual.Flag.AGENT_BRIEFING,+ };+});++const baseProps = {+ inputLayoutId: "test-layout",+ isCreatingSession: false,+ onCreateSession: vi.fn(),+ onSend: vi.fn(),+};++function mockHomeData() {+ const base = getGetV2ListLibraryAgentsResponseMock();+ server.use(+ getGetV2ListLibraryAgentsMockHandler({+ ...base,+ agents: [+ { ...base.agents[0], graph_id: "g-1", has_external_trigger: true },+ ],+ pagination: {+ total_items: 1,+ total_pages: 1,+ current_page: 1,+ page_size: 100,+ },+ }),+ getGetV1ListAllExecutionsMockHandler([]),+ // Both would render something if the briefing home mounted anyway.+ getGetV2GetPendingReviewsMockHandler200([+ {+ node_exec_id: "ne-1",+ node_id: "n-1",+ user_id: "u-1",+ graph_exec_id: "run-1",+ graph_id: "g-1",+ graph_version: 1,+ payload: { to: "[email protected]" },+ instructions: "Approve outreach email",+ editable: true,+ status: "WAITING",+ expert_id: "exp-1",+ expert_name: "Ana",+ expert_avatar_url: null,+ agent_name: "Lead Finder",+ library_agent_id: "lib-1",+ session_id: null,+ created_at: new Date(),+ },+ ]),+ getGetBriefingsGetLatestBriefingMockHandler200({+ id: "briefing-1",+ briefing_date: new Date(),+ created_at: new Date(),+ delivered_at: new Date(),+ content: {+ generated_at: new Date(),+ timezone: "UTC",+ zero_expert_fallback: false,+ run_items: [+ {+ expert_id: "expert-1",+ expert_name: "Sales Scout",+ expert_avatar_url: null,+ agent_name: "Lead Finder",+ graph_id: "graph-1",+ execution_id: "exec-1",+ library_agent_id: "lib-1",+ status: "COMPLETED",+ summary: "Found 3 leads",+ link: "/library/agents/lib-1?activeTab=runs&activeItem=exec-1",+ },+ ],+ decision_items: [],+ },+ }),+ );+}++test("keeps the pulse strip and mounts no briefing home when experts is off", async () => {+ mockHomeData();++ // Absence of the rendered text alone could pass just because the briefing+ // hadn't resolved yet. The briefing and pending-review queries only exist+ // inside CopilotHome, so "never requested" is the durable proof the gate+ // held — and it fails loudly if the gate is removed.+ const requestedPaths: string[] = [];+ function record({ request }: { request: Request }) {+ requestedPaths.push(new URL(request.url).pathname);+ }+ server.events.on("request:start", record);++ try {+ render(<EmptySession {...baseProps} />);++ // The pulse strip only renders once its own library + executions+ // requests have resolved, so by here a mounted CopilotHome would have+ // fired its queries too.+ expect(+ await screen.findByText("What's happening with your agents"),+ ).toBeDefined();++ expect(requestedPaths.some((path) => path.includes("briefing"))).toBe(+ false,+ );+ expect(requestedPaths.some((path) => path.includes("review"))).toBe(false);+ expect(screen.queryByText("What ran")).toBeNull();+ expect(screen.queryByText("What was found")).toBeNull();+ expect(screen.queryByText(/Needs your attention/)).toBeNull();+ } finally {+ server.events.removeListener("request:start", record);+ }+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsxnew file mode 100644index 0000000000..03ac69ebae--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/__tests__/main.test.tsx@@ -0,0 +1,415 @@+import { expect, test, vi } from "vitest";+import { http, HttpResponse } from "msw";+import { render, screen } from "@/tests/integrations/test-utils";+import { server } from "@/mocks/mock-server";+import {+ getGetV2ListLibraryAgentsMockHandler,+ getGetV2ListLibraryAgentsResponseMock,+} from "@/app/api/__generated__/endpoints/library/library.msw";+import { getGetV1ListAllExecutionsMockHandler } from "@/app/api/__generated__/endpoints/graphs/graphs.msw";+import { getGetBriefingsGetLatestBriefingMockHandler200 } from "@/app/api/__generated__/endpoints/briefings/briefings.msw";+import { getListExpertsMockHandler200 } from "@/app/api/__generated__/endpoints/experts/experts.msw";+import { getGetV1ListExecutionSchedulesForAUserMockHandler } from "@/app/api/__generated__/endpoints/schedules/schedules.msw";+import { getGetV2GetPendingReviewsMockHandler200 } from "@/app/api/__generated__/endpoints/executions/executions.msw";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { EmptySession } from "../../EmptySession/EmptySession";++// Rendered through EmptySession, not CopilotHome directly: the briefing home+// mounts inside it, and the onboarding surface + composer recipient picker+// that live there must survive the experts flag being on.+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {+ const actual =+ await importActual<+ typeof import("@/services/feature-flags/use-get-flag")+ >();+ return {+ ...actual,+ useGetFlag: (flag: string) =>+ flag === actual.Flag.HIRE_EXPERTS || flag === actual.Flag.AGENT_BRIEFING,+ };+});++const baseProps = {+ inputLayoutId: "test-layout",+ isCreatingSession: false,+ onCreateSession: vi.fn(),+ onSend: vi.fn(),+};++// Guarantees the pulse strip has at least one chip regardless of faker's+// random defaults — an agent with an external trigger always produces a+// "listening" sitrep item. Also pins pending reviews to empty since the+// generated mock otherwise returns 1-10 random reviews by default, which+// would make the needs-attention slot non-deterministic across tests.+function mockPulseStripAgent() {+ const base = getGetV2ListLibraryAgentsResponseMock();+ server.use(+ getGetV2ListLibraryAgentsMockHandler({+ ...base,+ agents: [+ { ...base.agents[0], graph_id: "g-1", has_external_trigger: true },+ ],+ pagination: {+ total_items: 1,+ total_pages: 1,+ current_page: 1,+ page_size: 100,+ },+ }),+ getGetV1ListAllExecutionsMockHandler([]),+ getGetV2GetPendingReviewsMockHandler200([]),+ );+}++const pendingReview: PendingHumanReviewModel = {+ node_exec_id: "ne-1",+ node_id: "n-1",+ user_id: "u-1",+ graph_exec_id: "run-1",+ graph_id: "g-1",+ graph_version: 1,+ payload: { to: "[email protected]" },+ instructions: "Approve outreach email",+ editable: true,+ status: "WAITING",+ expert_id: "exp-1",+ expert_name: "Ana",+ expert_avatar_url: null,+ agent_name: "Lead Finder",+ library_agent_id: "lib-1",+ session_id: null,+ created_at: new Date(),+};++const healthyExpert: Expert = {+ id: "expert-healthy",+ name: "Sales Scout",+ avatar_url: null,+ role: "Sales Researcher",+ bio: null,+ skills: [],+ tagline: "Finds leads while you sleep",+ identity: "You are a senior sales researcher.",+ voice_preferences: "",+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [],+ last_run_at: new Date("2026-08-06T10:00:00Z"),+ last_run_status: "COMPLETED",+};++const pausedExpert: Expert = {+ id: "expert-paused",+ name: "Support Bot",+ avatar_url: null,+ role: "Support Triager",+ bio: null,+ skills: [],+ tagline: "Triages tickets",+ identity: "You are a support triager.",+ voice_preferences: "",+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [],+ schedules_paused_at: new Date("2026-08-05T10:00:00Z"),+};++const needsSetupExpert: Expert = {+ id: "expert-needs-setup",+ name: "Ops Analyst",+ avatar_url: null,+ role: "Operations Analyst",+ bio: null,+ skills: [],+ tagline: "Keeps the ops dashboard current",+ identity: "You are an operations analyst.",+ voice_preferences: "",+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [+ {+ id: "wf-1",+ store_listing_version_id: "slv-1",+ library_agent_id: "lib-1",+ graph_id: "graph-1",+ name: "Daily Report",+ description: null,+ schedule_cron: "0 9 * * *",+ schedule_id: null,+ },+ ],+};++function mockTeamStrip() {+ server.use(+ getListExpertsMockHandler200([healthyExpert, pausedExpert]),+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),+ );+}++test("renders greeting and composer", async () => {+ mockPulseStripAgent();+ render(<EmptySession {...baseProps} />);+ expect(await screen.findByPlaceholderText(/./)).toBeDefined();+});++test("falls back to pulse strip when there is no briefing", async () => {+ mockPulseStripAgent();+ server.use(getGetBriefingsGetLatestBriefingMockHandler200(null));+ render(<EmptySession {...baseProps} />);+ expect(+ await screen.findByText("What's happening with your agents"),+ ).toBeDefined();+});++test("renders briefing sections when a briefing is available", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200({+ id: "briefing-1",+ briefing_date: new Date(),+ created_at: new Date(),+ delivered_at: new Date(),+ content: {+ generated_at: new Date(),+ timezone: "UTC",+ zero_expert_fallback: false,+ run_items: [+ {+ expert_id: "expert-1",+ expert_name: "Sales Scout",+ expert_avatar_url: null,+ agent_name: "Lead Finder",+ graph_id: "graph-1",+ execution_id: "exec-1",+ library_agent_id: "lib-1",+ status: "COMPLETED",+ summary: "Found 3 leads",+ link: "/library/agents/lib-1/runs/exec-1",+ },+ {+ expert_id: "expert-2",+ expert_name: "Support Bot",+ expert_avatar_url: null,+ agent_name: "Ticket Triager",+ graph_id: "graph-2",+ execution_id: "exec-2",+ library_agent_id: "lib-2",+ status: "FAILED",+ summary: null,+ link: "/library/agents/lib-2/runs/exec-2",+ },+ ],+ decision_items: [+ {+ node_exec_id: "node-1",+ graph_exec_id: "graph-exec-1",+ title: "Approve outreach email",+ expert_id: "expert-1",+ expert_name: "Sales Scout",+ expert_avatar_url: null,+ link: "/library/agents/lib-1/runs/exec-1?node=node-1",+ },+ ],+ },+ }),+ );+ render(<EmptySession {...baseProps} />);++ expect(await screen.findByText("What ran")).toBeDefined();+ expect(screen.getByText("What was found")).toBeDefined();+ // Findings carry their agent name, matching the thread markdown.+ const finding = screen.getByText(/Found 3 leads/);+ expect(finding.textContent).toContain("Lead Finder");++ // The card does not repeat the decisions: the needs-attention list below+ // shows the same pending reviews, and it can act on them.+ expect(screen.queryByText(/Needs your decision/)).toBeNull();+});++test("renders the team strip with hired experts", async () => {+ mockPulseStripAgent();+ server.use(getGetBriefingsGetLatestBriefingMockHandler200(null));+ mockTeamStrip();+ render(<EmptySession {...baseProps} />);++ expect(await screen.findByText("Sales Scout")).toBeDefined();+ expect(screen.getByText("Support Bot")).toBeDefined();+ expect(screen.getByText("Paused")).toBeDefined();++ // Each Chat link names its expert, so screen readers can tell the+ // repeated links apart.+ expect(+ screen+ .getByRole("link", { name: "Chat with Sales Scout" })+ .getAttribute("href"),+ ).toBe("/copilot?expertId=expert-healthy");+ expect(+ screen+ .getByRole("link", { name: "Chat with Support Bot" })+ .getAttribute("href"),+ ).toBe("/copilot?expertId=expert-paused");+});++test("uses singular grammar for a single workflow needing setup", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200(null),+ getListExpertsMockHandler200([needsSetupExpert]),+ getGetV1ListExecutionSchedulesForAUserMockHandler([]),+ );+ render(<EmptySession {...baseProps} />);++ expect(await screen.findByText("1 workflow needs setup")).toBeDefined();+});++test("renders a needs-attention row when a review is pending", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200(null),+ getGetV2GetPendingReviewsMockHandler200([pendingReview]),+ );+ render(<EmptySession {...baseProps} />);++ expect(await screen.findByText("Approve outreach email")).toBeDefined();+});++test("does not render the needs-attention slot when there are no pending reviews", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200(null),+ getGetV2GetPendingReviewsMockHandler200([]),+ );+ render(<EmptySession {...baseProps} />);++ await screen.findByText("What's happening with your agents");+ expect(screen.queryByText(/Needs your attention/)).toBeNull();+});++test("shows an error card instead of the pulse strip when the briefing fetch fails", async () => {+ mockPulseStripAgent();+ server.use(+ http.get("/api/proxy/api/briefings/latest", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );+ render(<EmptySession {...baseProps} />);++ expect(await screen.findByText("Failed to load your briefing")).toBeDefined();+ expect(screen.queryByText("What's happening with your agents")).toBeNull();+});++test("shows an error card when the pending-reviews fetch fails", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200(null),+ http.get("/api/proxy/api/review/pending", () =>+ HttpResponse.json({ detail: "boom" }, { status: 500 }),+ ),+ );+ render(<EmptySession {...baseProps} />);++ expect(+ await screen.findByText("Failed to load pending reviews"),+ ).toBeDefined();+ expect(screen.queryByText(/Needs your attention/)).toBeNull();+});++test("keeps the onboarding surface and recipient picker with the experts flag on", async () => {+ // hire-experts and onboarding-brain-dump are independent flags aimed at+ // overlapping beta cohorts; the briefing home must not cancel the other+ // rollout out from under a brand-new user.+ mockPulseStripAgent();+ server.use(getGetBriefingsGetLatestBriefingMockHandler200(null));+ render(<EmptySession {...baseProps} />);++ // The composer's expert picker is the only way to address an expert from+ // the home, and it only renders behind the experts flag.+ expect(await screen.findByText("Autopilot")).toBeDefined();+ // Suggestion themes come from EmptySession, not the briefing block.+ expect(screen.getByPlaceholderText(/./)).toBeDefined();+});++test("renders a run row without a link when the briefing has no deep link", async () => {+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200({+ id: "briefing-1",+ briefing_date: new Date(),+ created_at: new Date(),+ delivered_at: null,+ content: {+ generated_at: new Date(),+ timezone: "UTC",+ zero_expert_fallback: false,+ run_items: [+ {+ expert_id: null,+ expert_name: null,+ expert_avatar_url: null,+ agent_name: "Unlinked Agent",+ graph_id: "graph-9",+ execution_id: "exec-9",+ library_agent_id: null,+ status: "COMPLETED",+ summary: null,+ link: null,+ },+ ],+ decision_items: [],+ decision_total: 0,+ },+ }),+ );+ render(<EmptySession {...baseProps} />);++ const row = await screen.findByText("Unlinked Agent");+ expect(row.closest("a")).toBeNull();+});++test("does not render a hollow briefing card when there are no runs", async () => {+ // A run paused on an approval is not terminal, so it never lands in "What+ // ran" — leaving a card that would show only a date.+ mockPulseStripAgent();+ server.use(+ getGetBriefingsGetLatestBriefingMockHandler200({+ id: "briefing-1",+ briefing_date: new Date(),+ created_at: new Date(),+ delivered_at: null,+ content: {+ generated_at: new Date(),+ timezone: "UTC",+ zero_expert_fallback: false,+ run_items: [],+ decision_items: [+ {+ node_exec_id: "node-1",+ graph_exec_id: "graph-exec-1",+ title: "Approve outreach email",+ expert_id: null,+ expert_name: null,+ expert_avatar_url: null,+ link: "/library",+ },+ ],+ decision_total: 1,+ },+ }),+ );+ render(<EmptySession {...baseProps} />);++ await screen.findByPlaceholderText(/./);+ expect(screen.queryByText("This morning")).toBeNull();+ expect(screen.queryByText("What ran")).toBeNull();+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/BriefingCard.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/BriefingCard.tsxnew file mode 100644index 0000000000..718e84f15e--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/BriefingCard.tsx@@ -0,0 +1,119 @@+import Link from "next/link";+import type { BriefingResponse } from "@/app/api/__generated__/models/briefingResponse";+import type { BriefingRunItem } from "@/app/api/__generated__/models/briefingRunItem";+import { Card } from "@/components/atoms/Card/Card";+import { Text } from "@/components/atoms/Text/Text";+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";+import { cn } from "@/lib/utils";+import { formatBriefingDate, isInternalLink } from "./helpers";++interface Props {+ briefing: BriefingResponse;+}++// The briefing's decision items are deliberately not rendered here: the same+// pending reviews already appear — and are actionable — in the+// needs-attention list directly below this card. They stay in the thread+// markdown, where there is no such list.+export function BriefingCard({ briefing }: Props) {+ const { run_items } = briefing.content;+ const foundItems = run_items.filter((item) => item.summary);++ // A briefing can be all decisions and no terminal runs (a run paused on an+ // approval never completes), which would render as a card containing just+ // a date. The needs-attention list below carries that case on its own.+ if (run_items.length === 0) return null;++ return (+ <Card className="mb-5 space-y-5 text-left">+ <Text variant="small" className="text-zinc-500">+ {formatBriefingDate(briefing.briefing_date)}+ </Text>++ {run_items.length > 0 ? (+ <section className="flex flex-col gap-3">+ <Text variant="h5">What ran</Text>+ <div className="flex flex-col gap-2">+ {run_items.map((item) => (+ <RunRow key={item.execution_id} item={item} />+ ))}+ </div>+ </section>+ ) : null}++ {foundItems.length > 0 ? (+ <section className="flex flex-col gap-3">+ <Text variant="h5">What was found</Text>+ <div className="flex flex-col gap-2">+ {foundItems.map((item) => (+ <Text+ key={item.execution_id}+ variant="body"+ className="text-zinc-700"+ >+ {/* Attribution matters once more than one agent reports:+ mirrors the thread markdown's "**{agent}**: {summary}". */}+ <span className="font-medium">{item.agent_name}</span>:{" "}+ {item.summary}+ </Text>+ ))}+ </div>+ </section>+ ) : null}+ </Card>+ );+}++function RunRow({ item }: { item: BriefingRunItem }) {+ const isFailed = item.status !== "COMPLETED";+ const subtitle = [item.expert_name, isFailed ? "Failed" : "Completed"]+ .filter(Boolean)+ .join(" · ");++ const body = (+ <>+ <ExpertAvatar+ name={item.expert_name}+ avatarUrl={item.expert_avatar_url}+ size={32}+ />+ <div className="min-w-0 flex-1">+ <Text+ variant="body-medium"+ className={cn("truncate", isFailed && "text-destructive")}+ >+ {item.agent_name}+ </Text>+ <Text+ variant="small"+ className={cn(+ "truncate text-zinc-500",+ isFailed && "text-destructive",+ )}+ >+ {subtitle}+ </Text>+ </div>+ </>+ );++ // Relative paths only: the backend composes these, but nothing else stops+ // a future regression from delivering an absolute or `javascript:` URL to+ // a Next.js <Link>.+ if (!item.link || !isInternalLink(item.link)) {+ return (+ <div className="flex items-center gap-3 rounded-xl border border-zinc-200 p-3">+ {body}+ </div>+ );+ }++ return (+ <Link+ href={item.link}+ className="flex items-center gap-3 rounded-xl border border-zinc-200 p-3"+ >+ {body}+ </Link>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.test.tsnew file mode 100644index 0000000000..4c81d270f5--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.test.ts@@ -0,0 +1,45 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { formatBriefingDate, isInternalLink } from "./helpers";++describe("formatBriefingDate", () => {+ afterEach(() => {+ vi.useRealTimers();+ });++ it("labels today's briefing as this morning", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-07T09:00:00Z"));++ expect(formatBriefingDate("2026-08-07")).toBe("This morning");+ });++ it("does not shift a date-only string a day back", () => {+ // The API sends "2026-08-07" with no time part, so the client's date+ // transformer leaves it a string. `new Date(...)` would read it as UTC+ // midnight — i.e. Aug 6 in the evening for anyone west of UTC.+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-09T12:00:00Z"));++ expect(formatBriefingDate("2026-08-07")).toBe("August 7");+ });++ it("accepts an already-parsed Date", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-08-09T12:00:00Z"));++ expect(formatBriefingDate(new Date(2026, 7, 7, 9, 0))).toBe("August 7");+ });+});++describe("isInternalLink", () => {+ it("accepts an app-relative path", () => {+ expect(isInternalLink("/library/agents/lib-1")).toBe(true);+ });++ it.each(["https://evil.example", "javascript:alert(1)", "//evil.example"])(+ "rejects %s",+ (link) => {+ expect(isInternalLink(link)).toBe(false);+ },+ );+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.tsnew file mode 100644index 0000000000..4585eb45fc--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/BriefingCard/helpers.ts@@ -0,0 +1,16 @@+import { format, isToday, parseISO } from "date-fns";++export function formatBriefingDate(date: Date | string): string {+ // The generated type says Date, but date-only strings ("2026-08-07") skip+ // the client's date transformer (its regex requires a time part), so the+ // runtime value is still a string. parseISO reads it as LOCAL midnight —+ // `new Date("2026-08-07")` would read UTC midnight and shift the label a+ // day back for viewers west of UTC.+ const parsed = typeof date === "string" ? parseISO(date) : date;+ if (isToday(parsed)) return "This morning";+ return format(parsed, "MMMM d");+}++export function isInternalLink(link: string): boolean {+ return link.startsWith("/") && !link.startsWith("//");+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/TeamStrip.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/TeamStrip.tsxnew file mode 100644index 0000000000..93162c58d2--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/TeamStrip.tsx@@ -0,0 +1,58 @@+import Link from "next/link";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";+import { Text } from "@/components/atoms/Text/Text";+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";+import { getExpertStatusLine } from "./helpers";+import { useTeamStrip } from "./useTeamStrip";++export function TeamStrip() {+ const { isVisible, hiredExperts, schedules } = useTeamStrip();++ if (!isVisible) return null;++ return (+ <div className="mb-6 flex snap-x gap-3 overflow-x-auto pb-2 text-left">+ {hiredExperts.map((expert) => (+ <TeamStripCard key={expert.id} expert={expert} schedules={schedules} />+ ))}+ </div>+ );+}++interface CardProps {+ expert: Expert;+ schedules: GraphExecutionJobInfo[];+}++function TeamStripCard({ expert, schedules }: CardProps) {+ return (+ <div className="flex w-56 shrink-0 snap-start flex-col gap-3 rounded-2xl border border-zinc-200 bg-white p-4">+ <Link+ href={`/team/${expert.id}`}+ aria-label={`View ${expert.name}`}+ className="flex flex-col gap-2"+ >+ <ExpertAvatar name={expert.name} avatarUrl={expert.avatar_url} />+ <div className="min-w-0">+ <Text variant="body-medium" className="truncate">+ {expert.name}+ </Text>+ <Text variant="small" className="truncate text-zinc-500">+ {expert.role}+ </Text>+ </div>+ <Text variant="small" className="truncate text-zinc-500">+ {getExpertStatusLine(expert, schedules)}+ </Text>+ </Link>+ <Link+ href={`/copilot?expertId=${expert.id}`}+ aria-label={`Chat with ${expert.name}`}+ className="text-sm font-medium text-zinc-700 hover:text-zinc-900"+ >+ Chat+ </Link>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.test.tsnew file mode 100644index 0000000000..c5441ebb6a--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.test.ts@@ -0,0 +1,99 @@+import { describe, expect, it } from "vitest";+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { ExpertWorkflowRef } from "@/app/api/__generated__/models/expertWorkflowRef";+import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";+import { getExpertStatusLine } from "./helpers";++function makeWorkflow(id: string): ExpertWorkflowRef {+ // schedule_cron set + schedule_id missing is what "needs setup" means.+ return {+ id,+ store_listing_version_id: `slv-${id}`,+ library_agent_id: `lib-${id}`,+ graph_id: `graph-${id}`,+ name: `Workflow ${id}`,+ description: null,+ schedule_cron: "0 9 * * *",+ schedule_id: null,+ };+}++function makeExpert(overrides: Partial<Expert> = {}): Expert {+ return {+ id: "expert-1",+ name: "Sales Scout",+ avatar_url: null,+ role: "Sales Researcher",+ bio: null,+ skills: [],+ tagline: null,+ identity: "You are a senior sales researcher.",+ voice_preferences: "",+ boundaries: "",+ protected_soul_rules: [],+ is_template: false,+ source_template_id: null,+ is_archived: false,+ workflows: [],+ ...overrides,+ };+}++function makeSchedule(overrides: Partial<GraphExecutionJobInfo> = {}) {+ return {+ id: "sched-1",+ name: "Daily Report",+ user_id: "u-1",+ graph_id: "graph-1",+ graph_version: 1,+ cron: "0 9 * * *",+ input_data: {},+ next_run_time: "2026-08-10T14:30:00Z",+ expert_id: "expert-1",+ ...overrides,+ } as GraphExecutionJobInfo;+}++describe("getExpertStatusLine", () => {+ it("reports a paused expert before anything else", () => {+ const expert = makeExpert({+ schedules_paused_at: new Date("2026-08-05T10:00:00Z"),+ workflows: [makeWorkflow("1")],+ });++ expect(getExpertStatusLine(expert, [])).toBe("Paused");+ });++ it("uses singular grammar for one workflow needing setup", () => {+ const expert = makeExpert({ workflows: [makeWorkflow("1")] });++ expect(getExpertStatusLine(expert, [])).toBe("1 workflow needs setup");+ });++ it("uses plural grammar for several workflows needing setup", () => {+ const expert = makeExpert({+ workflows: [makeWorkflow("1"), makeWorkflow("2")],+ });++ expect(getExpertStatusLine(expert, [])).toBe("2 workflows need setup");+ });++ it("falls back to the last run once nothing needs setup", () => {+ const expert = makeExpert({+ last_run_at: new Date("2026-08-06T10:00:00Z"),+ last_run_status: "COMPLETED",+ });++ expect(getExpertStatusLine(expert, [])).toContain("Last run succeeded");+ });++ it("shows the next scheduled run for an expert that has never run", () => {+ const expert = makeExpert();++ expect(getExpertStatusLine(expert, [makeSchedule()])).toMatch(/^Next run /);+ });++ it("falls back to Idle with no runs and no schedules", () => {+ expect(getExpertStatusLine(makeExpert(), [])).toBe("Idle");+ });+});diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.tsnew file mode 100644index 0000000000..5aa7917e81--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/helpers.ts@@ -0,0 +1,34 @@+import type { Expert } from "@/app/api/__generated__/models/expert";+import type { GraphExecutionJobInfo } from "@/app/api/__generated__/models/graphExecutionJobInfo";+import {+ getExpertSchedules,+ getLastRunLabel,+ getNeedsSetupCount,+} from "@/app/(platform)/team/helpers";++export function getExpertStatusLine(+ expert: Expert,+ schedules: GraphExecutionJobInfo[],+): string {+ if (expert.schedules_paused_at) return "Paused";++ const needsSetup = getNeedsSetupCount(expert);+ if (needsSetup > 0) {+ const noun = needsSetup === 1 ? "workflow" : "workflows";+ const verb = needsSetup === 1 ? "needs" : "need";+ return `${needsSetup} ${noun} ${verb} setup`;+ }++ const lastRun = getLastRunLabel(expert);+ if (lastRun) return lastRun;++ const next = getExpertSchedules(expert, schedules)[0]?.next_run_time;+ if (next) {+ return `Next run ${new Date(next).toLocaleTimeString([], {+ hour: "numeric",+ minute: "2-digit",+ })}`;+ }++ return "Idle";+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/useTeamStrip.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/useTeamStrip.tsnew file mode 100644index 0000000000..6b6b2bbae3--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/components/TeamStrip/useTeamStrip.ts@@ -0,0 +1,30 @@+import { useListExperts } from "@/app/api/__generated__/endpoints/experts/experts";+import { useGetV1ListExecutionSchedulesForAUser } from "@/app/api/__generated__/endpoints/schedules/schedules";+import { okData } from "@/app/api/helpers";+import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";++export function useTeamStrip() {+ const isExpertsEnabled = useGetFlag(Flag.HIRE_EXPERTS);++ const expertsQuery = useListExperts({+ query: {+ // okData, like every sibling query here: an error body must never+ // reach the render layer typed as Expert[].+ select: (res) => okData(res) ?? [],+ enabled: isExpertsEnabled,+ },+ });+ const schedulesQuery = useGetV1ListExecutionSchedulesForAUser({+ query: { select: (res) => okData(res) ?? [], enabled: isExpertsEnabled },+ });++ const hiredExperts = (expertsQuery.data ?? []).filter(+ (expert) => !expert.is_template && !expert.is_archived,+ );++ return {+ isVisible: isExpertsEnabled && hiredExperts.length > 0,+ hiredExperts,+ schedules: schedulesQuery.data ?? [],+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/useCopilotHome.ts b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/useCopilotHome.tsnew file mode 100644index 0000000000..3e665d5360--- /dev/null+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/CopilotHome/useCopilotHome.ts@@ -0,0 +1,17 @@+import { useGetBriefingsGetLatestBriefing } from "@/app/api/__generated__/endpoints/briefings/briefings";+import { okData } from "@/app/api/helpers";++export function useCopilotHome() {+ const { data, isLoading, isError, refetch } =+ useGetBriefingsGetLatestBriefing({+ query: { select: (res) => okData(res) ?? null },+ });++ return {+ briefing: data ?? null,+ isLoadingBriefing: isLoading,+ isBriefingError: isError,+ refetchBriefing: refetch,+ hasBriefing: Boolean(data),+ };+}diff --git a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsxindex abb10d2efb..6e7476a861 100644--- a/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx+++ b/autogpt_platform/frontend/src/app/(platform)/copilot/components/EmptySession/EmptySession.tsx@@ -22,6 +22,7 @@ import { usePulseChips } from "../PulseChips/usePulseChips";import { Flag, useGetFlag } from "@/services/feature-flags/use-get-flag";import type { WorkspaceAttachment } from "../../helpers/workspaceAttachments";import { EmptyHero } from "./components/EmptyHero";+import { CopilotHome } from "../CopilotHome/CopilotHome";import { RecipientChip } from "../ChatInput/components/RecipientChip";import { useRecipientPicker } from "./useRecipientPicker";@@ -142,11 +143,23 @@ export function EmptySession({/>)}- {isAgentBriefingEnabled &&- !intro.isVisible &&- !intro.isAwaitingGreeting && (- <PulseChips chips={pulseChips} onChipClick={onSend} />- )}+ {!intro.isVisible &&+ !intro.isAwaitingGreeting &&+ (isExpertsEnabled ? (+ // The briefing home takes the chips' slot and falls back to+ // them — still on their own flag — when there's no briefing.+ <CopilotHome+ fallback={+ isAgentBriefingEnabled ? (+ <PulseChips chips={pulseChips} onChipClick={onSend} />+ ) : null+ }+ />+ ) : (+ isAgentBriefingEnabled && (+ <PulseChips chips={pulseChips} onChipClick={onSend} />+ )+ ))}{/* Held back while the greeting is on its way — it enters withthe greeting page instead of sitting under a bare hero. */}diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex a3fcdf11e0..ade3a13f3a 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -2873,6 +2873,34 @@}}},+ "/api/briefings/latest": {+ "get": {+ "tags": ["briefings"],+ "summary": "Get Latest Briefing",+ "description": "Return the user's current briefing, or None if there isn't a fresh one.\n\nOnly briefings covering today or yesterday qualify; anything older is\nhistory, not \"this morning\".\n\nStored content that fails to validate against the current BriefingContent\nshape (e.g. written by an older/newer version of the composer) is skipped\nrather than 500ing the request — and rather than hiding every older\nbriefing behind one unreadable row on the newest date.",+ "operationId": "getBriefingsGet latest briefing",+ "responses": {+ "200": {+ "description": "Successful Response",+ "content": {+ "application/json": {+ "schema": {+ "anyOf": [+ { "$ref": "#/components/schemas/BriefingResponse" },+ { "type": "null" }+ ],+ "title": "Response Getbriefingsget Latest Briefing"+ }+ }+ }+ },+ "401": {+ "$ref": "#/components/responses/HTTP401NotAuthenticatedError"+ }+ },+ "security": [{ "HTTPBearerJWT": [] }]+ }+ },"/api/builder/blocks": {"get": {"tags": ["v2"],@@ -15173,6 +15201,153 @@],"title": "BrainDumpStatus"},+ "BriefingContent": {+ "properties": {+ "generated_at": {+ "type": "string",+ "format": "date-time",+ "title": "Generated At"+ },+ "timezone": { "type": "string", "title": "Timezone" },+ "zero_expert_fallback": {+ "type": "boolean",+ "title": "Zero Expert Fallback"+ },+ "run_items": {+ "items": { "$ref": "#/components/schemas/BriefingRunItem" },+ "type": "array",+ "title": "Run Items"+ },+ "decision_items": {+ "items": { "$ref": "#/components/schemas/BriefingDecisionItem" },+ "type": "array",+ "title": "Decision Items"+ },+ "decision_total": {+ "type": "integer",+ "title": "Decision Total",+ "default": 0+ }+ },+ "type": "object",+ "required": [+ "generated_at",+ "timezone",+ "zero_expert_fallback",+ "run_items",+ "decision_items"+ ],+ "title": "BriefingContent"+ },+ "BriefingDecisionItem": {+ "properties": {+ "node_exec_id": { "type": "string", "title": "Node Exec Id" },+ "graph_exec_id": { "type": "string", "title": "Graph Exec Id" },+ "title": { "type": "string", "title": "Title" },+ "expert_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Id"+ },+ "expert_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Name"+ },+ "expert_avatar_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Avatar Url"+ },+ "link": { "type": "string", "title": "Link" }+ },+ "type": "object",+ "required": [+ "node_exec_id",+ "graph_exec_id",+ "title",+ "expert_id",+ "expert_name",+ "expert_avatar_url",+ "link"+ ],+ "title": "BriefingDecisionItem"+ },+ "BriefingResponse": {+ "properties": {+ "id": { "type": "string", "title": "Id" },+ "briefing_date": {+ "type": "string",+ "format": "date",+ "title": "Briefing Date"+ },+ "created_at": {+ "type": "string",+ "format": "date-time",+ "title": "Created At"+ },+ "delivered_at": {+ "anyOf": [+ { "type": "string", "format": "date-time" },+ { "type": "null" }+ ],+ "title": "Delivered At"+ },+ "content": { "$ref": "#/components/schemas/BriefingContent" }+ },+ "type": "object",+ "required": [+ "id",+ "briefing_date",+ "created_at",+ "delivered_at",+ "content"+ ],+ "title": "BriefingResponse"+ },+ "BriefingRunItem": {+ "properties": {+ "expert_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Id"+ },+ "expert_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Name"+ },+ "expert_avatar_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Avatar Url"+ },+ "agent_name": { "type": "string", "title": "Agent Name" },+ "graph_id": { "type": "string", "title": "Graph Id" },+ "execution_id": { "type": "string", "title": "Execution Id" },+ "library_agent_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Library Agent Id"+ },+ "status": { "type": "string", "title": "Status" },+ "summary": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Summary"+ },+ "link": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Link"+ }+ },+ "type": "object",+ "required": [+ "expert_id",+ "expert_name",+ "expert_avatar_url",+ "agent_name",+ "graph_id",+ "execution_id",+ "library_agent_id",+ "status",+ "summary",+ "link"+ ],+ "title": "BriefingRunItem"+ },"BulkMoveAgentsRequest": {"properties": {"agent_ids": {@@ -20592,6 +20767,34 @@"title": "Review Message","description": "Optional message from the reviewer"},+ "expert_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Id",+ "description": "Expert attributed to the requesting run"+ },+ "expert_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Name"+ },+ "expert_avatar_url": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Expert Avatar Url"+ },+ "agent_name": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Agent Name",+ "description": "Display name of the agent that requested the review"+ },+ "library_agent_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Library Agent Id",+ "description": "For run deep links"+ },+ "session_id": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Session Id",+ "description": "Chat session id for copilot run_block reviews"+ },"was_edited": {"anyOf": [{ "type": "boolean" }, { "type": "null" }],"title": "Was Edited",diff --git a/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsx b/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsxnew file mode 100644index 0000000000..b74619653a--- /dev/null+++ b/autogpt_platform/frontend/src/components/molecules/ExpertAvatar/ExpertAvatar.tsx@@ -0,0 +1,45 @@+import { Robot01Icon } from "@hugeicons/core-free-icons";+import {+ Avatar,+ AvatarFallback,+ AvatarImage,+} from "@/components/atoms/Avatar/Avatar";+import { Icon } from "@/components/atoms/Icon/Icon";+import { cn } from "@/lib/utils";++interface Props {+ name: string | null;+ avatarUrl: string | null;+ size?: number;+ className?: string;+}++/**+ * Expert avatar with a generic-agent fallback, shared by the copilot home+ * surfaces (briefing card, team strip, needs-attention list) so they stay+ * visually consistent.+ */+export function ExpertAvatar({ name, avatarUrl, size = 40, className }: Props) {+ const style = { width: size, height: size };++ if (!name) {+ return (+ <div+ style={style}+ className={cn(+ "flex shrink-0 items-center justify-center rounded-full bg-zinc-100",+ className,+ )}+ >+ <Icon icon={Robot01Icon} size={size / 2} className="text-zinc-500" />+ </div>+ );+ }++ return (+ <Avatar style={style} className={cn("shrink-0", className)}>+ {avatarUrl ? <AvatarImage src={avatarUrl} alt={name} /> : null}+ <AvatarFallback>{name}</AvatarFallback>+ </Avatar>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/NeedsAttentionList.tsx b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/NeedsAttentionList.tsxnew file mode 100644index 0000000000..e818b162ea--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/NeedsAttentionList.tsx@@ -0,0 +1,145 @@+import Link from "next/link";+import { useState } from "react";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { Button } from "@/components/atoms/Button/Button";+import { Skeleton } from "@/components/atoms/Skeleton/Skeleton";+import { Text } from "@/components/atoms/Text/Text";+import { ErrorCard } from "@/components/molecules/ErrorCard/ErrorCard";+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";+import { getReviewLink } from "@/lib/review-links";+import { getReviewTitle } from "./helpers";+import { useNeedsAttentionList } from "./useNeedsAttentionList";++export function NeedsAttentionList() {+ const {+ reviews,+ countLabel,+ isLoading,+ isError,+ refetch,+ pendingNodeExecIds,+ approve,+ decline,+ } = useNeedsAttentionList();++ if (isLoading) {+ return (+ <div className="flex flex-col gap-2">+ <Skeleton className="h-5 w-40" />+ <Skeleton className="h-16 w-full" />+ </div>+ );+ }++ if (isError) {+ return (+ <ErrorCard+ context="pending reviews"+ httpError={{ message: "Failed to load pending reviews" }}+ onRetry={() => refetch()}+ />+ );+ }++ if (reviews.length === 0) return null;++ return (+ <section className="flex flex-col gap-3">+ <Text variant="h5">Needs your attention ({countLabel})</Text>+ <div className="flex flex-col gap-2">+ {reviews.map((review) => (+ <NeedsAttentionRow+ key={review.node_exec_id}+ review={review}+ // Only the acted row locks up, so morning triage stays+ // parallel instead of serializing on each round-trip.+ isProcessing={pendingNodeExecIds.has(review.node_exec_id)}+ onApprove={approve}+ onDecline={decline}+ />+ ))}+ </div>+ </section>+ );+}++interface RowProps {+ review: PendingHumanReviewModel;+ isProcessing: boolean;+ onApprove: (review: PendingHumanReviewModel) => void;+ onDecline: (review: PendingHumanReviewModel) => void;+}++function NeedsAttentionRow({+ review,+ isProcessing,+ onApprove,+ onDecline,+}: RowProps) {+ // Decline rejects the agent's action outright, with no undo, in a flow+ // built for fast tapping — so it takes a second, deliberate tap.+ const [isConfirmingDecline, setIsConfirmingDecline] = useState(false);+ const title = getReviewTitle(review);+ const subtitle = [review.expert_name, review.agent_name]+ .filter(Boolean)+ .join(" · ");++ function handleDecline() {+ if (!isConfirmingDecline) {+ setIsConfirmingDecline(true);+ return;+ }+ setIsConfirmingDecline(false);+ onDecline(review);+ }++ return (+ <div className="flex items-center gap-3 rounded-xl border border-zinc-200 bg-white p-3">+ <ExpertAvatar+ name={review.expert_name ?? null}+ avatarUrl={review.expert_avatar_url ?? null}+ />+ <Link href={getReviewLink(review)} className="min-w-0 flex-1">+ <Text variant="body-medium" className="truncate">+ {title}+ </Text>+ {subtitle ? (+ <Text variant="small" className="truncate text-zinc-500">+ {subtitle}+ </Text>+ ) : null}+ </Link>+ <div className="flex shrink-0 items-center gap-2">+ <Button+ variant="primary"+ size="small"+ disabled={isProcessing}+ aria-label={`Approve: ${title}`}+ onClick={() => onApprove(review)}+ >+ Approve+ </Button>+ <Button+ // The armed state carries the destructive colour as well as the+ // label: in a fast-tapping flow a word swap alone is easy to miss,+ // and the next tap has no undo.+ variant={isConfirmingDecline ? "destructive" : "ghost"}+ size="small"+ disabled={isProcessing}+ aria-label={+ isConfirmingDecline+ ? `Confirm decline: ${title}`+ : `Decline: ${title}`+ }+ onClick={handleDecline}+ onBlur={() => setIsConfirmingDecline(false)}+ >+ {isConfirmingDecline ? "Confirm" : "Decline"}+ </Button>+ </div>+ <span aria-live="polite" className="sr-only">+ {isConfirmingDecline ? `Tap again to decline: ${title}` : ""}+ </span>+ </div>+ );+}diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsxnew file mode 100644index 0000000000..bbfaad0654--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/__tests__/NeedsAttentionList.test.tsx@@ -0,0 +1,250 @@+import userEvent from "@testing-library/user-event";+import { http, HttpResponse } from "msw";+import { expect, test } from "vitest";+import {+ getGetV2GetPendingReviewsMockHandler200,+ getPostV2ProcessReviewActionMockHandler200,+} from "@/app/api/__generated__/endpoints/executions/executions.msw";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { Toaster } from "@/components/molecules/Toast/toaster";+import { server } from "@/mocks/mock-server";+import { render, screen, waitFor } from "@/tests/integrations/test-utils";+import { NeedsAttentionList } from "../NeedsAttentionList";++const review: PendingHumanReviewModel = {+ node_exec_id: "ne-1",+ node_id: "n-1",+ user_id: "u-1",+ graph_exec_id: "run-1",+ graph_id: "g-1",+ graph_version: 1,+ payload: { to: "[email protected]" },+ instructions: "Approve outreach email",+ editable: true,+ status: "WAITING",+ expert_id: "exp-1",+ expert_name: "Ana",+ expert_avatar_url: null,+ agent_name: "Lead Finder",+ library_agent_id: "lib-1",+ session_id: null,+ created_at: new Date(),+};++test("renders attributed rows and approves in one tap", async () => {+ let actionBody: unknown;+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review]),+ getPostV2ProcessReviewActionMockHandler200(async (info) => {+ actionBody = await info.request.json();+ return { approved_count: 1, rejected_count: 0, failed_count: 0 };+ }),+ );++ render(<NeedsAttentionList />);+ expect(await screen.findByText("Approve outreach email")).toBeDefined();+ expect(screen.getByText(/Ana/)).toBeDefined();++ await userEvent.click(screen.getByRole("button", { name: /^Approve:/ }));+ await waitFor(() =>+ expect(actionBody).toMatchObject({+ reviews: [{ node_exec_id: "ne-1", approved: true }],+ }),+ );+});++test("only the acted row locks while its decision is in flight", async () => {+ const other = {+ ...review,+ node_exec_id: "ne-2",+ instructions: "Approve invoice",+ };+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review, other]),+ http.post("/api/proxy/api/review/action", async () => {+ await new Promise((resolve) => setTimeout(resolve, 200));+ return HttpResponse.json({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ });+ }),+ );++ render(<NeedsAttentionList />);+ const buttons = await screen.findAllByRole("button", { name: /^Approve:/ });+ await userEvent.click(buttons[0]);++ await waitFor(() => {+ const [first, second] = screen.getAllByRole("button", {+ name: /^Approve:/,+ }) as HTMLButtonElement[];+ expect(first.disabled).toBe(true);+ expect(second.disabled).toBe(false);+ });+});++test("confirms a successful decision with a toast", async () => {+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review]),+ getPostV2ProcessReviewActionMockHandler200({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ }),+ );++ render(+ <>+ <NeedsAttentionList />+ <Toaster />+ </>,+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /^Approve:/ }),+ );++ expect(await screen.findByText("Approved")).toBeDefined();+});++test("decline sends a rejection", async () => {+ let actionBody:+ | { reviews: Array<{ approved: boolean; message?: string }> }+ | undefined;+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review]),+ getPostV2ProcessReviewActionMockHandler200(async (info) => {+ actionBody = (await info.request.json()) as typeof actionBody;+ return { approved_count: 0, rejected_count: 1, failed_count: 0 };+ }),+ );++ render(<NeedsAttentionList />);+ // Decline is a hard reject with no undo, so it takes a second, deliberate+ // tap in a flow built for fast tapping.+ await userEvent.click(+ await screen.findByRole("button", { name: /^Decline:/ }),+ );+ expect(actionBody).toBeUndefined();+ await userEvent.click(+ await screen.findByRole("button", { name: /^Confirm decline:/ }),+ );+ await waitFor(() =>+ expect(actionBody?.reviews[0]).toMatchObject({ approved: false }),+ );+ // No canned reason: this surface has no field to write one in, so nothing+ // should reach the agent context / audit trail as if the user typed it.+ expect(actionBody?.reviews[0].message).toBeUndefined();+});++test("armed decline is announced and visually distinct, not just relabelled", async () => {+ server.use(getGetV2GetPendingReviewsMockHandler200([review]));++ render(<NeedsAttentionList />);+ const declineButton = await screen.findByRole("button", {+ name: /^Decline:/,+ });+ const initialClassName = declineButton.className;++ await userEvent.click(declineButton);++ const armed = await screen.findByRole("button", {+ name: /^Confirm decline:/,+ });+ expect(armed.className).not.toBe(initialClassName);+ expect(+ screen.getByText(`Tap again to decline: ${review.instructions}`),+ ).toBeDefined();+});++test("shows a destructive toast when approve fails", async () => {+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review]),+ http.post(+ "/api/proxy/api/review/action",+ () => new HttpResponse(null, { status: 500 }),+ ),+ );++ render(+ <>+ <NeedsAttentionList />+ <Toaster />+ </>,+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /^Approve:/ }),+ );++ expect(await screen.findByText("Failed to approve review")).toBeDefined();+});++test("renders nothing when there are no pending reviews", async () => {+ server.use(getGetV2GetPendingReviewsMockHandler200([]));++ const { container } = render(<NeedsAttentionList />);+ await waitFor(() => expect(container.firstChild).toBeNull());+});++test("reports a 200 that carries a failure as a failure, not an approval", async () => {+ // The mutation resolves on non-2xx and a 200 can still say failed_count > 0+ // (review already processed, node execution gone). Toasting "Approved"+ // there leaves the row reappearing with nothing explaining why.+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review]),+ getPostV2ProcessReviewActionMockHandler200({+ approved_count: 0,+ rejected_count: 0,+ failed_count: 1,+ error: "Review already processed",+ }),+ );++ render(+ <>+ <NeedsAttentionList />+ <Toaster />+ </>,+ );+ await userEvent.click(+ await screen.findByRole("button", { name: /^Approve:/ }),+ );++ expect(await screen.findByText("Failed to approve review")).toBeDefined();+ expect(screen.getByText("Review already processed")).toBeDefined();+ expect(screen.queryByText("Approved")).toBeNull();+});++test("a second row's decision does not unlock the first one mid-flight", async () => {+ const other = {+ ...review,+ node_exec_id: "ne-2",+ instructions: "Approve invoice",+ };+ server.use(+ getGetV2GetPendingReviewsMockHandler200([review, other]),+ http.post("/api/proxy/api/review/action", async () => {+ await new Promise((resolve) => setTimeout(resolve, 300));+ return HttpResponse.json({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ });+ }),+ );++ render(<NeedsAttentionList />);+ const buttons = await screen.findAllByRole("button", { name: /^Approve:/ });+ await userEvent.click(buttons[0]);+ await userEvent.click(buttons[1]);++ await waitFor(() => {+ const [first, second] = screen.getAllByRole("button", {+ name: /^Approve:/,+ }) as HTMLButtonElement[];+ // Both in flight -> both locked. A single pending slot would have+ // re-enabled the first row here, making it double-submittable.+ expect(first.disabled).toBe(true);+ expect(second.disabled).toBe(true);+ });+});diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.test.ts b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.test.tsnew file mode 100644index 0000000000..1779ba7686--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { getReviewTitle } from "./helpers";++function makeReview(+ overrides: Partial<PendingHumanReviewModel> = {},+): PendingHumanReviewModel {+ return {+ node_exec_id: "ne-1",+ node_id: "n-1",+ user_id: "u-1",+ graph_exec_id: "run-1",+ graph_id: "g-1",+ graph_version: 1,+ payload: {},+ editable: true,+ status: "WAITING",+ created_at: new Date(),+ ...overrides,+ };+}++describe("getReviewTitle", () => {+ it("prefers the review instructions", () => {+ expect(+ getReviewTitle(+ makeReview({+ instructions: "Approve email",+ agent_name: "Lead Finder",+ }),+ ),+ ).toBe("Approve email");+ });++ it("falls back to the agent name without instructions", () => {+ expect(getReviewTitle(makeReview({ agent_name: "Lead Finder" }))).toBe(+ "Lead Finder",+ );+ });++ it("falls back to a generic label when neither resolved", () => {+ expect(getReviewTitle(makeReview())).toBe("Review needed");+ });+});diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.ts b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.tsnew file mode 100644index 0000000000..170022d882--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/helpers.ts@@ -0,0 +1,5 @@+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";++export function getReviewTitle(review: PendingHumanReviewModel): string {+ return review.instructions || review.agent_name || "Review needed";+}diff --git a/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.tsnew file mode 100644index 0000000000..1a7c2f3778--- /dev/null+++ b/autogpt_platform/frontend/src/components/organisms/NeedsAttentionList/useNeedsAttentionList.ts@@ -0,0 +1,91 @@+import { useState } from "react";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { useToast } from "@/components/molecules/Toast/use-toast";+import { useNeedsAttention } from "@/hooks/useNeedsAttention";+import { useProcessReviews } from "@/hooks/useProcessReviews";++export function useNeedsAttentionList() {+ const { reviews, countLabel, isLoading, isError, refetch } =+ useNeedsAttention();+ const { processReviews } = useProcessReviews();+ const { toast } = useToast();+ // A set rather than a single slot: morning triage taps several rows in+ // quick succession, and one slot would unlock row A the moment row B+ // started, making A double-submittable while its POST was still in flight.+ const [pendingNodeExecIds, setPendingNodeExecIds] = useState<Set<string>>(+ new Set(),+ );++ function setPending(nodeExecId: string, isPending: boolean) {+ setPendingNodeExecIds((current) => {+ const next = new Set(current);+ if (isPending) next.add(nodeExecId);+ else next.delete(nodeExecId);+ return next;+ });+ }++ async function decide(+ review: PendingHumanReviewModel,+ approved: boolean,+ ): Promise<void> {+ const verb = approved ? "approve" : "decline";+ setPending(review.node_exec_id, true);+ try {+ const res = await processReviews(+ [+ {+ node_exec_id: review.node_exec_id,+ approved,+ // No message: this surface has no field to write one in, and a+ // canned English string would reach the agent's context and the+ // audit trail as if the user had typed it.+ auto_approve_future: false,+ },+ ],+ [review.graph_exec_id],+ );++ // The mutation resolves rather than throws on a non-200, and a 200 can+ // still carry failed_count > 0 (review already processed, node+ // execution gone). Reporting either as success would leave the row+ // reappearing on the next refetch with nothing explaining why.+ if (res.status !== 200) {+ throw new Error("Unexpected response from server");+ }+ if (res.data.failed_count > 0) {+ throw new Error(res.data.error || "The review could not be processed.");+ }++ toast({ title: approved ? "Approved" : "Declined" });+ } catch (error) {+ toast({+ title: `Failed to ${verb} review`,+ description:+ error instanceof Error ? error.message : "An error occurred",+ variant: "destructive",+ });+ } finally {+ setPending(review.node_exec_id, false);+ }+ }++ function approve(review: PendingHumanReviewModel) {+ return decide(review, true);+ }++ function decline(review: PendingHumanReviewModel) {+ return decide(review, false);+ }++ return {+ reviews,+ countLabel,+ isLoading,+ isError,+ refetch,+ pendingNodeExecIds,+ approve,+ decline,+ };+}diff --git a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsxindex 9b6c6a0860..778d4a17ca 100644--- a/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx+++ b/autogpt_platform/frontend/src/components/organisms/PendingReviewsList/PendingReviewsList.tsx@@ -5,7 +5,7 @@ import { Text } from "@/components/atoms/Text/Text";import { Button } from "@/components/atoms/Button/Button";import { Switch } from "@/components/atoms/Switch/Switch";import { useToast } from "@/components/molecules/Toast/use-toast";-import { usePostV2ProcessReviewAction } from "@/app/api/__generated__/endpoints/executions/executions";+import { useProcessReviews } from "@/hooks/useProcessReviews";import {Alert01Icon,ArrowDown01Icon,@@ -67,47 +67,8 @@ export function PendingReviewsList({);}, [reviews]);- const reviewActionMutation = usePostV2ProcessReviewAction({- mutation: {- onSuccess: (res) => {- if (res.status !== 200) {- toast({- title: "Failed to process reviews",- description: "Unexpected response from server",- variant: "destructive",- });- return;- }-- const result = res.data;-- if (result.failed_count > 0) {- toast({- title: "Reviews partially processed",- description: `${result.approved_count + result.rejected_count} succeeded, ${result.failed_count} failed. ${result.error || "Some reviews could not be processed."}`,- variant: "destructive",- });- } else {- toast({- title: "Reviews processed successfully",- description: `${result.approved_count} approved, ${result.rejected_count} rejected`,- variant: "default",- });- }-- setPendingAction(null);- onReviewComplete?.();- },- onError: (error: Error) => {- setPendingAction(null);- toast({- title: "Failed to process reviews",- description: error.message || "An error occurred",- variant: "destructive",- });- },- },- });+ const { processReviews: submitReviewAction, isProcessing } =+ useProcessReviews({ onSettled: onReviewComplete });function handleReviewDataChange(nodeExecId: string, data: string) {setReviewDataMap((prev) => ({ ...prev, [nodeExecId]: data }));@@ -142,7 +103,7 @@ export function PendingReviewsList({}));}- function processReviews(approved: boolean) {+ async function processReviews(approved: boolean) {if (reviews.length === 0) {toast({title: "No reviews to process",@@ -187,11 +148,46 @@ export function PendingReviewsList({});}- reviewActionMutation.mutate({- data: {- reviews: reviewItems,- },- });+ try {+ const res = await submitReviewAction(+ reviewItems,+ reviews.map((review) => review.graph_exec_id),+ );++ if (res.status !== 200) {+ toast({+ title: "Failed to process reviews",+ description: "Unexpected response from server",+ variant: "destructive",+ });+ return;+ }++ const result = res.data;++ if (result.failed_count > 0) {+ toast({+ title: "Reviews partially processed",+ description: `${result.approved_count + result.rejected_count} succeeded, ${result.failed_count} failed. ${result.error || "Some reviews could not be processed."}`,+ variant: "destructive",+ });+ } else {+ toast({+ title: "Reviews processed successfully",+ description: `${result.approved_count} approved, ${result.rejected_count} rejected`,+ variant: "default",+ });+ }+ } catch (error) {+ toast({+ title: "Failed to process reviews",+ description:+ error instanceof Error ? error.message : "An error occurred",+ variant: "destructive",+ });+ } finally {+ setPendingAction(null);+ }}if (reviews.length === 0) {@@ -316,23 +312,19 @@ export function PendingReviewsList({<div className="flex flex-wrap gap-2"><ButtononClick={() => processReviews(true)}- disabled={reviewActionMutation.isPending || reviews.length === 0}+ disabled={isProcessing || reviews.length === 0}variant="primary"className="flex min-w-20 items-center justify-center gap-2 rounded-full px-4 py-3"- loading={- pendingAction === "approve" && reviewActionMutation.isPending- }+ loading={pendingAction === "approve" && isProcessing}>Approve</Button><ButtononClick={() => processReviews(false)}- disabled={reviewActionMutation.isPending || reviews.length === 0}+ disabled={isProcessing || reviews.length === 0}variant="destructive"className="flex min-w-20 items-center justify-center gap-2 rounded-full bg-red-600 px-4 py-3"- loading={- pendingAction === "reject" && reviewActionMutation.isPending- }+ loading={pendingAction === "reject" && isProcessing}>Reject</Button>diff --git a/autogpt_platform/frontend/src/hooks/useNeedsAttention.ts b/autogpt_platform/frontend/src/hooks/useNeedsAttention.tsnew file mode 100644index 0000000000..e268e15d36--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useNeedsAttention.ts@@ -0,0 +1,32 @@+import { useGetV2GetPendingReviews } from "@/app/api/__generated__/endpoints/executions/executions";+import { okData } from "@/app/api/helpers";++const PAGE_SIZE = 100;++export function useNeedsAttention() {+ const { data, isLoading, isError, refetch } = useGetV2GetPendingReviews(+ { page: 1, page_size: PAGE_SIZE },+ {+ query: {+ select: (res) => okData(res) ?? [],+ // Pending reviews only change on the user's own action or an+ // overnight run, so refresh when the tab comes back into focus+ // rather than polling this (now enriched, multi-query) endpoint+ // every 30s for every open home tab.+ refetchOnWindowFocus: true,+ refetchInterval: 5 * 60_000,+ },+ },+ );+ const reviews = data ?? [];+ return {+ reviews,+ // A full page means there may be more behind it; don't present a+ // truncated count as if it were the total.+ countLabel:+ reviews.length >= PAGE_SIZE ? `${PAGE_SIZE}+` : String(reviews.length),+ isLoading,+ isError,+ refetch,+ };+}diff --git a/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx b/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsxnew file mode 100644index 0000000000..ff9c5f137b--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useProcessReviews.test.tsx@@ -0,0 +1,75 @@+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook } from "@testing-library/react";+import { HttpResponse, http } from "msw";+import type { ReactNode } from "react";+import { expect, test, vi } from "vitest";+import {+ getGetV2GetPendingReviewsForExecutionQueryKey,+ getGetV2GetPendingReviewsQueryKey,+} from "@/app/api/__generated__/endpoints/executions/executions";+import { getPostV2ProcessReviewActionMockHandler200 } from "@/app/api/__generated__/endpoints/executions/executions.msw";+import { server } from "@/mocks/mock-server";+import { useProcessReviews } from "./useProcessReviews";++function setup() {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ const spy = vi.spyOn(queryClient, "invalidateQueries");++ function wrapper({ children }: { children: ReactNode }) {+ return (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+ }++ const { result } = renderHook(() => useProcessReviews(), { wrapper });+ return {+ result,+ invalidatedKeys: () => spy.mock.calls.map((c) => c[0]?.queryKey),+ };+}++const item = {+ node_exec_id: "ne-1",+ approved: true,+ auto_approve_future: false,+};++// Dual-key invalidation is what makes the home count and the thread's list+// reconcile after either surface acts on a review; without it one of them+// keeps serving a review that has already been processed.+test("invalidates both the user-wide and the per-execution review queries", async () => {+ server.use(+ getPostV2ProcessReviewActionMockHandler200({+ approved_count: 1,+ rejected_count: 0,+ failed_count: 0,+ }),+ );+ const { result, invalidatedKeys } = setup();++ await result.current.processReviews([item], ["run-1", "run-1"]);++ const keys = invalidatedKeys();+ expect(keys).toContainEqual(getGetV2GetPendingReviewsQueryKey());+ const perExecution = getGetV2GetPendingReviewsForExecutionQueryKey("run-1");+ expect(keys).toContainEqual(perExecution);+ // Deduped: the same execution id twice must not fan out twice.+ expect(+ keys.filter((key) => JSON.stringify(key) === JSON.stringify(perExecution)),+ ).toHaveLength(1);+});++test("still invalidates when the mutation rejects", async () => {+ server.use(+ http.post("/api/proxy/api/review/action", () => HttpResponse.error()),+ );+ const { result, invalidatedKeys } = setup();++ await expect(+ result.current.processReviews([item], ["run-1"]),+ ).rejects.toBeDefined();++ expect(invalidatedKeys()).toContainEqual(getGetV2GetPendingReviewsQueryKey());+});diff --git a/autogpt_platform/frontend/src/hooks/useProcessReviews.ts b/autogpt_platform/frontend/src/hooks/useProcessReviews.tsnew file mode 100644index 0000000000..b089b53d19--- /dev/null+++ b/autogpt_platform/frontend/src/hooks/useProcessReviews.ts@@ -0,0 +1,38 @@+import {+ getGetV2GetPendingReviewsForExecutionQueryKey,+ getGetV2GetPendingReviewsQueryKey,+ usePostV2ProcessReviewAction,+} from "@/app/api/__generated__/endpoints/executions/executions";+import type { ReviewItem } from "@/app/api/__generated__/models/reviewItem";+import { useQueryClient } from "@tanstack/react-query";++export function useProcessReviews({+ onSettled,+}: { onSettled?: () => void } = {}) {+ const queryClient = useQueryClient();+ const { mutateAsync, isPending } = usePostV2ProcessReviewAction();++ async function processReviews(items: ReviewItem[], graphExecIds: string[]) {+ try {+ return await mutateAsync({ data: { reviews: items } });+ } finally {+ // Awaited so callers can keep a row locked until the refetch settles;+ // firing and forgetting leaves React Query serving the just-acted-on+ // review for the whole GET.+ await Promise.all([+ queryClient.invalidateQueries({+ queryKey: getGetV2GetPendingReviewsQueryKey(),+ }),+ ...[...new Set(graphExecIds)].map((graphExecId) =>+ queryClient.invalidateQueries({+ queryKey:+ getGetV2GetPendingReviewsForExecutionQueryKey(graphExecId),+ }),+ ),+ ]);+ onSettled?.();+ }+ }++ return { processReviews, isProcessing: isPending };+}diff --git a/autogpt_platform/frontend/src/lib/review-links.test.ts b/autogpt_platform/frontend/src/lib/review-links.test.tsnew file mode 100644index 0000000000..22577cd75b--- /dev/null+++ b/autogpt_platform/frontend/src/lib/review-links.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";+import { getReviewLink } from "./review-links";++function makeReview(+ overrides: Partial<PendingHumanReviewModel> = {},+): PendingHumanReviewModel {+ return {+ node_exec_id: "ne-1",+ node_id: "n-1",+ user_id: "u-1",+ graph_exec_id: "run-1",+ graph_id: "g-1",+ graph_version: 1,+ payload: {},+ instructions: "Approve outreach email",+ editable: true,+ status: "WAITING",+ created_at: new Date(),+ ...overrides,+ };+}++describe("getReviewLink", () => {+ it("opens the CoPilot thread for a session-scoped review", () => {+ expect(getReviewLink(makeReview({ session_id: "sess-1" }))).toBe(+ "/copilot?sessionId=sess-1",+ );+ });++ it("selects the run on the library agent page", () => {+ // activeTab/activeItem are the params NewAgentLibraryView parses;+ // anything else lands on the agent page without opening the run.+ expect(+ getReviewLink(+ makeReview({ library_agent_id: "lib-1", graph_exec_id: "run-1" }),+ ),+ ).toBe("/library/agents/lib-1?activeTab=runs&activeItem=run-1");+ });++ it("prefers the session link when both ids are present", () => {+ expect(+ getReviewLink(+ makeReview({ session_id: "sess-1", library_agent_id: "lib-1" }),+ ),+ ).toBe("/copilot?sessionId=sess-1");+ });++ it("falls back to the library when neither id resolved", () => {+ expect(getReviewLink(makeReview())).toBe("/library");+ });+});diff --git a/autogpt_platform/frontend/src/lib/review-links.ts b/autogpt_platform/frontend/src/lib/review-links.tsnew file mode 100644index 0000000000..f53f4caef8--- /dev/null+++ b/autogpt_platform/frontend/src/lib/review-links.ts@@ -0,0 +1,33 @@+import type { PendingHumanReviewModel } from "@/app/api/__generated__/models/pendingHumanReviewModel";++/**+ * Deep link to wherever a pending human review can be acted on.+ *+ * Lives here rather than next to a component so review surfaces (copilot+ * home, thread, library) share one definition of these routes instead of+ * each embedding path literals.+ *+ * Both ids come from the backend's review enrichment: `session_id` is set+ * for every CoPilot `run_block` review, `library_agent_id` for reviews+ * raised by a real graph execution.+ *+ * The library route selects a run via `activeTab`/`activeItem` — those are+ * the params `NewAgentLibraryView` actually parses, so anything else lands+ * on the agent page without opening the run.+ *+ * The morning briefing composes these same two routes server-side, in+ * `backend/copilot/briefing/generate.py` (`_run_link` and the decision-link+ * branch of `compose_briefing`) — change both together.+ */+export function getReviewLink(review: PendingHumanReviewModel): string {+ if (review.session_id) {+ return `/copilot?sessionId=${encodeURIComponent(review.session_id)}`;+ }+ if (review.library_agent_id) {+ return (+ `/library/agents/${encodeURIComponent(review.library_agent_id)}` ++ `?activeTab=runs&activeItem=${encodeURIComponent(review.graph_exec_id)}`+ );+ }+ return "/library";+}diff --git a/autogpt_platform/frontend/src/mocks/mock-handlers.ts b/autogpt_platform/frontend/src/mocks/mock-handlers.tsindex 6f2ebd1655..7b10c4655d 100644--- a/autogpt_platform/frontend/src/mocks/mock-handlers.ts+++ b/autogpt_platform/frontend/src/mocks/mock-handlers.ts@@ -8,6 +8,7 @@ import {getGetBrainDumpIntroMockHandler200,getGetBrainDumpRecommendedProvidersMockHandler200,} from "@/app/api/__generated__/endpoints/brain-dump/brain-dump.msw";+import { getBriefingsMock } from "@/app/api/__generated__/endpoints/briefings/briefings.msw";import { getChatMock } from "@/app/api/__generated__/endpoints/chat/chat.msw";import { getCreditsMock } from "@/app/api/__generated__/endpoints/credits/credits.msw";import { getDefaultMock } from "@/app/api/__generated__/endpoints/default/default.msw";@@ -51,6 +52,7 @@ export const mockHandlers = [ready: true,providers: [],}),+ ...getBriefingsMock(),...getChatMock(),...getCreditsMock(),...getDefaultMock(),