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
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +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 |
| Activity history cleanup | `/api/cron/cleanup-activity-history` | `45 4 * * *` | Deletes organization adoption history past its retention: daily member activity and Search MCP call metadata after 400 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/**
* The adoption CSV export's authorization against real PostgreSQL and Redis: every member's
* activity is for organization admins and owners only, so a member is refused before any read
* while an admin gets one row per member.
*/
import { db } from '@sim/db'
import { member, organization, user } from '@sim/db/schema'
import { generateId } from '@sim/utils/id'
import { eq, inArray } from 'drizzle-orm'
import { NextRequest } from 'next/server'
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'

vi.hoisted(() => vi.stubEnv('USAGE_MONITORING_ENABLED', 'true'))
const sessionUser = vi.hoisted(() => ({ id: '' }))
vi.mock('@/lib/auth', async (importOriginal) => ({
...(await importOriginal<typeof import('@/lib/auth')>()),
getSession: async () => ({ user: { id: sessionUser.id }, session: { id: 'session-fixture' } }),
}))

import { GET } from '@/app/api/organizations/[id]/usage/adoption/export/route'

const organizationId = generateId()
const memberUserId = generateId()
const adminUserId = generateId()
const users = [memberUserId, adminUserId]

function exportAs(userId: string) {
sessionUser.id = userId
return GET(
new NextRequest(
`http://localhost:3000/api/organizations/${organizationId}/usage/adoption/export?preset=30d`
),
{ params: Promise.resolve({ id: organizationId }) }
)
}

describe('adoption export', () => {
beforeAll(async () => {
const now = new Date()
await db.insert(user).values(
users.map((id) => ({
id,
name: 'Export fixture',
email: `${id}@adoption-export.test`,
emailVerified: true,
createdAt: now,
updatedAt: now,
}))
)
await db
.insert(organization)
.values({ id: organizationId, name: 'Export fixture', slug: `export-${organizationId}` })
await db.insert(member).values([
{ id: generateId(), userId: memberUserId, organizationId, role: 'member' },
{ id: generateId(), userId: adminUserId, organizationId, role: 'admin' },
])
})

afterAll(async () => {
await db.delete(organization).where(eq(organization.id, organizationId))
await db.delete(user).where(inArray(user.id, users))
})

it('refuses a member who is not an admin or owner', async () => {
const response = await exportAs(memberUserId)
expect(response.status).toBe(403)
expect(response.headers.get('Content-Type')).not.toContain('text/csv')
})

it('exports every member for an admin', async () => {
const response = await exportAs(adminUserId)
expect(response.status).toBe(200)
expect(response.headers.get('Content-Type')).toContain('text/csv')
expect((await response.text()).split('\n')).toHaveLength(3)
})
})
3 changes: 3 additions & 0 deletions apps/sim/app/api/v2/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { runHeadlessCopilotLifecycle } from '@/lib/mothership/request/lifecycle/
import { requestExplicitStreamAbort } from '@/lib/mothership/request/session/explicit-abort'
import type { OrchestratorResult, StreamEvent } from '@/lib/mothership/request/types'
import { normalizeSecretMountPolicy } from '@/lib/mothership/secret-mount-policy'
import { recordMemberActivity } from '@/lib/organizations/member-activity/record'
import { CAPABILITY_RULES } from '@/lib/permission-groups/capabilities'
import {
capabilityRefusal,
Expand Down Expand Up @@ -383,6 +384,8 @@ export const POST = withRouteHandler(
req.signal.addEventListener('abort', onAbort, { once: true })
}

// Admitted and billed: the route takes only a person's own credential, so the turn is theirs.
recordMemberActivity({ userId, surface: 'agent', scope: { kind: 'workspace', workspaceId } })
const runLifecycle = (onEvent?: (event: StreamEvent) => Promise<void>) =>
runHeadlessCopilotLifecycle(requestPayload, {
userId,
Expand Down
65 changes: 65 additions & 0 deletions apps/sim/lib/billing/core/organization-adoption.integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,71 @@ describe('organization adoption', () => {
).toBe(true)
})

it('reads a window starting tomorrow as empty, with headlines ending today', () => {
const now = new Date('2026-11-28T15:00:00Z')
const tomorrow = adoptionDays(
organizationId,
{ start: new Date('2026-11-29T00:00:00Z'), end: new Date('2026-11-30T00:00:00Z') },
now
)
expect([tomorrow.from, tomorrow.to, tomorrow.asOf]).toEqual([
'2026-11-29',
'2026-11-29',
'2026-11-29',
])
})

it('keeps the day a short window inside one UTC day falls on', () => {
const short = adoptionDays(
organizationId,
{ start: new Date('2026-11-10T00:30:00Z'), end: new Date('2026-11-10T23:30:00Z') },
new Date('2026-12-15T00:00:00Z')
)
expect([short.from, short.to]).toEqual(['2026-11-10', '2026-11-11'])
})

it('runs a window ending now through today', () => {
const now = new Date('2026-11-28T15:00:00Z')
const trailing = adoptionDays(
organizationId,
{ start: new Date('2026-11-21T15:00:00Z'), end: now },
new Date(now.getTime() + 1000)
)
expect([trailing.from, trailing.to, trailing.asOf]).toEqual([
'2026-11-21',
'2026-11-29',
'2026-11-29',
])
})

it('reads a period in another time zone as the same UTC days, for counts and Search MCP alike', async () => {
const pacific = adoptionDays(
organizationId,
{ start: new Date('2026-11-01T08:00:00Z'), end: new Date('2026-11-29T08:00:00Z') },
new Date('2026-12-15T00:00:00Z')
)
expect([pacific.from, pacific.to]).toEqual([days.from, days.to])
const late = generateId()
await db.insert(organizationSearchMcpInvocation).values({
id: late,
organizationId,
userId: ben,
authKind: 'personal_api_key',
toolName: 'search',
outcome: 'success',
durationMs: 5,
createdAt: new Date('2026-11-29T05:00:00Z'),
})
try {
const tools = await readAdoptionBreakdown(pacific, 'mcp_tool')
expect(tools.rows.find((row) => row.id === 'search')?.total).toBe(2)
} finally {
await db
.delete(organizationSearchMcpInvocation)
.where(eq(organizationSearchMcpInvocation.id, late))
}
})

it('lists every current member, inactive ones included, most days active first', async () => {
const page = await readAdoptionMemberPage(days, 'days', 0)

Expand Down
40 changes: 26 additions & 14 deletions apps/sim/lib/billing/core/organization-adoption.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,36 +24,48 @@ const BREAKDOWN_MAX_ROWS = 500
/** The longest export, in members; an organization larger than this exports its most active. */
export const ADOPTION_EXPORT_MAX_ROWS = 10_000

/** A window as the UTC calendar days the daily counts are keyed by: `[from, to)`. */
/**
* A window as the UTC calendar days every adoption read is keyed by, `[from, to)`: the daily
* counts and the Search MCP log alike, so the two never disagree about a period's edges.
*/
export interface AdoptionDays {
organizationId: string
from: string
to: string
/** The exclusive day the headline 1/7/28-day counts end at: the window's end, or today. */
asOf: string
/** The instant the window started, for the Search MCP log, which keeps exact times. */
start: Date
end: Date
}

function utcDay(instant: Date): string {
return instant.toISOString().slice(0, 10)
}

/** The UTC days a window touches, ending no later than today. */
/**
* The UTC days of a window: from the day its start falls on to the day its end falls on
* (exclusive), or through today when the window runs past now. A period in another time zone
* therefore keeps its day count rather than gaining a partial UTC day at either edge.
*/
export function adoptionDays(
organizationId: string,
window: { start: Date; end: Date },
now = new Date()
): AdoptionDays {
const end = window.end < now ? window.end : now
/** A window that starts after today is empty, not a window that runs backwards. */
const asOf = utcDay(new Date(end.getTime() - 1 + DAY_MS))
if (window.start >= end) {
const today = utcDay(end)
return { organizationId, from: today, to: today, asOf, start: end, end }
const today = utcDay(now)
// A window ending anywhere in today, as a trailing preset ending now does, runs through today.
const to =
window.end > new Date(`${today}T00:00:00.000Z`)
? utcDay(new Date(now.getTime() + DAY_MS))
: utcDay(window.end)
const from = utcDay(window.start)
// A window that starts after it ends or after now is empty; any other
// window keeps at least the day it starts on, as a short one inside one UTC day would not.
if (window.start >= window.end || window.start >= now || from > to)
return { organizationId, from: to, to, asOf: to }
if (from === to) {
const next = utcDay(new Date(new Date(`${from}T00:00:00.000Z`).getTime() + DAY_MS))
return { organizationId, from, to: next, asOf: next }
}
return { organizationId, from: utcDay(window.start), to: asOf, asOf, start: window.start, end }
return { organizationId, from, to, asOf: to }
}

function dayBefore(day: string, days: number): string {
Expand Down Expand Up @@ -250,8 +262,8 @@ export async function readAdoptionBreakdown(
FROM ${organizationSearchMcpInvocation} i
JOIN ${member} m ON m.user_id = i.user_id AND m.organization_id = i.organization_id
WHERE i.organization_id = ${days.organizationId}
AND i.created_at >= ${days.start.toISOString()}::timestamptz
AND i.created_at < ${days.end.toISOString()}::timestamptz
AND i.created_at >= (${days.from}::timestamp AT TIME ZONE 'UTC')
AND i.created_at < (${days.to}::timestamp AT TIME ZONE 'UTC')
GROUP BY 1
ORDER BY total DESC, label ASC
LIMIT ${BREAKDOWN_MAX_ROWS + 1}`)
Expand Down
15 changes: 6 additions & 9 deletions apps/sim/lib/execution/preprocessing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@ 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 {
isPersonWorkflowRun,
recordMemberActivity,
} from '@/lib/organizations/member-activity/record'
import type { CoreTriggerType } from '@/stores/logs/filters/types'

const logger = createLogger('ExecutionPreprocessing')
Expand Down Expand Up @@ -1109,14 +1112,8 @@ 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({
if (isPersonWorkflowRun(useAuthenticatedUserAsActor, triggerType) && userId && workspaceId) {
recordMemberActivity({
userId,
surface: 'workflows',
scope: { kind: 'workspace', workspaceId },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export async function runSlackSearchAssistant(
await checkAccess()
await persistSlackSearchQuestion(chat.id, userId, messageId, job.message.query)
questionPersisted = true
void recordMemberActivity({
recordMemberActivity({
userId,
surface: 'slack',
scope: { kind: 'organization', organizationId: installation.organizationId },
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/lib/knowledge/mcp/activity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export async function recordOrganizationSearchMcpActivity(
})
}
if (input.userId && input.outcome !== 'rate_limited') {
await recordMemberActivity({
recordMemberActivity({
userId: input.userId,
surface: 'search_mcp',
scope: { kind: 'organization', organizationId: input.organizationId },
Expand Down
7 changes: 3 additions & 4 deletions apps/sim/lib/mothership/chat/post.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +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 { chatTurnSurface, 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 @@ -1315,10 +1315,9 @@ export async function handleUnifiedChatPost(req: NextRequest) {
branch.kind === 'organization'
? { kind: 'organization', organizationId: branch.organizationId }
: { kind: 'workspace', workspaceId: branch.workspaceId }
void recordMemberActivity({
recordMemberActivity({
userId: authenticatedUserId,
surface:
branch.kind === 'organization' && body.mode === 'assistant' ? 'assistant' : 'agent',
surface: chatTurnSurface(branch.kind === 'organization', body.mode),
scope: activityScope,
})
}
Expand Down
Loading
Loading