Skip to content

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.

fix(platform): home briefing reads persisted UserBriefing with live delta (#14017)

Abhimanyu Yadavd4af8a786f92
diff --git a/autogpt_platform/backend/backend/api/features/home/activity.py b/autogpt_platform/backend/backend/api/features/home/activity.py
index c392d23eb4..65eb7caa36 100644
--- a/autogpt_platform/backend/backend/api/features/home/activity.py
+++ b/autogpt_platform/backend/backend/api/features/home/activity.py
@@ -1,74 +1,16 @@
-from datetime import datetime, timedelta
-
from backend.api.features.experts.models import Expert
+from backend.copilot.briefing.outcome import as_utc_or_none, run_link
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
-from .helpers import (
- UNKNOWN_AGENT,
- AgentRef,
- as_utc,
- as_utc_or_none,
- parse_datetime,
- run_link,
- split_summary,
- to_home_expert,
-)
-from .models import (
- HomeActiveTask,
- HomeBriefing,
- HomeBriefingOutcome,
- HomeDailyActivity,
- HomeUpcomingTask,
- HomeWeekSummary,
-)
+from .helpers import UNKNOWN_AGENT, AgentRef, parse_datetime, to_home_expert
+from .models import HomeActiveTask, HomeDailyActivity, HomeUpcomingTask, HomeWeekSummary
-_MAX_OUTCOMES = 4
_MAX_ACTIVE = 3
_MAX_UPCOMING = 4
-def compose_briefing(
- *,
- now: datetime,
- executions: list[GraphExecutionMeta],
- expert_by_id: dict[str, Expert],
- agent_by_graph: dict[str, AgentRef],
-) -> HomeBriefing:
- window_start = now - timedelta(hours=24)
- terminal = [
- execution
- for execution in executions
- if execution.status in {ExecutionStatus.COMPLETED, ExecutionStatus.FAILED}
- and _occurred_at(execution, now) >= window_start
- ]
- # Failures first (they need a decision), then most recent within each group.
- terminal.sort(
- key=lambda execution: (
- execution.status == ExecutionStatus.COMPLETED,
- -_occurred_at(execution, now).timestamp(),
- )
- )
- outcomes = [
- _briefing_outcome(execution, expert_by_id, agent_by_graph)
- for execution in terminal[:_MAX_OUTCOMES]
- ]
- completed = sum(
- execution.status == ExecutionStatus.COMPLETED for execution in terminal
- )
- failed = sum(execution.status == ExecutionStatus.FAILED for execution in terminal)
- shown_completed = sum(outcome.status == "completed" for outcome in outcomes)
- return HomeBriefing(
- generated_at=now,
- window_started_at=window_start,
- completed_count=completed,
- failed_count=failed,
- routine_count=max(0, completed - shown_completed),
- outcomes=outcomes,
- )
-
-
def compose_active_tasks(
executions: list[GraphExecutionMeta],
expert_by_id: dict[str, Expert],
@@ -160,47 +102,3 @@ def compose_week_summary(
for day in summary.daily
],
)
-
-
-def _briefing_outcome(
- execution: GraphExecutionMeta,
- expert_by_id: dict[str, Expert],
- agent_by_graph: dict[str, AgentRef],
-) -> HomeBriefingOutcome:
- agent = agent_by_graph.get(execution.graph_id, UNKNOWN_AGENT)
- raw_summary = execution.stats.activity_status if execution.stats else None
- error = execution.stats.error if execution.stats else None
- failed = execution.status == ExecutionStatus.FAILED
- if failed:
- fallback_detail = (
- error or "Open the run to inspect the failure and choose the next step."
- )
- else:
- fallback_detail = "Completed successfully."
- # Only an AI summary may become the headline. A raw exception string is the
- # detail, never the card title.
- title, detail = split_summary(
- raw_summary,
- fallback_title=f"{agent.name} {'needs a retry' if failed else 'finished'}",
- fallback_detail=fallback_detail,
- )
- return HomeBriefingOutcome(
- id=execution.id,
- status="failed" if failed else "completed",
- title=title,
- summary=detail,
- expert=(
- to_home_expert(expert_by_id[execution.expert_id])
- if execution.expert_id in expert_by_id
- else None
- ),
- agent_name=agent.name,
- occurred_at=as_utc_or_none(execution.ended_at or execution.started_at),
- duration_seconds=execution.stats.duration if execution.stats else 0,
- cost_cents=execution.stats.cost if execution.stats else 0,
- link=run_link(agent.library_agent_id, execution.id),
- )
-
-
-def _occurred_at(execution: GraphExecutionMeta, now: datetime) -> datetime:
- return as_utc(execution.ended_at or execution.started_at or now)
diff --git a/autogpt_platform/backend/backend/api/features/home/activity_test.py b/autogpt_platform/backend/backend/api/features/home/activity_test.py
index 779418061d..42cb17bebe 100644
--- a/autogpt_platform/backend/backend/api/features/home/activity_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/activity_test.py
@@ -4,12 +4,7 @@ from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserDailyCost, UserExecutionCostSummary
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
-from .activity import (
- compose_active_tasks,
- compose_briefing,
- compose_upcoming_tasks,
- compose_week_summary,
-)
+from .activity import compose_active_tasks, compose_upcoming_tasks, compose_week_summary
from .helpers import AgentRef
NOW = datetime(2026, 8, 10, 9, 0, tzinfo=timezone.utc)
@@ -42,79 +37,6 @@ def _execution(
)
-def test_briefing_ignores_runs_outside_the_24h_window() -> None:
- briefing = compose_briefing(
- now=NOW,
- executions=[
- _execution(
- exec_id="fresh",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=2),
- ),
- _execution(
- exec_id="stale",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=30),
- ),
- ],
- expert_by_id={},
- agent_by_graph={"graph": AgentRef(name="Inbox triage", library_agent_id=None)},
- )
-
- assert briefing.window_started_at == NOW - timedelta(hours=24)
- assert briefing.completed_count == 1
- assert [outcome.id for outcome in briefing.outcomes] == ["fresh"]
-
-
-def test_briefing_lists_failures_before_successes() -> None:
- briefing = compose_briefing(
- now=NOW,
- executions=[
- _execution(
- exec_id="ok",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=1),
- activity_status="Sorted 12 emails. Nothing needed a reply.",
- ),
- _execution(
- exec_id="broken",
- status=ExecutionStatus.FAILED,
- ended_at=NOW - timedelta(hours=3),
- ),
- ],
- expert_by_id={},
- agent_by_graph={"graph": AgentRef(name="Inbox triage", library_agent_id=None)},
- )
-
- assert [outcome.status for outcome in briefing.outcomes] == ["failed", "completed"]
- assert briefing.failed_count == 1
- assert briefing.outcomes[0].title == "Inbox triage needs a retry"
- assert briefing.outcomes[1].title == "Sorted 12 emails."
- assert briefing.outcomes[1].summary == "Nothing needed a reply."
-
-
-def test_briefing_counts_unlisted_successes_as_routine() -> None:
- executions = [
- _execution(
- exec_id=f"run-{index}",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=1),
- )
- for index in range(6)
- ]
-
- briefing = compose_briefing(
- now=NOW,
- executions=executions,
- expert_by_id={},
- agent_by_graph={"graph": AgentRef(name="Inbox triage", library_agent_id=None)},
- )
-
- assert briefing.completed_count == 6
- assert len(briefing.outcomes) == 4
- assert briefing.routine_count == 2
-
-
def test_week_summary_maps_status_counts_and_credits() -> None:
summary = compose_week_summary(
UserExecutionCostSummary(
@@ -155,62 +77,6 @@ def test_week_summary_maps_status_counts_and_credits() -> None:
assert summary.daily[0].failed_count == 1
-def test_briefing_keeps_a_raw_error_out_of_the_headline() -> None:
- briefing = compose_briefing(
- now=NOW,
- executions=[
- _execution(
- exec_id="broken",
- status=ExecutionStatus.FAILED,
- ended_at=NOW - timedelta(hours=1),
- error="KeyError: 'recipient'",
- )
- ],
- expert_by_id={},
- agent_by_graph=TRIAGE,
- )
-
- assert briefing.outcomes[0].title == "Inbox triage needs a retry"
- assert briefing.outcomes[0].summary == "KeyError: 'recipient'"
-
-
-def test_briefing_orders_each_status_group_most_recent_first() -> None:
- briefing = compose_briefing(
- now=NOW,
- executions=[
- _execution(
- exec_id="old-failure",
- status=ExecutionStatus.FAILED,
- ended_at=NOW - timedelta(hours=8),
- ),
- _execution(
- exec_id="new-failure",
- status=ExecutionStatus.FAILED,
- ended_at=NOW - timedelta(hours=1),
- ),
- _execution(
- exec_id="old-success",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=9),
- ),
- _execution(
- exec_id="new-success",
- status=ExecutionStatus.COMPLETED,
- ended_at=NOW - timedelta(hours=2),
- ),
- ],
- expert_by_id={},
- agent_by_graph=TRIAGE,
- )
-
- assert [outcome.id for outcome in briefing.outcomes] == [
- "new-failure",
- "old-failure",
- "new-success",
- "old-success",
- ]
-
-
def test_active_tasks_map_status_and_cap_the_list() -> None:
executions = [
_execution(
diff --git a/autogpt_platform/backend/backend/api/features/home/attention.py b/autogpt_platform/backend/backend/api/features/home/attention.py
index 948d51d0ec..ab08a56fed 100644
--- a/autogpt_platform/backend/backend/api/features/home/attention.py
+++ b/autogpt_platform/backend/backend/api/features/home/attention.py
@@ -4,9 +4,10 @@ from urllib.parse import quote
from backend.api.features.executions.review.model import PendingHumanReviewModel
from backend.api.features.experts.models import Expert
+from backend.copilot.briefing.outcome import as_utc, run_link
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
-from .helpers import as_utc, run_link, setup_count, to_home_expert
+from .helpers import setup_count, to_home_expert
from .models import HomeAction, HomeAttentionItem, HomeExpert
# Longest payload preview we return before clipping it with an ellipsis.
diff --git a/autogpt_platform/backend/backend/api/features/home/briefing.py b/autogpt_platform/backend/backend/api/features/home/briefing.py
new file mode 100644
index 0000000000..7bb0bbec97
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/home/briefing.py
@@ -0,0 +1,216 @@
+"""The "what happened overnight" card on /home.
+
+The 9am job persists a `UserBriefing` and posts it into the copilot thread, so
+that row — not a fresh 24h recompute — is what the card anchors on. Runs that
+reached a terminal state *after* the row was generated are appended live, so a
+run finishing at 10:30am shows up on the next poll rather than tomorrow morning.
+"""
+
+from datetime import datetime, timedelta
+from typing import Literal
+
+from backend.api.features.experts.models import Expert
+from backend.copilot.briefing.models import BriefingContent, BriefingRunItem
+from backend.copilot.briefing.outcome import (
+ as_utc,
+ as_utc_or_none,
+ compose_run_outcome,
+ outcome_fallbacks,
+)
+from backend.data.execution import ExecutionStatus, GraphExecutionMeta
+
+from .helpers import UNKNOWN_AGENT, AgentRef, to_home_expert
+from .models import HomeBriefing, HomeBriefingOutcome, HomeExpert
+
+_MAX_OUTCOMES = 4
+_BRIEFING_WINDOW = timedelta(hours=24)
+
+
+def compose_briefing(
+ *,
+ now: datetime,
+ executions: list[GraphExecutionMeta],
+ expert_by_id: dict[str, Expert],
+ agent_by_graph: dict[str, AgentRef],
+ persisted: BriefingContent | None = None,
+) -> HomeBriefing:
+ if persisted is None:
+ window_start = now - _BRIEFING_WINDOW
+ return _briefing(
+ generated_at=now,
+ window_started_at=window_start,
+ outcomes=_live_outcomes(
+ executions, window_start, now, expert_by_id, agent_by_graph
+ ),
+ source="live",
+ )
+
+ generated_at = as_utc(persisted.generated_at)
+ anchored = [_outcome(item, expert_by_id) for item in persisted.run_items]
+ anchored_ids = {outcome.id for outcome in anchored}
+ fresh = [
+ outcome
+ for outcome in _live_outcomes(
+ executions, generated_at, now, expert_by_id, agent_by_graph
+ )
+ if outcome.id not in anchored_ids
+ ]
+ # Stable sort: failures need a decision so they lead, and within a status
+ # group the briefing's own ordering survives ahead of the newer runs.
+ merged = anchored + fresh
+ merged.sort(key=lambda outcome: outcome.status == "completed")
+ # `run_items` is capped by the job, so the anchor is a slice of the night
+ # rather than all of it. The stored totals carry the rest; without them a
+ # 12-run night would report the 10 that fit.
+ anchored_completed = sum(outcome.status == "completed" for outcome in anchored)
+ return _briefing(
+ generated_at=generated_at,
+ window_started_at=generated_at - _BRIEFING_WINDOW,
+ outcomes=merged,
+ source="persisted",
+ omitted_completed=max(0, persisted.completed_total - anchored_completed),
+ omitted_failed=max(
+ 0, persisted.failed_total - len(anchored) + anchored_completed
+ ),
+ )
+
+
+def without_summaries(content: BriefingContent) -> BriefingContent:
+ """Strip the AI-written text out of a stored briefing.
+
+ Summaries are persisted regardless of `AI_ACTIVITY_STATUS`, and the live
+ path scrubs them per-execution when the flag is off — so the persisted path
+ has to scrub them too, or the card would leak what the gate hides.
+
+ An item without a summary carries no AI text at all: its `title`/`detail`
+ already came from the non-AI fallback, and for a failure that detail is the
+ run's own error — which the live gate keeps (it drops only
+ `activity_status` and `correctness_score`). Clearing those too would
+ downgrade a real error to the generic retry line the moment home switched
+ to the persisted row.
+ """
+ return content.model_copy(
+ update={
+ "run_items": [
+ (
+ item.model_copy(update={"summary": None, "title": "", "detail": ""})
+ if item.summary
+ else item
+ )
+ for item in content.run_items
+ ]
+ }
+ )
+
+
+def _briefing(
+ *,
+ generated_at: datetime,
+ window_started_at: datetime,
+ outcomes: list[HomeBriefingOutcome],
+ source: Literal["persisted", "live"],
+ omitted_completed: int = 0,
+ omitted_failed: int = 0,
+) -> HomeBriefing:
+ """`omitted_*` are runs the briefing covered but did not list, so they
+ count toward the totals (and the routine overflow) without a card."""
+ listed_completed = sum(outcome.status == "completed" for outcome in outcomes)
+ completed = listed_completed + omitted_completed
+ shown = outcomes[:_MAX_OUTCOMES]
+ shown_completed = sum(outcome.status == "completed" for outcome in shown)
+ return HomeBriefing(
+ generated_at=generated_at,
+ window_started_at=window_started_at,
+ completed_count=completed,
+ failed_count=len(outcomes) - listed_completed + omitted_failed,
+ routine_count=max(0, completed - shown_completed),
+ outcomes=shown,
+ source=source,
+ )
+
+
+def _live_outcomes(
+ executions: list[GraphExecutionMeta],
+ since: datetime,
+ now: datetime,
+ expert_by_id: dict[str, Expert],
+ agent_by_graph: dict[str, AgentRef],
+) -> list[HomeBriefingOutcome]:
+ terminal = [
+ execution
+ for execution in executions
+ if execution.status in {ExecutionStatus.COMPLETED, ExecutionStatus.FAILED}
+ and _occurred_at(execution, now) >= since
+ ]
+ # Failures first (they need a decision), then most recent within each group.
+ terminal.sort(
+ key=lambda execution: (
+ execution.status == ExecutionStatus.COMPLETED,
+ -_occurred_at(execution, now).timestamp(),
+ )
+ )
+ return [
+ _outcome(_run_item(execution, expert_by_id, agent_by_graph), expert_by_id)
+ for execution in terminal
+ ]
+
+
+def _run_item(
+ execution: GraphExecutionMeta,
+ expert_by_id: dict[str, Expert],
+ agent_by_graph: dict[str, AgentRef],
+) -> BriefingRunItem:
+ agent = agent_by_graph.get(execution.graph_id, UNKNOWN_AGENT)
+ return compose_run_outcome(
+ execution,
+ agent_name=agent.name,
+ library_agent_id=agent.library_agent_id,
+ expert=expert_by_id.get(execution.expert_id or ""),
+ )
+
+
+def _outcome(
+ item: BriefingRunItem, expert_by_id: dict[str, Expert]
+) -> HomeBriefingOutcome:
+ failed = item.status == "FAILED"
+ # `error=None` because there is no error left to pass: the shared composer
+ # already resolved it into `item.detail`. These fallbacks only cover an
+ # item whose text fields are empty (a row older than them, or one the
+ # activity gate scrubbed).
+ fallback_title, fallback_detail = outcome_fallbacks(
+ item.agent_name, failed=failed, error=None
+ )
+ return HomeBriefingOutcome(
+ id=item.execution_id,
+ status="failed" if failed else "completed",
+ title=item.title or fallback_title,
+ summary=item.detail or fallback_detail,
+ expert=_expert(item, expert_by_id),
+ agent_name=item.agent_name,
+ occurred_at=as_utc_or_none(item.occurred_at),
+ duration_seconds=item.duration_seconds,
+ cost_cents=item.cost_cents,
+ link=item.link,
+ )
+
+
+def _expert(
+ item: BriefingRunItem, expert_by_id: dict[str, Expert]
+) -> HomeExpert | None:
+ """Prefer the live expert record; a stored briefing keeps its own copy of
+ the display fields for an expert that has since been archived or renamed."""
+ live = expert_by_id.get(item.expert_id or "")
+ if live:
+ return to_home_expert(live)
+ if not item.expert_id or not item.expert_name:
+ return None
+ return HomeExpert(
+ id=item.expert_id,
+ name=item.expert_name,
+ role=item.expert_role or "",
+ avatar_url=item.expert_avatar_url,
+ )
+
+
+def _occurred_at(execution: GraphExecutionMeta, now: datetime) -> datetime:
+ return as_utc(execution.ended_at or execution.started_at or now)
diff --git a/autogpt_platform/backend/backend/api/features/home/briefing_test.py b/autogpt_platform/backend/backend/api/features/home/briefing_test.py
new file mode 100644
index 0000000000..b0490cff66
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/home/briefing_test.py
@@ -0,0 +1,580 @@
+from datetime import datetime, timedelta, timezone
+
+from backend.api.features.experts.models import Expert
+from backend.copilot.briefing.generate import AgentInfo
+from backend.copilot.briefing.generate import compose_briefing as compose_job_briefing
+from backend.copilot.briefing.models import BriefingContent, BriefingRunItem
+from backend.data.execution import ExecutionStatus, GraphExecutionMeta
+
+from .briefing import compose_briefing, without_summaries
+from .helpers import AgentRef
+
+NOW = datetime(2026, 8, 10, 9, 0, tzinfo=timezone.utc)
+TRIAGE = {"graph": AgentRef(name="Inbox triage", library_agent_id="library-agent")}
+NO_LINK = {"graph": AgentRef(name="Inbox triage", library_agent_id=None)}
+
+
+def _execution(
+ *,
+ exec_id: str,
+ status: ExecutionStatus,
+ ended_at: datetime,
+ activity_status: str | None = None,
+ error: str | None = None,
+ expert_id: str | None = None,
+ graph_id: str = "graph",
+) -> GraphExecutionMeta:
+ return GraphExecutionMeta(
+ id=exec_id,
+ user_id="user",
+ graph_id=graph_id,
+ graph_version=1,
+ inputs=None,
+ credential_inputs=None,
+ nodes_input_masks=None,
+ preset_id=None,
+ status=status,
+ started_at=ended_at - timedelta(minutes=1),
+ ended_at=ended_at,
+ expert_id=expert_id,
+ stats=GraphExecutionMeta.Stats(
+ activity_status=activity_status, error=error, duration=42.0, cost=7
+ ),
+ )
+
+
+def _expert(expert_id: str = "expert-1") -> Expert:
+ return Expert(
+ id=expert_id,
+ name="Ana",
+ avatar_url="https://a/x.png",
+ 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=[],
+ )
+
+
+def _stored(
+ *items: BriefingRunItem,
+ generated_at: datetime = NOW,
+ completed_total: int = 0,
+ failed_total: int = 0,
+) -> BriefingContent:
+ return BriefingContent(
+ generated_at=generated_at,
+ timezone="UTC",
+ zero_expert_fallback=False,
+ run_items=list(items),
+ decision_items=[],
+ decision_total=0,
+ completed_total=completed_total,
+ failed_total=failed_total,
+ )
+
+
+def _stored_item(
+ execution_id: str,
+ *,
+ status: str = "COMPLETED",
+ title: str = "Sorted 12 emails.",
+ detail: str = "Nothing needed a reply.",
+) -> BriefingRunItem:
+ return BriefingRunItem(
+ expert_id="expert-1",
+ expert_name="Ana",
+ expert_role="Researcher",
+ expert_avatar_url="https://a/x.png",
+ agent_name="Inbox triage",
+ graph_id="graph",
+ execution_id=execution_id,
+ library_agent_id="library-agent",
+ status=status,
+ summary=f"{title} {detail}",
+ title=title,
+ detail=detail,
+ occurred_at=NOW - timedelta(hours=2),
+ duration_seconds=42.0,
+ cost_cents=7,
+ link="/library/agents/library-agent?activeTab=runs&activeItem=" + execution_id,
+ )
+
+
+def test_briefing_ignores_runs_outside_the_24h_window() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[
+ _execution(
+ exec_id="fresh",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=2),
+ ),
+ _execution(
+ exec_id="stale",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=30),
+ ),
+ ],
+ expert_by_id={},
+ agent_by_graph=NO_LINK,
+ )
+
+ assert briefing.source == "live"
+ assert briefing.window_started_at == NOW - timedelta(hours=24)
+ assert briefing.completed_count == 1
+ assert [outcome.id for outcome in briefing.outcomes] == ["fresh"]
+
+
+def test_briefing_lists_failures_before_successes() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[
+ _execution(
+ exec_id="ok",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=1),
+ activity_status="Sorted 12 emails. Nothing needed a reply.",
+ ),
+ _execution(
+ exec_id="broken",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW - timedelta(hours=3),
+ ),
+ ],
+ expert_by_id={},
+ agent_by_graph=NO_LINK,
+ )
+
+ assert [outcome.status for outcome in briefing.outcomes] == ["failed", "completed"]
+ assert briefing.failed_count == 1
+ assert briefing.outcomes[0].title == "Inbox triage needs a retry"
+ assert briefing.outcomes[1].title == "Sorted 12 emails."
+ assert briefing.outcomes[1].summary == "Nothing needed a reply."
+
+
+def test_briefing_counts_unlisted_successes_as_routine() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[
+ _execution(
+ exec_id=f"run-{index}",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=1),
+ )
+ for index in range(6)
+ ],
+ expert_by_id={},
+ agent_by_graph=NO_LINK,
+ )
+
+ assert briefing.completed_count == 6
+ assert len(briefing.outcomes) == 4
+ assert briefing.routine_count == 2
+
+
+def test_briefing_keeps_a_raw_error_out_of_the_headline() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[
+ _execution(
+ exec_id="broken",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW - timedelta(hours=1),
+ error="KeyError: 'recipient'",
+ )
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ )
+
+ assert briefing.outcomes[0].title == "Inbox triage needs a retry"
+ assert briefing.outcomes[0].summary == "KeyError: 'recipient'"
+
+
+def test_briefing_orders_each_status_group_most_recent_first() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[
+ _execution(
+ exec_id="old-failure",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW - timedelta(hours=8),
+ ),
+ _execution(
+ exec_id="new-failure",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW - timedelta(hours=1),
+ ),
+ _execution(
+ exec_id="old-success",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=9),
+ ),
+ _execution(
+ exec_id="new-success",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=2),
+ ),
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ )
+
+ assert [outcome.id for outcome in briefing.outcomes] == [
+ "new-failure",
+ "old-failure",
+ "new-success",
+ "old-success",
+ ]
+
+
+def test_persisted_briefing_anchors_the_card_on_the_stored_row() -> None:
+ """The stored row is what the copilot thread was posted from, so the card
+ must tell that story — not a fresh 24h recompute of it."""
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=2),
+ # Present in the live window but absent from the stored row (the job
+ # only briefs expert-owned runs) — it must not become an anchor.
+ executions=[
+ _execution(
+ exec_id="not-in-the-briefing",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=3),
+ )
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("stored-run")),
+ )
+
+ assert briefing.source == "persisted"
+ assert briefing.generated_at == NOW
+ assert briefing.window_started_at == NOW - timedelta(hours=24)
+ assert [outcome.id for outcome in briefing.outcomes] == ["stored-run"]
+ outcome = briefing.outcomes[0]
+ assert (outcome.title, outcome.summary) == (
+ "Sorted 12 emails.",
+ "Nothing needed a reply.",
+ )
+ assert (outcome.duration_seconds, outcome.cost_cents) == (42.0, 7)
+
+
+def test_persisted_briefing_appends_runs_that_finished_after_it() -> None:
+ """A run that finishes at 10:30am belongs on the next poll, not tomorrow."""
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=2),
+ executions=[
+ _execution(
+ exec_id="after-the-briefing",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW + timedelta(hours=1, minutes=30),
+ activity_status="Booked the flight.",
+ ),
+ # Already told in the stored row — it must not be listed twice.
+ _execution(
+ exec_id="stored-run",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=2),
+ ),
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("stored-run")),
+ )
+
+ assert [outcome.id for outcome in briefing.outcomes] == [
+ "stored-run",
+ "after-the-briefing",
+ ]
+ assert briefing.completed_count == 2
+ assert briefing.outcomes[1].title == "Booked the flight."
+
+
+def test_persisted_briefing_sorts_a_later_failure_above_stored_successes() -> None:
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=3),
+ executions=[
+ _execution(
+ exec_id="broke-later",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW + timedelta(hours=2),
+ )
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("stored-run")),
+ )
+
+ assert [outcome.id for outcome in briefing.outcomes] == [
+ "broke-later",
+ "stored-run",
+ ]
+ assert (briefing.failed_count, briefing.completed_count) == (1, 1)
+
+
+def test_persisted_briefing_caps_outcomes_and_absorbs_the_overflow() -> None:
+ stored = _stored(*[_stored_item(f"stored-{index}") for index in range(3)])
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=4),
+ executions=[
+ _execution(
+ exec_id=f"later-{index}",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW + timedelta(hours=1, minutes=index),
+ )
+ for index in range(3)
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=stored,
+ )
+
+ assert briefing.completed_count == 6
+ assert len(briefing.outcomes) == 4
+ assert briefing.routine_count == 2
+ assert [outcome.id for outcome in briefing.outcomes][:3] == [
+ "stored-0",
+ "stored-1",
+ "stored-2",
+ ]
+
+
+def test_persisted_briefing_prefers_the_live_expert_record() -> None:
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={"expert-1": _expert()},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("stored-run")),
+ )
+
+ expert = briefing.outcomes[0].expert
+ assert expert is not None
+ assert (expert.id, expert.name, expert.role) == ("expert-1", "Ana", "Researcher")
+
+
+def test_persisted_briefing_drops_attribution_without_a_stored_name() -> None:
+ """An id with nothing to render beside it is not an attribution — the card
+ would otherwise show an expert row with a blank name."""
+ nameless = _stored_item("stored-run").model_copy(update={"expert_name": None})
+
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(nameless),
+ )
+
+ assert briefing.outcomes[0].expert is None
+
+
+def test_persisted_failures_keep_their_order_ahead_of_later_ones() -> None:
+ """Both halves are failures, so the status key can't separate them: the
+ stable sort is what keeps the briefing's own story first."""
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=2),
+ executions=[
+ _execution(
+ exec_id="broke-later",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW + timedelta(hours=1),
+ )
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("broke-overnight", status="FAILED")),
+ )
+
+ assert [outcome.id for outcome in briefing.outcomes] == [
+ "broke-overnight",
+ "broke-later",
+ ]
+ assert briefing.failed_count == 2
+
+
+def test_persisted_briefing_keeps_stored_attribution_for_an_unknown_expert() -> None:
+ """An expert archived since this morning still owns the run it produced."""
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(_stored_item("stored-run")),
+ )
+
+ expert = briefing.outcomes[0].expert
+ assert expert is not None
+ assert (expert.id, expert.name, expert.role) == ("expert-1", "Ana", "Researcher")
+
+
+def test_a_row_written_before_the_composer_was_unified_falls_back_to_the_agent() -> (
+ None
+):
+ """`title`/`detail` were added with the shared composer — an older row has
+ neither, and must still render a usable headline."""
+ legacy = BriefingRunItem(
+ expert_id=None,
+ expert_name=None,
+ expert_avatar_url=None,
+ agent_name="Inbox triage",
+ graph_id="graph",
+ execution_id="legacy-run",
+ library_agent_id=None,
+ status="FAILED",
+ summary="Sorted 12 emails.",
+ link=None,
+ )
+
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(legacy),
+ )
+
+ outcome = briefing.outcomes[0]
+ assert outcome.title == "Inbox triage needs a retry"
+ assert outcome.summary == (
+ "Open the run to inspect the failure and choose the next step."
+ )
+ assert outcome.expert is None
+
+
+def test_without_summaries_drops_the_ai_written_text() -> None:
+ stripped = without_summaries(_stored(_stored_item("stored-run")))
+
+ item = stripped.run_items[0]
+ assert (item.summary, item.title, item.detail) == (None, "", "")
+ assert item.agent_name == "Inbox triage"
+
+
+def test_without_summaries_keeps_an_error_the_ai_never_wrote() -> None:
+ """The live gate drops only `activity_status`/`correctness_score`, so a
+ failure with no summary keeps showing its real error. The persisted path
+ must not downgrade that same failure to the generic retry line."""
+ failure = _stored_item("broke", status="FAILED").model_copy(
+ update={
+ "summary": None,
+ "title": "Inbox triage needs a retry",
+ "detail": "SMTP connection refused",
+ }
+ )
+
+ item = without_summaries(_stored(failure)).run_items[0]
+
+ assert (item.title, item.detail) == (
+ "Inbox triage needs a retry",
+ "SMTP connection refused",
+ )
+
+
+def test_persisted_briefing_counts_runs_the_job_did_not_list() -> None:
+ """`run_items` is capped at 10 by the job. A 12-completion night must
+ still report 12 completed, with the unlisted ones falling into routine."""
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(
+ *(_stored_item(f"stored-{i}") for i in range(10)),
+ completed_total=12,
+ failed_total=0,
+ ),
+ )
+
+ assert briefing.completed_count == 12
+ assert briefing.failed_count == 0
+ assert len(briefing.outcomes) == 4
+ assert briefing.routine_count == 8
+
+
+def test_persisted_run_totals_absorb_runs_that_finished_later() -> None:
+ briefing = compose_briefing(
+ now=NOW + timedelta(hours=2),
+ executions=[
+ _execution(
+ exec_id="broke-later",
+ status=ExecutionStatus.FAILED,
+ ended_at=NOW + timedelta(hours=1),
+ )
+ ],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(
+ *(_stored_item(f"stored-{i}") for i in range(10)),
+ completed_total=12,
+ failed_total=0,
+ ),
+ )
+
+ assert (briefing.completed_count, briefing.failed_count) == (12, 1)
+
+
+def test_persisted_briefing_falls_back_to_the_listed_runs_without_totals() -> None:
+ """Rows written before the totals existed default them to 0 — the counts
+ then have to come off `run_items` rather than reporting nothing happened."""
+ briefing = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={},
+ agent_by_graph=TRIAGE,
+ persisted=_stored(
+ _stored_item("stored-run"),
+ _stored_item("broke", status="FAILED"),
+ ),
+ )
+
+ assert (briefing.completed_count, briefing.failed_count) == (1, 1)
+
+
+def test_the_job_and_home_describe_the_same_run_identically() -> None:
+ """One composer, two consumers: the copilot thread and the home card must
+ not be able to tell different stories about the same execution."""
+ execution = _execution(
+ exec_id="run-1",
+ status=ExecutionStatus.COMPLETED,
+ ended_at=NOW - timedelta(hours=1),
+ activity_status="Sorted 12 emails. Nothing needed a reply.",
+ expert_id="expert-1",
+ graph_id="g-1",
+ )
+ expert = _expert()
+
+ job_content = compose_job_briefing(
+ experts=[expert],
+ executions=[execution],
+ reviews=[],
+ agent_info_by_graph_id={"g-1": AgentInfo("Inbox triage", "library-agent")},
+ generated_at=NOW,
+ tz_name="UTC",
+ )
+ assert job_content is not None
+
+ home = compose_briefing(
+ now=NOW,
+ executions=[execution],
+ expert_by_id={"expert-1": expert},
+ agent_by_graph={
+ "g-1": AgentRef(name="Inbox triage", library_agent_id="library-agent")
+ },
+ )
+ anchored = compose_briefing(
+ now=NOW,
+ executions=[],
+ expert_by_id={"expert-1": expert},
+ agent_by_graph={},
+ persisted=job_content,
+ )
+
+ assert home.outcomes == anchored.outcomes
diff --git a/autogpt_platform/backend/backend/api/features/home/compose.py b/autogpt_platform/backend/backend/api/features/home/compose.py
index 5524f127c0..f502fc6b08 100644
--- a/autogpt_platform/backend/backend/api/features/home/compose.py
+++ b/autogpt_platform/backend/backend/api/features/home/compose.py
@@ -3,18 +3,15 @@ from datetime import datetime
from backend.api.features.executions.review.model import PendingHumanReviewModel
from backend.api.features.experts.models import Expert
from backend.api.features.library.model import LibraryAgentRef
+from backend.copilot.briefing.models import BriefingContent
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
-from .activity import (
- compose_active_tasks,
- compose_briefing,
- compose_upcoming_tasks,
- compose_week_summary,
-)
+from .activity import compose_active_tasks, compose_upcoming_tasks, compose_week_summary
from .agents import compose_agent_statuses, compose_team_summary
from .attention import compose_attention_items
+from .briefing import compose_briefing
from .helpers import agent_refs_by_graph, experts_by_schedule, next_runs_by_expert
from .models import HomeDashboardResponse
@@ -30,6 +27,7 @@ def compose_home_dashboard(
cost_summary: UserExecutionCostSummary,
credits_balance: int | None,
timezone_name: str,
+ persisted_briefing: BriefingContent | None = None,
) -> HomeDashboardResponse:
hired = [
expert
@@ -71,6 +69,7 @@ def compose_home_dashboard(
executions=executions,
expert_by_id=expert_by_id,
agent_by_graph=agent_by_graph,
+ persisted=persisted_briefing,
),
active_tasks=compose_active_tasks(executions, expert_by_id, agent_by_graph),
upcoming_tasks=compose_upcoming_tasks(schedules, expert_by_schedule),
diff --git a/autogpt_platform/backend/backend/api/features/home/helpers.py b/autogpt_platform/backend/backend/api/features/home/helpers.py
index 65a5b9c87f..15c08c9ba9 100644
--- a/autogpt_platform/backend/backend/api/features/home/helpers.py
+++ b/autogpt_platform/backend/backend/api/features/home/helpers.py
@@ -1,17 +1,14 @@
-from datetime import datetime, timezone
-from urllib.parse import quote
+from datetime import datetime
from pydantic import BaseModel, ConfigDict
from backend.api.features.experts.models import Expert
from backend.api.features.library.model import LibraryAgentRef
+from backend.copilot.briefing.outcome import DEFAULT_AGENT_NAME, as_utc
from backend.executor.scheduler import GraphExecutionJobInfo
from .models import HomeExpert
-# Longest a summary's first sentence may run before it is clipped into a title.
-_TITLE_MAX = 120
-
def to_home_expert(expert: Expert) -> HomeExpert:
return HomeExpert(
@@ -69,7 +66,7 @@ class AgentRef(BaseModel):
library_agent_id: str | None
-UNKNOWN_AGENT = AgentRef(name="Agent task", library_agent_id=None)
+UNKNOWN_AGENT = AgentRef(name=DEFAULT_AGENT_NAME, library_agent_id=None)
def agent_refs_by_graph(
@@ -100,41 +97,9 @@ def setup_count(expert: Expert) -> int:
)
-def as_utc(value: datetime) -> datetime:
- """Stored timestamps can come back naive; comparing those to an aware `now`
- raises, so pin anything naive to UTC before it reaches arithmetic or sorting.
- """
- return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
-
-
-def as_utc_or_none(value: datetime | None) -> datetime | None:
- return as_utc(value) if value else None
-
-
def parse_datetime(value: str) -> datetime | None:
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
return as_utc(parsed)
-
-
-def run_link(library_id: str | None, execution_id: str) -> str | None:
- if not library_id:
- return None
- return (
- f"/library/agents/{quote(library_id)}"
- f"?activeTab=runs&activeItem={quote(execution_id)}"
- )
-
-
-def split_summary(
- value: str | None, *, fallback_title: str, fallback_detail: str
-) -> tuple[str, str]:
- compact = " ".join(value.split()) if value else ""
- if not compact:
- return fallback_title, fallback_detail
- if ". " not in compact:
- return compact[:_TITLE_MAX], fallback_detail
- title, detail = compact.split(". ", 1)
- return f"{title}.", detail
diff --git a/autogpt_platform/backend/backend/api/features/home/helpers_test.py b/autogpt_platform/backend/backend/api/features/home/helpers_test.py
index e48e831062..91ccb2e9c0 100644
--- a/autogpt_platform/backend/backend/api/features/home/helpers_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/helpers_test.py
@@ -4,13 +4,7 @@ from backend.api.features.experts.models import Expert, ExpertWorkflowRef
from backend.executor.scheduler import GraphExecutionJobInfo
from .activity import compose_upcoming_tasks
-from .helpers import (
- experts_by_schedule,
- next_runs_by_expert,
- parse_datetime,
- run_link,
- split_summary,
-)
+from .helpers import experts_by_schedule, next_runs_by_expert, parse_datetime
SHARED_GRAPH = "graph-shared"
@@ -119,34 +113,6 @@ def test_upcoming_tasks_attribute_each_job_to_its_own_expert() -> None:
]
-def test_split_summary_uses_fallbacks_for_empty_input() -> None:
- assert split_summary(None, fallback_title="Ran", fallback_detail="All good") == (
- "Ran",
- "All good",
- )
- assert split_summary(" ", fallback_title="Ran", fallback_detail="All good") == (
- "Ran",
- "All good",
- )
-
-
-def test_split_summary_clips_a_single_sentence_title() -> None:
- title, detail = split_summary(
- "x" * 200, fallback_title="Ran", fallback_detail="All good"
- )
-
- assert title == "x" * 120
- assert detail == "All good"
-
-
-def test_split_summary_splits_on_the_first_sentence() -> None:
- assert split_summary(
- "Sorted 12 emails. Nothing needed a reply.",
- fallback_title="Ran",
- fallback_detail="All good",
- ) == ("Sorted 12 emails.", "Nothing needed a reply.")
-
-
def test_parse_datetime_pins_naive_values_to_utc() -> None:
assert parse_datetime("2026-08-10T09:00:00") == datetime(
2026, 8, 10, 9, 0, tzinfo=timezone.utc
@@ -158,10 +124,3 @@ def test_parse_datetime_pins_naive_values_to_utc() -> None:
def test_parse_datetime_returns_none_for_garbage() -> None:
assert parse_datetime("not-a-timestamp") is None
-
-
-def test_run_link_needs_a_library_agent() -> None:
- assert run_link(None, "execution") is None
- assert run_link("library agent", "exec/1") == (
- "/library/agents/library%20agent?activeTab=runs&activeItem=exec/1"
- )
diff --git a/autogpt_platform/backend/backend/api/features/home/models.py b/autogpt_platform/backend/backend/api/features/home/models.py
index 1ada6e4e36..cfe49c76e4 100644
--- a/autogpt_platform/backend/backend/api/features/home/models.py
+++ b/autogpt_platform/backend/backend/api/features/home/models.py
@@ -54,6 +54,10 @@ class HomeBriefing(BaseModel):
failed_count: int
routine_count: int
outcomes: list[HomeBriefingOutcome]
+ # "persisted": anchored on the morning `UserBriefing` the copilot thread was
+ # posted from, plus any run that finished after it. "live": no usable row
+ # for today, so the rolling 24h window was recomputed instead.
+ source: Literal["persisted", "live"] = "live"
class HomeActiveTask(BaseModel):
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index 16e6f1abd9..bf5766a0f9 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -2,8 +2,9 @@ import asyncio
import logging
from datetime import datetime, timedelta, timezone
from typing import Any
+from zoneinfo import ZoneInfo
-from pydantic import BaseModel
+from pydantic import BaseModel, ValidationError
from backend.api.features.executions.activity_gate import (
hide_activity_summaries_if_disabled,
@@ -12,6 +13,8 @@ from backend.api.features.executions.review.model import PendingHumanReviewModel
from backend.api.features.experts import experts_db
from backend.api.features.experts.models import Expert
from backend.api.features.library import db as library_db
+from backend.copilot.briefing.models import BriefingContent
+from backend.data import briefing as briefing_db
from backend.data import execution as execution_db
from backend.data import human_review as review_db
from backend.data import user as user_db
@@ -23,8 +26,10 @@ from backend.data.execution_cost_summary import (
)
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
from backend.util.clients import get_scheduler_client
+from backend.util.feature_flag import Flag, is_feature_enabled
from backend.util.timezone_utils import get_user_timezone_or_utc
+from .briefing import without_summaries
from .compose import compose_home_dashboard
from .models import HomeDashboardResponse
@@ -32,6 +37,9 @@ logger = logging.getLogger(__name__)
_EXECUTION_LIMIT = 300
_REVIEW_LIMIT = 100
+# Enough of a user id to correlate log lines for one user without writing the
+# whole identifier into logs that are retained and widely readable.
+_LOG_ID_CHARS = 12
class HomeSourceData(BaseModel):
@@ -61,8 +69,11 @@ async def build_home_dashboard(
{execution.graph_id for execution in data.executions}
| {review.graph_id for review in data.reviews}
)
- library_refs = await library_db.get_library_agent_refs_by_graph_ids(
- user_id, graph_ids
+ # Both depend on the gathered data (graph ids / timezone) but not on each
+ # other, so the briefing read costs no extra round-trip.
+ library_refs, persisted_briefing = await asyncio.gather(
+ library_db.get_library_agent_refs_by_graph_ids(user_id, graph_ids),
+ _persisted_briefing(user_id=user_id, timezone_name=data.timezone_name, now=now),
)
return compose_home_dashboard(
@@ -75,9 +86,56 @@ async def build_home_dashboard(
cost_summary=data.cost_summary,
credits_balance=data.credits_balance,
timezone_name=data.timezone_name,
+ persisted_briefing=persisted_briefing,
)
+async def _persisted_briefing(
+ *, user_id: str, timezone_name: str, now: datetime
+) -> BriefingContent | None:
+ """Today's stored briefing, or None when home should compute live instead.
+
+ None covers every way the anchor can be missing: no row yet (a pre-9am
+ signup), a job that failed, and — mirroring `briefings/routes.py` — stored
+ content written by a different composer version that no longer validates.
+
+ `delivered_at` is deliberately not part of that test. An unstamped row
+ means the content was stored but the thread post failed, and
+ `generate_and_deliver_briefing` redelivers *that same stored content* on
+ its next run rather than recomposing it. The undelivered row is therefore
+ already the canonical story; skipping it would put home back on a live
+ recompute that drifts from the message the user is about to receive —
+ exactly the divergence this card exists to remove.
+
+ The date comes off the request's own `now` rather than a second clock read:
+ loading the source data takes long enough to cross local midnight, and the
+ card would then look up tomorrow's row for a dashboard composed against
+ yesterday.
+ """
+ briefing_date = now.astimezone(ZoneInfo(timezone_name)).date()
+ try:
+ record = await briefing_db.get_briefing_for_date(user_id, briefing_date)
+ except Exception:
+ logger.warning(
+ "Home could not load the briefing for user %s", user_id[:_LOG_ID_CHARS]
+ )
+ return None
+ if record is None:
+ return None
+ try:
+ content = BriefingContent.model_validate(record.content)
+ except ValidationError:
+ logger.warning(
+ "Briefing %s failed to validate against BriefingContent; "
+ "home is composing its card live instead",
+ record.id,
+ )
+ return None
+ if await is_feature_enabled(Flag.AI_ACTIVITY_STATUS, user_id):
+ return content
+ return without_summaries(content)
+
+
async def _load_home_source_data(
*,
user_id: str,
@@ -141,7 +199,9 @@ async def _get_schedules(
try:
return await get_scheduler_client().get_execution_schedules(user_id=user_id)
except Exception:
- logger.warning("Home could not load schedules for user %s", user_id[:12])
+ logger.warning(
+ "Home could not load schedules for user %s", user_id[:_LOG_ID_CHARS]
+ )
return []
@@ -150,5 +210,7 @@ async def _get_credits(*, user_id: str, organization_id: str | None) -> int | No
model = await get_credit_model(user_id, organization_id)
return await model.get_credits(user_id, organization_id)
except Exception:
- logger.warning("Home could not load credits for user %s", user_id[:12])
+ logger.warning(
+ "Home could not load credits for user %s", user_id[:_LOG_ID_CHARS]
+ )
return None
diff --git a/autogpt_platform/backend/backend/api/features/home/service_test.py b/autogpt_platform/backend/backend/api/features/home/service_test.py
index bdf5bdc29d..12fcabecba 100644
--- a/autogpt_platform/backend/backend/api/features/home/service_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/service_test.py
@@ -1,9 +1,10 @@
-from datetime import datetime, timedelta, timezone
+from datetime import date, datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock
import pytest
from pytest_mock import MockerFixture
+from backend.copilot.briefing.models import BriefingContent, BriefingRunItem
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
@@ -79,6 +80,233 @@ def home_dependencies(mocker: MockerFixture):
"backend.api.features.home.service.get_credit_model",
AsyncMock(return_value=credit_model),
)
+ mocker.patch(
+ "backend.api.features.home.service.briefing_db.get_briefing_for_date",
+ AsyncMock(return_value=None),
+ )
+
+
+def _stored_briefing(**overrides) -> BriefingContent:
+ item = BriefingRunItem(
+ expert_id=None,
+ expert_name=None,
+ expert_avatar_url=None,
+ agent_name="Inbox triage",
+ graph_id="graph-1",
+ execution_id="stored-run",
+ library_agent_id=None,
+ status="COMPLETED",
+ summary="Filed the report. Nothing else was pending.",
+ title="Filed the report.",
+ detail="Nothing else was pending.",
+ occurred_at=datetime.now(timezone.utc) - timedelta(hours=1),
+ link=None,
+ )
+ return BriefingContent(
+ generated_at=datetime.now(timezone.utc) - timedelta(minutes=30),
+ timezone="UTC",
+ zero_expert_fallback=True,
+ run_items=[item],
+ decision_items=[],
+ decision_total=0,
+ **overrides,
+ )
+
+
+def _patch_stored_briefing(mocker: MockerFixture, content: object) -> None:
+ mocker.patch(
+ "backend.api.features.home.service.briefing_db.get_briefing_for_date",
+ AsyncMock(return_value=MagicMock(id="briefing-1", content=content)),
+ )
+
+
+async def test_briefing_anchors_on_todays_persisted_row(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ _patch_stored_briefing(mocker, _stored_briefing().model_dump(mode="json"))
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "persisted"
+ # The stored row anchors the card; the run that finished after it is
+ # appended live rather than held back until tomorrow morning.
+ assert [outcome.id for outcome in dashboard.briefing.outcomes] == [
+ "stored-run",
+ "exec-1",
+ ]
+ assert dashboard.briefing.outcomes[0].title == "Filed the report."
+ assert dashboard.briefing.outcomes[1].title == "Booked the flight."
+
+
+async def test_briefing_rejects_a_row_with_negative_totals(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """The counts drive what the card claims happened, and a stored row is
+ otherwise taken as canonical — a negative total is a corrupt row, so it
+ has to fail validation and drop home onto the live path."""
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ corrupt = _stored_briefing().model_dump(mode="json") | {"completed_total": -3}
+ _patch_stored_briefing(mocker, corrupt)
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "live"
+ assert dashboard.briefing.outcomes[0].title == "Booked the flight."
+
+
+async def test_briefing_anchors_on_a_row_the_job_could_not_deliver(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """`delivered_at=None` means the content was stored but the thread post
+ failed. The job redelivers that same stored content, so it is still the
+ canonical story — going live here would drift from the pending message."""
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.briefing_db.get_briefing_for_date",
+ AsyncMock(
+ return_value=MagicMock(
+ id="briefing-1",
+ delivered_at=None,
+ content=_stored_briefing().model_dump(mode="json"),
+ )
+ ),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "persisted"
+ assert dashboard.briefing.outcomes[0].title == "Filed the report."
+
+
+async def test_briefing_falls_back_to_live_when_the_stored_row_is_malformed(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ _patch_stored_briefing(mocker, {"unexpected": "shape"})
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "live"
+ assert dashboard.briefing.outcomes[0].title == "Booked the flight."
+
+
+async def test_briefing_falls_back_to_live_when_the_lookup_raises(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """A briefing the page cannot read is not worth a 500 — /home is the
+ landing page, and every other tile on it is still fine."""
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.briefing_db.get_briefing_for_date",
+ AsyncMock(side_effect=Exception("database is down")),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "live"
+ assert dashboard.briefing.outcomes[0].title == "Booked the flight."
+
+
+async def test_briefing_is_live_when_no_row_exists_yet(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """A user who signed up after 9am has no briefing to anchor on."""
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "live"
+ assert [outcome.id for outcome in dashboard.briefing.outcomes] == ["exec-1"]
+
+
+async def test_briefing_date_comes_from_the_requests_own_clock(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """Loading the source data can cross local midnight. The row looked up has
+ to be the one for the date the rest of the dashboard was composed against —
+ a second clock read would fetch tomorrow's row for today's dashboard."""
+ just_before_midnight = datetime(2026, 8, 10, 23, 59, 59, tzinfo=timezone.utc)
+ clock = MagicMock(wraps=datetime)
+ # Any read after the first lands on the next day; only one is allowed.
+ clock.now.side_effect = [
+ just_before_midnight,
+ just_before_midnight + timedelta(seconds=2),
+ ]
+ mocker.patch("backend.api.features.home.service.datetime", clock)
+ lookup = AsyncMock(return_value=None)
+ mocker.patch(
+ "backend.api.features.home.service.briefing_db.get_briefing_for_date", lookup
+ )
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=True),
+ )
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert lookup.await_args.args[1] == date(2026, 8, 10)
+ assert dashboard.generated_at == just_before_midnight
+
+
+async def test_persisted_summaries_are_scrubbed_when_the_activity_flag_is_off(
+ mocker: MockerFixture, home_dependencies
+) -> None:
+ """Summaries are stored regardless of the flag, so the persisted path has
+ to scrub them too — otherwise the card leaks what the gate hides."""
+ mocker.patch(
+ "backend.api.features.executions.activity_gate.is_feature_enabled",
+ AsyncMock(return_value=False),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.is_feature_enabled",
+ AsyncMock(return_value=False),
+ )
+ _patch_stored_briefing(mocker, _stored_briefing().model_dump(mode="json"))
+
+ dashboard = await build_home_dashboard(user_id="user-1")
+
+ assert dashboard.briefing.source == "persisted"
+ assert dashboard.briefing.outcomes[0].title == "Inbox triage finished"
+ assert dashboard.briefing.outcomes[0].summary == "Completed successfully."
+ # The hybrid response also appends the live run; a one-sided scrub that
+ # covered only the stored half would still leak through that one.
+ assert dashboard.briefing.outcomes[1].title == "Agent task finished"
+ assert dashboard.briefing.outcomes[1].summary == "Completed successfully."
@pytest.mark.asyncio
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate.py b/autogpt_platform/backend/backend/copilot/briefing/generate.py
index 82a1a3490f..2687780a60 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate.py
@@ -1,6 +1,5 @@
import asyncio
import logging
-import re
import uuid
from datetime import datetime, timedelta
from datetime import timezone as dt_timezone
@@ -26,6 +25,8 @@ 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
+from .outcome import DEFAULT_AGENT_NAME, compose_run_outcome, run_link
+from .render import render_briefing_markdown
logger = logging.getLogger(__name__)
@@ -40,8 +41,6 @@ _MAX_DECISION_ITEMS = 10
_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"
@@ -63,35 +62,6 @@ class AgentInfo(NamedTuple):
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],
@@ -114,24 +84,13 @@ def compose_briefing(
# 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),
- )
- )
+ run_items = [
+ _run_item(execution, agent_info_by_graph_id, experts_by_id)
+ for execution in terminal[:_MAX_RUN_ITEMS]
+ ]
+ # Counted before the cap: home reports "N completed / N failed" off the
+ # stored row, and len(run_items) would under-report a busy night.
+ failed_total = sum(1 for e in terminal if str(e.status) == "FAILED")
expert_id_by_exec = {e.id: e.expert_id for e in executions}
decision_items = []
@@ -145,7 +104,10 @@ def compose_briefing(
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
+ link = (
+ run_link(info.library_agent_id if info else None, 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.
@@ -174,62 +136,23 @@ def compose_briefing(
run_items=run_items,
decision_items=decision_items,
decision_total=len(reviews),
+ completed_total=len(terminal) - failed_total,
+ failed_total=failed_total,
)
-# 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()
+def _run_item(
+ execution: GraphExecutionMeta,
+ agent_info_by_graph_id: dict[str, AgentInfo],
+ experts_by_id: dict[str, Expert],
+) -> BriefingRunItem:
+ info = agent_info_by_graph_id.get(execution.graph_id)
+ return compose_run_outcome(
+ execution,
+ agent_name=info.name if info else DEFAULT_AGENT_NAME,
+ library_agent_id=info.library_agent_id if info else None,
+ expert=experts_by_id.get(execution.expert_id or ""),
+ )
# Fixed namespace so the same (user, local calendar date) always derives the
@@ -245,7 +168,7 @@ def _merge_agent_info(agent_info: dict[str, AgentInfo], experts: list[Expert]) -
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.name or (existing.name if existing else DEFAULT_AGENT_NAME),
wf.library_agent_id
or (existing.library_agent_id if existing else None),
)
@@ -299,7 +222,7 @@ async def _compose_fresh_briefing(
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
+ ref.graph_id: AgentInfo(ref.name or DEFAULT_AGENT_NAME, ref.id) for ref in refs
}
_merge_agent_info(agent_info, experts)
diff --git a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
index 718c39f5c7..2fd9e503ec 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/generate_test.py
@@ -1,12 +1,10 @@
-from datetime import datetime, timezone
+from datetime import datetime, timedelta, timezone
import pytest
-from backend.copilot.briefing.generate import (
- AgentInfo,
- compose_briefing,
- render_briefing_markdown,
-)
+from backend.copilot.briefing.generate import AgentInfo, compose_briefing
+from backend.copilot.briefing.render import render_briefing_markdown
+from backend.data.execution import ExecutionStatus, GraphExecutionMeta
NOW = datetime(2026, 8, 7, 9, 0, tzinfo=timezone.utc)
@@ -38,16 +36,24 @@ def make_exec(
id="run-1",
graph_id="g-1",
expert_id="exp-1",
- status="COMPLETED",
+ status=ExecutionStatus.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
+ return GraphExecutionMeta(
+ id=id,
+ user_id="user-1",
+ graph_id=graph_id,
+ graph_version=1,
+ inputs=None,
+ credential_inputs=None,
+ nodes_input_masks=None,
+ preset_id=None,
+ status=status,
+ started_at=NOW - timedelta(minutes=5),
+ ended_at=NOW,
+ expert_id=expert_id,
+ stats=GraphExecutionMeta.Stats(activity_status=summary),
+ )
def make_review(
@@ -181,8 +187,8 @@ 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"),
+ make_exec(id="run-1", status=ExecutionStatus.COMPLETED),
+ make_exec(id="run-2", status=ExecutionStatus.FAILED),
],
reviews=[],
agent_info_by_graph_id={"g-1": AgentInfo("Lead Finder", "lib-1")},
@@ -194,7 +200,9 @@ def test_failed_runs_sort_before_completed():
def test_run_items_capped_at_ten():
- executions = [make_exec(id=f"run-{i}", status="COMPLETED") for i in range(12)]
+ executions = [
+ make_exec(id=f"run-{i}", status=ExecutionStatus.COMPLETED) for i in range(12)
+ ]
content = compose_briefing(
experts=[make_expert()],
executions=executions,
@@ -562,14 +570,14 @@ async def test_generate_keeps_library_link_when_workflow_has_no_library_agent_id
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")
+def test_run_items_carry_the_card_fields_home_reads():
+ """The stored row is what /home anchors its card on, so the shared composer
+ has to persist the split headline, timings and cost — not just the raw
+ summary the markdown renderer needs."""
+ execution = make_exec(summary="Filed 2 tickets. All were duplicates.")
+ execution.stats = GraphExecutionMeta.Stats(
+ activity_status="Filed 2 tickets. All were duplicates.", duration=12.5, cost=3
+ )
content = compose_briefing(
experts=[make_expert()],
@@ -581,7 +589,11 @@ def test_summary_reads_stats_model_not_just_dict():
)
assert content is not None
- assert content.run_items[0].summary == "Filed 2 tickets"
+ item = content.run_items[0]
+ assert item.summary == "Filed 2 tickets. All were duplicates."
+ assert (item.title, item.detail) == ("Filed 2 tickets.", "All were duplicates.")
+ assert (item.duration_seconds, item.cost_cents) == (12.5, 3)
+ assert item.expert_role == "Researcher"
def test_markdown_escapes_untrusted_text_in_link_labels():
@@ -609,6 +621,27 @@ def test_markdown_escapes_untrusted_text_in_link_labels():
)
+def test_run_totals_survive_the_run_item_cap():
+ """Home reports "N completed / N failed" off the stored row, so the counts
+ have to describe the whole night rather than the 10 runs that fit."""
+ executions = [
+ make_exec(id=f"run-{i}", status=ExecutionStatus.COMPLETED) for i in range(12)
+ ] + [make_exec(id="broke", status=ExecutionStatus.FAILED)]
+
+ 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
+ assert (content.completed_total, content.failed_total) == (12, 1)
+
+
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."""
@@ -717,7 +750,7 @@ async def test_generate_writes_recomposed_content_back_to_an_unreadable_row(
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"
+ assert update_call.args[2]["run_items"][0]["agent_name"] == "Agent task"
@pytest.mark.asyncio
@@ -788,7 +821,6 @@ async def test_generate_bounds_the_execution_query(monkeypatch):
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
diff --git a/autogpt_platform/backend/backend/copilot/briefing/models.py b/autogpt_platform/backend/backend/copilot/briefing/models.py
index 6d9b13b1a7..29c547c057 100644
--- a/autogpt_platform/backend/backend/copilot/briefing/models.py
+++ b/autogpt_platform/backend/backend/copilot/briefing/models.py
@@ -1,6 +1,6 @@
from datetime import datetime
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
class BriefingRunItem(BaseModel):
@@ -12,8 +12,18 @@ class BriefingRunItem(BaseModel):
execution_id: str
library_agent_id: str | None
status: str
+ # Raw `stats.activity_status`, kept verbatim for the markdown renderer.
summary: str | None
link: str | None
+ # Card fields the home dashboard reads off a stored briefing. All default,
+ # so a stored row that predates them still validates — the home mapper
+ # falls back to the agent-name headline when `title` is empty.
+ expert_role: str | None = None
+ title: str = ""
+ detail: str = ""
+ occurred_at: datetime | None = None
+ duration_seconds: float = 0
+ cost_cents: int = 0
class BriefingDecisionItem(BaseModel):
@@ -32,8 +42,14 @@ class BriefingContent(BaseModel):
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 = 0
+ # Pre-cap totals. Each list above is truncated for rendering, so these are
+ # what a consumer counts from; they default to 0 both so rows stored before
+ # the field existed still validate and so "<= len(<list>)" reads as
+ # "nothing was truncated". `ge=0` because a stored row is treated as
+ # canonical — a negative count is a corrupt row, and failing validation
+ # sends both readers down their existing recompute path rather than
+ # letting it reach the card.
+ decision_total: int = Field(default=0, ge=0)
+ # Split by outcome because home reports completed and failed separately.
+ completed_total: int = Field(default=0, ge=0)
+ failed_total: int = Field(default=0, ge=0)
diff --git a/autogpt_platform/backend/backend/copilot/briefing/outcome.py b/autogpt_platform/backend/backend/copilot/briefing/outcome.py
new file mode 100644
index 0000000000..02674284dd
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/briefing/outcome.py
@@ -0,0 +1,121 @@
+"""One execution, one briefing item — shared by every consumer.
+
+The 9am job (``backend/copilot/briefing/generate.py``) and the home dashboard
+(``backend/api/features/home/briefing.py``) both describe "what happened
+overnight". Composing that description in two places let the copilot thread and
+the home card disagree about the same run, so both now come through here.
+"""
+
+from datetime import datetime, timezone
+from urllib.parse import quote
+
+from backend.api.features.experts.models import Expert
+from backend.data.execution import ExecutionStatus, GraphExecutionMeta
+
+from .models import BriefingRunItem
+
+# Shared fallback for a run whose agent couldn't be resolved in the library.
+DEFAULT_AGENT_NAME = "Agent task"
+_FAILED_DETAIL = "Open the run to inspect the failure and choose the next step."
+_COMPLETED_DETAIL = "Completed successfully."
+# Longest a summary's first sentence may run before it is clipped into a title.
+_TITLE_MAX = 120
+
+
+def compose_run_outcome(
+ execution: GraphExecutionMeta,
+ *,
+ agent_name: str,
+ library_agent_id: str | None,
+ expert: Expert | None,
+) -> BriefingRunItem:
+ """Describe one terminal execution as a briefing item.
+
+ `execution` must have reached COMPLETED or FAILED: anything that is not
+ FAILED is described as a success, so a still-running execution would be
+ reported as finished. Both callers filter to terminal statuses first.
+ """
+ failed = execution.status == ExecutionStatus.FAILED
+ stats = execution.stats
+ raw_summary = stats.activity_status if stats else None
+ fallback_title, fallback_detail = outcome_fallbacks(
+ agent_name, failed=failed, error=stats.error if stats else None
+ )
+ # Only an AI summary may become the headline. A raw exception string is the
+ # detail, never the card title.
+ title, detail = split_summary(
+ raw_summary, fallback_title=fallback_title, fallback_detail=fallback_detail
+ )
+ return BriefingRunItem(
+ expert_id=expert.id if expert else None,
+ expert_name=expert.name if expert else None,
+ expert_role=expert.role if expert else None,
+ expert_avatar_url=expert.avatar_url if expert else None,
+ agent_name=agent_name,
+ graph_id=execution.graph_id,
+ execution_id=execution.id,
+ library_agent_id=library_agent_id,
+ status="FAILED" if failed else "COMPLETED",
+ summary=raw_summary,
+ title=title,
+ detail=detail,
+ occurred_at=as_utc_or_none(execution.ended_at or execution.started_at),
+ duration_seconds=stats.duration if stats else 0,
+ cost_cents=stats.cost if stats else 0,
+ link=run_link(library_agent_id, execution.id),
+ )
+
+
+def outcome_fallbacks(
+ agent_name: str, *, failed: bool, error: str | None
+) -> tuple[str, str]:
+ """Headline and detail for a run that carries no AI summary."""
+ if failed:
+ return f"{agent_name} needs a retry", error or _FAILED_DETAIL
+ return f"{agent_name} finished", _COMPLETED_DETAIL
+
+
+def split_summary(
+ value: str | None, *, fallback_title: str, fallback_detail: str
+) -> tuple[str, str]:
+ compact = " ".join(value.split()) if value else ""
+ if not compact:
+ return fallback_title, fallback_detail
+ if ". " not in compact:
+ return compact[:_TITLE_MAX], fallback_detail
+ title, detail = compact.split(". ", 1)
+ # A first sentence can run past the limit too — clip it like the
+ # single-sentence branch, or one rambling summary becomes a card headline
+ # hundreds of characters wide.
+ return f"{title[: _TITLE_MAX - 1].rstrip()}.", detail
+
+
+def run_link(library_agent_id: str | 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``). Both ids are encoded with ``safe=""`` so
+ they stay single components: ``quote`` keeps ``/`` by default, and an id
+ carrying one would otherwise redraw the path boundary. That also stops a
+ link target from carrying markdown or URL metacharacters.
+
+ Same route contract as the frontend's ``getReviewLink``
+ (``frontend/src/lib/review-links.ts``) — change both together.
+ """
+ if not library_agent_id:
+ return None
+ return (
+ f"/library/agents/{quote(library_agent_id, safe='')}"
+ f"?activeTab=runs&activeItem={quote(execution_id, safe='')}"
+ )
+
+
+def as_utc(value: datetime) -> datetime:
+ """Stored timestamps can come back naive; comparing those to an aware `now`
+ raises, so pin anything naive to UTC before it reaches arithmetic or sorting.
+ """
+ return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
+
+
+def as_utc_or_none(value: datetime | None) -> datetime | None:
+ return as_utc(value) if value else None
diff --git a/autogpt_platform/backend/backend/copilot/briefing/outcome_test.py b/autogpt_platform/backend/backend/copilot/briefing/outcome_test.py
new file mode 100644
index 0000000000..92b0c3aabc
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/briefing/outcome_test.py
@@ -0,0 +1,163 @@
+from datetime import datetime, timedelta, timezone
+
+from backend.api.features.experts.models import Expert
+from backend.data.execution import ExecutionStatus, GraphExecutionMeta
+
+from .outcome import as_utc, compose_run_outcome, run_link, split_summary
+
+NOW = datetime(2026, 8, 10, 9, 0, tzinfo=timezone.utc)
+
+
+def _execution(
+ *,
+ status: ExecutionStatus = ExecutionStatus.COMPLETED,
+ activity_status: str | None = None,
+ error: str | None = None,
+) -> GraphExecutionMeta:
+ return GraphExecutionMeta(
+ id="run-1",
+ user_id="user",
+ graph_id="graph-1",
+ graph_version=1,
+ inputs=None,
+ credential_inputs=None,
+ nodes_input_masks=None,
+ preset_id=None,
+ status=status,
+ started_at=NOW - timedelta(minutes=5),
+ ended_at=NOW,
+ expert_id="expert-1",
+ stats=GraphExecutionMeta.Stats(
+ activity_status=activity_status, error=error, duration=30.0, cost=9
+ ),
+ )
+
+
+def _expert() -> Expert:
+ return Expert(
+ id="expert-1",
+ name="Ana",
+ avatar_url="https://a/x.png",
+ 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=[],
+ )
+
+
+def test_outcome_splits_the_summary_and_carries_stats() -> None:
+ item = compose_run_outcome(
+ _execution(activity_status="Sorted 12 emails. Nothing needed a reply."),
+ agent_name="Inbox triage",
+ library_agent_id="lib-1",
+ expert=_expert(),
+ )
+
+ assert (item.title, item.detail) == ("Sorted 12 emails.", "Nothing needed a reply.")
+ assert item.summary == "Sorted 12 emails. Nothing needed a reply."
+ assert (item.status, item.duration_seconds, item.cost_cents) == (
+ "COMPLETED",
+ 30.0,
+ 9,
+ )
+ assert item.occurred_at == NOW
+ assert item.link == "/library/agents/lib-1?activeTab=runs&activeItem=run-1"
+ assert (item.expert_name, item.expert_role) == ("Ana", "Researcher")
+
+
+def test_a_raw_error_stays_out_of_the_headline() -> None:
+ item = compose_run_outcome(
+ _execution(status=ExecutionStatus.FAILED, error="KeyError: 'recipient'"),
+ agent_name="Inbox triage",
+ library_agent_id=None,
+ expert=None,
+ )
+
+ assert item.status == "FAILED"
+ assert item.title == "Inbox triage needs a retry"
+ assert item.detail == "KeyError: 'recipient'"
+ assert item.link is None
+ assert item.expert_id is None
+
+
+def test_a_failure_without_an_error_gets_a_next_step_detail() -> None:
+ item = compose_run_outcome(
+ _execution(status=ExecutionStatus.FAILED),
+ agent_name="Inbox triage",
+ library_agent_id=None,
+ expert=None,
+ )
+
+ assert item.detail == (
+ "Open the run to inspect the failure and choose the next step."
+ )
+
+
+def test_split_summary_uses_fallbacks_for_empty_input() -> None:
+ assert split_summary(None, fallback_title="Ran", fallback_detail="All good") == (
+ "Ran",
+ "All good",
+ )
+ assert split_summary(" ", fallback_title="Ran", fallback_detail="All good") == (
+ "Ran",
+ "All good",
+ )
+
+
+def test_split_summary_clips_a_single_sentence_title() -> None:
+ title, detail = split_summary(
+ "x" * 200, fallback_title="Ran", fallback_detail="All good"
+ )
+
+ assert title == "x" * 120
+ assert detail == "All good"
+
+
+def test_split_summary_clips_a_long_first_sentence() -> None:
+ """A period past the limit must not smuggle an unbounded headline through
+ the split branch."""
+ title, detail = split_summary(
+ "y" * 200 + ". And then some more.",
+ fallback_title="Ran",
+ fallback_detail="All good",
+ )
+
+ assert title == "y" * 119 + "."
+ assert len(title) == 120
+ assert detail == "And then some more."
+
+
+def test_split_summary_splits_on_the_first_sentence() -> None:
+ assert split_summary(
+ "Sorted 12 emails. Nothing needed a reply.",
+ fallback_title="Ran",
+ fallback_detail="All good",
+ ) == ("Sorted 12 emails.", "Nothing needed a reply.")
+
+
+def test_run_link_needs_a_library_agent() -> None:
+ assert run_link(None, "execution") is None
+ assert run_link("library agent", "exec-1") == (
+ "/library/agents/library%20agent?activeTab=runs&activeItem=exec-1"
+ )
+
+
+def test_run_link_keeps_each_id_a_single_url_component() -> None:
+ """`quote` keeps `/` by default; an id carrying one would otherwise move
+ the boundary between the path and the route it addresses."""
+ assert run_link("lib/1", "exec/1") == (
+ "/library/agents/lib%2F1?activeTab=runs&activeItem=exec%2F1"
+ )
+
+
+def test_as_utc_pins_naive_timestamps() -> None:
+ assert as_utc(NOW.replace(tzinfo=None)) == NOW
+ assert as_utc(NOW) == NOW
diff --git a/autogpt_platform/backend/backend/copilot/briefing/render.py b/autogpt_platform/backend/backend/copilot/briefing/render.py
new file mode 100644
index 0000000000..d5a836d783
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/briefing/render.py
@@ -0,0 +1,59 @@
+"""Markdown rendering for the briefing posted into the copilot thread."""
+
+import re
+
+from .models import BriefingContent
+
+# 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 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()
+
+
+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})"
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/MorningBriefing/MorningBriefing.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/MorningBriefing/MorningBriefing.tsx
index 4d118895d2..ece46fc3ce 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/components/MorningBriefing/MorningBriefing.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/MorningBriefing/MorningBriefing.tsx
@@ -8,6 +8,7 @@ import {
import type { HomeDashboardResponse } from "@/app/api/__generated__/models/homeDashboardResponse";
import { Icon } from "@/components/atoms/Icon/Icon";
import { Text } from "@/components/atoms/Text/Text";
+import { formatBriefingWindowStart } from "../../helpers";
import { HomeTileEmpty } from "../HomeTileEmpty/HomeTileEmpty";
import { HomeTileFilter } from "../HomeTileFilter/HomeTileFilter";
import { HomeTile } from "../HomeTile/HomeTile";
@@ -69,7 +70,12 @@ export function MorningBriefing({ dashboard, className }: Props) {
}
header={
<Text variant="large" className="text-zinc-600">
- The outcomes worth knowing from the last 24 hours.
+ The outcomes worth knowing since{" "}
+ {formatBriefingWindowStart(
+ briefing.window_started_at,
+ dashboard.timezone,
+ )}
+ .
</Text>
}
>
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts b/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
index ebdd1fb281..cacbc66a5d 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/home/helpers.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import type { HomeDashboardResponse } from "@/app/api/__generated__/models/homeDashboardResponse";
import {
+ formatBriefingWindowStart,
formatCurrency,
formatDuration,
formatHeaderDate,
@@ -50,6 +51,16 @@ describe("formatters", () => {
).toEqual({ weekday: "Monday", calendarDate: "August 10" });
});
+ it("names the start of the briefing window", () => {
+ expect(
+ formatBriefingWindowStart(
+ new Date("2026-08-09T03:30:00Z"),
+ "Asia/Kolkata",
+ "en-US",
+ ),
+ ).toBe("Sunday 9:00 AM");
+ });
+
it("formats measured runtime and cost", () => {
expect(formatDuration(18_120)).toBe("5h 2m");
expect(formatDuration(120)).toBe("2m");
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
index 64365f2437..80cc999d30 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
+++ b/autogpt_platform/frontend/src/app/(platform)/home/helpers.ts
@@ -42,6 +42,22 @@ export function formatHeaderDate(
};
}
+// The briefing card anchors on the persisted 9am briefing and keeps appending
+// runs that finish through the day, so its span is only "the last 24 hours"
+// first thing in the morning. Name the actual start instead of a fixed window.
+export function formatBriefingWindowStart(
+ value: Date,
+ timeZone: string,
+ locale?: string,
+): string {
+ return new Intl.DateTimeFormat(locale, {
+ timeZone,
+ weekday: "long",
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(new Date(value));
+}
+
export function formatDuration(totalSeconds: number): string {
const totalMinutes = Math.round(totalSeconds / 60);
const hours = Math.floor(totalMinutes / 60);
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index ff873f533b..1cb21ee328 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -15372,8 +15372,21 @@
},
"decision_total": {
"type": "integer",
+ "minimum": 0.0,
"title": "Decision Total",
"default": 0
+ },
+ "completed_total": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Completed Total",
+ "default": 0
+ },
+ "failed_total": {
+ "type": "integer",
+ "minimum": 0.0,
+ "title": "Failed Total",
+ "default": 0
}
},
"type": "object",
@@ -15478,6 +15491,29 @@
"link": {
"anyOf": [{ "type": "string" }, { "type": "null" }],
"title": "Link"
+ },
+ "expert_role": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Expert Role"
+ },
+ "title": { "type": "string", "title": "Title", "default": "" },
+ "detail": { "type": "string", "title": "Detail", "default": "" },
+ "occurred_at": {
+ "anyOf": [
+ { "type": "string", "format": "date-time" },
+ { "type": "null" }
+ ],
+ "title": "Occurred At"
+ },
+ "duration_seconds": {
+ "type": "number",
+ "title": "Duration Seconds",
+ "default": 0
+ },
+ "cost_cents": {
+ "type": "integer",
+ "title": "Cost Cents",
+ "default": 0
}
},
"type": "object",
@@ -19121,6 +19157,12 @@
"items": { "$ref": "#/components/schemas/HomeBriefingOutcome" },
"type": "array",
"title": "Outcomes"
+ },
+ "source": {
+ "type": "string",
+ "enum": ["persisted", "live"],
+ "title": "Source",
+ "default": "live"
}
},
"type": "object",