feat: implement admin panel for managing builds with retry functionality

This commit is contained in:
Ben Allfree
2025-12-01 11:12:33 -08:00
parent c8c4588310
commit 8cba89a9e0
8 changed files with 499 additions and 13 deletions
+4
View File
@@ -9,8 +9,10 @@
*/
import type * as actions from "../actions.js";
import type * as admin from "../admin.js";
import type * as auth from "../auth.js";
import type * as builds from "../builds.js";
import type * as helpers from "../helpers.js";
import type * as http from "../http.js";
import type * as lib_r2 from "../lib/r2.js";
import type * as plugins from "../plugins.js";
@@ -24,8 +26,10 @@ import type {
declare const fullApi: ApiFromModules<{
actions: typeof actions;
admin: typeof admin;
auth: typeof auth;
builds: typeof builds;
helpers: typeof helpers;
http: typeof http;
"lib/r2": typeof lib_r2;
plugins: typeof plugins;
+77
View File
@@ -0,0 +1,77 @@
import { getAuthUserId } from '@convex-dev/auth/server'
import { v } from 'convex/values'
import { api } from './_generated/api'
import { query } from './_generated/server'
import { computeFlagsFromConfig } from './builds'
import { adminMutation, adminQuery } from './helpers'
export const isAdmin = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx)
if (!userId) return false
const userSettings = await ctx.db
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', userId))
.first()
return userSettings?.isAdmin === true
},
})
export const listFailedBuilds = adminQuery({
args: {},
handler: async (ctx) => {
const failedBuilds = await ctx.db
.query('builds')
.filter((q) => q.eq(q.field('status'), 'failure'))
.order('desc')
.collect()
return failedBuilds
},
})
export const listAllBuilds = adminQuery({
args: {},
handler: async (ctx) => {
const allBuilds = await ctx.db.query('builds').order('desc').collect()
return allBuilds
},
})
export const retryBuild = adminMutation({
args: {
buildId: v.id('builds'),
},
handler: async (ctx, args) => {
const build = await ctx.db.get(args.buildId)
if (!build) {
throw new Error('Build not found')
}
// Compute flags from config
const flags = computeFlagsFromConfig(build.config)
// Dispatch new GitHub build with same config
// This will use the latest YAML from the branch
await ctx.scheduler.runAfter(0, api.actions.dispatchGithubBuild, {
target: build.config.target,
version: build.config.version,
buildId: args.buildId,
flags,
buildHash: build.buildHash,
plugins: build.config.pluginsEnabled ?? [],
})
// Update build status to queued
await ctx.db.patch(args.buildId, {
status: 'queued',
updatedAt: Date.now(),
})
return { success: true }
},
})
+13
View File
@@ -252,6 +252,7 @@ export const updateBuildStatus = internalMutation({
artifactPath?: string
sourceUrl?: string
githubRunId?: number
githubRunIdHistory?: number[]
} = {
status: args.status,
}
@@ -272,10 +273,22 @@ export const updateBuildStatus = internalMutation({
}
// Set githubRunId if provided
// When a new run ID comes in, move the previous one to history
const existingHistory = [...new Set(build.githubRunIdHistory || [])]
if (args.githubRunId !== undefined) {
const existingRunId = build.githubRunId
// Only update if the run ID is actually changing
if (existingRunId !== undefined && existingRunId !== args.githubRunId) {
// Prepend existing run ID to history array, avoiding duplicates
existingHistory.unshift(existingRunId)
}
updateData.githubRunId = args.githubRunId
}
updateData.githubRunIdHistory = [...new Set(existingHistory)].filter(
(id) => id !== args.githubRunId
)
await ctx.db.patch(args.buildId, updateData)
},
})
+118
View File
@@ -0,0 +1,118 @@
import { getAuthUserId } from '@convex-dev/auth/server'
import { ConvexError, v } from 'convex/values'
import {
customAction,
customCtx,
customMutation,
customQuery,
} from 'convex-helpers/server/customFunctions'
import { api } from './_generated/api'
import { action, mutation, query } from './_generated/server'
export const authQuery = customQuery(
query,
customCtx(async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (identity === null) {
throw new ConvexError('Not authenticated!')
}
return {}
})
)
export const authMutation = customMutation(
mutation,
customCtx(async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (identity === null) {
throw new ConvexError('Not authenticated!')
}
return {}
})
)
export const authAction = customAction(
action,
customCtx(async (ctx) => {
const identity = await ctx.auth.getUserIdentity()
if (identity === null) {
throw new ConvexError('Not authenticated!')
}
return {}
})
)
export const adminQuery = customQuery(
query,
customCtx(async (ctx) => {
const userId = await getAuthUserId(ctx)
if (!userId) {
throw new ConvexError('Not authenticated!')
}
const userSettings = await ctx.db
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', userId))
.first()
if (userSettings?.isAdmin !== true) {
throw new ConvexError('Unauthorized: Admin access required')
}
return {}
})
)
export const adminMutation = customMutation(
mutation,
customCtx(async (ctx) => {
const userId = await getAuthUserId(ctx)
if (!userId) {
throw new ConvexError('Not authenticated!')
}
const userSettings = await ctx.db
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', userId))
.first()
if (userSettings?.isAdmin !== true) {
throw new ConvexError('Unauthorized: Admin access required')
}
return {}
})
)
export const adminAction = customAction(
action,
customCtx(async (ctx) => {
const userId = await getAuthUserId(ctx)
if (!userId) {
throw new ConvexError('Not authenticated!')
}
// Actions can't access ctx.db directly, so we need to use a query
const isAdmin = await ctx.runQuery(api.helpers.checkIsAdmin, {
userId,
})
if (!isAdmin) {
throw new ConvexError('Unauthorized: Admin access required')
}
return {}
})
)
// Internal query to check if user is admin (used by action middleware)
export const checkIsAdmin = query({
args: { userId: v.id('users') },
handler: async (ctx, args) => {
const userSettings = await ctx.db
.query('userSettings')
.withIndex('by_user', (q) => q.eq('userId', args.userId))
.first()
return userSettings?.isAdmin === true
},
})
+7
View File
@@ -32,6 +32,7 @@ export const buildFields = {
artifactPath: v.optional(v.string()),
sourceUrl: v.optional(v.string()),
githubRunId: v.optional(v.number()),
githubRunIdHistory: v.optional(v.array(v.number())),
}
export const pluginFields = {
@@ -40,11 +41,17 @@ export const pluginFields = {
updatedAt: v.number(),
}
export const userSettingsFields = {
userId: v.id('users'),
isAdmin: v.boolean(),
}
export const schema = defineSchema({
...authTables,
profiles: defineTable(profileFields),
builds: defineTable(buildFields),
plugins: defineTable(pluginFields).index('by_slug', ['slug']),
userSettings: defineTable(userSettingsFields).index('by_user', ['userId']),
})
export type ProfilesDoc = Doc<'profiles'>
+2
View File
@@ -9,6 +9,7 @@ import {
} from 'react-router-dom'
import { Toaster } from '@/components/ui/sonner'
import Navbar from './components/Navbar'
import Admin from './pages/Admin'
import BuildNew from './pages/BuildNew'
import BuildProgress from './pages/BuildProgress'
import Dashboard from './pages/Dashboard'
@@ -51,6 +52,7 @@ function App() {
<Routes>
<Route path="/" element={<LandingPage />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/admin" element={<Admin />} />
<Route path="/builds/new/:buildHash" element={<BuildNew />} />
<Route path="/builds/new" element={<BuildNew />} />
<Route path="/builds/:buildHash" element={<BuildProgress />} />
+57 -13
View File
@@ -1,23 +1,67 @@
import { useAuthActions } from '@convex-dev/auth/react'
import { Authenticated, Unauthenticated, useQuery } from 'convex/react'
import { Link } from 'react-router-dom'
import { Button } from '@/components/ui/button'
import { api } from '../../convex/_generated/api'
export default function Navbar() {
const { signIn, signOut } = useAuthActions()
const isAdmin = useQuery(api.admin.isAdmin)
return (
<nav className="border-b border-slate-800 bg-slate-950">
<div className="max-w-7xl mx-auto px-8 py-4">
<div className="flex items-center justify-between">
<Link
to="/"
className="flex items-center gap-3 hover:opacity-80 transition-opacity"
>
<img
src="/favicon-96x96.png"
alt="Mesh Forge logo"
className="h-10 w-10 rounded-lg"
/>
<span className="text-2xl font-bold bg-gradient-to-r from-cyan-400 to-blue-600 bg-clip-text text-transparent">
Mesh Forge
</span>
</Link>
<div className="flex items-center gap-8">
<Link
to="/"
className="flex items-center gap-3 hover:opacity-80 transition-opacity"
>
<img
src="/favicon-96x96.png"
alt="Mesh Forge logo"
className="h-10 w-10 rounded-lg"
/>
<span className="text-2xl font-bold bg-gradient-to-r from-cyan-400 to-blue-600 bg-clip-text text-transparent">
Mesh Forge
</span>
</Link>
<div className="flex items-center gap-4">
<Authenticated>
<Link
to="/dashboard"
className="text-slate-300 hover:text-white transition-colors"
>
Dashboard
</Link>
{isAdmin && (
<Link
to="/admin"
className="text-slate-300 hover:text-white transition-colors"
>
Admin
</Link>
)}
</Authenticated>
</div>
</div>
<div className="flex items-center gap-4">
<Unauthenticated>
<Button
onClick={() =>
signIn('google', { redirectTo: window.location.href })
}
className="bg-white text-slate-900 hover:bg-slate-200"
>
Sign in
</Button>
</Unauthenticated>
<Authenticated>
<Button variant="outline" onClick={() => signOut()}>
Sign Out
</Button>
</Authenticated>
</div>
</div>
</div>
</nav>
+221
View File
@@ -0,0 +1,221 @@
import { useMutation, useQuery } from 'convex/react'
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { api } from '../../convex/_generated/api'
import type { Id } from '../../convex/_generated/dataModel'
type FilterType = 'all' | 'failed'
export default function Admin() {
const navigate = useNavigate()
const [filter, setFilter] = useState<FilterType>('failed')
const isAdmin = useQuery(api.admin.isAdmin)
const failedBuilds = useQuery(api.admin.listFailedBuilds)
const allBuilds = useQuery(api.admin.listAllBuilds)
const retryBuild = useMutation(api.admin.retryBuild)
const builds = filter === 'failed' ? failedBuilds : allBuilds
// Show loading state
if (isAdmin === undefined) {
return (
<div className="min-h-screen bg-slate-950 text-white flex items-center justify-center">
<div className="text-slate-400">Loading...</div>
</div>
)
}
// Redirect if not admin
if (isAdmin === false) {
return (
<div className="min-h-screen bg-slate-950 text-white flex items-center justify-center">
<div className="text-center">
<h1 className="text-2xl font-bold mb-4">Access Denied</h1>
<p className="text-slate-400 mb-4">
You must be an admin to access this page.
</p>
<Button onClick={() => navigate('/')}>Go Home</Button>
</div>
</div>
)
}
const handleRetry = async (buildId: Id<'builds'>) => {
try {
await retryBuild({ buildId })
toast.success('Build retry initiated', {
description: 'The build has been queued with the latest YAML.',
})
} catch (error) {
toast.error('Failed to retry build', {
description: String(error),
})
}
}
const formatDate = (timestamp: number) => {
return new Date(timestamp).toLocaleString()
}
const getStatusBadge = (status: string) => {
const statusConfig = {
success: {
bg: 'bg-green-500/20',
text: 'text-green-400',
label: 'Success',
},
failure: { bg: 'bg-red-500/20', text: 'text-red-400', label: 'Failed' },
queued: {
bg: 'bg-yellow-500/20',
text: 'text-yellow-400',
label: 'Queued',
},
}
const config = statusConfig[status as keyof typeof statusConfig] || {
bg: 'bg-slate-500/20',
text: 'text-slate-400',
label: status,
}
return (
<span className={`px-2 py-1 ${config.bg} ${config.text} rounded text-sm`}>
{config.label}
</span>
)
}
return (
<div className="min-h-screen bg-slate-950 text-white p-8">
<header className="mb-8">
<h1 className="text-3xl font-bold mb-2">Admin - Builds</h1>
<p className="text-slate-400 mb-4">
View and manage builds. Retry failed builds with the latest GitHub
Actions workflow YAML.
</p>
<div className="flex gap-2">
<Button
variant={filter === 'all' ? 'default' : 'outline'}
onClick={() => setFilter('all')}
className={filter === 'all' ? 'bg-cyan-600 hover:bg-cyan-700' : ''}
>
All Builds
</Button>
<Button
variant={filter === 'failed' ? 'default' : 'outline'}
onClick={() => setFilter('failed')}
className={
filter === 'failed' ? 'bg-cyan-600 hover:bg-cyan-700' : ''
}
>
Failed Builds
</Button>
</div>
</header>
<main>
{builds === undefined ? (
<div className="text-center text-slate-400 py-12">
Loading builds...
</div>
) : builds.length === 0 ? (
<div className="text-center text-slate-400 py-12">
No {filter === 'failed' ? 'failed ' : ''}builds found.
</div>
) : (
<div className="space-y-4">
{builds.map((build) => (
<div
key={build._id}
className="bg-slate-900 border border-slate-800 rounded-lg p-6"
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-4 mb-2">
<h3 className="text-lg font-semibold">
Build:{' '}
<Link
to={`/builds/${build.buildHash}`}
className="text-cyan-400 hover:text-cyan-300 underline"
>
{build.buildHash.substring(0, 8)}
</Link>
</h3>
{getStatusBadge(build.status)}
</div>
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm text-slate-300">
<div>
<span className="text-slate-500">Target:</span>{' '}
<span className="font-mono">{build.config.target}</span>
</div>
<div>
<span className="text-slate-500">Version:</span>{' '}
<span className="font-mono">
{build.config.version}
</span>
</div>
<div>
<span className="text-slate-500">
{build.completedAt ? 'Completed' : 'Started'}:
</span>{' '}
{build.completedAt
? formatDate(build.completedAt)
: build.startedAt
? formatDate(build.startedAt)
: 'Unknown'}
</div>
<div>
<span className="text-slate-500">Run ID:</span>{' '}
{build.githubRunId ? (
<a
href={`https://github.com/MeshEnvy/configurable-web-flasher/actions/runs/${build.githubRunId}`}
target="_blank"
rel="noopener noreferrer"
className="text-cyan-400 hover:text-cyan-300 underline"
>
{build.githubRunId}
</a>
) : (
'N/A'
)}
</div>
</div>
{build.githubRunIdHistory &&
build.githubRunIdHistory.length > 0 && (
<div className="mt-2 text-xs text-slate-500">
Previous runs:{' '}
{build.githubRunIdHistory.map((id, idx) => (
<span key={id}>
<a
href={`https://github.com/MeshEnvy/configurable-web-flasher/actions/runs/${id}`}
target="_blank"
rel="noopener noreferrer"
className="text-cyan-400 hover:text-cyan-300 underline"
>
{id}
</a>
{idx <
(build.githubRunIdHistory?.length ?? 0) - 1 &&
', '}
</span>
))}
</div>
)}
</div>
<div className="ml-4">
<Button
onClick={() => handleRetry(build._id)}
className="bg-cyan-600 hover:bg-cyan-700"
>
Re-run Build
</Button>
</div>
</div>
</div>
))}
</div>
)}
</main>
</div>
)
}