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(backend): record how each agent run started and emit activation events (#14286)
Nicholas Tindle32f2d4b2a08b
diff --git a/autogpt_platform/backend/backend/api/external/v1/routes.py b/autogpt_platform/backend/backend/api/external/v1/routes.pyindex 07f86bba21..43166ea582 100644--- a/autogpt_platform/backend/backend/api/external/v1/routes.py+++ b/autogpt_platform/backend/backend/api/external/v1/routes.py@@ -17,9 +17,10 @@ from backend.copilot.rate_limit import UserPaywalledError, enforce_payment_paywafrom backend.data import execution as execution_dbfrom backend.data import graph as graph_dbfrom backend.data import user as user_db+from backend.data.auth.api_key import APIKeyInfofrom backend.data.auth.base import APIAuthorizationInfofrom backend.data.block import BlockInput, CompletedBlockOutput-from backend.data.execution import ExecutionContext+from backend.data.execution import ExecutionContext, ExecutionTriggerfrom backend.executor.utils import (add_graph_execution,charge_for_direct_block_execution,@@ -233,6 +234,8 @@ async def execute_graph(graph_version=graph_version,organization_id=org_id,team_id=team_id,+ trigger=ExecutionTrigger.API,+ trigger_ref=auth.id if isinstance(auth, APIKeyInfo) else auth.type,)return {"id": graph_exec.id}except UserPaywalledError:diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex 4a18a8750a..26d71449e8 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -1773,6 +1773,8 @@ async def stream_chat_post(message_metadata=message_metadata,message_already_persisted=resume_persisted_kickoff,is_user_message=request.is_user_message,+ expert_id=session.expert_id,+ session_origin=session.metadata.origin,context=request.context,voice=request.voice,file_ids=sanitized_file_ids,diff --git a/autogpt_platform/backend/backend/api/features/experts/routes.py b/autogpt_platform/backend/backend/api/features/experts/routes.pyindex edc4b16c49..6e2c4f1ea5 100644--- a/autogpt_platform/backend/backend/api/features/experts/routes.py+++ b/autogpt_platform/backend/backend/api/features/experts/routes.py@@ -32,6 +32,7 @@ from backend.api.features.experts.models import (RaiseResult,validate_avatar_url,)+from backend.util import product_analyticsfrom backend.util.exceptions import NotFoundErrorrouter = APIRouter(@@ -158,7 +159,9 @@ async def hire_expert(user_id: str = Security(autogpt_auth_lib.get_user_id),) -> HireResult:try:- return await experts_db.hire_expert(user_id, request.template_id, request.name)+ result = await experts_db.hire_expert(+ user_id, request.template_id, request.name+ )except experts_db.ExpertTemplateNotFoundError as e:raise fastapi.HTTPException(status_code=404, detail=str(e))except experts_db.ExpertNotFoundError as e:@@ -178,6 +181,13 @@ async def hire_expert(status_code=409,detail={"code": "active_expert_limit", "limit": e.limit},)+ product_analytics.track_expert_hired(+ user_id=user_id,+ expert_id=result.expert.id,+ template_id=request.template_id,+ name=result.expert.name,+ )+ return result@router.post(diff --git a/autogpt_platform/backend/backend/api/features/integrations/router.py b/autogpt_platform/backend/backend/api/features/integrations/router.pyindex cfc9ac04ab..fc70877300 100644--- a/autogpt_platform/backend/backend/api/features/integrations/router.py+++ b/autogpt_platform/backend/backend/api/features/integrations/router.py@@ -22,6 +22,7 @@ from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR, HTTP_502_BAD_GATEWAfrom backend.api.features.library.db import set_preset_webhook, update_presetfrom backend.api.features.library.model import LibraryAgentPresetfrom backend.data.db_accessors import experts_db+from backend.data.execution import ExecutionTriggerfrom backend.data.graph import NodeModel, get_graph, set_node_webhookfrom backend.data.integrations import (WebhookEvent,@@ -75,6 +76,7 @@ from backend.integrations.oauth import (from backend.integrations.oauth.device_base import BaseDeviceAuthHandlerfrom backend.integrations.providers import ProviderName, provider_keyfrom backend.integrations.webhooks import get_webhook_manager+from backend.util import product_analyticsfrom backend.util.exceptions import (ExpertRunPausedError,GraphNotAccessibleError,@@ -412,6 +414,12 @@ async def callback(f"Successfully processed OAuth callback for user {user_id} "f"and provider {provider.value}")+ product_analytics.track_integration_connected(+ user_id=user_id,+ provider=provider.value,+ credential_type=credentials.type,+ method="oauth",+ )return to_meta_response(credentials)@@ -745,6 +753,12 @@ async def device_auth_poll(logger.debug(f"Device auth approved for user {user_id} and provider {provider.value}")+ product_analytics.track_integration_connected(+ user_id=user_id,+ provider=provider.value,+ credential_type=credentials.type,+ method="device_code",+ )return DeviceAuthPollResponse(status="approved",credentials=to_meta_response(credentials),@@ -980,6 +994,12 @@ async def create_credentials(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,detail="Failed to store credentials",)+ product_analytics.track_integration_connected(+ user_id=user_id,+ provider=provider.value,+ credential_type=credentials.type,+ method="manual",+ )return to_meta_response(credentials)@@ -1232,7 +1252,7 @@ async def _execute_webhook_node_trigger(from backend.api.features.orgs.db import get_user_default_teamorg_id, ws_id = await get_user_default_team(webhook.user_id)- await add_graph_execution(+ graph_exec = await add_graph_execution(user_id=webhook.user_id,graph_id=node.graph_id,graph_version=node.graph_version,@@ -1240,6 +1260,14 @@ async def _execute_webhook_node_trigger(organization_id=org_id,team_id=ws_id,webhook_id=webhook_id,+ trigger=ExecutionTrigger.WEBHOOK,+ trigger_ref=webhook_id,+ )+ product_analytics.track_trigger_fired(+ user_id=webhook.user_id,+ webhook_id=webhook_id,+ graph_id=node.graph_id,+ graph_exec_id=graph_exec.id,)except GraphNotInLibraryError as e:logger.warning(@@ -1338,7 +1366,7 @@ async def _execute_webhook_preset_trigger(from backend.api.features.orgs.db import get_user_default_teamorg_id, ws_id = await get_user_default_team(webhook.user_id)- await add_graph_execution(+ graph_exec = await add_graph_execution(user_id=webhook.user_id,graph_id=preset.graph_id,preset_id=preset.id,@@ -1349,6 +1377,16 @@ async def _execute_webhook_preset_trigger(team_id=ws_id,expert_id=preset.expert_id,webhook_id=webhook.id,+ trigger=ExecutionTrigger.WEBHOOK,+ trigger_ref=webhook_id,+ )+ product_analytics.track_trigger_fired(+ user_id=webhook.user_id,+ webhook_id=webhook_id,+ graph_id=preset.graph_id,+ graph_exec_id=graph_exec.id,+ expert_id=preset.expert_id,+ preset_id=preset.id,)except ExpertRunPausedError as e:# Expected steady-state while the expert is paused/over budget —diff --git a/autogpt_platform/backend/backend/api/features/library/routes/presets.py b/autogpt_platform/backend/backend/api/features/library/routes/presets.pyindex 8f0f0ea14b..24d10bc81c 100644--- a/autogpt_platform/backend/backend/api/features/library/routes/presets.py+++ b/autogpt_platform/backend/backend/api/features/library/routes/presets.py@@ -6,7 +6,7 @@ from fastapi import APIRouter, Body, Depends, HTTPException, Query, Security, stfrom backend.api.features.experts import experts_dbfrom backend.copilot.rate_limit import enforce_payment_paywall-from backend.data.execution import GraphExecutionMeta+from backend.data.execution import ExecutionTrigger, GraphExecutionMetafrom backend.data.model import CredentialsMetaInputfrom backend.executor.utils import add_graph_executionfrom backend.util.exceptions import (@@ -335,6 +335,8 @@ async def execute_preset(graph_credentials_inputs=merged_credential_inputs,organization_id=exec_org_id,team_id=exec_team_id,+ trigger=ExecutionTrigger.MANUAL,+ trigger_ref="preset",)except ExpertRunPausedError as e:# A paused/over-budget expert is a user-visible state, not a serverdiff --git a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py b/autogpt_platform/backend/backend/api/features/orgs/regression_test.pyindex 74bdcb5980..61ab7aaaf9 100644--- a/autogpt_platform/backend/backend/api/features/orgs/regression_test.py+++ b/autogpt_platform/backend/backend/api/features/orgs/regression_test.py@@ -93,6 +93,8 @@ def _make_execution_row(m.organizationId = Nonem.teamId = Nonem.expertId = None+ m.triggerSource = None+ m.triggerRef = Nonem.scheduleId = Nonem.webhookId = Nonereturn mdiff --git a/autogpt_platform/backend/backend/api/features/v1.py b/autogpt_platform/backend/backend/api/features/v1.pyindex 393f1cff01..221c84f5b3 100644--- a/autogpt_platform/backend/backend/api/features/v1.py+++ b/autogpt_platform/backend/backend/api/features/v1.py@@ -2162,6 +2162,8 @@ async def execute_graph(dry_run=dry_run,organization_id=ctx.org_id,team_id=ctx.team_id,+ trigger=execution_db.ExecutionTrigger.MANUAL,+ trigger_ref=source,)record_graph_operation(operation="execute", status="success")if source == "library":diff --git a/autogpt_platform/backend/backend/blocks/agent.py b/autogpt_platform/backend/backend/blocks/agent.pyindex cfd345ad3b..6d7fab68db 100644--- a/autogpt_platform/backend/backend/blocks/agent.py+++ b/autogpt_platform/backend/backend/blocks/agent.py@@ -10,7 +10,12 @@ from backend.blocks._base import (BlockSchemaInput,BlockType,)-from backend.data.execution import ExecutionContext, ExecutionStatus, NodesInputMasks+from backend.data.execution import (+ ExecutionContext,+ ExecutionStatus,+ ExecutionTrigger,+ NodesInputMasks,+)from backend.data.model import NodeExecutionStats, SchemaFieldfrom backend.util.json import validate_with_jsonschemafrom backend.util.retry import func_retry@@ -102,6 +107,8 @@ class AgentExecutorBlock(Block):dry_run=execution_context.dry_run,organization_id=execution_context.organization_id,team_id=execution_context.team_id,+ trigger=ExecutionTrigger.SUBGRAPH,+ trigger_ref=graph_exec_id,)logger = execution_utils.LogMetadata(diff --git a/autogpt_platform/backend/backend/copilot/baseline/service.py b/autogpt_platform/backend/backend/copilot/baseline/service.pyindex 69761ac0fb..f71551d9f9 100644--- a/autogpt_platform/backend/backend/copilot/baseline/service.py+++ b/autogpt_platform/backend/backend/copilot/baseline/service.py@@ -1714,6 +1714,9 @@ async def stream_chat_completion_baseline(user_id=user_id,session_id=session_id,message_length=len(message or ""),+ expert_id=session.expert_id,+ origin=session.metadata.origin,+ surface=session.metadata.source_platform,)# Capture count *before* the pending drain so is_first_turn and thediff --git a/autogpt_platform/backend/backend/copilot/executor/utils.py b/autogpt_platform/backend/backend/copilot/executor/utils.pyindex 84856fabf8..0a21ce30b8 100644--- a/autogpt_platform/backend/backend/copilot/executor/utils.py+++ b/autogpt_platform/backend/backend/copilot/executor/utils.py@@ -588,6 +588,8 @@ async def schedule_chat_turn(message_metadata: dict[str, Any] | None = None,message_already_persisted: bool = False,is_user_message: bool = True,+ expert_id: str | None = None,+ session_origin: str | None = None,context: dict[str, str] | None = None,voice: bool = False,file_ids: list[str] | None = None,@@ -658,6 +660,9 @@ async def schedule_chat_turn(user_id=user_id,session_id=session_id,message_length=raw_message_length,+ expert_id=expert_id,+ origin=session_origin,+ surface="chat",)if is_duplicate:diff --git a/autogpt_platform/backend/backend/copilot/sdk/service.py b/autogpt_platform/backend/backend/copilot/sdk/service.pyindex de53fa8e7c..47d39f2d01 100644--- a/autogpt_platform/backend/backend/copilot/sdk/service.py+++ b/autogpt_platform/backend/backend/copilot/sdk/service.py@@ -4573,6 +4573,9 @@ async def stream_chat_completion_sdk( # pyright: ignore[reportGeneralTypeIssuesuser_id=user_id,session_id=session_id,message_length=len(message or ""),+ expert_id=session.expert_id,+ origin=session.metadata.origin,+ surface=session.metadata.source_platform,)# Structured log prefix: [SDK][<session>][T<turn>]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.pyindex 652e1e54ca..8cb86cf1a3 100644--- a/autogpt_platform/backend/backend/copilot/tools/activity_event_hooks_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/activity_event_hooks_test.py@@ -5,10 +5,6 @@ from datetime import UTC, datetimefrom backend.copilot.model import ChatSessionfrom backend.copilot.tools.models import BlockOutputResponse, ErrorResponsefrom 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,@@ -114,28 +110,3 @@ def test_run_block_does_not_report_llm_credential_use() -> None:)assert tool.activity_event(session=session, result=model_call) 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/run_agent.py b/autogpt_platform/backend/backend/copilot/tools/run_agent.pyindex 56a401ef35..fcc48df1e4 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_agent.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_agent.py@@ -12,7 +12,11 @@ from backend.copilot.model import ChatSessionfrom backend.copilot.tool_display import emit_tool_display_namefrom backend.copilot.tracking import track_agent_run_success, track_agent_scheduledfrom backend.data.db_accessors import execution_db, graph_db, library_db, user_db-from backend.data.execution import ExecutionStatus, GraphExecutionWithNodes+from backend.data.execution import (+ ExecutionStatus,+ ExecutionTrigger,+ GraphExecutionWithNodes,+)from backend.data.graph import GraphModelfrom backend.data.model import CredentialsMetaInputfrom backend.executor import utils as execution_utils@@ -920,6 +924,8 @@ class RunAgentTool(BaseTool):team_id=team_id,preset_id=preset_id,expert_id=session.expert_id,+ trigger=ExecutionTrigger.COPILOT,+ trigger_ref=session_id,)except GraphValidationError as e:return self._handle_graph_validation_race(diff --git a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.pyindex f6513db2cb..df717d16c6 100644--- a/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py+++ b/autogpt_platform/backend/backend/copilot/tools/schedule_followup.py@@ -35,7 +35,6 @@ from apscheduler.triggers.cron import CronTriggerfrom backend.copilot.model import ChatSession, get_chat_sessionfrom backend.copilot.tools.session_context import is_followups_feature_enabledfrom backend.copilot.tracking import track_followup_scheduled-from backend.data.activity_event import ActivityEventDraftfrom backend.data.db_accessors import user_dbfrom backend.util.clients import get_scheduler_clientfrom backend.util.timezone_utils import get_user_timezone_or_utc@@ -144,26 +143,8 @@ 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,- },- )+ # The schedule.created activity event is recorded by the scheduler when+ # the job is persisted, so it covers every creation path, not just this tool.async def _execute(self,diff --git a/autogpt_platform/backend/backend/copilot/tracking.py b/autogpt_platform/backend/backend/copilot/tracking.pyindex d50716fe2e..b2710ad864 100644--- a/autogpt_platform/backend/backend/copilot/tracking.py+++ b/autogpt_platform/backend/backend/copilot/tracking.py@@ -1,49 +1,15 @@"""PostHog analytics tracking for the chat system."""-import atexitimport loggingfrom typing import Any-from posthog import Posthog-+from backend.util import product_analytics+from backend.util.posthog_client import get_posthog_client as _get_posthog_clientfrom backend.util.settings import Settingslogger = logging.getLogger(__name__)settings = Settings()-# PostHog client instance (lazily initialized)-_posthog_client: Posthog | None = None---def _shutdown_posthog() -> None:- """Flush and shutdown PostHog client on process exit."""- if _posthog_client is not None:- _posthog_client.flush()- _posthog_client.shutdown()---atexit.register(_shutdown_posthog)---def _get_posthog_client() -> Posthog | None:- """Get or create the PostHog client instance."""- global _posthog_client- if _posthog_client is not None:- return _posthog_client-- if not settings.secrets.posthog_api_key:- logger.debug("PostHog API key not configured, analytics disabled")- return None-- _posthog_client = Posthog(- settings.secrets.posthog_api_key,- host=settings.secrets.posthog_host,- )- logger.info(- f"PostHog client initialized with host: {settings.secrets.posthog_host}"- )- return _posthog_client-def _get_base_properties() -> dict[str, Any]:"""Get base properties included in all events."""@@ -57,6 +23,10 @@ def track_user_message(user_id: str | None,session_id: str,message_length: int,+ *,+ expert_id: str | None = None,+ origin: str | None = None,+ surface: str | None = None,) -> None:"""Track when a user sends a message in chat.@@ -64,7 +34,21 @@ def track_user_message(user_id: The user's ID (or None for anonymous)session_id: The chat session IDmessage_length: Length of the user's message+ expert_id: Expert the session is scoped to, if any+ origin: Session origin ("interactive" | "automation"), when known+ surface: Where the message came from (web chat, slack, telegram, ...)"""+ # The activation event (run_autopilot / run_expert) is the one GTM+ # dashboards and experiments build on; copilot_message_sent stays for+ # the existing copilot dashboards.+ product_analytics.track_chat_turn(+ user_id=user_id,+ session_id=session_id,+ expert_id=expert_id,+ origin=origin,+ surface=surface,+ )+client = _get_posthog_client()if not client:returndiff --git a/autogpt_platform/backend/backend/copilot/turn_queue.py b/autogpt_platform/backend/backend/copilot/turn_queue.pyindex 9f0c6bf8aa..845426d00e 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue.py@@ -53,6 +53,7 @@ from backend.copilot.rate_limit import (get_global_rate_limits,is_user_paywalled,)+from backend.copilot.tracking import track_user_messagefrom backend.data.db_accessors import chat_dbfrom backend.integrations.codex.access import has_codex_access@@ -429,5 +430,18 @@ async def dispatch_next_for_user(user_id: str) -> bool:)raise+ if pending.role == "user" and pending.content:+ try:+ track_user_message(+ user_id=user_id,+ session_id=head.session_id,+ message_length=len(pending.content),+ expert_id=head.expert_id,+ origin=head.metadata.origin,+ surface="chat",+ )+ except Exception:+ logger.warning("Failed to track promoted chat turn", exc_info=True)+await invalidate_session_cache(head.session_id)return Truediff --git a/autogpt_platform/backend/backend/copilot/turn_queue_test.py b/autogpt_platform/backend/backend/copilot/turn_queue_test.pyindex a8c5f65fa0..b8d1f1d37b 100644--- a/autogpt_platform/backend/backend/copilot/turn_queue_test.py+++ b/autogpt_platform/backend/backend/copilot/turn_queue_test.py@@ -54,6 +54,13 @@ def _mock_session(session_id: str = "s1", title: str | None = "T") -> MagicMock:return s[email protected](autouse=True)+def tracked_message(monkeypatch: pytest.MonkeyPatch) -> MagicMock:+ tracker = MagicMock()+ monkeypatch.setattr(turn_queue, "track_user_message", tracker)+ return tracker++# ── enqueue_turn payload encoding ──────────────────────────────────────@@ -211,6 +218,78 @@ async def test_try_enqueue_turn_raises_when_at_inflight_cap() -> None:# ── dispatch_next_for_user ─────────────────────────────────────────────+ (+ "expert_id",+ "origin",+ "role",+ "claim",+ "dispatch_fails",+ "tracking_fails",+ "expected_event",+ ),+ [+ ("expert-1", "interactive", "user", True, False, False, True),+ (None, "automation", "user", True, False, False, True),+ ("expert-1", "interactive", "user", False, False, False, False),+ ("expert-1", "interactive", "user", True, True, False, False),+ ("expert-1", "interactive", "assistant", True, False, False, False),+ ("expert-1", "interactive", "user", True, False, True, True),+ ],+)+async def test_promoted_turn_tracking_preserves_session_attribution(+ tracked_message: MagicMock,+ expert_id: str | None,+ origin: str,+ role: str,+ claim: bool,+ dispatch_fails: bool,+ tracking_fails: bool,+ expected_event: bool,+) -> None:+ if tracking_fails:+ tracked_message.side_effect = RuntimeError("tracking failed")+ head = _mock_session()+ head.expert_id = expert_id+ head.metadata.origin = origin+ head.metadata.llm_auth_provider = "codex"+ pending = _pyd_message(role=role)+ db = MagicMock()+ db.get_latest_user_message_in_session = AsyncMock(return_value=pending)+ db.update_chat_session_status = AsyncMock(return_value=True)+ dispatched = AsyncMock(+ side_effect=RuntimeError("dispatch failed") if dispatch_fails else None+ )+ with (+ _patch_queued_list([head]),+ patch.object(turn_queue, "chat_db", return_value=db),+ patch.object(turn_queue, "has_codex_access", new=AsyncMock(return_value=True)),+ patch.object(+ turn_queue, "claim_queued_session", new=AsyncMock(return_value=claim)+ ),+ patch.object(turn_queue, "invalidate_session_cache", new=AsyncMock()),+ patch("backend.copilot.executor.utils.dispatch_turn", new=dispatched),+ ):+ if dispatch_fails:+ with pytest.raises(RuntimeError, match="dispatch failed"):+ await turn_queue.dispatch_next_for_user("u1")+ else:+ assert await turn_queue.dispatch_next_for_user("u1") is claim++ if expected_event:+ tracked_message.assert_called_once_with(+ user_id="u1",+ session_id="s1",+ message_length=5,+ expert_id=expert_id,+ origin=origin,+ surface="chat",+ )+ else:+ tracked_message.assert_not_called()++def _patch_queued_list(rows):"""Patch ``list_queued_sessions`` (the dispatcher's queue read) toreturn the given rows. Patching the helper rather than thediff --git a/autogpt_platform/backend/backend/data/execution.py b/autogpt_platform/backend/backend/data/execution.pyindex 18122ce1f6..f38a2a4e72 100644--- a/autogpt_platform/backend/backend/data/execution.py+++ b/autogpt_platform/backend/backend/data/execution.py@@ -2,7 +2,7 @@ import loggingimport queuefrom collections import defaultdictfrom datetime import datetime, timedelta, timezone-from enum import Enum+from enum import Enum, StrEnumfrom typing import (Annotated,Any,@@ -147,6 +147,29 @@ class BlockErrorStats(BaseModel):ExecutionStatus = AgentExecutionStatus+++class ExecutionTrigger(StrEnum):+ """How a graph execution was started. Persisted on the execution row.++ ``manual`` a person clicked run (UI surface in triggerRef) or ran a preset+ ``api`` external API key (key id in triggerRef)+ ``schedule`` a cron/one-shot schedule fired (schedule id in triggerRef)+ ``webhook`` an integration webhook fired (webhook id in triggerRef)+ ``copilot`` the copilot run_agent tool (chat session id in triggerRef)+ ``subgraph`` nested run started by an AgentExecutorBlock (parent exec id)+ ``admin`` reserved for future admin-initiated executions+ """++ MANUAL = "manual"+ API = "api"+ SCHEDULE = "schedule"+ WEBHOOK = "webhook"+ COPILOT = "copilot"+ SUBGRAPH = "subgraph"+ ADMIN = "admin"++NodeInputMask = Mapping[str, JsonValue]NodesInputMasks = Mapping[str, NodeInputMask]@@ -216,6 +239,10 @@ class GraphExecutionMeta(BaseDbModel):# resume/requeue recovery reason as org/team above.expert_id: Optional[str] = None+ # How the run was started (ExecutionTrigger value) and by what. Null on+ # rows created before the columns existed.+ trigger_source: Optional[str] = None+ trigger_ref: Optional[str] = None# What started this run, when it was not a person: the scheduler job or# the webhook that fired. Soft references; either may be gone by now.schedule_id: Optional[str] = None@@ -372,6 +399,8 @@ class GraphExecutionMeta(BaseDbModel):organization_id=_graph_exec.organizationId,team_id=_graph_exec.teamId,expert_id=_graph_exec.expertId,+ trigger_source=_graph_exec.triggerSource,+ trigger_ref=_graph_exec.triggerRef,schedule_id=_graph_exec.scheduleId,webhook_id=_graph_exec.webhookId,)@@ -927,6 +956,8 @@ async def create_graph_execution(organization_id: Optional[str] = None,team_id: Optional[str] = None,expert_id: Optional[str] = None,+ trigger_source: Optional[ExecutionTrigger] = None,+ trigger_ref: Optional[str] = None,schedule_id: Optional[str] = None,webhook_id: Optional[str] = None,) -> GraphExecutionWithNodes:@@ -983,6 +1014,8 @@ async def create_graph_execution("agentPresetId": preset_id,"parentGraphExecutionId": parent_graph_exec_id,**({"expertId": expert_id} if expert_id else {}),+ **({"triggerSource": trigger_source.value} if trigger_source else {}),+ **({"triggerRef": trigger_ref} if trigger_ref else {}),**({"scheduleId": schedule_id} if schedule_id else {}),**({"webhookId": webhook_id} if webhook_id else {}),**({"stats": Json({"is_dry_run": True})} if is_dry_run else {}),diff --git a/autogpt_platform/backend/backend/data/execution_stats_test.py b/autogpt_platform/backend/backend/data/execution_stats_test.pyindex 59a6a39c06..4203b0bec6 100644--- a/autogpt_platform/backend/backend/data/execution_stats_test.py+++ b/autogpt_platform/backend/backend/data/execution_stats_test.py@@ -25,6 +25,8 @@ def _db_execution(*, status: ExecutionStatus, stats: dict):organizationId=None,teamId=None,expertId=None,+ triggerSource=None,+ triggerRef=None,scheduleId=None,webhookId=None,)diff --git a/autogpt_platform/backend/backend/executor/manager.py b/autogpt_platform/backend/backend/executor/manager.pyindex 546000cc12..4b11d00345 100644--- a/autogpt_platform/backend/backend/executor/manager.py+++ b/autogpt_platform/backend/backend/executor/manager.py@@ -52,7 +52,7 @@ from backend.integrations.credential_lease import CredentialLeasefrom backend.integrations.credentials_store import provider_matchesfrom backend.integrations.creds_manager import IntegrationCredentialsManagerfrom backend.monitoring.instrumentation import record_graph_run_completion-from backend.util import json+from backend.util import json, product_analyticsfrom backend.util.clients import (get_async_execution_event_bus,get_database_manager_async_client,@@ -1087,6 +1087,7 @@ class ExecutionProcessor:activity_events.handle_run_completed(db_client, graph_exec, exec_meta, exec_stats)+ product_analytics.handle_run_finished(graph_exec, exec_meta, exec_stats)update_graph_execution_state(db_client=db_client,diff --git a/autogpt_platform/backend/backend/executor/schedule_events.py b/autogpt_platform/backend/backend/executor/schedule_events.pynew file mode 100644index 0000000000..5ac672d5a6--- /dev/null+++ b/autogpt_platform/backend/backend/executor/schedule_events.py@@ -0,0 +1,113 @@+"""Best-effort recording of new schedules, whichever surface created them.++The scheduler is the one place every schedule passes through (REST route,+copilot tools, expert installs), so it records each new schedule once: a+``schedule.created`` ActivityEvent for the Home feed and the ``analytics.*``+views, and a ``schedule_created`` product event. Mirrors+``backend.executor.activity_events`` for run completions: recording the+schedule must never fail or delay the schedule.++The activity event goes through the DatabaseManager RPC, whose client keeps+retrying for a long time while the service is unreachable. That write is+therefore handed to a small background worker pool: the schedule call returns+immediately and a DatabaseManager outage costs a log line, not a stalled+scheduler. The pool is bounded so an outage queues records instead of+spawning a thread per schedule, and its workers are joined at interpreter+exit so an in-flight write is not cut off by shutdown.+"""++import logging+from collections.abc import Callable+from concurrent.futures import ThreadPoolExecutor+from datetime import datetime+from threading import Lock++from pydantic import BaseModel++from backend.data.activity_event import ActivityEventDraft+from backend.util import product_analytics+from backend.util.clients import get_database_manager_client+from backend.util.product_analytics import ScheduleTarget++logger = logging.getLogger(__name__)+++class ScheduleCreatedRecord(BaseModel):+ user_id: str+ schedule_id: str+ title: str+ target: ScheduleTarget+ expert_id: str | None = None+ organization_id: str | None = None+ cron: str | None = None+ run_at: datetime | None = None+ graph_id: str | None = None+ session_id: str | None = None+ next_run_time: str | None = None+++def record_schedule_created(record: ScheduleCreatedRecord) -> None:+ try:+ _submit(lambda: _write_activity_event(record))+ except Exception:+ logger.warning(+ "Failed to submit schedule.created for %s",+ record.schedule_id,+ exc_info=True,+ )+ product_analytics.track_schedule_created(+ user_id=record.user_id,+ schedule_id=record.schedule_id,+ target=record.target,+ expert_id=record.expert_id,+ cron=record.cron,+ run_at=record.run_at,+ graph_id=record.graph_id,+ session_id=record.session_id,+ )+++def _write_activity_event(record: ScheduleCreatedRecord) -> None:+ try:+ get_database_manager_client().create_activity_event(+ user_id=record.user_id,+ draft=ActivityEventDraft(+ category="SCHEDULE",+ event_type="schedule.created",+ title=record.title,+ schedule_id=record.schedule_id,+ expert_id=record.expert_id,+ organization_id=record.organization_id,+ session_id=record.session_id,+ object_id=record.graph_id,+ data={+ "target": record.target,+ "cron": record.cron,+ "run_at": record.run_at.isoformat() if record.run_at else None,+ "next_run_time": record.next_run_time,+ "is_recurring": record.cron is not None,+ },+ ),+ )+ except Exception:+ logger.warning(+ "Failed to record schedule.created for %s",+ record.schedule_id,+ exc_info=True,+ )+++_executor: ThreadPoolExecutor | None = None+_executor_lock = Lock()+++def _submit(work: Callable[[], None]) -> None:+ """Run *work* off the caller's thread. Tests replace this to run inline."""+ global _executor+ with _executor_lock:+ if _executor is None:+ _executor = ThreadPoolExecutor(+ max_workers=2, thread_name_prefix="schedule-created-activity-event"+ )+ executor = _executor+ executor.submit(work)diff --git a/autogpt_platform/backend/backend/executor/schedule_events_test.py b/autogpt_platform/backend/backend/executor/schedule_events_test.pynew file mode 100644index 0000000000..4641f27b0c--- /dev/null+++ b/autogpt_platform/backend/backend/executor/schedule_events_test.py@@ -0,0 +1,74 @@+from concurrent.futures import ThreadPoolExecutor, TimeoutError+from threading import Event+from unittest.mock import Mock, call++import pytest++from backend.executor import schedule_events+++def test_rejected_activity_submission_preserves_schedule_and_product_event(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ schedule_events, "_submit", Mock(side_effect=RuntimeError("executor stopped"))+ )+ tracker = Mock()+ monkeypatch.setattr(+ schedule_events.product_analytics, "track_schedule_created", tracker+ )++ schedule_events.record_schedule_created(+ schedule_events.ScheduleCreatedRecord(+ user_id="user-1",+ schedule_id="schedule-1",+ title="Daily digest",+ target="agent",+ )+ )++ tracker.assert_called_once()+ assert tracker.call_args.kwargs["schedule_id"] == "schedule-1"+++def test_concurrent_schedules_share_one_executor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ first_started = Event()+ release_first = Event()+ pool = Mock()+ extra_pool = Mock()+ first_work = Mock()+ second_work = Mock()+ pool.submit.side_effect = lambda work: work()++ def create_pool(**kwargs: object) -> Mock:+ if first_started.is_set():+ return extra_pool+ first_started.set()+ assert release_first.wait(timeout=5)+ return pool++ factory = Mock(side_effect=create_pool)+ monkeypatch.setattr(schedule_events, "_executor", None)+ monkeypatch.setattr(schedule_events, "ThreadPoolExecutor", factory)++ with ThreadPoolExecutor(max_workers=2) as callers:+ first = callers.submit(schedule_events._submit, first_work)+ assert first_started.wait(timeout=5)+ second = callers.submit(schedule_events._submit, second_work)+ try:+ second.result(timeout=0.2)+ except TimeoutError:+ pass+ finally:+ release_first.set()+ first.result(timeout=5)+ second.result(timeout=5)++ factory.assert_called_once_with(+ max_workers=2, thread_name_prefix="schedule-created-activity-event"+ )+ pool.submit.assert_has_calls([call(first_work), call(second_work)], any_order=True)+ first_work.assert_called_once_with()+ second_work.assert_called_once_with()diff --git a/autogpt_platform/backend/backend/executor/scheduler.py b/autogpt_platform/backend/backend/executor/scheduler.pyindex 502039cde7..1ca737b648 100644--- a/autogpt_platform/backend/backend/executor/scheduler.py+++ b/autogpt_platform/backend/backend/executor/scheduler.py@@ -40,8 +40,9 @@ from backend.copilot.model import create_chat_session, get_chat_sessionfrom backend.copilot.optimize_blocks import optimize_block_descriptionsfrom backend.copilot.transports import resolve_default_chat_routefrom backend.data.db_accessors import experts_db-from backend.data.execution import GraphExecutionWithNodes+from backend.data.execution import ExecutionTrigger, GraphExecutionWithNodesfrom backend.data.model import CredentialsMetaInput, GraphInput+from backend.executor import schedule_eventsfrom backend.executor import utils as execution_utilsfrom backend.monitoring import (flush_matured_alerts,@@ -51,6 +52,7 @@ from backend.monitoring import (send_due_briefings,)from backend.monitoring.instrumentation import SCHEDULER_JOBS+from backend.util import product_analyticsfrom backend.util.clients import (get_database_manager_async_client,get_database_manager_client,@@ -213,9 +215,21 @@ async def _execute_graph(**kwargs):organization_id=args.organization_id,team_id=args.team_id,expert_id=args.expert_id,+ trigger=ExecutionTrigger.SCHEDULE,+ trigger_ref=args.schedule_id,schedule_id=args.schedule_id,)await db.increment_onboarding_runs(args.user_id)+ product_analytics.track_schedule_fired(+ user_id=args.user_id,+ schedule_id=args.schedule_id,+ target=product_analytics.schedule_target(+ expert_id=args.expert_id, is_copilot_turn=False+ ),+ expert_id=args.expert_id,+ graph_id=args.graph_id,+ graph_exec_id=graph_exec.id,+ )elapsed = asyncio.get_event_loop().time() - start_timelogger.info(f"Graph execution started with ID {graph_exec.id} for graph {args.graph_id} "@@ -463,6 +477,15 @@ async def _execute_copilot_turn(**kwargs):llm_auth_provider=target_session.metadata.llm_auth_provider,llm_credential_id=target_session.metadata.llm_credential_id,)+ product_analytics.track_schedule_fired(+ user_id=args.user_id,+ schedule_id=args.schedule_id,+ target=product_analytics.schedule_target(+ expert_id=args.expert_id, is_copilot_turn=True+ ),+ expert_id=args.expert_id,+ session_id=target_session_id,+ )elapsed = asyncio.get_event_loop().time() - start_timelogger.info(f"Dispatched scheduled copilot turn for session "@@ -1522,6 +1545,53 @@ def _next_run_time_iso(job_obj: JobObj) -> str:return job_obj.next_run_time.isoformat() if job_obj.next_run_time else ""+def _record_graph_schedule_created(+ job_args: GraphExecutionJobArgs, job_obj: JobObj, *, title: str+) -> None:+ """Record a new agent/expert schedule. See ``schedule_events``."""+ if not job_args.schedule_id:+ return+ schedule_events.record_schedule_created(+ schedule_events.ScheduleCreatedRecord(+ user_id=job_args.user_id,+ schedule_id=job_args.schedule_id,+ title=title,+ target=product_analytics.schedule_target(+ expert_id=job_args.expert_id, is_copilot_turn=False+ ),+ expert_id=job_args.expert_id,+ organization_id=job_args.organization_id or None,+ cron=job_args.cron,+ graph_id=job_args.graph_id,+ next_run_time=_next_run_time_iso(job_obj) or None,+ )+ )+++def _record_copilot_turn_schedule_created(+ job_args: CopilotTurnJobArgs, job_obj: JobObj, *, title: str+) -> None:+ """Record a new Autopilot/expert follow-up schedule. See ``schedule_events``."""+ if not job_args.schedule_id:+ return+ schedule_events.record_schedule_created(+ schedule_events.ScheduleCreatedRecord(+ user_id=job_args.user_id,+ schedule_id=job_args.schedule_id,+ title=title,+ target=product_analytics.schedule_target(+ expert_id=job_args.expert_id, is_copilot_turn=True+ ),+ expert_id=job_args.expert_id,+ organization_id=job_args.organization_id or None,+ cron=job_args.cron,+ run_at=job_args.run_at,+ session_id=job_args.session_id,+ next_run_time=_next_run_time_iso(job_obj) or None,+ )+ )++def _job_info_fields(job_obj: JobObj) -> dict[str, str]:"""The id/name/next_run_time/timezone block both JobInfo classes need.@@ -2028,6 +2098,9 @@ class Scheduler(AppService):f"Added job {job.id} with cron schedule '{cron}' in timezone "f"{user_timezone}")+ _record_graph_schedule_created(+ job_args, job, title=name or "Scheduled agent run"+ )return GraphExecutionJobInfo.from_db(job_args, job)@expose@@ -2098,6 +2171,9 @@ class Scheduler(AppService):f"Added copilot-turn job {job.id} ({trigger.__class__.__name__}) "f"for session {session_label} in timezone {user_timezone}")+ _record_copilot_turn_schedule_created(+ job_args, job, title=name or message[:80] or "Follow-up"+ )return CopilotTurnJobInfo.from_db(job_args, job)@exposediff --git a/autogpt_platform/backend/backend/executor/scheduler_activation_test.py b/autogpt_platform/backend/backend/executor/scheduler_activation_test.pynew file mode 100644index 0000000000..472c911acd--- /dev/null+++ b/autogpt_platform/backend/backend/executor/scheduler_activation_test.py@@ -0,0 +1,145 @@+"""Tests for the schedule.created record written when a schedule is persisted."""++from datetime import UTC, datetime+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from backend.executor import schedule_events+from backend.executor.schedule_events import (+ ScheduleCreatedRecord,+ record_schedule_created,+)+from backend.executor.scheduler import (+ CopilotTurnJobArgs,+ GraphExecutionJobArgs,+ _record_copilot_turn_schedule_created,+ _record_graph_schedule_created,+)+++def db_client(monkeypatch: pytest.MonkeyPatch) -> Mock:+ client = Mock()+ monkeypatch.setattr(schedule_events, "get_database_manager_client", lambda: client)+ # The write normally runs on a background thread; run it inline so the+ # assertions below see it.+ monkeypatch.setattr(schedule_events, "_submit", lambda work: work())+ return client+++def track_created(monkeypatch: pytest.MonkeyPatch) -> Mock:+ tracker = Mock()+ monkeypatch.setattr(+ schedule_events.product_analytics, "track_schedule_created", tracker+ )+ return tracker+++def _job(next_run_time: datetime | None = datetime(2026, 9, 3, 7, tzinfo=UTC)):+ return SimpleNamespace(id="sched-1", name="x", next_run_time=next_run_time)+++def _graph_args(expert_id: str | None = None) -> GraphExecutionJobArgs:+ return GraphExecutionJobArgs(+ schedule_id="sched-1",+ user_id="user-1",+ graph_id="graph-1",+ graph_version=3,+ agent_name="Daily digest",+ cron="0 7 * * *",+ input_data={},+ organization_id="org-1",+ expert_id=expert_id,+ )+++def test_graph_schedule_records_activity_event_and_product_event(+ db_client: Mock, track_created: Mock+) -> None:+ _record_graph_schedule_created(_graph_args(), _job(), title="Daily digest")++ db_client.create_activity_event.assert_called_once()+ kwargs = db_client.create_activity_event.call_args.kwargs+ draft = kwargs["draft"]+ assert kwargs["user_id"] == "user-1"+ assert draft.category == "SCHEDULE"+ assert draft.event_type == "schedule.created"+ assert draft.title == "Daily digest"+ assert draft.schedule_id == "sched-1"+ assert draft.object_id == "graph-1"+ assert draft.organization_id == "org-1"+ assert draft.session_id is None+ assert draft.data["target"] == "agent"+ assert draft.data["cron"] == "0 7 * * *"+ assert draft.data["is_recurring"] is True+ assert draft.data["next_run_time"] == "2026-09-03T07:00:00+00:00"++ track_created.assert_called_once()+ props = track_created.call_args.kwargs+ assert props["target"] == "agent"+ assert props["graph_id"] == "graph-1"+ assert props["schedule_id"] == "sched-1"+ assert "name" not in props+++def test_expert_schedule_targets_expert(db_client: Mock, track_created: Mock) -> None:+ _record_graph_schedule_created(_graph_args(expert_id="expert-1"), _job(), title="t")++ draft = db_client.create_activity_event.call_args.kwargs["draft"]+ assert draft.expert_id == "expert-1"+ assert draft.data["target"] == "expert"+ assert track_created.call_args.kwargs["target"] == "expert"+++def test_copilot_turn_schedule_records_session_and_run_at(+ db_client: Mock, track_created: Mock+) -> None:+ run_at = datetime(2026, 9, 2, 15, 30, tzinfo=UTC)+ args = CopilotTurnJobArgs(+ schedule_id="sched-2",+ user_id="user-1",+ session_id="session-1",+ message="Check whether CI is green",+ run_at=run_at,+ )++ _record_copilot_turn_schedule_created(+ args, _job(next_run_time=None), title="Check CI"+ )++ draft = db_client.create_activity_event.call_args.kwargs["draft"]+ assert draft.session_id == "session-1"+ assert draft.object_id is None+ assert draft.organization_id is None+ assert draft.data["target"] == "autopilot"+ assert draft.data["is_recurring"] is False+ assert draft.data["run_at"] == run_at.isoformat()+ assert draft.data["next_run_time"] is None+ assert track_created.call_args.kwargs["target"] == "autopilot"+ assert track_created.call_args.kwargs["session_id"] == "session-1"+++def test_db_failure_never_breaks_schedule_creation(+ db_client: Mock, track_created: Mock+) -> None:+ db_client.create_activity_event.side_effect = RuntimeError("db down")++ record_schedule_created(+ ScheduleCreatedRecord(+ user_id="user-1", schedule_id="sched-1", title="t", target="agent"+ )+ )++ track_created.assert_called_once()+++def test_missing_schedule_id_is_skipped(db_client: Mock, track_created: Mock) -> None:+ args = _graph_args().model_copy(update={"schedule_id": None})++ _record_graph_schedule_created(args, _job(), title="t")++ db_client.create_activity_event.assert_not_called()+ track_created.assert_not_called()diff --git a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py b/autogpt_platform/backend/backend/executor/scheduler_unit_test.pyindex 436886b8fd..61790fa13b 100644--- a/autogpt_platform/backend/backend/executor/scheduler_unit_test.py+++ b/autogpt_platform/backend/backend/executor/scheduler_unit_test.py@@ -46,6 +46,17 @@ from backend.util.exceptions import (_SCHEDULER_PATH = "backend.executor.scheduler"[email protected](autouse=True)+def mock_external_services(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ "backend.executor.scheduler.resolve_default_chat_route",+ AsyncMock(return_value=("platform", None)),+ )+ monkeypatch.setattr(+ "backend.executor.schedule_events.record_schedule_created", MagicMock()+ )++# ---------------------------------------------------------------------------# _build_trigger# ---------------------------------------------------------------------------diff --git a/autogpt_platform/backend/backend/executor/utils.py b/autogpt_platform/backend/backend/executor/utils.pyindex c31bfa1fed..fc8c5f65e2 100644--- a/autogpt_platform/backend/backend/executor/utils.py+++ b/autogpt_platform/backend/backend/executor/utils.py@@ -33,6 +33,7 @@ from backend.data.dynamic_fields import merge_execution_inputfrom backend.data.execution import (ExecutionContext,ExecutionStatus,+ ExecutionTrigger,GraphExecutionMeta,GraphExecutionStats,GraphExecutionWithNodes,@@ -48,6 +49,7 @@ from backend.data.model import (from backend.data.rabbitmq import Exchange, ExchangeType, Queue, RabbitMQConfigfrom backend.integrations.credentials_store import is_system_credentialfrom backend.monitoring.instrumentation import record_graph_execution+from backend.util import product_analyticsfrom backend.util.clients import (get_async_execution_event_bus,get_async_execution_queue,@@ -1250,6 +1252,8 @@ async def add_graph_execution(schedule_id: Optional[str] = None,webhook_id: Optional[str] = None,bypass_paywall: bool = False,+ trigger: ExecutionTrigger = ExecutionTrigger.MANUAL,+ trigger_ref: Optional[str] = None,) -> GraphExecutionWithNodes:"""Add a graph execution to the queue, recording the outcome.@@ -1276,6 +1280,8 @@ async def add_graph_execution(schedule_id=schedule_id,webhook_id=webhook_id,bypass_paywall=bypass_paywall,+ trigger=trigger,+ trigger_ref=trigger_ref,)except GraphValidationError:record_graph_execution(@@ -1309,6 +1315,8 @@ async def _add_graph_execution(schedule_id: Optional[str] = None,webhook_id: Optional[str] = None,bypass_paywall: bool = False,+ trigger: ExecutionTrigger = ExecutionTrigger.MANUAL,+ trigger_ref: Optional[str] = None,) -> GraphExecutionWithNodes:"""Adds a graph execution to the queue and returns the execution entry.@@ -1335,6 +1343,11 @@ async def _add_graph_execution(bypass_paywall: Skip the per-user paywall check. Set ONLY for adminrecovery paths (requeueing stuck executions on behalf of a userwho may be on NO_TIER) — never for user-initiated runs.+ trigger: How the run was started. Persisted on the execution row and+ used to decide which activation event (if any) to emit. Ignored+ in REQUEUE mode, where the original row is authoritative.+ trigger_ref: Identifier of what started the run for that trigger+ (schedule id, webhook id, chat session id, API key id, UI surface).Returns:GraphExecutionWithNodes: The execution entry.Raises:@@ -1363,6 +1376,7 @@ async def _add_graph_execution(if not bypass_paywall and await is_user_paywalled(user_id):raise UserPaywalledError("A subscription is required to run agents.")+ is_new_execution = graph_exec_id is Nonecontext_expert_id = execution_context.expert_id if execution_context else Noneif expert_id is not None and context_expert_id not in (None, expert_id):raise ValueError(@@ -1534,6 +1548,8 @@ async def _add_graph_execution(organization_id=organization_id,team_id=team_id,expert_id=expert_id,+ trigger_source=trigger,+ trigger_ref=trigger_ref,schedule_id=schedule_id,webhook_id=webhook_id,)@@ -1706,6 +1722,18 @@ async def _add_graph_execution(except Exception as e:logger.error(f"Failed to increment onboarding runs for user #{user_id}: {e}")+ if is_new_execution:+ product_analytics.track_agent_run_started(+ user_id=user_id,+ graph_id=graph_id,+ graph_exec_id=graph_exec.id,+ trigger=trigger,+ trigger_ref=trigger_ref,+ expert_id=expert_id,+ preset_id=preset_id,+ is_dry_run=dry_run,+ )+return graph_execdiff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.pyindex 35eb0d08d2..a26c6cf4d7 100644--- a/autogpt_platform/backend/backend/executor/utils_test.py+++ b/autogpt_platform/backend/backend/executor/utils_test.py@@ -9,6 +9,7 @@ from backend.data.dynamic_fields import merge_execution_input, parse_execution_ofrom backend.data.execution import (ExecutionContext,ExecutionStatus,+ ExecutionTrigger,GraphExecutionWithNodes,)from backend.data.model import User@@ -24,6 +25,18 @@ from backend.executor.utils import (from backend.util.mock import MockObject[email protected](autouse=True)+def mock_account_state(mocker: MockerFixture) -> None:+ mocker.patch(+ "backend.executor.utils.onboarding_db.increment_onboarding_runs",+ new=mocker.AsyncMock(),+ )+ mocker.patch(+ "backend.executor.utils._spend_approval_required",+ new=mocker.AsyncMock(return_value=None),+ )++def test_parse_execution_output():# Test case for basic outputoutput = ("result", "value")@@ -448,6 +461,8 @@ async def test_add_graph_execution_is_repeatable(mocker: MockerFixture):organization_id=None,team_id=None,expert_id=None,+ trigger_source=ExecutionTrigger.MANUAL,+ trigger_ref=None,schedule_id=None,webhook_id=None,)diff --git a/autogpt_platform/backend/backend/util/posthog_client.py b/autogpt_platform/backend/backend/util/posthog_client.pynew file mode 100644index 0000000000..0c19441dbf--- /dev/null+++ b/autogpt_platform/backend/backend/util/posthog_client.py@@ -0,0 +1,54 @@+"""Process-wide PostHog client shared by every server-side analytics emitter.++The client batches events on a background thread, so one instance per+process is both cheaper and safer than one per module. Emitters must treat+``None`` as "analytics disabled" and never let tracking raise into the+request or execution that produced the event.+"""++import atexit+import logging+from threading import Lock++from posthog import Posthog++from backend.util.settings import Settings++logger = logging.getLogger(__name__)++_client: Posthog | None = None+_initialized = False+_client_lock = Lock()+++def get_posthog_client() -> Posthog | None:+ global _client, _initialized+ if _initialized:+ return _client+ with _client_lock:+ if _initialized:+ return _client++ try:+ settings = Settings()+ if settings.secrets.posthog_api_key:+ _client = Posthog(+ settings.secrets.posthog_api_key,+ host=settings.secrets.posthog_host,+ )+ else:+ logger.debug("PostHog API key not configured, analytics disabled")+ except Exception:+ logger.warning("Failed to initialize PostHog analytics", exc_info=True)+ return None+ _initialized = True+ return _client+++def _shutdown() -> None:+ if _client is not None:+ _client.flush()+ _client.shutdown()+++atexit.register(_shutdown)diff --git a/autogpt_platform/backend/backend/util/posthog_client_test.py b/autogpt_platform/backend/backend/util/posthog_client_test.pynew file mode 100644index 0000000000..035ba6c72c--- /dev/null+++ b/autogpt_platform/backend/backend/util/posthog_client_test.py@@ -0,0 +1,105 @@+from concurrent.futures import ThreadPoolExecutor, TimeoutError+from threading import Event+from unittest.mock import Mock++import pytest++from backend.util import posthog_client++[email protected](autouse=True)+def reset_client_state(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(posthog_client, "_client", None)+ monkeypatch.setattr(posthog_client, "_initialized", False, raising=False)+++def test_concurrent_initialization_reuses_one_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ first_started = Event()+ release_first = Event()+ client = Mock()+ extra_client = Mock()++ def create_client(*args: object, **kwargs: object) -> Mock:+ if first_started.is_set():+ return extra_client+ first_started.set()+ assert release_first.wait(timeout=5)+ return client++ settings = Mock()+ settings.secrets.posthog_api_key = "test-key"+ settings.secrets.posthog_host = "https://example.com"+ factory = Mock(side_effect=create_client)+ monkeypatch.setattr(posthog_client, "_client", None)+ monkeypatch.setattr(posthog_client, "Settings", Mock(return_value=settings))+ monkeypatch.setattr(posthog_client, "Posthog", factory)++ with ThreadPoolExecutor(max_workers=2) as executor:+ first = executor.submit(posthog_client.get_posthog_client)+ assert first_started.wait(timeout=5)+ second = executor.submit(posthog_client.get_posthog_client)+ try:+ second.result(timeout=0.2)+ except TimeoutError:+ pass+ finally:+ release_first.set()++ assert first.result(timeout=5) is client+ assert second.result(timeout=5) is client++ factory.assert_called_once_with("test-key", host="https://example.com")+++def test_disabled_analytics_does_not_create_a_client(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ settings = Mock()+ settings.secrets.posthog_api_key = ""+ factory = Mock()+ monkeypatch.setattr(posthog_client, "_client", None)+ monkeypatch.setattr(posthog_client, "Settings", Mock(return_value=settings))+ monkeypatch.setattr(posthog_client, "Posthog", factory)++ assert posthog_client.get_posthog_client() is None+ factory.assert_not_called()+++def test_disabled_analytics_is_cached(monkeypatch: pytest.MonkeyPatch) -> None:+ settings = Mock()+ settings.secrets.posthog_api_key = ""+ settings_factory = Mock(return_value=settings)+ monkeypatch.setattr(posthog_client, "Settings", settings_factory)++ assert posthog_client.get_posthog_client() is None+ assert posthog_client.get_posthog_client() is None++ settings_factory.assert_called_once_with()++[email protected]("failure", ["settings", "client"])+def test_initialization_failure_is_safe_and_retryable(+ monkeypatch: pytest.MonkeyPatch, failure: str+) -> None:+ settings = Mock()+ settings.secrets.posthog_api_key = "test-key"+ settings.secrets.posthog_host = "https://example.com"+ client = Mock()+ settings_factory = Mock(return_value=settings)+ client_factory = Mock(return_value=client)+ if failure == "settings":+ settings_factory.side_effect = [+ RuntimeError("configuration unavailable"),+ settings,+ ]+ else:+ client_factory.side_effect = [RuntimeError("client unavailable"), client]+ monkeypatch.setattr(posthog_client, "Settings", settings_factory)+ monkeypatch.setattr(posthog_client, "Posthog", client_factory)++ assert posthog_client.get_posthog_client() is None+ assert posthog_client.get_posthog_client() is client+ assert posthog_client.get_posthog_client() is client+ assert settings_factory.call_count == 2diff --git a/autogpt_platform/backend/backend/util/product_analytics.py b/autogpt_platform/backend/backend/util/product_analytics.pynew file mode 100644index 0000000000..24adb07561--- /dev/null+++ b/autogpt_platform/backend/backend/util/product_analytics.py@@ -0,0 +1,329 @@+"""Server-side product analytics: the activation events GTM reports on.++One vocabulary, emitted once per real user action from the backend choke+points (execution creation, executor completion, chat-turn persistence, the+scheduler, webhook delivery), so PostHog funnels and experiments count the+same things the ``analytics.*`` SQL views count from the primary tables.++Event vocabulary (PostHog event name -> SQL equivalent):++- ``run_agent`` human-initiated agent run (manual UI, API key, copilot+ tool). AgentGraphExecution.triggerSource IN+ ('manual', 'api', 'copilot') AND expertId IS NULL.+- ``run_autopilot`` user turn in an Autopilot chat. ChatMessage role='user'+ on a session with expertId IS NULL and interactive origin.+- ``run_expert`` user turn in an expert chat, or a human-initiated run of+ an expert's workflow (property ``kind`` tells which).+- ``agent_run_completed`` / ``agent_run_failed`` terminal run outcome, with+ ``trigger`` so failures can be split by how they started.+ Includes subgraph and automated runs; filter to human+ triggers when comparing outcomes with run-start events.+- ``schedule_created`` a schedule was registered (``target``: agent | autopilot |+ expert). ActivityEvent category SCHEDULE / schedule.created.+- ``schedule_fired`` a schedule produced work. For agent/expert targets the run+ row carries triggerSource='schedule' and triggerRef=schedule+ id; for autopilot targets the session has origin='automation'.+- ``trigger_fired`` a webhook produced a run (triggerSource='webhook').+- ``expert_hired`` a user hired an expert from a template.+- ``integration_connected`` a user connected a credential (OAuth or manual).+ IntegrationCredential rows by createdByUserId.++Every emitter is best-effort: tracking can never break the work it describes.+"""++import logging+from datetime import datetime+from enum import StrEnum+from typing import TYPE_CHECKING, Any, Literal++from backend.util.posthog_client import get_posthog_client+from backend.util.settings import Settings++if TYPE_CHECKING:+ from backend.data.execution import GraphExecutionEntry, GraphExecutionMeta+ from backend.data.model import GraphExecutionStats++logger = logging.getLogger(__name__)+settings = Settings()+++class ActivationEvent(StrEnum):+ RUN_AGENT = "run_agent"+ RUN_AUTOPILOT = "run_autopilot"+ RUN_EXPERT = "run_expert"+ AGENT_RUN_COMPLETED = "agent_run_completed"+ AGENT_RUN_FAILED = "agent_run_failed"+ SCHEDULE_CREATED = "schedule_created"+ SCHEDULE_FIRED = "schedule_fired"+ TRIGGER_FIRED = "trigger_fired"+ EXPERT_HIRED = "expert_hired"+ INTEGRATION_CONNECTED = "integration_connected"+++ScheduleTarget = Literal["agent", "autopilot", "expert"]++# Triggers that mean "a person asked for this run now". Schedule and webhook+# runs are reported as schedule_fired / trigger_fired by their own emitters,+# and nested sub-graph runs are an implementation detail of the parent run.+HUMAN_RUN_TRIGGERS = frozenset({"manual", "api", "copilot"})+++def _enum_value(value: Any) -> Any:+ return getattr(value, "value", value)+++def track(+ user_id: str | None,+ event: ActivationEvent,+ properties: dict[str, Any] | None = None,+) -> None:+ """Send one event for *user_id*. Silently no-ops when analytics is off."""+ if not user_id:+ return+ try:+ client = get_posthog_client()+ if client is None:+ return+ client.capture(+ distinct_id=user_id,+ event=event.value,+ properties={+ "environment": settings.config.app_env.value,+ "source": "platform",+ **{k: v for k, v in (properties or {}).items() if v is not None},+ },+ )+ except Exception:+ logger.warning("Failed to track %s for user %s", event.value, user_id)+++def track_agent_run_started(+ *,+ user_id: str,+ graph_id: str,+ graph_exec_id: str,+ trigger: str | None,+ trigger_ref: str | None = None,+ expert_id: str | None = None,+ preset_id: str | None = None,+ is_dry_run: bool = False,+) -> None:+ trigger_value = _enum_value(trigger)+ if is_dry_run or trigger_value not in HUMAN_RUN_TRIGGERS:+ return+ properties = {+ "graph_id": graph_id,+ "graph_exec_id": graph_exec_id,+ "trigger": trigger_value,+ "trigger_ref": trigger_ref,+ "expert_id": expert_id,+ "preset_id": preset_id,+ }+ if expert_id:+ track(+ user_id,+ ActivationEvent.RUN_EXPERT,+ {**properties, "kind": "workflow_run"},+ )+ else:+ track(user_id, ActivationEvent.RUN_AGENT, properties)+++def track_agent_run_finished(+ *,+ user_id: str,+ graph_id: str,+ graph_exec_id: str,+ status: Any,+ trigger: str | None,+ expert_id: str | None = None,+ failure_reason: Any = None,+ cost_cents: int | None = None,+ duration_seconds: float | None = None,+ is_dry_run: bool = False,+) -> None:+ if is_dry_run:+ return+ status_value = _enum_value(status)+ if status_value == "COMPLETED":+ event = ActivationEvent.AGENT_RUN_COMPLETED+ elif status_value == "FAILED":+ event = ActivationEvent.AGENT_RUN_FAILED+ else:+ return+ track(+ user_id,+ event,+ {+ "graph_id": graph_id,+ "graph_exec_id": graph_exec_id,+ "trigger": _enum_value(trigger),+ "expert_id": expert_id,+ "failure_reason": _enum_value(failure_reason),+ "cost_cents": cost_cents,+ "duration_seconds": duration_seconds,+ },+ )+++def handle_run_finished(+ graph_exec: "GraphExecutionEntry",+ exec_meta: "GraphExecutionMeta",+ exec_stats: "GraphExecutionStats",+) -> None:+ """Executor completion hook. Mirrors activity_events.handle_run_completed."""+ try:+ track_agent_run_finished(+ user_id=graph_exec.user_id,+ graph_id=graph_exec.graph_id,+ graph_exec_id=graph_exec.graph_exec_id,+ status=exec_meta.status,+ trigger=exec_meta.trigger_source,+ expert_id=exec_meta.expert_id,+ failure_reason=exec_stats.failure_reason,+ cost_cents=exec_stats.cost,+ duration_seconds=exec_stats.walltime,+ is_dry_run=exec_stats.is_dry_run,+ )+ except Exception:+ logger.warning(+ "Failed to track run outcome for %s",+ graph_exec.graph_exec_id,+ exc_info=True,+ )+++def track_chat_turn(+ *,+ user_id: str | None,+ session_id: str,+ expert_id: str | None = None,+ origin: str | None = None,+ surface: str | None = None,+) -> None:+ """A person sent a chat message. Model-authored turns are not activation."""+ if origin == "automation":+ return+ track(+ user_id,+ ActivationEvent.RUN_EXPERT if expert_id else ActivationEvent.RUN_AUTOPILOT,+ {+ "session_id": session_id,+ "expert_id": expert_id,+ "origin": origin,+ "surface": surface or "chat",+ "kind": "chat_turn",+ },+ )+++def schedule_target(*, expert_id: str | None, is_copilot_turn: bool) -> ScheduleTarget:+ if expert_id:+ return "expert"+ return "autopilot" if is_copilot_turn else "agent"+++def track_schedule_created(+ *,+ user_id: str,+ schedule_id: str,+ target: ScheduleTarget,+ expert_id: str | None = None,+ cron: str | None = None,+ run_at: datetime | None = None,+ graph_id: str | None = None,+ session_id: str | None = None,+) -> None:+ track(+ user_id,+ ActivationEvent.SCHEDULE_CREATED,+ {+ "schedule_id": schedule_id,+ "target": target,+ "expert_id": expert_id,+ "cron": cron,+ "is_recurring": cron is not None,+ "run_at": run_at.isoformat() if run_at else None,+ "graph_id": graph_id,+ "session_id": session_id,+ },+ )+++def track_schedule_fired(+ *,+ user_id: str,+ schedule_id: str | None,+ target: ScheduleTarget,+ expert_id: str | None = None,+ graph_id: str | None = None,+ graph_exec_id: str | None = None,+ session_id: str | None = None,+) -> None:+ track(+ user_id,+ ActivationEvent.SCHEDULE_FIRED,+ {+ "schedule_id": schedule_id,+ "target": target,+ "expert_id": expert_id,+ "graph_id": graph_id,+ "graph_exec_id": graph_exec_id,+ "session_id": session_id,+ },+ )+++def track_trigger_fired(+ *,+ user_id: str,+ webhook_id: str,+ graph_id: str,+ graph_exec_id: str,+ expert_id: str | None = None,+ preset_id: str | None = None,+) -> None:+ track(+ user_id,+ ActivationEvent.TRIGGER_FIRED,+ {+ "webhook_id": webhook_id,+ "graph_id": graph_id,+ "graph_exec_id": graph_exec_id,+ "expert_id": expert_id,+ "preset_id": preset_id,+ "target": "expert" if expert_id else "agent",+ },+ )+++def track_expert_hired(+ *,+ user_id: str,+ expert_id: str,+ template_id: str | None = None,+ name: str | None = None,+) -> None:+ track(+ user_id,+ ActivationEvent.EXPERT_HIRED,+ {"expert_id": expert_id, "template_id": template_id, "name": name},+ )+++def track_integration_connected(+ *,+ user_id: str,+ provider: str,+ credential_type: str,+ method: Literal["oauth", "manual", "device_code"],+) -> None:+ track(+ user_id,+ ActivationEvent.INTEGRATION_CONNECTED,+ {+ "provider": _enum_value(provider),+ "credential_type": _enum_value(credential_type),+ "method": method,+ },+ )diff --git a/autogpt_platform/backend/backend/util/product_analytics_test.py b/autogpt_platform/backend/backend/util/product_analytics_test.pynew file mode 100644index 0000000000..adffcb8213--- /dev/null+++ b/autogpt_platform/backend/backend/util/product_analytics_test.py@@ -0,0 +1,277 @@+"""Tests for the activation event vocabulary and its emitters."""++from unittest.mock import Mock++import pytest++from backend.util import product_analytics+from backend.util.product_analytics import ActivationEvent+from backend.util.settings import AppEnvironment+++def capture(monkeypatch: pytest.MonkeyPatch) -> Mock:+ client = Mock()+ monkeypatch.setattr(product_analytics, "get_posthog_client", lambda: client)+ return client.capture+++def _only_call(capture: Mock) -> tuple[str, dict]:+ assert capture.call_count == 1+ kwargs = capture.call_args.kwargs+ return kwargs["event"], kwargs["properties"]+++def test_track_is_a_noop_without_client(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(product_analytics, "get_posthog_client", lambda: None)+ product_analytics.track("user-1", ActivationEvent.RUN_AGENT, {"graph_id": "g"})+++def test_track_is_a_noop_without_user(capture: Mock) -> None:+ product_analytics.track(None, ActivationEvent.RUN_AGENT, {"graph_id": "g"})+ capture.assert_not_called()+++def test_track_adds_base_properties_and_drops_nulls(capture: Mock) -> None:+ product_analytics.track(+ "user-1", ActivationEvent.RUN_AGENT, {"graph_id": "g", "expert_id": None}+ )++ event, properties = _only_call(capture)+ assert capture.call_args.kwargs["distinct_id"] == "user-1"+ assert event == "run_agent"+ assert properties["source"] == "platform"+ assert "environment" in properties+ assert properties["graph_id"] == "g"+ assert "expert_id" not in properties+++def test_track_swallows_client_errors(capture: Mock) -> None:+ capture.side_effect = RuntimeError("posthog down")+ product_analytics.track("user-1", ActivationEvent.RUN_AGENT)++[email protected]("trigger", ["manual", "api", "copilot"])+def test_human_run_start_is_run_agent(capture: Mock, trigger: str) -> None:+ product_analytics.track_agent_run_started(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ trigger=trigger,+ trigger_ref="library",+ )++ event, properties = _only_call(capture)+ assert event == "run_agent"+ assert properties["trigger"] == trigger+ assert properties["trigger_ref"] == "library"+++def test_run_start_accepts_enum_trigger(capture: Mock) -> None:+ from backend.data.execution import ExecutionTrigger++ product_analytics.track_agent_run_started(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ trigger=ExecutionTrigger.MANUAL,+ )++ event, properties = _only_call(capture)+ assert event == "run_agent"+ assert properties["trigger"] == "manual"+++def test_expert_workflow_run_start_is_run_expert(capture: Mock) -> None:+ product_analytics.track_agent_run_started(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ trigger="manual",+ expert_id="expert-1",+ )++ event, properties = _only_call(capture)+ assert event == "run_expert"+ assert properties["kind"] == "workflow_run"+ assert properties["expert_id"] == "expert-1"++[email protected]("trigger", ["schedule", "webhook", "subgraph", "admin", None])+def test_non_human_run_start_emits_nothing(capture: Mock, trigger: str | None) -> None:+ product_analytics.track_agent_run_started(+ user_id="user-1", graph_id="graph-1", graph_exec_id="exec-1", trigger=trigger+ )+ capture.assert_not_called()+++def test_dry_run_start_emits_nothing(capture: Mock) -> None:+ product_analytics.track_agent_run_started(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ trigger="manual",+ is_dry_run=True,+ )+ capture.assert_not_called()+++def test_run_finished_completed(capture: Mock) -> None:+ from backend.data.execution import ExecutionStatus++ product_analytics.track_agent_run_finished(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ status=ExecutionStatus.COMPLETED,+ trigger="schedule",+ cost_cents=12,+ duration_seconds=3.5,+ )++ event, properties = _only_call(capture)+ assert event == "agent_run_completed"+ assert properties["trigger"] == "schedule"+ assert properties["cost_cents"] == 12+ assert properties["duration_seconds"] == 3.5+++def test_run_finished_failed_carries_failure_reason(capture: Mock) -> None:+ from backend.data.execution import ExecutionStatus+ from backend.util.exceptions import ExecutionFailureReason++ product_analytics.track_agent_run_finished(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ status=ExecutionStatus.FAILED,+ trigger="manual",+ failure_reason=ExecutionFailureReason.INSUFFICIENT_BALANCE,+ )++ event, properties = _only_call(capture)+ assert event == "agent_run_failed"+ assert properties["failure_reason"] == "insufficient_balance"+++def test_run_finished_terminated_or_dry_run_emits_nothing(capture: Mock) -> None:+ from backend.data.execution import ExecutionStatus++ product_analytics.track_agent_run_finished(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ status=ExecutionStatus.TERMINATED,+ trigger="manual",+ )+ product_analytics.track_agent_run_finished(+ user_id="user-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ status=ExecutionStatus.COMPLETED,+ trigger="manual",+ is_dry_run=True,+ )+ capture.assert_not_called()+++def test_chat_turn_autopilot_vs_expert(capture: Mock) -> None:+ product_analytics.track_chat_turn(user_id="user-1", session_id="s1")+ product_analytics.track_chat_turn(+ user_id="user-1", session_id="s2", expert_id="expert-1", surface="slack"+ )++ events = [c.kwargs["event"] for c in capture.call_args_list]+ assert events == ["run_autopilot", "run_expert"]+ autopilot_props = capture.call_args_list[0].kwargs["properties"]+ expert_props = capture.call_args_list[1].kwargs["properties"]+ assert autopilot_props["surface"] == "chat"+ assert autopilot_props["kind"] == "chat_turn"+ assert expert_props["surface"] == "slack"+ assert expert_props["expert_id"] == "expert-1"+++def test_automation_chat_turn_emits_nothing(capture: Mock) -> None:+ product_analytics.track_chat_turn(+ user_id="user-1", session_id="s1", origin="automation"+ )+ capture.assert_not_called()+++def test_schedule_target() -> None:+ assert (+ product_analytics.schedule_target(expert_id=None, is_copilot_turn=False)+ == "agent"+ )+ assert (+ product_analytics.schedule_target(expert_id=None, is_copilot_turn=True)+ == "autopilot"+ )+ assert (+ product_analytics.schedule_target(expert_id="e", is_copilot_turn=True)+ == "expert"+ )+ assert (+ product_analytics.schedule_target(expert_id="e", is_copilot_turn=False)+ == "expert"+ )+++def test_schedule_created_and_fired(capture: Mock) -> None:+ product_analytics.track_schedule_created(+ user_id="user-1",+ schedule_id="sched-1",+ target="autopilot",+ cron=None,+ )+ product_analytics.track_schedule_fired(+ user_id="user-1", schedule_id="sched-1", target="agent", graph_exec_id="exec-1"+ )++ created, fired = capture.call_args_list+ assert created.kwargs["event"] == "schedule_created"+ assert created.kwargs["properties"]["is_recurring"] is False+ assert created.kwargs["properties"]["target"] == "autopilot"+ assert fired.kwargs["event"] == "schedule_fired"+ assert fired.kwargs["properties"]["graph_exec_id"] == "exec-1"+++def test_integration_connected(capture: Mock, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ product_analytics.settings.config, "app_env", AppEnvironment.LOCAL+ )+ product_analytics.track_integration_connected(+ user_id="user-1",+ provider="github",+ credential_type="oauth2",+ method="oauth",+ )++ event, properties = _only_call(capture)+ assert event == "integration_connected"+ assert properties == {+ "environment": "local",+ "source": "platform",+ "provider": "github",+ "credential_type": "oauth2",+ "method": "oauth",+ }+++def test_trigger_fired_and_expert_hired(capture: Mock) -> None:+ product_analytics.track_trigger_fired(+ user_id="user-1",+ webhook_id="wh-1",+ graph_id="graph-1",+ graph_exec_id="exec-1",+ expert_id="expert-1",+ )+ product_analytics.track_expert_hired(+ user_id="user-1", expert_id="expert-1", template_id="tmpl-1", name="Maria"+ )++ trigger, hired = capture.call_args_list+ assert trigger.kwargs["event"] == "trigger_fired"+ assert trigger.kwargs["properties"]["target"] == "expert"+ assert hired.kwargs["event"] == "expert_hired"+ assert hired.kwargs["properties"]["template_id"] == "tmpl-1"diff --git a/autogpt_platform/backend/migrations/20260902120000_add_execution_trigger_source/migration.sql b/autogpt_platform/backend/migrations/20260902120000_add_execution_trigger_source/migration.sqlnew file mode 100644index 0000000000..199cb87c9e--- /dev/null+++ b/autogpt_platform/backend/migrations/20260902120000_add_execution_trigger_source/migration.sql@@ -0,0 +1,4 @@+-- AlterTable+ALTER TABLE "AgentGraphExecution"+ ADD COLUMN "triggerSource" TEXT,+ ADD COLUMN "triggerRef" TEXT;diff --git a/autogpt_platform/backend/schema.prisma b/autogpt_platform/backend/schema.prismaindex 6932f6eff3..dcb9bdac6f 100644--- a/autogpt_platform/backend/schema.prisma+++ b/autogpt_platform/backend/schema.prisma@@ -1335,6 +1335,14 @@ model AgentGraphExecution {expertId String?Expert Expert? @relation(fields: [expertId], references: [id], onDelete: SetNull)+ // How the run was started (values: backend.data.execution.ExecutionTrigger).+ // Persisted so analytics can separate human-initiated runs from schedule,+ // webhook, API and copilot-initiated ones instead of inferring it from the+ // preset / expert / parent columns. Null for rows that predate the column.+ triggerSource String?+ // What started the run, for that source: schedule id, webhook id, chat+ // session id, API key id, or the UI surface for manual runs.+ triggerRef String?// What started this run, when it was not a person: the scheduler job or// the webhook that fired. Soft references, since jobs live in// APScheduler's own store and webhooks are cleaned up independently.diff --git a/autogpt_platform/frontend/src/app/api/openapi.json b/autogpt_platform/frontend/src/app/api/openapi.jsonindex e4be259924..d8bd176704 100644--- a/autogpt_platform/frontend/src/app/api/openapi.json+++ b/autogpt_platform/frontend/src/app/api/openapi.json@@ -21915,6 +21915,14 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Expert Id"},+ "trigger_source": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Source"+ },+ "trigger_ref": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Ref"+ },"schedule_id": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Schedule Id"@@ -22104,6 +22112,14 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Expert Id"},+ "trigger_source": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Source"+ },+ "trigger_ref": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Ref"+ },"schedule_id": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Schedule Id"@@ -22217,6 +22233,14 @@"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Expert Id"},+ "trigger_source": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Source"+ },+ "trigger_ref": {+ "anyOf": [{ "type": "string" }, { "type": "null" }],+ "title": "Trigger Ref"+ },"schedule_id": {"anyOf": [{ "type": "string" }, { "type": "null" }],"title": "Schedule Id"