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
3 changes: 0 additions & 3 deletions apps/web/src/app/admin/api/abuse/blacklisted-domains/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,8 @@ export async function GET() {
try {
const BLACKLIST_DOMAINS = await getBlacklistedDomains();

// Get counts for each blacklisted domain
const domainCounts = await Promise.all(
BLACKLIST_DOMAINS.map(async domain => {
// Build conditions for both @domain and .domain patterns
const conditions = or(
sql`lower(${kilocode_users.google_user_email}) LIKE ${`%@${domain.toLowerCase()}`}`,
sql`lower(${kilocode_users.google_user_email}) LIKE ${`%.${domain.toLowerCase()}`}`
Expand All @@ -32,7 +30,6 @@ export async function GET() {
})
);

// Sort by blocked count descending
domainCounts.sort((a, b) => b.blockedCount - a.blockedCount);

return NextResponse.json({
Expand Down
3 changes: 0 additions & 3 deletions apps/web/src/app/admin/api/account-deduplication/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@ export async function GET(
const totalPages = Math.max(1, Math.ceil(total / limit));
const offset = (page - 1) * limit;

// Get the paginated set of duplicate normalized_email values
const duplicateEmailRows = await db
.select({ normalized_email: kilocode_users.normalized_email })
.from(kilocode_users)
Expand All @@ -84,7 +83,6 @@ export async function GET(
.map(row => row.normalized_email)
.filter((e): e is string => e !== null);

// Fetch all users for those normalized emails
const users = await db
.select({
id: kilocode_users.id,
Expand All @@ -101,7 +99,6 @@ export async function GET(
.where(inArray(kilocode_users.normalized_email, emailValues))
.orderBy(kilocode_users.normalized_email, kilocode_users.created_at);

// Group users by normalized_email
const groupMap = new Map<string, DuplicateUser[]>();
for (const user of users) {
const key = user.normalized_email;
Expand Down
2 changes: 0 additions & 2 deletions apps/web/src/app/admin/api/alerting/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ export function useDeleteAlertingConfig() {
);
}

// --- TTFB alerting hooks ---

export function useTtfbAlertingConfigs() {
const trpc = useTRPC();
return useQuery(trpc.admin.alerting.listTtfbConfigs.queryOptions());
Expand Down
10 changes: 0 additions & 10 deletions apps/web/src/app/admin/api/slack-bot/stats/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,15 +95,13 @@ export async function GET(
const startDate = new Date();
startDate.setDate(startDate.getDate() - days);

// Helper function to safely convert BigInt to number
const bigIntToNumber = (value: unknown): number => {
if (value === null || value === undefined) return 0;
if (typeof value === 'bigint') return Number(value);
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value);
return Number(value) || 0;
};

// Overview stats
const overviewResult = await db
.select({
total_requests: sql<number>`COUNT(*)`,
Expand All @@ -118,23 +116,20 @@ export async function GET(

const overviewStats = overviewResult[0];

// Requests in last 24h
const last24hResult = await db
.select({
count: sql<number>`COUNT(*)`,
})
.from(slack_bot_requests)
.where(sql`${slack_bot_requests.created_at} >= NOW() - INTERVAL '24 hours'`);

// Requests in last 7 days
const last7dResult = await db
.select({
count: sql<number>`COUNT(*)`,
})
.from(slack_bot_requests)
.where(sql`${slack_bot_requests.created_at} >= NOW() - INTERVAL '7 days'`);

// Weekly Active Users (WAU) - rolling 7-day window
const wauResult = await db
.select({
count: sql<number>`COUNT(DISTINCT ${slack_bot_requests.slack_user_id})`,
Expand All @@ -160,7 +155,6 @@ export async function GET(
weeklyActiveUsers: bigIntToNumber(wauResult[0]?.count),
};

// Daily stats for the chart
const dailyStatsResult = await db
.select({
date: sql<string>`DATE(${slack_bot_requests.created_at})`,
Expand All @@ -182,7 +176,6 @@ export async function GET(
avgResponseTimeMs: Math.round(bigIntToNumber(row.avg_response_time_ms)),
}));

// Usage by organization
const usageByOrgResult = await db
.select({
organization_id: slack_bot_requests.owned_by_organization_id,
Expand Down Expand Up @@ -210,7 +203,6 @@ export async function GET(
lastRequestAt: row.last_request_at || '',
}));

// Usage by Slack user
const usageByUserResult = await db
.select({
slack_user_id: slack_bot_requests.slack_user_id,
Expand Down Expand Up @@ -240,7 +232,6 @@ export async function GET(
lastRequestAt: row.last_request_at || '',
}));

// Recent requests (logs)
const recentRequestsResult = await db
.select({
id: slack_bot_requests.id,
Expand Down Expand Up @@ -282,7 +273,6 @@ export async function GET(
organizationName: row.organization_name,
}));

// Error summary
const errorSummaryResult = await db
.select({
error_message: slack_bot_requests.error_message,
Expand Down
4 changes: 0 additions & 4 deletions apps/web/src/app/admin/api/users/[id]/referrals/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,9 @@ export async function GET(

const userId = (await params).id;

// Existence check
const user = await findUserById(userId);
if (!user) return NextResponse.json({ error: 'User not found' }, { status: 404 });

// Code owned by the user (normalize unlimited to 0 if absent)
const refCode = await getReferralCodeForUser(userId);
const code =
refCode != null
Expand All @@ -49,13 +47,11 @@ export async function GET(
}
: null;

// All usages where this user is the redeemer => determines referrers
const referrerRows = await db
.select()
.from(referral_code_usages)
.where(eq(referral_code_usages.redeeming_kilo_user_id, userId));

// Usages where this user is the referrer => referred users
const redemptions = await getReferralCodeUsages(userId);
const referredIdsSet = redemptions.map(r => r.redeeming_kilo_user_id);

Expand Down
14 changes: 0 additions & 14 deletions apps/web/src/app/admin/api/users/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import { captureException } from '@sentry/nextjs';
export async function GET(
request: NextRequest
): Promise<NextResponse<{ error: string } | UsersApiResponse>> {
// Parse query parameters outside try block for error reporting
const { searchParams } = new URL(request.url);
const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '25')));
Expand All @@ -50,7 +49,6 @@ export async function GET(
const autoTopUp = searchParams.get('autoTopUp');

try {
// Check authentication and admin status
const { authFailedResponse } = await getUserFromAuth({ adminOnly: true });
if (authFailedResponse) {
return authFailedResponse;
Expand All @@ -59,13 +57,10 @@ export async function GET(
const hasValidationStytch = searchParams.get('hasValidationStytch');
const hasValidationNovelCard = searchParams.get('hasValidationNovelCard');

// Validate sortBy field
const sortField = sortableFields.includes(sortBy) ? sortBy : 'created_at';

// Build where conditions
const conditions = [];

// User-specific search condition
if (searchTerm) {
const referralCodeOwnerId = (
await db
Expand All @@ -89,9 +84,7 @@ export async function GET(
);
}

// Notes and blocked reason search condition
if (notesSearchTerm) {
// Get user IDs that have matching admin notes
const usersWithMatchingNotes = await db
.selectDistinct({ kilo_user_id: user_admin_notes.kilo_user_id })
.from(user_admin_notes)
Expand All @@ -109,7 +102,6 @@ export async function GET(
);
}

// Filter conditions
if (hasValidationStytch === 'true') {
conditions.push(eq(kilocode_users.has_validation_stytch, true));
} else if (hasValidationStytch === 'false') {
Expand All @@ -127,14 +119,12 @@ export async function GET(
conditions.push(eq(kilocode_users.has_validation_novel_card_with_hold, false));
}

// Blocked status filter
if (blockedStatus === 'blocked') {
conditions.push(isNotNull(kilocode_users.blocked_reason));
} else if (blockedStatus === 'not_blocked') {
conditions.push(isNull(kilocode_users.blocked_reason));
}

// Organization membership filter - use EXISTS subquery for performance
if (orgMembership === 'in_org') {
conditions.push(
exists(
Expand All @@ -155,7 +145,6 @@ export async function GET(
);
}

// Payment status filter
if (paymentStatus === 'paid') {
conditions.push(gt(kilocode_users.total_microdollars_acquired, 0));
} else if (paymentStatus === 'never_paid') {
Expand All @@ -167,7 +156,6 @@ export async function GET(
);
}

// Auto top-up filter
if (autoTopUp === 'enabled') {
conditions.push(eq(kilocode_users.auto_top_up_enabled, true));
} else if (autoTopUp === 'disabled') {
Expand All @@ -176,7 +164,6 @@ export async function GET(

const whereCondition = conditions.length > 0 ? and(...conditions) : undefined;

// Build order condition
const orderFunction = sortOrder === 'asc' ? asc : desc;
const orderCondition = orderFunction(kilocode_users[sortField]);

Expand Down Expand Up @@ -208,7 +195,6 @@ export async function GET(

const notesByUserId = Map.groupBy(notes, note => note.kilo_user_id);

// Calculate pagination metadata
const totalPages = Math.ceil(totalUserCount / limit);

const usersWithPaymentStatus: UserTableProps[] = await Promise.all(
Expand Down
41 changes: 0 additions & 41 deletions apps/web/src/app/admin/auto-routing/BenchmarksSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,6 @@ import { parseAdminResponse } from './admin-fetch';
import { SchedulerConfigCard } from './SchedulerConfigCard';
import { useSystemOneModelOptions } from './system-one-models';

// ---------------------------------------------------------------------------
// Pure helpers (exported for unit tests)
// ---------------------------------------------------------------------------

export function formatAccuracy(n: number): string {
return `${(n * 100).toFixed(1)}%`;
}
Expand Down Expand Up @@ -218,10 +214,6 @@ export function policyOverridesFromForm(
return Object.keys(overrides).length > 0 ? overrides : null;
}

// ---------------------------------------------------------------------------
// Model picker helpers (exported for unit tests)
// ---------------------------------------------------------------------------

/** Pins a saved model id that is absent from the eligible catalog so it stays selectable. */
export function pinnedModelFor(id: string): ModelOption {
return { id, name: id };
Expand Down Expand Up @@ -276,10 +268,6 @@ export function effortCoverageForModel(
return `${supported} · ${measured} of ${efforts.length} measured${outstanding.length > 0 ? ` · ${outstanding.join(', ')}` : ''}`;
}

// ---------------------------------------------------------------------------
// Fetch helpers
// ---------------------------------------------------------------------------

async function fetchBenchmarkConfig(router: AutoRouter) {
const response = await fetch(`/admin/api/auto-routing/benchmark-config?router=${router}`);
return parseAdminResponse(response, BenchmarkConfigResponseSchema);
Expand Down Expand Up @@ -365,10 +353,6 @@ async function fetchBenchmarkRoutingTable(router: AutoRouter) {
);
}

// ---------------------------------------------------------------------------
// Local form state type for decider model rows
// ---------------------------------------------------------------------------

type DeciderModelRow = BenchmarkPlatformModel;

function optionalNumberText(value: number | null | undefined): string {
Expand Down Expand Up @@ -500,10 +484,6 @@ export function formStateToConfig(
};
}

// ---------------------------------------------------------------------------
// Config editor sub-component
// ---------------------------------------------------------------------------

function ConfigSectionHeading({ title, description }: { title: string; description: string }) {
return (
<div className="mt-4 flex flex-col gap-0.5">
Expand Down Expand Up @@ -1165,10 +1145,6 @@ function BenchmarkConfigEditor({
);
}

// ---------------------------------------------------------------------------
// Run summaries expandable table
// ---------------------------------------------------------------------------

function RunSummariesTable({ run, id }: { run: BenchmarkRun; id: string }) {
const isDecider = run.kind === 'decider';

Expand Down Expand Up @@ -1252,10 +1228,6 @@ function RunSummariesTable({ run, id }: { run: BenchmarkRun; id: string }) {
);
}

// ---------------------------------------------------------------------------
// Runs table
// ---------------------------------------------------------------------------

function statusBadgeVariant(
status: BenchmarkRun['status']
): 'default' | 'secondary' | 'destructive' {
Expand Down Expand Up @@ -1369,10 +1341,6 @@ function BenchmarkRunsTable({ runs }: { runs: BenchmarkRun[] }) {
);
}

// ---------------------------------------------------------------------------
// Routing table view
// ---------------------------------------------------------------------------

function RoutingTableSummary({ table }: { table: BenchmarkRoutingTableResponse['table'] }) {
if (!table) return null;

Expand Down Expand Up @@ -1495,10 +1463,6 @@ export function RoutingTableView({ data }: { data: BenchmarkRoutingTableResponse
);
}

// ---------------------------------------------------------------------------
// Registry summary
// ---------------------------------------------------------------------------

const REGISTRY_STATUSES = ['pending', 'running', 'ready', 'failed'] as const;

function RegistrySummary({
Expand Down Expand Up @@ -1555,10 +1519,6 @@ function RegistrySummary({
);
}

// ---------------------------------------------------------------------------
// Main exported section component
// ---------------------------------------------------------------------------

export function RouterBenchmarksSection({ router }: { router: AutoRouter }) {
const queryClient = useQueryClient();
const [forceRerun, setForceRerun] = useState(false);
Expand Down Expand Up @@ -1612,7 +1572,6 @@ export function RouterBenchmarksSection({ router }: { router: AutoRouter }) {
queryFn: () => fetchBenchmarkRuns('all', router),
});

// Poll runs every 30s while any run is 'running'
const hasRunningRun = allRunsQuery.data?.runs.some(r => r.status === 'running') ?? false;
const refetchRuns = runsQuery.refetch;
const refetchAllRuns = allRunsQuery.refetch;
Expand Down
Loading
Loading