Skip to content

Commit 6f254bb

Browse files
authored
feat(insights): record daily member activity per surface for organization adoption (#10532)
* feat(insights): record daily member activity per surface for organization adoption Counts each person's use of the Assistant, agent chats, the Search page, the Search MCP server, the Slack app and their own workflow runs per UTC day in organization_member_activity_daily, only for members of the owning organization. Adds a daily retention sweep (member activity after 400 days, Search MCP call metadata after 270 days) and a backfill script for the history already in copilot_messages and the MCP invocation log. * fix(insights): count only runs a person starts, dedupe forked backfill turns, bound retention batches * fix(insights): keep sweeping after a batch timeout, replace backfilled days whole
1 parent 1187560 commit 6f254bb

23 files changed

Lines changed: 69063 additions & 2 deletions

File tree

‎apps/docs/content/docs/platform/enterprise/self-hosted.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ Persist the same value as `CRON_SECRET` on the application and its scheduler. Ea
215215
| Retention: file versions | `GET /api/cron/cleanup-file-versions` | Daily | No |
216216
| OAuth token cleanup | `GET /api/cron/cleanup-oauth-tokens` | Hourly | Yes |
217217
| Workspace source staging cleanup | `GET /api/cron/cleanup-source-staging` | Hourly | Yes |
218+
| Retention: activity history | `GET /api/cron/cleanup-activity-history` | Daily | Yes |
218219

219220
Included schedules still require the cron service to be configured and running. For an external scheduler, a request looks like:
220221

‎apps/docs/content/docs/platform/self-hosting/background-jobs.mdx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa
182182
| Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired |
183183
| Stale execution cleanup | `/api/cron/cleanup-stale-executions` | `*/30 * * * *` | Fails runs whose worker died without finishing — workflow executions, background jobs, table jobs and table runs — so they stop showing as running |
184184
| OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail |
185+
| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity after 400 days, Search MCP call metadata after 270 days |
185186
| Workspace source staging cleanup | `/api/cron/cleanup-source-staging` | `30 * * * *` | Deletes binary files staged for a workspace source apply a day after they were last staged |
186187
| SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings |
187188
| Data drains | `/api/cron/run-data-drains` | `0 * * * *` | Enterprise data drains |
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { createLogger } from '@sim/logger'
2+
import { getErrorMessage } from '@sim/utils/errors'
3+
import { type NextRequest, NextResponse } from 'next/server'
4+
import { verifyCronAuth } from '@/lib/auth/internal'
5+
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
6+
import { sweepActivityHistory } from '@/lib/organizations/member-activity/retention'
7+
8+
export const dynamic = 'force-dynamic'
9+
export const maxDuration = 60
10+
11+
const logger = createLogger('CleanupActivityHistoryAPI')
12+
13+
/** Removes organization adoption history past its retention windows; cron-authenticated. */
14+
export const GET = withRouteHandler(async (request: NextRequest) => {
15+
const authError = verifyCronAuth(request, 'activity history cleanup')
16+
if (authError) return authError
17+
18+
try {
19+
const result = await sweepActivityHistory()
20+
logger.info('Activity history swept', result)
21+
return NextResponse.json({ success: true, ...result })
22+
} catch (error) {
23+
logger.error('Failed to sweep activity history', { error })
24+
return NextResponse.json(
25+
{ error: getErrorMessage(error, 'Failed to sweep activity history') },
26+
{ status: 500 }
27+
)
28+
}
29+
})

‎apps/sim/lib/execution/preprocessing.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import type { SubscriptionPlan } from '@/lib/core/rate-limiter/types'
3939
import { withDatabaseReadRetry } from '@/lib/db/read-retry'
4040
import { claimBlockedRunLog } from '@/lib/execution/blocked-run-log'
4141
import { LoggingSession, type SessionStartParams } from '@/lib/logs/execution/logging-session'
42+
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
4243
import type { CoreTriggerType } from '@/stores/logs/filters/types'
4344

4445
const logger = createLogger('ExecutionPreprocessing')
@@ -1108,6 +1109,19 @@ export async function preprocessExecution(
11081109
executionType,
11091110
effectiveTimeoutMs: executionTimeout[executionType],
11101111
})
1112+
/** A run the person started from the editor or with their own API key, never a child or table run. */
1113+
if (
1114+
useAuthenticatedUserAsActor &&
1115+
(triggerType === 'manual' || triggerType === 'api') &&
1116+
userId &&
1117+
workspaceId
1118+
) {
1119+
void recordMemberActivity({
1120+
userId,
1121+
surface: 'workflows',
1122+
scope: { kind: 'workspace', workspaceId },
1123+
})
1124+
}
11111125

11121126
return {
11131127
success: true,

‎apps/sim/lib/knowledge/application/slack-search/assistant.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
import { AbortReason, isExplicitStopReason } from '@/lib/mothership/request/session/abort-reason'
5353
import type { OrchestratorResult } from '@/lib/mothership/request/types'
5454
import { organizationRoutes } from '@/lib/navigation/paths'
55+
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
5556
import { SlackSearchAssistantStream } from '@/lib/slack-search/assistant-stream'
5657
import { deliverSlackSearchConnections } from '@/lib/slack-search/connections'
5758
import {
@@ -183,6 +184,11 @@ export async function runSlackSearchAssistant(
183184
await checkAccess()
184185
await persistSlackSearchQuestion(chat.id, userId, messageId, job.message.query)
185186
questionPersisted = true
187+
void recordMemberActivity({
188+
userId,
189+
surface: 'slack',
190+
scope: { kind: 'organization', organizationId: installation.organizationId },
191+
})
186192
titleTask = generateSlackSearchChatTitle(memberPrincipal(), {
187193
job,
188194
signal: controller.signal,

‎apps/sim/lib/knowledge/mcp/activity.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { createLogger } from '@sim/logger'
44
import { getErrorMessage } from '@sim/utils/errors'
55
import { generateId } from '@sim/utils/id'
66
import { sql } from 'drizzle-orm'
7+
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
78

89
const logger = createLogger('OrganizationSearchMcpActivity')
910

@@ -20,7 +21,10 @@ export type SearchMcpActivityInput = Pick<
2021
| 'createdAt'
2122
>
2223

23-
/** Stores content-free metadata from an admitted MCP request, independently of tool success. */
24+
/**
25+
* Stores content-free metadata from an admitted MCP request, independently of tool success, and
26+
* counts a person's call that was not rate limited toward their adoption.
27+
*/
2428
export async function recordOrganizationSearchMcpActivity(
2529
input: SearchMcpActivityInput
2630
): Promise<void> {
@@ -45,4 +49,11 @@ export async function recordOrganizationSearchMcpActivity(
4549
error: getErrorMessage(error),
4650
})
4751
}
52+
if (input.userId && input.outcome !== 'rate_limited') {
53+
await recordMemberActivity({
54+
userId: input.userId,
55+
surface: 'search_mcp',
56+
scope: { kind: 'organization', organizationId: input.organizationId },
57+
})
58+
}
4859
}

‎apps/sim/lib/mothership/chat/post.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from '@/lib/billing/core/attribution'
2020
import { type AtomicClaimResult, chatSendIdempotency } from '@/lib/core/idempotency'
2121
import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types'
22+
import type { ResourceScope } from '@/lib/core/resource-scope'
2223
import { listPersonalCredentials } from '@/lib/credentials/application/personal-credentials'
2324
import {
2425
isKnowledgeMemberAccessAvailable,
@@ -83,6 +84,7 @@ import { getLocalChatStreamLease } from '@/lib/mothership/request/session/abort'
8384
import type { ExecutionContext } from '@/lib/mothership/request/types'
8485
import { hasAddressableId } from '@/lib/mothership/resources/types'
8586
import { prepareExecutionContext } from '@/lib/mothership/tools/handlers/context'
87+
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
8688
import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions'
8789
import { capabilityRefusalResponse } from '@/lib/permission-groups/capability-response'
8890
import { captureServerEvent } from '@/lib/posthog/server'
@@ -1309,6 +1311,16 @@ export async function handleUnifiedChatPost(req: NextRequest) {
13091311
})
13101312
// Admission committed. A failure to attach this HTTP sink must leave the turn recoverable.
13111313
sendClaim = undefined
1314+
const activityScope: ResourceScope =
1315+
branch.kind === 'organization'
1316+
? { kind: 'organization', organizationId: branch.organizationId }
1317+
: { kind: 'workspace', workspaceId: branch.workspaceId }
1318+
void recordMemberActivity({
1319+
userId: authenticatedUserId,
1320+
surface:
1321+
branch.kind === 'organization' && body.mode === 'assistant' ? 'assistant' : 'agent',
1322+
scope: activityScope,
1323+
})
13121324
}
13131325
const stream = createSSEStream({
13141326
requestPayload,

0 commit comments

Comments
 (0)