Milestone (a): project skeleton and OIDC login

- Next.js 16 + Tailwind + shadcn/ui skeleton
- Auth.js v5 generic OIDC (Pocket ID, PKCE) with optional group gate
- proxy.ts gates all pages and API routes
- Drizzle schema (models, files, jobs, logs, worker state) on SQLite/libsql
- Worker skeleton: migrations, interrupted-job recovery, heartbeat

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-05 15:32:52 +02:00
commit 891e496157
47 files changed
+14945

No files matched your search

+47
View File
@@ -0,0 +1,47 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { auth, signOut } from "@/auth";
import { Button } from "@/components/ui/button";
import { WorkerIndicator } from "@/components/worker-indicator";
import { getWorkerStatus } from "@/lib/worker-status";
export default async function AppLayout({ children }: LayoutProps<"/">) {
const session = await auth();
if (!session?.user) redirect("/login");
const worker = await getWorkerStatus();
return (
<div className="flex min-h-screen flex-col">
<header className="border-b">
<div className="mx-auto flex h-14 max-w-6xl items-center gap-6 px-4">
<Link href="/" className="font-semibold">
Model Manager
</Link>
<nav className="flex items-center gap-4 text-sm text-muted-foreground">
<Link href="/" className="hover:text-foreground">
Library
</Link>
</nav>
<div className="ml-auto flex items-center gap-3">
<WorkerIndicator initial={worker} />
<span className="hidden text-sm text-muted-foreground sm:inline">
{session.user.name ?? session.user.email}
</span>
<form
action={async () => {
"use server";
await signOut({ redirectTo: "/login" });
}}
>
<Button type="submit" variant="ghost" size="sm">
Sign out
</Button>
</form>
</div>
</div>
</header>
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-6">{children}</main>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
export default function LibraryPage() {
return (
<div className="flex flex-col gap-4">
<h1 className="text-xl font-semibold">Library</h1>
<Card>
<CardHeader>
<CardTitle>No models yet</CardTitle>
<CardDescription>Adding models from Hugging Face comes in the next milestone.</CardDescription>
</CardHeader>
</Card>
</div>
);
}
+3
View File
@@ -0,0 +1,3 @@
import { handlers } from "@/auth";
export const { GET, POST } = handlers;
+12
View File
@@ -0,0 +1,12 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
export const GET = withAuth(async (_req, { session }) => {
return NextResponse.json({
user: { name: session.user.name, email: session.user.email, groups: session.user.groups },
worker: await getWorkerStatus(),
});
});
+129
View File
@@ -0,0 +1,129 @@
@import "tailwindcss";
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
@theme inline {
--font-heading: var(--font-sans);
--font-sans: var(--font-sans);
--color-sidebar-ring: var(--sidebar-ring);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-chart-5: var(--chart-5);
--color-chart-4: var(--chart-4);
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
--color-destructive: var(--destructive);
--color-accent-foreground: var(--accent-foreground);
--color-accent: var(--accent);
--color-muted-foreground: var(--muted-foreground);
--color-muted: var(--muted);
--color-secondary-foreground: var(--secondary-foreground);
--color-secondary: var(--secondary);
--color-primary-foreground: var(--primary-foreground);
--color-primary: var(--primary);
--color-popover-foreground: var(--popover-foreground);
--color-popover: var(--popover);
--color-card-foreground: var(--card-foreground);
--color-card: var(--card);
--color-foreground: var(--foreground);
--color-background: var(--background);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.205 0 0);
--primary-foreground: oklch(0.985 0 0);
--secondary: oklch(0.97 0 0);
--secondary-foreground: oklch(0.205 0 0);
--muted: oklch(0.97 0 0);
--muted-foreground: oklch(0.556 0 0);
--accent: oklch(0.97 0 0);
--accent-foreground: oklch(0.205 0 0);
--destructive: oklch(0.577 0.245 27.325);
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--radius: 0.625rem;
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.205 0 0);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.97 0 0);
--sidebar-accent-foreground: oklch(0.205 0 0);
--sidebar-border: oklch(0.922 0 0);
--sidebar-ring: oklch(0.708 0 0);
}
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.922 0 0);
--primary-foreground: oklch(0.205 0 0);
--secondary: oklch(0.269 0 0);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.269 0 0);
--muted-foreground: oklch(0.708 0 0);
--accent: oklch(0.269 0 0);
--accent-foreground: oklch(0.985 0 0);
--destructive: oklch(0.704 0.191 22.216);
--border: oklch(1 0 0 / 10%);
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
--chart-5: oklch(0.269 0 0);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.488 0.243 264.376);
--sidebar-primary-foreground: oklch(0.985 0 0);
--sidebar-accent: oklch(0.269 0 0);
--sidebar-accent-foreground: oklch(0.985 0 0);
--sidebar-border: oklch(1 0 0 / 10%);
--sidebar-ring: oklch(0.556 0 0);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
html {
@apply font-sans;
}
}
+27
View File
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import "./globals.css";
import { Geist, Geist_Mono } from "next/font/google";
import { cn } from "@/lib/utils";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner";
const geist = Geist({ subsets: ["latin"], variable: "--font-sans" });
const geistMono = Geist_Mono({ subsets: ["latin"], variable: "--font-mono" });
export const metadata: Metadata = {
title: "Model Manager",
description: "Download and manage local LLMs from Hugging Face",
};
export default function RootLayout({ children }: LayoutProps<"/">) {
return (
<html lang="en" suppressHydrationWarning className={cn("font-sans", geist.variable, geistMono.variable)}>
<body className="min-h-screen bg-background text-foreground antialiased">
<ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange>
{children}
<Toaster />
</ThemeProvider>
</body>
</html>
);
}
+54
View File
@@ -0,0 +1,54 @@
import { redirect } from "next/navigation";
import { auth, OIDC_PROVIDER_ID, signIn } from "@/auth";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
const ERRORS: Record<string, string> = {
AccessDenied: "Your account is not in a group that is allowed to use this app.",
Configuration: "Login is misconfigured. Check the server logs and the OIDC_* settings.",
OAuthCallbackError: "The identity provider returned an error. Please try again.",
};
/** Only allow same-origin relative paths as post-login targets. */
function safeCallback(value: string | string[] | undefined): string {
const v = Array.isArray(value) ? value[0] : value;
return v && v.startsWith("/") && !v.startsWith("//") ? v : "/";
}
export default async function LoginPage({ searchParams }: PageProps<"/login">) {
const params = await searchParams;
const callbackUrl = safeCallback(params.callbackUrl);
if ((await auth())?.user) redirect(callbackUrl);
const errorKey = typeof params.error === "string" ? params.error : undefined;
const error = errorKey ? (ERRORS[errorKey] ?? "Login failed. Please try again.") : undefined;
return (
<main className="flex min-h-screen items-center justify-center p-4">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle className="text-lg">Model Manager</CardTitle>
<CardDescription>Sign in to manage local models.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{error && (
<p role="alert" className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</p>
)}
<form
action={async () => {
"use server";
await signIn(OIDC_PROVIDER_ID, { redirectTo: callbackUrl });
}}
>
<Button type="submit" className="w-full" size="lg">
Sign in with Pocket ID
</Button>
</form>
</CardContent>
</Card>
</main>
);
}
+64
View File
@@ -0,0 +1,64 @@
import NextAuth, { type NextAuthConfig } from "next-auth";
import { authEnv } from "@/lib/server-env";
declare module "next-auth" {
interface Session {
user: {
name?: string | null;
email?: string | null;
image?: string | null;
groups: string[];
};
}
}
export const OIDC_PROVIDER_ID = "pocket-id";
function groupsFromProfile(profile: unknown): string[] {
const groups = (profile as { groups?: unknown } | undefined)?.groups;
if (Array.isArray(groups)) return groups.filter((g): g is string => typeof g === "string");
if (typeof groups === "string") return [groups];
return [];
}
// Config is built lazily (per request) so `next build` doesn't need OIDC env vars.
export const { handlers, auth, signIn, signOut } = NextAuth((): NextAuthConfig => {
const env = authEnv();
const restrictGroups = env.OIDC_ALLOWED_GROUPS.length > 0;
return {
trustHost: true,
session: { strategy: "jwt", maxAge: 7 * 24 * 60 * 60 },
pages: { signIn: "/login", error: "/login" },
providers: [
{
id: OIDC_PROVIDER_ID,
name: "Pocket ID",
type: "oidc",
issuer: env.OIDC_ISSUER,
clientId: env.OIDC_CLIENT_ID,
clientSecret: env.OIDC_CLIENT_SECRET,
checks: ["pkce", "state", "nonce"],
authorization: {
params: { scope: restrictGroups ? "openid profile email groups" : "openid profile email" },
},
},
],
callbacks: {
// Group gate. Fails closed: if groups are required and the claim is missing, deny.
signIn({ profile }) {
if (!restrictGroups) return true;
const groups = groupsFromProfile(profile);
return groups.some((g) => env.OIDC_ALLOWED_GROUPS.includes(g));
},
jwt({ token, profile }) {
if (profile) token.groups = groupsFromProfile(profile);
return token;
},
session({ session, token }) {
session.user.groups = Array.isArray(token.groups) ? (token.groups as string[]) : [];
return session;
},
},
};
});
+7
View File
@@ -0,0 +1,7 @@
"use client";
import { ThemeProvider as NextThemesProvider } from "next-themes";
export function ThemeProvider(props: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props} />;
}
+108
View File
@@ -0,0 +1,108 @@
"use client"
import * as React from "react"
import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
import { cn } from "cn"
function Avatar({
className,
size = "default",
...props
}: AvatarPrimitive.Root.Props & {
size?: "default" | "sm" | "lg"
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
)}
{...props}
/>
)
}
function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn(
"aspect-square size-full rounded-full object-cover",
className
)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: AvatarPrimitive.Fallback.Props) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"flex size-full items-center justify-center rounded-full bg-muted text-sm text-muted-foreground group-data-[size=sm]/avatar:text-xs",
className
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2 *:data-[slot=avatar]:ring-background",
className
)}
{...props}
/>
)
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"relative flex size-8 shrink-0 items-center justify-center rounded-full bg-muted text-sm text-muted-foreground ring-2 ring-background group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
{...props}
/>
)
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarGroup,
AvatarGroupCount,
AvatarBadge,
}
+51
View File
@@ -0,0 +1,51 @@
import { mergeProps } from "@base-ui/react/merge-props"
import { useRender } from "@base-ui/react/use-render"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
const badgeVariants = cva(
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-4xl border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary:
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
render,
...props
}: useRender.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
return useRender({
defaultTagName: "span",
props: mergeProps<"span">(
{
className: cn(badgeVariants({ variant }), className),
},
props
),
render,
state: {
slot: "badge",
variant,
},
})
}
export { Badge, badgeVariants }
+57
View File
@@ -0,0 +1,57 @@
import { Button as ButtonPrimitive } from "@base-ui/react/button"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "cn"
const buttonVariants = cva(
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
"border-border bg-background hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default:
"h-8 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-[min(var(--radius-md),10px)] px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-7 gap-1 rounded-[min(var(--radius-md),12px)] px-2.5 text-[0.8rem] in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3.5",
lg: "h-9 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-8",
"icon-xs":
"size-6 rounded-[min(var(--radius-md),10px)] in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-7 rounded-[min(var(--radius-md),12px)] in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
...props
}: ButtonPrimitive.Props & VariantProps<typeof buttonVariants>) {
return (
<ButtonPrimitive
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+102
View File
@@ -0,0 +1,102 @@
import * as React from "react"
import { cn } from "cn"
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-xl bg-card py-(--card-spacing) text-sm text-card-foreground ring-1 ring-foreground/10 [--card-spacing:--spacing(4)] has-data-[slot=card-footer]:pb-0 has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(3)] data-[size=sm]:has-data-[slot=card-footer]:pb-0 *:[img:first-child]:rounded-t-xl *:[img:last-child]:rounded-b-xl",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-t-xl px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn(
"font-heading text-base leading-snug font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-(--card-spacing)", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn(
"flex items-center rounded-b-xl border-t bg-muted/50 p-(--card-spacing)",
className
)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
+267
View File
@@ -0,0 +1,267 @@
"use client"
import * as React from "react"
import { Menu as MenuPrimitive } from "@base-ui/react/menu"
import { cn } from "cn"
import { ChevronRightIcon, CheckIcon } from "lucide-react"
function DropdownMenu({ ...props }: MenuPrimitive.Root.Props) {
return <MenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({ ...props }: MenuPrimitive.Portal.Props) {
return <MenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
}
function DropdownMenuTrigger({ ...props }: MenuPrimitive.Trigger.Props) {
return <MenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />
}
function DropdownMenuContent({
align = "start",
alignOffset = 0,
side = "bottom",
sideOffset = 4,
className,
...props
}: MenuPrimitive.Popup.Props &
Pick<
MenuPrimitive.Positioner.Props,
"align" | "alignOffset" | "side" | "sideOffset"
>) {
return (
<MenuPrimitive.Portal>
<MenuPrimitive.Positioner
className="isolate z-50 outline-none"
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
>
<MenuPrimitive.Popup
data-slot="dropdown-menu-content"
className={cn("z-50 max-h-(--available-height) w-(--anchor-width) min-w-32 origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-lg bg-popover p-1 text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 outline-none data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:overflow-hidden data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</MenuPrimitive.Positioner>
</MenuPrimitive.Portal>
)
}
function DropdownMenuGroup({ ...props }: MenuPrimitive.Group.Props) {
return <MenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
}
function DropdownMenuLabel({
className,
inset,
...props
}: MenuPrimitive.GroupLabel.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.GroupLabel
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-1.5 py-1 text-xs font-medium text-muted-foreground data-inset:pl-7",
className
)}
{...props}
/>
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: MenuPrimitive.Item.Props & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<MenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({ ...props }: MenuPrimitive.SubmenuRoot.Props) {
return <MenuPrimitive.SubmenuRoot data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: MenuPrimitive.SubmenuTrigger.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.SubmenuTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-popup-open:bg-accent data-popup-open:text-accent-foreground data-open:bg-accent data-open:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto" />
</MenuPrimitive.SubmenuTrigger>
)
}
function DropdownMenuSubContent({
align = "start",
alignOffset = -3,
side = "right",
sideOffset = 0,
className,
...props
}: React.ComponentProps<typeof DropdownMenuContent>) {
return (
<DropdownMenuContent
data-slot="dropdown-menu-sub-content"
className={cn("w-auto min-w-[96px] rounded-lg bg-popover p-1 text-popover-foreground shadow-lg ring-1 ring-foreground/10 duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
align={align}
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
inset,
...props
}: MenuPrimitive.CheckboxItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-checkbox-item-indicator"
>
<MenuPrimitive.CheckboxItemIndicator>
<CheckIcon
/>
</MenuPrimitive.CheckboxItemIndicator>
</span>
{children}
</MenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({ ...props }: MenuPrimitive.RadioGroup.Props) {
return (
<MenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
inset,
...props
}: MenuPrimitive.RadioItem.Props & {
inset?: boolean
}) {
return (
<MenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
data-inset={inset}
className={cn(
"relative flex cursor-default items-center gap-1.5 rounded-md py-1 pr-8 pl-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground focus:**:text-accent-foreground data-inset:pl-7 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span
className="pointer-events-none absolute right-2 flex items-center justify-center"
data-slot="dropdown-menu-radio-item-indicator"
>
<MenuPrimitive.RadioItemIndicator>
<CheckIcon
/>
</MenuPrimitive.RadioItemIndicator>
</span>
{children}
</MenuPrimitive.RadioItem>
)
}
function DropdownMenuSeparator({
className,
...props
}: MenuPrimitive.Separator.Props) {
return (
<MenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"ml-auto text-xs tracking-widest text-muted-foreground group-focus/dropdown-menu-item:text-accent-foreground",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}
+24
View File
@@ -0,0 +1,24 @@
"use client"
import { Separator as SeparatorPrimitive } from "@base-ui/react/separator"
import { cn } from "cn"
function Separator({
className,
orientation = "horizontal",
...props
}: SeparatorPrimitive.Props) {
return (
<SeparatorPrimitive
data-slot="separator"
orientation={orientation}
className={cn(
"shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",
className
)}
{...props}
/>
)
}
export { Separator }
+49
View File
@@ -0,0 +1,49 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
import { CircleCheckIcon, InfoIcon, TriangleAlertIcon, OctagonXIcon, Loader2Icon } from "lucide-react"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: (
<CircleCheckIcon className="size-4" />
),
info: (
<InfoIcon className="size-4" />
),
warning: (
<TriangleAlertIcon className="size-4" />
),
error: (
<OctagonXIcon className="size-4" />
),
loading: (
<Loader2Icon className="size-4 animate-spin" />
),
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
toastOptions={{
classNames: {
toast: "cn-toast",
},
}}
{...props}
/>
)
}
export { Toaster }
+33
View File
@@ -0,0 +1,33 @@
"use client";
import { useEffect, useState } from "react";
import { Badge } from "@/components/ui/badge";
import type { WorkerStatus } from "@/lib/worker-status";
/** Polls /api/status and shows whether the background worker is alive. */
export function WorkerIndicator({ initial }: { initial: WorkerStatus }) {
const [status, setStatus] = useState(initial);
useEffect(() => {
const tick = async () => {
try {
const res = await fetch("/api/status", { cache: "no-store" });
if (res.ok) setStatus((await res.json()).worker);
} catch {
// keep last known state
}
};
const id = setInterval(tick, 10_000);
return () => clearInterval(id);
}, []);
return (
<Badge
variant={status.online ? "secondary" : "destructive"}
title={status.hfVersion ?? (status.online ? "hf CLI not found" : undefined)}
>
<span className={`size-1.5 rounded-full ${status.online ? "bg-emerald-500" : "bg-destructive"}`} />
Worker {status.online ? "online" : "offline"}
</Badge>
);
}
+15
View File
@@ -0,0 +1,15 @@
import "server-only";
import type { Session } from "next-auth";
import { NextResponse } from "next/server";
import { auth } from "@/auth";
type Handler<Ctx> = (req: Request, ctx: Ctx & { session: Session }) => Promise<Response> | Response;
/** Wraps a route handler so it only runs for a logged-in user (defense in depth behind proxy.ts). */
export function withAuth<Ctx = unknown>(handler: Handler<Ctx>) {
return async (req: Request, ctx: Ctx) => {
const session = await auth();
if (!session?.user) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
return handler(req, { ...ctx, session });
};
}
+42
View File
@@ -0,0 +1,42 @@
import { mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { createClient, type Client } from "@libsql/client";
import { drizzle, type LibSQLDatabase } from "drizzle-orm/libsql";
import { coreEnv } from "@/lib/env";
import * as schema from "./schema";
export type Db = LibSQLDatabase<typeof schema>;
type Holder = { client?: Client; db?: Db };
// Survive Next.js dev hot reloads without opening a new pool each time.
const holder = ((globalThis as { __kanameDb?: Holder }).__kanameDb ??= {});
function ensureParentDir(url: string) {
if (!url.startsWith("file:")) return;
const path = url.slice("file:".length);
if (path === ":memory:") return;
mkdirSync(dirname(resolve(path)), { recursive: true });
}
/**
* Shared Drizzle instance. Web and worker each open their own pool on the same SQLite file;
* WAL mode lets the web app read while the worker writes.
*/
export function db(): Db {
if (!holder.db) {
const url = coreEnv().DATABASE_URL;
ensureParentDir(url);
// `timeout` is SQLite's busy timeout (ms) and applies to every pooled connection.
holder.client = createClient({ url, timeout: 5000 });
holder.db = drizzle(holder.client, { schema });
}
return holder.db;
}
/** Database-level settings. journal_mode=WAL is persistent, so running it once per process is enough. */
export async function initDb(): Promise<void> {
db();
await holder.client!.execute("PRAGMA journal_mode=WAL");
}
export { schema };
+8
View File
@@ -0,0 +1,8 @@
import { runMigrations } from "./migrate";
runMigrations()
.then(() => console.log("migrations applied"))
.catch((err) => {
console.error(err);
process.exit(1);
});
+9
View File
@@ -0,0 +1,9 @@
import { resolve } from "node:path";
import { migrate } from "drizzle-orm/libsql/migrator";
import { db, initDb } from "./client";
/** Applies pending migrations from ./drizzle. Run by the worker at startup (and `npm run db:migrate`). */
export async function runMigrations(): Promise<void> {
await initDb();
await migrate(db(), { migrationsFolder: resolve(process.cwd(), "drizzle") });
}
+246
View File
@@ -0,0 +1,246 @@
import { sql } from "drizzle-orm";
import {
index,
integer,
primaryKey,
sqliteTable,
text,
uniqueIndex,
} from "drizzle-orm/sqlite-core";
import { ulid } from "ulid";
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
// - Primary keys are ULID strings, generated in the app, never reused.
// - Timestamps are integer milliseconds (mode "timestamp_ms").
// - Byte counts are integers (safe up to 2^53).
// - Enums are text columns with a TS-level enum, not DB enums.
// - Foreign keys are declared, but deletes cascade in app code: SQLite only enforces
// FKs per connection with PRAGMA foreign_keys=ON, which libsql's pool doesn't guarantee.
const id = () =>
text("id")
.primaryKey()
.$defaultFn(() => ulid());
const createdAt = () =>
integer("created_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date());
const updatedAt = () =>
integer("updated_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date())
.$onUpdateFn(() => new Date());
const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
export const MODEL_STATUSES = [
"pending", // added, nothing downloaded yet
"downloading",
"ready", // all selected files present at pinned SHA
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
"failed", // last download failed
"deleting",
] as const;
export type ModelStatus = (typeof MODEL_STATUSES)[number];
export const models = sqliteTable(
"models",
{
id: id(),
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
repoId: text("repo_id").notNull(), // "org/name"
trackedRevision: text("tracked_revision").notNull().default("main"),
pinnedSha: text("pinned_sha").notNull(),
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
localPath: text("local_path").notNull(),
/**
* Selection rule, applied to the repo's file list. Checkbox picks are stored as escaped
* exact-path globs, so the same rule can be re-applied to a newer revision.
*/
includePatterns: text("include_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
excludePatterns: text("exclude_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
status: text("status", { enum: MODEL_STATUSES }).notNull().default("pending"),
/** Latest SHA of trackedRevision seen on the Hub (update check). */
remoteSha: text("remote_sha"),
lastCheckedAt: ts("last_checked_at"),
lastCheckError: text("last_check_error"),
lastVerifiedAt: ts("last_verified_at"),
downloadedAt: ts("downloaded_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
);
/** History of SHAs a model has been pinned to. */
export const modelRevisions = sqliteTable(
"model_revisions",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
sha: text("sha").notNull(),
pinnedAt: ts("pinned_at")
.notNull()
.$defaultFn(() => new Date()),
supersededAt: ts("superseded_at"),
},
(t) => [index("model_revisions_model_idx").on(t.modelId)],
);
export const MODEL_FILE_STATES = [
"pending", // not downloaded yet / not checked
"present", // exists with the expected size
"missing",
"size_mismatch",
"hash_mismatch",
"verified", // deep verify: hash matches
] as const;
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
export const modelFiles = sqliteTable(
"model_files",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
path: text("path").notNull(),
size: integer("size").notNull(),
/** Git blob SHA-1 from the Hub tree API. */
blobOid: text("blob_oid"),
/** SHA-256 for LFS/Xet files (null for small git-stored files). */
lfsSha256: text("lfs_sha256"),
selected: integer("selected", { mode: "boolean" }).notNull().default(false),
state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"),
checkedAt: ts("checked_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("model_files_model_path_uq").on(t.modelId, t.path)],
);
// ---------------------------------------------------------------------------
// Jobs (executed by the worker)
// ---------------------------------------------------------------------------
export const JOB_KINDS = ["download", "verify", "deep_verify"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export const JOB_PURPOSES = ["initial", "repair", "update"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"queued",
"downloading",
"verifying",
"completed",
"failed",
"cancelled",
"interrupted",
] as const;
export type JobState = (typeof JOB_STATES)[number];
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
export const JOB_ERROR_CODES = [
"auth", // invalid/missing token
"gated", // gated repo, access not granted
"repo_not_found",
"revision_not_found",
"disk_full",
"network",
"size_mismatch", // finished but files don't match expected sizes
"unknown",
] as const;
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
export const jobs = sqliteTable(
"jobs",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
kind: text("kind", { enum: JOB_KINDS }).notNull(),
purpose: text("purpose", { enum: JOB_PURPOSES }),
targetSha: text("target_sha").notNull(),
state: text("state", { enum: JOB_STATES }).notNull().default("queued"),
attempt: integer("attempt").notNull().default(0),
totalBytes: integer("total_bytes").notNull().default(0),
doneBytes: integer("done_bytes").notNull().default(0),
speedBps: integer("speed_bps"),
etaSeconds: integer("eta_seconds"),
exitCode: integer("exit_code"),
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
errorMessage: text("error_message"),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
);
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
export type JobFileState = (typeof JOB_FILE_STATES)[number];
export const jobFiles = sqliteTable(
"job_files",
{
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
modelFileId: text("model_file_id")
.notNull()
.references(() => modelFiles.id),
path: text("path").notNull(),
expectedBytes: integer("expected_bytes").notNull(),
doneBytes: integer("done_bytes").notNull().default(0),
state: text("state", { enum: JOB_FILE_STATES }).notNull().default("pending"),
},
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
);
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
export type LogStream = (typeof LOG_STREAMS)[number];
export const jobLogs = sqliteTable(
"job_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
);
// ---------------------------------------------------------------------------
// Worker liveness
// ---------------------------------------------------------------------------
export const workerState = sqliteTable("worker_state", {
id: text("id").primaryKey(), // "worker"
pid: integer("pid"),
hfVersion: text("hf_version"),
startedAt: ts("started_at").notNull(),
heartbeatAt: ts("heartbeat_at").notNull(),
});
+56
View File
@@ -0,0 +1,56 @@
import { z } from "zod";
// Shared by the web app and the worker. Never import this from a client component:
// it contains HF_TOKEN. Web code should go through "@/lib/server-env", which is guarded
// by "server-only".
const emptyToUndefined = (v: unknown) => (v === "" ? undefined : v);
const coreSchema = z.object({
HF_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
MODELS_DIR: z.preprocess(emptyToUndefined, z.string().default("/models")),
DATABASE_URL: z.preprocess(emptyToUndefined, z.string().default("file:/data/app.db")),
MAX_CONCURRENT_DOWNLOADS: z.preprocess(emptyToUndefined, z.coerce.number().int().min(1).default(1)),
UPDATE_CHECK_INTERVAL_HOURS: z.preprocess(emptyToUndefined, z.coerce.number().min(0).default(12)),
});
const authSchema = z.object({
OIDC_ISSUER: z.url(),
OIDC_CLIENT_ID: z.string().min(1),
OIDC_CLIENT_SECRET: z.string().min(1),
OIDC_ALLOWED_GROUPS: z.preprocess(
(v) =>
typeof v === "string"
? v
.split(",")
.map((g) => g.trim())
.filter(Boolean)
: [],
z.array(z.string()),
),
});
export type CoreEnv = z.infer<typeof coreSchema>;
export type AuthEnv = z.infer<typeof authSchema>;
let core: CoreEnv | undefined;
let auth: AuthEnv | undefined;
function parse<T extends z.ZodType>(schema: T, name: string): z.infer<T> {
const result = schema.safeParse(process.env);
if (!result.success) {
const issues = result.error.issues.map((i) => ` ${i.path.join(".")}: ${i.message}`).join("\n");
throw new Error(`Invalid ${name} environment:\n${issues}`);
}
return result.data;
}
/** Config needed by both web and worker. Parsed lazily so `next build` works without env. */
export function coreEnv(): CoreEnv {
return (core ??= parse(coreSchema, "core"));
}
/** OIDC config, only needed by the web app. */
export function authEnv(): AuthEnv {
return (auth ??= parse(authSchema, "auth"));
}
+3
View File
@@ -0,0 +1,3 @@
import "server-only";
export { coreEnv, authEnv } from "@/lib/env";
+1
View File
@@ -0,0 +1 @@
export { cn } from "cn"
+28
View File
@@ -0,0 +1,28 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { workerState } from "@/lib/db/schema";
/** The worker writes a heartbeat every 5s; after this long without one we call it offline. */
const OFFLINE_AFTER_MS = 20_000;
export type WorkerStatus = {
online: boolean;
heartbeatAt: string | null;
hfVersion: string | null;
};
export async function getWorkerStatus(): Promise<WorkerStatus> {
try {
const row = await db().query.workerState.findFirst({ where: eq(workerState.id, "worker") });
if (!row) return { online: false, heartbeatAt: null, hfVersion: null };
return {
online: Date.now() - row.heartbeatAt.getTime() < OFFLINE_AFTER_MS,
heartbeatAt: row.heartbeatAt.toISOString(),
hfVersion: row.hfVersion,
};
} catch {
// Table missing (worker never ran migrations yet) or DB unavailable.
return { online: false, heartbeatAt: null, hfVersion: null };
}
}
+31
View File
@@ -0,0 +1,31 @@
import { type NextFetchEvent, type NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
// Gate every page and API route. Unauthenticated page requests go to /login,
// API requests get a 401. Route handlers check the session again (see lib/api-auth.ts).
const gate = auth((req) => {
if (req.auth) return;
const { pathname, search } = req.nextUrl;
if (pathname.startsWith("/api/")) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
}
const loginUrl = new URL("/login", req.url);
if (pathname !== "/") loginUrl.searchParams.set("callbackUrl", pathname + search);
return NextResponse.redirect(loginUrl);
});
// Next.js requires a literal function export here; `export default auth(...)` isn't recognized.
// With a lazy (function) config, next-auth's `auth(handler)` returns a Promise of the handler,
// even though its types say otherwise, hence the await.
type ProxyHandler = (req: NextRequest, event: NextFetchEvent) => Promise<Response | undefined>;
export async function proxy(req: NextRequest, event: NextFetchEvent) {
const handler = (await gate) as unknown as ProxyHandler;
return handler(req, event);
}
export const config = {
// Everything except the Auth.js endpoints, the login page and static assets.
matcher: ["/((?!api/auth|login|_next/static|_next/image|favicon.ico).*)"],
};
+83
View File
@@ -0,0 +1,83 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { inArray } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { runMigrations } from "@/lib/db/migrate";
import { ACTIVE_JOB_STATES, jobLogs, jobs, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { log } from "./log";
const HEARTBEAT_MS = 5_000;
async function detectHfVersion(): Promise<string | null> {
try {
const { stdout } = await promisify(execFile)("hf", ["version"], { timeout: 30_000 });
return stdout.trim() || null;
} catch {
return null;
}
}
/** Jobs that were running when the worker last stopped can't still be running: mark them interrupted. */
async function recoverInterruptedJobs() {
const stale = await db()
.update(jobs)
.set({ state: "interrupted", finishedAt: new Date(), speedBps: null, etaSeconds: null })
.where(inArray(jobs.state, [...ACTIVE_JOB_STATES]))
.returning({ id: jobs.id });
if (stale.length === 0) return;
await db()
.insert(jobLogs)
.values(
stale.map((j) => ({
jobId: j.id,
stream: "system" as const,
line: "Worker restarted while this job was running. Marked as interrupted; resume to continue.",
})),
);
log.warn(`marked ${stale.length} job(s) as interrupted`);
}
async function heartbeat(startedAt: Date, hfVersion: string | null) {
const now = new Date();
await db()
.insert(workerState)
.values({ id: "worker", pid: process.pid, hfVersion, startedAt, heartbeatAt: now })
.onConflictDoUpdate({
target: workerState.id,
set: { pid: process.pid, hfVersion, startedAt, heartbeatAt: now },
});
}
async function main() {
const env = coreEnv();
log.info(`starting (pid ${process.pid}), models dir: ${env.MODELS_DIR}`);
await runMigrations();
log.info("database migrated");
await recoverInterruptedJobs();
const hfVersion = await detectHfVersion();
if (hfVersion) log.info(`hf CLI: ${hfVersion}`);
else log.warn("hf CLI not found on PATH; downloads will fail until it is installed");
const startedAt = new Date();
await heartbeat(startedAt, hfVersion);
const timer = setInterval(() => {
heartbeat(startedAt, hfVersion).catch((err) => log.error("heartbeat failed", err));
}, HEARTBEAT_MS);
const shutdown = (signal: string) => {
log.info(`received ${signal}, shutting down`);
clearInterval(timer);
process.exit(0);
};
process.on("SIGINT", () => shutdown("SIGINT"));
process.on("SIGTERM", () => shutdown("SIGTERM"));
}
main().catch((err) => {
log.error("fatal", err);
process.exit(1);
});
+12
View File
@@ -0,0 +1,12 @@
// Console logger for the worker process (job output goes to the job_logs table instead).
function fmt(level: string, msg: string) {
return `${new Date().toISOString()} [worker] ${level} ${msg}`;
}
export const log = {
info: (msg: string) => console.log(fmt("INFO ", msg)),
warn: (msg: string) => console.warn(fmt("WARN ", msg)),
error: (msg: string, err?: unknown) =>
console.error(fmt("ERROR", msg), err instanceof Error ? err.stack ?? err.message : (err ?? "")),
};