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

+19
View File
@@ -0,0 +1,19 @@
# Hugging Face token (server-side only; passed to the hf CLI via environment)
HF_TOKEN=
# Where models are stored: <MODELS_DIR>/<org>/<repo>
MODELS_DIR=/models
# SQLite database (keep on a local volume, not NFS)
DATABASE_URL=file:/data/app.db
MAX_CONCURRENT_DOWNLOADS=1
# 0 disables the periodic update check
UPDATE_CHECK_INTERVAL_HOURS=12
# Auth.js: generate with `npx auth secret` or `openssl rand -base64 33`
AUTH_SECRET=
# Public URL of this app; OIDC redirect URI is <AUTH_URL>/api/auth/callback/pocket-id
AUTH_URL=https://models.example.com
OIDC_ISSUER=https://auth.example.com
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# Optional, comma-separated. If set, only members of these groups (from the `groups` claim) can log in.
OIDC_ALLOWED_GROUPS=
+4
View File
@@ -0,0 +1,4 @@
# Keep LF everywhere: the app runs in Linux containers.
* text=auto eol=lf
*.png binary
*.ico binary
+45
View File
@@ -0,0 +1,45 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
!.env.example
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# local runtime data (SQLite, downloaded models)
/data/
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
# This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+29
View File
@@ -0,0 +1,29 @@
# Changelog
All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.1.0] - 2026-10-05
Milestone (a): project skeleton and OIDC login.
### Added
- Next.js 16 (App Router) + TypeScript + Tailwind v4 + shadcn/ui (Base UI) project.
- OIDC login via Auth.js v5 (pinned `next-auth@5.0.0-beta.32`) with a generic provider
(`pocket-id`), authorization code flow with PKCE, state and nonce. JWT sessions, 7 days.
- Optional group gate `OIDC_ALLOWED_GROUPS` (requests the `groups` scope, fails closed when the
claim is missing).
- `src/proxy.ts` gates every page (redirect to `/login`) and API route (401); route handlers
re-check the session (`withAuth`).
- Login page with readable errors (access denied, misconfiguration) and safe `callbackUrl` handling.
- Drizzle ORM schema on SQLite via libsql: `models`, `model_revisions`, `model_files`, `jobs`,
`job_files`, `job_logs`, `worker_state`; initial migration in `drizzle/`.
- Worker process skeleton (`src/worker`): applies migrations, marks stale running jobs as
`interrupted` on startup, detects the `hf` CLI version, writes a heartbeat every 5 s.
- Header badge showing whether the worker is online; `/api/status` endpoint.
- Env validation with zod (`src/lib/env.ts`), `.env.example`.
- `npm run dev` starts web and worker together.
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+31
View File
@@ -0,0 +1,31 @@
# Model Manager
Self-hosted web UI for downloading and managing local LLMs from Hugging Face.
Downloads are done by the official `hf` CLI; the Hub API is used for metadata.
## Architecture
- **web** (`next dev` / `next start`): Next.js App Router UI + API routes, OIDC login via Auth.js.
- **worker** (`src/worker`): owns the job queue, spawns `hf download`, tracks progress, runs update checks.
Applies DB migrations at startup.
- They talk only through the SQLite database (`DATABASE_URL`).
## Local development
```bash
cp .env.example .env # then fill in OIDC_* and AUTH_SECRET; use local paths, e.g.
# DATABASE_URL=file:./data/app.db, MODELS_DIR=./data/models, AUTH_URL=http://localhost:3000
npm install
npm run dev # starts web (http://localhost:3000) and worker together
```
OIDC redirect URI for the client in Pocket ID: `<AUTH_URL>/api/auth/callback/pocket-id`.
Other scripts:
| Script | What it does |
| --- | --- |
| `npm run dev:web` / `npm run dev:worker` | run one side only |
| `npm run db:generate` | create a migration after changing `src/lib/db/schema.ts` |
| `npm run db:migrate` | apply migrations without starting the worker |
| `npm run typecheck`, `npm run lint` | checks |
+25
View File
@@ -0,0 +1,25 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "base-nova",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "sqlite",
schema: "./src/lib/db/schema.ts",
out: "./drizzle",
});
+100
View File
@@ -0,0 +1,100 @@
CREATE TABLE `job_files` (
`job_id` text NOT NULL,
`model_file_id` text NOT NULL,
`path` text NOT NULL,
`expected_bytes` integer NOT NULL,
`done_bytes` integer DEFAULT 0 NOT NULL,
`state` text DEFAULT 'pending' NOT NULL,
PRIMARY KEY(`job_id`, `model_file_id`),
FOREIGN KEY (`job_id`) REFERENCES `jobs`(`id`) ON UPDATE no action ON DELETE no action,
FOREIGN KEY (`model_file_id`) REFERENCES `model_files`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE TABLE `job_logs` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`job_id` text NOT NULL,
`ts` integer NOT NULL,
`stream` text NOT NULL,
`line` text NOT NULL,
FOREIGN KEY (`job_id`) REFERENCES `jobs`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `job_logs_job_idx` ON `job_logs` (`job_id`,`id`);--> statement-breakpoint
CREATE TABLE `jobs` (
`id` text PRIMARY KEY NOT NULL,
`model_id` text NOT NULL,
`kind` text NOT NULL,
`purpose` text,
`target_sha` text NOT NULL,
`state` text DEFAULT 'queued' NOT NULL,
`attempt` integer DEFAULT 0 NOT NULL,
`total_bytes` integer DEFAULT 0 NOT NULL,
`done_bytes` integer DEFAULT 0 NOT NULL,
`speed_bps` integer,
`eta_seconds` integer,
`exit_code` integer,
`error_code` text,
`error_message` text,
`cancel_requested_at` integer,
`started_at` integer,
`finished_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `jobs_state_idx` ON `jobs` (`state`);--> statement-breakpoint
CREATE INDEX `jobs_model_idx` ON `jobs` (`model_id`);--> statement-breakpoint
CREATE TABLE `model_files` (
`id` text PRIMARY KEY NOT NULL,
`model_id` text NOT NULL,
`path` text NOT NULL,
`size` integer NOT NULL,
`blob_oid` text,
`lfs_sha256` text,
`selected` integer DEFAULT false NOT NULL,
`state` text DEFAULT 'pending' NOT NULL,
`checked_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE UNIQUE INDEX `model_files_model_path_uq` ON `model_files` (`model_id`,`path`);--> statement-breakpoint
CREATE TABLE `model_revisions` (
`id` text PRIMARY KEY NOT NULL,
`model_id` text NOT NULL,
`sha` text NOT NULL,
`pinned_at` integer NOT NULL,
`superseded_at` integer,
FOREIGN KEY (`model_id`) REFERENCES `models`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE INDEX `model_revisions_model_idx` ON `model_revisions` (`model_id`);--> statement-breakpoint
CREATE TABLE `models` (
`id` text PRIMARY KEY NOT NULL,
`repo_type` text DEFAULT 'model' NOT NULL,
`repo_id` text NOT NULL,
`tracked_revision` text DEFAULT 'main' NOT NULL,
`pinned_sha` text NOT NULL,
`local_path` text NOT NULL,
`include_patterns` text DEFAULT '[]' NOT NULL,
`exclude_patterns` text DEFAULT '[]' NOT NULL,
`status` text DEFAULT 'pending' NOT NULL,
`remote_sha` text,
`last_checked_at` integer,
`last_check_error` text,
`last_verified_at` integer,
`downloaded_at` integer,
`created_at` integer NOT NULL,
`updated_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `models_repo_uq` ON `models` (`repo_type`,`repo_id`);--> statement-breakpoint
CREATE TABLE `worker_state` (
`id` text PRIMARY KEY NOT NULL,
`pid` integer,
`hf_version` text,
`started_at` integer NOT NULL,
`heartbeat_at` integer NOT NULL
);
+711
View File
@@ -0,0 +1,711 @@
{
"version": "6",
"dialect": "sqlite",
"id": "d6f6feea-3dd0-41f3-82af-fe63d09ca635",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"job_files": {
"name": "job_files",
"columns": {
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"model_file_id": {
"name": "model_file_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"expected_bytes": {
"name": "expected_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
}
},
"indexes": {},
"foreignKeys": {
"job_files_job_id_jobs_id_fk": {
"name": "job_files_job_id_jobs_id_fk",
"tableFrom": "job_files",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
},
"job_files_model_file_id_model_files_id_fk": {
"name": "job_files_model_file_id_model_files_id_fk",
"tableFrom": "job_files",
"tableTo": "model_files",
"columnsFrom": [
"model_file_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {
"job_files_job_id_model_file_id_pk": {
"columns": [
"job_id",
"model_file_id"
],
"name": "job_files_job_id_model_file_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"job_logs": {
"name": "job_logs",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"ts": {
"name": "ts",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"stream": {
"name": "stream",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"line": {
"name": "line",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"job_logs_job_idx": {
"name": "job_logs_job_idx",
"columns": [
"job_id",
"id"
],
"isUnique": false
}
},
"foreignKeys": {
"job_logs_job_id_jobs_id_fk": {
"name": "job_logs_job_id_jobs_id_fk",
"tableFrom": "job_logs",
"tableTo": "jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"jobs": {
"name": "jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"kind": {
"name": "kind",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"target_sha": {
"name": "target_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'queued'"
},
"attempt": {
"name": "attempt",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"total_bytes": {
"name": "total_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"done_bytes": {
"name": "done_bytes",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"speed_bps": {
"name": "speed_bps",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"eta_seconds": {
"name": "eta_seconds",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"exit_code": {
"name": "exit_code",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_code": {
"name": "error_code",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error_message": {
"name": "error_message",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"cancel_requested_at": {
"name": "cancel_requested_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"finished_at": {
"name": "finished_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"jobs_state_idx": {
"name": "jobs_state_idx",
"columns": [
"state"
],
"isUnique": false
},
"jobs_model_idx": {
"name": "jobs_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"jobs_model_id_models_id_fk": {
"name": "jobs_model_id_models_id_fk",
"tableFrom": "jobs",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_files": {
"name": "model_files",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"path": {
"name": "path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"size": {
"name": "size",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"blob_oid": {
"name": "blob_oid",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"lfs_sha256": {
"name": "lfs_sha256",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"selected": {
"name": "selected",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"state": {
"name": "state",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"checked_at": {
"name": "checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"model_files_model_path_uq": {
"name": "model_files_model_path_uq",
"columns": [
"model_id",
"path"
],
"isUnique": true
}
},
"foreignKeys": {
"model_files_model_id_models_id_fk": {
"name": "model_files_model_id_models_id_fk",
"tableFrom": "model_files",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"model_revisions": {
"name": "model_revisions",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"model_id": {
"name": "model_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sha": {
"name": "sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"pinned_at": {
"name": "pinned_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"superseded_at": {
"name": "superseded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"model_revisions_model_idx": {
"name": "model_revisions_model_idx",
"columns": [
"model_id"
],
"isUnique": false
}
},
"foreignKeys": {
"model_revisions_model_id_models_id_fk": {
"name": "model_revisions_model_id_models_id_fk",
"tableFrom": "model_revisions",
"tableTo": "models",
"columnsFrom": [
"model_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"models": {
"name": "models",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"repo_type": {
"name": "repo_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'model'"
},
"repo_id": {
"name": "repo_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"tracked_revision": {
"name": "tracked_revision",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'main'"
},
"pinned_sha": {
"name": "pinned_sha",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"local_path": {
"name": "local_path",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"include_patterns": {
"name": "include_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"exclude_patterns": {
"name": "exclude_patterns",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'[]'"
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"remote_sha": {
"name": "remote_sha",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_checked_at": {
"name": "last_checked_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_check_error": {
"name": "last_check_error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"last_verified_at": {
"name": "last_verified_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"downloaded_at": {
"name": "downloaded_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"models_repo_uq": {
"name": "models_repo_uq",
"columns": [
"repo_type",
"repo_id"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"worker_state": {
"name": "worker_state",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"pid": {
"name": "pid",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"hf_version": {
"name": "hf_version",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"heartbeat_at": {
"name": "heartbeat_at",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+13
View File
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1791206191116,
"tag": "0000_init",
"breakpoints": true
}
]
}
+18
View File
@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;
+8
View File
@@ -0,0 +1,8 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
// Native SQLite driver: load from node_modules at runtime instead of bundling.
serverExternalPackages: ["@libsql/client", "libsql"],
};
export default nextConfig;
+12251
View File
File diff suppressed because it is too large. Load diff
+50
View File
@@ -0,0 +1,50 @@
{
"name": "kaname",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
"dev:web": "next dev",
"dev:worker": "dotenv -e .env -- tsx watch src/worker/index.ts",
"build": "next build",
"start": "next start",
"worker": "tsx src/worker/index.ts",
"lint": "eslint",
"typecheck": "next typegen && tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts"
},
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
"class-variance-authority": "^0.7.1",
"cn": "^0.4.0",
"drizzle-orm": "^0.45.3",
"lucide-react": "^1.52.0",
"next": "16.3.8",
"next-auth": "^5.0.0-beta.32",
"next-themes": "^0.4.6",
"react": "19.2.8",
"react-dom": "19.2.8",
"server-only": "^0.0.1",
"shadcn": "^4.21.1",
"sonner": "^2.0.8",
"tw-animate-css": "^1.4.0",
"ulid": "^3.0.2",
"zod": "^4.6.5"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"concurrently": "^10.0.5",
"dotenv-cli": "^11.0.0",
"drizzle-kit": "^0.31.11",
"eslint": "^9",
"eslint-config-next": "16.3.8",
"tailwindcss": "^4",
"tsx": "^4.23.15",
"typescript": "^5"
}
}
+7
View File
@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;
+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 ?? "")),
};
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}