diff --git a/.env.example b/.env.example index 82fc1ec..842ad88 100644 --- a/.env.example +++ b/.env.example @@ -37,7 +37,7 @@ KANAME_VERSION= # --------------------------------------------------------------------------- MAX_CONCURRENT_DOWNLOADS=1 -# Hub update check interval; 0 disables it +# How often the worker checks every model on the Hub (still there? later: newer commits); 0 disables it UPDATE_CHECK_INTERVAL_HOURS=12 # 1 (default): hf downloads over plain HTTP, so progress can be measured from bytes on disk. # 0: use Xet (chunk-level dedup on updates), but progress only advances in large jumps. diff --git a/CHANGELOG.md b/CHANGELOG.md index a22ebaa..9813816 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,17 @@ step 1 (Hugging Face downloader) is released as a minor version. tree (base model → quantized/finetuned → this repo) listing other local models of the same base. - Hub metadata now includes the author's avatar and the relation to the base model; existing models are refetched once by the worker. +- Models deleted from Hugging Face are flagged, never deleted locally: the worker checks every model + every `UPDATE_CHECK_INTERVAL_HOURS` (and right after a failed download) whether the repo and the + pinned commit still exist. A deleted repo (or one made private) or a rewritten history shows a + warning badge in the library (searchable, and a value of the Status filter), a banner on the model + page, and blocks new downloads and "Download more". "On the Hub" in the sidebar shows the last + check, with "Check now". +- Create tags in Settings (name and color), before any model uses them. +- Tag picker on the model page and in Add model: a dropdown with "Create new tag…" first, then your + existing tags with their colors, and "Manage tags…". +- Account menu in the header with your profile picture from the OIDC provider (initials as + fallback): name and email, links to the settings, theme (system/light/dark) and sign out. ### Changed @@ -40,6 +51,9 @@ step 1 (Hugging Face downloader) is released as a minor version. can't bypass it. - Quant labels (library column, Quant filter, "Local copy") only count model weights, not MTP, mmproj or imatrix files. +- Tags are no longer deleted automatically when no model uses them anymore; delete them in Settings. +- Settings has separate pages for **File labels** and **Tags**. +- Header: app icon, navigation with icons and the current page highlighted. ### Fixed diff --git a/drizzle/0007_hub_state.sql b/drizzle/0007_hub_state.sql new file mode 100644 index 0000000..aca4ddd --- /dev/null +++ b/drizzle/0007_hub_state.sql @@ -0,0 +1,2 @@ +ALTER TABLE `models` ADD `hub_state` text;--> statement-breakpoint +ALTER TABLE `models` ADD `hub_missing_since` integer; \ No newline at end of file diff --git a/drizzle/meta/0007_snapshot.json b/drizzle/meta/0007_snapshot.json new file mode 100644 index 0000000..655a4fd --- /dev/null +++ b/drizzle/meta/0007_snapshot.json @@ -0,0 +1,960 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "4bf01375-42a2-440f-aeba-69644c7bca95", + "prevId": "84e7c88b-53c4-4eba-8f2f-7de08b494316", + "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": {} + }, + "model_tags": { + "name": "model_tags", + "columns": { + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "tag_id": { + "name": "tag_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "model_tags_tag_idx": { + "name": "model_tags_tag_idx", + "columns": [ + "tag_id" + ], + "isUnique": false + } + }, + "foreignKeys": { + "model_tags_model_id_models_id_fk": { + "name": "model_tags_model_id_models_id_fk", + "tableFrom": "model_tags", + "tableTo": "models", + "columnsFrom": [ + "model_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "model_tags_tag_id_tags_id_fk": { + "name": "model_tags_tag_id_tags_id_fk", + "tableFrom": "model_tags", + "tableTo": "tags", + "columnsFrom": [ + "tag_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "model_tags_model_id_tag_id_pk": { + "columns": [ + "model_id", + "tag_id" + ], + "name": "model_tags_model_id_tag_id_pk" + } + }, + "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 + }, + "hub_state": { + "name": "hub_state", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_missing_since": { + "name": "hub_missing_since", + "type": "integer", + "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 + }, + "base_models": { + "name": "base_models", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "base_relation": { + "name": "base_relation", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "author_avatar_url": { + "name": "author_avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "architecture": { + "name": "architecture", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "pipeline_tag": { + "name": "pipeline_tag", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "license": { + "name": "license", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hub_tags": { + "name": "hub_tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "metadata_fetched_at": { + "name": "metadata_fetched_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": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tags": { + "name": "tags", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "tags_slug_uq": { + "name": "tags_slug_uq", + "columns": [ + "slug" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "worker_state": { + "name": "worker_state", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "instance_id": { + "name": "instance_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "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 + }, + "models_dir_free_bytes": { + "name": "models_dir_free_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "models_dir_total_bytes": { + "name": "models_dir_total_bytes", + "type": "integer", + "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": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 7fee44e..26bd5dc 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -50,6 +50,13 @@ "when": 1791224932279, "tag": "0006_settings_and_tag_color", "breakpoints": true + }, + { + "idx": 7, + "version": "6", + "when": 1791233230682, + "tag": "0007_hub_state", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/(app)/[org]/[repo]/download-card.tsx b/src/app/(app)/[org]/[repo]/download-card.tsx index 23291c8..a768457 100644 --- a/src/app/(app)/[org]/[repo]/download-card.tsx +++ b/src/app/(app)/[org]/[repo]/download-card.tsx @@ -15,7 +15,16 @@ import { formatBytes, percent } from "@/lib/format"; const OPEN = ["queued", "downloading", "verifying"]; /** Sidebar card: current download state, actions and (while running) per-file progress. */ -export function DownloadCard({ modelId, status }: { modelId: string; status: ModelStatus }) { +export function DownloadCard({ + modelId, + status, + hubMissing, +}: { + modelId: string; + status: ModelStatus; + /** The repo or pinned commit is gone from the Hub; no new downloads. */ + hubMissing: boolean; +}) { const { snapshot } = useLive({ model: modelId }); const [busy, setBusy] = useState(false); const latest = snapshot?.jobs[0]; @@ -35,6 +44,7 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free download slot." : "Queued, but the worker is offline."; else if (open) hint = "Runs in the background; you can close this page."; else if (status === "ready") hint = "All selected files are present."; + else if (hubMissing) hint = "Can't download: no longer available on Hugging Face. Local files are kept."; return (
@@ -84,6 +94,7 @@ export function DownloadCard({ modelId, status }: { modelId: string; status: Mod ) : ( status !== "ready" && + !hubMissing && snapshot && ( + ); +} diff --git a/src/app/(app)/[org]/[repo]/page.tsx b/src/app/(app)/[org]/[repo]/page.tsx index b3993e9..be04f4f 100644 --- a/src/app/(app)/[org]/[repo]/page.tsx +++ b/src/app/(app)/[org]/[repo]/page.tsx @@ -11,11 +11,13 @@ import { MessagesSquareIcon, ScaleIcon, SparklesIcon, + TriangleAlertIcon, } from "lucide-react"; import type { Metadata } from "next"; import Link from "next/link"; import { notFound, redirect } from "next/navigation"; import { CopyButton } from "@/components/copy-button"; +import { HubStateBadge } from "@/components/hub-state-badge"; import { LocalTime } from "@/components/local-time"; import { ModelStatusBadge } from "@/components/model-status-badge"; import { buttonVariants } from "@/components/ui/button"; @@ -30,6 +32,7 @@ import { modelTagList } from "@/lib/tags"; import { getWorkerStatus } from "@/lib/worker-status"; import { DownloadCard } from "./download-card"; import { FilesTab } from "./files-tab"; +import { HubCheckButton } from "./hub-check"; import { JobsTab } from "./jobs-tab"; import { ModelCard } from "./model-card"; import { RemoveModelButton } from "./remove-model-button"; @@ -90,6 +93,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o const hub = `https://huggingface.co/${model.repoId}`; const baseModels = model.baseModels ?? []; const hubTags = model.hubTags ?? []; + const hubMissing = model.hubState === "repo_missing" || model.hubState === "commit_missing"; const [tags, related, card, worker] = await Promise.all([ modelTagList(model.id), @@ -125,6 +129,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o

{name}

+
{model.status === "pending" && } 🤗 Hugging Face @@ -159,6 +164,32 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o + {hubMissing && ( +
+ +
+

+ {model.hubState === "repo_missing" + ? "This repo is no longer on Hugging Face" + : "The pinned commit is no longer on Hugging Face"} +

+

+ {model.hubState === "repo_missing" + ? "It was deleted, renamed or made private. " + : "The repo's history was rewritten. "} + Your local copy is kept and stays usable; downloading more files or repairing isn't possible. + {model.hubMissingSince && ( + <> + {" "} + Missing since . + + )} +

+
+ +
+ )} +
{/* Content card with the tabs as a segmented control in its header */} @@ -220,6 +251,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o others={others} freeBytes={worker.online ? worker.modelsDirFreeBytes : null} busy={model.status === "downloading"} + hubMissing={hubMissing} /> )} {tab === "jobs" && ( @@ -231,7 +263,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
- - setTagsText(e.target.value)} - placeholder="roleplay, security" - list="known-tags" - /> - - {knownTags.map((t) => ( -
diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index 5dd8718..41c2710 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -1,8 +1,9 @@ import Link from "next/link"; import { redirect } from "next/navigation"; import { auth, signOut } from "@/auth"; -import { Button } from "@/components/ui/button"; +import { AppNav } from "@/components/app-nav"; import { LabelSettingsProvider } from "@/components/labels"; +import { UserMenu } from "@/components/user-menu"; import { WorkerIndicator } from "@/components/worker-indicator"; import { getFileRoleStyles } from "@/lib/settings"; import { getWorkerStatus } from "@/lib/worker-status"; @@ -16,34 +17,23 @@ export default async function AppLayout({ children }: LayoutProps<"/">) { return (
-
- +
+ + {/* eslint-disable-next-line @next/next/no-img-element */} + Kaname - {process.env.APP_VERSION ?? "dev"} + {process.env.APP_VERSION ?? "dev"} - +
- - {session.user.name ?? session.user.email} - -
{ + { "use server"; await signOut({ redirectTo: "/login" }); }} - > - - + />
diff --git a/src/app/(app)/library-view.tsx b/src/app/(app)/library-view.tsx index 059dc05..b5a8f49 100644 --- a/src/app/(app)/library-view.tsx +++ b/src/app/(app)/library-view.tsx @@ -6,6 +6,7 @@ import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useMemo, useState } from "react"; import { JobProgress, JobStateBadge } from "@/components/job-progress"; import { LocalTime } from "@/components/local-time"; +import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge"; import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge"; import { TagBadge, TagDot } from "@/components/tag-badge"; import { Badge } from "@/components/ui/badge"; @@ -55,6 +56,7 @@ function toSearchable(r: LibraryRow): SearchableModel { pipelineTag: r.pipelineTag, license: r.license, status: r.status, + hubStatus: r.hubState && r.hubState !== "available" ? HUB_STATE_LABEL[r.hubState].label : null, }; } @@ -218,7 +220,10 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) { {job.state !== "queued" && } ) : ( - + + + + )} diff --git a/src/app/(app)/settings/labels/page.tsx b/src/app/(app)/settings/labels/page.tsx index d827c7b..5610d66 100644 --- a/src/app/(app)/settings/labels/page.tsx +++ b/src/app/(app)/settings/labels/page.tsx @@ -1,18 +1,10 @@ import type { Metadata } from "next"; import { getFileRoleStyles } from "@/lib/settings"; -import { listTags } from "@/lib/tags"; import { FileLabelSettings } from "./file-label-settings"; -import { TagSettings } from "./tag-settings"; export const dynamic = "force-dynamic"; -export const metadata: Metadata = { title: "Labels · Settings" }; +export const metadata: Metadata = { title: "File labels · Settings" }; export default async function LabelSettingsPage() { - const [fileRoles, tags] = await Promise.all([getFileRoleStyles(), listTags()]); - return ( -
- - -
- ); + return ; } diff --git a/src/app/(app)/settings/layout.tsx b/src/app/(app)/settings/layout.tsx index 4d53499..5570031 100644 --- a/src/app/(app)/settings/layout.tsx +++ b/src/app/(app)/settings/layout.tsx @@ -1,7 +1,10 @@ -import { TagsIcon } from "lucide-react"; +import { TagIcon, TagsIcon } from "lucide-react"; import { SettingsNav } from "./settings-nav"; -const SECTIONS = [{ href: "/settings/labels", label: "Labels", icon: }]; +const SECTIONS = [ + { href: "/settings/labels", label: "File labels", icon: }, + { href: "/settings/tags", label: "Tags", icon: }, +]; export default function SettingsLayout({ children }: LayoutProps<"/settings">) { return ( diff --git a/src/app/(app)/settings/tags/page.tsx b/src/app/(app)/settings/tags/page.tsx new file mode 100644 index 0000000..7fc5fc9 --- /dev/null +++ b/src/app/(app)/settings/tags/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; +import { listTags } from "@/lib/tags"; +import { TagSettings } from "./tag-settings"; + +export const dynamic = "force-dynamic"; +export const metadata: Metadata = { title: "Tags · Settings" }; + +export default async function TagSettingsPage() { + return ; +} diff --git a/src/app/(app)/settings/labels/tag-settings.tsx b/src/app/(app)/settings/tags/tag-settings.tsx similarity index 64% rename from src/app/(app)/settings/labels/tag-settings.tsx rename to src/app/(app)/settings/tags/tag-settings.tsx index ce95e86..52f46ad 100644 --- a/src/app/(app)/settings/labels/tag-settings.tsx +++ b/src/app/(app)/settings/tags/tag-settings.tsx @@ -1,6 +1,6 @@ "use client"; -import { Trash2Icon } from "lucide-react"; +import { PlusIcon, Trash2Icon } from "lucide-react"; import { useRouter } from "next/navigation"; import { useState } from "react"; import { toast } from "sonner"; @@ -19,21 +19,22 @@ import { import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; -import { autoTagColor, isLabelColor } from "@/lib/colors"; +import { autoTagColor, isLabelColor, type LabelColor } from "@/lib/colors"; import type { Tag } from "@/lib/tags"; -import { ColorPicker } from "./color-picker"; +import { ColorPicker } from "../labels/color-picker"; -/** Rename, recolor or delete user tags. Changes save immediately. */ +/** Create, rename, recolor or delete user tags. Changes save immediately. */ export function TagSettings({ tags }: { tags: (Tag & { count: number })[] }) { return ( Tags - Your own tags (added on a model page or when adding a model). Tags without a color get an automatic one. + Your own tags, to attach on a model page or when adding a model. Tags without a color get an automatic one. - + + {tags.length === 0 ? (

No tags yet.

) : ( @@ -48,6 +49,64 @@ export function TagSettings({ tags }: { tags: (Tag & { count: number })[] }) { ); } +function NewTagRow() { + const router = useRouter(); + const [name, setName] = useState(""); + const [color, setColor] = useState(null); + const [busy, setBusy] = useState(false); + + async function create(e: React.FormEvent) { + e.preventDefault(); + if (!name.trim()) return; + setBusy(true); + try { + const res = await fetch("/api/tags", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ name, color }), + }); + const json = await res.json().catch(() => ({})); + if (!res.ok) { + toast.error(json.error?.message ?? `Could not create tag (${res.status})`); + return; + } + toast.success(`Tag "${json.name}" created`); + setName(""); + setColor(null); + router.refresh(); + } finally { + setBusy(false); + } + } + + return ( +
+ {name.trim() ? ( + + ) : ( + New tag + )} + setName(e.target.value)} + placeholder="e.g. roleplay" + aria-label="New tag name" + className="h-8" + /> + + + + ); +} + function TagRow({ tag }: { tag: Tag & { count: number } }) { const router = useRouter(); const [name, setName] = useState(tag.name); diff --git a/src/app/api/models/[id]/hub-check/route.ts b/src/app/api/models/[id]/hub-check/route.ts new file mode 100644 index 0000000..0f8c5b9 --- /dev/null +++ b/src/app/api/models/[id]/hub-check/route.ts @@ -0,0 +1,12 @@ +import { NextResponse } from "next/server"; +import { withAuth } from "@/lib/api-auth"; +import { apiError } from "@/lib/api-errors"; +import { checkHubAvailability, getCheckedModel } from "@/lib/hub/availability"; + +/** Check right now whether the repo and pinned commit are still on the Hub. */ +export const POST = withAuth>(async (_req, { params }) => { + const { id } = await params; + const model = await getCheckedModel(id); + if (!model) return apiError(404, "not_found", "Model not found."); + return NextResponse.json(await checkHubAvailability(model)); +}); diff --git a/src/app/api/tags/route.ts b/src/app/api/tags/route.ts index c37e22d..25d3195 100644 --- a/src/app/api/tags/route.ts +++ b/src/app/api/tags/route.ts @@ -1,8 +1,22 @@ import { NextResponse } from "next/server"; +import { z } from "zod"; import { withAuth } from "@/lib/api-auth"; -import { listTags } from "@/lib/tags"; +import { apiError, handleApiError } from "@/lib/api-errors"; +import { createTag, listTags, TagError } from "@/lib/tags"; export const dynamic = "force-dynamic"; /** All user tags with usage counts. */ export const GET = withAuth(async () => NextResponse.json(await listTags())); + +const Body = z.object({ name: z.string(), color: z.string().nullable().optional() }); + +/** Create a tag that isn't on any model yet. */ +export const POST = withAuth(async (req) => { + try { + return NextResponse.json(await createTag(Body.parse(await req.json())), { status: 201 }); + } catch (err) { + if (err instanceof TagError) return apiError(err.status, err.code, err.message); + return handleApiError(err); + } +}); diff --git a/src/components/app-nav.tsx b/src/components/app-nav.tsx new file mode 100644 index 0000000..df4a9ac --- /dev/null +++ b/src/components/app-nav.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { LibraryIcon, SettingsIcon } from "lucide-react"; +import Link from "next/link"; +import { usePathname } from "next/navigation"; +import { cn } from "@/lib/utils"; + +const LINKS = [ + { href: "/", label: "Library", icon: LibraryIcon, active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/jobs/") }, + { href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") }, +]; + +/** Main navigation; model and job pages count as part of the library. */ +export function AppNav() { + const pathname = usePathname(); + return ( + + ); +} diff --git a/src/components/hub-state-badge.tsx b/src/components/hub-state-badge.tsx new file mode 100644 index 0000000..7dbaef7 --- /dev/null +++ b/src/components/hub-state-badge.tsx @@ -0,0 +1,32 @@ +import { TriangleAlertIcon } from "lucide-react"; +import type { HubState } from "@/lib/db/schema"; +import { cn } from "@/lib/utils"; + +export const HUB_STATE_LABEL: Record, { label: string; title: string }> = { + repo_missing: { + label: "deleted on Hub", + title: "The repo is no longer on Hugging Face (deleted, or made private). Your local files are kept.", + }, + commit_missing: { + label: "commit deleted on Hub", + title: "The pinned commit is no longer on Hugging Face (history rewritten). Your local files are kept.", + }, +}; + +/** Warning badge when a model's repo or pinned commit disappeared from the Hub; nothing otherwise. */ +export function HubStateBadge({ state, className }: { state: HubState | null; className?: string }) { + if (!state || state === "available") return null; + const { label, title } = HUB_STATE_LABEL[state]; + return ( + + + {label} + + ); +} diff --git a/src/components/tag-picker.tsx b/src/components/tag-picker.tsx new file mode 100644 index 0000000..8996729 --- /dev/null +++ b/src/components/tag-picker.tsx @@ -0,0 +1,131 @@ +"use client"; + +import { ChevronDownIcon, PlusIcon, SettingsIcon } from "lucide-react"; +import Link from "next/link"; +import { useEffect, useRef, useState } from "react"; +import { TagDot } from "@/components/tag-badge"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; +import { Input } from "@/components/ui/input"; +import type { Tag } from "@/lib/tags"; +import { cn } from "@/lib/utils"; + +/** + * "Add tag" dropdown: the first entry creates a new tag (inline name field), below it the existing + * tags that aren't picked yet. Calls `onPick` with the tag name. + */ +export function TagPicker({ + exclude, + onPick, + disabled, + className, +}: { + /** Tag names already applied (case-insensitive), hidden from the list. */ + exclude: string[]; + /** Picked tag name; `tag` is set when an existing tag was chosen. */ + onPick: (name: string, tag?: Tag) => void | Promise; + disabled?: boolean; + className?: string; +}) { + const [known, setKnown] = useState([]); + const [creating, setCreating] = useState(false); + const [name, setName] = useState(""); + const inputRef = useRef(null); + const cancelled = useRef(false); + + function load() { + fetch("/api/tags") + .then((r) => (r.ok ? r.json() : [])) + .then((all: Tag[]) => setKnown(all)) + .catch(() => {}); + } + useEffect(load, []); + + useEffect(() => { + if (!creating) return; + cancelled.current = false; + inputRef.current?.focus(); + }, [creating]); + + function finishCreating() { + setCreating(false); + setName(""); + } + + async function submit() { + const value = name.trim(); + const existing = known.find((t) => t.name.toLowerCase() === value.toLowerCase()); + if (value) await onPick(existing?.name ?? value, existing); + finishCreating(); + } + + if (creating) { + return ( +
{ + e.preventDefault(); + inputRef.current?.blur(); // blur submits, so Enter and click-away can't add twice + }} + > + setName(e.target.value)} + onBlur={() => (name.trim() && !cancelled.current ? void submit() : finishCreating())} + onKeyDown={(e) => { + if (e.key !== "Escape") return; + cancelled.current = true; + inputRef.current?.blur(); + }} + placeholder="New tag name…" + disabled={disabled} + maxLength={40} + className="h-6 w-40 text-xs" + aria-label="New tag name" + /> +
+ ); + } + + const hidden = new Set(exclude.map((n) => n.toLowerCase())); + const available = known.filter((t) => !hidden.has(t.name.toLowerCase())); + return ( + open && load()}> + + + Add tag + + + + setCreating(true)}> + + Create new tag… + + {available.length > 0 && } + {available.map((t) => ( + void onPick(t.name, t)}> + + {t.name} + + ))} + + } className="text-muted-foreground"> + + Manage tags… + + + + ); +} diff --git a/src/components/user-menu.tsx b/src/components/user-menu.tsx new file mode 100644 index 0000000..a0c1ad3 --- /dev/null +++ b/src/components/user-menu.tsx @@ -0,0 +1,97 @@ +"use client"; + +import { LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react"; +import Link from "next/link"; +import { useTheme } from "next-themes"; +import { useTransition } from "react"; +import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuRadioGroup, + DropdownMenuRadioItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu"; + +export type MenuUser = { name: string | null; email: string | null; image: string | null }; + +function initials(user: MenuUser): string { + const source = user.name || user.email || "?"; + const parts = source.split(/[\s@._-]+/).filter(Boolean); + return ((parts[0]?.[0] ?? "?") + (parts.length > 1 ? parts[1][0] : "")).toUpperCase(); +} + +function UserAvatar({ user, size }: { user: MenuUser; size?: "sm" | "default" | "lg" }) { + return ( + + {user.image && } + {initials(user)} + + ); +} + +/** Avatar from the OIDC profile; opens a menu with account info, settings, theme and sign out. */ +export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutAction: () => Promise }) { + const { theme, setTheme } = useTheme(); + const [signingOut, startSignOut] = useTransition(); + + return ( + + + + {user.name ?? user.email} + + +
+ +
+ {user.name ?? "Signed in"} + {user.email && {user.email}} +
+
+ + + Settings + }> + + File labels + + }> + + Tags + + + + + Theme + setTheme(v as string)}> + + + System + + + + Light + + + + Dark + + + + + startSignOut(() => signOutAction())}> + + {signingOut ? "Signing out…" : "Sign out"} + +
+
+ ); +} diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts index b20fd20..706bc0d 100644 --- a/src/lib/db/schema.ts +++ b/src/lib/db/schema.ts @@ -46,6 +46,10 @@ export const MODEL_STATUSES = [ ] as const; export type ModelStatus = (typeof MODEL_STATUSES)[number]; +/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */ +export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const; +export type HubState = (typeof HUB_STATES)[number]; + export const models = sqliteTable( "models", { @@ -73,6 +77,10 @@ export const models = sqliteTable( remoteSha: text("remote_sha"), lastCheckedAt: ts("last_checked_at"), lastCheckError: text("last_check_error"), + /** Result of the last successful Hub check; null until checked. */ + hubState: text("hub_state", { enum: HUB_STATES }), + /** When the repo or pinned commit was first seen missing; cleared when it's back. */ + hubMissingSince: ts("hub_missing_since"), lastVerifiedAt: ts("last_verified_at"), downloadedAt: ts("downloaded_at"), // Hub metadata (for search/filters), refreshed by the worker. Null until fetched. diff --git a/src/lib/hub/availability.ts b/src/lib/hub/availability.ts new file mode 100644 index 0000000..4181662 --- /dev/null +++ b/src/lib/hub/availability.ts @@ -0,0 +1,73 @@ +import { asc, eq, isNull, lt, or } from "drizzle-orm"; +import { db } from "@/lib/db/client"; +import { models, type HubState } from "@/lib/db/schema"; +import { getRepoInfo, HubError } from "./client"; + +type CheckedModel = Pick; + +/** Why new downloads are impossible, or null if the Hub still has the repo at the pinned commit. */ +export function hubMissingMessage(model: { repoId: string; hubState: HubState | null }): string | null { + if (model.hubState === "repo_missing") { + return `${model.repoId} is no longer on Hugging Face (deleted, or made private), so nothing more can be downloaded. Your local files are kept.`; + } + if (model.hubState === "commit_missing") { + return `The pinned commit of ${model.repoId} is no longer on Hugging Face (history rewritten), so nothing more can be downloaded from it. Your local files are kept.`; + } + return null; +} + +export type HubCheckResult = { state: HubState } | { state: null; error: string }; + +/** + * Is the repo, and the pinned commit, still on the Hub? Stores the result on the model. Only a + * definite answer changes `hubState`; network errors, rate limits or a bad token are kept as + * `lastCheckError`. Never touches local files. + */ +export async function checkHubAvailability(model: CheckedModel): Promise { + let result: HubCheckResult; + try { + await getRepoInfo(model.repoId, model.pinnedSha); + result = { state: "available" }; + } catch (err) { + if (err instanceof HubError && err.code === "repo_not_found") result = { state: "repo_missing" }; + else if (err instanceof HubError && err.code === "revision_not_found") result = { state: "commit_missing" }; + // Gated repos exist; access is a download concern, not availability. + else if (err instanceof HubError && (err.code === "gated_no_token" || err.code === "gated_no_access")) { + result = { state: "available" }; + } else result = { state: null, error: err instanceof Error ? err.message : String(err) }; + } + + const now = new Date(); + await db() + .update(models) + .set( + result.state === null + ? { lastCheckedAt: now, lastCheckError: result.error } + : { + lastCheckedAt: now, + lastCheckError: null, + hubState: result.state, + hubMissingSince: result.state === "available" ? null : (model.hubMissingSince ?? now), + }, + ) + .where(eq(models.id, model.id)); + return result; +} + +/** Models whose last Hub check is older than `intervalMs` (or never ran), oldest first. */ +export async function modelsDueForHubCheck(intervalMs: number, limit = 50): Promise { + const cutoff = new Date(Date.now() - intervalMs); + return db() + .select({ id: models.id, repoId: models.repoId, pinnedSha: models.pinnedSha, hubMissingSince: models.hubMissingSince }) + .from(models) + .where(or(isNull(models.lastCheckedAt), lt(models.lastCheckedAt, cutoff))) + .orderBy(asc(models.lastCheckedAt)) + .limit(limit); +} + +export async function getCheckedModel(id: string): Promise { + return db().query.models.findFirst({ + columns: { id: true, repoId: true, pinnedSha: true, hubMissingSince: true }, + where: eq(models.id, id), + }); +} diff --git a/src/lib/jobs.ts b/src/lib/jobs.ts index af0a704..5cb4f13 100644 --- a/src/lib/jobs.ts +++ b/src/lib/jobs.ts @@ -2,6 +2,7 @@ import "server-only"; import { and, asc, desc, eq, gt, gte, inArray, isNull, or } from "drizzle-orm"; import { ulid } from "ulid"; import { db } from "@/lib/db/client"; +import { hubMissingMessage } from "@/lib/hub/availability"; import { ACTIVE_JOB_STATES, type JobPurpose, @@ -14,7 +15,7 @@ import { export class JobError extends Error { constructor( - public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable", + public code: "not_found" | "busy" | "nothing_selected" | "not_cancellable" | "hub_missing", message: string, public status: number, ) { @@ -30,6 +31,8 @@ export async function queueDownload(modelId: string, purpose: JobPurpose = "init const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new JobError("not_found", "Model not found.", 404); + const missing = hubMissingMessage(model); + if (missing) throw new JobError("hub_missing", missing, 409); const open = await d.query.jobs.findFirst({ columns: { id: true }, diff --git a/src/lib/library.ts b/src/lib/library.ts index 81294ab..55974a7 100644 --- a/src/lib/library.ts +++ b/src/lib/library.ts @@ -20,6 +20,7 @@ export async function listLibrary() { pinnedSha: models.pinnedSha, remoteSha: models.remoteSha, status: models.status, + hubState: models.hubState, createdAt: models.createdAt, downloadedAt: models.downloadedAt, baseModels: models.baseModels, diff --git a/src/lib/models.ts b/src/lib/models.ts index 61c8507..add45d8 100644 --- a/src/lib/models.ts +++ b/src/lib/models.ts @@ -3,15 +3,15 @@ import { and, eq, inArray, sql } from "drizzle-orm"; import { ulid } from "ulid"; import { db } from "@/lib/db/client"; import { jobs, modelFiles, modelRevisions, models, modelTags } from "@/lib/db/schema"; +import { hubMissingMessage } from "@/lib/hub/availability"; import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client"; import { metadataColumns } from "@/lib/hub/refresh"; import { queueDownload } from "@/lib/jobs"; import { escapeGlob, isSelected, matchesAny, type SelectionRule } from "@/lib/selection"; -import { deleteUnusedTags } from "@/lib/tags"; export class ModelError extends Error { constructor( - public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy", + public code: "already_exists" | "empty_selection" | "not_found" | "not_removable" | "busy" | "hub_missing", message: string, public status: number, ) { @@ -100,7 +100,6 @@ export async function removeModel(id: string): Promise { d.delete(modelRevisions).where(eq(modelRevisions.modelId, id)), d.delete(models).where(eq(models.id, id)), ]); - await deleteUnusedTags(); } function chunk(items: T[], size: number): T[][] { @@ -118,6 +117,8 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise const d = db(); const model = await d.query.models.findFirst({ where: eq(models.id, modelId) }); if (!model) throw new ModelError("not_found", "Model not found.", 404); + const missing = hubMissingMessage(model); + if (missing) throw new ModelError("hub_missing", missing, 409); const open = await d.query.jobs.findFirst({ columns: { id: true }, diff --git a/src/lib/search.test.ts b/src/lib/search.test.ts index ffa73f8..baf08c7 100644 --- a/src/lib/search.test.ts +++ b/src/lib/search.test.ts @@ -55,6 +55,7 @@ const model = (over: Partial): SearchableModel => ({ pipelineTag: "text-generation", license: "apache-2.0", status: "ready", + hubStatus: null, ...over, }); @@ -70,6 +71,16 @@ describe("matchesQuery", () => { }); }); +describe("hub status", () => { + it("is searchable and an extra Status filter value", () => { + const gone = model({ hubStatus: "deleted on Hub" }); + assert.ok(matchesQuery(gone, "deleted")); + assert.ok(!matchesQuery(model({}), "deleted")); + assert.ok(matchesFilters(gone, { ...EMPTY_FILTERS, status: ["deleted on hub"] })); + assert.ok(matchesFilters(gone, { ...EMPTY_FILTERS, status: ["ready"] })); + }); +}); + describe("filters and facet counts", () => { const models = [ model({}), diff --git a/src/lib/search.ts b/src/lib/search.ts index 61b06b1..44e3d5e 100644 --- a/src/lib/search.ts +++ b/src/lib/search.ts @@ -12,6 +12,8 @@ export type SearchableModel = { pipelineTag: string | null; license: string | null; status: string; + /** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */ + hubStatus: string | null; }; export const FACETS = ["author", "family", "quant", "tag", "status"] as const; @@ -31,7 +33,7 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] { case "tag": return m.tags; case "status": - return [m.status]; + return m.hubStatus ? [m.status, m.hubStatus] : [m.status]; } } @@ -48,6 +50,7 @@ function haystack(m: SearchableModel): string { m.pipelineTag, m.license, m.status, + m.hubStatus, ] .filter(Boolean) .join(" ") diff --git a/src/lib/tags.ts b/src/lib/tags.ts index e92666b..3756b44 100644 --- a/src/lib/tags.ts +++ b/src/lib/tags.ts @@ -60,15 +60,24 @@ export async function addTag(modelId: string, rawName: string): Promise { return tag; } -/** Detach a tag; tags no model uses anymore are deleted. */ +/** Detach a tag from a model. The tag itself stays (delete it in Settings). */ export async function removeTag(modelId: string, tagId: string): Promise { - const d = db(); - await d.delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId))); - await deleteUnusedTags(); + await db().delete(modelTags).where(and(eq(modelTags.modelId, modelId), eq(modelTags.tagId, tagId))); } -export async function deleteUnusedTags(): Promise { - await db().run(sql`delete from ${tags} where ${tags.id} not in (select ${modelTags.tagId} from ${modelTags})`); +/** Create a tag without attaching it (Settings). 409 if the name exists (case-insensitive). */ +export async function createTag(input: { name: string; color?: string | null }): Promise { + const { name, slug } = normalizeTagName(input.name); + const color = input.color ?? null; + if (color !== null && !isLabelColor(color)) throw new TagError("invalid", "Unknown color.", 400); + const d = db(); + const inserted = await d + .insert(tags) + .values({ id: ulid(), name, slug, color }) + .onConflictDoNothing({ target: tags.slug }) + .returning({ id: tags.id, name: tags.name, color: tags.color }); + if (inserted.length === 0) throw new TagError("invalid", `A tag named "${name}" already exists.`, 409); + return inserted[0]; } /** Rename a tag and/or set its color (null = automatic). */ diff --git a/src/worker/index.ts b/src/worker/index.ts index 1432af2..6c42c0c 100644 --- a/src/worker/index.ts +++ b/src/worker/index.ts @@ -9,6 +9,7 @@ import { db } from "@/lib/db/client"; import { runMigrations } from "@/lib/db/migrate"; import { ACTIVE_JOB_STATES, jobFiles, jobLogs, jobs, modelFiles, models, workerState } from "@/lib/db/schema"; import { coreEnv } from "@/lib/env"; +import { checkHubAvailability, modelsDueForHubCheck } from "@/lib/hub/availability"; import { backfillMetadata } from "@/lib/hub/refresh"; import { DownloadRunner } from "./download"; import { log } from "./log"; @@ -19,6 +20,8 @@ const TICK_MS = 1_000; /** A lease older than this is considered abandoned (worker crashed without releasing it). */ const LEASE_STALE_MS = 20_000; const SHUTDOWN_GRACE_MS = 8_000; +/** How often to look for models whose Hub check is due (the check interval itself is configurable). */ +const HUB_CHECK_SCAN_MS = 10 * 60_000; /** Touched on every heartbeat; the Docker healthcheck checks its age. */ const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive"); @@ -208,10 +211,42 @@ async function startJob(job: typeof jobs.$inferSelect) { log.info(`job ${job.id}: downloading ${model.repoId} (${files.length} files, attempt ${job.attempt})`); runner .run() + .then(async () => { + // A failed download may mean the repo or commit is gone from the Hub; find out right away. + const done = await db().query.jobs.findFirst({ columns: { state: true }, where: eq(jobs.id, job.id) }); + if (done?.state === "failed") await reportHubCheck(model, await checkHubAvailability(model)); + }) .catch((err) => log.error(`job ${job.id} crashed`, err)) .finally(() => runners.delete(job.id)); } +// --------------------------------------------------------------------------- +// Hub availability: flags models whose repo or pinned commit disappeared from the Hub +// --------------------------------------------------------------------------- + +function reportHubCheck(model: { repoId: string }, result: Awaited>) { + if (result.state === null) log.warn(`Hub check for ${model.repoId} failed: ${result.error}`); + else if (result.state !== "available") log.warn(`${model.repoId}: ${result.state.replace("_", " ")} on the Hub (local files kept)`); +} + +let checkingHub = false; +async function checkHubDue() { + const hours = coreEnv().UPDATE_CHECK_INTERVAL_HOURS; + if (checkingHub || stopping || hours <= 0) return; + checkingHub = true; + try { + for (const model of await modelsDueForHubCheck(hours * 3_600_000)) { + if (stopping) break; + reportHubCheck(model, await checkHubAvailability(model)); + await sleep(1_000); // be gentle with the Hub API + } + } catch (err) { + log.error("Hub check failed", err); + } finally { + checkingHub = false; + } +} + let ticking = false; async function tick() { if (ticking || stopping) return; @@ -278,7 +313,9 @@ async function main() { await heartbeat(); timers.push(setInterval(() => heartbeat().catch((err) => log.error("heartbeat failed", err)), HEARTBEAT_MS)); timers.push(setInterval(() => void tick(), TICK_MS)); + timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS)); void tick(); + setTimeout(() => void checkHubDue(), 15_000); } function sleep(ms: number) {