Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/docs/content/docs/platform/enterprise/self-hosted.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,7 @@ Persist the same value as `CRON_SECRET` on the application and its scheduler. Ea
| Retention: file versions | `GET /api/cron/cleanup-file-versions` | Daily | No |
| OAuth token cleanup | `GET /api/cron/cleanup-oauth-tokens` | Hourly | Yes |
| Workspace source staging cleanup | `GET /api/cron/cleanup-source-staging` | Hourly | Yes |
| Retention: activity history | `GET /api/cron/cleanup-activity-history` | Daily | Yes |

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ Create a workflow with a Schedule trigger set to every minute, deploy it, and wa
| Table row TTL cleanup | `/api/cron/cleanup-table-row-ttl` | `*/15 * * * *` | Deletes table rows whose TTL column has expired |
| 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 |
| OAuth token cleanup | `/api/cron/cleanup-oauth-tokens` | `0 * * * *` | Deletes access and refresh tokens after the retention tail |
| 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 |
| 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 |
| SCIM reconciliation | `/api/cron/scim-reconcile` | `17 * * * *` | Re-applies directory group mappings |
| Data drains | `/api/cron/run-data-drains` | `0 * * * *` | Enterprise data drains |
Expand Down
29 changes: 29 additions & 0 deletions apps/sim/app/api/cron/cleanup-activity-history/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { verifyCronAuth } from '@/lib/auth/internal'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { sweepActivityHistory } from '@/lib/organizations/member-activity/retention'

export const dynamic = 'force-dynamic'
export const maxDuration = 60

const logger = createLogger('CleanupActivityHistoryAPI')

/** Removes organization adoption history past its retention windows; cron-authenticated. */
export const GET = withRouteHandler(async (request: NextRequest) => {
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
const authError = verifyCronAuth(request, 'activity history cleanup')
if (authError) return authError

try {
const result = await sweepActivityHistory()
logger.info('Activity history swept', result)
return NextResponse.json({ success: true, ...result })
} catch (error) {
logger.error('Failed to sweep activity history', { error })
return NextResponse.json(
{ error: getErrorMessage(error, 'Failed to sweep activity history') },
{ status: 500 }
)
}
})
14 changes: 14 additions & 0 deletions apps/sim/lib/execution/preprocessing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import type { SubscriptionPlan } from '@/lib/core/rate-limiter/types'
import { withDatabaseReadRetry } from '@/lib/db/read-retry'
import { claimBlockedRunLog } from '@/lib/execution/blocked-run-log'
import { LoggingSession, type SessionStartParams } from '@/lib/logs/execution/logging-session'
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
import type { CoreTriggerType } from '@/stores/logs/filters/types'

const logger = createLogger('ExecutionPreprocessing')
Expand Down Expand Up @@ -1108,6 +1109,19 @@ export async function preprocessExecution(
executionType,
effectiveTimeoutMs: executionTimeout[executionType],
})
/** A run the person started from the editor or with their own API key, never a child or table run. */
if (
useAuthenticatedUserAsActor &&
(triggerType === 'manual' || triggerType === 'api') &&
userId &&
workspaceId
) {
void recordMemberActivity({
userId,
surface: 'workflows',
scope: { kind: 'workspace', workspaceId },
})
}

return {
success: true,
Expand Down
6 changes: 6 additions & 0 deletions apps/sim/lib/knowledge/application/slack-search/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
import { AbortReason, isExplicitStopReason } from '@/lib/mothership/request/session/abort-reason'
import type { OrchestratorResult } from '@/lib/mothership/request/types'
import { organizationRoutes } from '@/lib/navigation/paths'
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
import { SlackSearchAssistantStream } from '@/lib/slack-search/assistant-stream'
import { deliverSlackSearchConnections } from '@/lib/slack-search/connections'
import {
Expand Down Expand Up @@ -183,6 +184,11 @@ export async function runSlackSearchAssistant(
await checkAccess()
await persistSlackSearchQuestion(chat.id, userId, messageId, job.message.query)
questionPersisted = true
void recordMemberActivity({
userId,
surface: 'slack',
scope: { kind: 'organization', organizationId: installation.organizationId },
})
titleTask = generateSlackSearchChatTitle(memberPrincipal(), {
job,
signal: controller.signal,
Expand Down
13 changes: 12 additions & 1 deletion apps/sim/lib/knowledge/mcp/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { sql } from 'drizzle-orm'
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'

const logger = createLogger('OrganizationSearchMcpActivity')

Expand All @@ -20,7 +21,10 @@ export type SearchMcpActivityInput = Pick<
| 'createdAt'
>

/** Stores content-free metadata from an admitted MCP request, independently of tool success. */
/**
* Stores content-free metadata from an admitted MCP request, independently of tool success, and
* counts a person's call that was not rate limited toward their adoption.
*/
export async function recordOrganizationSearchMcpActivity(
input: SearchMcpActivityInput
): Promise<void> {
Expand All @@ -45,4 +49,11 @@ export async function recordOrganizationSearchMcpActivity(
error: getErrorMessage(error),
})
}
if (input.userId && input.outcome !== 'rate_limited') {
await recordMemberActivity({
userId: input.userId,
surface: 'search_mcp',
scope: { kind: 'organization', organizationId: input.organizationId },
})
}
}
12 changes: 12 additions & 0 deletions apps/sim/lib/mothership/chat/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '@/lib/billing/core/attribution'
import { type AtomicClaimResult, chatSendIdempotency } from '@/lib/core/idempotency'
import { asOrchestrationError, statusForOrchestrationError } from '@/lib/core/orchestration/types'
import type { ResourceScope } from '@/lib/core/resource-scope'
import { listPersonalCredentials } from '@/lib/credentials/application/personal-credentials'
import {
isKnowledgeMemberAccessAvailable,
Expand Down Expand Up @@ -83,6 +84,7 @@ import { getLocalChatStreamLease } from '@/lib/mothership/request/session/abort'
import type { ExecutionContext } from '@/lib/mothership/request/types'
import { hasAddressableId } from '@/lib/mothership/resources/types'
import { prepareExecutionContext } from '@/lib/mothership/tools/handlers/context'
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
import { isWorkspaceCapabilityWithheld } from '@/lib/permission-groups/capability-assertions'
import { capabilityRefusalResponse } from '@/lib/permission-groups/capability-response'
import { captureServerEvent } from '@/lib/posthog/server'
Expand Down Expand Up @@ -1309,6 +1311,16 @@ export async function handleUnifiedChatPost(req: NextRequest) {
})
// Admission committed. A failure to attach this HTTP sink must leave the turn recoverable.
sendClaim = undefined
const activityScope: ResourceScope =
branch.kind === 'organization'
? { kind: 'organization', organizationId: branch.organizationId }
: { kind: 'workspace', workspaceId: branch.workspaceId }
void recordMemberActivity({
userId: authenticatedUserId,
surface:
branch.kind === 'organization' && body.mode === 'assistant' ? 'assistant' : 'agent',
scope: activityScope,
})
}
const stream = createSSEStream({
requestPayload,
Expand Down
Loading
Loading