-
Notifications
You must be signed in to change notification settings - Fork 37
feat(admin): add safety identifier backfill panel #1863
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
08c03ac
feat(admin): add safety identifier backfill panel
kilo-code-bot[bot] b42b00a
feat(admin): show Vercel Downstream Safety Identifier in user admin UI
kilo-code-bot[bot] 49d9b4a
refactor(admin): merge safety identifier backfill into single API call
kilo-code-bot[bot] d36fcfa
refactor(admin): single query for safety identifier backfill
kilo-code-bot[bot] c6ae0e8
Merge commit 'b42b00abc542298753d2ec74c58a4a1a6cb3df5a' into feat/adm…
chrarnoldus dd8e1fc
Merge branch 'main' into feat/admin-safety-identifier-backfill
chrarnoldus f05f6d3
fmt
chrarnoldus 2394b56
Delete obsolete script
chrarnoldus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import { NextResponse } from 'next/server'; | ||
| import { getUserFromAuth } from '@/lib/user.server'; | ||
| import { db } from '@/lib/drizzle'; | ||
| import { kilocode_users } from '@kilocode/db'; | ||
| import { | ||
| generateOpenRouterUpstreamSafetyIdentifier, | ||
| generateVercelDownstreamSafetyIdentifier, | ||
| } from '@/lib/providerHash'; | ||
| import { isNull, count, or, desc, eq } from 'drizzle-orm'; | ||
|
|
||
| const missingEither = or( | ||
| isNull(kilocode_users.openrouter_upstream_safety_identifier), | ||
| isNull(kilocode_users.vercel_downstream_safety_identifier) | ||
| ); | ||
|
|
||
| export type SafetyIdentifierCountsResponse = { | ||
| missing: number; | ||
| }; | ||
|
|
||
| export type BackfillBatchResponse = { | ||
| processed: number; | ||
| remaining: boolean; | ||
| }; | ||
|
|
||
| export async function GET(): Promise< | ||
| NextResponse<SafetyIdentifierCountsResponse | { error: string }> | ||
| > { | ||
| const { authFailedResponse } = await getUserFromAuth({ adminOnly: true }); | ||
| if (authFailedResponse) return authFailedResponse; | ||
|
|
||
| const [result] = await db.select({ count: count() }).from(kilocode_users).where(missingEither); | ||
|
|
||
| return NextResponse.json({ missing: result?.count ?? 0 }); | ||
| } | ||
|
|
||
| export async function POST(): Promise<NextResponse<BackfillBatchResponse | { error: string }>> { | ||
| const { authFailedResponse } = await getUserFromAuth({ adminOnly: true }); | ||
| if (authFailedResponse) return authFailedResponse; | ||
|
|
||
| const processed = await db.transaction(async tran => { | ||
| const rows = await tran | ||
| .select({ id: kilocode_users.id }) | ||
| .from(kilocode_users) | ||
| .where(missingEither) | ||
| .orderBy(desc(kilocode_users.created_at)) | ||
| .limit(1000); | ||
|
|
||
| for (const user of rows) { | ||
| const openrouter_upstream_safety_identifier = generateOpenRouterUpstreamSafetyIdentifier( | ||
|
chrarnoldus marked this conversation as resolved.
|
||
| user.id | ||
| ); | ||
| if (openrouter_upstream_safety_identifier === null) { | ||
| return null; | ||
| } | ||
| await tran | ||
| .update(kilocode_users) | ||
| .set({ | ||
| openrouter_upstream_safety_identifier, | ||
| vercel_downstream_safety_identifier: generateVercelDownstreamSafetyIdentifier(user.id), | ||
| }) | ||
| .where(eq(kilocode_users.id, user.id)) | ||
| .execute(); | ||
| } | ||
|
|
||
| return rows.length; | ||
| }); | ||
|
|
||
| if (processed === null) { | ||
| return NextResponse.json( | ||
| { error: 'OPENROUTER_ORG_ID is not configured on this server' }, | ||
| { status: 500 } | ||
| ); | ||
| } | ||
|
|
||
| return NextResponse.json({ processed, remaining: processed === 1000 }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| 'use client'; | ||
|
|
||
| import { useState } from 'react'; | ||
| import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; | ||
| import { Button } from '@/components/ui/button'; | ||
| import { Alert, AlertDescription } from '@/components/ui/alert'; | ||
| import { Badge } from '@/components/ui/badge'; | ||
| import type { | ||
| SafetyIdentifierCountsResponse, | ||
| BackfillBatchResponse, | ||
| } from '../api/safety-identifiers/route'; | ||
|
|
||
| type BatchLog = { | ||
| processed: number; | ||
| timestamp: Date; | ||
| }; | ||
|
|
||
| export function SafetyIdentifiersBackfill() { | ||
| const [logs, setLogs] = useState<BatchLog[]>([]); | ||
| const queryClient = useQueryClient(); | ||
|
|
||
| const { data: counts, isLoading } = useQuery<SafetyIdentifierCountsResponse>({ | ||
| queryKey: ['safety-identifier-counts'], | ||
| queryFn: async () => { | ||
| const res = await fetch('/admin/api/safety-identifiers'); | ||
| return res.json() as Promise<SafetyIdentifierCountsResponse>; | ||
| }, | ||
| refetchInterval: false, | ||
| }); | ||
|
|
||
| const mutation = useMutation<BackfillBatchResponse, Error>({ | ||
| mutationFn: async () => { | ||
| const res = await fetch('/admin/api/safety-identifiers', { method: 'POST' }); | ||
| if (!res.ok) { | ||
| const body = (await res.json()) as { error?: string }; | ||
| throw new Error(body.error ?? `HTTP ${res.status}`); | ||
| } | ||
| return res.json() as Promise<BackfillBatchResponse>; | ||
| }, | ||
| onSuccess: data => { | ||
| setLogs(prev => [{ processed: data.processed, timestamp: new Date() }, ...prev]); | ||
| void queryClient.invalidateQueries({ queryKey: ['safety-identifier-counts'] }); | ||
| }, | ||
| }); | ||
|
|
||
| const isDone = counts?.missing === 0; | ||
|
|
||
| return ( | ||
| <div className="space-y-6"> | ||
| <p className="text-muted-foreground text-sm"> | ||
| Backfill safety identifiers for users missing either field. Each click processes up to 1 000 | ||
| users. Click repeatedly until the counter reaches zero. | ||
| </p> | ||
|
|
||
| <div className="bg-background rounded-lg border p-6 space-y-4"> | ||
| <div className="flex items-center gap-3"> | ||
| <span className="font-medium">Users missing a safety identifier</span> | ||
| {isLoading ? ( | ||
| <Badge variant="secondary">Loading…</Badge> | ||
| ) : isDone ? ( | ||
| <Badge variant="default" className="bg-green-600"> | ||
| All filled | ||
| </Badge> | ||
| ) : ( | ||
| <Badge variant="destructive">{(counts?.missing ?? 0).toLocaleString()} missing</Badge> | ||
| )} | ||
| </div> | ||
|
|
||
| {mutation.isError && ( | ||
| <Alert variant="destructive"> | ||
| <AlertDescription>{mutation.error.message}</AlertDescription> | ||
| </Alert> | ||
| )} | ||
|
|
||
| <Button | ||
| onClick={() => mutation.mutate()} | ||
| disabled={isLoading || isDone || mutation.isPending} | ||
| variant={isDone ? 'outline' : 'default'} | ||
| > | ||
| {mutation.isPending ? 'Backfilling…' : isDone ? 'Nothing to do' : 'Backfill next 1 000'} | ||
| </Button> | ||
| </div> | ||
|
|
||
| {logs.length > 0 && ( | ||
| <div className="bg-background rounded-lg border p-4 space-y-2"> | ||
| <h4 className="text-sm font-medium">Batch log</h4> | ||
| <div className="space-y-1 font-mono text-xs"> | ||
| {logs.map((log, i) => ( | ||
| <div key={i} className="text-muted-foreground flex gap-2"> | ||
| <span className="shrink-0">{log.timestamp.toLocaleTimeString()}</span> | ||
| <span>processed {log.processed.toLocaleString()} users</span> | ||
| </div> | ||
| ))} | ||
| </div> | ||
| </div> | ||
| )} | ||
| </div> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| import { SafetyIdentifiersBackfill } from '../components/SafetyIdentifiersBackfill'; | ||
| import AdminPage from '../components/AdminPage'; | ||
| import { BreadcrumbItem, BreadcrumbPage } from '@/components/ui/breadcrumb'; | ||
|
|
||
| const breadcrumbs = ( | ||
| <> | ||
| <BreadcrumbItem> | ||
| <BreadcrumbPage>Safety Identifiers</BreadcrumbPage> | ||
| </BreadcrumbItem> | ||
| </> | ||
| ); | ||
|
|
||
| export default function SafetyIdentifiersPage() { | ||
| return ( | ||
| <AdminPage breadcrumbs={breadcrumbs}> | ||
| <div className="flex w-full flex-col gap-y-4"> | ||
| <div className="flex items-center justify-between"> | ||
| <h2 className="text-2xl font-bold">Safety Identifier Backfill</h2> | ||
| </div> | ||
| <SafetyIdentifiersBackfill /> | ||
| </div> | ||
| </AdminPage> | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.