Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(analytics): restore broken events and add product tracking (MCP, connectors, databases, calendar, CRM, search, notifications, routines) (#8424)
Chaitanya Agarwal34fe69d6f835
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 4e6459a38f..40b7c65c79 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -2134,6 +2134,8 @@],"analytics_client": ["crates/analytics_client",+ "crates/macro_env",+ "crates/macro_env_var","crates/workspace-hack"],"anthropic": [@@ -2664,6 +2666,8 @@"cal": ["crates/analytics_client","crates/cal",+ "crates/macro_env",+ "crates/macro_env_var","crates/model-error-response","crates/workspace-hack"],diff --git a/Cargo.lock b/Cargo.lockindex 6545f535e8..81a5bb978d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -521,6 +521,7 @@ dependencies = ["ai_tools","ai_toolset","ai_usage",+ "analytics_client","anyhow","async-openai","async-stream",@@ -593,6 +594,7 @@ dependencies = ["lexical_client","lexical_mention_extractor","log",+ "lru 0.16.4","macro_auth","macro_authorization","macro_aws_config",@@ -1336,11 +1338,14 @@ version = "0.1.0"dependencies = ["chrono","hex",+ "macro_env","reqwest 0.13.4","serde","serde_json","sha2 0.10.9",+ "tokio","tracing",+ "uuid","workspace-hack",]diff --git a/apps/web/src/features/auth/EmailAuth.test.tsx b/apps/web/src/features/auth/EmailAuth.test.tsxindex fa09eebfe4..09e389437b 100644--- a/apps/web/src/features/auth/EmailAuth.test.tsx+++ b/apps/web/src/features/auth/EmailAuth.test.tsx@@ -18,6 +18,7 @@ const mocks = vi.hoisted(() => ({linkId: 'oauth-link',searchParams: {} as Record<string, string>,restore: vi.fn(),+ track: vi.fn(),openAddInbox: vi.fn(),fetchProviders: vi.fn(),}));@@ -41,7 +42,7 @@ vi.mock('@core/auth', () => ({ updateUserAuth: vi.fn() }));vi.mock('@core/auth/email', () => ({ redirectToEmailAuth: vi.fn() }));vi.mock('@core/auth/login-events', () => ({ publishLoginSuccess: vi.fn() }));vi.mock('@app/lib/analytics/analytics-context', () => ({- useAnalytics: () => ({ pageView: vi.fn() }),+ useAnalytics: () => ({ pageView: vi.fn(), track: mocks.track }),}));vi.mock('@core/component/Toast/Toast', () => ({toast: { success: mocks.success, failure: mocks.failure },@@ -130,6 +131,10 @@ describe('inbox consent callback', () => {forceShare: false,});expect(mocks.refetch).toHaveBeenCalledOnce();+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith(+ 'email_link_callback_result',+ { outcome: 'connected' }+ );});it('explains pending work and lets the user return without a later redirect', async () => {@@ -173,6 +178,10 @@ describe('inbox consent callback', () => {));expect(mocks.navigate).toHaveBeenCalledOnce();+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith(+ 'email_link_callback_result',+ { outcome: 'no_gmail_grant' }+ );});it('still holds the callback for a shared-inbox confirmation', async () => {diff --git a/apps/web/src/features/auth/EmailAuth.tsx b/apps/web/src/features/auth/EmailAuth.tsxindex 33be4ad2c0..f25ff215cf 100644--- a/apps/web/src/features/auth/EmailAuth.tsx+++ b/apps/web/src/features/auth/EmailAuth.tsx@@ -3,6 +3,7 @@ import { openAddInboxDialog } from '@app/features/inbox/AddInboxDialog';import { AdminConsentRequiredDialog } from '@app/features/inbox/AdminConsentRequiredDialog';import { ShareInboxConflictDialog } from '@app/features/inbox/ShareInboxConflictDialog';import { useAnalytics } from '@app/lib/analytics/analytics-context';+import type { AppEvents } from '@app/lib/analytics/app-events';import { updateUserAuth } from '@core/auth';import { redirectToEmailAuth } from '@core/auth/email';import { publishLoginSuccess } from '@core/auth/login-events';@@ -158,6 +159,10 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {const navigate = useNavigate();const [searchParams] = useSearchParams();const { query, initEmailLink } = useEmailLinks();+ const analytics = useAnalytics();+ const trackOutcome = (+ outcome: AppEvents['email_link_callback_result']['outcome']+ ) => analytics.track('email_link_callback_result', { outcome });let disposed = false;onCleanup(() => {disposed = true;@@ -218,6 +223,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {try {await initEmailLink({ linkId, forceShare }).match(async () => {+ trackOutcome('connected');// Pull the newly-provisioned link into the cache before leaving the// callback so the inbox panel shows it immediately on return rather// than flashing a stale list until its own refetch lands.@@ -227,6 +233,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {},async (err) => {if (err.tag === 'AlreadyInitialized') {+ trackOutcome('already_initialized');await query.refetch();navigateAfterLink(linkId);return;@@ -234,6 +241,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {// The mailbox is already connected by someone else. Hold the callback open// and let the user confirm sharing it before retrying with forceShare.if (err.tag === 'SharedInboxConflict' && !forceShare) {+ trackOutcome('shared_inbox_conflict');setConflict({linkId,emailAddress: err.emailAddress,@@ -242,6 +250,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {return;}if (err.tag === 'PaymentRequired') {+ trackOutcome('payment_required');toast.failure('A professional subscription is required to add another inbox.');@@ -249,17 +258,20 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {return;}if (err.tag === 'NoGmailGrant') {+ trackOutcome('no_gmail_grant');toast.failure('Gmail access was not granted. Please allow all requested permissions and try again.');navigateAfterLink(linkId);return;}+ trackOutcome('failed');toast.failure('Failed to add inbox');navigateAfterLink(linkId);});} catch {+ trackOutcome('exception');if (disposed) return;toast.failure('Failed to finish connecting your account. Please try again from Settings.'@@ -315,6 +327,7 @@ function EmailLinkCallback(props: Pick<EmailAuthParams, 'successPath'>) {return;}if (!linkId) {+ trackOutcome('missing_link_id');toast.failure('Missing link id in callback URL');navigateToSuccess();return;diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsindex a66d5e3208..279c8c2dda 100644--- a/apps/web/src/features/block-agent/context/pending-session.ts+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -23,6 +23,7 @@*/import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';+import { analytics } from '@app/lib/analytics';import { AgentSession } from '@core/agent-session/AgentSession';import {type PromptSubmitSurface,@@ -213,6 +214,13 @@ export function startPendingSession(// writes are readable. Marked first, a refusal to that read is waited// out rather than reported as a session that is not ours.markSessionCreated(created);+ // `agent`, as BlockLoader reports the session's opens.+ analytics.track('create_entity', {+ entityType: 'agent',+ entityId: created,+ agentId: options.botId,+ submitSurface: options.submitSurface,+ });// A warm claim releases its server reservation before creation answers.replenishWarmAgentSession(result.value.session.ownerId);fireAndForget(diff --git a/apps/web/src/features/block-database/component/Block.tsx b/apps/web/src/features/block-database/component/Block.tsxindex fca0c8e02b..69cc29d84e 100644--- a/apps/web/src/features/block-database/component/Block.tsx+++ b/apps/web/src/features/block-database/component/Block.tsx@@ -434,6 +434,7 @@ const Block: Component = () => {)}</Show><DatabaseGrid+ host="block"databaseId={databaseId}table={table()}canEdit={canEdit() && !activeCreation()}diff --git a/apps/web/src/features/block-database/component/DatabaseGrid.tsx b/apps/web/src/features/block-database/component/DatabaseGrid.tsxindex f08e02e9d8..bff35f651f 100644--- a/apps/web/src/features/block-database/component/DatabaseGrid.tsx+++ b/apps/web/src/features/block-database/component/DatabaseGrid.tsx@@ -52,6 +52,10 @@ import {DatabaseTextEditor,DatabaseTextValue,} from '../database-mentions';+import {+ type DatabaseGridHost,+ trackQueryRuns,+} from '../primitives/track-query-runs';import { createColumnCasts } from '../queries/column-casts';import {addDatabaseColumnOptions,@@ -76,6 +80,8 @@ export type DatabaseGridProps = {/** Host framing for the records area, below the toolbar. */contentClass?: string;databaseId: string;+ /** Where the grid is shown, for analytics. */+ host: DatabaseGridHost;table: TableDetail;canEdit: boolean;/** The view on screen: a stored one, or the table's own All records. */@@ -189,6 +195,12 @@ function TableAdapter(props: DatabaseGridProps & { tableId: string }) {onTableChanged: (listener) =>useDatabaseTableChanges((change) => listener(change.tableId)),});+ trackQueryRuns({+ databaseId,+ tableId: props.tableId,+ host: props.host,+ view: () => props.view,+ });const source = withRelationLabels(createDatabaseRowsSource({databaseId,diff --git a/apps/web/src/features/block-database/definition.ts b/apps/web/src/features/block-database/definition.tsindex 6028ccce96..a0b344bc21 100644--- a/apps/web/src/features/block-database/definition.ts+++ b/apps/web/src/features/block-database/definition.ts@@ -19,6 +19,10 @@ export const definition = defineBlock({// A database is not a soup entity and not a cloud-storage item, so the// open-tracking path (history row + soup refetch) has nothing to write.openTrackingEnabled: false,+ // Opening a database is still a product signal. Calendar, the other block+ // without history, stays off: it always loads one fixed id and `open_view`+ // already counts it.+ openAnalyticsEnabled: true,editPermissionEnabled: true,async load(source, _intent) {if (!(await waitForDatabaseRollout())) return LoadErrors.MISSING;diff --git a/apps/web/src/features/block-database/document-database.tsx b/apps/web/src/features/block-database/document-database.tsxindex 1ecd4a51da..fd4f0ee583 100644--- a/apps/web/src/features/block-database/document-database.tsx+++ b/apps/web/src/features/block-database/document-database.tsx@@ -267,6 +267,7 @@ export function DocumentDatabase(props: {/></div><DatabaseGrid+ host="document"contentClass="m-3 rounded-lg border border-edge-muted"databaseId={databaseId}table={shown()}diff --git a/apps/web/src/features/block-database/primitives/track-query-runs.test.ts b/apps/web/src/features/block-database/primitives/track-query-runs.test.tsnew file mode 100644index 0000000000..c5db157e23--- /dev/null+++ b/apps/web/src/features/block-database/primitives/track-query-runs.test.ts@@ -0,0 +1,100 @@+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import { createRoot, createSignal } from 'solid-js';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const track = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));++import { trackQueryRuns } from './track-query-runs';++const view = (id: string, sortKeys = 0): DatabaseView => ({+ id,+ databaseId: 'db',+ tableId: 'tasks',+ name: id,+ position: '80',+ layout: { kind: 'table', columns: [] },+ query: {+ filter: null,+ sort: Array.from({ length: sortKeys }, (_, index) => ({+ column: `column-${index}`,+ direction: 'ascending' as const,+ })),+ },+ createdAt: '2026-10-21T00:00:00Z',+ updatedAt: '2026-10-21T00:00:00Z',+});++beforeEach(() => {+ vi.useFakeTimers();+ track.mockClear();+});+afterEach(() => vi.useRealTimers());++function mount(initial: DatabaseView) {+ return createRoot((dispose) => {+ const [current, setCurrent] = createSignal(initial);+ trackQueryRuns({+ databaseId: 'db',+ tableId: 'tasks',+ host: 'document',+ view: current,+ });+ return { setCurrent, dispose };+ });+}++it('reports an open per view, including a switch to another view', () => {+ const grid = mount(view('board'));+ grid.setCurrent(view('backlog'));++ expect(track.mock.calls).toEqual([+ [+ 'database_query_run',+ {+ databaseId: 'db',+ tableId: 'tasks',+ viewId: 'board',+ host: 'document',+ trigger: 'open',+ filterConditions: 0,+ sortKeys: 0,+ },+ ],+ [+ 'database_query_run',+ expect.objectContaining({ viewId: 'backlog', trigger: 'open' }),+ ],+ ]);+ grid.dispose();+});++it('reports a query change once it settles', () => {+ const grid = mount(view('board'));+ track.mockClear();++ grid.setCurrent(view('board', 1));+ grid.setCurrent(view('board', 2));+ vi.advanceTimersByTime(999);+ expect(track).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);++ expect(track).toHaveBeenCalledExactlyOnceWith(+ 'database_query_run',+ expect.objectContaining({ trigger: 'query_change', sortKeys: 2 })+ );+ grid.dispose();+});++it('reports a change still settling when the grid closes', () => {+ const grid = mount(view('board'));+ track.mockClear();++ grid.setCurrent(view('board', 1));+ grid.dispose();++ expect(track).toHaveBeenCalledExactlyOnceWith(+ 'database_query_run',+ expect.objectContaining({ trigger: 'query_change', sortKeys: 1 })+ );+});diff --git a/apps/web/src/features/block-database/primitives/track-query-runs.ts b/apps/web/src/features/block-database/primitives/track-query-runs.tsnew file mode 100644index 0000000000..bddc5e2b6d--- /dev/null+++ b/apps/web/src/features/block-database/primitives/track-query-runs.ts@@ -0,0 +1,59 @@+import { analytics } from '@app/lib/analytics';+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import { type Accessor, createEffect, on, onCleanup, untrack } from 'solid-js';++/** Where a database grid is shown: its own block, a document, or a form's responses. */+export type DatabaseGridHost = 'block' | 'document' | 'form';++/** A filter or sort edit counts once it has been left alone this long. */+const QUERY_SETTLE_MS = 1000;++/**+ * Reports `database_query_run` once when a view opens (including a switch to+ * another view) and once per settled filter or sort change. Refreshes, cache+ * reruns and layout edits reread the same query and are not counted. A change+ * still settling when the view switches or the grid closes is reported then.+ */+export function trackQueryRuns(props: {+ databaseId: string;+ tableId: string;+ host: DatabaseGridHost;+ view: Accessor<DatabaseView>;+}) {+ const track = (view: DatabaseView, trigger: 'open' | 'query_change') =>+ analytics.track('database_query_run', {+ databaseId: props.databaseId,+ tableId: props.tableId,+ viewId: view.id,+ host: props.host,+ trigger,+ filterConditions: view.query.filter?.conditions.length ?? 0,+ sortKeys: view.query.sort?.length ?? 0,+ });++ let settling: DatabaseView | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const flush = () => {+ clearTimeout(timer);+ if (settling) track(settling, 'query_change');+ settling = undefined;+ };++ createEffect(+ on(+ () => [props.view().id, JSON.stringify(props.view().query)] as const,+ ([viewId], previous) => {+ const view = untrack(props.view);+ if (previous?.[0] !== viewId) {+ flush();+ track(view, 'open');+ return;+ }+ settling = view;+ clearTimeout(timer);+ timer = setTimeout(flush, QUERY_SETTLE_MS);+ }+ )+ );+ onCleanup(flush);+}diff --git a/apps/web/src/features/block-form/form-responses-grid.tsx b/apps/web/src/features/block-form/form-responses-grid.tsxindex d409311313..54c4fd6218 100644--- a/apps/web/src/features/block-form/form-responses-grid.tsx+++ b/apps/web/src/features/block-form/form-responses-grid.tsx@@ -60,6 +60,7 @@ export function FormResponsesGrid(props: {return (<div class="@container/database flex min-h-0 flex-1 flex-col overflow-hidden"><DatabaseGrid+ host="form"databaseId={props.databaseId}table={shown()}canEdit={canEdit()}diff --git a/apps/web/src/features/channel/Calls/use-channel-calls-source.ts b/apps/web/src/features/channel/Calls/use-channel-calls-source.tsindex 3b2197ea2f..d511f1e5e0 100644--- a/apps/web/src/features/channel/Calls/use-channel-calls-source.ts+++ b/apps/web/src/features/channel/Calls/use-channel-calls-source.ts@@ -30,6 +30,7 @@ export function useChannelCallsSource(// The quick-access pool is not this channel's calls, so matches come from// the search service.const search = createSearchState({+ surface: () => 'channel_calls',text: searchText,disableLocalSearch: () => true,buildRequest: (request) =>diff --git a/apps/web/src/features/channel/Channel/ChannelDetail.tsx b/apps/web/src/features/channel/Channel/ChannelDetail.tsxindex 514b8c7f7a..e449492a99 100644--- a/apps/web/src/features/channel/Channel/ChannelDetail.tsx+++ b/apps/web/src/features/channel/Channel/ChannelDetail.tsx@@ -1,5 +1,6 @@import { ViewShell } from '@app/components/view-shell';import { ChatWithAgentButton } from '@app/features/chat/ChatWithAgentButton';+import { useAnalytics } from '@app/lib/analytics/analytics-context';import { ChannelAttachmentsTab } from '@channel/Attachments/ChannelAttachmentsTab';import { useChannelBotManagement } from '@channel/Bots/use-channel-bot-management';import { useCallContextOptional } from '@channel/Call/CallContext';@@ -46,6 +47,7 @@ import {Match,on,onCleanup,+ onMount,Show,Switch,} from 'solid-js';@@ -279,6 +281,15 @@ function ChannelDetailContent(props: ChannelDetailProps) {const canCall = useChannelCanCall(channelId);const channelName = useChannelName(channelId, props.fallbackName);useSplitDisplayName(() => channelName() ?? 'New Channel');+ const analytics = useAnalytics();+ // Keyed by channel id, so this counts one open per channel shown.+ onMount(() => {+ analytics.pageView('channel');+ analytics.track('open_entity', {+ entityType: 'channel',+ entityId: channelId,+ });+ });const requestFromTarget = (target: ChannelTargetRequest | undefineddiff --git a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsxindex 6d9a04a4c7..d65f753056 100644--- a/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx+++ b/apps/web/src/features/channel/Channel/tests/channel-detail-navigation.test.tsx@@ -13,6 +13,10 @@ const mocks = vi.hoisted(() => ({joinRequested: false,}));+const analytics = vi.hoisted(() => ({ pageView: vi.fn(), track: vi.fn() }));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => analytics,+}));vi.mock('@channel/Channel/ChannelSurface', () => ({ChannelSurface: (props: {targetRequest?: ChannelTargetRequest;@@ -118,12 +122,25 @@ const messageRequests = () =>);beforeEach(() => {+ analytics.track.mockClear();mocks.requests.length = 0;mocks.joinRequested = false;});afterEach(cleanup);describe('channel detail navigation', () => {+ it('counts one open per channel shown', async () => {+ const view = render(() => (+ <ChannelDetail channelId={CHANNEL_ID}>{() => null}</ChannelDetail>+ ));+ await navigate({ message: 'message-1' });++ expect(analytics.track.mock.calls).toEqual([+ ['open_entity', { entityType: 'channel', entityId: CHANNEL_ID }],+ ]);+ view.unmount();+ });+it('measures tab content against the height left after channel chrome', () => {const view = render(() => (<ChannelDetail channelId={CHANNEL_ID}>{() => null}</ChannelDetail>diff --git a/apps/web/src/features/channels-view/queries/channel-search-source.ts b/apps/web/src/features/channels-view/queries/channel-search-source.tsindex 5e20569d2d..97c7cc4e61 100644--- a/apps/web/src/features/channels-view/queries/channel-search-source.ts+++ b/apps/web/src/features/channels-view/queries/channel-search-source.ts@@ -31,6 +31,7 @@ export function createChannelSearchSource(options: {return byId;});const search = createSearchState({+ surface: () => 'channels',enabled,text: options.text,localPool: () => [...localChannels().values()].map((data) => ({ data })),diff --git a/apps/web/src/features/command/queries/mobile-full-text-search.ts b/apps/web/src/features/command/queries/mobile-full-text-search.tsindex fae421fde7..06d7d08df9 100644--- a/apps/web/src/features/command/queries/mobile-full-text-search.ts+++ b/apps/web/src/features/command/queries/mobile-full-text-search.ts@@ -12,6 +12,7 @@ export function createMobileFullTextSearch(category: Accessor<EntitySearchCategory>) {const search = createSearchState({+ surface: () => 'mobile_search',text,disableLocalSearch: () => true,enabled: () => category() !== 'projects' && !!text().trim(),diff --git a/apps/web/src/features/crm/pipeline-entries-adapter.tsx b/apps/web/src/features/crm/pipeline-entries-adapter.tsxindex 22b2c4cf3a..f6e975bc5f 100644--- a/apps/web/src/features/crm/pipeline-entries-adapter.tsx+++ b/apps/web/src/features/crm/pipeline-entries-adapter.tsx@@ -52,6 +52,7 @@ export function createCrmPipelineEntries(const saved = await savePipelineEntryCell(deps.storage,entry,+ props.record.type,cell,value,option !== undefineddiff --git a/apps/web/src/features/crm/queries/companies.test.tsx b/apps/web/src/features/crm/queries/companies.test.tsxnew file mode 100644index 0000000000..97549306e4--- /dev/null+++ b/apps/web/src/features/crm/queries/companies.test.tsx@@ -0,0 +1,87 @@+import { cleanup, render } from '@solidjs/testing-library';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import type { CrmRecordDependencies } from './dependencies';++const track = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));++import {+ useCreateCompanyMutation,+ useCreateContactMutation,+} from './companies';++const storage = { createCompany: vi.fn(), createContact: vi.fn() };+let client: QueryClient;++beforeEach(() => {+ track.mockReset();+ storage.createCompany.mockReset();+ storage.createContact.mockReset();+ client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });+});+afterEach(() => {+ cleanup();+ client.clear();+});++function mount() {+ const deps = { storage, client } as unknown as CrmRecordDependencies;+ let mutations!: {+ company: ReturnType<typeof useCreateCompanyMutation>;+ contact: ReturnType<typeof useCreateContactMutation>;+ };+ function Probe() {+ mutations = {+ company: useCreateCompanyMutation(deps),+ contact: useCreateContactMutation(deps),+ };+ return null;+ }+ render(() => (+ <QueryClientProvider client={client}>+ <Probe />+ </QueryClientProvider>+ ));+ return mutations;+}++it('reports a created company and contact with their ids', async () => {+ storage.createCompany.mockResolvedValue(ok({ id: 'company-1' }));+ storage.createContact.mockResolvedValue(+ ok({ id: 'contact-1', companyId: 'company-1' })+ );+ const mutations = mount();++ await mutations.company.mutateAsync({ name: 'Acme', domain: 'acme.com' });+ await mutations.contact.mutateAsync({+ companyId: 'company-1',+ name: 'Ada',+ email: '[email protected]',+ });++ expect(track.mock.calls).toEqual([+ ['crm_company_created', { companyId: 'company-1' }],+ ['crm_contact_created', { companyId: 'company-1', contactId: 'contact-1' }],+ ]);+});++it('reports nothing when creation fails', async () => {+ storage.createCompany.mockResolvedValue(err([{ message: 'Taken' }]));+ storage.createContact.mockResolvedValue(err([{ message: 'Taken' }]));+ const mutations = mount();++ await expect(+ mutations.company.mutateAsync({ name: 'Acme', domain: 'acme.com' })+ ).rejects.toBeDefined();+ await expect(+ mutations.contact.mutateAsync({+ companyId: 'company-1',+ name: 'Ada',+ email: '[email protected]',+ })+ ).rejects.toBeDefined();++ expect(track).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/crm/queries/companies.ts b/apps/web/src/features/crm/queries/companies.tsindex f0e6202368..9e57e5f637 100644--- a/apps/web/src/features/crm/queries/companies.ts+++ b/apps/web/src/features/crm/queries/companies.ts@@ -1,4 +1,5 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';+import { analytics } from '@app/lib/analytics';import { ThrownResultError, throwOnErr } from '@core/util/result';import type { CrmCompanyEntity } from '@entity';import { soupKeys } from '@queries/soup/keys';@@ -152,6 +153,7 @@ export function useCreateCompanyMutation(deps: CrmRecordDependencies) {mutationFn: ({ name, domain }: { name: string; domain: string }) =>throwOnErr(() => deps.storage.createCompany({ name, domain })),onSuccess: (data) => {+ analytics.track('crm_company_created', { companyId: data.id });deps.client.setQueryData(crmKeys.company(data.id).queryKey, data);return deps.client.invalidateQueries({ queryKey: soupKeys._def });},@@ -209,13 +211,18 @@ export function useCreateContactMutation(deps: CrmRecordDependencies) {throwOnErr(() =>deps.storage.createContact({ companyId, name, email })),- onSuccess: (_data, { companyId }) =>- Promise.all([+ onSuccess: (contact, { companyId }) => {+ analytics.track('crm_contact_created', {+ companyId,+ contactId: contact.id,+ });+ return Promise.all([deps.client.invalidateQueries({queryKey: crmKeys.company(companyId).queryKey,}),deps.client.invalidateQueries({ queryKey: soupKeys._def }),- ]),+ ]);+ },}),() => deps.client);diff --git a/apps/web/src/features/crm/queries/pipeline-data.test.tsx b/apps/web/src/features/crm/queries/pipeline-data.test.tsxindex 942f92337a..b659d9466c 100644--- a/apps/web/src/features/crm/queries/pipeline-data.test.tsx+++ b/apps/web/src/features/crm/queries/pipeline-data.test.tsx@@ -9,6 +9,9 @@ import { createDatabaseApiSource } from '../../database/queries/api-source';import type { Pipeline } from '../core/pipeline';import { createPipelineApi, pipelineCell } from './pipeline-data';+const track = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));+const pipeline: Pipeline = {id: 'pipeline',databaseId: 'storage-only',@@ -290,3 +293,35 @@ it('preserves unknown insert outcomes through the shared writer', async () => {expect(result.isErr() && result.error.kind).toBe('outcome-unknown');expect(apply).toHaveBeenCalledTimes(1);});++it('reports committed pipeline writes as entries edited, never refused ones', async () => {+ track.mockReset();+ const host = setup();+ const ops = [+ {+ kind: 'rows' as const,+ table: 'records',+ change: { kind: 'insert' as const, rows: [[]] },+ },+ ];++ await host.api.applyOps({ ops });+ const refused = createPipelineApi(+ {+ ...host.storage,+ applyCrmPipelineOps: () =>+ errAsync([{ code: 'CONFLICT', message: 'Changed.', refusal: null }]),+ },+ pipeline+ );+ await refused.applyOps({ ops });++ expect(track).toHaveBeenCalledExactlyOnceWith('crm_pipeline_entries_edited', {+ pipelineId: 'pipeline',+ recordType: 'company',+ surface: 'pipeline',+ insertedRows: 1,+ updatedRows: 0,+ deletedRows: 0,+ });+});diff --git a/apps/web/src/features/crm/queries/pipeline-data.ts b/apps/web/src/features/crm/queries/pipeline-data.tsindex c6dbda37f7..060720c6b1 100644--- a/apps/web/src/features/crm/queries/pipeline-data.ts+++ b/apps/web/src/features/crm/queries/pipeline-data.ts@@ -1,3 +1,6 @@+import { analytics } from '@app/lib/analytics';+import type { DatabaseOp } from '@core/database-sql/generated/types';+import { countRowWrites } from '@queries/storage/databases';import type { ColumnDetail } from '@service-storage/generated/schemas/columnDetail';import type { PropertyValue } from '@service-storage/generated/schemas/propertyValue';import { err, errAsync, ok, ResultAsync } from 'neverthrow';@@ -44,6 +47,26 @@ export function pipelineCell(.exhaustive(() => null);}+/**+ * Reports a committed pipeline write's row counts: inserted rows are entries+ * added, updated rows include stage moves. Never cell contents.+ */+export function trackPipelineEntryWrites(+ pipeline: { id: string; recordType?: Pipeline['recordType'] },+ surface: 'pipeline' | 'record',+ ops: DatabaseOp[]+) {+ const counts = countRowWrites(ops);+ if (counts.insertedRows + counts.updatedRows + counts.deletedRows === 0)+ return;+ analytics.track('crm_pipeline_entries_edited', {+ pipelineId: pipeline.id,+ recordType: pipeline.recordType,+ surface,+ ...counts,+ });+}+/** Transport adapter only; the shared provider owns queries and editing. */export function createPipelineApi(storage: Pick<@@ -109,6 +132,10 @@ export function createPipelineApi(applyOps: (batch) =>storage.applyCrmPipelineOps(pipeline.id, batch)- .mapErr(([error]) => error),+ .mapErr(([error]) => error)+ .map((applied) => {+ trackPipelineEntryWrites(pipeline, 'pipeline', batch.ops);+ return applied;+ }),};}diff --git a/apps/web/src/features/crm/queries/pipeline-entries.test.ts b/apps/web/src/features/crm/queries/pipeline-entries.test.tsindex 54fba1cd03..dd22509f6e 100644--- a/apps/web/src/features/crm/queries/pipeline-entries.test.ts+++ b/apps/web/src/features/crm/queries/pipeline-entries.test.ts@@ -1,7 +1,16 @@import type { CrmPipelineEntryFieldsFragment } from '@service-storage/graphql/generated/graphql';+import { okAsync } from 'neverthrow';import { expect, it, vi } from 'vitest';import { UNAVAILABLE_OPTION } from '../../database/core/grid-cells';-import { pipelineEntriesInput, toPipelineEntry } from './pipeline-entries';+import {+ type PipelineEntriesDependencies,+ pipelineEntriesInput,+ savePipelineEntryCell,+ toPipelineEntry,+} from './pipeline-entries';++const track = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));vi.mock('@service-storage/graphql-soup', () => ({getGraphqlSoupClient: vi.fn(),@@ -187,3 +196,36 @@ it('reads one company or one contact through soup', () => {);expect(contact?.initial?.limit).toBe(1);});++it('reports a record page pipeline write with the record type', async () => {+ const mapped = toPipelineEntry(+ entry([+ {+ __typename: 'GraphqlCrmPipelineCell',+ column: column({ id: 'notes' }),+ value: null,+ },+ ])+ );+ const storage = {+ applyCrmPipelineOps: vi.fn(() => okAsync({ results: [], changes: [] })),+ } as unknown as PipelineEntriesDependencies['storage'];++ await savePipelineEntryCell(+ storage,+ mapped,+ 'contact',+ mapped.cells[0],+ 'Follow up',+ false+ );++ expect(track).toHaveBeenCalledExactlyOnceWith('crm_pipeline_entries_edited', {+ pipelineId: 'pipeline',+ recordType: 'contact',+ surface: 'record',+ insertedRows: 0,+ updatedRows: 1,+ deletedRows: 0,+ });+});diff --git a/apps/web/src/features/crm/queries/pipeline-entries.ts b/apps/web/src/features/crm/queries/pipeline-entries.tsindex 5d48c7a223..812df8501e 100644--- a/apps/web/src/features/crm/queries/pipeline-entries.ts+++ b/apps/web/src/features/crm/queries/pipeline-entries.ts@@ -20,6 +20,7 @@ import type {PipelineEntryRecord,} from '../core/pipeline-entry';import type { CrmRecordDependencies } from './dependencies';+import { trackPipelineEntryWrites } from './pipeline-data';/** What the record's pipeline cards read and write through. */export type PipelineEntriesDependencies = {@@ -172,6 +173,8 @@ export function createPipelineEntriesQuery(export function savePipelineEntryCell(storage: PipelineEntriesDependencies['storage'],entry: PipelineEntry,+ /** Whose record page the entry is edited from. */+ recordType: PipelineEntryRecord['type'],cell: PipelineEntryCell,value: DatabaseCellValue,createOptions: boolean@@ -183,7 +186,15 @@ export function savePipelineEntryCell(applyOps: (batch) =>storage.applyCrmPipelineOps(entry.pipeline.id, batch)- .mapErr(([error]) => error),+ .mapErr(([error]) => error)+ .map((applied) => {+ trackPipelineEntryWrites(+ { id: entry.pipeline.id, recordType },+ 'record',+ batch.ops+ );+ return applied;+ }),},{ kind: 'cell', rowId: entry.rowId, columnId: cell.column.id, value },createOptionsdiff --git a/apps/web/src/features/drive-view/components/FileDetail.test.tsx b/apps/web/src/features/drive-view/components/FileDetail.test.tsxindex d07aaee7f3..750c49eb0a 100644--- a/apps/web/src/features/drive-view/components/FileDetail.test.tsx+++ b/apps/web/src/features/drive-view/components/FileDetail.test.tsx@@ -4,6 +4,10 @@ import { type Accessor, createSignal, type JSX, onCleanup } from 'solid-js';import { render } from 'solid-js/web';import { afterEach, describe, expect, it, vi } from 'vitest';+const analytics = vi.hoisted(() => ({ pageView: vi.fn(), track: vi.fn() }));+vi.mock('@app/lib/analytics/analytics-context', () => ({+ useAnalytics: () => analytics,+}));vi.mock('@components/app/side-panel', () => ({}));vi.mock('@core/mobile/native-network-status', () => ({nativeNetworkStatus: () => 'online',@@ -50,6 +54,7 @@ import { FileDetailLoadGate } from './FileDetail';let dispose: (() => void) | undefined;afterEach(() => {+ analytics.track.mockClear();dispose?.();document.body.replaceChildren();});@@ -62,6 +67,7 @@ function mount(load: () => Promise<Loaded>, cleanupEditor?: () => void) {() => (<FileDetailLoadGatedocumentId="private-document"+ entityType="md"label="document"load={load}>@@ -133,6 +139,36 @@ describe('file access errors', () => {expect(load).toHaveBeenCalledTimes(3);});+ it('counts an open once the document loads, not on access reloads', async () => {+ const load = vi+ .fn<() => Promise<Loaded>>()+ .mockResolvedValueOnce({ userAccessLevel: 'view' })+ .mockResolvedValue({ userAccessLevel: 'edit' });+ const container = mount(load);+ await vi.waitFor(() =>+ expect(container.textContent).toContain('Document content: view')+ );+ notifyAccess?.('edit');+ await vi.waitFor(() =>+ expect(container.textContent).toContain('Document content: edit')+ );++ expect(analytics.track.mock.calls).toEqual([+ ['open_entity', { entityType: 'md', entityId: 'private-document' }],+ ]);+ });++ it('counts no open for a document that failed to load', async () => {+ const container = mount(async () => {+ throw new ThrownResultError([{ code: 'NOT_FOUND', message: 'Missing' }]);+ });+ await vi.waitFor(() =>+ expect(container.textContent).toContain('Try again')+ );++ expect(analytics.track).not.toHaveBeenCalled();+ });+it.each(['NETWORK_ERROR', 'NOT_FOUND', 'GONE'])('keeps %s separate from denied access',async (code) => {diff --git a/apps/web/src/features/drive-view/components/FileDetail.tsx b/apps/web/src/features/drive-view/components/FileDetail.tsxindex 6bf8938b94..2e45c6d7d4 100644--- a/apps/web/src/features/drive-view/components/FileDetail.tsx+++ b/apps/web/src/features/drive-view/components/FileDetail.tsx@@ -3,6 +3,7 @@ import {useSharedAccessUpdates,} from '@app/features/access-requests/access-requests';import { shareEntity } from '@app/features/access-requests/core/types';+import { useAnalytics } from '@app/lib/analytics/analytics-context';import {DocumentFileSidePanelSections,SidePanel,@@ -19,6 +20,7 @@ import type { AccessLevel } from '@service-storage/generated/schemas/accessLevelimport type { DocumentMetadata } from '@service-storage/generated/schemas/documentMetadata';import { Button } from '@ui';import {+ createEffect,createResource,ErrorBoundary,type JSX,@@ -97,14 +99,31 @@ export function FileDetailLoadGate<T extends { userAccessLevel: AccessLevel },>(props: {documentId: string;+ /** The block the document opens as, reported on `open_entity`. */+ entityType: string;label: string;load: (documentId: string) => Promise<T>;children: (data: T) => JSX.Element;}) {+ const analytics = useAnalytics();const [document, { refetch, mutate }] = createResource(() => props.documentId,props.load);+ // Counts the open once per document, as BlockLoader does for blocks; access+ // changes and retries reload the same document without reopening it.+ let trackedDocumentId: string | undefined;+ createEffect(() => {+ if (document.state !== 'ready') return;+ const documentId = props.documentId;+ if (trackedDocumentId === documentId) return;+ trackedDocumentId = documentId;+ analytics.pageView(props.entityType);+ analytics.track('open_entity', {+ entityType: props.entityType,+ entityId: documentId,+ });+ });const reload = () => {// Dispose the old editor and its sync source before loading a new token.mutate(undefined);diff --git a/apps/web/src/features/drive-view/queries/drive-data-source.ts b/apps/web/src/features/drive-view/queries/drive-data-source.tsindex d69e4f8143..8cb4767351 100644--- a/apps/web/src/features/drive-view/queries/drive-data-source.ts+++ b/apps/web/src/features/drive-view/queries/drive-data-source.ts@@ -180,6 +180,7 @@ export function createDriveDataSource(options: {});const search = createSearchState({+ surface: () => 'drive',text: () => selection().search,enabled: facetsReady,diff --git a/apps/web/src/features/drive-view/views/CanvasDetail.tsx b/apps/web/src/features/drive-view/views/CanvasDetail.tsxindex 3d28853264..e667dc64f2 100644--- a/apps/web/src/features/drive-view/views/CanvasDetail.tsx+++ b/apps/web/src/features/drive-view/views/CanvasDetail.tsx@@ -121,6 +121,7 @@ export function CanvasDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="canvas"label="canvas"load={loadCanvasDocument}>diff --git a/apps/web/src/features/drive-view/views/CodeDetail.tsx b/apps/web/src/features/drive-view/views/CodeDetail.tsxindex 02ffc10c54..18fce4d303 100644--- a/apps/web/src/features/drive-view/views/CodeDetail.tsx+++ b/apps/web/src/features/drive-view/views/CodeDetail.tsx@@ -141,6 +141,7 @@ export function CodeDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="code"label="code document"load={loadCodeDocument}>diff --git a/apps/web/src/features/drive-view/views/ImageDetail.tsx b/apps/web/src/features/drive-view/views/ImageDetail.tsxindex 180493888e..2e6584f6cf 100644--- a/apps/web/src/features/drive-view/views/ImageDetail.tsx+++ b/apps/web/src/features/drive-view/views/ImageDetail.tsx@@ -58,6 +58,7 @@ export function ImageDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="image"label="image"load={loadImageDocument}>diff --git a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx b/apps/web/src/features/drive-view/views/MarkdownDetail.tsxindex e55edf1f14..cb2328ac8a 100644--- a/apps/web/src/features/drive-view/views/MarkdownDetail.tsx+++ b/apps/web/src/features/drive-view/views/MarkdownDetail.tsx@@ -150,6 +150,7 @@ export function MarkdownDetail(props: MarkdownDetailProps) {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="md"label={props.kind === 'task' ? 'task' : 'document'}load={loadMarkdownDocument}>diff --git a/apps/web/src/features/drive-view/views/PdfDetail.tsx b/apps/web/src/features/drive-view/views/PdfDetail.tsxindex b473ec17eb..d9a78a2f90 100644--- a/apps/web/src/features/drive-view/views/PdfDetail.tsx+++ b/apps/web/src/features/drive-view/views/PdfDetail.tsx@@ -203,6 +203,7 @@ export function PdfDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="pdf"label="PDF"load={loadPdfDocument}>diff --git a/apps/web/src/features/drive-view/views/UnknownDetail.tsx b/apps/web/src/features/drive-view/views/UnknownDetail.tsxindex 45034be113..028cce8c93 100644--- a/apps/web/src/features/drive-view/views/UnknownDetail.tsx+++ b/apps/web/src/features/drive-view/views/UnknownDetail.tsx@@ -83,6 +83,7 @@ export function UnknownDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="unknown"label="file"load={loadUnknownDocument}>diff --git a/apps/web/src/features/drive-view/views/VideoDetail.tsx b/apps/web/src/features/drive-view/views/VideoDetail.tsxindex 56c714e5e2..eadb7d23e4 100644--- a/apps/web/src/features/drive-view/views/VideoDetail.tsx+++ b/apps/web/src/features/drive-view/views/VideoDetail.tsx@@ -71,6 +71,7 @@ export function VideoDetail(props: {return (<FileDetailLoadGatedocumentId={props.documentId}+ entityType="video"label="video"load={loadVideoDocument}>diff --git a/apps/web/src/features/email-view/queries/use-email-query.ts b/apps/web/src/features/email-view/queries/use-email-query.tsindex b5e15c50e3..02dda70513 100644--- a/apps/web/src/features/email-view/queries/use-email-query.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.ts@@ -179,6 +179,7 @@ export function useEmailDataSource(// The quick-access pool behind local search holds no email threads, so// every search result comes from the search service.const search = createSearchState({+ surface: () => 'email',text: () => state.search,enabled: () => sourceEnabled() && searchFavoritesReady(),disableLocalSearch: () => true,diff --git a/apps/web/src/features/home/queries/use-home-query.ts b/apps/web/src/features/home/queries/use-home-query.tsindex a49e0b2635..297c4fef35 100644--- a/apps/web/src/features/home/queries/use-home-query.ts+++ b/apps/web/src/features/home/queries/use-home-query.ts@@ -342,6 +342,7 @@ function useSoupHomeDataSource(});const search = createSearchState({+ surface: () => 'home',text: () => state.search,localPool,buildRequest: (request) => buildHomeSearchRequest(viewContext(), request),diff --git a/apps/web/src/features/home/use-home-recommendations.ts b/apps/web/src/features/home/use-home-recommendations.tsindex b5a229e618..5562733698 100644--- a/apps/web/src/features/home/use-home-recommendations.ts+++ b/apps/web/src/features/home/use-home-recommendations.ts@@ -77,7 +77,14 @@ export function useHomeRecommendations() {}if (notification) {- const result = await openNotification(notification, splitManager, true);+ const result = await openNotification(+ notification,+ splitManager,+ true,+ undefined,+ undefined,+ { source: 'home_recommendation' }+ );if (result.isOk()) {await notificationSource.markAsRead(notification);return;diff --git a/apps/web/src/features/next-soup/soup-view/create-search-state.ts b/apps/web/src/features/next-soup/soup-view/create-search-state.tsindex abab4f20da..f64f2bbe15 100644--- a/apps/web/src/features/next-soup/soup-view/create-search-state.ts+++ b/apps/web/src/features/next-soup/soup-view/create-search-state.ts@@ -12,6 +12,8 @@ import { type Accessor, createMemo, type Setter } from 'solid-js';import { buildSoupSearchRequest } from './search-request';interface CreateSearchStateArgs {+ /** Where the search runs, for analytics. */+ surface: Accessor<string>;soup: SoupState;filters: Accessor<QueryState>;assignees: Accessor<string[]>;@@ -26,6 +28,7 @@ interface CreateSearchStateArgs {}export const createSearchState = ({+ surface,soup,filters,assignees,@@ -79,6 +82,7 @@ export const createSearchState = ({};const search = createSharedSearchState({+ surface,text: searchText,buildRequest: (search) => buildSoupSearchRequest(filters(), search),localPool,diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsxindex 0789c2d1b1..2c2da53b9d 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view-context.tsx@@ -795,6 +795,7 @@ export const createSoupViewState = (props: SoupViewContextProviderProps) => {});const search = createSearchState({+ surface: () => activeListView() ?? 'soup',soup,filters: () => applyViewFilters(queryFilters.state),assignees: assigneeFilter,diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex 5dca066a22..02fe21d1b0 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -1,6 +1,7 @@import { openCalendarView } from '@app/features/calendar-view/calendar-navigation';import { createCalendarRange } from '@app/features/calendar-view/calendar-range';import { crmRecordContent } from '@app/features/crm/crm-hosted-content';+import { analytics } from '@app/lib/analytics';import {getChannelParams,navigateToChannelMessage,@@ -604,6 +605,17 @@ function getSupportedHandler();}+/**+ * Where a notification was opened from: the app's own lists, a browser+ * notification, a native (iOS, Android, macOS) notification, or a home+ * recommendation that opens through its notification.+ */+export type NotificationOpenSource =+ | 'in_app'+ | 'browser_push'+ | 'native_push'+ | 'home_recommendation';+/*** Opens the notification given the layout manager.* Some notifications are not supported and will return an error.@@ -618,13 +630,28 @@ export function openNotification(* clicked).*/sourceHandle?: SplitHandle,- options: { onApplied?: VoidFunction } = {}+ options: { onApplied?: VoidFunction; source?: NotificationOpenSource } = {}): ResultAsync<void, NotSupportedError> {+ const reportOpened = () =>+ analytics.track('notification_opened', {+ source: options.source ?? 'in_app',+ notificationType: notification.notification_metadata.tag,+ entityType: notification.entity_type,+ });+ // A native tap on a cold start is retried until the layout applies it, so+ // it counts once, when it applies.+ const reportOnApplied =+ options.source === 'native_push' ? options.onApplied : undefined;const handler = getSupportedHandler(notification,entity,sourceHandle,- options.onApplied+ reportOnApplied+ ? () => {+ reportOpened();+ reportOnApplied();+ }+ : options.onApplied);if (!handler) {return errAsync({@@ -632,6 +659,7 @@ export function openNotification(notificationType: notification.notification_metadata.tag,});}+ if (!reportOnApplied) reportOpened();return ResultAsync.fromSafePromise(handler(layoutManager, newSplit));}@@ -654,6 +682,7 @@ export function openSingleStackNotification(return true;}+/** Opens a notification a native notification tap named by id. */export function openNotificationFromId(notificationId: string,layoutManager: SplitManager,@@ -699,7 +728,7 @@ export function openNotificationFromId(false,undefined,undefined,- { onApplied: options.onApplied }+ { onApplied: options.onApplied, source: 'native_push' });};diff --git a/apps/web/src/features/notifications/notification-platform.ts b/apps/web/src/features/notifications/notification-platform.tsindex 97edac6180..7a4622f9fb 100644--- a/apps/web/src/features/notifications/notification-platform.ts+++ b/apps/web/src/features/notifications/notification-platform.ts@@ -189,7 +189,14 @@ export async function maybeHandlePlatformNotification() {notificationHandle.onClick(() => {window.focus();- openNotification(notification, splitLayoutManager);+ openNotification(+ notification,+ splitLayoutManager,+ false,+ undefined,+ undefined,+ { source: 'browser_push' }+ );notificationHandle.close();});}diff --git a/apps/web/src/features/notifications/tests/notification-platform.test.ts b/apps/web/src/features/notifications/tests/notification-platform.test.tsindex 040c3a4ab0..9f456c3187 100644--- a/apps/web/src/features/notifications/tests/notification-platform.test.ts+++ b/apps/web/src/features/notifications/tests/notification-platform.test.ts@@ -273,7 +273,11 @@ describe('maybeHandlePlatformNotification', () => {expect(focus).toHaveBeenCalledOnce();expect(openNotification).toHaveBeenCalledExactlyOnceWith(notification,- layout+ layout,+ false,+ undefined,+ undefined,+ { source: 'browser_push' });expect(handle.close).toHaveBeenCalledOnce();} finally {diff --git a/apps/web/src/features/notifications/tests/reminder-navigation.test.ts b/apps/web/src/features/notifications/tests/reminder-navigation.test.tsindex 376ef679ed..e37443dfe2 100644--- a/apps/web/src/features/notifications/tests/reminder-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/reminder-navigation.test.ts@@ -16,6 +16,9 @@ vi.mock('../notification-stacking', () => ({const flags = vi.hoisted(() => ({ reminders: true }));const getNotificationById = vi.hoisted(() => vi.fn());+const track = vi.hoisted(() => vi.fn());++vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));vi.mock('@app/features/calendar-view/calendar-range', () => ({createCalendarRange: vi.fn(),@@ -79,6 +82,47 @@ describe('reminder notification navigation', () => {flags.reminders = true;openWithSplit.mockReset();getNotificationById.mockReset();+ track.mockReset();+ });++ it('reports an in-app open with the notification type', async () => {+ await openNotification(reminderNotification(), layout);+ expect(track).toHaveBeenCalledExactlyOnceWith('notification_opened', {+ source: 'in_app',+ notificationType: 'reminder',+ entityType: 'email_thread',+ });+ });++ it('reports a native notification tap as a push open', async () => {+ const source = {+ notifications: () => [{ ...reminderNotification(), id: 'n-1' }],+ } as unknown as NotificationSource;+ await openNotificationFromId('n-1', layout, source);+ expect(track).toHaveBeenCalledExactlyOnceWith('notification_opened', {+ source: 'native_push',+ notificationType: 'reminder',+ entityType: 'email_thread',+ });+ });++ it('counts a retried native tap once, when its navigation applies', async () => {+ const source = {+ notifications: () => [{ ...reminderNotification(), id: 'n-1' }],+ } as unknown as NotificationSource;+ const onApplied = vi.fn();+ await openNotificationFromId('n-1', layout, source, { onApplied });+ await openNotificationFromId('n-1', layout, source, { onApplied });+ expect(track).not.toHaveBeenCalled();++ openWithSplit.mock.calls[1][1].onApplied();++ expect(track).toHaveBeenCalledExactlyOnceWith('notification_opened', {+ source: 'native_push',+ notificationType: 'reminder',+ entityType: 'email_thread',+ });+ expect(onApplied).toHaveBeenCalledOnce();});it('opens the original email thread', async () => {@@ -135,6 +179,7 @@ describe('reminder notification navigation', () => {notificationId: 'notification-1',});expect(openWithSplit).not.toHaveBeenCalled();+ expect(track).not.toHaveBeenCalled();});});vi.mock('@channel/queries/prefetch-channel-target', () => ({diff --git a/apps/web/src/features/onboarding/primitives/flow-storage.ts b/apps/web/src/features/onboarding/primitives/flow-storage.tsindex 155b4ab4a2..2759d5dafb 100644--- a/apps/web/src/features/onboarding/primitives/flow-storage.ts+++ b/apps/web/src/features/onboarding/primitives/flow-storage.ts@@ -16,6 +16,8 @@ const KEYS = {next: 'onboarding-flow-next',/** Inbox count when a connect started, to detect a landed link after reload. */connectBaseline: 'onboarding-flow-email-baseline',+ /** Tools whose connect started, so one that lands after GitHub's OAuth reload is still reported. */+ pendingConnectors: 'onboarding-flow-pending-connectors',/** Presentation choices from the signed-out slides. */signupDraft: 'onboarding-signup-draft',} as const;@@ -70,6 +72,7 @@ export const saveNext = (next: string) => write(KEYS.next, next);export function clearFlowProgress() {write(KEYS.step, undefined);write(KEYS.next, undefined);+ write(KEYS.pendingConnectors, undefined);}export function readConnectBaseline(): number | undefined {@@ -82,6 +85,27 @@ export function readConnectBaseline(): number | undefined {export const saveConnectBaseline = (count: number | undefined) =>write(KEYS.connectBaseline, count === undefined ? undefined : String(count));+export function readPendingConnectors(): ReadonlySet<string> {+ const raw = read(KEYS.pendingConnectors);+ if (raw === null) return new Set();+ try {+ const slugs: unknown = JSON.parse(raw);+ if (Array.isArray(slugs))+ return new Set(+ slugs.filter((slug): slug is string => typeof slug === 'string')+ );+ } catch {+ // Fall through: malformed state reports nothing.+ }+ return new Set();+}++export const savePendingConnectors = (slugs: ReadonlySet<string>) =>+ write(+ KEYS.pendingConnectors,+ slugs.size === 0 ? undefined : JSON.stringify([...slugs])+ );+export const readSignupDraft = () => parseSignupDraft(read(KEYS.signupDraft));export const saveSignupDraft = (draft: SignupDraft) =>diff --git a/apps/web/src/features/onboarding/views/tools-step.test.tsx b/apps/web/src/features/onboarding/views/tools-step.test.tsxindex 1fa083847a..1f5e21e7f3 100644--- a/apps/web/src/features/onboarding/views/tools-step.test.tsx+++ b/apps/web/src/features/onboarding/views/tools-step.test.tsx@@ -1,9 +1,16 @@import { cleanup, fireEvent, screen, waitFor } from '@solidjs/testing-library';import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ readPendingConnectors,+ savePendingConnectors,+} from '../primitives/flow-storage';import { renderWithFakeOnboarding } from '../tests/render';import { ToolsStep } from './tools-step';-afterEach(cleanup);+afterEach(() => {+ cleanup();+ sessionStorage.clear();+});describe('onboarding tools', () => {it('keeps Drive and Sheets available, hides excluded Google apps, and reuses native connections', async () => {@@ -112,3 +119,52 @@ it('distinguishes a linked GitHub account from repository setup', () => {);expect(fake.calls()).toContain('configureGithubRepositories');});+it('tracks a connector once its connection lands, not ones already connected', async () => {+ const { fake } = renderWithFakeOnboarding(+ () => <ToolsStep onContinue={vi.fn()} />,+ {+ catalog: [+ { slug: 'linear', name: 'Linear', iconUrl: null },+ { slug: 'notion', name: 'Notion', iconUrl: null },+ ],+ connectedTools: ['linear'],+ }+ );+ fireEvent.click(screen.getByRole('button', { name: 'Connect Notion' }));+ await waitFor(() =>+ expect(+ screen.getByRole('button', { name: 'Connected to Notion' })+ ).toBeTruthy()+ );+ expect(+ fake+ .events()+ .filter((item) => item.event === 'onboarding_v4_connector_connected')+ ).toEqual([+ {+ event: 'onboarding_v4_connector_connected',+ data: { connector: 'notion' },+ },+ ]);+});+it('reports a GitHub connect that lands after the OAuth reload', async () => {+ // Web GitHub OAuth reloads the page, so the step remounts with the link.+ savePendingConnectors(new Set(['github']));+ const { fake } = renderWithFakeOnboarding(+ () => <ToolsStep onContinue={vi.fn()} />,+ { githubLinkStatus: 'linked' }+ );+ await waitFor(() =>+ expect(+ fake+ .events()+ .filter((item) => item.event === 'onboarding_v4_connector_connected')+ ).toEqual([+ {+ event: 'onboarding_v4_connector_connected',+ data: { connector: 'github' },+ },+ ])+ );+ expect(readPendingConnectors().size).toBe(0);+});diff --git a/apps/web/src/features/onboarding/views/tools-step.tsx b/apps/web/src/features/onboarding/views/tools-step.tsxindex 62204c6566..ab40dfbae3 100644--- a/apps/web/src/features/onboarding/views/tools-step.tsx+++ b/apps/web/src/features/onboarding/views/tools-step.tsx@@ -1,9 +1,14 @@+import { canonicalPipedreamSlug } from '@core/pipedream/slugs';import { fireAndForget } from '@core/util/fireAndForget';import SearchIcon from '@phosphor/magnifying-glass.svg';-import { createSignal, For, Show } from 'solid-js';+import { createEffect, createSignal, For, Show } from 'solid-js';import { ContinueButton } from '../components/controls';import { ToolTile } from '../components/tool-tile';import { type Tool, useOnboardingContext } from '../context/onboarding-context';+import {+ readPendingConnectors,+ savePendingConnectors,+} from '../primitives/flow-storage';import { orderOnboardingTools } from '../primitives/tools';/** Uses the same searchable, paginated catalog and hosted connection flow as Settings. */@@ -13,6 +18,20 @@ export function ToolsStep(props: { onContinue: () => void }) {const connected = context.createConnectedTools({ poll: true });const entries = () => orderOnboardingTools(catalog.entries());const [busy, setBusy] = createSignal<string>();+ // Hosted OAuth finishes out of band, so a connection counts once polling+ // reports a tool this step started connecting. Kept in session storage+ // because GitHub's web OAuth reloads the page before its link lands.+ const [pending, setPending] = createSignal(readPendingConnectors());+ createEffect(() => savePendingConnectors(pending()));+ createEffect(() => {+ const landed = [...pending()].filter((slug) =>+ ['connected', 'account-linked'].includes(connected.state(slug))+ );+ if (landed.length === 0) return;+ for (const slug of landed)+ context.track('onboarding_v4_connector_connected', { connector: slug });+ setPending((set) => new Set([...set].filter((s) => !landed.includes(s))));+ });const connect = async (tool: Tool) => {if (@@ -21,6 +40,7 @@ export function ToolsStep(props: { onContinue: () => void }) {)return;setBusy(tool.slug);+ setPending((set) => new Set(set).add(canonicalPipedreamSlug(tool.slug)));try {await context.connectTool(tool);} finally {diff --git a/apps/web/src/features/routines/queries/routine-draft.ts b/apps/web/src/features/routines/queries/routine-draft.tsindex 2fb288b2f3..644646062f 100644--- a/apps/web/src/features/routines/queries/routine-draft.ts+++ b/apps/web/src/features/routines/queries/routine-draft.ts@@ -45,6 +45,15 @@ function getAgentTask(schedule: ScheduledAction): RoutineTask | undefined {return result.success ? result.data : undefined;}+/** Whether a routine runs an agent or a bare model; undefined when its task is unreadable. */+export function routineTargetKind(+ schedule: ScheduledAction+): RoutineTarget['kind'] | undefined {+ const task = getAgentTask(schedule);+ if (!task) return undefined;+ return task.agent ? 'agent' : 'model';+}+function targetFromTask(task: RoutineTask): RoutineTarget {if (task.agent) {if (task.model != null) {diff --git a/apps/web/src/features/routines/queries/routine-sources.ts b/apps/web/src/features/routines/queries/routine-sources.tsindex 9a8c80492f..8eba495c2d 100644--- a/apps/web/src/features/routines/queries/routine-sources.ts+++ b/apps/web/src/features/routines/queries/routine-sources.ts@@ -79,12 +79,16 @@ export function createRoutineDetailSource(const activate = useSetScheduleEnabledMutation({onError: (error) => callbacks.onError('Failed to update routine', error),});- const duplicate = useCreateScheduleMutation({- onSuccess: (created) => {- if (created.id) callbacks.onDuplicated(created.id);+ const duplicate = useCreateScheduleMutation(+ {+ onSuccess: (created) => {+ if (created.id) callbacks.onDuplicated(created.id);+ },+ onError: (error) =>+ callbacks.onError('Failed to duplicate routine', error),},- onError: (error) => callbacks.onError('Failed to duplicate routine', error),- });+ 'duplicate'+ );const history = useScheduleHistoryQuery(id, () =>Boolean(raw() && raw()?.owner === userId()));diff --git a/apps/web/src/features/routines/queries/schedules.test.tsx b/apps/web/src/features/routines/queries/schedules.test.tsxindex 605c3cab06..a9931d54f3 100644--- a/apps/web/src/features/routines/queries/schedules.test.tsx+++ b/apps/web/src/features/routines/queries/schedules.test.tsx@@ -5,12 +5,20 @@ import { err, ok } from 'neverthrow';import { render } from 'solid-js/web';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { scheduledActionKeys } from './keys';-import { useSetScheduleEnabledMutation } from './schedules';+import {+ useCreateScheduleMutation,+ useRunScheduleNowMutation,+ useSetScheduleEnabledMutation,+} from './schedules';const setEnabled = vi.hoisted(() => vi.fn());+const createSchedule = vi.hoisted(() => vi.fn());+const runNow = vi.hoisted(() => vi.fn());+const track = vi.hoisted(() => vi.fn());vi.mock('@service-scheduled-action/client', () => ({- scheduledActionClient: { setEnabled },+ scheduledActionClient: { setEnabled, createSchedule, runNow },}));+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));vi.mock('@queries/client', async () => {const { QueryClient } = await import('@tanstack/solid-query');return { queryClient: new QueryClient() };@@ -67,6 +75,9 @@ function schedules(): ScheduledAction[] | undefined {beforeEach(() => {setEnabled.mockReset();+ createSchedule.mockReset();+ runNow.mockReset();+ track.mockReset();queryClient.setQueryData(scheduledActionKeys.list.queryKey, [routine, other]);});@@ -139,3 +150,91 @@ describe('routine activation', () => {expect(schedules()).toEqual([{ ...routine, claimed }, other]);});});++describe('routine analytics', () => {+ const agentRoutine: ScheduledAction = {+ ...routine,+ task: {+ agent: { bot_id: '01a15c48-43af-7050-9059-8c5e46d6d7d7' },+ prompt: '',+ user_prompt: 'Post the daily metrics',+ },+ };++ const request = {+ name: agentRoutine.name,+ kind: agentRoutine.kind,+ task: agentRoutine.task,+ trigger: agentRoutine.trigger,+ enabled: true,+ };++ function mountRoutineMutations() {+ let mutations!: {+ create: ReturnType<typeof useCreateScheduleMutation>;+ duplicate: ReturnType<typeof useCreateScheduleMutation>;+ run: ReturnType<typeof useRunScheduleNowMutation>;+ };+ function Probe() {+ mutations = {+ create: useCreateScheduleMutation(),+ duplicate: useCreateScheduleMutation(undefined, 'duplicate'),+ run: useRunScheduleNowMutation(),+ };+ return null;+ }+ dispose = render(+ () => (+ <QueryClientProvider client={queryClient}>+ <Probe />+ </QueryClientProvider>+ ),+ document.createElement('div')+ );+ return mutations;+ }++ it('reports created and duplicated routines, but not failed ones', async () => {+ createSchedule.mockResolvedValue(ok(agentRoutine));+ const mutations = mountRoutineMutations();++ await mutations.create.mutateAsync(request);+ await mutations.duplicate.mutateAsync(request);+ createSchedule.mockResolvedValueOnce(err([{ message: 'Invalid' }]));+ await expect(mutations.create.mutateAsync(request)).rejects.toBeDefined();++ expect(track.mock.calls).toEqual([+ [+ 'routine_created',+ {+ routineId: 'routine',+ source: 'new',+ triggerType: 'cron',+ targetKind: 'agent',+ },+ ],+ [+ 'routine_created',+ expect.objectContaining({ routineId: 'routine', source: 'duplicate' }),+ ],+ ]);+ });++ it('reports an accepted manual run with the target kind from the list cache', async () => {+ queryClient.setQueryData(scheduledActionKeys.list.queryKey, [agentRoutine]);+ runNow.mockResolvedValue(ok({}));+ const mutations = mountRoutineMutations();++ await mutations.run.mutateAsync({ scheduleId: 'routine' });+ runNow.mockResolvedValueOnce(err([{ message: 'Busy' }]));+ await expect(+ mutations.run.mutateAsync({ scheduleId: 'routine' })+ ).rejects.toBeDefined();++ expect(track).toHaveBeenCalledExactlyOnceWith('routine_run', {+ routineId: 'routine',+ trigger: 'manual',+ targetKind: 'agent',+ });+ });+});diff --git a/apps/web/src/features/routines/queries/schedules.ts b/apps/web/src/features/routines/queries/schedules.tsindex 02f9dead54..61f2bee82b 100644--- a/apps/web/src/features/routines/queries/schedules.ts+++ b/apps/web/src/features/routines/queries/schedules.ts@@ -1,3 +1,4 @@+import { analytics } from '@app/lib/analytics';import { throwOnErr } from '@core/util/result';import { queryClient } from '@queries/client';import { type MutationCallbacks, withCallbacks } from '@queries/utils';@@ -16,6 +17,7 @@ import {} from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { scheduledActionKeys } from './keys';+import { routineTargetKind } from './routine-draft';const QUERY_REFETCH_BEHAVIOR = {refetchOnMount: 'always' as const,@@ -128,7 +130,9 @@ function _invalidateScheduleHistory(scheduleId: string) {}export function useCreateScheduleMutation(- callbacks?: MutationCallbacks<ScheduledAction, Error, CreateScheduledAction>+ callbacks?: MutationCallbacks<ScheduledAction, Error, CreateScheduledAction>,+ /** Whether the user created the routine or duplicated one, for analytics. */+ source: 'new' | 'duplicate' = 'new') {return useMutation(() => ({mutationFn: async (request: CreateScheduledAction) =>@@ -138,6 +142,13 @@ export function useCreateScheduleMutation(...withCallbacks({onSuccess: async (schedule) => {+ // Client-side until scheduled_action reports to PostHog itself.+ analytics.track('routine_created', {+ routineId: schedule.id ?? undefined,+ source,+ triggerType: schedule.trigger.type,+ targetKind: routineTargetKind(schedule),+ });upsertSchedule(schedule);await invalidateSchedules();},@@ -277,6 +288,28 @@ export function useRunScheduleNowMutation(throwOnErr(async () => await scheduledActionClient.runNow({ scheduleId })),- ...withCallbacks({}, callbacks),+ ...withCallbacks(+ {+ // A run the server accepted, not its outcome; scheduled and event+ // runs never pass through the client.+ onSuccess: (_execution, { scheduleId }) => {+ const schedule =+ queryClient.getQueryData<ScheduledAction>(+ scheduledActionKeys.detail({ scheduleId }).queryKey+ ) ??+ queryClient+ .getQueryData<ScheduledAction[]>(+ scheduledActionKeys.list.queryKey+ )+ ?.find((item) => item.id === scheduleId);+ analytics.track('routine_run', {+ routineId: scheduleId,+ trigger: 'manual',+ targetKind: schedule && routineTargetKind(schedule),+ });+ },+ },+ callbacks+ ),}));}diff --git a/apps/web/src/features/soup/search/create-search-state.test.ts b/apps/web/src/features/soup/search/create-search-state.test.tsnew file mode 100644index 0000000000..9b0bea03a4--- /dev/null+++ b/apps/web/src/features/soup/search/create-search-state.test.ts@@ -0,0 +1,127 @@+import { createRoot, createSignal } from 'solid-js';+import { createStore } from 'solid-js/store';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';++const track = vi.hoisted(() => vi.fn());+vi.mock('@app/lib/analytics', () => ({ analytics: { track } }));+vi.mock('./context', () => ({ useOptionalSearchContext: () => undefined }));++const [query, setQuery] = createStore({+ isSuccess: false,+ isPlaceholderData: false,+ isFetching: false,+ isFetchingNextPage: false,+ data: [] as { id: string }[],+});+vi.mock('@queries/soup/search', () => ({+ useSearchSoupQuery: () => query,+ validateSearchServiceText: (text: string) => text.length >= 3,+}));++import { createSearchState } from './create-search-state';++beforeEach(() => {+ vi.useFakeTimers();+ track.mockReset();+ setQuery({ isSuccess: false, isFetching: false, data: [] });+});+afterEach(() => {+ vi.useRealTimers();+});++function land(count: number) {+ setQuery({+ isSuccess: true,+ isFetching: false,+ data: Array.from({ length: count }, (_, index) => ({ id: `${index}` })),+ });+}++it('reports only the query the user settles on', () => {+ const [text, setText] = createSignal('');+ const dispose = createRoot((dispose) => {+ createSearchState({+ surface: () => 'email',+ text,+ disableLocalSearch: () => true,+ buildRequest: ({ query, matchType }) => ({+ params: {},+ body: { query, match_type: matchType },+ }),+ });+ return dispose;+ });++ setText('inv');+ vi.advanceTimersByTime(300);+ land(3);+ setQuery({ isFetching: true });+ setText('invoice');+ vi.advanceTimersByTime(300);+ land(12);+ vi.advanceTimersByTime(1500);+ // A refetch or a later page of the same query is not another search.+ setQuery({ isFetching: true });+ land(40);+ vi.advanceTimersByTime(1500);+ dispose();++ expect(track).toHaveBeenCalledExactlyOnceWith('search_performed', {+ surface: 'email',+ matchType: 'partial',+ resultCount: '10-49',+ });+});++it('reports a pending search when the surface closes', () => {+ const dispose = createRoot((dispose) => {+ createSearchState({+ surface: () => 'drive',+ text: () => '"roadmap"',+ disableLocalSearch: () => true,+ buildRequest: ({ query, matchType }) => ({+ params: {},+ body: { query, match_type: matchType },+ }),+ });+ return dispose;+ });+ land(0);+ expect(track).not.toHaveBeenCalled();+ dispose();+ expect(track).toHaveBeenCalledExactlyOnceWith('search_performed', {+ surface: 'drive',+ matchType: 'exact',+ resultCount: '0',+ });+});++it('counts the same query again after the box is cleared', () => {+ const [text, setText] = createSignal('');+ const dispose = createRoot((dispose) => {+ createSearchState({+ surface: () => 'search',+ text,+ disableLocalSearch: () => true,+ buildRequest: ({ query, matchType }) => ({+ params: {},+ body: { query, match_type: matchType },+ }),+ });+ return dispose;+ });++ setText('invoice');+ vi.advanceTimersByTime(300);+ land(3);+ vi.advanceTimersByTime(1500);+ setText('');+ vi.advanceTimersByTime(300);+ setText('invoice');+ vi.advanceTimersByTime(300);+ land(3);+ vi.advanceTimersByTime(1500);+ dispose();++ expect(track).toHaveBeenCalledTimes(2);+});diff --git a/apps/web/src/features/soup/search/create-search-state.ts b/apps/web/src/features/soup/search/create-search-state.tsindex 609b988f02..895ad5d3be 100644--- a/apps/web/src/features/soup/search/create-search-state.ts+++ b/apps/web/src/features/soup/search/create-search-state.ts@@ -1,3 +1,4 @@+import { analytics } from '@app/lib/analytics';import { arrayEquals } from '@core/util/compareUtils';import { debouncedDependent } from '@core/util/debounce';import { type EntityData, isChannelEntity } from '@entity/types/entity';@@ -7,13 +8,21 @@ import {useSearchSoupQuery,validateSearchServiceText,} from '@queries/soup/search';-import { type Accessor, createMemo } from 'solid-js';+import {+ type Accessor,+ createEffect,+ createMemo,+ onCleanup,+ untrack,+} from 'solid-js';import { type SoupSearchPoolEntry, useOptionalSearchContext } from './context';import { createSoupFreshSearch, nameFuzzySearchFilter } from './utils';const LOCAL_SEARCH_DEBOUNCE_MS = 20;const SERVICE_SEARCH_DEBOUNCE_MS = 300;const FEATURED_RESULT_COUNT = 3;+/** A query whose results stay unreplaced this long counts as one search. */+const SEARCH_SETTLE_MS = 1500;export type SoupSearchMatchType = 'exact' | 'partial';@@ -23,6 +32,8 @@ export type SoupSearchRequest = {};export type CreateSearchStateOptions = {+ /** Where the search runs (a view id such as 'search' or 'email'), for analytics. */+ surface: Accessor<string>;text: Accessor<string>;buildRequest: (search: SoupSearchRequest) => SearchSoupQueryArgs;enabled?: Accessor<boolean>;@@ -45,6 +56,56 @@ export function soupSearchMatchType(query: string): SoupSearchMatchType {const freshSearch = createSoupFreshSearch();+/** Coarse result-count buckets; the first page caps the count. */+function searchResultCountBucket(count: number): string {+ if (count === 0) return '0';+ if (count < 10) return '1-9';+ if (count < 50) return '10-49';+ return '50+';+}++/**+ * Reports one `search_performed` per settled service query. Results landing+ * for a newer query replace the pending report, so typing reports only the+ * query the user stopped on; leaving the surface reports it at once. Once+ * service search turns off (the box is cleared), the same query counts again.+ */+function trackSettledSearches(+ surface: Accessor<string>,+ searching: Accessor<boolean>,+ landed: Accessor<+ { query: string; matchType: SoupSearchMatchType; count: number } | undefined+ >+) {+ // Refetches and later pages of the same query are not new searches.+ let lastQuery: string | undefined;+ let pending: (() => void) | undefined;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const flush = () => {+ clearTimeout(timer);+ pending?.();+ pending = undefined;+ };+ createEffect(() => {+ if (!searching()) {+ lastQuery = undefined;+ return;+ }+ const search = landed();+ if (!search || search.query === lastQuery) return;+ lastQuery = search.query;+ clearTimeout(timer);+ const properties = {+ surface: untrack(surface),+ matchType: search.matchType,+ resultCount: searchResultCountBucket(search.count),+ };+ pending = () => analytics.track('search_performed', properties);+ timer = setTimeout(flush, SEARCH_SETTLE_MS);+ });+ onCleanup(flush);+}+/*** Combines local quick-access search with service-backed results while* retaining the established Soup search behavior.@@ -118,6 +179,21 @@ export function createSearchState(options: CreateSearchStateOptions) {return searchQuery.data ?? [];});+ trackSettledSearches(options.surface, queryEnabled, () => {+ const query = serviceText();+ if (+ !searchQuery.isSuccess ||+ searchQuery.isPlaceholderData ||+ searchQuery.isFetching+ )+ return undefined;+ return {+ query,+ matchType: soupSearchMatchType(query),+ count: searchQuery.data?.length ?? 0,+ };+ });+const featuredIds = createMemo<string[]>(() => localFuzzyResults().map((entity) => entity.id),[],diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.tsindex c16aa35f80..e0fcc1b13d 100644--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts@@ -219,6 +219,7 @@ export function useTasksDataSource(enabled: facetOptionsReady,}): createSearchState({+ surface: () => 'tasks',text: () => state.search,localPool,enabled: facetOptionsReady,diff --git a/apps/web/src/lib/analytics/app-events.ts b/apps/web/src/lib/analytics/app-events.tsindex 474ab37d6e..201d4999df 100644--- a/apps/web/src/lib/analytics/app-events.ts+++ b/apps/web/src/lib/analytics/app-events.ts@@ -159,6 +159,11 @@ export type AppEvents = {* An entity was opened in a split (md, task, pdf, chat, email, channel,* canvas, code, project, company, contact, ...). Fired from BlockLoader on* successful load; nested blocks and preview-panel peeks are excluded.+ * Route-owned detail views fire it themselves: documents from+ * FileDetailLoadGate, channels from ChannelDetail, calls and PRs from their+ * detail views. Blocks without an open history row fire it only when they+ * set `openAnalyticsEnabled` (database); calendar does not, since it loads+ * one fixed id and `open_view` already counts it.*/open_entity: EntityEventPayload;/**@@ -167,6 +172,11 @@ export type AppEvents = {* split-layout component registry.*/open_view: { viewId: string } & Record<string, unknown>;+ /**+ * Agent sessions report create, rename (`update_entity`) and delete as+ * `entityType: 'agent'`, the type their `open_entity` carries. The retired+ * AI chat reported `chat`; count both for AI conversations over time.+ */create_entity: EntityEventPayload;update_entity: EntityEventPayload & {/** Which property changed: 'name' | 'parent_project' | 'status' | ... */@@ -188,7 +198,18 @@ export type AppEvents = {theme_changed: { themeId: string };+ /**+ * A message sent to AI, with `attachmentCount` files. `surface` is 'chat'+ * for the legacy AI chat and 'agent' for an accepted agent-session prompt+ * (AgentSession.sendPrompt), which also carries `agentSessionId`,+ * `agentId`, `newSession`, `submitSurface` and `queued`. Events before the+ * agent tracking have no `surface`.+ */ai_message_sent: Record<string, unknown>;+ /**+ * A file added to the legacy AI chat's input, on upload or drop. Agent+ * sessions report attachments as `ai_message_sent.attachmentCount` instead.+ */ai_attachment_add: Record<string, unknown>;/** A paid user opened Stripe Checkout for an AI credit pack. */ai_credits_checkout_start: { amountCents: number };@@ -198,6 +219,21 @@ export type AppEvents = {plan_changed: { plan: 'premium' | 'max'; from?: string };email_message_sent: Record<string, unknown>;+ /**+ * How the inbox-link OAuth callback ended. `connected` covers re-linking an+ * inbox that was already connected; the client cannot tell them apart.+ */+ email_link_callback_result: {+ outcome:+ | 'connected'+ | 'already_initialized'+ | 'shared_inbox_conflict'+ | 'payment_required'+ | 'no_gmail_grant'+ | 'failed'+ | 'exception'+ | 'missing_link_id';+ };channel_message_sent: Record<string, unknown>;channel_messages_load: {@@ -211,8 +247,9 @@ export type AppEvents = {};// --- Calls ---------------------------------------------------------------- // Frontend call interactions. Authoritative lifecycle (ended, recording,- // summary) is server-driven and tracked backend-side.+ // Frontend call interactions only. Recordings, transcripts and summaries+ // are produced server-side and send no PostHog events yet; the call service+ // publishes them only to Kafka (`call.recording_ready`, `call.record_summarized`).call_action: {action:| 'join_clicked'@@ -247,6 +284,106 @@ export type AppEvents = {block_pdf_definition_open: Record<string, unknown>;block_pdf_section_open: Record<string, unknown>;++ // --- Databases -----------------------------------------------------------+ /** A committed ops batch wrote rows of a database (grid, board, forms). */+ database_rows_edited: {+ databaseId: string;+ insertedRows: number;+ updatedRows: number;+ deletedRows: number;+ };+ /**+ * A database grid read its view: once when a view opens (a view switch+ * included) and once per filter or sort change that settles for a second.+ * Refreshes, live updates and layout edits are not counted. `host` tells a+ * database's own page from a grid embedded in a document or a form's+ * responses; only `block` opens are database opens.+ */+ database_query_run: {+ databaseId: string;+ tableId: string;+ viewId: string;+ host: 'block' | 'document' | 'form';+ trigger: 'open' | 'query_change';+ /** Top-level filter conditions; 0 when unfiltered. */+ filterConditions: number;+ sortKeys: number;+ };++ // --- Calendar ------------------------------------------------------------+ calendar_event_created: {+ eventId: string;+ attendees: number;+ recurring: boolean;+ macroCall: boolean;+ conference: boolean;+ };+ calendar_event_rsvp: {+ response: 'accepted' | 'declined' | 'tentative';+ scope: 'all' | 'this_event';+ };++ // --- Notifications -------------------------------------------------------+ /**+ * A notification was opened: from the app's lists and stacks (`in_app`), a+ * browser notification, a native iOS, Android or macOS notification tap+ * (`native_push`, counted once its navigation applies; `macro_device` tells+ * the platforms apart), or a home recommendation that opens through its+ * notification (`home_recommendation`, not a notification-driven open).+ */+ notification_opened: {+ source: 'in_app' | 'browser_push' | 'native_push' | 'home_recommendation';+ notificationType: string;+ entityType: string;+ };++ // --- Search --------------------------------------------------------------+ /**+ * One service search per settled query: a query whose results stay+ * unreplaced for 1.5s, or the last one when the surface closes. Refetches+ * and later pages of the same query are not counted; no query text is sent.+ */+ search_performed: {+ /** View id ('search', 'email', 'tasks', ...), 'home', or 'mobile_search'. */+ surface: string;+ matchType: 'exact' | 'partial';+ /** First page only: '0' | '1-9' | '10-49' | '50+'. */+ resultCount: string;+ };++ // --- CRM -----------------------------------------------------------------+ crm_company_created: { companyId: string };+ crm_contact_created: { companyId: string; contactId: string };+ /**+ * A committed pipeline write: inserted rows are entries added, updated+ * rows include stage moves and other cell edits.+ */+ crm_pipeline_entries_edited: {+ pipelineId: string;+ recordType?: 'company' | 'contact';+ /** The pipeline editor or the record page's pipeline cards. */+ surface: 'pipeline' | 'record';+ insertedRows: number;+ updatedRows: number;+ deletedRows: number;+ };++ // --- Routines ------------------------------------------------------------+ // Client-side until the scheduled_action service reports to PostHog;+ // scheduled and event-triggered runs are not counted yet.+ routine_created: {+ routineId?: string;+ source: 'new' | 'duplicate';+ triggerType: string;+ targetKind?: 'agent' | 'model';+ };+ /** A manual Run now the server accepted, not the run's outcome. */+ routine_run: {+ routineId: string;+ trigger: 'manual';+ targetKind?: 'agent' | 'model';+ };};export type AppEventNames = keyof AppEvents;diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsindex 9ee1055cef..440124ed22 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -143,6 +143,8 @@ function invalidate(id = SESSION) {for (const listener of updates.listeners) listener({ agentSessionId: id });}+const analytics = vi.hoisted(() => ({ track: vi.fn() }));+vi.mock('@app/lib/analytics', () => ({ analytics }));vi.mock('@core/agent-fold/client', () => fold);vi.mock('@service-agent-harness/client', () => ({agentHarnessServiceClient: harness,@@ -310,6 +312,55 @@ describe('AgentSession', () => {live.release();});+ it('counts an accepted prompt as an agent AI message, and nothing else', async () => {+ harness.get.mockResolvedValue(ok({ ...session, botId: 'bot-id' }));+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({ type: 'stop' });+ await live.issue({ type: 'prompt', prompt: 'hi' });+ harness.control.mockResolvedValueOnce(err([{ code: 'FORBIDDEN' }]));+ await live.issue({ type: 'prompt', prompt: 'refused' });+ await settle();++ expect(analytics.track.mock.calls).toEqual([+ [+ 'ai_message_sent',+ {+ surface: 'agent',+ agentSessionId: SESSION,+ agentId: 'bot-id',+ newSession: false,+ submitSurface: 'agent_session',+ queued: false,+ attachmentCount: 0,+ },+ ],+ ]);+ live.release();+ });++ it('reports the files an accepted prompt carries on its AI message', async () => {+ const live = AgentSession.acquire(SESSION);+ await live.load();++ await live.issue({+ type: 'prompt',+ prompt: 'see these',+ attachments: [+ { uri: 'https://files.test/a', name: 'a.pdf' },+ { uri: 'https://files.test/b', name: 'b.png' },+ ],+ });+ await settle();++ expect(analytics.track).toHaveBeenCalledExactlyOnceWith(+ 'ai_message_sent',+ expect.objectContaining({ surface: 'agent', attachmentCount: 2 })+ );+ live.release();+ });+it('reissues the speculation under the id the harness minted instead', async () => {harness.control.mockResolvedValue(ok({ actionId: 'server-id', status: 'sent' })diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.tsindex f2044c7fd5..ced0ca213d 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts@@ -19,6 +19,7 @@* rows the socket delivers after it are appended to the cached copy here.*/+import { analytics } from '@app/lib/analytics';import {AgentFoldWorkerUnavailable,closeSession,@@ -470,7 +471,14 @@ export class AgentSession {new Error(result.error.map((error) => error.message).join(' ')));} else {- trace.accepted(result.value.actionId, result.value.status === 'queued');+ const queued = result.value.status === 'queued';+ trace.accepted(result.value.actionId, queued);+ const attachments =+ request.type === 'prompt' ? (request.attachments?.length ?? 0) : 0;+ fireAndForget(+ this.trackPromptSent(trace, queued, attachments),+ 'agent-session'+ );}return result;} catch (error) {@@ -483,6 +491,28 @@ export class AgentSession {}}+ /**+ * Count an accepted prompt as an AI message, with the files it carries as+ * `attachmentCount`, as the retired AI chat reported its messages, so AI+ * engagement keeps one definition across both.+ */+ private async trackPromptSent(+ trace: PromptTrace,+ queued: boolean,+ attachmentCount: number+ ): Promise<void> {+ const row = await this.sessionRow;+ analytics.track('ai_message_sent', {+ surface: 'agent',+ agentSessionId: this.id,+ agentId: row.isOk() ? row.value.botId : undefined,+ newSession: trace.newSession,+ submitSurface: trace.submitSurface,+ queued,+ attachmentCount,+ });+ }+/*** Show an action the server already holds as if it had dispatched. Nothing* is sent: the server queued this action earlier under `actionId`, and thediff --git a/apps/web/src/lib/core/agent-session/prompt-telemetry.ts b/apps/web/src/lib/core/agent-session/prompt-telemetry.tsindex 426f782d66..cbbac61779 100644--- a/apps/web/src/lib/core/agent-session/prompt-telemetry.ts+++ b/apps/web/src/lib/core/agent-session/prompt-telemetry.ts@@ -149,6 +149,10 @@ const CREATE_PATH = /\/agent-sessions$/;const CONTROL_PATH = /\/agent-sessions\/[^/]+\/control$/;export class PromptTrace {+ /** The prompt opens a new session rather than continuing one. */+ readonly newSession: boolean;+ /** The bounded UI origin the prompt was submitted from. */+ readonly submitSurface: PromptSubmitSurface;readonly #span: Span | undefined;readonly #sessionId: string;readonly #startedAt = performance.now();@@ -170,7 +174,10 @@ export class PromptTrace {constructor(sessionId: string, options: PromptTraceOptions) {this.#sessionId = sessionId;- this.#span = start(sessionId, options);+ this.newSession = options.newSession;+ this.submitSurface =+ options.submitSurface ?? submitSurface(options.newSession);+ this.#span = start(sessionId, options, this.submitSurface);this.#recordInputDelay();if (options.newSession) this.#watchResponse('created', CREATE_PATH);this.#stallTimer = setTimeout(@@ -511,16 +518,14 @@ function messagesOf(event: FoldedStreamEvent): FoldedMessage[] {function start(sessionId: string,- options: PromptTraceOptions+ options: PromptTraceOptions,+ surface: PromptSubmitSurface): Span | undefined {try {const span = Telemetry.span('agent.prompt');span.setAttr('agent.session.id', sessionId);span.setAttr('agent.prompt.new_session', options.newSession);- span.setAttr(- 'agent.prompt.submit_surface',- options.submitSurface ?? submitSurface(options.newSession)- );+ span.setAttr('agent.prompt.submit_surface', surface);if (options.create) {const { warmClaim, modelOverride, modelFallback, effort } =options.create;diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.tsindex 57bea29436..15f20aecd6 100644--- a/apps/web/src/lib/core/block.ts+++ b/apps/web/src/lib/core/block.ts@@ -394,9 +394,16 @@ export type BlockDefinition</** flag to indicate wether this block should enable collaborative features. */liveTrackingEnabled?: boolean;- /** Whether mounting this block records entity-open analytics and history. */+ /** Whether mounting this block records an entity-open history row and page view. */openTrackingEnabled?: boolean;+ /**+ * Whether mounting this block sends `open_entity`. Defaults to+ * `openTrackingEnabled`; set it on a block without a history row whose opens+ * are still a product signal, as `block-database` does.+ */+ openAnalyticsEnabled?: boolean;+accepted: Record<string, string>;/** The default name of the file when creating a new block of this type. */diff --git a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts b/apps/web/src/lib/core/component/AI/component/input/buildRequest.tsindex 6c81626a32..fef4f00407 100644--- a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts+++ b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts@@ -69,6 +69,7 @@ export function useSendChatMessage() {}analytics.track('ai_message_sent', {+ surface: 'chat',model: model ?? DEFAULT_MODEL,attachmentCount: attachments.length,});diff --git a/apps/web/src/lib/core/internal/BlockLoader.test.tsx b/apps/web/src/lib/core/internal/BlockLoader.test.tsxindex ad30822365..be5430465e 100644--- a/apps/web/src/lib/core/internal/BlockLoader.test.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.test.tsx@@ -6,16 +6,20 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest';vi.mock('@core/context/user', () => ({ useIsAuthenticated: () => () => true }));+let nested = true;vi.mock('@core/block', () => ({createBlockSignal<T>() {const signal = createSignal<T>();return Object.assign(signal, { get: signal[0], set: signal[1] });},- useIsNestedBlock: () => true,+ useIsNestedBlock: () => nested,}));+const analytics = vi.hoisted(() => ({ track: vi.fn(), pageView: vi.fn() }));vi.mock('@app/lib/analytics/analytics-context', () => ({- useAnalytics: () => ({}),+ useAnalytics: () => analytics,}));+const trackBlockOpened = vi.hoisted(() => vi.fn());+vi.mock('./trackBlockOpened', () => ({ track: trackBlockOpened }));vi.mock('@queries/client', () => ({ useQueryClient: () => ({}) }));vi.mock('@service-storage/client', () => ({blockNameToItemType: () => 'document',@@ -49,6 +53,10 @@ import { BlockLoader, blockDataSignal } from './BlockLoader';afterEach(cleanup);beforeEach(() => {+ nested = true;+ analytics.track.mockClear();+ analytics.pageView.mockClear();+ trackBlockOpened.mockClear();blockDataSignal.set(undefined);blockErrorSignal.set(undefined);blockLoadRetrySignal.set(undefined);@@ -349,3 +357,56 @@ it('drops a revoked open document, cleans its source, and loads fresh credentialexpect(blockErrorSignal.get()).toBeNull();expect(blockLoadRetrySignal.get()).toBe(1);});++it('reports an open for a block without open history that asks for it', async () => {+ nested = false;+ render(() => (+ <BlockLoader+ id="01a1460f-3198-7650-9b32-a43b49108e47"+ source={{ type: 'dss', id: '01a1460f-3198-7650-9b32-a43b49108e47' }}+ definition={{+ name: 'database',+ description: 'Database',+ accepted: {},+ component: () => null,+ openTrackingEnabled: false,+ openAnalyticsEnabled: true,+ load: async () => ok({ id: 'database' }),+ }}+ />+ ));+ await vi.waitFor(() =>+ expect(analytics.track).toHaveBeenCalledWith('open_entity', {+ entityType: 'database',+ entityId: '01a1460f-3198-7650-9b32-a43b49108e47',+ })+ );+ expect(analytics.pageView).not.toHaveBeenCalled();+ expect(trackBlockOpened).not.toHaveBeenCalled();+});++it('reports no open for a block without open history by default', async () => {+ nested = false;+ render(() => (+ <BlockLoader+ id="calendar"+ source={{ type: 'dss', id: 'calendar' }}+ definition={{+ name: 'calendar',+ description: 'Calendar',+ accepted: {},+ component: () => null,+ openTrackingEnabled: false,+ load: async () => ok({ id: 'calendar' }),+ }}+ />+ ));+ await vi.waitFor(() =>+ expect(blockDataSignal.get()).toMatchObject({ id: 'calendar' })+ );+ expect(analytics.track).not.toHaveBeenCalledWith(+ 'open_entity',+ expect.anything()+ );+ expect(analytics.pageView).not.toHaveBeenCalled();+});diff --git a/apps/web/src/lib/core/internal/BlockLoader.tsx b/apps/web/src/lib/core/internal/BlockLoader.tsxindex 9a26d21f2c..23a7b21529 100644--- a/apps/web/src/lib/core/internal/BlockLoader.tsx+++ b/apps/web/src/lib/core/internal/BlockLoader.tsx@@ -198,8 +198,9 @@ Check that the load function does not return a preload source when the intent isconst data = result.value;setError(null);- if (!isNested && data && props.definition.openTrackingEnabled !== false) {- const trackOpened = () => {+ if (!isNested && data) {+ const tracksOpenHistory = props.definition.openTrackingEnabled !== false;+ if (tracksOpenHistory) {// we need to pass in a client accessor since the mutation is dynamically imported outside a query context providerimport('./trackBlockOpened').then(({ track }) => {@@ -218,13 +219,13 @@ Check that the load function does not return a preload source when the intent is);analytics.pageView(data.__block);+ }++ if (props.definition.openAnalyticsEnabled ?? tracksOpenHistory)analytics.track('open_entity', {entityType: data.__block,entityId: props.id,});- };-- trackOpened();}setData(() => data);diff --git a/apps/web/src/lib/queries/agent-session/entity-mutations.test.ts b/apps/web/src/lib/queries/agent-session/entity-mutations.test.tsindex 67bf191f10..568cfe3338 100644--- a/apps/web/src/lib/queries/agent-session/entity-mutations.test.ts+++ b/apps/web/src/lib/queries/agent-session/entity-mutations.test.ts@@ -7,7 +7,9 @@ const mocks = vi.hoisted(() => ({changed: vi.fn(),invalidate: vi.fn(),soup: vi.fn(),+ track: vi.fn(),}));+vi.mock('@app/lib/analytics', () => ({ analytics: { track: mocks.track } }));vi.mock('@service-agent-harness/client', () => ({agentHarnessServiceClient: { rename: mocks.rename, delete: mocks.delete },}));@@ -32,6 +34,11 @@ it('renames through the owning API and refreshes shared consumers', async () =>});expect(mocks.soup).toHaveBeenCalledOnce();expect(mocks.invalidate).toHaveBeenCalledTimes(2);+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith('update_entity', {+ entityType: 'agent',+ entityId: 'session',+ property: 'name',+ });});it('does not publish a failed rename', async () => {mocks.rename.mockResolvedValue(err(new Error('forbidden')));@@ -40,10 +47,15 @@ it('does not publish a failed rename', async () => {).rejects.toBeDefined();expect(mocks.changed).not.toHaveBeenCalled();expect(mocks.soup).not.toHaveBeenCalled();+ expect(mocks.track).not.toHaveBeenCalled();});it('deletes through the owning API, not a document deletion', async () => {mocks.delete.mockResolvedValue(ok(undefined));await deleteAgentSession('session');expect(mocks.delete).toHaveBeenCalledWith('session');expect(mocks.soup).toHaveBeenCalledOnce();+ expect(mocks.track).toHaveBeenCalledExactlyOnceWith('delete_entity', {+ entityType: 'agent',+ entityId: 'session',+ });});diff --git a/apps/web/src/lib/queries/agent-session/entity-mutations.ts b/apps/web/src/lib/queries/agent-session/entity-mutations.tsindex 18f84b054c..7c94fa7089 100644--- a/apps/web/src/lib/queries/agent-session/entity-mutations.ts+++ b/apps/web/src/lib/queries/agent-session/entity-mutations.ts@@ -1,3 +1,4 @@+import { analytics } from '@app/lib/analytics';import { fireAndForget } from '@core/util/fireAndForget';import { throwOnErr } from '@core/util/result';import { agentHarnessServiceClient } from '@service-agent-harness/client';@@ -17,8 +18,14 @@ function refreshSessionEntity(id: string) {});}+// Agent sessions report as `agent`, as BlockLoader reports their opens.export async function renameAgentSession(id: string, name: string) {await throwOnErr(() => agentHarnessServiceClient.rename(id, name));+ analytics.track('update_entity', {+ entityType: 'agent',+ entityId: id,+ property: 'name',+ });handleAgentSessionRenamed({ agentSessionId: id, name });refreshSessionEntity(id);}@@ -30,5 +37,6 @@ export async function setAgentSessionArchived(id: string, isArchived: boolean) {export async function deleteAgentSession(id: string) {await throwOnErr(() => agentHarnessServiceClient.delete(id));+ analytics.track('delete_entity', { entityType: 'agent', entityId: id });refreshSessionEntity(id);}diff --git a/apps/web/src/lib/queries/calendar/mutations.ts b/apps/web/src/lib/queries/calendar/mutations.tsindex de3aae0616..0642fab793 100644--- a/apps/web/src/lib/queries/calendar/mutations.ts+++ b/apps/web/src/lib/queries/calendar/mutations.ts@@ -1,3 +1,4 @@+import { analytics } from '@app/lib/analytics';import { fireAndForget } from '@core/util/fireAndForget';import { thrownResultErrorHasCode, throwOnErr } from '@core/util/result';import { Telemetry } from '@macro-inc/observability';@@ -329,6 +330,12 @@ export function useRsvpCalendarEventMutation(callbacks?: RsvpCallbacks) {},};},+ onSuccess: (_data, args) => {+ analytics.track('calendar_event_rsvp', {+ response: args.response,+ scope: args.scope ?? (args.recurrenceId ? 'this_event' : 'all'),+ });+ },onError: (_error, _args, context) => context?.rollback(),onSettled: (_data, _error, args, context) => {context?.release();@@ -812,6 +819,15 @@ export function useCreateCalendarEventMutation(callbacks?: CreateCallbacks) {},...withCallbacks<CalendarEventEntity, Error, CreateCalendarEventRequest>({+ onSuccess: (event, args) => {+ analytics.track('calendar_event_created', {+ eventId: event.id,+ attendees: args.attendees?.length ?? 0,+ recurring: (args.recurrenceLines?.length ?? 0) > 0,+ macroCall: args.macroCall === true,+ conference: args.conference != null,+ });+ },onSettled: () => invalidateCalendarOccurrences(),},callbacksdiff --git a/apps/web/src/lib/queries/storage/databases.test.ts b/apps/web/src/lib/queries/storage/databases.test.tsindex 67555a7127..56cc69e6a5 100644--- a/apps/web/src/lib/queries/storage/databases.test.ts+++ b/apps/web/src/lib/queries/storage/databases.test.ts@@ -426,6 +426,83 @@ describe('shared ops cache effects', () => {).toBe(6);expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false);});+ it('reports committed row writes by kind without cell contents', async () => {+ mock.applyOps.mockReturnValue(okAsync({ results: [], changes: [] }));+ await applyDatabaseOps('db', [+ {+ kind: 'rows',+ table: 'tasks',+ change: { kind: 'insert', rows: [[], []] },+ },+ {+ kind: 'rows',+ table: 'tasks',+ change: {+ kind: 'update',+ changes: { kind: 'uniform', rows: ['a', 'b', 'c'], cells: [] },+ },+ },+ { kind: 'table', table: 'tasks', change: { kind: 'delete' } },+ ]);+ expect(mock.track).toHaveBeenCalledExactlyOnceWith('database_rows_edited', {+ databaseId: 'db',+ insertedRows: 2,+ updatedRows: 3,+ deletedRows: 0,+ });+ });+ it('does not report schema-only or refused batches as row edits', async () => {+ mock.applyOps.mockReturnValueOnce(okAsync({ results: [], changes: [] }));+ await applyDatabaseOps('db', [+ { kind: 'table', table: 'tasks', change: { kind: 'delete' } },+ ]);+ mock.applyOps.mockReturnValueOnce(+ errAsync([{ code: 'CONFLICT', message: 'Changed.', refusal: null }])+ );+ await applyDatabaseOps('db', [+ {+ kind: 'rows',+ table: 'tasks',+ change: { kind: 'delete', rows: ['row'] },+ },+ ]);+ expect(mock.track).not.toHaveBeenCalled();+ });+ it('does not report the cells a column type conversion copies as row edits', async () => {+ mock.applyOps.mockReturnValue(okAsync({ results: [], changes: [] }));+ await applyDatabaseOps('db', [+ {+ kind: 'column',+ table: 'tasks',+ column: 'status-as-select',+ change: {+ kind: 'create',+ definition: {+ source: 'new',+ name: 'Status',+ type: { type: 'select', multi: false },+ options: [],+ },+ after: 'status',+ },+ },+ {+ kind: 'rows',+ table: 'tasks',+ change: {+ kind: 'update',+ changes: {+ kind: 'per_row',+ rows: [+ { row: 'a', cells: [] },+ { row: 'b', cells: [] },+ ],+ },+ },+ },+ ]);+ expect(mock.track).not.toHaveBeenCalled();+ });it('invalidates optimistic state after a refused batch', async () => {queryClient.setQueryData(key, detail);mock.applyOps.mockReturnValue(diff --git a/apps/web/src/lib/queries/storage/databases.ts b/apps/web/src/lib/queries/storage/databases.tsindex 617922c8a6..b8829825ef 100644--- a/apps/web/src/lib/queries/storage/databases.ts+++ b/apps/web/src/lib/queries/storage/databases.ts@@ -166,6 +166,41 @@ export function onDatabaseBatchCommitted(return () => committedListeners.delete(listener);}+/** How many rows a batch inserts, updates and deletes; never cell contents. */+export function countRowWrites(ops: DatabaseOp[]) {+ const rows = { insert: 0, update: 0, delete: 0 };+ for (const op of ops) {+ if (op.kind !== 'rows') continue;+ rows[op.change.kind] +=+ op.change.kind === 'update'+ ? op.change.changes.rows.length+ : op.change.rows.length;+ }+ return {+ insertedRows: rows.insert,+ updatedRows: rows.update,+ deletedRows: rows.delete,+ };+}++/**+ * Reports a batch's row writes as edits. A batch that creates a table or a+ * column fills it in the same request (a type conversion copies every cell+ * into its new column), so its row writes are a schema change, not edits.+ */+function trackRowEdits(databaseId: string, ops: DatabaseOp[]) {+ const createsSchema = ops.some(+ (op) =>+ (op.kind === 'table' || op.kind === 'column') &&+ op.change.kind === 'create'+ );+ if (createsSchema) return;+ const counts = countRowWrites(ops);+ if (counts.insertedRows + counts.updatedRows + counts.deletedRows === 0)+ return;+ analytics.track('database_rows_edited', { databaseId, ...counts });+}+/*** Apply ops to one database as the current viewer, together or not at all.* Each table `baseVersions` names must still be at that version, or the batch@@ -195,6 +230,7 @@ export function applyDatabaseOps(tableVersions,});applyDatabaseTableVersions(databaseId, tableVersions);+ trackRowEdits(databaseId, ops);// Schema-only creation waits for data callers need to focus or patch views.// A row edit that mints options keeps the write queue moving.const createsColumnData = ops.some(diff --git a/crates/analytics_client/Cargo.toml b/crates/analytics_client/Cargo.tomlindex 74af0802b8..d16850f18e 100644--- a/crates/analytics_client/Cargo.toml+++ b/crates/analytics_client/Cargo.toml@@ -7,9 +7,12 @@ version = "0.1.0"[dependencies]chrono = { workspace = true }hex = { workspace = true }+macro_env = { path = "../macro_env" }reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sha2 = { workspace = true }+tokio = { workspace = true, features = ["sync"] }tracing = { workspace = true }+uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }diff --git a/crates/analytics_client/src/background.rs b/crates/analytics_client/src/background.rsnew file mode 100644index 0000000000..bd7c1557f2--- /dev/null+++ b/crates/analytics_client/src/background.rs@@ -0,0 +1,49 @@+//! Sending analytics off the request path, with a cap on concurrent sends.++#[cfg(test)]+mod test;++use std::sync::Arc;++use tokio::{sync::Semaphore, task::JoinHandle};++use crate::AnalyticsClient;++/// Sends analytics on background tasks, at most `max_in_flight` at a time.+///+/// When that many sends are running, new ones are dropped rather than queued,+/// so a slow analytics provider never piles up tasks, sockets, or the lookups+/// a send makes before it posts.+#[derive(Clone)]+pub struct BackgroundSender {+ client: AnalyticsClient,+ in_flight: Arc<Semaphore>,+}++impl BackgroundSender {+ /// Sends through `client`, running at most `max_in_flight` sends at once.+ pub fn new(client: AnalyticsClient, max_in_flight: usize) -> Self {+ Self {+ client,+ in_flight: Arc::new(Semaphore::new(max_in_flight)),+ }+ }++ /// Runs `send` on a background task, or drops it when `max_in_flight`+ /// sends are already running. Returns the task when it was started.+ pub fn spawn<F, Fut>(&self, send: F) -> Option<JoinHandle<()>>+ where+ F: FnOnce(AnalyticsClient) -> Fut,+ Fut: Future<Output = ()> + Send + 'static,+ {+ let Ok(permit) = self.in_flight.clone().try_acquire_owned() else {+ tracing::debug!("dropped an analytics event: too many sends in flight");+ return None;+ };+ let send = send(self.client.clone());+ Some(tokio::spawn(async move {+ send.await;+ drop(permit);+ }))+ }+}diff --git a/crates/analytics_client/src/background/test.rs b/crates/analytics_client/src/background/test.rsnew file mode 100644index 0000000000..f04e2d2420--- /dev/null+++ b/crates/analytics_client/src/background/test.rs@@ -0,0 +1,20 @@+use super::*;+use tokio::sync::oneshot;++#[tokio::test]+async fn sends_past_the_cap_are_dropped_until_one_finishes() {+ let sender = BackgroundSender::new(AnalyticsClient::noop(), 1);+ let (release, released) = oneshot::channel::<()>();++ let first = sender+ .spawn(|_| async move {+ let _ = released.await;+ })+ .unwrap();+ assert!(sender.spawn(|_| async {}).is_none());++ release.send(()).unwrap();+ first.await.unwrap();++ assert!(sender.spawn(|_| async {}).is_some());+}diff --git a/crates/analytics_client/src/lib.rs b/crates/analytics_client/src/lib.rsindex e5373710de..489c67e68f 100644--- a/crates/analytics_client/src/lib.rs+++ b/crates/analytics_client/src/lib.rs@@ -1,8 +1,12 @@#![deny(missing_docs)]//! Analytics client for tracking events to GA, Meta, and PostHog.+mod background;+mod product_event;mod providers;+pub use background::BackgroundSender;+pub use product_event::ProductEventProperties;pub use providers::{MetaActionSource, MetaUserData};use providers::{GoogleAnalyticsProvider, MetaProvider, PostHogProvider};@@ -147,7 +151,7 @@ impl AnalyticsClient {/// - `distinct_id`: Unique identifier for the user (e.g., email or user ID)/// - `event_name`: Name of the event (e.g., "subscription_created")/// - `properties`: Additional event properties- #[tracing::instrument(skip(self, properties), err)]+ #[tracing::instrument(skip(self, distinct_id, properties), err)]pub async fn track_posthog(&self,distinct_id: &str,diff --git a/crates/analytics_client/src/product_event.rs b/crates/analytics_client/src/product_event.rsnew file mode 100644index 0000000000..98cb162045--- /dev/null+++ b/crates/analytics_client/src/product_event.rs@@ -0,0 +1,50 @@+//! Properties shared by server-side product events.++#[cfg(test)]+mod test;++use macro_env::Environment;+use serde::Serialize;++/// An event's own properties plus the context the web app's events carry, so+/// server-side and browser events filter and group the same way in PostHog.+#[derive(Debug, Serialize)]+pub struct ProductEventProperties<P> {+ #[serde(flatten)]+ properties: P,+ /// Same values as the web app's `env` super property, so the usual+ /// `env != 'DEV'` filter also excludes the develop deployment here.+ env: &'static str,+ /// Same values as the web app's `macro_environment` super property.+ macro_environment: &'static str,+ #[serde(skip_serializing_if = "Option::is_none")]+ team_id: Option<uuid::Uuid>,+ /// PostHog group analytics, keyed like the web app's+ /// `posthog.group('team', ...)`.+ #[serde(rename = "$groups", skip_serializing_if = "Option::is_none")]+ groups: Option<TeamGroup>,+}++#[derive(Debug, Serialize)]+struct TeamGroup {+ team: uuid::Uuid,+}++impl<P> ProductEventProperties<P> {+ /// Wraps `properties` for an event from `environment`, attributed to+ /// `team_id` when the user belongs to a team.+ pub fn new(properties: P, environment: Environment, team_id: Option<uuid::Uuid>) -> Self {+ let (env, macro_environment) = match environment {+ Environment::Production => ("PROD", "prod"),+ Environment::Develop => ("DEV", "dev"),+ Environment::Local => ("LOCAL", "local"),+ };+ Self {+ properties,+ env,+ macro_environment,+ team_id,+ groups: team_id.map(|team| TeamGroup { team }),+ }+ }+}diff --git a/crates/analytics_client/src/product_event/test.rs b/crates/analytics_client/src/product_event/test.rsnew file mode 100644index 0000000000..022d191e53--- /dev/null+++ b/crates/analytics_client/src/product_event/test.rs@@ -0,0 +1,35 @@+use super::*;+use serde_json::json;++#[test]+fn team_member_events_carry_environment_and_team_group() {+ let team_id = uuid::Uuid::parse_str("7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f").unwrap();++ let properties = ProductEventProperties::new(+ json!({ "provider": "linear" }),+ Environment::Production,+ Some(team_id),+ );++ assert_eq!(+ serde_json::to_value(properties).unwrap(),+ json!({+ "provider": "linear",+ "env": "PROD",+ "macro_environment": "prod",+ "team_id": "7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f",+ "$groups": { "team": "7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f" },+ })+ );+}++#[test]+fn events_without_a_team_omit_the_group() {+ let properties =+ ProductEventProperties::new(json!({ "provider": "linear" }), Environment::Develop, None);++ assert_eq!(+ serde_json::to_value(properties).unwrap(),+ json!({ "provider": "linear", "env": "DEV", "macro_environment": "dev" })+ );+}diff --git a/crates/analytics_client/src/providers/posthog.rs b/crates/analytics_client/src/providers/posthog.rsindex 40b42b370f..b7bad4c6b5 100644--- a/crates/analytics_client/src/providers/posthog.rs+++ b/crates/analytics_client/src/providers/posthog.rs@@ -1,7 +1,16 @@//! PostHog analytics provider.+#[cfg(test)]+mod test;++use std::time::Duration;+use serde::Serialize;+/// Longest a capture may take. Analytics run beside product requests, so a+/// slow PostHog must not hold sockets or tasks open.+const CAPTURE_TIMEOUT: Duration = Duration::from_secs(5);+/// PostHog analytics provider for server-side event tracking.#[derive(Clone)]pub struct PostHogProvider {@@ -28,7 +37,7 @@ impl PostHogProvider {/// - `distinct_id`: Unique identifier for the user (e.g., email or user ID)/// - `event_name`: Name of the event (e.g., "subscription_created")/// - `properties`: Additional event properties- #[tracing::instrument(skip(self, properties), err)]+ #[tracing::instrument(skip(self, distinct_id, properties), err)]pub async fn capture(&self,distinct_id: &str,@@ -37,18 +46,15 @@ impl PostHogProvider {) -> Result<(), reqwest::Error> {let url = format!("{}/i/v0/e/", self.host.trim_end_matches('/'));- let properties = serde_json::to_value(properties).unwrap_or_default();-- let payload = serde_json::json!({- "api_key": self.api_key,- "event": event_name,- "distinct_id": distinct_id,- "properties": properties,- });-self.client.post(&url)- .json(&payload)+ .timeout(CAPTURE_TIMEOUT)+ .json(&capture_payload(+ &self.api_key,+ distinct_id,+ event_name,+ properties,+ )).send().await?.error_for_status()?;@@ -56,3 +62,26 @@ impl PostHogProvider {Ok(())}}++/// The capture request body. Server events never carry the user's IP, so+/// GeoIP is off: otherwise PostHog would place every user at the server and+/// overwrite their person location.+fn capture_payload(+ api_key: &str,+ distinct_id: &str,+ event_name: &str,+ properties: impl Serialize,+) -> serde_json::Value {+ let mut properties = match serde_json::to_value(properties) {+ Ok(serde_json::Value::Object(properties)) => properties,+ _ => serde_json::Map::new(),+ };+ properties.insert("$geoip_disable".to_owned(), true.into());++ serde_json::json!({+ "api_key": api_key,+ "event": event_name,+ "distinct_id": distinct_id,+ "properties": properties,+ })+}diff --git a/crates/analytics_client/src/providers/posthog/test.rs b/crates/analytics_client/src/providers/posthog/test.rsnew file mode 100644index 0000000000..c4053f997f--- /dev/null+++ b/crates/analytics_client/src/providers/posthog/test.rs@@ -0,0 +1,28 @@+use super::*;+use serde_json::json;++#[test]+fn server_events_turn_off_geoip_and_keep_their_properties() {+ assert_eq!(+ capture_payload(+ "phc_test",+ "macro|[email protected]",+ "integration_connected",+ json!({ "provider": "linear" }),+ ),+ json!({+ "api_key": "phc_test",+ "event": "integration_connected",+ "distinct_id": "macro|[email protected]",+ "properties": { "provider": "linear", "$geoip_disable": true },+ })+ );+}++#[test]+fn events_without_properties_still_turn_off_geoip() {+ assert_eq!(+ capture_payload("phc_test", "macro|[email protected]", "team_create", ())["properties"],+ json!({ "$geoip_disable": true })+ );+}diff --git a/crates/mcp_client/src/inbound/axum_router.rs b/crates/mcp_client/src/inbound/axum_router.rsindex 74571d590d..f7e2c671a0 100644--- a/crates/mcp_client/src/inbound/axum_router.rs+++ b/crates/mcp_client/src/inbound/axum_router.rs@@ -1,5 +1,5 @@use crate::domain::{- models::{McpServerRecord, OAuthClientMetadata},+ models::{MacroUserIdStr, McpServerRecord, OAuthClientMetadata},ports::{McpServerStore, OAuthClient},};use axum::{@@ -20,12 +20,25 @@ use utoipa::{IntoParams, ToSchema};#[cfg(test)]mod test;+/// Hook invoked after an OAuth flow completes and the credentials are saved.+/// Hosts use this to react to a connection the moment it exists (e.g. record+/// analytics); implementations must be quick or spawn.+pub type McpAuthCompletedHook = Arc<+ dyn Fn(McpServerRecord) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,+>;++/// Hook invoked after a user removes a server they had added, with the record+/// as it was before removal. Implementations must be quick or spawn.+pub type McpServerRemovedHook = McpAuthCompletedHook;+/// Shared state for the MCP router.pub struct McpRouterState<S, O, Auth> {store: Arc<S>,oauth: Arc<O>,authorization_state: MacroAuthorizationState<Auth>,client_metadata: OAuthClientMetadata,+ on_auth_completed: Option<McpAuthCompletedHook>,+ on_server_removed: Option<McpServerRemovedHook>,}impl<S, O, Auth> Clone for McpRouterState<S, O, Auth> {@@ -35,6 +48,8 @@ impl<S, O, Auth> Clone for McpRouterState<S, O, Auth> {oauth: self.oauth.clone(),authorization_state: self.authorization_state.clone(),client_metadata: self.client_metadata.clone(),+ on_auth_completed: self.on_auth_completed.clone(),+ on_server_removed: self.on_server_removed.clone(),}}}@@ -64,9 +79,25 @@ whereoauth: Arc::new(oauth),authorization_state,client_metadata,+ on_auth_completed: None,+ on_server_removed: None,}}+ /// Invoke `hook` whenever an OAuth flow completes (see+ /// [`McpAuthCompletedHook`]).+ pub fn with_auth_completed_hook(mut self, hook: McpAuthCompletedHook) -> Self {+ self.on_auth_completed = Some(hook);+ self+ }++ /// Invoke `hook` whenever a user removes a server (see+ /// [`McpServerRemovedHook`]).+ pub fn with_server_removed_hook(mut self, hook: McpServerRemovedHook) -> Self {+ self.on_server_removed = Some(hook);+ self+ }+/// Access the underlying server store.pub fn store(&self) -> Arc<S> {self.store.clone()@@ -402,13 +433,49 @@ whereanyhow::Error: From<S::Err>,{let user = &authorization.authorization.user;- state- .store- .delete(&user.macro_user_id, ¶ms.url)+ remove_server(+ state.store.as_ref(),+ state.on_server_removed.as_ref(),+ &user.macro_user_id,+ ¶ms.url,+ )+ .await?;++ Ok(StatusCode::NO_CONTENT)+}++/// Deletes a user's server, then passes the removed record to `on_removed`.+///+/// The record is read only when there is a hook, so a plain delete does no+/// extra read or decryption. A record that can't be read (e.g. credentials+/// that no longer decrypt) never blocks the delete: the hook is skipped+/// instead. Deleting an unknown URL stays a quiet no-op.+async fn remove_server<S>(+ store: &S,+ on_removed: Option<&McpServerRemovedHook>,+ user_id: &MacroUserIdStr<'static>,+ server_url: &str,+) -> anyhow::Result<()>+where+ S: McpServerStore,+ anyhow::Error: From<S::Err>,+{+ let removed = match on_removed {+ Some(_) => store.load(user_id, server_url).await.unwrap_or_else(|error| {+ tracing::warn!(error = ?error, "could not read MCP server before removal; skipping the removal hook");+ None+ }),+ None => None,+ };+ store+ .delete(user_id, server_url).await.map_err(anyhow::Error::from)?;- Ok(StatusCode::NO_CONTENT)+ if let (Some(record), Some(hook)) = (removed, on_removed) {+ hook(record).await;+ }+ Ok(())}#[utoipa::path(@@ -512,10 +579,14 @@ where{let (code, csrf_state) = parse_callback_params(params)?;- state+ let record = state.oauth.exchange_authorization_code(&code, &csrf_state).await?;+ if let Some(hook) = &state.on_auth_completed {+ hook(record).await;+ }+Ok("Authorization successful. You can close this tab.".to_string())}diff --git a/crates/mcp_client/src/inbound/axum_router/test.rs b/crates/mcp_client/src/inbound/axum_router/test.rsindex 542e6b0b6e..8acd722e0c 100644--- a/crates/mcp_client/src/inbound/axum_router/test.rs+++ b/crates/mcp_client/src/inbound/axum_router/test.rs@@ -66,3 +66,141 @@ fn missing_state_without_error_is_malformed() {let result = parse_callback_params(params(Some("a-code"), None, None, None));assert!(matches!(result, Err(McpHandlerErr::MalformedCallback)));}++/// A store whose `load` can fail, as it does when stored credentials no+/// longer decrypt.+#[derive(Default)]+struct FakeStore {+ records: std::sync::Mutex<Vec<McpServerRecord>>,+ load_fails: bool,+ loads: std::sync::atomic::AtomicUsize,+}++impl McpServerStore for FakeStore {+ type Err = anyhow::Error;++ async fn save(&self, record: &McpServerRecord) -> Result<(), Self::Err> {+ self.records.lock().unwrap().push(record.clone());+ Ok(())+ }++ async fn load(+ &self,+ user_id: &MacroUserIdStr<'static>,+ server_url: &str,+ ) -> Result<Option<McpServerRecord>, Self::Err> {+ self.loads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ if self.load_fails {+ anyhow::bail!("credential ciphertext too short");+ }+ Ok(self+ .records+ .lock()+ .unwrap()+ .iter()+ .find(|record| &record.user_id == user_id && record.url == server_url)+ .cloned())+ }++ async fn delete(+ &self,+ user_id: &MacroUserIdStr<'static>,+ server_url: &str,+ ) -> Result<(), Self::Err> {+ self.records+ .lock()+ .unwrap()+ .retain(|record| !(&record.user_id == user_id && record.url == server_url));+ Ok(())+ }++ async fn list(+ &self,+ user_id: &MacroUserIdStr<'static>,+ ) -> Result<Vec<McpServerRecord>, Self::Err> {+ Ok(self+ .records+ .lock()+ .unwrap()+ .iter()+ .filter(|record| &record.user_id == user_id)+ .cloned()+ .collect())+ }+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++fn server() -> McpServerRecord {+ McpServerRecord {+ user_id: user(),+ url: "https://mcp.linear.app/mcp".to_owned(),+ server_name: "Linear".to_owned(),+ credentials: None,+ enabled: true,+ }+}++fn recording_hook() -> (+ McpServerRemovedHook,+ Arc<std::sync::Mutex<Vec<McpServerRecord>>>,+) {+ let removed = Arc::new(std::sync::Mutex::new(Vec::new()));+ let seen = removed.clone();+ let hook: McpServerRemovedHook = Arc::new(move |record| {+ seen.lock().unwrap().push(record);+ Box::pin(async {})+ });+ (hook, removed)+}++#[tokio::test]+async fn a_server_whose_record_cannot_be_read_is_still_deleted() {+ let store = FakeStore {+ records: std::sync::Mutex::new(vec![server()]),+ load_fails: true,+ ..FakeStore::default()+ };+ let (hook, removed) = recording_hook();++ remove_server(&store, Some(&hook), &user(), "https://mcp.linear.app/mcp")+ .await+ .unwrap();++ assert!(store.records.lock().unwrap().is_empty());+ assert!(removed.lock().unwrap().is_empty());+}++#[tokio::test]+async fn the_removal_hook_gets_the_removed_record() {+ let store = FakeStore {+ records: std::sync::Mutex::new(vec![server()]),+ ..FakeStore::default()+ };+ let (hook, removed) = recording_hook();++ remove_server(&store, Some(&hook), &user(), "https://mcp.linear.app/mcp")+ .await+ .unwrap();++ let removed = removed.lock().unwrap();+ assert_eq!(removed.len(), 1);+ assert_eq!(removed[0].url, "https://mcp.linear.app/mcp");+}++#[tokio::test]+async fn deleting_without_a_hook_does_not_read_the_record() {+ let store = FakeStore {+ records: std::sync::Mutex::new(vec![server()]),+ ..FakeStore::default()+ };++ remove_server(&store, None, &user(), "https://mcp.linear.app/mcp")+ .await+ .unwrap();++ assert!(store.records.lock().unwrap().is_empty());+ assert_eq!(store.loads.load(std::sync::atomic::Ordering::SeqCst), 0);+}diff --git a/crates/pipedream_mcp/src/domain/service/connect.rs b/crates/pipedream_mcp/src/domain/service/connect.rsindex 09891ebb36..1b11b0bb0d 100644--- a/crates/pipedream_mcp/src/domain/service/connect.rs+++ b/crates/pipedream_mcp/src/domain/service/connect.rs@@ -75,7 +75,8 @@ whereOk(record)}-/// Remove a connected app, revoking its Pipedream account.+/// Remove a connected app, revoking its Pipedream account. Returns the+/// connection that was removed, or `None` when the app was not connected.////// The Pipedream deletion is best effort: failing to clean up remotely must/// not strand the local row, so remote failures are logged and the local@@ -86,7 +87,7 @@ pub async fn disconnect_mcp_server<S, P>(pipedream: &P,user_id: &MacroUserIdStr<'static>,app_slug: &str,-) -> anyhow::Result<()>+) -> anyhow::Result<Option<PipedreamConnection>>whereS: ConnectionStore,P: PipedreamConnect,@@ -96,7 +97,7 @@ where.load(user_id, app_slug).await.map_err(anyhow::Error::from)?;- if let Some(record) = record+ if let Some(record) = &record&& let Err(e) = pipedream.delete_account(&record.account_id).await{tracing::warn!(error = ?e, account_id = %record.account_id, "failed to delete Pipedream account");@@ -107,5 +108,5 @@ where.await.map_err(anyhow::Error::from)?;- Ok(())+ Ok(record)}diff --git a/crates/pipedream_mcp/src/domain/service/connect/test.rs b/crates/pipedream_mcp/src/domain/service/connect/test.rsindex 495c1ee915..fb3fedf4b1 100644--- a/crates/pipedream_mcp/src/domain/service/connect/test.rs+++ b/crates/pipedream_mcp/src/domain/service/connect/test.rs@@ -244,10 +244,14 @@ async fn disconnect_revokes_the_pipedream_account_and_deletes_the_row() {.unwrap();let pd = FakePipedream::default();- disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear")+ let removed = disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear").await.unwrap();+ assert_eq!(+ removed.map(|connection| connection.account_id),+ Some("apn_1".to_owned())+ );assert_eq!(*pd.deleted.lock().unwrap(), vec!["apn_1".to_owned()]);assert!(store.records.lock().unwrap().is_empty());}@@ -257,9 +261,10 @@ async fn disconnect_of_unknown_app_is_a_quiet_noop() {let store = FakeStore::default();let pd = FakePipedream::default();- disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear")+ let removed = disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear").await.unwrap();+ assert!(removed.is_none());assert!(pd.deleted.lock().unwrap().is_empty());}diff --git a/crates/pipedream_mcp/src/inbound/axum_router.rs b/crates/pipedream_mcp/src/inbound/axum_router.rsindex f073636a9e..014cc22136 100644--- a/crates/pipedream_mcp/src/inbound/axum_router.rs+++ b/crates/pipedream_mcp/src/inbound/axum_router.rs@@ -24,6 +24,17 @@ use utoipa::{IntoParams, ToSchema};#[cfg(test)]mod test;+/// Hook invoked after a connect flow completes and the record is saved.+/// Hosts use this to react to a connection the moment it exists (e.g. record+/// analytics); implementations must be quick or spawn.+pub type PipedreamAuthCompletedHook = Arc<+ dyn Fn(PipedreamConnection) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,+>;++/// Hook invoked after a user disconnects an app, with the connection as it+/// was before removal. Implementations must be quick or spawn.+pub type PipedreamDisconnectedHook = PipedreamAuthCompletedHook;+/// Shared state for the MCP router.////// `pipedream` is the single connect path. When it is `None` (deployment not@@ -33,6 +44,8 @@ pub struct PipedreamRouterState<S, P, Auth> {store: Arc<S>,pipedream: Option<Arc<P>>,authorization_state: MacroAuthorizationState<Auth>,+ on_auth_completed: Option<PipedreamAuthCompletedHook>,+ on_disconnected: Option<PipedreamDisconnectedHook>,}impl<S, P, Auth> Clone for PipedreamRouterState<S, P, Auth> {@@ -41,6 +54,8 @@ impl<S, P, Auth> Clone for PipedreamRouterState<S, P, Auth> {store: self.store.clone(),pipedream: self.pipedream.clone(),authorization_state: self.authorization_state.clone(),+ on_auth_completed: self.on_auth_completed.clone(),+ on_disconnected: self.on_disconnected.clone(),}}}@@ -69,9 +84,25 @@ wherestore: Arc::new(store),pipedream,authorization_state,+ on_auth_completed: None,+ on_disconnected: None,}}+ /// Invoke `hook` whenever a connect flow completes (see+ /// [`PipedreamAuthCompletedHook`]).+ pub fn with_auth_completed_hook(mut self, hook: PipedreamAuthCompletedHook) -> Self {+ self.on_auth_completed = Some(hook);+ self+ }++ /// Invoke `hook` whenever a user disconnects an app (see+ /// [`PipedreamDisconnectedHook`]).+ pub fn with_disconnected_hook(mut self, hook: PipedreamDisconnectedHook) -> Self {+ self.on_disconnected = Some(hook);+ self+ }+/// Access the underlying server store.pub fn store(&self) -> Arc<S> {self.store.clone()@@ -481,7 +512,7 @@ where{let user = &authorization.authorization.user;let pipedream = state.pipedream()?;- disconnect_mcp_server(+ let removed = disconnect_mcp_server(state.store.as_ref(),pipedream.as_ref(),&user.macro_user_id,@@ -489,6 +520,10 @@ where).await?;+ if let (Some(connection), Some(hook)) = (removed, &state.on_disconnected) {+ hook(connection).await;+ }+Ok(StatusCode::NO_CONTENT)}@@ -571,6 +606,10 @@ where).await?;+ if let Some(hook) = &state.on_auth_completed {+ hook(record.clone()).await;+ }+Ok(Json(PipedreamConnectionResponse::from_record(&record)))}diff --git a/docs/guides/add-block.md b/docs/guides/add-block.mdindex 357208c310..a2fb1ee2a7 100644--- a/docs/guides/add-block.md+++ b/docs/guides/add-block.md@@ -72,8 +72,10 @@ and none of the file-type steps. Sections 4 and 5 are one or the other.- Options: `accepted` (extension → MIME; `{}` for entities),`liveTrackingEnabled` (presence indicators), `editPermissionEnabled` (theshare menu inside the block offers Edit only when set), `openTrackingEnabled`- (defaults on and writes a history row; turn it off when there is nothing to- record, as `block-database` does), `defaultFilename`, `aliases`.+ (defaults on and writes a history row and page view; turn it off when there+ is nothing to record, as `block-database` does), `openAnalyticsEnabled`+ (whether opens send `open_entity`; defaults to `openTrackingEnabled`, and+ `block-database` turns it back on), `defaultFilename`, `aliases`.- Gate the block with a flag in `apps/web/src/lib/core/constant/featureFlags.ts`via the [feature-flags skill](../../.agents/skills/feature-flags/SKILL.md).`isFeatureEnabled` answers `false` until PostHog has loaded, so on a cold deepdiff --git a/docs/guides/consolidate-agent-services.md b/docs/guides/consolidate-agent-services.mdindex fb97f57cb3..70adc445d9 100644--- a/docs/guides/consolidate-agent-services.md+++ b/docs/guides/consolidate-agent-services.md@@ -70,8 +70,8 @@ Doppler values while historical-image rollback is still needed. `APP_BASE_URL`is also ignored by the new harness; other services may still consume it.`POSTHOG_API_KEY` and `POSTHOG_HOST` are already typed harness fields. They-remain available for existing feature flags and future analytics. No MCP-analytics events or tracking client are added by this consolidation.+drive feature flags and the public MCP and integration analytics; when the key+is unset, analytics are off.## Prepare preview stack outputsdiff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.mdindex f3061f1dde..4708fe0f07 100644--- a/services/agent_harness_service/AGENTS.md+++ b/services/agent_harness_service/AGENTS.md@@ -26,8 +26,15 @@ Pulumi stacks; they do not host extra agent processes.reuses the harness tool context and retains bearer authentication. Users with`ai-code-mode` get `ExecuteCode`/`DescribeCodeTools` in place of SDK-coveredtools (`tool_service.rs`); the flag is cached per user (`tool_mode_cache.rs`).+ `src/public_mcp/analytics.rs` sends PostHog `$mcp_initialize` /+ `$mcp_tool_call` events (PostHog MCP analytics schema) in the background,+ with the user's team as the `team` group. At most 64 sends run at once+ (more are dropped) and each user's team is cached for 10 minutes.- `src/cognition/`: existing chat, completions, integrations, and projectionworkers; the library also exports their OpenAPI document.+ `src/cognition/service/integration_analytics.rs` sends PostHog+ `integration_connected` / `integration_disconnected` for native MCP servers+ and Pipedream apps, from the router hooks wired in `src/cognition/server.rs`.- `src/scheduling.rs`: routine HTTP routes and background scheduling;domain/adapters live in `crates/scheduled_action`.- `src/preview.rs` + `src/preview/`: preview control routes, public HTTP and SSH listeners;@@ -104,8 +111,9 @@ hostnames and internally rewrites cognition paths. `PREVIEW_DOMAIN` and`PREVIEW_SSH_HOST` remain infrastructure-generated Doppler settings. Legacy`MCP_PUBLIC_URL`, `MCP_CLIENT_PUBLIC_URL`, `PREVIEW_APP_ORIGIN`, and`PREVIEW_CONTROL_HOSTS` values are retained only for old-image rollback; new-code does not read them. `POSTHOG_API_KEY` and `POSTHOG_HOST` remain-available for feature flags and future analytics; MCP emits no analytics events.+code does not read them. `POSTHOG_API_KEY` and `POSTHOG_HOST` drive+feature flags and the MCP and integration analytics; when the key is unset,+analytics are off.In deployed configs, `DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY`is cognition's Secrets Manager reference; AI tools resolve the separate`DOCUMENT_STORAGE_SERVICE_CLOUDFRONT_SIGNER_PRIVATE_KEY_SECRET_NAME` reference.@@ -126,6 +134,12 @@ listener failure shuts down the process so ECS can replace the task.Daytona sandbox, `@macro-new`/`@macro` (`INMEM_BOT_ID`) on the in-process ACPruntime — check which one a bug report is about before debugging containers.+- Analytics record the tool name, outcome, duration, and client headers only;+ never add tool arguments or results to them.+- The public MCP server is stateless, so tool calls carry no `clientInfo`; the+ client is identified per call by its `User-Agent` / `x-anthropic-client`+ headers and per session by `$mcp_initialize`.+## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/config-and-service-urls.md`diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.tomlindex 9660610037..ab02ca3074 100644--- a/services/agent_harness_service/Cargo.toml+++ b/services/agent_harness_service/Cargo.toml@@ -46,6 +46,7 @@ ai_projections = { path = "../../crates/ai_projections", features = ["agent"] }ai_tools = { path = "../../crates/ai_tools" }ai_toolset = { path = "../../crates/ai_toolset" }ai_usage = { path = "../../crates/ai_usage" }+analytics_client = { path = "../../crates/analytics_client" }anyhow = { workspace = true }async-openai = { workspace = true }async-stream = { workspace = true }@@ -118,6 +119,7 @@ lazy_static = { workspace = true }lexical_client = { path = "../../crates/lexical_client" }lexical_mention_extractor = { path = "../../crates/lexical_mention_extractor" }log = { workspace = true }+lru = { workspace = true }macro_auth = { path = "../../crates/macro_auth" }macro_authorization = { path = "../../crates/macro_authorization", features = ["axum", "outbound", "postgres"] }macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }diff --git a/services/agent_harness_service/src/cognition/config.rs b/services/agent_harness_service/src/cognition/config.rsindex 6ed0601940..ee93cc5897 100644--- a/services/agent_harness_service/src/cognition/config.rs+++ b/services/agent_harness_service/src/cognition/config.rs@@ -64,6 +64,10 @@ maybe_env_vars!(/// unauthenticated because Pipedream is the caller. When unset, the/// webhook route is not mounted.pub struct PipedreamWebhookSecret;+ /// PostHog project token. When unset, integration analytics are not sent.+ pub struct PosthogApiKey;+ /// PostHog ingestion origin. Falls back to the US origin when unset.+ pub struct PosthogHost;);/// The configuration parameters for the application.@@ -144,6 +148,10 @@ pub struct Config {pub pipedream_webhook_uri: PipedreamWebhookUri,/// Shared secret guarding the public Pipedream webhook route.pub pipedream_webhook_secret: PipedreamWebhookSecret,+ /// PostHog project token for integration connect/disconnect analytics.+ pub posthog_api_key: PosthogApiKey,+ /// PostHog ingestion origin for integration analytics.+ pub posthog_host: PosthogHost,/// The internal api keypub internal_api_key: InternalApiKey,/// AI editing worker URL@@ -245,6 +253,8 @@ impl Config {pipedream_allowed_origins: PipedreamAllowedOrigins::Unset,pipedream_webhook_uri: PipedreamWebhookUri::Unset,pipedream_webhook_secret: PipedreamWebhookSecret::Unset,+ posthog_api_key: PosthogApiKey::Unset,+ posthog_host: PosthogHost::Unset,internal_api_key: InternalApiKey::Comptime(""),ai_editing_worker_url: AiEditingWorkerUrl::unwrap_new().to_string(),document_permission_jwt: DocumentPermissionJwt::Comptime("DOCUMENT_PERMISSION_JWT"),diff --git a/services/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rsindex e9a2f5e4c5..7650838a06 100644--- a/services/agent_harness_service/src/cognition/server.rs+++ b/services/agent_harness_service/src/cognition/server.rs@@ -4,7 +4,10 @@use crate::cognition::{api::{self, context::ApiContext},config::{Config, Environment},- service,+ service::{+ self,+ integration_analytics::{IntegrationAnalytics, IntegrationChange, IntegrationEvent},+ },};use ai_tools::{NoOpCallRtcClient, NoOpConnectionService, NoOpNotificationIngress};use anyhow::Context;@@ -1003,18 +1006,69 @@ pub async fn build(mcp_client_metadata.clone(),mcp_pre_registered,);+ // Record connector connects and disconnects for product analytics.+ let integration_analytics = IntegrationAnalytics::from_config(&config, &db);+ let analytics_for_auth_hook = integration_analytics.clone();+ let mcp_auth_hook: mcp_client::inbound::axum_router::McpAuthCompletedHook =+ Arc::new(move |record: mcp_client::domain::models::McpServerRecord| {+ analytics_for_auth_hook.record(+ record.user_id,+ IntegrationChange::Connected,+ IntegrationEvent::mcp_server(&record.url),+ );+ Box::pin(async {})+ });+ let analytics_for_mcp_removed_hook = integration_analytics.clone();+ let mcp_removed_hook: mcp_client::inbound::axum_router::McpServerRemovedHook =+ Arc::new(move |record: mcp_client::domain::models::McpServerRecord| {+ if let Some(event) = IntegrationEvent::removed_mcp_server(&record) {+ analytics_for_mcp_removed_hook.record(+ record.user_id,+ IntegrationChange::Disconnected,+ event,+ );+ }+ Box::pin(async {})+ });let mcp_state = mcp_client::inbound::McpRouterState::new(mcp_server_repo,mcp_oauth,authorization_state.clone(),mcp_client_metadata,- );-+ )+ .with_auth_completed_hook(mcp_auth_hook)+ .with_server_removed_hook(mcp_removed_hook);++ let analytics_for_pipedream_hook = integration_analytics.clone();+ let pipedream_auth_hook: pipedream_mcp::inbound::axum_router::PipedreamAuthCompletedHook =+ Arc::new(+ move |connection: pipedream_mcp::domain::models::PipedreamConnection| {+ analytics_for_pipedream_hook.record(+ connection.user_id,+ IntegrationChange::Connected,+ IntegrationEvent::pipedream(&connection.app_slug),+ );+ Box::pin(async {})+ },+ );+ let pipedream_disconnected_hook: pipedream_mcp::inbound::axum_router::PipedreamDisconnectedHook =+ Arc::new(+ move |connection: pipedream_mcp::domain::models::PipedreamConnection| {+ integration_analytics.record(+ connection.user_id,+ IntegrationChange::Disconnected,+ IntegrationEvent::pipedream(&connection.app_slug),+ );+ Box::pin(async {})+ },+ );let pipedream_state = pipedream_mcp::inbound::PipedreamRouterState::new(pipedream_repo,pipedream_client,authorization_state.clone(),- );+ )+ .with_auth_completed_hook(pipedream_auth_hook)+ .with_disconnected_hook(pipedream_disconnected_hook);let cancellation = tokio_util::sync::CancellationToken::new();super::refresh::start(diff --git a/services/agent_harness_service/src/cognition/service/integration_analytics.rs b/services/agent_harness_service/src/cognition/service/integration_analytics.rsnew file mode 100644index 0000000000..e1631ccd28--- /dev/null+++ b/services/agent_harness_service/src/cognition/service/integration_analytics.rs@@ -0,0 +1,178 @@+//! Product analytics for the agent connections (native MCP servers and+//! Pipedream apps) users connect and disconnect.+//!+//! Recorded server-side so every surface that connects an app — onboarding,+//! settings, the agent chat, mobile — is counted the same way.++#[cfg(test)]+mod test;++use std::sync::Arc;++use analytics_client::{+ AnalyticsClient, AnalyticsClientConfig, BackgroundSender, PostHogConfig, ProductEventProperties,+};+use entity_access::{domain::ports::AccessRepository, outbound::PgAccessRepository};+use macro_env::Environment;+use macro_user_id::user_id::MacroUserIdStr;+use mcp_client::domain::models::McpServerRecord;+use serde::Serialize;+use sqlx::PgPool;++use crate::cognition::config::Config;++/// Whether a connection was made or removed.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum IntegrationChange {+ /// The user finished a connect flow: OAuth for a native MCP server, or+ /// Pipedream Connect for an app. Re-authorizing an app that is already+ /// connected finishes another flow and is recorded again, so count+ /// distinct (person, provider) pairs for connected apps.+ Connected,+ /// The user removed a connected app.+ Disconnected,+}++impl IntegrationChange {+ fn event_name(self) -> &'static str {+ match self {+ Self::Connected => "integration_connected",+ Self::Disconnected => "integration_disconnected",+ }+ }+}++/// One app a user connected or removed.+#[derive(Clone, Debug, Eq, PartialEq, Serialize)]+pub struct IntegrationEvent {+ /// The app: a Pipedream app slug (`linear`, `stripe`, `granola`, ...) or+ /// the host of a native MCP server (`mcp.notion.com`). The same product+ /// can appear both ways; `connection_type` tells them apart.+ provider: String,+ /// How the app is connected: `pipedream` or `mcp_server`.+ connection_type: &'static str,+}++impl IntegrationEvent {+ /// An app connected through Pipedream Connect.+ pub fn pipedream(app_slug: &str) -> Self {+ Self {+ provider: app_slug.to_owned(),+ connection_type: "pipedream",+ }+ }++ /// A native MCP server the user removed, or `None` when it never+ /// finished OAuth. A server counts as connected when OAuth completes, so+ /// only an authenticated one counts as disconnected.+ pub fn removed_mcp_server(record: &McpServerRecord) -> Option<Self> {+ record+ .credentials+ .as_ref()+ .map(|_| Self::mcp_server(&record.url))+ }++ /// A native MCP server, identified by its host only: paths and queries+ /// of user-added server URLs can carry tokens.+ pub fn mcp_server(server_url: &str) -> Self {+ let provider = url::Url::parse(server_url)+ .ok()+ .and_then(|url| url.host_str().map(str::to_owned))+ .unwrap_or_else(|| "unknown".to_owned());+ Self {+ provider,+ connection_type: "mcp_server",+ }+ }+}++/// Most integration analytics sends in flight at once; past it, events are+/// dropped.+const MAX_IN_FLIGHT_SENDS: usize = 16;++/// Records integration changes to PostHog, or nothing when PostHog is not+/// configured.+#[derive(Clone)]+pub struct IntegrationAnalytics {+ sink: Option<Arc<PostHogSink>>,+}++struct PostHogSink {+ sender: BackgroundSender,+ teams: PgAccessRepository,+ environment: Environment,+}++impl IntegrationAnalytics {+ /// PostHog analytics when `POSTHOG_API_KEY` is set, attributing each event+ /// to the user's team; otherwise analytics that record nothing.+ pub fn from_config(config: &Config, db: &PgPool) -> Self {+ let Some(api_key) = config.posthog_api_key.value() else {+ tracing::info!("POSTHOG_API_KEY unset; integration analytics disabled");+ return Self { sink: None };+ };+ let client = AnalyticsClient::new(AnalyticsClientConfig {+ posthog: Some(PostHogConfig {+ api_key: api_key.to_owned(),+ host: config+ .posthog_host+ .value()+ .unwrap_or("https://us.i.posthog.com")+ .to_owned(),+ }),+ ..AnalyticsClientConfig::default()+ });+ Self {+ sink: Some(Arc::new(PostHogSink {+ sender: BackgroundSender::new(client, MAX_IN_FLIGHT_SENDS),+ teams: PgAccessRepository::new(db.clone()),+ environment: config.environment,+ })),+ }+ }++ /// Records `change` in the background so analytics never delays or fails+ /// the connect or disconnect request.+ pub fn record(+ &self,+ user_id: MacroUserIdStr<'static>,+ change: IntegrationChange,+ event: IntegrationEvent,+ ) {+ let Some(sink) = &self.sink else {+ return;+ };+ let task_sink = sink.clone();+ sink.sender.spawn(move |posthog| async move {+ task_sink.capture(&posthog, user_id, change, event).await;+ });+ }+}++impl PostHogSink {+ async fn capture(+ &self,+ posthog: &AnalyticsClient,+ user_id: MacroUserIdStr<'static>,+ change: IntegrationChange,+ event: IntegrationEvent,+ ) {+ let team_id = self+ .teams+ .get_user_team(&user_id.0)+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, "failed to resolve team for integration analytics");+ })+ .ok()+ .flatten()+ .map(|team| team.team_id);+ let properties = ProductEventProperties::new(event, self.environment, team_id);+ let _ = posthog+ .track_posthog(user_id.as_ref(), change.event_name(), &properties)+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, event = change.event_name(), "failed to track integration analytics event");+ });+ }+}diff --git a/services/agent_harness_service/src/cognition/service/integration_analytics/test.rs b/services/agent_harness_service/src/cognition/service/integration_analytics/test.rsnew file mode 100644index 0000000000..81af328bb0--- /dev/null+++ b/services/agent_harness_service/src/cognition/service/integration_analytics/test.rs@@ -0,0 +1,64 @@+use super::*;+use serde_json::json;++#[test]+fn pipedream_apps_are_identified_by_their_slug() {+ assert_eq!(+ serde_json::to_value(IntegrationEvent::pipedream("google_drive")).unwrap(),+ json!({ "provider": "google_drive", "connection_type": "pipedream" })+ );+}++#[test]+fn mcp_servers_are_identified_by_host_without_path_or_query() {+ assert_eq!(+ serde_json::to_value(IntegrationEvent::mcp_server(+ "https://mcp.example.com/sse/abc123?token=secret"+ ))+ .unwrap(),+ json!({ "provider": "mcp.example.com", "connection_type": "mcp_server" })+ );+}++#[test]+fn unparseable_mcp_server_urls_are_recorded_as_unknown() {+ assert_eq!(+ serde_json::to_value(IntegrationEvent::mcp_server("not a url")).unwrap(),+ json!({ "provider": "unknown", "connection_type": "mcp_server" })+ );+}++fn mcp_server_record(+ credentials: Option<mcp_client::domain::models::StoredCredentials>,+) -> McpServerRecord {+ McpServerRecord {+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap(),+ url: "https://mcp.linear.app/mcp".to_owned(),+ server_name: "Linear".to_owned(),+ credentials,+ enabled: true,+ }+}++#[test]+fn removing_an_authenticated_mcp_server_is_a_disconnect() {+ let credentials = mcp_client::domain::models::StoredCredentials::new(+ "client".to_owned(),+ None,+ Vec::new(),+ None,+ );++ assert_eq!(+ IntegrationEvent::removed_mcp_server(&mcp_server_record(Some(credentials))),+ Some(IntegrationEvent::mcp_server("https://mcp.linear.app/mcp"))+ );+}++#[test]+fn removing_a_server_that_never_finished_oauth_is_not_a_disconnect() {+ assert_eq!(+ IntegrationEvent::removed_mcp_server(&mcp_server_record(None)),+ None+ );+}diff --git a/services/agent_harness_service/src/cognition/service/mod.rs b/services/agent_harness_service/src/cognition/service/mod.rsindex 18f02ab5ee..d02c8d9d4c 100644--- a/services/agent_harness_service/src/cognition/service/mod.rs+++ b/services/agent_harness_service/src/cognition/service/mod.rs@@ -2,5 +2,6 @@ pub mod ai_stream_registry;pub mod chat_renamer;pub mod get_chat;pub mod id_mapping;+pub mod integration_analytics;pub mod notification;pub mod structured_completion;diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 6ba1dfac71..086b3193f4 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -44,7 +44,8 @@ macro_env_var::env_vars!();macro_env_var::maybe_env_vars!(- /// PostHog project token for feature flags; reserved for future MCP analytics. No MCP events are emitted.+ /// PostHog project token for feature flags and public MCP analytics. When+ /// unset, both are off.pub struct PosthogApiKey;/// Regional PostHog ingestion origin; defaults to the US origin.pub struct PosthogHost;diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 496647da92..29150eb0fa 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -644,6 +644,7 @@ async fn run() -> anyhow::Result<()> {&config,&secrets,tool_context.clone(),+ pool.clone(),macro_auth::middleware::decode_jwt::JwtValidationArgs::new_with_secret_manager(config.environment,&secrets,diff --git a/services/agent_harness_service/src/public_mcp.rs b/services/agent_harness_service/src/public_mcp.rsindex 27f0f1ba18..bc5d1de7e5 100644--- a/services/agent_harness_service/src/public_mcp.rs+++ b/services/agent_harness_service/src/public_mcp.rs@@ -1,4 +1,5 @@//! Public workspace MCP and OAuth, hosted on the harness's public listener.+mod analytics;mod markdown_images;#[cfg(test)]mod test;@@ -7,6 +8,8 @@ mod tool_response;mod tool_service;use crate::config::Config;+use analytics::McpAnalytics;+use analytics_client::{AnalyticsClient, AnalyticsClientConfig, PostHogConfig};use anyhow::Context;use macro_auth::middleware::decode_jwt::JwtValidationArgs;use mcp_auth_proxy::{@@ -42,10 +45,15 @@ const DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS: [&str; 5] = [];/// Build public MCP routes using the harness's shared tools and identities.+#[expect(+ clippy::too_many_arguments,+ reason = "each argument is a separate harness resource the router shares; bundling them only moves the list"+)]pub async fn router(config: &Config,secrets: &secretsmanager_client::SecretsManager,tool_context: ai_tools::ToolServiceContext,+ db: sqlx::PgPool,jwt_args: JwtValidationArgs,background_tasks: tokio_util::task::TaskTracker,cancellation: tokio_util::sync::CancellationToken,@@ -53,6 +61,7 @@ pub async fn router() -> anyhow::Result<axum::Router> {let public_url = macro_service_urls::McpPublicUrl::new()?;let auth_proxy = build_auth_proxy(config, secrets, &public_url).await?;+ let analytics = build_analytics(config, db);let item_base_url = macro_service_urls::AppServiceUrl::new()?.to_string();let static_file_base_url =url::Url::parse(macro_service_urls::StaticFileServiceUrl::new()?.as_ref())?;@@ -82,6 +91,7 @@ pub async fn router(tool_context.clone(),item_base_url.clone(),static_file_base_url.clone(),+ analytics.clone(),);Ok(match &code_mode {Some(code_mode) => service.with_code_mode(code_mode.clone()),@@ -198,6 +208,30 @@ async fn build_auth_proxy(}))}+/// PostHog MCP analytics when `POSTHOG_API_KEY` is set; otherwise disabled.+fn build_analytics(config: &Config, db: sqlx::PgPool) -> McpAnalytics {+ let Some(api_key) = config.posthog_api_key.value() else {+ tracing::info!("POSTHOG_API_KEY unset; MCP analytics disabled");+ return McpAnalytics::disabled();+ };+ let client = AnalyticsClient::new(AnalyticsClientConfig {+ posthog: Some(PostHogConfig {+ api_key: api_key.to_owned(),+ host: config+ .posthog_host+ .value()+ .unwrap_or("https://us.i.posthog.com")+ .to_owned(),+ }),+ ..AnalyticsClientConfig::default()+ });+ McpAnalytics::posthog(+ client,+ entity_access::outbound::PgAccessRepository::new(db),+ config.environment,+ )+}+/// Builds the redirect URI policy the broker enforces at registration and at/// authorize, from the configured host list or the built-in default.fn build_redirect_uri_policy(config: &Config) -> RedirectUriPolicy {diff --git a/services/agent_harness_service/src/public_mcp/analytics.rs b/services/agent_harness_service/src/public_mcp/analytics.rsnew file mode 100644index 0000000000..7346cb1e41--- /dev/null+++ b/services/agent_harness_service/src/public_mcp/analytics.rs@@ -0,0 +1,355 @@+//! Server-side product analytics for MCP traffic.+//!+//! Events use PostHog's MCP analytics schema (`$mcp_initialize`,+//! `$mcp_tool_call`, `$mcp_*` properties), so PostHog's MCP dashboards and its+//! client ("harness") bucketing read them without custom insights. Tool+//! arguments and results are never recorded: only the tool name, outcome, and+//! timing.++#[cfg(test)]+mod test;++use std::{+ num::NonZeroUsize,+ sync::{Arc, Mutex},+ time::{Duration, Instant},+};++use analytics_client::{AnalyticsClient, BackgroundSender, ProductEventProperties};+use entity_access::{domain::ports::AccessRepository, outbound::PgAccessRepository};+use lru::LruCache;+use macro_env::Environment;+use macro_user_id::user_id::MacroUserIdStr;+use mcp_auth_proxy::inbound::middleware::McpAuthMethod;+use serde::Serialize;++/// Name the server advertises in `initialize`, recorded on every event.+pub const SERVER_NAME: &str = "macro-tools";++/// Longest header value recorded. User agents are the longest signal clients+/// send; anything past this is noise.+const MAX_HEADER_LEN: usize = 256;++/// What an MCP HTTP request says about the client that sent it.+///+/// The server runs stateless, so a tool call carries no `clientInfo`; these+/// headers are what identify the client on every call.+#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]+pub struct McpClientSignals {+ #[serde(+ rename = "$mcp_client_user_agent",+ skip_serializing_if = "Option::is_none"+ )]+ user_agent: Option<String>,+ /// Anthropic's surfaces (Claude.ai, Claude Code, Cowork) name themselves+ /// here; PostHog's harness bucketing reads it first.+ #[serde(rename = "$mcp_vendor_client", skip_serializing_if = "Option::is_none")]+ vendor_client: Option<String>,+ #[serde(+ rename = "$mcp_protocol_version",+ skip_serializing_if = "Option::is_none"+ )]+ protocol_version: Option<String>,+ #[serde(rename = "$mcp_auth_method", skip_serializing_if = "Option::is_none")]+ auth_method: Option<&'static str>,+}++impl McpClientSignals {+ /// Reads the client signals from the HTTP request behind an MCP message.+ pub fn from_request_parts(parts: Option<&http::request::Parts>) -> Self {+ let Some(parts) = parts else {+ return Self::default();+ };+ let header = |name: &str| {+ parts+ .headers+ .get(name)+ .and_then(|value| value.to_str().ok())+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .map(|value| value.chars().take(MAX_HEADER_LEN).collect())+ };+ Self {+ user_agent: header("user-agent"),+ vendor_client: header("x-anthropic-client"),+ protocol_version: header("mcp-protocol-version"),+ auth_method: parts+ .extensions+ .get::<McpAuthMethod>()+ .map(|method| method.as_str()),+ }+ }+}++/// How a tool call ended.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum ToolCallOutcome {+ /// The tool ran and returned a result.+ Success,+ /// The request named no registered tool, or its arguments were missing or+ /// did not match the tool's schema.+ InvalidRequest,+ /// The tool ran and reported an error to the model.+ ToolError,+}++impl ToolCallOutcome {+ /// PostHog's `$mcp_error_type` bucket. Tool errors carry no reliable+ /// cause, so they leave the bucket unset rather than guess one.+ fn error_type(self) -> Option<&'static str> {+ match self {+ Self::Success | Self::ToolError => None,+ Self::InvalidRequest => Some("validation"),+ }+ }+}++/// One MCP request worth recording.+#[derive(Clone, Debug, Eq, PartialEq)]+pub enum McpAnalyticsEvent {+ /// A client opened an MCP session.+ Initialize {+ /// `clientInfo.name`, e.g. `claude-ai`, `openai-mcp`, `cursor-vscode`.+ client_name: String,+ /// `clientInfo.version`.+ client_version: String,+ /// The protocol version the client asked for.+ protocol_version: String,+ },+ /// A client called a tool.+ ToolCall {+ /// The registered tool name, e.g. `ContentSearch`.+ tool_name: String,+ /// How the call ended.+ outcome: ToolCallOutcome,+ /// Wall-clock time spent handling the call.+ duration: Duration,+ },+}++impl McpAnalyticsEvent {+ fn name(&self) -> &'static str {+ match self {+ Self::Initialize { .. } => "$mcp_initialize",+ Self::ToolCall { .. } => "$mcp_tool_call",+ }+ }+}++#[derive(Debug, Serialize)]+#[serde(untagged)]+enum EventSpecificProperties<'a> {+ Initialize {+ #[serde(rename = "$mcp_client_name")]+ client_name: &'a str,+ #[serde(rename = "$mcp_client_version")]+ client_version: &'a str,+ #[serde(rename = "$mcp_protocol_version")]+ protocol_version: &'a str,+ },+ ToolCall {+ #[serde(rename = "$mcp_tool_name")]+ tool_name: &'a str,+ #[serde(rename = "$mcp_is_error")]+ is_error: bool,+ #[serde(rename = "$mcp_error_type", skip_serializing_if = "Option::is_none")]+ error_type: Option<&'static str>,+ #[serde(rename = "$mcp_duration_ms")]+ duration_ms: u64,+ },+}++#[derive(Debug, Serialize)]+struct EventProperties<'a> {+ // Flattened first so the request header's protocol version cannot+ // override the one `initialize` negotiated: serde keeps the last key.+ #[serde(flatten)]+ client: &'a McpClientSignals,+ #[serde(flatten)]+ event: EventSpecificProperties<'a>,+ #[serde(rename = "$mcp_server_name")]+ server_name: &'static str,+ #[serde(rename = "$mcp_server_version")]+ server_version: &'static str,+}++impl<'a> EventProperties<'a> {+ fn new(event: &'a McpAnalyticsEvent, client: &'a McpClientSignals) -> Self {+ let event = match event {+ McpAnalyticsEvent::Initialize {+ client_name,+ client_version,+ protocol_version,+ } => EventSpecificProperties::Initialize {+ client_name,+ client_version,+ protocol_version,+ },+ McpAnalyticsEvent::ToolCall {+ tool_name,+ outcome,+ duration,+ } => EventSpecificProperties::ToolCall {+ tool_name,+ is_error: *outcome != ToolCallOutcome::Success,+ error_type: outcome.error_type(),+ duration_ms: u64::try_from(duration.as_millis()).unwrap_or(u64::MAX),+ },+ };+ Self {+ client,+ event,+ server_name: SERVER_NAME,+ server_version: env!("CARGO_PKG_VERSION"),+ }+ }+}++/// Most MCP analytics sends in flight at once; past it, events are dropped.+const MAX_IN_FLIGHT_SENDS: usize = 64;++/// How long a user's team is reused before it is read again. Tool calls are+/// frequent and share the harness database pool, while team membership+/// rarely changes.+const TEAM_TTL: Duration = Duration::from_secs(10 * 60);++/// Users whose team is remembered at once.+const TEAM_CACHE_CAPACITY: usize = 10_000;++/// Records MCP product analytics to PostHog, or nothing when PostHog is not+/// configured.+#[derive(Clone)]+pub struct McpAnalytics {+ sink: Option<Arc<PostHogSink>>,+}++struct PostHogSink {+ sender: BackgroundSender,+ teams: PgAccessRepository,+ team_cache: TeamCache,+ environment: Environment,+}++impl McpAnalytics {+ /// Analytics that records nothing.+ pub fn disabled() -> Self {+ Self { sink: None }+ }++ /// Analytics that records to PostHog, attributing each event to the+ /// user's team when they belong to one.+ pub fn posthog(+ client: AnalyticsClient,+ teams: PgAccessRepository,+ environment: Environment,+ ) -> Self {+ Self {+ sink: Some(Arc::new(PostHogSink {+ sender: BackgroundSender::new(client, MAX_IN_FLIGHT_SENDS),+ teams,+ team_cache: TeamCache::new(TEAM_CACHE_CAPACITY),+ environment,+ })),+ }+ }++ /// Records `event` for `user_id` in the background, so analytics never+ /// delays or fails an MCP response.+ pub fn record(+ &self,+ user_id: MacroUserIdStr<'static>,+ client: McpClientSignals,+ event: McpAnalyticsEvent,+ ) {+ let Some(sink) = &self.sink else {+ return;+ };+ let task_sink = sink.clone();+ sink.sender.spawn(move |posthog| async move {+ task_sink.capture(&posthog, user_id, client, event).await;+ });+ }+}++impl PostHogSink {+ async fn capture(+ &self,+ posthog: &AnalyticsClient,+ user_id: MacroUserIdStr<'static>,+ client: McpClientSignals,+ event: McpAnalyticsEvent,+ ) {+ let team_id = self.team_id(&user_id).await;+ let properties = ProductEventProperties::new(+ EventProperties::new(&event, &client),+ self.environment,+ team_id,+ );+ let _ = posthog+ .track_posthog(user_id.as_ref(), event.name(), &properties)+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, event = event.name(), "failed to track MCP analytics event");+ });+ }++ /// The user's team, from the cache when it is fresh. A failed read is not+ /// cached, so the next event tries again.+ async fn team_id(&self, user_id: &MacroUserIdStr<'static>) -> Option<uuid::Uuid> {+ if let Some(team_id) = self.team_cache.get(user_id, Instant::now()) {+ return team_id;+ }+ let team_id = self+ .teams+ .get_user_team(&user_id.0)+ .await+ .inspect_err(|error| {+ tracing::warn!(error=?error, "failed to resolve team for MCP analytics");+ })+ .ok()?+ .map(|team| team.team_id);+ self.team_cache+ .put(user_id.clone(), team_id, Instant::now());+ team_id+ }+}++/// Each user's team (or none), remembered for [`TEAM_TTL`].+struct TeamCache {+ entries: Mutex<LruCache<MacroUserIdStr<'static>, CachedTeam>>,+}++#[derive(Clone, Copy)]+struct CachedTeam {+ team_id: Option<uuid::Uuid>,+ read_at: Instant,+}++impl TeamCache {+ fn new(capacity: usize) -> Self {+ Self {+ entries: Mutex::new(LruCache::new(+ NonZeroUsize::new(capacity).expect("a nonzero capacity"),+ )),+ }+ }++ /// The user's team as read within [`TEAM_TTL`] of `now`, or `None` when+ /// it has to be read again.+ fn get(&self, user_id: &MacroUserIdStr<'static>, now: Instant) -> Option<Option<uuid::Uuid>> {+ let mut entries = self.entries.lock().expect("team cache poisoned");+ let cached = *entries.get(user_id)?;+ if now.saturating_duration_since(cached.read_at) < TEAM_TTL {+ return Some(cached.team_id);+ }+ entries.pop(user_id);+ None+ }++ fn put(&self, user_id: MacroUserIdStr<'static>, team_id: Option<uuid::Uuid>, read_at: Instant) {+ self.entries+ .lock()+ .expect("team cache poisoned")+ .put(user_id, CachedTeam { team_id, read_at });+ }+}diff --git a/services/agent_harness_service/src/public_mcp/analytics/test.rs b/services/agent_harness_service/src/public_mcp/analytics/test.rsnew file mode 100644index 0000000000..0125356dd4--- /dev/null+++ b/services/agent_harness_service/src/public_mcp/analytics/test.rs@@ -0,0 +1,205 @@+use super::*;+use serde_json::json;++fn request_parts(+ headers: &[(&str, &str)],+ auth_method: Option<McpAuthMethod>,+) -> http::request::Parts {+ let mut builder = http::Request::builder().uri("/mcp").method("POST");+ for (name, value) in headers {+ builder = builder.header(*name, *value);+ }+ let (mut parts, ()) = builder.body(()).unwrap().into_parts();+ if let Some(auth_method) = auth_method {+ parts.extensions.insert(auth_method);+ }+ parts+}++fn properties(+ event: &McpAnalyticsEvent,+ client: &McpClientSignals,+ environment: Environment,+ team_id: Option<uuid::Uuid>,+) -> serde_json::Value {+ serde_json::to_value(ProductEventProperties::new(+ EventProperties::new(event, client),+ environment,+ team_id,+ ))+ .unwrap()+}++#[test]+fn client_signals_read_headers_and_auth_method() {+ let parts = request_parts(+ &[+ ("user-agent", "claude-code/2.1.0 (cli)"),+ ("x-anthropic-client", "ClaudeCode"),+ ("mcp-protocol-version", "2025-06-18"),+ ],+ Some(McpAuthMethod::ApiKey),+ );++ let signals = McpClientSignals::from_request_parts(Some(&parts));++ assert_eq!(+ serde_json::to_value(&signals).unwrap(),+ json!({+ "$mcp_client_user_agent": "claude-code/2.1.0 (cli)",+ "$mcp_vendor_client": "ClaudeCode",+ "$mcp_protocol_version": "2025-06-18",+ "$mcp_auth_method": "api_key",+ })+ );+}++#[test]+fn client_signals_truncate_long_headers_and_skip_blank_ones() {+ let long_agent = "a".repeat(1000);+ let parts = request_parts(+ &[+ ("user-agent", long_agent.as_str()),+ ("x-anthropic-client", " "),+ ],+ None,+ );++ let signals = McpClientSignals::from_request_parts(Some(&parts));++ assert_eq!(+ serde_json::to_value(&signals).unwrap(),+ json!({ "$mcp_client_user_agent": "a".repeat(256) })+ );+}++#[test]+fn client_signals_are_empty_without_request_parts() {+ assert_eq!(+ McpClientSignals::from_request_parts(None),+ McpClientSignals::default()+ );+}++#[test]+fn successful_tool_call_records_name_timing_and_team_only() {+ let team_id = uuid::Uuid::parse_str("7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f").unwrap();+ let client = McpClientSignals::from_request_parts(Some(&request_parts(+ &[("user-agent", "openai-mcp/1.0.0")],+ Some(McpAuthMethod::OAuth),+ )));+ let event = McpAnalyticsEvent::ToolCall {+ tool_name: "ContentSearch".to_owned(),+ outcome: ToolCallOutcome::Success,+ duration: Duration::from_millis(1234),+ };++ assert_eq!(+ properties(&event, &client, Environment::Production, Some(team_id)),+ json!({+ "$mcp_tool_name": "ContentSearch",+ "$mcp_is_error": false,+ "$mcp_duration_ms": 1234,+ "$mcp_client_user_agent": "openai-mcp/1.0.0",+ "$mcp_auth_method": "oauth",+ "$mcp_server_name": "macro-tools",+ "$mcp_server_version": env!("CARGO_PKG_VERSION"),+ "env": "PROD",+ "macro_environment": "prod",+ "team_id": "7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f",+ "$groups": { "team": "7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f" },+ })+ );+}++#[test]+fn failed_tool_calls_use_posthogs_error_buckets() {+ for (outcome, error_type) in [+ (ToolCallOutcome::InvalidRequest, Some("validation")),+ (ToolCallOutcome::ToolError, None),+ ] {+ let event = McpAnalyticsEvent::ToolCall {+ tool_name: "EditDocument".to_owned(),+ outcome,+ duration: Duration::from_millis(5),+ };++ let value = properties(+ &event,+ &McpClientSignals::default(),+ Environment::Develop,+ None,+ );++ assert_eq!(value["$mcp_is_error"], json!(true));+ assert_eq!(+ value.get("$mcp_error_type"),+ error_type.map(|t| json!(t)).as_ref()+ );+ assert_eq!(value["env"], json!("DEV"));+ assert!(value.get("$groups").is_none());+ assert!(value.get("team_id").is_none());+ }+}++#[test]+fn a_cached_team_is_reused_until_it_expires() {+ let cache = TeamCache::new(10);+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let team_id = uuid::Uuid::parse_str("7f9c2b1e-3d4a-4c5b-8e6f-1a2b3c4d5e6f").unwrap();+ let read_at = Instant::now();++ cache.put(user.clone(), Some(team_id), read_at);++ assert_eq!(+ cache.get(&user, read_at + Duration::from_secs(9 * 60)),+ Some(Some(team_id))+ );+ assert_eq!(+ cache.get(&user, read_at + Duration::from_secs(10 * 60)),+ None+ );+ assert_eq!(cache.get(&user, read_at), None);+}++#[test]+fn users_without_a_team_are_cached_as_teamless() {+ let cache = TeamCache::new(10);+ let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();+ let read_at = Instant::now();++ cache.put(user.clone(), None, read_at);++ assert_eq!(cache.get(&user, read_at), Some(None));+}++#[test]+fn initialize_records_client_info_and_negotiated_protocol_version() {+ let client = McpClientSignals::from_request_parts(Some(&request_parts(+ &[+ ("user-agent", "Claude-User"),+ ("mcp-protocol-version", "2024-11-05"),+ ],+ Some(McpAuthMethod::OAuth),+ )));+ let event = McpAnalyticsEvent::Initialize {+ client_name: "claude-ai".to_owned(),+ client_version: "0.1.0".to_owned(),+ protocol_version: "2025-06-18".to_owned(),+ };++ assert_eq!(+ properties(&event, &client, Environment::Production, None),+ json!({+ "$mcp_client_name": "claude-ai",+ "$mcp_client_version": "0.1.0",+ "$mcp_protocol_version": "2025-06-18",+ "$mcp_client_user_agent": "Claude-User",+ "$mcp_auth_method": "oauth",+ "$mcp_server_name": "macro-tools",+ "$mcp_server_version": env!("CARGO_PKG_VERSION"),+ "env": "PROD",+ "macro_environment": "prod",+ })+ );+}diff --git a/services/agent_harness_service/src/public_mcp/tool_service.rs b/services/agent_harness_service/src/public_mcp/tool_service.rsindex a7e3b6a74f..6805628782 100644--- a/services/agent_harness_service/src/public_mcp/tool_service.rs+++ b/services/agent_harness_service/src/public_mcp/tool_service.rs@@ -1,3 +1,6 @@+use crate::public_mcp::analytics::{+ McpAnalytics, McpAnalyticsEvent, McpClientSignals, SERVER_NAME, ToolCallOutcome,+};use crate::public_mcp::markdown_images::MarkdownImageResolver;use crate::public_mcp::tool_response::tool_result_with_media;use agent_code_mode::inbound::toolset::UserCodeModeToolContext;@@ -11,7 +14,7 @@ use rmcp::{PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool, ToolAnnotations,},};-use std::sync::Arc;+use std::{sync::Arc, time::Instant};/// Maps our protocol-agnostic annotations onto the MCP wire representation.///@@ -66,6 +69,8 @@ pub struct AuthenticatedToolService<Context> {static_file_base_url: url::Url,/// Present when this deployment can run code.code_mode: Option<Arc<CodeModeSurface<Context>>>,+ /// Records sessions and tool calls to product analytics.+ analytics: McpAnalytics,}impl<Context> AuthenticatedToolService<Context> {@@ -75,6 +80,7 @@ impl<Context> AuthenticatedToolService<Context> {context: Context,item_base_url: String,static_file_base_url: url::Url,+ analytics: McpAnalytics,) -> Self {Self {toolset,@@ -82,6 +88,7 @@ impl<Context> AuthenticatedToolService<Context> {item_base_url,static_file_base_url,code_mode: None,+ analytics,}}@@ -123,6 +130,10 @@ impl<Context> AuthenticatedToolService<Context> {rmcp::ErrorData::internal_error("missing user identity — is auth configured?", None)})}++ fn client_signals(extensions: &rmcp::model::Extensions) -> McpClientSignals {+ McpClientSignals::from_request_parts(extensions.get::<http::request::Parts>())+ }}#[cfg(test)]@@ -135,21 +146,18 @@ wherefn get_info(&self) -> ServerInfo {let mut info = ServerInfo::new(ServerCapabilities::builder().enable_tools().build());let base_url = self.item_base_url.trim_end_matches('/');- info.server_info = rmcp::model::Implementation::new(- "macro-tools",- env!("CARGO_PKG_VERSION"),- )- .with_title("Macro")- .with_description(- "Search, read, and create content across documents, emails, and messages in Macro.",- )- // The same icon the web app's <link rel="icon"> points at, so the- // server shows up in MCP clients with the Macro favicon.- .with_icons(vec![- Icon::new(format!("{base_url}/app/macro-favicon.svg"))- .with_mime_type("image/svg+xml")- .with_sizes(vec!["any".to_owned()]),- ]);+ info.server_info = rmcp::model::Implementation::new(SERVER_NAME, env!("CARGO_PKG_VERSION"))+ .with_title("Macro")+ .with_description(+ "Search, read, and create content across documents, emails, and messages in Macro.",+ )+ // The same icon the web app's <link rel="icon"> points at, so the+ // server shows up in MCP clients with the Macro favicon.+ .with_icons(vec![+ Icon::new(format!("{base_url}/app/macro-favicon.svg"))+ .with_mime_type("image/svg+xml")+ .with_sizes(vec!["any".to_owned()]),+ ]);info.instructions = Some(format!("This server provides tools for interacting with a user's Macro workspace. \Use ContentSearch and NameSearch to find entities. \@@ -173,11 +181,22 @@ whererequest: InitializeRequestParams,context: rmcp::service::RequestContext<rmcp::RoleServer>,) -> Result<InitializeResult, rmcp::ErrorData> {+ let user_id = Self::authenticated_user_id(&context.extensions)?;+ // `initialize` is the only message that names the client, so it is+ // where sessions are counted per client.+ self.analytics.record(+ user_id.clone(),+ Self::client_signals(&context.extensions),+ McpAnalyticsEvent::Initialize {+ client_name: request.client_info.name.clone(),+ client_version: request.client_info.version.clone(),+ protocol_version: request.protocol_version.to_string(),+ },+ );if context.peer.peer_info().is_none() {context.peer.set_peer_info(request);}let mut info = self.get_info();- let user_id = Self::authenticated_user_id(&context.extensions)?;if self.tool_mode(&user_id).await == ToolMode::Code&& let Some(instructions) = info.instructions.as_mut(){@@ -207,25 +226,62 @@ wherecontext: rmcp::service::RequestContext<rmcp::RoleServer>,) -> Result<rmcp::model::CallToolResult, rmcp::ErrorData> {let user_id = Self::authenticated_user_id(&context.extensions)?;+ let started = Instant::now();+ // Bounded: an unknown tool's name is whatever the client sent.+ let tool_name = request.name.chars().take(128).collect();++ let (outcome, result) = self.run_tool(user_id.clone(), request, &context).await;+ self.analytics.record(+ user_id,+ Self::client_signals(&context.extensions),+ McpAnalyticsEvent::ToolCall {+ tool_name,+ outcome,+ duration: started.elapsed(),+ },+ );+ result+ }+}++impl<Context> AuthenticatedToolService<Context>+where+ Context: Clone + Send + Sync + MarkdownImageResolver + 'static,+{+ /// Runs one tool call and classifies how it ended, for analytics.+ async fn run_tool(+ &self,+ user_id: MacroUserIdStr<'static>,+ request: rmcp::model::CallToolRequestParams,+ context: &rmcp::service::RequestContext<rmcp::RoleServer>,+ ) -> (+ ToolCallOutcome,+ Result<rmcp::model::CallToolResult, rmcp::ErrorData>,+ ) {let mut request_context = RequestContext::new(user_id.clone());- let arguments = request- .arguments- .map(serde_json::Value::Object)- .ok_or(rmcp::ErrorData::invalid_params("No params provided", None))?;+ let Some(arguments) = request.arguments.map(serde_json::Value::Object) else {+ return (+ ToolCallOutcome::InvalidRequest,+ Err(rmcp::ErrorData::invalid_params("No params provided", None)),+ );+ };if let Some(code_mode) = &self.code_mode&& code_mode.tools.tools.contains_key(request.name.as_ref()){if self.tool_mode(&user_id).await != ToolMode::Code {- return Err(rmcp::ErrorData::resource_not_found(- format!("tool {} not found", request.name),- None,- ));+ return (+ ToolCallOutcome::InvalidRequest,+ Err(rmcp::ErrorData::resource_not_found(+ format!("tool {} not found", request.name),+ None,+ )),+ );}request_context.cancel = context.ct.clone();- let result = code_mode+ let result = match code_mode.tools.try_tool_call(code_mode.context.clone(),@@ -234,15 +290,31 @@ where&arguments,).await- .map_err(|error| rmcp::ErrorData::invalid_params(error.to_string(), None))?;- return Ok(match result {+ {+ Ok(result) => result,+ Err(error) => {+ return (+ ToolCallOutcome::InvalidRequest,+ Err(rmcp::ErrorData::invalid_params(error.to_string(), None)),+ );+ }+ };+ return match result {+ Ok(value) => (+ ToolCallOutcome::Success,+ Ok(CallToolResult::structured(value)),+ ),// A failed program is a completed execution with a receipt.- Ok(value) => CallToolResult::structured(value),- Err(error) => CallToolResult::error(vec![Content::text(error.description)]),- });+ Err(error) => (+ ToolCallOutcome::ToolError,+ Ok(CallToolResult::error(vec![Content::text(+ error.description,+ )])),+ ),+ };}- let result = self+ let result = match self.toolset.try_tool_call(self.context.clone(),@@ -251,27 +323,40 @@ where&arguments,).await- .map_err(|error| match error {- ai_toolset::ToolSetError::Deserialization(error) => {- rmcp::ErrorData::parse_error(error.to_string(), None)- }- ai_toolset::ToolSetError::NotFound(message) => {- rmcp::ErrorData::resource_not_found(message, None)- }- })?;+ {+ Ok(result) => result,+ Err(ai_toolset::ToolSetError::Deserialization(error)) => {+ return (+ ToolCallOutcome::InvalidRequest,+ Err(rmcp::ErrorData::parse_error(error.to_string(), None)),+ );+ }+ Err(ai_toolset::ToolSetError::NotFound(message)) => {+ return (+ ToolCallOutcome::InvalidRequest,+ Err(rmcp::ErrorData::resource_not_found(message, None)),+ );+ }+ };match result {- Ok(value) => Ok(tool_result_with_media(- &self.context,- &user_id,- &request.name,- &self.static_file_base_url,- value,- )- .await),- Err(error) => Ok(rmcp::model::CallToolResult::error(vec![Content::text(- error.description,- )])),+ Ok(value) => (+ ToolCallOutcome::Success,+ Ok(tool_result_with_media(+ &self.context,+ &user_id,+ &request.name,+ &self.static_file_base_url,+ value,+ )+ .await),+ ),+ Err(error) => (+ ToolCallOutcome::ToolError,+ Ok(rmcp::model::CallToolResult::error(vec![Content::text(+ error.description,+ )])),+ ),}}}diff --git a/services/agent_harness_service/src/public_mcp/tool_service/test.rs b/services/agent_harness_service/src/public_mcp/tool_service/test.rsindex 4660cb65d3..de45400793 100644--- a/services/agent_harness_service/src/public_mcp/tool_service/test.rs+++ b/services/agent_harness_service/src/public_mcp/tool_service/test.rs@@ -8,6 +8,7 @@ fn empty_service() -> AuthenticatedToolService<()> {(),"https://macro.com".to_owned(),url::Url::parse("https://static-file-service.macro.com").unwrap(),+ McpAnalytics::disabled(),)}diff --git a/services/mcp_auth_proxy/src/inbound/middleware.rs b/services/mcp_auth_proxy/src/inbound/middleware.rsindex dcb9bacfc4..fad6f67314 100644--- a/services/mcp_auth_proxy/src/inbound/middleware.rs+++ b/services/mcp_auth_proxy/src/inbound/middleware.rs@@ -17,6 +17,26 @@ use macro_user_id::user_id::MacroUserIdStr;#[derive(Clone)]pub struct JwtAccessToken(pub String);+/// Which kind of credential authenticated an MCP request.+#[derive(Clone, Copy, Debug, Eq, PartialEq)]+pub enum McpAuthMethod {+ /// A FusionAuth access token, as issued by the OAuth broker to clients+ /// such as Claude.ai, ChatGPT, or Cursor.+ OAuth,+ /// A Macro API key the user created and pasted into the client.+ ApiKey,+}++impl McpAuthMethod {+ /// Stable lowercase label for logs and analytics.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::OAuth => "oauth",+ Self::ApiKey => "api_key",+ }+ }+}+fn resource_metadata_path() -> String {format!("{}/.well-known/oauth-protected-resource",@@ -77,7 +97,7 @@ fn unauthorized_response(request: &Request<Body>, error: Option<&str>) -> Respon}/// Validates `Authorization: Bearer <token>` and stores the authenticated-/// [`MacroUserIdStr`] in the request extensions.+/// [`MacroUserIdStr`] and its [`McpAuthMethod`] in the request extensions.pub async fn validate_bearer(axum::extract::State(jwt_args): axum::extract::State<JwtValidationArgs>,mut request: Request<Body>,@@ -103,9 +123,9 @@ pub async fn validate_bearer(}};- let user_id = match jwt_token {- JwtToken::MacroAccessToken(token) => token.macro_user_id.clone(),- JwtToken::MacroApiToken(token) => token.macro_user_id.clone(),+ let (user_id, auth_method) = match jwt_token {+ JwtToken::MacroAccessToken(token) => (token.macro_user_id, McpAuthMethod::OAuth),+ JwtToken::MacroApiToken(token) => (token.macro_user_id, McpAuthMethod::ApiKey),};let user_id = match MacroUserIdStr::try_from(user_id) {@@ -117,6 +137,7 @@ pub async fn validate_bearer(};request.extensions_mut().insert(user_id);+ request.extensions_mut().insert(auth_method);request.extensions_mut().insert(JwtAccessToken(token));next.run(request).await