Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
import { waitUntil } from "cloudflare:workers";
import { ActivationRepository } from "@/server/features/activation/repositories/ActivationRepository";
import { captureServerEvent } from "@/server/lib/posthog";
// Orgs whose activation milestones are already recorded (or in flight) in
// this isolate. Only *first* timestamps matter, so after one successful write
// these hot paths (every API-key /mcp request, every external tool call)
// never touch the DB again for that org.
const recordedAuthorizedOrgs = new Set<string>();
const recordedToolCallOrgs = new Set<string>();
/**
* Milestone writes for the dashboard's MCP activation card. Both are awaited
* inline by their callers (not waitUntil) so the upsert runs inside the
* request's DB client scope, and both swallow errors: activation tracking
* must never fail an OAuth flow or a tool call.
*/
export async function recordMcpAuthorized(
organizationId: string,
): Promise<void> {
if (recordedAuthorizedOrgs.has(organizationId)) return;
recordedAuthorizedOrgs.add(organizationId);
try {
await ActivationRepository.recordFirstMcpAuthorized(organizationId);
} catch (error) {
// Allow a retry on a later call rather than losing the milestone.
recordedAuthorizedOrgs.delete(organizationId);
console.error("activation: recordMcpAuthorized failed", error);
}
}
export async function recordExternalMcpToolCall(
organizationId: string,
): Promise<void> {
if (recordedToolCallOrgs.has(organizationId)) return;
recordedToolCallOrgs.add(organizationId);
try {
await ActivationRepository.recordFirstMcpToolCall(organizationId);
} catch (error) {
// Allow a retry on a later call rather than losing the milestone.
recordedToolCallOrgs.delete(organizationId);
console.error("activation: recordExternalMcpToolCall failed", error);
}
}
/**
* An agent's first connection or first project finishes the user's
* onboarding. Reports the completion only from the call that made it.
* Best-effort like the milestones above: the agent's action already worked.
*/
export async function completeOnboardingFromAgent(
user: { userId: string; organizationId: string },
via: "agent_connect" | "agent_project",
): Promise<void> {
const completed = await ActivationRepository.markOnboardingCompleted(
user.userId,
user.organizationId,
).catch((error: unknown) => {
console.error(`activation: onboarding completion (${via}) failed`, error);
return false;
});
if (!completed) return;
waitUntil(
captureServerEvent({
distinctId: user.userId,
event: "onboarding:completed",
organizationId: user.organizationId,
properties: { via },
}),
);
}