Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

implement observibility

ali-inkco8c75b9f43ca3
diff --git a/packages/app/src/builder-ui/components/APIEndpoint.class.ts b/packages/app/src/builder-ui/components/APIEndpoint.class.ts
index 708d7d44..a9b97ebf 100644
--- a/packages/app/src/builder-ui/components/APIEndpoint.class.ts
+++ b/packages/app/src/builder-ui/components/APIEndpoint.class.ts
@@ -1,4 +1,4 @@
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { debounce } from 'lodash-es';
import { EMBODIMENT_DESCRIPTIONS } from '../../shared/constants/general';
import EventEmitter from '../EventEmitter.class';
@@ -155,7 +155,7 @@ export class APIEndpoint extends Component {
type: 'textarea',
label: 'Description',
value: '',
- help: 'Provide a short overview for teammates and AI to understand the skill\'s purpose.',
+ help: "Provide a short overview for teammates and AI to understand the skill's purpose.",
tooltipClasses: 'w-56 ',
arrowClasses: '-ml-11',
validate: `maxlength=1000`,
@@ -379,7 +379,7 @@ export class APIEndpoint extends Component {
const missingSettings = requiredSettings.filter((setting) => !this.data[setting.id]);
if (missingSettings.length === 0 && this.properties?.inputProps?.length > 0) {
- PostHog.track('app_form_preview_impression', {});
+ Observability.userBehavior.recordInteraction('app_form_preview_impression', {});
this.formPreviewButton = this.addComponentButton(
`<div class="fa-solid fa-play" id="form-preview-button-icon"></div><p class="ml-2 font-semibold">Form Preview</p>`,
' ',
@@ -666,7 +666,7 @@ export class APIEndpoint extends Component {
}
private async handleFormPreviewBtnClick() {
- PostHog.track('app_form_preview_click', {});
+ Observability.userBehavior.recordInteraction('app_form_preview_click', {});
let autoFillDataJson = this.cachedAutoFillDataJson;
const formPreviewButton = this.domElement.querySelector(
diff --git a/packages/app/src/builder-ui/components/AgentCard.class.ts b/packages/app/src/builder-ui/components/AgentCard.class.ts
index 20c1984b..18475074 100644
--- a/packages/app/src/builder-ui/components/AgentCard.class.ts
+++ b/packages/app/src/builder-ui/components/AgentCard.class.ts
@@ -1,5 +1,5 @@
import { TooltipV2 } from '@src/react/shared/components/_legacy/ui/tooltip/tooltipV2';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import interact from 'interactjs';
import jsPlumb from 'jsplumb';
import EventEmitter from '../EventEmitter.class';
@@ -608,7 +608,7 @@ export class AgentCard extends EventEmitter {
destroyCanvasContextMenu();
e.stopPropagation();
- PostHog.track('app_preview_as_chatbot_click', {});
+ Observability.userBehavior.recordInteraction('app_preview_as_chatbot_click', {});
const embodimentTestButton = document.querySelector('#btn-emb-chatbot-main');
const embodimentOpened = document.querySelector(
diff --git a/packages/app/src/builder-ui/components/Component.class/index.ts b/packages/app/src/builder-ui/components/Component.class/index.ts
index 5dc1c2a2..a3a54a4c 100644
--- a/packages/app/src/builder-ui/components/Component.class/index.ts
+++ b/packages/app/src/builder-ui/components/Component.class/index.ts
@@ -11,7 +11,7 @@ import { readFormValues, syncCompositeValues } from '../../ui/form';
import { ComponentDocLinks } from '@src/builder-ui/enums/doc-links.enum';
import { errorToast, successToast, warningToast } from '@src/shared/components/toast';
import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { jsonrepair } from 'jsonrepair';
import { isEqual } from 'lodash-es';
import { TooltipV2 } from '../../../react/shared/components/_legacy/ui/tooltip/tooltipV2';
@@ -525,7 +525,7 @@ export class Component extends EventEmitter {
`Missing Settings ${missingSettings.map((e) => e.name).join(', ')}`,
'alert pointer',
() => {
- PostHog.track('app_component_alert_click', {
+ Observability.userBehavior.recordInteraction('app_component_alert_click', {
type: 'missing settings',
});
this.editSettings();
@@ -625,7 +625,7 @@ export class Component extends EventEmitter {
if (missingSettings.length > 0) {
this.addComponentMessage(`Missing Settings`, 'alert pointer', () => {
- PostHog.track('app_component_alert_click', {
+ Observability.userBehavior.recordInteraction('app_component_alert_click', {
type: 'missing settings',
});
this.editSettings();
@@ -747,7 +747,7 @@ export class Component extends EventEmitter {
`Missing Key "${keyName}"`,
'alert pointer',
() => {
- PostHog.track('app_component_alert_click', {
+ Observability.userBehavior.recordInteraction('app_component_alert_click', {
type: 'missing key',
});
missingKeyMessageClickHandler.bind(this, keyName)();
@@ -2935,7 +2935,7 @@ export class Component extends EventEmitter {
operation: 'step' | 'run' = 'step',
prefillValues?: Record<string, any>,
) {
- PostHog.track('app_debug_inject_click', {});
+ Observability.userBehavior.recordInteraction('app_debug_inject_click', {});
event.stopPropagation();
event.stopImmediatePropagation();
const debugBtn = this.domElement.querySelector('.btn-debug');
@@ -3515,7 +3515,7 @@ function addMissingKey({
await saveKey({ ...fieldValues, apiKey: mockKey }, dialog);
// #region enable mock data
- PostHog.track('app_mock_screen_impression', {
+ Observability.userBehavior.recordInteraction('app_mock_screen_impression', {
source: 'skip_and_set_mock_data',
});
await saveMockOutputs(component);
diff --git a/packages/app/src/builder-ui/components/Component.class/mock-data-handler.ts b/packages/app/src/builder-ui/components/Component.class/mock-data-handler.ts
index f624e7fe..423b655a 100644
--- a/packages/app/src/builder-ui/components/Component.class/mock-data-handler.ts
+++ b/packages/app/src/builder-ui/components/Component.class/mock-data-handler.ts
@@ -1,4 +1,4 @@
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { lsCache } from '../../../shared/Cache.class';
import { MOCK_DATA_CACHE_KEY } from '../../../shared/constants/general';
import { JSON_FIELD_CLASS } from '../../constants';
@@ -210,7 +210,7 @@ export function saveMockOutputs(component: Component) {
try {
await insertOrUpdateMockData(component.uid, { enabled: true, data: { outputs } });
- PostHog.track('app_set_mock_data', {});
+ Observability.userBehavior.recordFeatureUsage('app_set_mock_data', {});
resolve('saved');
} finally {
@@ -441,7 +441,7 @@ export async function addMockDataToggleButton(component: Component) {
await insertOrUpdateMockData(component.uid, { enabled: false });
MockDataToggleButtonState.turnOff(component);
} else {
- PostHog.track('app_mock_screen_impression', {
+ Observability.userBehavior.recordInteraction('app_mock_screen_impression', {
source: 'use_mock_data_button',
});
await saveMockOutputs(component);
diff --git a/packages/app/src/builder-ui/components/Component.class/settings-editor.ts b/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
index f7507dee..c295ccc9 100644
--- a/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
+++ b/packages/app/src/builder-ui/components/Component.class/settings-editor.ts
@@ -1,5 +1,5 @@
import { errorToast, successToast } from '@src/shared/components/toast';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { Component } from '.';
import { FEATURE_FLAGS } from '../../../shared/constants/featureflags';
import {
@@ -112,7 +112,7 @@ async function onComponentLoad(sidebar) {
const isDebugCurrentlyOn = debugSwitcher && debugSwitcher.classList.contains('active');
// Fire telemetry event
- PostHog.track('test_with_debug_component_sidebar_clicked', {
+ Observability.userBehavior.recordInteraction('test_with_debug_component_sidebar_clicked', {
source: 'component_settings_sidebar',
componentType: component.constructor.name,
componentId: component.uid,
diff --git a/packages/app/src/builder-ui/debugger.ts b/packages/app/src/builder-ui/debugger.ts
index 324a1abc..6b9634c0 100644
--- a/packages/app/src/builder-ui/debugger.ts
+++ b/packages/app/src/builder-ui/debugger.ts
@@ -1,4 +1,5 @@
import { errorToast, successToast, warningToast } from '@src/shared/components/toast';
+import { Observability } from '@src/shared/observability';
import { PostHog } from '@src/shared/posthog';
import interact from 'interactjs';
import { jsonrepair } from 'jsonrepair';
@@ -142,7 +143,10 @@ function toggleSwitch(on: boolean) {
const debugSwitcherMessage = document?.querySelector('.debug-switcher-message');
if (on) {
- PostHog.track('debug_button_click', { position: 'bottom center of builder', type: 'debug' });
+ Observability.userBehavior.recordInteraction('debug_button_click', {
+ position: 'bottom center of builder',
+ type: 'debug',
+ });
}
// if (switcherText?.classList.contains('hidden')) {
// if (on) {
@@ -392,7 +396,10 @@ export async function init() {
const attachBtn = document.getElementById('debug-menubtn-attach');
runBtn?.addEventListener('click', async (event) => {
console.log('debug run');
- PostHog.track('debug_button_click', { position: 'bottom center of builder', type: 'run' });
+ Observability.userBehavior.recordInteraction('debug_button_click', {
+ position: 'bottom center of builder',
+ type: 'run',
+ });
const playIcon = runBtn.querySelector('.mif-play');
const stopIcon = runBtn.querySelector('.mif-pause');
const isRunning = runBtn.classList.contains('running');
@@ -432,7 +439,10 @@ export async function init() {
});
stepBtn.addEventListener('click', async (event) => {
console.log('debug Step');
- PostHog.track('debug_button_click', { position: 'bottom center of builder', type: 'step' });
+ Observability.userBehavior.recordInteraction('debug_button_click', {
+ position: 'bottom center of builder',
+ type: 'step',
+ });
const agent = workspace.agent;
if (!debugSessions?.[agent.id]?.sessionID) {
_openDebugDialog(event, 'step');
@@ -487,7 +497,10 @@ export async function init() {
attachBtn.addEventListener('click', async (e) => {
//attach to a live debug session
- PostHog.track('debug_button_click', { position: 'bottom center of builder', type: 'attach' });
+ Observability.userBehavior.recordInteraction('debug_button_click', {
+ position: 'bottom center of builder',
+ type: 'attach',
+ });
log('Attaching to live debug session ...');
const agent = workspace.agent;
if (!agent) return;
@@ -522,7 +535,10 @@ export async function init() {
});
document.getElementById('debug-menubtn-stop').addEventListener('click', async (e) => {
- PostHog.track('debug_button_click', { position: 'bottom center of builder', type: 'stop' });
+ Observability.userBehavior.recordInteraction('debug_button_click', {
+ position: 'bottom center of builder',
+ type: 'stop',
+ });
stopDebugSession();
runBtn.removeAttribute('disabled');
@@ -610,7 +626,7 @@ export async function runDebug() {
runBtn.classList.add('running');
isRunning = true;
- PostHog.track('app_run_agent', {});
+ Observability.userBehavior.recordFeatureUsage('app_run_agent', {});
let sessionID;
let processComponents = true;
@@ -652,7 +668,10 @@ export async function runDebug() {
}
console.log('debug run end');
- PostHog.track('app_workflow_test_completed', { status: workflowStatus, source: 'debugger' });
+ Observability.userBehavior.recordWorkflowCompletion('app_workflow_test_completed', {
+ status: workflowStatus,
+ source: 'debugger',
+ });
runTooltipLabel.innerHTML = 'Run';
runBtn.classList.remove('running');
diff --git a/packages/app/src/builder-ui/pages/builder/components-menu.ts b/packages/app/src/builder-ui/pages/builder/components-menu.ts
index 68592d18..9e63d652 100644
--- a/packages/app/src/builder-ui/pages/builder/components-menu.ts
+++ b/packages/app/src/builder-ui/pages/builder/components-menu.ts
@@ -5,7 +5,7 @@ import { Workspace } from '../../workspace/Workspace.class';
import { PRICING_PLAN_REDIRECT } from '@react/shared/constants/navigation';
import { V4_ENTERPRISE_PLANS } from '@src/react/features/agent-settings/constants';
import { LEGACY_PLANS } from '@src/shared/constants/general';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import interact from 'interactjs';
import { Agent } from '../../Agent.class';
import config from '../../config';
@@ -748,7 +748,7 @@ function setupBuilderMenuDragDrop() {
return;
}
- Analytics.track('app_component_used', {
+ Observability.userBehavior.recordFeatureUsage('app_component_used', {
name: event.relatedTarget.getAttribute('smt-component'),
type: !!templateId ? 'integration' : 'component',
});
@@ -914,7 +914,7 @@ function setupBuilderMenuDragDrop() {
}
function renderUpgradeModal() {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: '/builder',
source: 'adding integrations to the agent',
});
@@ -940,7 +940,7 @@ function renderUpgradeModal() {
cssClass:
'bg-primary-100 text-white rounded-md px-4 py-1.5 hover:opacity-75 cursor-pointer w-full',
callback: (_, dialog) => {
- Analytics.track('upgrade_click', {
+ Observability.userBehavior.recordInteraction('upgrade_click', {
page_url: '/builder',
source: 'adding integrations in the agent',
});
@@ -977,7 +977,7 @@ function renderCompUpgradeModal({
page_url: string;
};
}) {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: analytics.page_url,
source: analytics.source,
});
@@ -1090,7 +1090,7 @@ function isLegacyPlan() {
}
function renderRestrictedAccessModal(feature: string) {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: '/builder',
source: `adding ${feature}`,
});
@@ -1148,7 +1148,7 @@ function renderRestrictedAccessModal(feature: string) {
}
function renderRestrictedAccessModalWebTools() {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: '/builder',
source: 'adding web tools',
});
diff --git a/packages/app/src/builder-ui/tutorials/index.ts b/packages/app/src/builder-ui/tutorials/index.ts
index b2801a65..c481335b 100644
--- a/packages/app/src/builder-ui/tutorials/index.ts
+++ b/packages/app/src/builder-ui/tutorials/index.ts
@@ -2,7 +2,7 @@ import { authStore } from '@shared/state_stores/auth';
import { userSettingKeys } from '@shared/userSettingKeys';
import { getUserSettings, saveUserSettings } from '@src/react/shared/hooks/useUserSettings';
import { TUTORIAL_CUTOFF_DATE } from '@src/shared/constants/tutorial';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
export const builderPageTutorialWorkflow = async () => {
const userInfo = authStore.getState().userInfo;
@@ -32,7 +32,7 @@ export const builderPageTutorialWorkflow = async () => {
},
onReset: () => {
// Called when overlay is about to be cleared
- Analytics.track('builder_page_tutorial_completed', {
+ Observability.userBehavior.recordWorkflowCompletion('builder_page_tutorial_completed', {
page_url: '/builder',
source: 'Tutorial completed on builder page onboarding',
});
diff --git a/packages/app/src/builder-ui/ui/dialogs.ts b/packages/app/src/builder-ui/ui/dialogs.ts
index 509b4f30..f9d41c45 100644
--- a/packages/app/src/builder-ui/ui/dialogs.ts
+++ b/packages/app/src/builder-ui/ui/dialogs.ts
@@ -17,7 +17,7 @@ import {
import { createForm, handleTemplateVars, readFormValidation, readFormValues } from './form/';
import { errorToast } from '@src/shared/components/toast';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import yaml from 'js-yaml';
import { debounce } from 'lodash-es';
import { EMBODIMENT_DESCRIPTIONS } from '../../shared/constants/general';
@@ -289,7 +289,7 @@ document.addEventListener('DOMContentLoaded', async () => {
const chatbotButton = document.getElementById('btn-emb-chatbot-main');
if (chatbotButton) {
chatbotButton.addEventListener('click', async (event) => {
- PostHog.track('test_embodiment_click', {
+ Observability.userBehavior.recordInteraction('test_embodiment_click', {
position: 'top right of builder dropdown',
});
@@ -431,14 +431,14 @@ export async function createEmbodimentSidebar(title?, content?, actions?, toolti
switch (key.toLowerCase()) {
case 'llm':
if (window.workspace) {
- PostHog.track('agentLLM_embodiment_click', {
+ Observability.userBehavior.recordInteraction('agentLLM_embodiment_click', {
position: 'embodiment sidebar tab',
});
openLLMEmbodiment(window.workspace, embodimentHandlers.openEmbodimentDialog);
}
break;
case 'api':
- PostHog.track('api_embodiment_click', {
+ Observability.userBehavior.recordInteraction('api_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openAPIEmbodiment?.();
@@ -446,7 +446,7 @@ export async function createEmbodimentSidebar(title?, content?, actions?, toolti
case 'chat':
const chatContCls = convertTitleToClass(EMBODIMENT_DESCRIPTIONS.chat.title);
if (!sidebarContent.querySelector(`.${chatContCls}`)) {
- PostHog.track('chatbot_embodiment_click', {
+ Observability.userBehavior.recordInteraction('chatbot_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openChatbotEmbodiment?.();
@@ -471,26 +471,26 @@ export async function createEmbodimentSidebar(title?, content?, actions?, toolti
}
break;
case 'chatgpt':
- PostHog.track('chatgpt_embodiment_click', {
+ Observability.userBehavior.recordInteraction('chatgpt_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openChatGPTEmbodiment?.();
break;
case 'postman':
- PostHog.track('postman_embodiment_click', {
+ Observability.userBehavior.recordInteraction('postman_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openPostmanEmbodiment?.();
break;
case 'alexa':
- PostHog.track('alexa_embodiment_click', {
+ Observability.userBehavior.recordInteraction('alexa_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openAlexaEmbodiment?.();
break;
case 'agent_skill':
const agentSkillContCls = convertTitleToClass(EMBODIMENT_DESCRIPTIONS.agent_skill.title);
- PostHog.track('form_preview_embodiment_click', {
+ Observability.userBehavior.recordInteraction('form_preview_embodiment_click', {
position: 'embodiment sidebar tab',
});
if (!sidebarContent.querySelector(`.${agentSkillContCls}`)) {
@@ -511,7 +511,7 @@ export async function createEmbodimentSidebar(title?, content?, actions?, toolti
break;
case 'mcp':
- PostHog.track('mcp_embodiment_click', {
+ Observability.userBehavior.recordInteraction('mcp_embodiment_click', {
position: 'embodiment sidebar tab',
});
embodimentHandlers.openMCPEmbodiment?.();
diff --git a/packages/app/src/react/app/routes.tsx b/packages/app/src/react/app/routes.tsx
index a9fc4bb3..cc7c8e68 100644
--- a/packages/app/src/react/app/routes.tsx
+++ b/packages/app/src/react/app/routes.tsx
@@ -6,7 +6,7 @@ import { Spinner } from '@src/react/shared/components/ui/spinner';
import { useAuthCtx } from '@src/react/shared/contexts/auth.context';
import { IPageRoute } from '@src/react/shared/types/route';
import { FEATURE_FLAGS } from '@src/shared/constants/featureflags';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { useEffect } from 'react';
import { Route, Routes, useNavigate } from 'react-router-dom';
import { useGetBookAnIntroCall } from '../features/onboarding/hooks/useGetUserOnboardingSettings';
@@ -68,7 +68,7 @@ const RoutesWrapper = ({ pages }: { pages: IPageRoute[] }) => {
const { name: planName, isDefaultPlan, isCustomPlan } = subs?.plan ?? {};
const { name, jobtype, jobRoleLabel } = userOnBoarding ?? {};
- PostHog.identify(id, {
+ Observability.userIdentity.identifyUser(id, {
name,
email,
autenticationSource: avatar
diff --git a/packages/app/src/react/features/agent-settings/components/Assignments/ChatWithAgentWidget.tsx b/packages/app/src/react/features/agent-settings/components/Assignments/ChatWithAgentWidget.tsx
index 10811b93..c94a6cb3 100644
--- a/packages/app/src/react/features/agent-settings/components/Assignments/ChatWithAgentWidget.tsx
+++ b/packages/app/src/react/features/agent-settings/components/Assignments/ChatWithAgentWidget.tsx
@@ -2,8 +2,8 @@ import WidgetCard from '@react/features/agent-settings/components/WidgetCard';
import { useAgentSettingsCtx } from '@react/features/agent-settings/contexts/agent-settings.context';
import { PRIMARY_BUTTON_STYLE, SECONDARY_BUTTON_STYLE } from '@react/shared/constants/style';
import { useAuthCtx } from '@react/shared/contexts/auth.context';
+import { Observability } from '@src/shared/observability';
import { EVENTS } from '@src/shared/posthog/constants/events';
-import { PostHog } from '@src/shared/posthog/index';
import classNames from 'classnames';
import { Tooltip } from 'flowbite-react';
import { Info } from 'lucide-react';
@@ -115,9 +115,12 @@ const ChatWithAgentWidget = ({ isWriteAccess, isAgentDeployed }: Props) => {
`${isAgentDeployed ? PRIMARY_BUTTON_STYLE : SECONDARY_BUTTON_STYLE}`,
)}
onClick={(e) => {
- PostHog.track(EVENTS.AGENT_SETTINGS_EVENTS.app_chat_with_agent, {
- source: 'agent settings',
- });
+ Observability.userBehavior.recordFeatureUsage(
+ EVENTS.AGENT_SETTINGS_EVENTS.app_chat_with_agent,
+ {
+ source: 'agent settings',
+ },
+ );
!isAgentDeployed && e.preventDefault();
}}
target="_blank"
diff --git a/packages/app/src/react/features/agent-settings/components/CapabilitiesWidget/index.tsx b/packages/app/src/react/features/agent-settings/components/CapabilitiesWidget/index.tsx
index ea2111e0..46e4ff3c 100644
--- a/packages/app/src/react/features/agent-settings/components/CapabilitiesWidget/index.tsx
+++ b/packages/app/src/react/features/agent-settings/components/CapabilitiesWidget/index.tsx
@@ -7,7 +7,7 @@ import { Component } from '@react/shared/types/agent-data.types';
import { EVENTS } from '@shared/posthog/constants/events';
import { CloseIcon } from '@src/react/shared/components/svgs';
import { plugins, PluginTarget, PluginType } from '@src/react/shared/plugins/Plugins';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import { Badge, Tooltip } from 'flowbite-react';
import { Info } from 'lucide-react';
@@ -121,9 +121,12 @@ function Endpoint({ component }: { component: Component }) {
<button
className=" flex group-hover:flex items-center"
onClick={() => {
- PostHog.track(EVENTS.AGENT_SETTINGS_EVENTS.app_agent_skills_click, {
- button: 'call',
- });
+ Observability.userBehavior.recordFeatureUsage(
+ EVENTS.AGENT_SETTINGS_EVENTS.app_agent_skills_click,
+ {
+ button: 'call',
+ },
+ );
setIsTriggeringSkill(true);
}}
>
diff --git a/packages/app/src/react/features/agent-settings/components/OverviewWidgetsContainer/index.tsx b/packages/app/src/react/features/agent-settings/components/OverviewWidgetsContainer/index.tsx
index 20d8cd32..182c18c5 100644
--- a/packages/app/src/react/features/agent-settings/components/OverviewWidgetsContainer/index.tsx
+++ b/packages/app/src/react/features/agent-settings/components/OverviewWidgetsContainer/index.tsx
@@ -9,8 +9,8 @@ import { Agent } from '@react/shared/types/agent-data.types';
import { Embodiment } from '@react/shared/types/api-results.types';
import { LLMFormController } from '@src/builder-ui/helpers/LLMFormController.helper';
import { errorToast } from '@src/shared/components/toast';
+import { Observability } from '@src/shared/observability';
import { EVENTS } from '@src/shared/posthog/constants/events';
-import { PostHog } from '@src/shared/posthog/index';
import { LLMRegistry } from '@src/shared/services/LLMRegistry.service';
import { llmModelsStore } from '@src/shared/state_stores/llm-models';
import { useQuery, useQueryClient } from '@tanstack/react-query';
@@ -363,9 +363,12 @@ const OverviewWidgetsContainer = ({ isWriteAccess }: { isWriteAccess: boolean })
await Promise.all(promises);
if (postHogEvent.app_LLM_selected) {
- await PostHog.track(EVENTS.AGENT_SETTINGS_EVENTS.app_LLM_selected, {
- model: formik.values.chatGptModel,
- });
+ await Observability.userBehavior.recordFeatureUsage(
+ EVENTS.AGENT_SETTINGS_EVENTS.app_LLM_selected,
+ {
+ model: formik.values.chatGptModel,
+ },
+ );
setPostHogEvent((prev) => ({ ...prev, app_LLM_selected: null }));
}
diff --git a/packages/app/src/react/features/agent-settings/components/widget-subscribe-info.tsx b/packages/app/src/react/features/agent-settings/components/widget-subscribe-info.tsx
index cfe527b9..89135175 100644
--- a/packages/app/src/react/features/agent-settings/components/widget-subscribe-info.tsx
+++ b/packages/app/src/react/features/agent-settings/components/widget-subscribe-info.tsx
@@ -1,6 +1,6 @@
import { Button } from '@react/shared/components/ui/newDesign/button';
import { PRICING_PLAN_REDIRECT } from '@react/shared/constants/navigation';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import { useEffect } from 'react';
import config from '../../../../builder-ui/config';
@@ -14,14 +14,14 @@ type Props = {
const WidgetSubscribeInfo = ({ infoText, analytics }: Props) => {
useEffect(() => {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: analytics?.page_url,
source: analytics?.source,
});
}, []);
const handleUpgrade = () => {
- Analytics.track('upgrade_click', {
+ Observability.userBehavior.recordInteraction('upgrade_click', {
page_url: analytics?.page_url,
source: analytics?.source,
});
diff --git a/packages/app/src/react/features/agent-settings/dialogs/ChatBot.tsx b/packages/app/src/react/features/agent-settings/dialogs/ChatBot.tsx
index 163ee163..651c88bc 100644
--- a/packages/app/src/react/features/agent-settings/dialogs/ChatBot.tsx
+++ b/packages/app/src/react/features/agent-settings/dialogs/ChatBot.tsx
@@ -27,7 +27,7 @@ import { extractError } from '@react/shared/utils/errors';
import { validateDomains, validateURL } from '@react/shared/utils/utils';
import { ChatbotEmbodimentData } from '@src/react/shared/types/api-results.types';
import { errorToast, successToast, warningToast } from '@src/shared/components/toast';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import classNames from 'classnames';
import { Tooltip } from 'flowbite-react';
import { Info } from 'lucide-react';
@@ -601,10 +601,13 @@ const ChatBotDialog = ({
onChange={(e) => {
setIsChatBotFullScreen(e.target.checked);
if (e.target.checked) {
- Analytics.track('app_chatbot_message_view_enabled', {
- description:
- 'Event is triggered when the message view checkbox in chatbot configurations is ticked',
- });
+ Observability.userBehavior.recordFeatureUsage(
+ 'app_chatbot_message_view_enabled',
+ {
+ description:
+ 'Event is triggered when the message view checkbox in chatbot configurations is ticked',
+ },
+ );
}
}}
/>
diff --git a/packages/app/src/react/features/agent-settings/pages/AgentSettingsPage.tsx b/packages/app/src/react/features/agent-settings/pages/AgentSettingsPage.tsx
index a01962ab..11896ce2 100644
--- a/packages/app/src/react/features/agent-settings/pages/AgentSettingsPage.tsx
+++ b/packages/app/src/react/features/agent-settings/pages/AgentSettingsPage.tsx
@@ -16,7 +16,7 @@ import { useAuthCtx } from '@react/shared/contexts/auth.context';
import config from '@src/builder-ui/config';
import FullScreenError from '@src/react/features/error-pages/pages/FullScreenError';
import { plugins, PluginTarget, PluginType } from '@src/react/shared/plugins/Plugins';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import { Breadcrumb } from 'flowbite-react';
import { useEffect, useRef, useState } from 'react';
import { FaHome } from 'react-icons/fa';
@@ -62,16 +62,18 @@ export const AgentSettingTabs = () => {
const isWriteAccess = pageAccess.write;
const isOnPaidPlan = userInfo?.subs?.plan?.paid ?? false;
- const pluginWidgets = plugins.getPluginsByTarget(PluginTarget.AgentSettingsWidgets, PluginType.Config).flatMap((plugin) => (plugin as any).config).reduce((acc, plugin) => {
- Object.keys(plugin).forEach((key) => {
- if (!acc[key]) {
- acc[key] = [];
- }
- acc[key].push(...plugin[key]);
- });
- return acc;
- }, {});
-
+ const pluginWidgets = plugins
+ .getPluginsByTarget(PluginTarget.AgentSettingsWidgets, PluginType.Config)
+ .flatMap((plugin) => (plugin as any).config)
+ .reduce((acc, plugin) => {
+ Object.keys(plugin).forEach((key) => {
+ if (!acc[key]) {
+ acc[key] = [];
+ }
+ acc[key].push(...plugin[key]);
+ });
+ return acc;
+ }, {});
const baseWidgets: Record<keyof typeof BaseAgentSettingsTabs, React.ReactNode[]> = {
Overview: [<OverviewWidgetsContainer isWriteAccess={isWriteAccess} />],
@@ -98,8 +100,7 @@ export const AgentSettingTabs = () => {
],
};
- let mergedWidgets = {...baseWidgets, ...pluginWidgets};
-
+ let mergedWidgets = { ...baseWidgets, ...pluginWidgets };
// we need to make sure that the original widgets objects are not overridden by the plugin widgets if the same key exists
Object.keys(baseWidgets).forEach((key) => {
@@ -108,8 +109,6 @@ export const AgentSettingTabs = () => {
}
});
-
-
return (
<>
<div className="flex justify-around mb-6 border-solid border-b-2 border-gray-200">
@@ -173,7 +172,7 @@ export const AgentSettingsPageBody = (props: Props) => {
);
const handleUpgrade = () => {
- Analytics.track('upgrade_click', {
+ Observability.userBehavior.recordInteraction('upgrade_click', {
page_url: '/agent_settings',
source: 'upgrade button displayed alongside My Workflow',
});
@@ -181,7 +180,7 @@ export const AgentSettingsPageBody = (props: Props) => {
};
useEffect(() => {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: '/agent_settings',
source: 'upgrade button displayed alongside My Workflow',
});
diff --git a/packages/app/src/react/features/agents/components/meta/up-sell.tsx b/packages/app/src/react/features/agents/components/meta/up-sell.tsx
index 5559168d..8b63f6bd 100644
--- a/packages/app/src/react/features/agents/components/meta/up-sell.tsx
+++ b/packages/app/src/react/features/agents/components/meta/up-sell.tsx
@@ -2,7 +2,7 @@ import { ReactNode, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Modal from '@react/shared/components/ui/modals/Modal';
-import { Analytics } from '@shared/posthog/services/analytics';
+import { Observability } from '@shared/observability';
type Props = {
body?: ReactNode;
@@ -14,14 +14,14 @@ type Props = {
const UpSellModal = ({ onClose, children, analytics }: Props) => {
const navigate = useNavigate();
useEffect(() => {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: analytics?.page_url,
source: analytics.source,
});
}, []); // eslint-disable-line react-hooks/exhaustive-deps
const handleUpgradeClick = () => {
- Analytics.track('upgrade_click', {
+ Observability.userBehavior.recordInteraction('upgrade_click', {
page_url: analytics?.page_url,
source: analytics?.source,
});
diff --git a/packages/app/src/react/features/agents/components/modals/deploy-agent-modal.tsx b/packages/app/src/react/features/agents/components/modals/deploy-agent-modal.tsx
index 9f051825..722ec67f 100644
--- a/packages/app/src/react/features/agents/components/modals/deploy-agent-modal.tsx
+++ b/packages/app/src/react/features/agents/components/modals/deploy-agent-modal.tsx
@@ -21,7 +21,7 @@ import FormEmbodimentModal from '@src/react/features/embodiments/form-embodiment
import LovableEmbodimentModal from '@src/react/features/embodiments/lovable-embodiment-modal';
import { errorToast, successToast } from '@src/shared/components/toast';
import { SMYTHOS_DOCS_URL } from '@src/shared/constants/general';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import { builderStore } from '@src/shared/state_stores/builder/store';
import { useQuery } from '@tanstack/react-query';
import { Tooltip } from 'flowbite-react';
@@ -339,14 +339,14 @@ function DeployAgentModal({ userInfo, deploymentSidebarCtx }) {
},
operation: 'insertOrUpdate',
});
- Analytics.track('app_deploy_first_agent', {
+ Observability.userBehavior.recordWorkflowCompletion('app_deploy_first_agent', {
createdAt: new Date().toISOString().split('T')[0],
});
- Analytics.track('app_deploy_agent', {
+ Observability.userBehavior.recordFeatureUsage('app_deploy_agent', {
createdAt: new Date().toISOString().split('T')[0],
});
} else {
- Analytics.track('app_deploy_agent', {
+ Observability.userBehavior.recordFeatureUsage('app_deploy_agent', {
createdAt: new Date().toISOString().split('T')[0],
});
}
diff --git a/packages/app/src/react/features/agents/hooks/useAgentsPageTutorial.ts b/packages/app/src/react/features/agents/hooks/useAgentsPageTutorial.ts
index cac389e7..ef45c0f9 100644
--- a/packages/app/src/react/features/agents/hooks/useAgentsPageTutorial.ts
+++ b/packages/app/src/react/features/agents/hooks/useAgentsPageTutorial.ts
@@ -1,7 +1,7 @@
import { useAuthCtx } from '@react/shared/contexts/auth.context';
import { useGetUserSettings, useStoreUserSettings } from '@react/shared/hooks/useUserSettings';
import { TUTORIAL_CUTOFF_DATE } from '@src/shared/constants/tutorial';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import { userSettingKeys } from '@src/shared/userSettingKeys';
import { useEffect, useRef } from 'react';
@@ -68,7 +68,7 @@ export function useAgentsPageTutorial(options: UseAgentsPageTutorialOptions = {}
},
onReset: () => {
// Called when overlay is about to be cleared
- Analytics.track('home_page_tutorial_completed', {
+ Observability.userBehavior.recordWorkflowCompletion('home_page_tutorial_completed', {
page_url: '/agents',
source: 'Tutorial completed on home page onboarding',
});
diff --git a/packages/app/src/react/features/agents/pages/AgentsPage.tsx b/packages/app/src/react/features/agents/pages/AgentsPage.tsx
index 78745dc9..43ae07c8 100644
--- a/packages/app/src/react/features/agents/pages/AgentsPage.tsx
+++ b/packages/app/src/react/features/agents/pages/AgentsPage.tsx
@@ -10,7 +10,7 @@ import { useAuthCtx } from '@react/shared/contexts/auth.context';
import { OnboardingTaskType } from '@react/shared/types/onboard.types';
import { FEATURE_FLAGS } from '@shared/constants/featureflags';
import { V4_ALL_PLANS } from '@shared/constants/general';
-import { Analytics } from '@shared/posthog/services/analytics';
+import { Observability } from '@shared/observability';
import { UserSettingsKey } from '@src/backend/types/user-data';
import { PluginComponents } from '@src/react/shared/plugins/PluginComponents';
import { PluginTarget } from '@src/react/shared/plugins/Plugins';
@@ -94,7 +94,9 @@ function AgentsPage() {
},
operation: 'insertOrUpdate',
});
- Analytics.track('app_build_first_agent', { createdAt: sortedAgents[0]?.createdAt });
+ Observability.userBehavior.recordWorkflowCompletion('app_build_first_agent', {
+ createdAt: sortedAgents[0]?.createdAt,
+ });
}
}, [agents, isUserSettingsFetched]);
diff --git a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
index 0be20465..82f6b43b 100644
--- a/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
+++ b/packages/app/src/react/features/ai-chat/pages/ai-chat.tsx
@@ -19,8 +19,8 @@ import {
} from '@react/features/ai-chat/hooks';
import { FILE_LIMITS } from '@react/features/ai-chat/utils/file';
import { useAgent } from '@react/shared/hooks/agent';
+import { Observability } from '@shared/observability';
import { EVENTS } from '@shared/posthog/constants/events';
-import { Analytics } from '@shared/posthog/services/analytics';
const AIChat = () => {
const params = useParams<{ agentId: string }>();
@@ -118,8 +118,8 @@ const AIChat = () => {
clearMessages();
await createNewChatSession();
chatInputRef.current?.focus();
- Analytics.track(EVENTS.CHAT_EVENTS.SESSION_END);
- Analytics.track(EVENTS.CHAT_EVENTS.SESSION_START);
+ Observability.userBehavior.recordInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
+ Observability.userBehavior.recordInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
}, [createNewChatSession, clearMessages, stopGenerating, setShowScrollButton]);
useEffect(() => {
@@ -138,8 +138,8 @@ const AIChat = () => {
}, [isAgentLoading, inputDisabled]);
useEffect(() => {
- Analytics.track(EVENTS.CHAT_EVENTS.SESSION_START);
- return () => Analytics.track(EVENTS.CHAT_EVENTS.SESSION_END);
+ Observability.userBehavior.recordInteraction(EVENTS.CHAT_EVENTS.SESSION_START);
+ return () => Observability.userBehavior.recordInteraction(EVENTS.CHAT_EVENTS.SESSION_END);
}, []);
// Fast context value - minimal dependencies
diff --git a/packages/app/src/react/features/builder/components/agent-deployment-sidebar/DeploymentsHistory.tsx b/packages/app/src/react/features/builder/components/agent-deployment-sidebar/DeploymentsHistory.tsx
index 6ff42443..5c5158a5 100644
--- a/packages/app/src/react/features/builder/components/agent-deployment-sidebar/DeploymentsHistory.tsx
+++ b/packages/app/src/react/features/builder/components/agent-deployment-sidebar/DeploymentsHistory.tsx
@@ -4,7 +4,7 @@ import { useDeploymentSidebarCtx } from '@src/react/features/builder/contexts/de
import { Spinner } from '@src/react/shared/components/ui/spinner';
import { useAuthCtx } from '@src/react/shared/contexts/auth.context';
import { Deployment } from '@src/react/shared/types/api-results.types';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import classNames from 'classnames';
import { useState } from 'react';
@@ -28,7 +28,7 @@ const DeploymentsHistory = () => {
const restoreVersionConfirmation = async (deploymentId: string) => {
if (!userInfo?.subs?.plan?.paid) {
- Analytics.track('upgrade_impression', {
+ Observability.userBehavior.recordInteraction('upgrade_impression', {
page_url: '/builder',
source: 'restoring previous version',
});
diff --git a/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/FormFill.tsx b/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/FormFill.tsx
index 810ceaa9..d495b830 100644
--- a/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/FormFill.tsx
+++ b/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/FormFill.tsx
@@ -2,8 +2,7 @@ import { generateComponentInputsSchema } from '@src/react/features/agent-setting
import AgentComponentInput from '@src/react/features/agent-settings/utils/AgentComponentInput';
import { useEndpointFormPreview } from '@src/react/features/builder/contexts/endpoint-form-preview-sidebar.context';
import { Button } from '@src/react/shared/components/ui/newDesign/button';
-import { PostHog } from '@src/shared/posthog';
-import { Analytics } from '@src/shared/posthog/services/analytics';
+import { Observability } from '@src/shared/observability';
import { Form, Formik } from 'formik';
import { useEffect, useRef } from 'react';
/**
@@ -18,15 +17,21 @@ const FormFill = ({ setIsFormVisible }: { setIsFormVisible: (value: boolean) =>
const dynamicValidationSchema = generateComponentInputsSchema(selectedSkill?.inputsTypes);
const handleSubmit = async (values: any, { resetForm }: { resetForm: () => void }) => {
setIsFormVisible(false);
- Analytics.track('app_form_preview_run_button_click', {});
+ Observability.userBehavior.recordInteraction('app_form_preview_run_button_click', {});
callSkillMutation.mutate(values, {
onSuccess: () => {
- PostHog.track('app_workflow_test_completed', { status: 'success', source: 'form preview' });
+ Observability.userBehavior.recordWorkflowCompletion('app_workflow_test_completed', {
+ status: 'success',
+ source: 'form preview',
+ });
setLastFormValues(values);
setView('home');
},
onError: () => {
- PostHog.track('app_workflow_test_completed', { status: 'failed', source: 'form preview' });
+ Observability.systemInsight.recordError('app_workflow_test_completed', {
+ status: 'failed',
+ source: 'form preview',
+ });
setLastFormValues(values);
setView('home');
},
diff --git a/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/ResponseView.tsx b/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/ResponseView.tsx
index 3a26194b..0effc929 100644
--- a/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/ResponseView.tsx
+++ b/packages/app/src/react/features/builder/components/endpoint-form-preview-sidebar/views/ResponseView.tsx
@@ -2,7 +2,7 @@ import PreviewableAsset from '@src/react/features/builder/components/endpoint-fo
import { useEndpointFormPreview } from '@src/react/features/builder/contexts/endpoint-form-preview-sidebar.context';
import { TextArea } from '@src/react/shared/components/ui/newDesign/textarea';
import { FEATURE_FLAGS } from '@src/shared/constants/featureflags';
-import { PostHog } from '@src/shared/posthog';
+import { Observability } from '@src/shared/observability';
import classNames from 'classnames';
import { useMemo, useRef, useState } from 'react';
import { FaCheck } from 'react-icons/fa';
@@ -40,7 +40,7 @@ const ResponseView = () => {
if (component && typeof component.openDebugDialog === 'function') {
// Fire telemetry event
const { PostHog } = await import('@src/shared/posthog');
- PostHog.track('debug_modal_opened', {
+ Observability.userBehavior.recordInteraction('debug_modal_opened', {
source: 'test_as_form',
});
@@ -56,7 +56,7 @@ const ResponseView = () => {
<span
className="font-semibold border-b border-solid pb-0.5 cursor-pointer text-blue-500 border-blue-500"
onClick={() => {
- PostHog.track('debug_api_modal_opened_test_as_form', {
+ Observability.userBehavior.recordInteraction('debug_api_modal_opened_test_as_form', {
source: 'test_as_form',
variant: 'control',
});
@@ -74,7 +74,7 @@ const ResponseView = () => {
<button
className="font-semibold cursor-pointer text-blue-500 bg-transparent hover:text-smythos-blue focus:outline-none py-2 rounded-lg text-sm transition-colors"
onClick={() => {
- PostHog.track('debug_api_modal_opened_test_as_form', {
+ Observability.userBehavior.recordInteraction('debug_api_modal_opened_test_as_form', {
source: 'test_as_form',
variant: 'variant_1',
});
diff --git a/packages/app/src/react/features/embodiments/embodiment-settings.ts b/packages/app/src/react/features/embodiments/embodiment-settings.ts
index fd493aeb..3361b556 100644
--- a/packages/app/src/react/features/embodiments/embodiment-settings.ts
+++ b/packages/app/src/react/features/embodiments/embodiment-settings.ts
@@ -2,8 +2,8 @@ import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useEffect, useState } from 'react';
import { Agent as AgentInstance } from '../../../builder-ui/Agent.class';
import config from '../../../builder-ui/config';
+import { Observability } from '../../../shared/observability';
import { EVENTS } from '../../../shared/posthog/constants/events';
-import { PostHog } from '../../../shared/posthog/index';
import { useAuthCtx } from '../../shared/contexts/auth.context';
import { Embodiment } from '../../shared/types/api-results.types';
import { updateEmbodiment } from '../agent-settings/clients';
@@ -342,9 +342,12 @@ export const useAgentEmbodimentSettings = (
await updateEmbodiment(agentId, embodimentType, status);
if (status) {
- PostHog.track(EVENTS.AGENT_SETTINGS_EVENTS.app_work_location_toggle, {
- locationType: embodimentType.toLowerCase(),
- });
+ Observability.userBehavior.recordFeatureUsage(
+ EVENTS.AGENT_SETTINGS_EVENTS.app_work_location_toggle,
+ {
+ locationType: embodimentType.toLowerCase(),
+ },
+ );
}
updateAgentSettingsCache(embodimentType, formattedValue, false);
callCallback();
diff --git a/packages/app/src/react/shared/plugins/Plugins.ts b/packages/app/src/react/shared/plugins/Plugins.ts
index ea866214..5d946c5b 100644
--- a/packages/app/src/react/shared/plugins/Plugins.ts
+++ b/packages/app/src/react/shared/plugins/Plugins.ts
@@ -13,6 +13,30 @@ export enum PluginTarget {
AgentsPageGenerateAgentForm = 'agentsPage/generateAgentForm',
AgentsPageOnboardingTasks = 'agentsPage/onboardingTasks',
VaultPageSmythOSRecommendedModels = 'vaultPage/smythOSRecommendedModels',
+
+ /**
+ * UserBehaviorObservabilityProvider - Injected by enterprise edition to capture user interaction patterns
+ * Provides implementation for recording user actions, feature usage, and workflow completion metrics
+ * Default: No-op implementation in community edition
+ * Enterprise: PostHog-based implementation for product analytics
+ */
+ UserBehaviorObservabilityProvider = 'observability/userBehaviorProvider',
+
+ /**
+ * SystemInsightCaptureProvider - Injected by enterprise edition for system-level event monitoring
+ * Enables collection of system performance, error patterns, and operational metrics
+ * Default: No-op implementation in community edition
+ * Enterprise: PostHog-based implementation for system analytics
+ */
+ SystemInsightCaptureProvider = 'observability/systemInsightProvider',
+
+ /**
+ * UserIdentityContextProvider - Injected by enterprise edition to associate user context with observability data
+ * Manages user identity correlation across different monitoring surfaces
+ * Default: No-op implementation in community edition
+ * Enterprise: PostHog-based implementation for user identification
+ */
+ UserIdentityContextProvider = 'observability/userIdentityProvider',
}
export enum PluginType {
diff --git a/packages/app/src/shared/observability/README.md b/packages/app/src/shared/observability/README.md
new file mode 100644
index 00000000..c93462a0
--- /dev/null
+++ b/packages/app/src/shared/observability/README.md
@@ -0,0 +1,181 @@
+# Observability System
+
+This directory contains the plugin-based observability system for the SmythOS platform.
+
+## Overview
+
+The observability system provides a unified API for recording user behavior, system events, and performance metrics. It uses a plugin architecture to cleanly separate community and enterprise editions:
+
+- **Community Edition**: Uses no-op implementations (disabled by default)
+- **Enterprise Edition**: Injects PostHog-based implementations via plugins
+
+## Architecture
+
+### Files
+
+- **`types.ts`**: Interface definitions for observability providers
+- **`no-op-providers.ts`**: Default no-op implementations (zero overhead)
+- **`index.ts`**: Main API that uses the plugin system
+
+### Key Concepts
+
+1. **Plugin-Based**: Uses the existing plugin system (`@react/shared/plugins/Plugins`)
+2. **Disabled by Default**: Community edition has zero analytics overhead
+3. **Type-Safe**: Full TypeScript interfaces for all providers
+4. **Vendor-Agnostic**: Abstract interfaces allow any analytics backend
+
+## Usage
+
+### Import the API
+
+```typescript
+import { Observability } from '@src/shared/observability';
+```
+
+### Record User Interactions
+
+```typescript
+Observability.userBehavior.recordInteraction('button_clicked', {
+ buttonId: 'submit',
+ page: 'agent-settings',
+});
+```
+
+### Record Feature Usage
+
+```typescript
+Observability.userBehavior.recordFeatureUsage('agent_deployment', {
+ deploymentType: 'api',
+ modelProvider: 'openai',
+});
+```
+
+### Record Workflow Completions
+
+```typescript
+Observability.userBehavior.recordWorkflowCompletion('agent_creation', {
+ duration: 120,
+ success: true,
+});
+```
+
+### Record System Events
+
+```typescript
+Observability.systemInsight.recordSystemEvent('deployment_completed', {
+ agentId: 'agent-123',
+ success: true,
+});
+```
+
+### Record Errors
+
+```typescript
+Observability.systemInsight.recordError('api_call_failed', {
+ endpoint: '/api/agents',
+ errorMessage: error.message,
+});
+```
+
+### Record Performance Metrics
+
+```typescript
+Observability.systemInsight.recordPerformanceMetric('page_load_time', 1234, {
+ page: 'agents',
+});
+```
+
+### User Identification
+
+```typescript
+Observability.userIdentity.identifyUser('user-123', {
+ email: '[email protected]',
+ plan: 'enterprise',
+});
+```
+
+## How It Works
+
+1. **Plugin Registration** (Enterprise Only):
+ - Enterprise edition registers PostHog providers in `src/react/plugins.tsx`
+ - Uses `PluginTarget.UserBehaviorObservabilityProvider` and other targets
+ - Happens during app initialization
+
+2. **Lazy Loading**:
+ - Providers are lazy-loaded on first use
+ - Falls back to no-op implementation if no plugin registered
+
+3. **Zero Overhead**:
+ - In community edition, all methods are empty functions
+ - No performance impact when analytics are disabled
+
+## Plugin Targets
+
+Three plugin targets are available for provider registration:
+
+- `UserBehaviorObservabilityProvider`: User interactions and feature usage
+- `SystemInsightCaptureProvider`: System events and performance metrics
+- `UserIdentityContextProvider`: User identification and context
+
+## Documentation
+
+- **[Migration Guide](../../../../../docs/OBSERVABILITY_PLUGIN_SYSTEM.md)**: Complete guide for migrating from old Analytics API
+- **[Examples](../../../../../docs/OBSERVABILITY_EXAMPLES.md)**: Practical examples for common scenarios
+- **[Plugin System](../../react/shared/plugins/Plugins.ts)**: Core plugin infrastructure
+
+## For Enterprise Edition
+
+Enterprise implementations are in `src/shared/observability/` (not in community code).
+
+See `src/shared/observability/posthog-providers.ts` for PostHog implementations.
+
+## Advantages
+
+### For Community Users
+
+- No tracking or analytics by default
+- Zero performance overhead
+- Transparent and open source
+
+### For Enterprise Users
+
+- Full analytics capabilities
+- Product usage insights
+- Performance monitoring
+
+### For Developers
+
+- Single, consistent API
+- Easy to test (mock providers)
+- Type-safe with TypeScript
+- Follows existing patterns
+
+## Testing
+
+In tests, you can easily mock observability:
+
+```typescript
+// Mock the plugin to return your test provider
+jest.mock('@react/shared/plugins/Plugins', () => ({
+ plugins: {
+ getPluginsByTarget: () => [
+ {
+ type: 'config',
+ config: mockObservabilityProvider,
+ },
+ ],
+ },
+}));
+```
+
+## Best Practices
+
+1. **Be Specific**: Use descriptive event names
+2. **Add Context**: Include relevant properties
+3. **Handle Errors**: Observability should never break your app
+4. **Respect Privacy**: Don't log sensitive data
+5. **Test Locally**: Events work in dev with `isProd: false`
+
+## Questions?
+
+See the documentation linked above or reach out to the platform team.
diff --git a/packages/app/src/shared/observability/index.ts b/packages/app/src/shared/observability/index.ts
new file mode 100644
index 00000000..830116cf
--- /dev/null
+++ b/packages/app/src/shared/observability/index.ts
@@ -0,0 +1,194 @@
+/**
+ * Observability Service
+ *
+ * This module provides the main API for observability throughout the application.
+ * It uses the plugin system to allow enterprise editions to inject their own
+ * implementations while keeping the community edition free of analytics code.
+ *
+ * By default, all operations are no-ops (disabled). Enterprise editions can
+ * enable observability by registering providers via the plugin system.
+ *
+ * @example
+ * ```typescript
+ * // In community code - works with or without enterprise plugin
+ * import { Observability } from '@src/shared/observability';
+ *
+ * Observability.userBehavior.recordInteraction('button_clicked', { buttonId: 'submit' });
+ * ```
+ */
+
+import { plugins, PluginTarget, PluginType } from '@react/shared/plugins/Plugins';
+import {
+ NoOpSystemInsightCapture,
+ NoOpUserBehaviorObservability,
+ NoOpUserIdentityContext,
+} from './no-op-providers';
+import type {
+ ISystemInsightCapture,
+ IUserBehaviorObservability,
+ IUserIdentityContext,
+} from './types';
+
+/**
+ * Lazy-loaded singleton for user behavior observability
+ */
+let userBehaviorInstance: IUserBehaviorObservability | null = null;
+
+/**
+ * Lazy-loaded singleton for system insight capture
+ */
+let systemInsightInstance: ISystemInsightCapture | null = null;
+
+/**
+ * Lazy-loaded singleton for user identity context
+ */
+let userIdentityInstance: IUserIdentityContext | null = null;
+
+/**
+ * Gets the user behavior observability provider from plugins
+ * Falls back to no-op implementation if no plugin is registered
+ */
+function getUserBehaviorProvider(): IUserBehaviorObservability {
+ if (userBehaviorInstance) {
+ return userBehaviorInstance;
+ }
+
+ // Try to get provider from enterprise plugin
+ const registeredPlugins = plugins.getPluginsByTarget(
+ PluginTarget.UserBehaviorObservabilityProvider,
+ PluginType.Config,
+ );
+
+ if (registeredPlugins.length > 0 && registeredPlugins[0].type === PluginType.Config) {
+ const provider = registeredPlugins[0].config as IUserBehaviorObservability;
+ userBehaviorInstance = provider;
+ return provider;
+ }
+
+ // Fall back to no-op implementation (default for community edition)
+ userBehaviorInstance = new NoOpUserBehaviorObservability();
+ return userBehaviorInstance;
+}
+
+/**
+ * Gets the system insight capture provider from plugins
+ * Falls back to no-op implementation if no plugin is registered
+ */
+function getSystemInsightProvider(): ISystemInsightCapture {
+ if (systemInsightInstance) {
+ return systemInsightInstance;
+ }
+
+ // Try to get provider from enterprise plugin
+ const registeredPlugins = plugins.getPluginsByTarget(
+ PluginTarget.SystemInsightCaptureProvider,
+ PluginType.Config,
+ );
+
+ if (registeredPlugins.length > 0 && registeredPlugins[0].type === PluginType.Config) {
+ const provider = registeredPlugins[0].config as ISystemInsightCapture;
+ systemInsightInstance = provider;
+ return provider;
+ }
+
+ // Fall back to no-op implementation (default for community edition)
+ systemInsightInstance = new NoOpSystemInsightCapture();
+ return systemInsightInstance;
+}
+
+/**
+ * Gets the user identity context provider from plugins
+ * Falls back to no-op implementation if no plugin is registered
+ */
+function getUserIdentityProvider(): IUserIdentityContext {
+ if (userIdentityInstance) {
+ return userIdentityInstance;
+ }
+
+ // Try to get provider from enterprise plugin
+ const registeredPlugins = plugins.getPluginsByTarget(
+ PluginTarget.UserIdentityContextProvider,
+ PluginType.Config,
+ );
+
+ if (registeredPlugins.length > 0 && registeredPlugins[0].type === PluginType.Config) {
+ const provider = registeredPlugins[0].config as IUserIdentityContext;
+ userIdentityInstance = provider;
+ return provider;
+ }
+
+ // Fall back to no-op implementation (default for community edition)
+ userIdentityInstance = new NoOpUserIdentityContext();
+ return userIdentityInstance;
+}
+
+/**
+ * Main Observability API
+ *
+ * Provides a unified interface for all observability operations.
+ * Automatically uses plugin-registered implementations or falls back to no-ops.
+ *
+ * This is the primary export that should be used throughout the application.
+ */
+export const Observability = {
+ /**
+ * User behavior observability methods
+ * Records user interactions, feature usage, and workflow completions
+ */
+ userBehavior: {
+ recordInteraction: (eventName: string, properties?: Record<string, unknown>) => {
+ getUserBehaviorProvider().recordInteraction(eventName, properties);
+ },
+ recordFeatureUsage: (featureName: string, properties?: Record<string, unknown>) => {
+ getUserBehaviorProvider().recordFeatureUsage(featureName, properties);
+ },
+ recordWorkflowCompletion: (workflowName: string, properties?: Record<string, unknown>) => {
+ getUserBehaviorProvider().recordWorkflowCompletion(workflowName, properties);
+ },
+ },
+
+ /**
+ * System insight capture methods
+ * Records system events, errors, and performance metrics
+ */
+ systemInsight: {
+ recordSystemEvent: (eventName: string, properties?: Record<string, unknown>) => {
+ getSystemInsightProvider().recordSystemEvent(eventName, properties);
+ },
+ recordError: (errorName: string, properties?: Record<string, unknown>) => {
+ getSystemInsightProvider().recordError(errorName, properties);
+ },
+ recordPerformanceMetric: (
+ metricName: string,
+ value: number,
+ properties?: Record<string, unknown>,
+ ) => {
+ getSystemInsightProvider().recordPerformanceMetric(metricName, value, properties);
+ },
+ },
+
+ /**
+ * User identity context methods
+ * Manages user identification and context correlation
+ */
+ userIdentity: {
+ identifyUser: (userId: string, properties?: Record<string, unknown>) => {
+ getUserIdentityProvider().identifyUser({ userId, properties });
+ },
+ setUserProperties: (properties: Record<string, unknown>) => {
+ getUserIdentityProvider().setUserProperties(properties);
+ },
+ clearUserIdentity: () => {
+ getUserIdentityProvider().clearUserIdentity();
+ },
+ },
+};
+
+// Re-export types for convenience
+export type {
+ ISystemInsightCapture,
+ IUserBehaviorObservability,
+ IUserIdentityContext,
+ ObservabilityEventProperties,
+ UserIdentityContext,
+} from './types';
diff --git a/packages/app/src/shared/observability/no-op-providers.ts b/packages/app/src/shared/observability/no-op-providers.ts
new file mode 100644
index 00000000..c9c7003b
--- /dev/null
+++ b/packages/app/src/shared/observability/no-op-providers.ts
@@ -0,0 +1,106 @@
+/**
+ * No-Op Observability Providers
+ *
+ * These are the default implementations used in community edition.
+ * They implement the observability interfaces but perform no actual operations,
+ * ensuring zero overhead when analytics are not needed.
+ *
+ * Enterprise editions can override these by registering their own implementations
+ * via the plugin system.
+ */
+
+import type {
+ ISystemInsightCapture,
+ IUserBehaviorObservability,
+ IUserIdentityContext,
+ ObservabilityEventProperties,
+ UserIdentityContext,
+} from './types';
+
+/**
+ * No-op implementation of user behavior observability
+ * All methods are empty functions that do nothing
+ */
+export class NoOpUserBehaviorObservability implements IUserBehaviorObservability {
+ /**
+ * Records a user interaction (no-op)
+ */
+ recordInteraction(_eventName: string, _properties?: ObservabilityEventProperties): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Records feature usage (no-op)
+ */
+ recordFeatureUsage(_featureName: string, _properties?: ObservabilityEventProperties): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Records workflow completion (no-op)
+ */
+ recordWorkflowCompletion(
+ _workflowName: string,
+ _properties?: ObservabilityEventProperties,
+ ): void {
+ // No operation - disabled by default
+ }
+}
+
+/**
+ * No-op implementation of system insight capture
+ * All methods are empty functions that do nothing
+ */
+export class NoOpSystemInsightCapture implements ISystemInsightCapture {
+ /**
+ * Records a system event (no-op)
+ */
+ recordSystemEvent(_eventName: string, _properties?: ObservabilityEventProperties): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Records an error (no-op)
+ */
+ recordError(_errorName: string, _properties?: ObservabilityEventProperties): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Records a performance metric (no-op)
+ */
+ recordPerformanceMetric(
+ _metricName: string,
+ _value: number,
+ _properties?: ObservabilityEventProperties,
+ ): void {
+ // No operation - disabled by default
+ }
+}
+
+/**
+ * No-op implementation of user identity context
+ * All methods are empty functions that do nothing
+ */
+export class NoOpUserIdentityContext implements IUserIdentityContext {
+ /**
+ * Identifies a user (no-op)
+ */
+ identifyUser(_context: UserIdentityContext): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Sets user properties (no-op)
+ */
+ setUserProperties(_properties: ObservabilityEventProperties): void {
+ // No operation - disabled by default
+ }
+
+ /**
+ * Clears user identity (no-op)
+ */
+ clearUserIdentity(): void {
+ // No operation - disabled by default
+ }
+}
diff --git a/packages/app/src/shared/observability/types.ts b/packages/app/src/shared/observability/types.ts
new file mode 100644
index 00000000..99d9712f
--- /dev/null
+++ b/packages/app/src/shared/observability/types.ts
@@ -0,0 +1,141 @@
+/**
+ * Observability Type Definitions
+ *
+ * This module defines abstract interfaces for system observability and user behavior monitoring.
+ * These interfaces are designed to be implemented by enterprise editions to enable analytics
+ * while keeping the community edition free of direct analytics dependencies.
+ *
+ * The default implementations in community edition are no-ops (disabled by default).
+ * Enterprise editions inject concrete implementations via the plugin system.
+ */
+
+/**
+ * Properties that can be attached to user behavior events
+ */
+export type ObservabilityEventProperties = Record<
+ string,
+ string | number | boolean | null | undefined
+>;
+
+/**
+ * User identity information for context correlation
+ */
+export interface UserIdentityContext {
+ /** Unique user identifier */
+ userId: string;
+
+ /** Additional user properties for context enrichment */
+ properties?: ObservabilityEventProperties;
+}
+
+/**
+ * Interface for capturing user behavior and interaction patterns
+ *
+ * This abstraction allows enterprise editions to collect product usage metrics,
+ * feature adoption data, and workflow completion analytics without modifying
+ * community edition code.
+ */
+export interface IUserBehaviorObservability {
+ /**
+ * Records a user interaction or behavior event
+ *
+ * @param eventName - Descriptive name of the user action or behavior
+ * @param properties - Additional context about the event
+ *
+ * @example
+ * ```typescript
+ * recordInteraction('agent_created', { agentType: 'chatbot', source: 'template' });
+ * ```
+ */
+ recordInteraction(eventName: string, properties?: ObservabilityEventProperties): void;
+
+ /**
+ * Records a feature usage event
+ *
+ * @param featureName - Name of the feature being used
+ * @param properties - Additional context about feature usage
+ */
+ recordFeatureUsage(featureName: string, properties?: ObservabilityEventProperties): void;
+
+ /**
+ * Records a workflow completion event
+ *
+ * @param workflowName - Name of the completed workflow
+ * @param properties - Additional context about the workflow
+ */
+ recordWorkflowCompletion(workflowName: string, properties?: ObservabilityEventProperties): void;
+}
+
+/**
+ * Interface for capturing system-level insights and operational metrics
+ *
+ * This abstraction allows enterprise editions to monitor system performance,
+ * error patterns, and operational health without modifying community edition code.
+ */
+export interface ISystemInsightCapture {
+ /**
+ * Records a system-level event
+ *
+ * @param eventName - Descriptive name of the system event
+ * @param properties - Additional context about the event
+ *
+ * @example
+ * ```typescript
+ * recordSystemEvent('deployment_completed', { duration: 1200, success: true });
+ * ```
+ */
+ recordSystemEvent(eventName: string, properties?: ObservabilityEventProperties): void;
+
+ /**
+ * Records an error or exception
+ *
+ * @param errorName - Name or type of the error
+ * @param properties - Additional context about the error
+ */
+ recordError(errorName: string, properties?: ObservabilityEventProperties): void;
+
+ /**
+ * Records a performance metric
+ *
+ * @param metricName - Name of the performance metric
+ * @param value - Numeric value of the metric
+ * @param properties - Additional context about the metric
+ */
+ recordPerformanceMetric(
+ metricName: string,
+ value: number,
+ properties?: ObservabilityEventProperties,
+ ): void;
+}
+
+/**
+ * Interface for managing user identity context in observability systems
+ *
+ * This abstraction allows enterprise editions to correlate events with user identities
+ * for better analytics and insights.
+ */
+export interface IUserIdentityContext {
+ /**
+ * Associates a user identity with subsequent observability events
+ *
+ * @param context - User identity information
+ *
+ * @example
+ * ```typescript
+ * identifyUser({ userId: 'user-123', properties: { email: '[email protected]' } });
+ * ```
+ */
+ identifyUser(context: UserIdentityContext): void;
+
+ /**
+ * Updates user properties without changing the user identity
+ *
+ * @param properties - Properties to set or update
+ */
+ setUserProperties(properties: ObservabilityEventProperties): void;
+
+ /**
+ * Clears the current user identity context
+ */
+ clearUserIdentity(): void;
+}
diff --git a/packages/app/src/shared/posthog/services/analytics.ts b/packages/app/src/shared/posthog/services/analytics.ts
index 4e192514..91c6f767 100644
--- a/packages/app/src/shared/posthog/services/analytics.ts
+++ b/packages/app/src/shared/posthog/services/analytics.ts
@@ -1,19 +1,32 @@
-import { PostHog } from '@src/shared/posthog';
+/**
+ * @deprecated Use Observability API instead
+ * This service is kept for backward compatibility but forwards all calls to the new Observability API
+ *
+ * Migration:
+ * - Replace Analytics.track() with Observability.userBehavior.recordInteraction()
+ * - Or use Observability.userBehavior.recordFeatureUsage() for feature-specific events
+ * - Or use Observability.userBehavior.recordWorkflowCompletion() for workflow events
+ */
+
+import { Observability } from '@src/shared/observability';
import { isProdEnv } from '@src/shared/utils';
export const Analytics = {
- track: (eventName: string, properties: Record<string, any> = {}) => {
+ /**
+ * @deprecated Use Observability.userBehavior.recordInteraction() instead
+ */
+ track: (eventName: string, properties: Record<string, unknown> = {}) => {
try {
- // so any error doesn't break the app
+ // Forward to Observability API
const enhancedProperties = { ...properties };
-
+
// Add isProd if not already present to differentiate between prod and dev events
if (!('isProd' in enhancedProperties)) {
enhancedProperties.isProd = isProdEnv();
}
-
- PostHog.track(eventName, enhancedProperties);
-
+
+ // Forward to new Observability API
+ Observability.userBehavior.recordInteraction(eventName, enhancedProperties);
} catch (error) {
console.info('Error tracking event', error);
}