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.

feat(platform): surface agent work on the homepage via an activity event log (#14216)

Ubbea869696e3cad
diff --git a/autogpt_platform/backend/backend/api/features/home/compose.py b/autogpt_platform/backend/backend/api/features/home/compose.py
index 43c55df337..c27f8fb938 100644
--- a/autogpt_platform/backend/backend/api/features/home/compose.py
+++ b/autogpt_platform/backend/backend/api/features/home/compose.py
@@ -5,6 +5,7 @@ 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.copilot.model import ChatSessionInfo
+from backend.data.activity_event import ActivityEvent
from backend.data.execution import ExecutionStatus, GraphExecutionMeta
from backend.data.execution_cost_summary import UserExecutionCostSummary
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
@@ -15,6 +16,7 @@ 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
+from .recent_work import compose_recent_work
def compose_home_dashboard(
@@ -30,6 +32,8 @@ def compose_home_dashboard(
timezone_name: str,
questions: list[ChatSessionInfo] | None = None,
persisted_briefing: BriefingContent | None = None,
+ work_events: list[ActivityEvent] | None = None,
+ session_titles: dict[str, str | None] | None = None,
) -> HomeDashboardResponse:
hired = [
expert
@@ -82,4 +86,7 @@ def compose_home_dashboard(
team=compose_team_summary(agents),
agents=agents,
week=compose_week_summary(cost_summary, credits_balance),
+ recent_work=compose_recent_work(
+ work_events or [], expert_by_id, session_titles or {}
+ ),
)
diff --git a/autogpt_platform/backend/backend/api/features/home/models.py b/autogpt_platform/backend/backend/api/features/home/models.py
index 0773f1436e..b1d524847a 100644
--- a/autogpt_platform/backend/backend/api/features/home/models.py
+++ b/autogpt_platform/backend/backend/api/features/home/models.py
@@ -1,7 +1,7 @@
from datetime import date, datetime
from typing import Literal
-from pydantic import BaseModel
+from pydantic import BaseModel, Field
from backend.api.features.executions.review.model import PendingHumanReviewModel
@@ -122,6 +122,40 @@ class HomeWeekSummary(BaseModel):
daily: list[HomeDailyActivity]
+class HomeWorkActor(BaseModel):
+ # "expert" = a hired expert did it, "autopilot" = the default copilot
+ # assistant, "agent" = a graph run with no expert attribution.
+ kind: Literal["expert", "autopilot", "agent"]
+ name: str
+ expert: HomeExpert | None = None
+
+
+class HomeRecentWorkItem(BaseModel):
+ id: str
+ category: Literal["file", "integration", "schedule"]
+ event_type: str
+ title: str
+ occurred_at: datetime
+ provider: str | None = None
+ file_id: str | None = None
+ mime_type: str | None = None
+
+
+class HomeRecentWorkGroup(BaseModel):
+ actor: HomeWorkActor
+ session_id: str | None = None
+ session_title: str | None = None
+ link: str | None = None
+ latest_at: datetime
+ items: list[HomeRecentWorkItem]
+ more_count: int = 0
+
+
+class HomeRecentWork(BaseModel):
+ groups: list[HomeRecentWorkGroup] = Field(default_factory=list)
+ total_count: int = 0
+
+
class HomeDashboardResponse(BaseModel):
generated_at: datetime
timezone: str
@@ -132,3 +166,6 @@ class HomeDashboardResponse(BaseModel):
team: HomeTeamSummary
agents: list[HomeAgentStatus]
week: HomeWeekSummary
+ # Optional with a default so pre-existing clients (and their fixtures)
+ # keep validating; the backend always populates it.
+ recent_work: HomeRecentWork = Field(default_factory=HomeRecentWork)
diff --git a/autogpt_platform/backend/backend/api/features/home/recent_work.py b/autogpt_platform/backend/backend/api/features/home/recent_work.py
new file mode 100644
index 0000000000..c3bb4969f6
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/home/recent_work.py
@@ -0,0 +1,103 @@
+"""Compose the Home "Recent work" feed from activity events.
+
+Runs are deliberately excluded here: completed runs are the briefing's
+job. This card shows the durable things agents produced — files written,
+integration actions taken, schedules set up — grouped by who did the
+work and in which thread.
+"""
+
+from typing import Literal
+
+from backend.api.features.experts.models import Expert
+from backend.data.activity_event import ActivityEvent
+
+from .helpers import to_home_expert
+from .models import (
+ HomeRecentWork,
+ HomeRecentWorkGroup,
+ HomeRecentWorkItem,
+ HomeWorkActor,
+)
+
+_MAX_GROUPS = 6
+_MAX_ITEMS_PER_GROUP = 4
+
+_ITEM_CATEGORIES: dict[str, Literal["file", "integration", "schedule"]] = {
+ "FILE": "file",
+ "INTEGRATION": "integration",
+ "SCHEDULE": "schedule",
+}
+
+
+def compose_recent_work(
+ events: list[ActivityEvent],
+ expert_by_id: dict[str, Expert],
+ session_titles: dict[str, str | None],
+) -> HomeRecentWork:
+ """Group displayable events by (actor, thread), newest group first.
+
+ *events* arrive newest-first, so first-seen insertion order already
+ ranks groups by their latest event.
+ """
+ grouped: dict[tuple[str, str], list[ActivityEvent]] = {}
+ for event in events:
+ if event.category not in _ITEM_CATEGORIES:
+ continue
+ key = (event.expert_id or "", event.session_id or "")
+ grouped.setdefault(key, []).append(event)
+
+ groups = [
+ _compose_group(group_events, expert_by_id, session_titles)
+ for group_events in grouped.values()
+ ]
+ total_count = sum(len(group_events) for group_events in grouped.values())
+ return HomeRecentWork(groups=groups[:_MAX_GROUPS], total_count=total_count)
+
+
+def _compose_group(
+ events: list[ActivityEvent],
+ expert_by_id: dict[str, Expert],
+ session_titles: dict[str, str | None],
+) -> HomeRecentWorkGroup:
+ newest = events[0]
+ session_id = newest.session_id
+ return HomeRecentWorkGroup(
+ actor=_compose_actor(newest, expert_by_id),
+ session_id=session_id,
+ session_title=session_titles.get(session_id) if session_id else None,
+ link=f"/copilot?sessionId={session_id}" if session_id else None,
+ latest_at=newest.created_at,
+ items=[_compose_item(event) for event in events[:_MAX_ITEMS_PER_GROUP]],
+ more_count=max(0, len(events) - _MAX_ITEMS_PER_GROUP),
+ )
+
+
+def _compose_actor(
+ event: ActivityEvent, expert_by_id: dict[str, Expert]
+) -> HomeWorkActor:
+ if event.expert_id:
+ expert = expert_by_id.get(event.expert_id)
+ if expert:
+ return HomeWorkActor(
+ kind="expert", name=expert.name, expert=to_home_expert(expert)
+ )
+ # The expert was archived or removed after the fact; the event and
+ # its attribution kind survive, only the profile is gone.
+ return HomeWorkActor(kind="expert", name="Expert")
+ if event.session_id:
+ return HomeWorkActor(kind="autopilot", name="Autopilot")
+ return HomeWorkActor(kind="agent", name="Agent run")
+
+
+def _compose_item(event: ActivityEvent) -> HomeRecentWorkItem:
+ mime_type = event.data.get("mime_type")
+ return HomeRecentWorkItem(
+ id=event.id,
+ category=_ITEM_CATEGORIES[event.category],
+ event_type=event.event_type,
+ title=event.title,
+ occurred_at=event.created_at,
+ provider=event.provider,
+ file_id=event.object_id if event.category == "FILE" else None,
+ mime_type=mime_type if isinstance(mime_type, str) else None,
+ )
diff --git a/autogpt_platform/backend/backend/api/features/home/recent_work_test.py b/autogpt_platform/backend/backend/api/features/home/recent_work_test.py
new file mode 100644
index 0000000000..47ec6a087d
--- /dev/null
+++ b/autogpt_platform/backend/backend/api/features/home/recent_work_test.py
@@ -0,0 +1,129 @@
+from datetime import datetime, timedelta, timezone
+
+from backend.api.features.experts.models import Expert
+from backend.data.activity_event import ActivityEvent, ActivityEventCategory
+
+from .recent_work import _MAX_ITEMS_PER_GROUP, compose_recent_work
+
+NOW = datetime(2026, 8, 28, 9, 0, tzinfo=timezone.utc)
+
+
+def _expert(expert_id: str, name: str) -> Expert:
+ return Expert(
+ id=expert_id,
+ name=name,
+ avatar_url=None,
+ role="Marketing",
+ tagline=None,
+ bio=None,
+ skills=[],
+ identity="",
+ voice_preferences="",
+ boundaries="",
+ protected_soul_rules=[],
+ is_template=False,
+ source_template_id=None,
+ is_archived=False,
+ workflows=[],
+ last_run_status=None,
+ schedules_paused_at=None,
+ )
+
+
+def _event(
+ *,
+ event_id: str,
+ category: ActivityEventCategory = "FILE",
+ minutes_ago: int = 0,
+ expert_id: str | None = None,
+ session_id: str | None = None,
+ title: str = "draft.md",
+ provider: str | None = None,
+ object_id: str | None = None,
+) -> ActivityEvent:
+ return ActivityEvent(
+ id=event_id,
+ user_id="user-1",
+ created_at=NOW - timedelta(minutes=minutes_ago),
+ category=category,
+ event_type="file.created" if category == "FILE" else "integration.action",
+ title=title,
+ expert_id=expert_id,
+ session_id=session_id,
+ provider=provider,
+ object_id=object_id,
+ )
+
+
+def test_groups_by_actor_and_thread_newest_first() -> None:
+ maria = _expert("maria", "Maria")
+ events = [
+ _event(event_id="e1", expert_id="maria", session_id="s1", minutes_ago=1),
+ _event(event_id="e2", session_id="s2", minutes_ago=5),
+ _event(event_id="e3", expert_id="maria", session_id="s1", minutes_ago=10),
+ ]
+
+ work = compose_recent_work(events, {"maria": maria}, {"s1": "Blog pipeline"})
+
+ assert work.total_count == 3
+ assert [group.actor.name for group in work.groups] == ["Maria", "Autopilot"]
+ maria_group = work.groups[0]
+ assert maria_group.actor.kind == "expert"
+ assert maria_group.actor.expert is not None
+ assert maria_group.session_title == "Blog pipeline"
+ assert maria_group.link == "/copilot?sessionId=s1"
+ assert [item.id for item in maria_group.items] == ["e1", "e3"]
+ assert work.groups[1].actor.kind == "autopilot"
+
+
+def test_runs_are_excluded_and_items_capped() -> None:
+ events = [
+ _event(
+ event_id=f"e{index}",
+ expert_id="maria",
+ session_id="s1",
+ minutes_ago=index,
+ )
+ for index in range(_MAX_ITEMS_PER_GROUP + 3)
+ ] + [_event(event_id="run-1", category="RUN", session_id="s1")]
+
+ work = compose_recent_work(events, {}, {})
+
+ assert work.total_count == _MAX_ITEMS_PER_GROUP + 3
+ group = work.groups[0]
+ assert len(group.items) == _MAX_ITEMS_PER_GROUP
+ assert group.more_count == 3
+ # The expert profile is gone but the attribution kind survives.
+ assert group.actor.kind == "expert"
+ assert group.actor.name == "Expert"
+
+
+def test_graph_run_integration_event_without_session() -> None:
+ events = [
+ _event(
+ event_id="e1",
+ category="INTEGRATION",
+ title="Send Email",
+ provider="google",
+ object_id="block-1",
+ )
+ ]
+
+ work = compose_recent_work(events, {}, {})
+
+ group = work.groups[0]
+ assert group.actor.kind == "agent"
+ assert group.link is None
+ assert group.items[0].provider == "google"
+ assert group.items[0].file_id is None
+
+
+def test_file_items_carry_file_id_and_mime_type() -> None:
+ event = _event(event_id="e1", session_id="s1", object_id="file-9")
+ event.data = {"mime_type": "text/markdown", "size_bytes": 10}
+
+ work = compose_recent_work([event], {}, {})
+
+ item = work.groups[0].items[0]
+ assert item.file_id == "file-9"
+ assert item.mime_type == "text/markdown"
diff --git a/autogpt_platform/backend/backend/api/features/home/service.py b/autogpt_platform/backend/backend/api/features/home/service.py
index 250f77adb8..c1bd134480 100644
--- a/autogpt_platform/backend/backend/api/features/home/service.py
+++ b/autogpt_platform/backend/backend/api/features/home/service.py
@@ -16,6 +16,7 @@ from backend.api.features.library import db as library_db
from backend.copilot import db as chat_db
from backend.copilot.briefing.models import BriefingContent
from backend.copilot.model import ChatSessionInfo
+from backend.data import activity_event as activity_db
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
@@ -39,6 +40,7 @@ logger = logging.getLogger(__name__)
_EXECUTION_LIMIT = 300
_REVIEW_LIMIT = 100
+_WORK_EVENT_LIMIT = 200
# 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
@@ -52,6 +54,7 @@ class HomeSourceData(BaseModel):
schedules: list[GraphExecutionJobInfo | CopilotTurnJobInfo]
credits_balance: int | None
questions: list[ChatSessionInfo]
+ work_events: list[activity_db.ActivityEvent]
timezone_name: str
@@ -72,11 +75,15 @@ async def build_home_dashboard(
{execution.graph_id for execution in data.executions}
| {review.graph_id for review in data.reviews}
)
- # 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(
+ work_session_ids = list(
+ {event.session_id for event in data.work_events if event.session_id}
+ )
+ # All depend on the gathered data (graph ids / session ids / timezone) but
+ # not on each other, so these reads cost no extra round-trip.
+ library_refs, persisted_briefing, session_titles = 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),
+ _get_session_titles(user_id=user_id, session_ids=work_session_ids),
)
return compose_home_dashboard(
@@ -91,6 +98,8 @@ async def build_home_dashboard(
timezone_name=data.timezone_name,
questions=data.questions,
persisted_briefing=persisted_briefing,
+ work_events=data.work_events,
+ session_titles=session_titles,
)
@@ -172,6 +181,9 @@ async def _load_home_source_data(
_get_credits(user_id=user_id, organization_id=organization_id)
)
questions_task = asyncio.create_task(_get_pending_questions(user_id=user_id))
+ work_events_task = asyncio.create_task(
+ _get_work_events(user_id=user_id, since=week_start)
+ )
user_task = asyncio.create_task(user_db.get_user_by_id(user_id))
# Gather rather than awaiting one by one: a failure in the first task would
# otherwise leave the rest detached with their exceptions never retrieved.
@@ -183,6 +195,7 @@ async def _load_home_source_data(
schedules_task,
credits_task,
questions_task,
+ work_events_task,
user_task,
]
await asyncio.gather(*started)
@@ -197,6 +210,7 @@ async def _load_home_source_data(
schedules=schedules_task.result(),
credits_balance=credits_task.result(),
questions=questions_task.result(),
+ work_events=work_events_task.result(),
timezone_name=get_user_timezone_or_utc(user.timezone if user else None),
)
@@ -234,6 +248,40 @@ async def _get_pending_questions(*, user_id: str) -> list[ChatSessionInfo]:
return []
+async def _get_work_events(
+ *, user_id: str, since: datetime
+) -> list[activity_db.ActivityEvent]:
+ # Fail-soft like schedules and credits: a broken audit read costs the
+ # Recent work card, not the page. Ships with the expert-team surface,
+ # so it is gated exactly like pending questions.
+ try:
+ if not await is_feature_enabled(Flag.HIRE_EXPERTS, user_id, default=False):
+ return []
+ return await activity_db.list_activity_events(
+ user_id,
+ since=since,
+ categories=["FILE", "INTEGRATION", "SCHEDULE"],
+ limit=_WORK_EVENT_LIMIT,
+ )
+ except Exception:
+ logger.warning(
+ "Home could not load work events for user %s", user_id[:_LOG_ID_CHARS]
+ )
+ return []
+
+
+async def _get_session_titles(
+ *, user_id: str, session_ids: list[str]
+) -> dict[str, str | None]:
+ try:
+ return await chat_db.get_session_titles(user_id, session_ids)
+ except Exception:
+ logger.warning(
+ "Home could not load session titles for user %s", user_id[:_LOG_ID_CHARS]
+ )
+ return {}
+
+
async def _get_credits(*, user_id: str, organization_id: str | None) -> int | None:
try:
model = await get_credit_model(user_id, organization_id)
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 6c4f33d02b..765693c5a9 100644
--- a/autogpt_platform/backend/backend/api/features/home/service_test.py
+++ b/autogpt_platform/backend/backend/api/features/home/service_test.py
@@ -85,6 +85,24 @@ def home_dependencies(mocker: MockerFixture):
"backend.api.features.home.service.briefing_db.get_briefing_for_date",
AsyncMock(return_value=None),
)
+ # The flag-gated sources must be mocked even though the gates default to
+ # off: several tests patch `service.is_feature_enabled` module-wide to
+ # True, which opens these gates too. Left unmocked, they then run real
+ # Prisma queries on this test's function-scoped event loop — the closed
+ # loop leaves a dead connection in the shared engine pool that panics the
+ # query engine when a later (session-loop) test starts a transaction.
+ mocker.patch(
+ "backend.api.features.home.service.chat_db.get_sessions_with_pending_question",
+ AsyncMock(return_value=[]),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.chat_db.get_session_titles",
+ AsyncMock(return_value={}),
+ )
+ mocker.patch(
+ "backend.api.features.home.service.activity_db.list_activity_events",
+ AsyncMock(return_value=[]),
+ )
def _stored_briefing(**overrides) -> BriefingContent:
diff --git a/autogpt_platform/backend/backend/copilot/db.py b/autogpt_platform/backend/backend/copilot/db.py
index 8cd73d9ab9..9ab34378c6 100644
--- a/autogpt_platform/backend/backend/copilot/db.py
+++ b/autogpt_platform/backend/backend/copilot/db.py
@@ -961,6 +961,22 @@ async def get_sessions_with_pending_question(
return [ChatSessionInfo.from_db(s) for s in sessions]
+async def get_session_titles(
+ user_id: str, session_ids: list[str]
+) -> dict[str, str | None]:
+ """Titles for the given sessions of *user_id*, keyed by session id.
+
+ Sessions that no longer exist (or belong to someone else) are simply
+ absent — callers render a fallback label instead.
+ """
+ if not session_ids:
+ return {}
+ rows = await PrismaChatSession.prisma().find_many(
+ where={"id": {"in": session_ids}, "userId": user_id}
+ )
+ return {row.id: row.title for row in rows}
+
+
def _escape_like(value: str) -> str:
"""Escape LIKE wildcards so ``title_contains`` matches literally.
diff --git a/autogpt_platform/backend/backend/copilot/tools/activity_event_hooks_test.py b/autogpt_platform/backend/backend/copilot/tools/activity_event_hooks_test.py
new file mode 100644
index 0000000000..d26da94ee3
--- /dev/null
+++ b/autogpt_platform/backend/backend/copilot/tools/activity_event_hooks_test.py
@@ -0,0 +1,126 @@
+"""Tests for the activity-event drafts side-effecting tools report."""
+
+from datetime import UTC, datetime
+
+from backend.copilot.model import ChatSession
+from backend.copilot.tools.models import BlockOutputResponse, ErrorResponse
+from backend.copilot.tools.run_block import RunBlockTool
+from backend.copilot.tools.schedule_followup import (
+ ScheduleCreatedResponse,
+ ScheduleFollowupTool,
+)
+from backend.copilot.tools.workspace_files import (
+ WorkspaceWriteResponse,
+ WriteWorkspaceFileTool,
+)
+
+
+def _make_session(expert_id: str | None = None) -> ChatSession:
+ return ChatSession(
+ session_id="test-session",
+ user_id="test-user",
+ title=None,
+ messages=[],
+ usage=[],
+ credentials={},
+ started_at=datetime.now(UTC),
+ updated_at=datetime.now(UTC),
+ expert_id=expert_id,
+ )
+
+
+def _write_response(path: str) -> WorkspaceWriteResponse:
+ return WorkspaceWriteResponse(
+ message="File written",
+ file_id="file-1",
+ name="draft.md",
+ path=path,
+ mime_type="text/markdown",
+ size_bytes=42,
+ download_url="workspace://file-1#text/markdown",
+ )
+
+
+def test_write_workspace_file_reports_file_event() -> None:
+ result = _write_response("/sessions/s1/draft.md")
+
+ draft = WriteWorkspaceFileTool().activity_event(
+ session=_make_session(), result=result, filename="draft.md"
+ )
+
+ assert draft is not None
+ assert draft.category == "FILE"
+ assert draft.event_type == "file.created"
+ assert draft.title == "draft.md"
+ assert draft.object_id == "file-1"
+ assert draft.data["mime_type"] == "text/markdown"
+
+
+def test_write_with_overwrite_reports_update() -> None:
+ result = _write_response("/draft.md")
+
+ draft = WriteWorkspaceFileTool().activity_event(
+ session=_make_session(), result=result, filename="draft.md", overwrite=True
+ )
+
+ assert draft is not None
+ assert draft.event_type == "file.updated"
+
+
+def test_error_response_reports_nothing() -> None:
+ draft = WriteWorkspaceFileTool().activity_event(
+ session=_make_session(),
+ result=ErrorResponse(message="boom", session_id="test-session"),
+ filename="draft.md",
+ )
+
+ assert draft is None
+
+
+def test_run_block_reports_integration_action_only_with_provider() -> None:
+ tool = RunBlockTool()
+ session = _make_session()
+ with_provider = BlockOutputResponse(
+ message="Block executed",
+ block_id="block-1",
+ block_name="Send Email",
+ outputs={},
+ provider="google",
+ session_id="test-session",
+ )
+ without_provider = with_provider.model_copy(update={"provider": None})
+ dry_run = with_provider.model_copy(update={"is_dry_run": True})
+
+ draft = tool.activity_event(session=session, result=with_provider)
+ assert draft is not None
+ assert draft.category == "INTEGRATION"
+ assert draft.provider == "google"
+ assert draft.title == "Send Email"
+
+ assert tool.activity_event(session=session, result=without_provider) is None
+ assert tool.activity_event(session=session, result=dry_run) is None
+
+
+def test_schedule_followup_reports_schedule_event() -> None:
+ result = ScheduleCreatedResponse(
+ message="Follow-up scheduled",
+ schedule_id="sched-1",
+ next_run_time="2026-08-29T07:00:00+00:00",
+ is_recurring=True,
+ session_id="test-session",
+ )
+
+ draft = ScheduleFollowupTool().activity_event(
+ session=_make_session(expert_id="maria"),
+ result=result,
+ message="Draft the next blog post",
+ cron="0 7 */3 * *",
+ name="persian.sh blog draft",
+ )
+
+ assert draft is not None
+ assert draft.category == "SCHEDULE"
+ assert draft.event_type == "schedule.created"
+ assert draft.title == "persian.sh blog draft"
+ assert draft.schedule_id == "sched-1"
+ assert draft.data["cron"] == "0 7 */3 * *"
diff --git a/autogpt_platform/backend/backend/copilot/tools/base.py b/autogpt_platform/backend/backend/copilot/tools/base.py
index d61d136bb1..0eaa839469 100644
--- a/autogpt_platform/backend/backend/copilot/tools/base.py
+++ b/autogpt_platform/backend/backend/copilot/tools/base.py
@@ -8,7 +8,8 @@ from openai.types.chat import ChatCompletionToolParam
from backend.copilot.model import ChatSession
from backend.copilot.response_model import StreamToolOutputAvailable
-from backend.data.db_accessors import workspace_db
+from backend.data.activity_event import ActivityEventDraft
+from backend.data.db_accessors import activity_event_db, workspace_db
from backend.util.truncate import truncate
from backend.util.workspace import WorkspaceManager
@@ -107,6 +108,32 @@ async def _persist_and_summarize(
)
+async def _record_activity(
+ tool: "BaseTool",
+ user_id: str,
+ session: ChatSession,
+ result: "ToolResponseBase",
+ kwargs: dict[str, Any],
+) -> None:
+ """Persist the tool call's activity event, if the tool reports one.
+
+ Best-effort by contract: the audit log must never break the tool call
+ that produced it, so every failure is swallowed after a warning.
+ """
+ try:
+ draft = tool.activity_event(session=session, result=result, **kwargs)
+ if draft is None:
+ return
+ draft.session_id = draft.session_id or session.session_id
+ draft.expert_id = draft.expert_id or session.expert_id
+ draft.organization_id = draft.organization_id or session.organization_id
+ await activity_event_db().create_activity_event(user_id=user_id, draft=draft)
+ except Exception:
+ logger.warning(
+ "Failed to record activity event for tool %s", tool.name, exc_info=True
+ )
+
+
class BaseTool:
"""Base class for all chat tools."""
@@ -140,6 +167,22 @@ class BaseTool:
"""
return True
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: "ToolResponseBase",
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ """Describe the durable work this call performed.
+
+ Side-effecting tools override this to report what they did (file
+ written, schedule created, integration used) for the activity log.
+ Read-only tools keep the default None. Called only on successful
+ ``_execute`` returns; overrides narrow on their success response
+ type, which skips error responses for free.
+ """
+ return None
+
def as_openai_tool(self) -> ChatCompletionToolParam:
"""Convert to OpenAI tool format."""
return ChatCompletionToolParam(
@@ -186,6 +229,8 @@ class BaseTool:
try:
result = await self._execute(user_id, session, **kwargs)
+ if user_id:
+ await _record_activity(self, user_id, session, result, kwargs)
raw_output = result.model_dump_json(exclude_none=True)
if (
diff --git a/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py b/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
index 79a496787b..60ef794699 100644
--- a/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
+++ b/autogpt_platform/backend/backend/copilot/tools/manage_schedules.py
@@ -7,6 +7,7 @@ from pydantic import BaseModel
from backend.api.features.library.db import get_library_agent
from backend.copilot.model import ChatSession
+from backend.data.activity_event import ActivityEventDraft
from backend.executor.scheduler import CopilotTurnJobInfo, GraphExecutionJobInfo
from backend.util.clients import get_scheduler_client
from backend.util.exceptions import NotAuthorizedError, NotFoundError
@@ -213,6 +214,21 @@ class DeleteScheduleTool(BaseTool):
"required": ["schedule_id"],
}
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, ScheduleDeletedResponse):
+ return None
+ return ActivityEventDraft(
+ category="SCHEDULE",
+ event_type="schedule.deleted",
+ title="Removed a schedule",
+ schedule_id=result.schedule_id,
+ )
+
async def _execute(
self,
user_id: str | None,
diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block.py b/autogpt_platform/backend/backend/copilot/tools/run_block.py
index cf9cedc32f..bf3535db59 100644
--- a/autogpt_platform/backend/backend/copilot/tools/run_block.py
+++ b/autogpt_platform/backend/backend/copilot/tools/run_block.py
@@ -7,6 +7,7 @@ from typing import Any
from backend.copilot.constants import COPILOT_NODE_EXEC_ID_SEPARATOR
from backend.copilot.context import get_current_permissions
from backend.copilot.model import ChatSession
+from backend.data.activity_event import ActivityEventDraft
from .base import BaseTool
from .helpers import (
@@ -15,7 +16,13 @@ from .helpers import (
execute_block,
prepare_block_for_execution,
)
-from .models import BlockDetails, BlockDetailsResponse, ErrorResponse, ToolResponseBase
+from .models import (
+ BlockDetails,
+ BlockDetailsResponse,
+ BlockOutputResponse,
+ ErrorResponse,
+ ToolResponseBase,
+)
logger = logging.getLogger(__name__)
@@ -71,6 +78,29 @@ class RunBlockTool(BaseTool):
def requires_auth(self) -> bool:
return True
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ # Only a credentialed execution is an integration action; schema
+ # lookups, dry runs and credential-less blocks leave no audit trail.
+ if (
+ not isinstance(result, BlockOutputResponse)
+ or not result.success
+ or result.is_dry_run
+ or not result.provider
+ ):
+ return None
+ return ActivityEventDraft(
+ category="INTEGRATION",
+ event_type="integration.action",
+ title=result.block_name,
+ provider=result.provider,
+ object_id=result.block_id,
+ )
+
async def _execute(
self,
user_id: str | None,
diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
index b82091aebd..88166a7dd3 100644
--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py
@@ -35,6 +35,7 @@ from apscheduler.triggers.cron import CronTrigger
from backend.copilot.model import ChatSession, get_chat_session
from backend.copilot.tools.session_context import is_followups_feature_enabled
from backend.copilot.tracking import track_followup_scheduled
+from backend.data.activity_event import ActivityEventDraft
from backend.data.db_accessors import user_db
from backend.util.clients import get_scheduler_client
from backend.util.timezone_utils import get_user_timezone_or_utc
@@ -143,6 +144,27 @@ class ScheduleFollowupTool(BaseTool):
"required": ["message"],
}
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, ScheduleCreatedResponse):
+ return None
+ message: str = kwargs.get("message") or ""
+ return ActivityEventDraft(
+ category="SCHEDULE",
+ event_type="schedule.created",
+ title=kwargs.get("name") or message[:80] or "Follow-up",
+ schedule_id=result.schedule_id,
+ data={
+ "cron": kwargs.get("cron"),
+ "next_run_time": result.next_run_time,
+ "is_recurring": result.is_recurring,
+ },
+ )
+
async def _execute(
self,
user_id: str | None,
diff --git a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
index 722369c91c..91aa4d0cac 100644
--- a/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
+++ b/autogpt_platform/backend/backend/copilot/tools/workspace_files.py
@@ -19,6 +19,7 @@ from backend.copilot.context import (
)
from backend.copilot.model import ChatSession
from backend.copilot.tools.sandbox import make_session_path
+from backend.data.activity_event import ActivityEventDraft
from backend.util.settings import Config
from backend.util.workspace import WorkspaceManager
@@ -817,6 +818,26 @@ class WriteWorkspaceFileTool(BaseTool):
def requires_auth(self) -> bool:
return True
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, WorkspaceWriteResponse):
+ return None
+ return ActivityEventDraft(
+ category="FILE",
+ event_type="file.updated" if kwargs.get("overwrite") else "file.created",
+ title=result.name,
+ object_id=result.file_id,
+ data={
+ "path": result.path,
+ "mime_type": result.mime_type,
+ "size_bytes": result.size_bytes,
+ },
+ )
+
async def _execute(
self,
user_id: str | None,
@@ -1006,6 +1027,21 @@ class DeleteWorkspaceFileTool(BaseTool):
def requires_auth(self) -> bool:
return True
+ def activity_event(
+ self,
+ session: ChatSession,
+ result: ToolResponseBase,
+ **kwargs,
+ ) -> ActivityEventDraft | None:
+ if not isinstance(result, WorkspaceDeleteResponse) or not result.success:
+ return None
+ return ActivityEventDraft(
+ category="FILE",
+ event_type="file.deleted",
+ title=kwargs.get("path") or "Workspace file",
+ object_id=result.file_id,
+ )
+
async def _execute(
self,
user_id: str | None,
diff --git a/autogpt_platform/backend/backend/data/activity_event.py b/autogpt_platform/backend/backend/data/activity_event.py
new file mode 100644
index 0000000000..919a381823
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/activity_event.py
@@ -0,0 +1,108 @@
+"""Append-only log of work agents performed on the user's behalf.
+
+Written best-effort from the copilot tool layer and the graph executor,
+read by the Home "Recent work" feed. Emitters must swallow their own
+failures — recording the work can never be allowed to break the work.
+"""
+
+import enum
+from datetime import datetime
+from typing import Any, Literal, cast
+
+import prisma.models
+from pydantic import BaseModel, Field
+
+from backend.util.json import SafeJson
+
+ActivityEventCategory = Literal["FILE", "INTEGRATION", "RUN", "SCHEDULE"]
+
+
+class ActivityEventDraft(BaseModel):
+ """What an emitter knows at the moment the work happens.
+
+ Ownership (user id) and creation time are stamped by the write, not the
+ emitter. Attribution fields are optional so one shape serves copilot
+ tools (session + expert) and the executor (graph + node) alike.
+ """
+
+ category: ActivityEventCategory
+ event_type: str
+ title: str
+ organization_id: str | None = None
+ expert_id: str | None = None
+ session_id: str | None = None
+ graph_exec_id: str | None = None
+ node_exec_id: str | None = None
+ schedule_id: str | None = None
+ provider: str | None = None
+ object_id: str | None = None
+ data: dict[str, Any] = Field(default_factory=dict)
+
+
+class ActivityEvent(ActivityEventDraft):
+ id: str
+ user_id: str
+ created_at: datetime
+
+ @classmethod
+ def from_db(cls, row: prisma.models.ActivityEvent) -> "ActivityEvent":
+ # Depending on client generation settings the enum column comes back
+ # as a real enum locally but a plain string in the service process.
+ raw_category = row.category
+ if isinstance(raw_category, enum.Enum):
+ raw_category = raw_category.value
+ return cls(
+ id=row.id,
+ user_id=row.userId,
+ created_at=row.createdAt,
+ organization_id=row.organizationId,
+ expert_id=row.expertId,
+ session_id=row.sessionId,
+ graph_exec_id=row.graphExecId,
+ node_exec_id=row.nodeExecId,
+ schedule_id=row.scheduleId,
+ category=cast(ActivityEventCategory, raw_category),
+ event_type=row.eventType,
+ provider=row.provider,
+ object_id=row.objectId,
+ title=row.title,
+ data=dict(row.data) if row.data else {},
+ )
+
+
+async def create_activity_event(
+ user_id: str, draft: ActivityEventDraft
+) -> ActivityEvent:
+ row = await prisma.models.ActivityEvent.prisma().create(
+ data={
+ "userId": user_id,
+ "organizationId": draft.organization_id,
+ "expertId": draft.expert_id,
+ "sessionId": draft.session_id,
+ "graphExecId": draft.graph_exec_id,
+ "nodeExecId": draft.node_exec_id,
+ "scheduleId": draft.schedule_id,
+ "category": draft.category,
+ "eventType": draft.event_type,
+ "provider": draft.provider,
+ "objectId": draft.object_id,
+ "title": draft.title,
+ "data": SafeJson(draft.data),
+ }
+ )
+ return ActivityEvent.from_db(row)
+
+
+async def list_activity_events(
+ user_id: str,
+ since: datetime,
+ categories: list[ActivityEventCategory] | None = None,
+ limit: int = 200,
+) -> list[ActivityEvent]:
+ where: dict[str, Any] = {"userId": user_id, "createdAt": {"gte": since}}
+ if categories:
+ where["category"] = {"in": categories}
+ rows = await prisma.models.ActivityEvent.prisma().find_many(
+ where=where, order={"createdAt": "desc"}, take=limit
+ )
+ return [ActivityEvent.from_db(row) for row in rows]
diff --git a/autogpt_platform/backend/backend/data/activity_event_backfill.py b/autogpt_platform/backend/backend/data/activity_event_backfill.py
new file mode 100644
index 0000000000..d1ba244ce5
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/activity_event_backfill.py
@@ -0,0 +1,136 @@
+"""One-off backfill: seed file activity events from existing workspace files.
+
+Agent-created workspace files predate the activity-event log, so without
+this the Home "Recent work" feed starts empty even for users whose agents
+have been producing files for weeks. Derives a ``file.created`` event per
+live agent-created file, stamped with the file's own creation time.
+
+Safe to re-run: files that already have a FILE event are skipped.
+
+Run with:
+ poetry run python -m backend.data.activity_event_backfill [--dry-run]
+"""
+
+import argparse
+import asyncio
+import logging
+import re
+
+import prisma.models
+import prisma.types
+
+from backend.data import db
+from backend.util.json import SafeJson
+
+logger = logging.getLogger(__name__)
+
+_BATCH_SIZE = 500
+_SESSION_PATH = re.compile(r"^/sessions/([^/]+)/")
+
+
+async def backfill_file_events(dry_run: bool = False) -> int:
+ created_total = 0
+ skip = 0
+ while True:
+ files = await prisma.models.UserWorkspaceFile.prisma().find_many(
+ where={"isDeleted": False},
+ include={"Workspace": True},
+ # id as tiebreaker: createdAt is not unique, and skip-based pages
+ # over a non-deterministic order can drop rows on the boundary.
+ order=[{"createdAt": "asc"}, {"id": "asc"}],
+ take=_BATCH_SIZE,
+ skip=skip,
+ )
+ if not files:
+ return created_total
+ skip += len(files)
+ created_total += await _backfill_batch(files, dry_run=dry_run)
+
+
+async def _backfill_batch(
+ files: list[prisma.models.UserWorkspaceFile], dry_run: bool
+) -> int:
+ agent_files = [
+ file
+ for file in files
+ if file.Workspace and dict(file.metadata or {}).get("origin") == "agent-created"
+ ]
+ if not agent_files:
+ return 0
+
+ existing = await prisma.models.ActivityEvent.prisma().find_many(
+ where={"category": "FILE", "objectId": {"in": [f.id for f in agent_files]}}
+ )
+ seen_file_ids = {event.objectId for event in existing}
+
+ session_ids = [
+ match.group(1)
+ for file in agent_files
+ if (match := _SESSION_PATH.match(file.path))
+ ]
+ sessions = await prisma.models.ChatSession.prisma().find_many(
+ where={"id": {"in": session_ids}}
+ )
+ session_by_id = {session.id: session for session in sessions}
+
+ rows: list[prisma.types.ActivityEventCreateWithoutRelationsInput] = []
+ for file in agent_files:
+ if file.id in seen_file_ids or not file.Workspace:
+ continue
+ match = _SESSION_PATH.match(file.path)
+ session = session_by_id.get(match.group(1)) if match else None
+ if session and session.userId != file.Workspace.userId:
+ session = None
+ rows.append(
+ {
+ "createdAt": file.createdAt,
+ "userId": file.Workspace.userId,
+ "organizationId": session.organizationId if session else None,
+ "expertId": session.expertId if session else None,
+ "sessionId": session.id if session else None,
+ "category": "FILE",
+ "eventType": "file.created",
+ "objectId": file.id,
+ "title": file.name,
+ "data": SafeJson(
+ {
+ "path": file.path,
+ "mime_type": file.mimeType,
+ "size_bytes": int(file.sizeBytes),
+ "backfilled": True,
+ }
+ ),
+ }
+ )
+
+ if dry_run:
+ for row in rows:
+ logger.info(
+ "Would create event for file %s (%s)", row["title"], row["userId"]
+ )
+ return len(rows)
+ if rows:
+ await prisma.models.ActivityEvent.prisma().create_many(data=rows)
+ return len(rows)
+
+
+async def _main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--dry-run", action="store_true")
+ args = parser.parse_args()
+
+ logging.basicConfig(level=logging.INFO)
+ await db.connect()
+ try:
+ count = await backfill_file_events(dry_run=args.dry_run)
+ logger.info(
+ "%s %d file event(s)",
+ "Would backfill" if args.dry_run else "Backfilled",
+ count,
+ )
+ finally:
+ await db.disconnect()
+
+
+if __name__ == "__main__":
+ asyncio.run(_main())
diff --git a/autogpt_platform/backend/backend/data/db_accessors.py b/autogpt_platform/backend/backend/data/db_accessors.py
index 7dd6dc4476..e64685e351 100644
--- a/autogpt_platform/backend/backend/data/db_accessors.py
+++ b/autogpt_platform/backend/backend/data/db_accessors.py
@@ -183,6 +183,19 @@ def platform_cost_db():
return platform_cost_db
+def activity_event_db():
+ if db.is_connected():
+ from backend.data import activity_event as _activity_event_db
+
+ activity_event_db = _activity_event_db
+ else:
+ from backend.util.clients import get_database_manager_async_client
+
+ activity_event_db = get_database_manager_async_client()
+
+ return activity_event_db
+
+
def orgs_db():
if db.is_connected():
from backend.api.features.orgs import db as _orgs_db
diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.py
index 4a980211d1..e10927bf54 100644
--- a/autogpt_platform/backend/backend/data/db_manager.py
+++ b/autogpt_platform/backend/backend/data/db_manager.py
@@ -53,6 +53,7 @@ from backend.copilot.sharing.db import link_new_execution_to_chat_share
from backend.data import bot_analytics as bot_analytics_db
from backend.data import bot_installs as bot_installs_db
from backend.data import db
+from backend.data.activity_event import create_activity_event
from backend.data.alerts import (
count_alerts_sent_since,
get_briefing_alert_conditions,
@@ -452,6 +453,9 @@ class DatabaseManager(AppService):
# ============ Platform Cost Tracking ============ #
log_platform_cost = _(log_platform_cost)
+ # ============ Activity Events ============ #
+ create_activity_event = _(create_activity_event)
+
# ============ Push Notifications ============ #
get_user_push_subscriptions = _(get_user_push_subscriptions)
delete_push_subscription = _(delete_push_subscription)
@@ -650,6 +654,9 @@ 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)
+ # Activity events (executor completion hook)
+ create_activity_event = _(d.create_activity_event)
+
# Morning briefing (scheduler cron; runs Prisma-less)
append_plain_session_message = _(d.append_plain_session_message)
create_briefing = _(d.create_briefing)
@@ -841,6 +848,9 @@ class DatabaseManagerAsyncClient(AppServiceClient):
# ============ Platform Cost Tracking ============ #
log_platform_cost = d.log_platform_cost
+ # ============ Activity Events ============ #
+ create_activity_event = d.create_activity_event
+
# ============ Push Notifications ============ #
get_user_push_subscriptions = d.get_user_push_subscriptions
delete_push_subscription = d.delete_push_subscription
diff --git a/autogpt_platform/backend/backend/executor/activity_events.py b/autogpt_platform/backend/backend/executor/activity_events.py
new file mode 100644
index 0000000000..257fe18bbb
--- /dev/null
+++ b/autogpt_platform/backend/backend/executor/activity_events.py
@@ -0,0 +1,98 @@
+"""Best-effort activity-event emission from the graph executor.
+
+The executor runs Prisma-less, so writes go through the DatabaseManager
+RPC clients, mirroring cost_tracking. Every helper swallows its own
+failures: recording the work must never disrupt the execution that
+produced it.
+"""
+
+import logging
+from typing import TYPE_CHECKING, cast
+
+from backend.blocks._base import Block, BlockSchema
+from backend.data.activity_event import ActivityEventDraft
+from backend.data.execution import (
+ ExecutionStatus,
+ GraphExecutionEntry,
+ GraphExecutionMeta,
+ NodeExecutionEntry,
+)
+from backend.data.model import GraphExecutionStats
+
+if TYPE_CHECKING:
+ from backend.data.db_manager import (
+ DatabaseManagerAsyncClient,
+ DatabaseManagerClient,
+ )
+
+logger = logging.getLogger(__name__)
+
+
+async def log_node_integration_activity(
+ node_exec: NodeExecutionEntry,
+ block: Block,
+ db_client: "DatabaseManagerAsyncClient",
+) -> None:
+ """Record one integration.action per credentialed field of a completed node."""
+ try:
+ if node_exec.execution_context.dry_run:
+ return
+ input_model = cast(type[BlockSchema], block.input_schema)
+ for field_name in input_model.get_credentials_fields():
+ cred_data = node_exec.inputs.get(field_name)
+ if not cred_data or not isinstance(cred_data, dict):
+ continue
+ provider = cred_data.get("provider")
+ if not cred_data.get("id") or not provider:
+ continue
+ await db_client.create_activity_event(
+ user_id=node_exec.user_id,
+ draft=ActivityEventDraft(
+ category="INTEGRATION",
+ event_type="integration.action",
+ title=block.name,
+ provider=provider,
+ graph_exec_id=node_exec.graph_exec_id,
+ node_exec_id=node_exec.node_exec_id,
+ object_id=node_exec.block_id,
+ ),
+ )
+ except Exception:
+ logger.warning(
+ "Failed to log integration activity for node execution %s",
+ node_exec.node_exec_id,
+ exc_info=True,
+ )
+
+
+def handle_run_completed(
+ db_client: "DatabaseManagerClient",
+ graph_exec: GraphExecutionEntry,
+ exec_meta: GraphExecutionMeta,
+ exec_stats: GraphExecutionStats,
+) -> None:
+ """Record the run's terminal event, carrying the AI summary when present."""
+ try:
+ if exec_meta.status not in (ExecutionStatus.COMPLETED, ExecutionStatus.FAILED):
+ return
+ if exec_stats.is_dry_run:
+ return
+ completed = exec_meta.status == ExecutionStatus.COMPLETED
+ fallback = "Run finished" if completed else "Run failed"
+ db_client.create_activity_event(
+ user_id=graph_exec.user_id,
+ draft=ActivityEventDraft(
+ category="RUN",
+ event_type="run.completed" if completed else "run.failed",
+ title=exec_stats.activity_status or fallback,
+ expert_id=exec_meta.expert_id,
+ graph_exec_id=graph_exec.graph_exec_id,
+ data={"graph_id": graph_exec.graph_id},
+ ),
+ )
+ except Exception:
+ logger.warning(
+ "Failed to log run completion for %s",
+ graph_exec.graph_exec_id,
+ exc_info=True,
+ )
diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.py
index 0680749f2a..1879d15507 100644
--- a/autogpt_platform/backend/backend/executor/manager.py
+++ b/autogpt_platform/backend/backend/executor/manager.py
@@ -82,7 +82,7 @@ from backend.util.retry import (
)
from backend.util.settings import Settings
-from . import billing, expert_posts
+from . import activity_events, billing, expert_posts
from .activity_status_generator import (
INSUFFICIENT_BALANCE_GUIDANCE,
generate_activity_status_for_execution,
@@ -782,6 +782,12 @@ class ExecutionProcessor:
stats=execution_stats,
db_client=db_client,
)
+ if status == ExecutionStatus.COMPLETED:
+ await activity_events.log_node_integration_activity(
+ node_exec=node_exec,
+ block=node.block,
+ db_client=db_client,
+ )
if not node_exec.execution_context.dry_run:
reconciled_delta, _ = await billing.charge_reconciled_usage(
node_exec=node_exec,
@@ -1076,6 +1082,9 @@ class ExecutionProcessor:
expert_posts.handle_expert_run_post(
db_client, graph_exec, exec_meta.status, exec_stats
)
+ activity_events.handle_run_completed(
+ db_client, graph_exec, exec_meta, exec_stats
+ )
update_graph_execution_state(
db_client=db_client,
diff --git a/autogpt_platform/backend/migrations/20260828120000_add_activity_event/migration.sql b/autogpt_platform/backend/migrations/20260828120000_add_activity_event/migration.sql
new file mode 100644
index 0000000000..e2ea9a0754
--- /dev/null
+++ b/autogpt_platform/backend/migrations/20260828120000_add_activity_event/migration.sql
@@ -0,0 +1,38 @@
+-- CreateEnum
+CREATE TYPE "ActivityEventCategory" AS ENUM ('FILE', 'INTEGRATION', 'RUN', 'SCHEDULE');
+
+-- CreateTable
+CREATE TABLE "ActivityEvent" (
+ "id" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "userId" TEXT NOT NULL,
+ "organizationId" TEXT,
+ "expertId" TEXT,
+ "sessionId" TEXT,
+ "graphExecId" TEXT,
+ "nodeExecId" TEXT,
+ "scheduleId" TEXT,
+ "category" "ActivityEventCategory" NOT NULL,
+ "eventType" TEXT NOT NULL,
+ "provider" TEXT,
+ "objectId" TEXT,
+ "title" TEXT NOT NULL,
+ "data" JSONB NOT NULL DEFAULT '{}',
+
+ CONSTRAINT "ActivityEvent_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "ActivityEvent_userId_createdAt_idx" ON "ActivityEvent"("userId", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "ActivityEvent_userId_category_createdAt_idx" ON "ActivityEvent"("userId", "category", "createdAt");
+
+-- CreateIndex
+CREATE INDEX "ActivityEvent_sessionId_idx" ON "ActivityEvent"("sessionId");
+
+-- CreateIndex
+CREATE INDEX "ActivityEvent_expertId_createdAt_idx" ON "ActivityEvent"("expertId", "createdAt");
+
+-- AddForeignKey
+ALTER TABLE "ActivityEvent" ADD CONSTRAINT "ActivityEvent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prisma
index 1858f7187f..4edd84e83c 100644
--- a/autogpt_platform/backend/schema.prisma
+++ b/autogpt_platform/backend/schema.prisma
@@ -141,6 +141,7 @@ model User {
UserBalance UserBalance?
ChatSessions ChatSession[]
UserBriefings UserBriefing[]
+ ActivityEvents ActivityEvent[]
AgentPresets AgentPreset[]
LibraryAgents LibraryAgent[]
LibraryFolders LibraryFolder[]
@@ -318,6 +319,46 @@ model UserBriefing {
@@unique([userId, briefingDate])
}
+enum ActivityEventCategory {
+ FILE
+ INTEGRATION
+ RUN
+ SCHEDULE
+}
+
+// Append-only audit log of work agents performed on the user's behalf:
+// side-effecting copilot tool calls, credentialed block executions, and
+// run completions. Powers the Home "Recent work" feed.
+model ActivityEvent {
+ id String @id @default(uuid())
+ createdAt DateTime @default(now())
+
+ userId String
+ User User @relation(fields: [userId], references: [id], onDelete: Cascade)
+
+ organizationId String?
+
+ // Soft references on purpose: events must outlive the expert, session or
+ // schedule that produced them, so attribution falls back to `data`.
+ expertId String?
+ sessionId String?
+ graphExecId String?
+ nodeExecId String?
+ scheduleId String?
+
+ category ActivityEventCategory
+ eventType String
+ provider String?
+ objectId String?
+ title String
+ data Json @default("{}")
+
+ @@index([userId, createdAt])
+ @@index([userId, category, createdAt])
+ @@index([sessionId])
+ @@index([expertId, createdAt])
+}
+
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//////////////// USER WORKSPACE TABLES /////////////////
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/__tests__/recent-work.test.tsx b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/recent-work.test.tsx
new file mode 100644
index 0000000000..5b1d19a93f
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/home/__tests__/recent-work.test.tsx
@@ -0,0 +1,184 @@
+import { http, HttpResponse } from "msw";
+import { expect, test, vi } from "vitest";
+import type { HomeDashboardResponse } from "@/app/api/__generated__/models/homeDashboardResponse";
+import type { HomeRecentWork } from "@/app/api/__generated__/models/homeRecentWork";
+import { server } from "@/mocks/mock-server";
+import { render, screen } from "@/tests/integrations/test-utils";
+import HomePage from "../page";
+
+vi.mock("@/services/feature-flags/use-get-flag", async (importActual) => {
+ const actual =
+ await importActual<
+ typeof import("@/services/feature-flags/use-get-flag")
+ >();
+ return {
+ ...actual,
+ useFlagStatus: (flag: string) =>
+ flag === "hire-experts"
+ ? { enabled: true, ready: true }
+ : actual.useFlagStatus(flag as never),
+ useGetFlag: (flag: string) => flag === actual.Flag.HIRE_EXPERTS,
+ };
+});
+
+vi.mock("@/lib/auth/hooks/useAuth", () => ({
+ useAuth: () => ({
+ user: { user_metadata: { preferred_name: "Ubbe" } },
+ }),
+}));
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ push: vi.fn() }),
+ usePathname: () => "/home",
+ useSearchParams: () => new URLSearchParams(),
+ useParams: () => ({}),
+ notFound: () => {
+ throw new Error("NEXT_NOT_FOUND");
+ },
+}));
+
+const NOW = new Date("2026-08-28T09:00:00Z");
+const maria = {
+ id: "maria",
+ name: "Maria",
+ role: "Marketing",
+ avatar_url: null,
+};
+
+const recentWork: HomeRecentWork = {
+ total_count: 10,
+ groups: [
+ {
+ actor: { kind: "expert", name: "Maria", expert: maria },
+ session_id: "session-1",
+ session_title: "Blog pipeline",
+ link: "/copilot?sessionId=session-1",
+ latest_at: NOW,
+ items: [
+ {
+ id: "event-1",
+ category: "file",
+ event_type: "file.created",
+ title: "2026-08-28-code-review-metrics.md",
+ occurred_at: NOW,
+ file_id: "file-1",
+ mime_type: "text/markdown",
+ },
+ {
+ id: "event-2",
+ category: "schedule",
+ event_type: "schedule.created",
+ title: "persian.sh blog draft",
+ occurred_at: NOW,
+ },
+ ],
+ more_count: 6,
+ },
+ {
+ actor: { kind: "autopilot", name: "Autopilot" },
+ session_id: "session-2",
+ latest_at: NOW,
+ items: [
+ {
+ id: "event-3",
+ category: "integration",
+ event_type: "integration.action",
+ title: "Send Email",
+ occurred_at: NOW,
+ provider: "google",
+ },
+ ],
+ more_count: 0,
+ },
+ ],
+};
+
+const dashboard: HomeDashboardResponse = {
+ generated_at: NOW,
+ timezone: "UTC",
+ attention: [],
+ briefing: {
+ generated_at: NOW,
+ window_started_at: NOW,
+ completed_count: 0,
+ failed_count: 0,
+ routine_count: 0,
+ outcomes: [],
+ },
+ active_tasks: [],
+ upcoming_tasks: [],
+ team: { total: 1, ready: 1, working: 0, needs_attention: 0 },
+ agents: [],
+ week: {
+ run_count: 0,
+ completed_count: 0,
+ review_count: 0,
+ failed_count: 0,
+ total_runtime_seconds: 0,
+ timed_run_count: 0,
+ total_cost_cents: 0,
+ credits_balance: 0,
+ daily: [],
+ },
+ recent_work: recentWork,
+};
+
+function mockDashboard(response: HomeDashboardResponse) {
+ server.use(
+ http.get(/\/api\/proxy\/api\/home(?:\?.*)?$/, () =>
+ HttpResponse.json(response),
+ ),
+ );
+}
+
+test("shows agent work grouped by actor and thread", async () => {
+ mockDashboard(dashboard);
+
+ render(<HomePage />);
+
+ expect(
+ await screen.findByRole("heading", { name: "Recent work" }),
+ ).toBeDefined();
+ expect(screen.getByText("Maria")).toBeDefined();
+ expect(screen.getByText("Blog pipeline")).toBeDefined();
+ expect(screen.getByText("2026-08-28-code-review-metrics.md")).toBeDefined();
+ expect(screen.getByText("persian.sh blog draft")).toBeDefined();
+ expect(screen.getByText("Plus 6 more")).toBeDefined();
+ expect(screen.getByText("Autopilot")).toBeDefined();
+ expect(screen.getByText("Send Email")).toBeDefined();
+ expect(screen.getByText(/google/)).toBeDefined();
+});
+
+test("links a thread-backed group to its copilot session", async () => {
+ mockDashboard(dashboard);
+
+ render(<HomePage />);
+
+ await screen.findByRole("heading", { name: "Recent work" });
+ const links = screen
+ .getAllByRole("link")
+ .map((link) => link.getAttribute("href"));
+ expect(links).toContain("/copilot?sessionId=session-1");
+});
+
+test("shows a calm empty state when agents produced nothing yet", async () => {
+ mockDashboard({
+ ...dashboard,
+ recent_work: { groups: [], total_count: 0 },
+ });
+
+ render(<HomePage />);
+
+ expect(await screen.findByText("No work delivered yet")).toBeDefined();
+});
+
+test("renders the rest of the page when recent_work is absent", async () => {
+ const { recent_work, ...withoutRecentWork } = dashboard;
+ void recent_work;
+ mockDashboard(withoutRecentWork as HomeDashboardResponse);
+
+ render(<HomePage />);
+
+ expect(await screen.findByText("No work delivered yet")).toBeDefined();
+ expect(screen.getByRole("heading", { name: "Your briefing" })).toBeDefined();
+});
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/RecentWork.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/RecentWork.tsx
new file mode 100644
index 0000000000..aa2172b079
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/RecentWork.tsx
@@ -0,0 +1,62 @@
+"use client";
+
+import { WorkHistoryIcon } from "@hugeicons/core-free-icons";
+import type { HomeDashboardResponse } from "@/app/api/__generated__/models/homeDashboardResponse";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { HomeTile } from "../HomeTile/HomeTile";
+import { HomeTileEmpty } from "../HomeTileEmpty/HomeTileEmpty";
+import { WorkGroup } from "./components/WorkGroup";
+
+interface Props {
+ dashboard: HomeDashboardResponse;
+ className?: string;
+}
+
+export function RecentWork({ dashboard, className }: Props) {
+ const groups = dashboard.recent_work?.groups ?? [];
+
+ return (
+ <HomeTile
+ className={className}
+ contentClassName="flex flex-col"
+ surfaceClassName="py-4 sm:py-4"
+ title={
+ <div className="flex min-w-0 items-center gap-2">
+ <Icon
+ icon={WorkHistoryIcon}
+ size={18}
+ className="text-zinc-500"
+ aria-hidden="true"
+ />
+ <Text variant="h5" className="text-zinc-950">
+ Recent work
+ </Text>
+ </div>
+ }
+ header={
+ <Text variant="large" className="text-zinc-600">
+ What your agents produced this week.
+ </Text>
+ }
+ >
+ {groups.length === 0 ? (
+ <HomeTileEmpty
+ icon={WorkHistoryIcon}
+ title="No work delivered yet"
+ description="Files your agents write, integrations they use and schedules they set up will appear here."
+ />
+ ) : (
+ <div className="-mx-4 divide-y divide-zinc-100 sm:-mx-5">
+ {groups.map((group) => (
+ <WorkGroup
+ key={group.items[0]?.id ?? group.actor.name}
+ group={group}
+ timezone={dashboard.timezone}
+ />
+ ))}
+ </div>
+ )}
+ </HomeTile>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/components/WorkGroup.tsx b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/components/WorkGroup.tsx
new file mode 100644
index 0000000000..7da315db07
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/components/WorkGroup.tsx
@@ -0,0 +1,93 @@
+import { ArrowUpRight01Icon, Robot01Icon } from "@hugeicons/core-free-icons";
+import Link from "next/link";
+import type { HomeRecentWorkGroup } from "@/app/api/__generated__/models/homeRecentWorkGroup";
+import { Icon } from "@/components/atoms/Icon/Icon";
+import { Text } from "@/components/atoms/Text/Text";
+import { ExpertAvatar } from "@/components/molecules/ExpertAvatar/ExpertAvatar";
+import { formatWorkTime, getWorkItemIcon } from "../helpers";
+
+interface Props {
+ group: HomeRecentWorkGroup;
+ timezone: string;
+}
+
+export function WorkGroup({ group, timezone }: Props) {
+ const header = (
+ <div className="flex min-w-0 items-center gap-2">
+ {group.actor.expert ? (
+ <ExpertAvatar
+ name={group.actor.expert.name}
+ avatarUrl={group.actor.expert.avatar_url}
+ size={22}
+ />
+ ) : (
+ <span className="flex size-[22px] shrink-0 items-center justify-center rounded-full bg-zinc-100 text-zinc-500">
+ <Icon icon={Robot01Icon} size={13} aria-hidden="true" />
+ </span>
+ )}
+ <Text variant="body-medium" className="truncate text-zinc-950">
+ {group.actor.name}
+ </Text>
+ {group.session_title ? (
+ <>
+ <span className="text-zinc-300" aria-hidden="true">
+ ·
+ </span>
+ <Text variant="body" className="truncate text-zinc-500">
+ {group.session_title}
+ </Text>
+ </>
+ ) : null}
+ {group.link ? (
+ <Icon
+ icon={ArrowUpRight01Icon}
+ size={15}
+ className="ml-auto shrink-0 text-zinc-300 transition-colors group-hover:text-zinc-700"
+ aria-hidden="true"
+ />
+ ) : null}
+ </div>
+ );
+
+ return (
+ <article className="px-4 py-3 sm:px-5">
+ {group.link ? (
+ <Link
+ href={group.link}
+ className="group block outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-zinc-400"
+ >
+ {header}
+ </Link>
+ ) : (
+ header
+ )}
+ <div className="mt-2 flex flex-col gap-1.5">
+ {group.items.map((item) => (
+ <div key={item.id} className="flex items-start gap-2.5">
+ <span className="mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-md bg-zinc-100 text-zinc-500">
+ <Icon
+ icon={getWorkItemIcon(item.category)}
+ size={13}
+ aria-hidden="true"
+ />
+ </span>
+ <div className="min-w-0 flex-1">
+ <Text variant="body" className="truncate text-zinc-800">
+ {item.title}
+ </Text>
+ </div>
+ <span className="shrink-0 text-xs tabular-nums text-zinc-400">
+ {item.provider ? `${item.provider} · ` : ""}
+ {formatWorkTime(item.occurred_at, timezone)}
+ </span>
+ </div>
+ ))}
+ {group.more_count ? (
+ <Text variant="small" className="pl-[34px] text-zinc-400">
+ Plus {group.more_count} more
+ </Text>
+ ) : null}
+ </div>
+ </article>
+ );
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/helpers.ts b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/helpers.ts
new file mode 100644
index 0000000000..712e7ed9bf
--- /dev/null
+++ b/autogpt_platform/frontend/src/app/(platform)/home/components/RecentWork/helpers.ts
@@ -0,0 +1,26 @@
+import { File01Icon, PlugIcon, RepeatIcon } from "@hugeicons/core-free-icons";
+import type { IconSvgElement } from "@hugeicons/react";
+import type { HomeRecentWorkItemCategory } from "@/app/api/__generated__/models/homeRecentWorkItemCategory";
+
+export function getWorkItemIcon(
+ category: HomeRecentWorkItemCategory,
+): IconSvgElement {
+ if (category === "integration") return PlugIcon;
+ if (category === "schedule") return RepeatIcon;
+ return File01Icon;
+}
+
+// The feed spans up to a week, so unlike the briefing's time-only stamps the
+// weekday is load-bearing: "Mon 10:45" vs three files all labelled "10:45".
+export function formatWorkTime(
+ value: Date,
+ timeZone: string,
+ locale?: string,
+): string {
+ return new Intl.DateTimeFormat(locale, {
+ timeZone,
+ weekday: "short",
+ hour: "numeric",
+ minute: "2-digit",
+ }).format(new Date(value));
+}
diff --git a/autogpt_platform/frontend/src/app/(platform)/home/page.tsx b/autogpt_platform/frontend/src/app/(platform)/home/page.tsx
index 4b2e438afa..047f28098a 100644
--- a/autogpt_platform/frontend/src/app/(platform)/home/page.tsx
+++ b/autogpt_platform/frontend/src/app/(platform)/home/page.tsx
@@ -11,6 +11,7 @@ import { HomeHeader } from "./components/HomeHeader/HomeHeader";
import { MorningBriefing } from "./components/MorningBriefing/MorningBriefing";
import { NeedsYou } from "./components/NeedsYou/NeedsYou";
import { NowNext } from "./components/NowNext/NowNext";
+import { RecentWork } from "./components/RecentWork/RecentWork";
import { getTimeOfDayGreeting } from "./helpers";
import { useHomePage } from "./useHomePage";
@@ -57,6 +58,7 @@ export default function HomePage() {
<div className="flex min-w-0 flex-col gap-7 xl:col-span-8">
<NeedsYou dashboard={dashboard} />
<MorningBriefing dashboard={dashboard} />
+ <RecentWork dashboard={dashboard} />
</div>
<div className="flex min-w-0 flex-col gap-7 xl:col-span-4">
<AgentTeam dashboard={dashboard} />
diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.json
index b2da12afc0..0902ac1c96 100644
--- a/autogpt_platform/frontend/src/app/api/openapi.json
+++ b/autogpt_platform/frontend/src/app/api/openapi.json
@@ -20933,7 +20933,8 @@
"type": "array",
"title": "Agents"
},
- "week": { "$ref": "#/components/schemas/HomeWeekSummary" }
+ "week": { "$ref": "#/components/schemas/HomeWeekSummary" },
+ "recent_work": { "$ref": "#/components/schemas/HomeRecentWork" }
},
"type": "object",
"required": [
@@ -20963,6 +20964,89 @@
"required": ["id", "name", "role", "avatar_url"],
"title": "HomeExpert"
},
+ "HomeRecentWork": {
+ "properties": {
+ "groups": {
+ "items": { "$ref": "#/components/schemas/HomeRecentWorkGroup" },
+ "type": "array",
+ "title": "Groups"
+ },
+ "total_count": {
+ "type": "integer",
+ "title": "Total Count",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "title": "HomeRecentWork"
+ },
+ "HomeRecentWorkGroup": {
+ "properties": {
+ "actor": { "$ref": "#/components/schemas/HomeWorkActor" },
+ "session_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Id"
+ },
+ "session_title": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Session Title"
+ },
+ "link": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Link"
+ },
+ "latest_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Latest At"
+ },
+ "items": {
+ "items": { "$ref": "#/components/schemas/HomeRecentWorkItem" },
+ "type": "array",
+ "title": "Items"
+ },
+ "more_count": {
+ "type": "integer",
+ "title": "More Count",
+ "default": 0
+ }
+ },
+ "type": "object",
+ "required": ["actor", "latest_at", "items"],
+ "title": "HomeRecentWorkGroup"
+ },
+ "HomeRecentWorkItem": {
+ "properties": {
+ "id": { "type": "string", "title": "Id" },
+ "category": {
+ "type": "string",
+ "enum": ["file", "integration", "schedule"],
+ "title": "Category"
+ },
+ "event_type": { "type": "string", "title": "Event Type" },
+ "title": { "type": "string", "title": "Title" },
+ "occurred_at": {
+ "type": "string",
+ "format": "date-time",
+ "title": "Occurred At"
+ },
+ "provider": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Provider"
+ },
+ "file_id": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "File Id"
+ },
+ "mime_type": {
+ "anyOf": [{ "type": "string" }, { "type": "null" }],
+ "title": "Mime Type"
+ }
+ },
+ "type": "object",
+ "required": ["id", "category", "event_type", "title", "occurred_at"],
+ "title": "HomeRecentWorkItem"
+ },
"HomeTeamSummary": {
"properties": {
"total": { "type": "integer", "title": "Total" },
@@ -21043,6 +21127,25 @@
],
"title": "HomeWeekSummary"
},
+ "HomeWorkActor": {
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": ["expert", "autopilot", "agent"],
+ "title": "Kind"
+ },
+ "name": { "type": "string", "title": "Name" },
+ "expert": {
+ "anyOf": [
+ { "$ref": "#/components/schemas/HomeExpert" },
+ { "type": "null" }
+ ]
+ }
+ },
+ "type": "object",
+ "required": ["kind", "name"],
+ "title": "HomeWorkActor"
+ },
"HostScopedCredentials": {
"properties": {
"id": { "type": "string", "title": "Id" },